+
- | 卡密名称 |
- 卡密组ID |
- 类型 |
- 内容/库存 |
- 描述 |
- 状态 |
- 操作 |
+ 卡密名称 |
+ 卡密组ID |
+ 类型 |
+ 内容/库存 |
+ 描述 |
+ 状态 |
+ 操作 |
- {cards.map((card) => {
+ {filteredCards.map((card) => {
// 计算库存或内容预览
let stockInfo = '';
if (card.type === 'data' && card.data_content) {
const lines = card.data_content.split('\n').filter(line => line.trim());
stockInfo = `库存: ${lines.length} 条`;
} else if (card.type === 'text' && card.text_content) {
- stockInfo = card.text_content.substring(0, 20) + (card.text_content.length > 20 ? '...' : '');
+ stockInfo = card.text_content;
} else if (card.type === 'api' && card.api_config) {
stockInfo = card.api_config.url;
} else if (card.type === 'image' && card.image_url) {
@@ -336,26 +376,26 @@ const CardList: React.FC = () => {
return (
-
-
-
+
+
+
- {card.name}
+ {card.name}
|
-
+ |
|
-
-
+ {
card.type === 'api' ? 'API' : '图片'}
|
-
-
+ |
+
{stockInfo}
|
-
+ |
{card.description || '-'}
|
-
+ |
|
-
-
+
+
|
@@ -415,10 +455,10 @@ const CardList: React.FC = () => {
| |
- {cards.length === 0 && (
+ {filteredCards.length === 0 && (
-
暂无卡密配置,请点击右上角添加。
+
{cards.length === 0 ? '暂无卡密配置,请点击右上角添加。' : '没有符合当前筛选条件的卡密组。'}
)}
diff --git a/frontend/components/Dashboard.tsx b/frontend/components/Dashboard.tsx
index c73cc5e..ee09244 100644
--- a/frontend/components/Dashboard.tsx
+++ b/frontend/components/Dashboard.tsx
@@ -2,6 +2,7 @@ import React, { useEffect, useRef, useState } from 'react';
import { DashboardStats, OrderAnalytics, Order, OrderStatus, Item } from '../types';
import { getDashboardStats, getOrderAnalytics, getValidOrders, getItems } from '../services/api';
import { getDateRange, getPreviousDateRange, TimeRange } from '../dateRange';
+import { formatLocalDateTime } from '../dateTime';
import { TrendingUp, Users, ShoppingCart, AlertCircle, DollarSign, Activity, Package, ArrowUpRight, Calendar, X, BarChart3, PackageCheck, ExternalLink, Eye, Edit } from 'lucide-react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, Legend } from 'recharts';
@@ -588,7 +589,7 @@ const Dashboard: React.FC = () => {
{order.buyer_id}
{order.created_at && (
- {order.created_at}
+ {formatLocalDateTime(order.created_at)}
)}
|
diff --git a/frontend/components/ItemList.tsx b/frontend/components/ItemList.tsx
index b405ed8..306937d 100644
--- a/frontend/components/ItemList.tsx
+++ b/frontend/components/ItemList.tsx
@@ -1,4 +1,4 @@
-import React, { useEffect, useRef, useState } from 'react';
+import React, { useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { selectActivePublishBatch } from './itemPublishBatchState';
import { Item, AccountDetail, ShippingRule } from '../types';
@@ -19,7 +19,7 @@ import {
deleteItem,
getShippingRules
} from '../services/api';
-import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Link2, PackagePlus, Plus, RefreshCw, Save, ShoppingBag, Trash2, UploadCloud, X } from 'lucide-react';
+import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Filter, Link2, PackagePlus, Plus, RefreshCw, Save, ShoppingBag, Trash2, UploadCloud, User, X } from 'lucide-react';
interface ItemListProps {
onConfigureDelivery: (item: Item) => void;
@@ -77,6 +77,7 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => {
const [shippingRules, setShippingRules] = useState([]);
const [accounts, setAccounts] = useState([]);
const [selectedAccount, setSelectedAccount] = useState('');
+ const [accountFilter, setAccountFilter] = useState('');
const [loading, setLoading] = useState(false);
const [publishing, setPublishing] = useState(false);
const [batchLoading, setBatchLoading] = useState(false);
@@ -510,24 +511,72 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => {
}
};
+ const accountMap = useMemo(
+ () => new Map(accounts.map(account => [account.id, account])),
+ [accounts],
+ );
+ const visibleItems = useMemo(
+ () => accountFilter ? items.filter(item => item.cookie_id === accountFilter) : items,
+ [accountFilter, items],
+ );
+ const accountName = (cookieId: string) => {
+ const account = accountMap.get(cookieId);
+ const name = account?.remark || account?.nickname;
+ return name ? `${name} · ${cookieId.slice(0, 6)}` : `账号 ${cookieId.slice(0, 8)}`;
+ };
+ const accountNickname = (cookieId: string) => {
+ const account = accountMap.get(cookieId);
+ return account?.remark || account?.nickname || '未命名账号';
+ };
+
return (
-
+
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
- {items.map(item => {
+ {visibleItems.map(item => {
const linkedRules = rulesForItem(item);
const hasRule = linkedRules.length > 0;
return (
@@ -603,6 +652,10 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => {
{item.item_title}
+
+
+ {accountNickname(item.cookie_id)}
+
ID: {item.item_id}
@@ -622,10 +675,10 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => {
);
})}
- {items.length === 0 && (
+ {visibleItems.length === 0 && (
- 暂无商品数据,请选择账号进行同步
+ {accountFilter ? '该账号暂无商品数据' : '暂无商品数据,请选择账号进行同步'}
)}
@@ -675,7 +728,7 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => {
@@ -727,7 +780,7 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => {
@@ -857,7 +910,7 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => {
onChange={e => setSelectedAccount(e.target.value)}
>
- {accounts.map(acc => )}
+ {accounts.map(acc => )}
表格中“账号ID”为空时,会使用这里选择的账号。
@@ -924,7 +977,7 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => {
{[
- ['账号ID', '没有在上方选择默认账号时填写', '填写账号 ID;已经选择默认账号时可以留空'],
+ ['账号ID', '需要覆盖默认账号时填写', '上方默认发布账号为必选;本列留空时使用默认账号,填写后仅覆盖当前行'],
['标题', '每个商品都要填', '填写买家能看到的商品标题'],
['描述', '可以留空', '留空时会使用商品标题作为描述'],
['价格', '每个商品都要填', '只填数字,例如 19.90'],
diff --git a/frontend/components/Notifications.tsx b/frontend/components/Notifications.tsx
index f862e0d..1905fb4 100644
--- a/frontend/components/Notifications.tsx
+++ b/frontend/components/Notifications.tsx
@@ -15,6 +15,7 @@ import {
Check, MessageCircle, Mail, Webhook, Send as Telegram, Eye, EyeOff, Save,
} from 'lucide-react';
import { normalizeSMTPSettings } from '../smtpSettings';
+import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig } from '../notificationEmailConfig';
type ChannelTypeMeta = {
label: string;
@@ -139,18 +140,14 @@ const CHANNEL_TYPES: Record = {
icon: Mail,
fields: [
{ key: 'to_email', label: '收件邮箱', placeholder: 'receiver@example.com', required: true },
- { key: 'smtp_server', label: '覆盖 SMTP 服务器', placeholder: 'smtp.qq.com', help: '留空时使用上方系统级 SMTP 配置' },
- { key: 'smtp_port', label: '覆盖 SMTP 端口', placeholder: '587', type: 'number', help: '留空时使用系统级 SMTP 端口' },
- { key: 'smtp_user', label: '覆盖发件邮箱', placeholder: 'you@qq.com', help: '留空时使用系统级发件邮箱' },
- { key: 'smtp_password', label: '覆盖密码 / 授权码', type: 'password', help: '留空时使用系统级授权码' },
],
guide: {
steps: [
- '先在页面上方保存系统级 SMTP 服务器、端口、发件邮箱和授权码',
- '邮件渠道只需要填写收件邮箱',
- '如果某个渠道要使用不同发件邮箱,再填写下面的覆盖 SMTP 字段',
+ '通常先保存页面中的系统 SMTP 配置',
+ '邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP',
+ '只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置',
],
- note: '收件邮箱会写入 to_email;SMTP 字段留空时后端会复用系统级 SMTP 配置。',
+ note: '继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。',
},
},
};
@@ -188,6 +185,7 @@ const Notifications: React.FC = ({ isAdmin = false }) => {
const [smtp, setSmtp] = useState({});
const [smtpSaving, setSmtpSaving] = useState(false);
const [showSmtpPassword, setShowSmtpPassword] = useState(false);
+ const [showChannelSmtpPassword, setShowChannelSmtpPassword] = useState(false);
const [form, setForm] = useState({
name: '',
@@ -256,18 +254,28 @@ const Notifications: React.FC = ({ isAdmin = false }) => {
const openCreate = () => {
setEditing(null);
setForm({ name: '', type: 'bark', enabled: true, config: {}, event_types: [] });
+ setShowChannelSmtpPassword(false);
setShowModal(true);
};
const openEdit = (ch: NotificationChannel) => {
setEditing(ch);
+ const normalizedEmailConfig = ch.type === 'email'
+ ? normalizeEmailChannelConfig({ ...(ch.config || {}) })
+ : null;
+ const config = normalizedEmailConfig
+ ? (normalizedEmailConfig.use_custom_smtp === true
+ ? enableCustomSMTP(normalizedEmailConfig, smtp)
+ : normalizedEmailConfig)
+ : { ...(ch.config || {}) };
setForm({
name: ch.name,
type: ch.type,
enabled: ch.enabled,
- config: { ...(ch.config || {}) },
+ config,
event_types: ch.event_types || [],
});
+ setShowChannelSmtpPassword(false);
setShowModal(true);
};
@@ -283,9 +291,27 @@ const Notifications: React.FC = ({ isAdmin = false }) => {
showToast('error', '请填写渠道名称');
return;
}
+ let config = form.config;
+ if (form.type === 'email') {
+ config = buildEmailChannelConfig(form.config);
+ if (config.use_custom_smtp) {
+ const required = [
+ ['smtp_server', '独立 SMTP 服务器'],
+ ['smtp_port', '独立 SMTP 端口'],
+ ['smtp_user', '独立 SMTP 登录邮箱'],
+ ['smtp_password', '独立 SMTP 密码 / 授权码'],
+ ['smtp_from_address', '独立 SMTP 发件地址'],
+ ] as const;
+ const missing = required.find(([key]) => !String(config[key] || '').trim());
+ if (missing) {
+ showToast('error', `请填写 ${missing[1]}`);
+ return;
+ }
+ }
+ }
setSaving(true);
try {
- const payload = { name: form.name.trim(), type: form.type, config: form.config, event_types: form.event_types, enabled: form.enabled };
+ const payload = { name: form.name.trim(), type: form.type, config, event_types: form.event_types, enabled: form.enabled };
if (editing) {
await updateNotificationChannel(editing.id, payload);
} else {
@@ -664,6 +690,137 @@ const Notifications: React.FC = ({ isAdmin = false }) => {
))}
+ {form.type === 'email' && (
+
+
+
+ SMTP 来源
+
+ {form.config.use_custom_smtp === true
+ ? '当前渠道使用一套完整、独立的发件配置。'
+ : '当前渠道完整继承系统 SMTP,只单独设置收件邮箱。'}
+
+
+
+
+
+ {form.config.use_custom_smtp === true && (
+
+
+
+
+
+ setForm({ ...form, config: { ...form.config, smtp_user: e.target.value } })}
+ placeholder="your-email@qq.com"
+ className="w-full ios-input px-4 py-3 rounded-xl text-sm"
+ />
+
+
+
+
+
+ setForm({ ...form, config: { ...form.config, smtp_password: e.target.value } })}
+ placeholder="输入密码或授权码"
+ className="w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"
+ />
+
+
+
+
+
+
+
+
+
+
+
+ )}
+
+ )}
+
diff --git a/frontend/components/OrderList.tsx b/frontend/components/OrderList.tsx
index cf090a5..34700e7 100644
--- a/frontend/components/OrderList.tsx
+++ b/frontend/components/OrderList.tsx
@@ -1,9 +1,10 @@
-import React, { useEffect, useRef, useState } from 'react';
+import React, { useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
-import { Order, OrderStatus, Item } from '../types';
-import { getOrders, syncOrders, syncSingleOrder, manualShipOrder, updateOrder, deleteOrder, importOrders, getItems } from '../services/api';
+import { AccountDetail, Order, OrderStatus, Item } from '../types';
+import { getOrders, syncOrders, syncSingleOrder, manualShipOrder, updateOrder, deleteOrder, importOrders, getItems, getAccountDetails } from '../services/api';
import { Search, MoreHorizontal, Truck, RefreshCw, Copy, ChevronLeft, ChevronRight, PackageCheck, Edit, Eye, Plus, Save, X, User as UserIcon, Phone, MapPin, Upload, ExternalLink, Trash2 } from 'lucide-react';
import { failedOrderImportRows, normalizeOrderImportResult, OrderImportResult } from './orderImportState';
+import { formatLocalDateTime } from '../dateTime';
const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
const styles = {
@@ -36,8 +37,10 @@ const StatusBadge: React.FC<{ status: OrderStatus }> = ({ status }) => {
const OrderList: React.FC = () => {
const [orders, setOrders] = useState ([]);
const [items, setItems] = useState- ([]);
+ const [accounts, setAccounts] = useState([]);
const [itemNames, setItemNames] = useState>({});
const [filter, setFilter] = useState('all');
+ const [accountFilter, setAccountFilter] = useState('');
const [searchText, setSearchText] = useState(''); // 搜索文本
const [debouncedSearch, setDebouncedSearch] = useState('');
const requestSequence = useRef(0);
@@ -65,7 +68,7 @@ const OrderList: React.FC = () => {
setLoading(true);
try {
- const res = await getOrders(undefined, filter, page, 20, debouncedSearch);
+ const res = await getOrders(accountFilter || undefined, filter, page, 20, debouncedSearch);
if (sequence !== requestSequence.current) return;
setOrders(res.data);
setTotalPages(res.total_pages);
@@ -77,15 +80,15 @@ const OrderList: React.FC = () => {
};
// 从订单的 item_id 查找对应的商品名称(通过标题匹配)
- const getItemNameById = (orderId: string, orderItemTitle?: string): string => {
+ const getItemNameById = (cookieId: string, orderId: string, orderItemTitle?: string): string => {
// 如果订单有 item_title,优先使用
if (orderItemTitle && orderItemTitle.trim()) {
return orderItemTitle;
}
// 尝试通过 item_id 直接匹配
- if (itemNames[orderId]) {
- return itemNames[orderId];
+ if (itemNames[`${cookieId}:${orderId}`]) {
+ return itemNames[`${cookieId}:${orderId}`];
}
// 尝试在商品列表中查找相似标题的商品
@@ -113,7 +116,7 @@ const OrderList: React.FC = () => {
items.forEach(item => {
// 使用 item_id 作为键,商品标题作为值
if (item.item_id) {
- namesMap[item.item_id] = item.item_title || item.item_id;
+ namesMap[`${item.cookie_id}:${item.item_id}`] = item.item_title || item.item_id;
}
});
setItemNames(namesMap);
@@ -123,7 +126,7 @@ const OrderList: React.FC = () => {
const namesMap: Record = {};
itemsList.forEach(item => {
if (item.item_id) {
- namesMap[item.item_id] = item.item_title || item.item_id;
+ namesMap[`${item.cookie_id}:${item.item_id}`] = item.item_title || item.item_id;
}
});
setItemNames(namesMap);
@@ -139,10 +142,11 @@ const OrderList: React.FC = () => {
useEffect(() => {
loadOrders();
- }, [filter, page, debouncedSearch]);
+ }, [accountFilter, filter, page, debouncedSearch]);
useEffect(() => {
- getItems().then((itemsList) => {
+ Promise.all([getAccountDetails(), getItems()]).then(([accountList, itemsList]) => {
+ setAccounts(accountList);
setItems(itemsList);
buildItemNamesMapFrom(itemsList);
}).catch((e) => {
@@ -150,10 +154,25 @@ const OrderList: React.FC = () => {
});
}, []);
+ const accountMap = useMemo(
+ () => new Map(accounts.map(account => [account.id, account])),
+ [accounts],
+ );
+
+ const accountName = (cookieId: string) => {
+ const account = accountMap.get(cookieId);
+ const name = account?.remark || account?.nickname;
+ return name ? `${name} · ${cookieId.slice(0, 6)}` : `账号 ${cookieId.slice(0, 8)}`;
+ };
+ const accountNickname = (cookieId: string) => {
+ const account = accountMap.get(cookieId);
+ return account?.remark || account?.nickname || '未命名账号';
+ };
+
const handleSync = async () => {
setLoading(true);
try {
- const result = await syncOrders();
+ const result = await syncOrders(accountFilter || undefined, filter);
await loadOrders();
if (result?.message) {
alert(result.message);
@@ -357,7 +376,22 @@ const OrderList: React.FC = () => {
))}
-
+
+
+
+
+
+
{
onChange={(e) => { setSearchText(e.target.value); setPage(1); }}
className="ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"
/>
+
@@ -395,10 +430,14 @@ const OrderList: React.FC = () => {
- {getItemNameById(order.item_id, order.item_title)}
+ {getItemNameById(order.cookie_id, order.item_id, order.item_title)}
+
+
+
+ {accountNickname(order.cookie_id)}
订单ID: {order.order_id}
- 数量: {order.quantity} • {order.created_at}
+ 数量: {order.quantity} • {formatLocalDateTime(order.created_at)}
@@ -536,6 +575,10 @@ const OrderList: React.FC = () => {
订单号
{selectedOrder.order_id}
+
+ 所属账号
+ {accountNickname(selectedOrder.cookie_id)}
+
状态
@@ -550,7 +593,7 @@ const OrderList: React.FC = () => {
创建时间
- {selectedOrder.created_at}
+ {formatLocalDateTime(selectedOrder.created_at)}
@@ -564,7 +607,7 @@ const OrderList: React.FC = () => {
)}
- {getItemNameById(selectedOrder.item_id, selectedOrder.item_title)}
+ {getItemNameById(selectedOrder.cookie_id, selectedOrder.item_id, selectedOrder.item_title)}
商品ID: {selectedOrder.item_id}
{selectedOrder.item_price && (
diff --git a/frontend/components/Rules.tsx b/frontend/components/Rules.tsx
index 74f0a11..58b2533 100644
--- a/frontend/components/Rules.tsx
+++ b/frontend/components/Rules.tsx
@@ -1280,7 +1280,7 @@ const Rules: React.FC = ({ initialDeliveryTarget, onDeliveryTargetHa
updateVariant(index, { delay_seconds: Math.max(0, Number(event.target.value) || 0) })}
className="w-28 ios-input px-2 py-1.5 rounded-lg text-xs"
diff --git a/frontend/components/Sidebar.tsx b/frontend/components/Sidebar.tsx
index b559585..0cb2fc5 100644
--- a/frontend/components/Sidebar.tsx
+++ b/frontend/components/Sidebar.tsx
@@ -1,5 +1,6 @@
import React from 'react';
import { LayoutDashboard, Users, ShoppingBag, CreditCard, Settings, LogOut, Box, Sparkles, Zap, Bell } from 'lucide-react';
+import { YdisksBrandIcon } from './YdisksLogo';
interface SidebarProps {
activeTab: string;
@@ -24,8 +25,8 @@ const Sidebar: React.FC = ({ activeTab, isAdmin = false, onNavigat
-
- 
+
+
Ydisks闲鱼助手 PRO
diff --git a/frontend/components/YdisksLogo.test.tsx b/frontend/components/YdisksLogo.test.tsx
new file mode 100644
index 0000000..a32eb02
--- /dev/null
+++ b/frontend/components/YdisksLogo.test.tsx
@@ -0,0 +1,21 @@
+import React from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { describe, expect, test } from 'vitest';
+import YdisksLogo, { YdisksBrandIcon } from './YdisksLogo';
+
+describe('YdisksLogo', () => {
+ test('uses the complete 256px brand coordinate system', () => {
+ const html = renderToStaticMarkup( );
+ expect(html).toContain('viewBox="0 0 256 256"');
+ expect(html).toContain('M121.73,57.0003');
+ expect(html).toContain('fill="currentColor"');
+ });
+
+ test('renders the complete gradient squircle brand wrapper', () => {
+ const html = renderToStaticMarkup( );
+ expect(html).toContain('viewBox="0 0 120 120"');
+ expect(html).toContain('id="login-squircle-gradient"');
+ expect(html).toContain('M 114.00 60.00');
+ expect(html).toContain('w-12 h-12');
+ });
+});
diff --git a/frontend/components/YdisksLogo.tsx b/frontend/components/YdisksLogo.tsx
new file mode 100644
index 0000000..87efac6
--- /dev/null
+++ b/frontend/components/YdisksLogo.tsx
@@ -0,0 +1,43 @@
+import React from 'react';
+
+interface YdisksLogoProps {
+ className?: string;
+}
+
+interface YdisksBrandIconProps {
+ sizeClass?: string;
+ logoClassName?: string;
+}
+
+const YdisksLogo: React.FC = ({ className = 'w-full h-full text-white' }) => (
+
+);
+
+export const YdisksBrandIcon: React.FC = ({
+ sizeClass = 'w-12 h-12',
+ logoClassName = 'w-full h-full text-white',
+}) => (
+
+
+
+
+
+
+
+
+
+);
+
+export default YdisksLogo;
diff --git a/frontend/components/cardListState.test.ts b/frontend/components/cardListState.test.ts
new file mode 100644
index 0000000..0ba6a07
--- /dev/null
+++ b/frontend/components/cardListState.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, test } from 'vitest';
+import type { Card } from '../types';
+import { filterCards } from './cardListState';
+
+const cards = [
+ { id: 1, name: '年终总结 PPT', type: 'text' },
+ { id: 2, name: '年终总结兑换码', type: 'data' },
+ { id: 3, name: '产品介绍 PPT', type: 'text' },
+] as Card[];
+
+describe('filterCards', () => {
+ test('combines type and name filters with AND semantics', () => {
+ expect(filterCards(cards, 'text', '年终')).toEqual([cards[0]]);
+ });
+
+ test('matches names case-insensitively and ignores surrounding whitespace', () => {
+ expect(filterCards(cards, '', ' ppt ')).toEqual([cards[0], cards[2]]);
+ });
+});
diff --git a/frontend/components/cardListState.ts b/frontend/components/cardListState.ts
new file mode 100644
index 0000000..c82127c
--- /dev/null
+++ b/frontend/components/cardListState.ts
@@ -0,0 +1,13 @@
+import type { Card } from '../types';
+
+export const filterCards = (
+ cards: Card[],
+ typeFilter: Card['type'] | '',
+ nameSearch: string,
+): Card[] => {
+ const keyword = nameSearch.trim().toLocaleLowerCase();
+ return cards.filter(card => (
+ (!typeFilter || card.type === typeFilter)
+ && (!keyword || card.name.toLocaleLowerCase().includes(keyword))
+ ));
+};
diff --git a/frontend/dateTime.test.ts b/frontend/dateTime.test.ts
new file mode 100644
index 0000000..bb1ac95
--- /dev/null
+++ b/frontend/dateTime.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, test } from 'vitest';
+import { formatLocalDateTime } from './dateTime';
+
+describe('formatLocalDateTime', () => {
+ test('uses the browser local timezone and the standard second-level format', () => {
+ expect(formatLocalDateTime(new Date(2026, 6, 15, 10, 54, 12))).toBe('2026-07-15 10:54:12');
+ });
+
+ test('returns a placeholder for missing or invalid timestamps', () => {
+ expect(formatLocalDateTime()).toBe('-');
+ expect(formatLocalDateTime('not-a-date')).toBe('-');
+ });
+});
diff --git a/frontend/dateTime.ts b/frontend/dateTime.ts
new file mode 100644
index 0000000..723e82f
--- /dev/null
+++ b/frontend/dateTime.ts
@@ -0,0 +1,19 @@
+const padTwoDigits = (value: number): string => String(value).padStart(2, '0');
+
+/** Format a timestamp in the browser's current timezone. */
+export const formatLocalDateTime = (value?: string | number | Date | null): string => {
+ if (value === undefined || value === null || value === '') return '-';
+
+ const date = value instanceof Date ? value : new Date(value);
+ if (Number.isNaN(date.getTime())) return '-';
+
+ return [
+ date.getFullYear(),
+ padTwoDigits(date.getMonth() + 1),
+ padTwoDigits(date.getDate()),
+ ].join('-') + ' ' + [
+ padTwoDigits(date.getHours()),
+ padTwoDigits(date.getMinutes()),
+ padTwoDigits(date.getSeconds()),
+ ].join(':');
+};
diff --git a/frontend/notificationEmailConfig.test.ts b/frontend/notificationEmailConfig.test.ts
new file mode 100644
index 0000000..e35ba16
--- /dev/null
+++ b/frontend/notificationEmailConfig.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, test } from 'vitest';
+import { buildEmailChannelConfig, enableCustomSMTP, normalizeEmailChannelConfig } from './notificationEmailConfig';
+
+describe('email notification SMTP modes', () => {
+ test('recognizes legacy channel overrides as custom SMTP', () => {
+ expect(normalizeEmailChannelConfig({ to_email: 'to@example.com', smtp_server: 'legacy.example.com' }).use_custom_smtp).toBe(true);
+ });
+
+ test('inherit mode removes every channel-level SMTP override', () => {
+ expect(buildEmailChannelConfig({
+ to_email: ' to@example.com ',
+ use_custom_smtp: false,
+ smtp_server: 'stale.example.com',
+ smtp_use_tls: false,
+ })).toEqual({ to_email: 'to@example.com', use_custom_smtp: false });
+ });
+
+ test('custom mode starts from a complete copy of system SMTP settings', () => {
+ const result = enableCustomSMTP({ to_email: 'to@example.com' }, {
+ smtp_server: 'smtp.example.com',
+ smtp_port: 465,
+ smtp_user: 'from@example.com',
+ smtp_password: 'secret',
+ smtp_use_tls: false,
+ smtp_use_ssl: true,
+ });
+ expect(result).toMatchObject({
+ use_custom_smtp: true,
+ smtp_server: 'smtp.example.com',
+ smtp_port: 465,
+ smtp_from_address: 'from@example.com',
+ smtp_use_tls: false,
+ smtp_use_ssl: true,
+ });
+ });
+});
diff --git a/frontend/notificationEmailConfig.ts b/frontend/notificationEmailConfig.ts
new file mode 100644
index 0000000..952b195
--- /dev/null
+++ b/frontend/notificationEmailConfig.ts
@@ -0,0 +1,59 @@
+const smtpOverrideKeys = [
+ 'smtp_server',
+ 'smtp_port',
+ 'smtp_user',
+ 'smtp_password',
+ 'smtp_from_name',
+ 'smtp_from_address',
+ 'smtp_use_tls',
+ 'smtp_use_ssl',
+] as const;
+
+const parseBoolean = (value: unknown, fallback: boolean): boolean => {
+ if (typeof value === 'boolean') return value;
+ if (typeof value === 'string') {
+ if (['true', '1', 'yes', 'on'].includes(value.toLowerCase())) return true;
+ if (['false', '0', 'no', 'off'].includes(value.toLowerCase())) return false;
+ }
+ return fallback;
+};
+
+export const normalizeEmailChannelConfig = (config: Record): Record => {
+ const hasExplicitMode = Object.prototype.hasOwnProperty.call(config, 'use_custom_smtp');
+ const hasLegacyOverrides = smtpOverrideKeys.some(key => String(config[key] ?? '').trim() !== '');
+ return {
+ ...config,
+ use_custom_smtp: hasExplicitMode
+ ? parseBoolean(config.use_custom_smtp, false)
+ : hasLegacyOverrides,
+ };
+};
+
+export const enableCustomSMTP = (
+ config: Record,
+ systemSettings: Record,
+): Record => {
+ const next: Record = { ...config, use_custom_smtp: true };
+ for (const key of smtpOverrideKeys) {
+ if (String(next[key] ?? '').trim() === '' && systemSettings[key] !== undefined) {
+ next[key] = systemSettings[key];
+ }
+ }
+ next.smtp_port ||= 587;
+ next.smtp_from_address ||= next.smtp_user || '';
+ next.smtp_use_tls = parseBoolean(next.smtp_use_tls, true);
+ next.smtp_use_ssl = parseBoolean(next.smtp_use_ssl, false);
+ return next;
+};
+
+export const buildEmailChannelConfig = (config: Record): Record => {
+ const normalized = normalizeEmailChannelConfig(config);
+ const result: Record = {
+ to_email: String(normalized.to_email ?? '').trim(),
+ use_custom_smtp: normalized.use_custom_smtp === true,
+ };
+ if (result.use_custom_smtp) {
+ for (const key of smtpOverrideKeys) result[key] = normalized[key];
+ }
+ return result;
+};
diff --git a/frontend/routing.test.ts b/frontend/routing.test.ts
index 5d3a72c..00943c2 100644
--- a/frontend/routing.test.ts
+++ b/frontend/routing.test.ts
@@ -71,13 +71,14 @@ describe('frontend navigation routing', () => {
expect(settings).toContain('只有网络不可用或超时才回退本机引擎');
});
- test('email notification config uses backend recipient field names', () => {
+ test('email notification config separates system and custom SMTP modes', () => {
const notifications = readFrontendFile('components/Notifications.tsx');
expect(notifications).toContain('interface NotificationsProps');
expect(notifications).toContain('isAdmin && (');
expect(notifications).toContain("key: 'to_email'");
- expect(notifications).toContain('留空时使用上方系统级 SMTP 配置');
+ expect(notifications).toContain('完整继承系统 SMTP');
+ expect(notifications).toContain('use_custom_smtp');
expect(notifications).not.toContain("key: 'from'");
expect(notifications).not.toContain('注册验证码');
});
diff --git a/frontend/services/api.test.ts b/frontend/services/api.test.ts
index 0c6915a..be6de25 100644
--- a/frontend/services/api.test.ts
+++ b/frontend/services/api.test.ts
@@ -187,6 +187,18 @@ test('getItems normalizes multi-spec flags from backend values', async () => {
});
});
+test('getItems forwards the selected account filter', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse([]));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await getItems('account-2');
+
+ expect(fetchMock).toHaveBeenCalledWith('/items?cookie_id=account-2', expect.objectContaining({
+ method: 'GET',
+ credentials: 'include',
+ }));
+});
+
test('getSystemSettings normalizes numeric renewal retention', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({
ai_model: 'qwen-plus',
diff --git a/frontend/services/api.ts b/frontend/services/api.ts
index ae7c030..93e91b2 100644
--- a/frontend/services/api.ts
+++ b/frontend/services/api.ts
@@ -159,6 +159,19 @@ export const updateAccountSettings = async (id: string, data: AccountSettingsUpd
return put(`/cookies/${id}/settings`, data);
};
+export interface LongLoginSettings {
+ can_open_long_login: boolean;
+ enabled: boolean;
+}
+
+export const getLongLoginSettings = async (id: string): Promise => {
+ return get(`/cookies/${id}/long-login`);
+};
+
+export const setLongLoginSettings = async (id: string, enabled: boolean): Promise => {
+ return put(`/cookies/${id}/long-login`, { enabled });
+};
+
export interface PasswordLoginStartResponse {
success: boolean;
session_id?: string;
@@ -413,8 +426,8 @@ export const appendCardData = async (cardId: string | number, content: string):
const normalizeBooleanFlag = (value: unknown): boolean =>
value === true || value === 1 || value === '1';
-export const getItems = async (): Promise- => {
- const res = await get('/items');
+export const getItems = async (cookieId?: string): Promise
- => {
+ const res = await get('/items', cookieId ? { cookie_id: cookieId } : undefined);
const items = Array.isArray(res) ? res : (res.items || []);
return items.map((item: any) => ({
...item,
diff --git a/internal/account/manager_extra_test.go b/internal/account/manager_extra_test.go
index 31976a9..2440c24 100644
--- a/internal/account/manager_extra_test.go
+++ b/internal/account/manager_extra_test.go
@@ -3,6 +3,7 @@ package account
import (
"context"
"errors"
+ "log/slog"
"path/filepath"
"strings"
"sync"
@@ -12,8 +13,34 @@ import (
"xianyu-go/internal/db"
"xianyu-go/internal/engine"
"xianyu-go/internal/xianyu/mtop"
+ "xianyu-go/internal/xianyu/ws"
)
+type fakeWSDialer struct{}
+
+func (fakeWSDialer) Dial(context.Context, ws.Config, *slog.Logger) (engine.WSConn, error) {
+ return fakeWSConn{}, nil
+}
+
+type fakeWSConn struct{}
+
+func (fakeWSConn) Register(context.Context, string, string) error { return nil }
+func (fakeWSConn) HeartbeatLoop(ctx context.Context, _ time.Duration) error {
+ <-ctx.Done()
+ return ctx.Err()
+}
+func (fakeWSConn) ReceiveLoop(ctx context.Context, _ func(map[string]any)) error {
+ <-ctx.Done()
+ return ctx.Err()
+}
+func (fakeWSConn) Close() error { return nil }
+func (fakeWSConn) SendText(context.Context, string, string, string, string) error {
+ return nil
+}
+func (fakeWSConn) SendImage(context.Context, string, string, string, string, int, int) error {
+ return nil
+}
+
// fakeMtop 是注入 engine.Account 的可控 mtop 客户端,避免真实网络。
// refreshErr 非空时 RefreshToken 返回该错误;block 非空时阻塞到该 chan
// 关闭或 ctx 取消(用于让 Run 挂起、模拟"账号在线运行中")。
@@ -98,6 +125,7 @@ func startAccountWithMtop(t *testing.T, mgr *Manager, cookieID, cookieValue stri
Handler: mgr.handler,
Logger: mgr.logger,
MTop: mtopClient,
+ WSDialer: fakeWSDialer{},
})
accCtx, accCancel := context.WithCancel(runCtx)
ma := &managedAccount{
diff --git a/internal/adapter/adapter.go b/internal/adapter/adapter.go
index 7b226c3..5169b28 100644
--- a/internal/adapter/adapter.go
+++ b/internal/adapter/adapter.go
@@ -1,7 +1,7 @@
-// Package adapter 是账号运行时与外部能力(浏览器自动化、通知、自动化中心)的装配层。
+// Package adapter 是账号运行时与外部能力(风控验证、通知、自动化中心)的装配层。
//
// 它实现 engine.Handler 与 automation.OrderDetailFetcher,把系统事件转发到自动化中心、
-// 把订单详情抓取/密码登录刷新接到浏览器、把账号告警推到通知器。业务逻辑集中在此,
+// 把订单详情抓取/凭证续期接到 Go 协议客户端、把账号告警推到通知器。业务逻辑集中在此,
// cmd/server 只负责构造与接线。
package adapter
@@ -21,20 +21,13 @@ import (
"xianyu-go/internal/renewal"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
- "xianyu-go/internal/xianyu/protocol"
xrenew "xianyu-go/internal/xianyu/renew"
)
-// browserManager 是 adapter 所需的浏览器能力最小契约。*browser.Manager 实现该接口;
-// 测试可注入桩实现,避免依赖 Chromium。
+// browserManager 只暴露风控验证能力。普通 Token、Cookie 续期、订单和
+// WebSocket 流程不得通过 Chromium 实现。
type browserManager interface {
- FetchOrderDetail(ctx context.Context, orderID, cookieID, cookieValue string, requireSpec ...bool) (*browser.OrderDetail, error)
- CookieRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (map[string]string, error)
- PasswordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool) (map[string]string, error)
-}
-
-type browserQuickRenewer interface {
- BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error)
+ TokenCaptchaRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider browser.TokenCaptchaURLProvider) (string, error)
}
type browserTokenCaptchaRecoverer interface {
@@ -45,12 +38,20 @@ type browserTokenCaptchaEngineRecoverer interface {
TokenCaptchaRecoverWithEngine(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider browser.TokenCaptchaURLProvider) (cookies, engine string, err error)
}
+type browserTokenCaptchaSnapshotReader interface {
+ TokenCaptchaCookieSnapshot(ctx context.Context, cookieID string, headless bool) (cookies string, snapshot []cookierefresh.BrowserCookie, err error)
+}
+
type tokenCaptchaRequester interface {
RequestFreshCaptchaURLContext(ctx context.Context, cookiesStr, deviceID string) (*mtop.FreshCaptchaResult, error)
}
+type orderDetailClient interface {
+ FetchOrderDetail(ctx context.Context, cookiesStr, orderID string) (*mtop.OrderDetailResult, error)
+}
+
// Adapter 实现 engine.Handler 与 automation.OrderDetailFetcher,
-// 把系统消息、订单详情抓取和密码登录刷新接到浏览器与自动化中心。
+// 把系统消息、订单详情抓取和协议级凭证续期接到 Go 客户端与自动化中心。
//
// 自动发货只走 automation.Center;用户聊天消息由 Account 内部 ReplyService 处理,
// 故 HandleChatMessage 为空实现。
@@ -63,6 +64,7 @@ type Adapter struct {
renewSvc xrenew.Service
cooldown *renewal.CooldownManager
captchaReq tokenCaptchaRequester
+ orderMTop orderDetailClient
orderFetchMu sync.Mutex
lastOrderFetch time.Time
@@ -93,6 +95,7 @@ func New(store *db.Store, bm *browser.Manager, logger *slog.Logger) *Adapter {
logger: logger,
cooldown: renewal.GlobalCooldown,
captchaReq: mtop.NewClient(),
+ orderMTop: mtop.NewClient(),
passwordProcessing: make(map[string]struct{}),
}
}
@@ -120,6 +123,9 @@ func (a *Adapter) SetRenewService(s xrenew.Service) { a.renewSvc = s }
// SetTokenCaptchaRequester 覆盖 token 风控验证链接刷新器,便于测试隔离网络。
func (a *Adapter) SetTokenCaptchaRequester(r tokenCaptchaRequester) { a.captchaReq = r }
+// SetOrderDetailClient 覆盖纯 Go 订单详情客户端,便于测试隔离网络。
+func (a *Adapter) SetOrderDetailClient(c orderDetailClient) { a.orderMTop = c }
+
// HandleChatMessage 用户聊天消息由 Account 内部 ReplyService 处理,此处空实现满足接口。
func (a *Adapter) HandleChatMessage(_ context.Context, _ engine.ChatMessage) error {
return nil
@@ -208,6 +214,7 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
newCookies := ""
captchaEngine := "playwright"
remoteHandled := false
+ captchaHeadless := browser.ResolveHeadless(showBrowser)
var err error
if remoteConfig := a.loadRemoteCaptchaConfig(ctx); remoteConfig != nil {
newCookies, remoteHandled, err = solveRemoteCaptcha(
@@ -230,11 +237,11 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
}
if withEngine, ok := a.browser.(browserTokenCaptchaEngineRecoverer); ok {
newCookies, captchaEngine, err = withEngine.TokenCaptchaRecoverWithEngine(
- ctx, cookieID, cookieStr, verificationURL, browser.ResolveHeadless(showBrowser), provider,
+ ctx, cookieID, cookieStr, verificationURL, captchaHeadless, provider,
)
} else {
newCookies, err = br.TokenCaptchaRecover(
- ctx, cookieID, cookieStr, verificationURL, browser.ResolveHeadless(showBrowser), provider,
+ ctx, cookieID, cookieStr, verificationURL, captchaHeadless, provider,
)
}
}
@@ -256,7 +263,34 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
if strings.TrimSpace(newCookies) == "" {
return nil, false
}
- if err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, cookierefresh.MetadataWithoutSnapshot(metadataJSON), time.Now().Unix()); err != nil {
+ var cookieSnapshot []cookierefresh.BrowserCookie
+ snapshotComplete := false
+ if !remoteHandled {
+ if reader, ok := a.browser.(browserTokenCaptchaSnapshotReader); ok {
+ profileCookies, profileSnapshot, readErr := reader.TokenCaptchaCookieSnapshot(ctx, cookieID, captchaHeadless)
+ if readErr != nil {
+ a.logger.Warn("读取滑块验证后完整 Cookie Jar 失败,回退 Go 快照合并", "account", cookieID, "err", readErr)
+ } else {
+ cookieSnapshot = cookierefresh.NormalizeSnapshot(profileSnapshot)
+ if cookieSnapshot == nil {
+ cookieSnapshot = []cookierefresh.BrowserCookie{}
+ }
+ snapshotComplete = true
+ newCookies = profileCookies
+ }
+ }
+ }
+ if !snapshotComplete {
+ if existing, complete := cookierefresh.SnapshotFromMetadataOK(metadataJSON); complete {
+ cookieSnapshot = cookierefresh.ReconcileSnapshotWithCookieString(existing, newCookies)
+ snapshotComplete = true
+ }
+ }
+ updatedMetadata := cookierefresh.MetadataWithoutSnapshot(metadataJSON)
+ if snapshotComplete {
+ updatedMetadata = cookierefresh.MetadataWithSnapshot(metadataJSON, cookieSnapshot)
+ }
+ if err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, updatedMetadata, time.Now().Unix()); err != nil {
a.logger.Warn("保存 token 风控恢复 Cookie 失败", "account", cookieID, "err", err)
if a.store != nil && a.store.RiskLogs != nil {
_ = a.store.RiskLogs.Update(ctx, logID, db.RiskControlLog{
@@ -282,7 +316,12 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
}
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelInfo,
"token 风控验证已自动恢复", "系统已完成验证并更新登录凭证。")
- return &mtop.RefreshResult{UpdatedCookies: newCookies}, true
+ return &mtop.RefreshResult{
+ UpdatedCookies: newCookies,
+ CookieSnapshot: cookieSnapshot,
+ CookieSnapshotComplete: snapshotComplete,
+ CookieStateChanged: newCookies != cookieStr || snapshotComplete,
+ }, true
}
// HandleSystemEvent 把系统卡片事件转发到自动化中心,由自动化规则决定是否执行。
@@ -294,14 +333,14 @@ func (a *Adapter) HandleSystemEvent(ctx context.Context, task automation.Task) e
return a.automation.HandleTask(ctx, task)
}
-// FetchOrderDetail 实现 automation.OrderDetailFetcher。只在本地订单缺少关键字段时启动浏览器,
-// 并将所有账号的详情请求串行化、至少间隔 3 秒,避免短时间高频访问闲鱼。
-func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemID, buyerID, cookieStr string) (*automation.OrderDetail, error) {
+// FetchOrderDetail 实现 automation.OrderDetailFetcher。只在本地订单缺少关键字段时
+// 调用纯 Go MTOP 客户端,并将详情请求串行化、至少间隔 3 秒,避免短时间高频访问闲鱼。
+func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemID, buyerID, _ string) (*automation.OrderDetail, error) {
if detail, ok := a.localOrderDetail(ctx, orderID); ok {
return detail, nil
}
- if a.browser == nil {
- return nil, fmt.Errorf("订单缺少规格/数量信息且浏览器自动化未启用")
+ if a.orderMTop == nil {
+ return nil, fmt.Errorf("订单详情 MTOP 客户端未配置")
}
a.orderFetchMu.Lock()
@@ -320,12 +359,47 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
}
}
a.lastOrderFetch = time.Now()
- detail, err := a.browser.FetchOrderDetail(ctx, orderID, cookieID, cookieStr, true)
+ credentialUnlock := a.store.LockAccountCredentials(cookieID)
+ defer credentialUnlock()
+ account, err := a.store.Cookies.GetDetails(ctx, cookieID)
if err != nil {
- return nil, err
+ return nil, fmt.Errorf("读取订单账号最新 Cookie: %w", err)
}
- if detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieStr {
- _ = a.store.Cookies.UpdateValueExisting(ctx, cookieID, detail.UpdatedCookies)
+ if account == nil || (strings.TrimSpace(account.Value) == "" && !hasCompleteCookieSnapshot(account.MetadataJSON)) {
+ return nil, fmt.Errorf("订单账号 %s Cookie 为空", cookieID)
+ }
+ cookieStr := account.Value
+ var requestCtx context.Context
+ var cookieSession *mtop.CookieSession
+ if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(account.MetadataJSON); complete {
+ requestCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot)
+ } else {
+ requestCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr)
+ }
+ detail, fetchErr := a.orderMTop.FetchOrderDetail(requestCtx, cookieStr, orderID)
+ authoritativeCookies, authoritativeSnapshot, sessionChanged := cookieSession.State()
+ if sessionChanged {
+ metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
+ if authoritativeSnapshot != nil {
+ metadata = cookierefresh.MetadataWithSnapshot(account.MetadataJSON, authoritativeSnapshot)
+ }
+ if persistErr := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, authoritativeCookies, metadata, time.Now().Unix()); persistErr != nil {
+ fetchErr = errors.Join(fetchErr, fmt.Errorf("保存订单详情响应 Cookie: %w", persistErr))
+ } else {
+ cookieStr = authoritativeCookies
+ }
+ }
+ if fetchErr != nil {
+ return nil, fetchErr
+ }
+ if detail == nil {
+ return nil, errors.New("订单详情 MTOP 接口返回空结果")
+ }
+ if !sessionChanged && authoritativeSnapshot == nil && detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieStr {
+ metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
+ if err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, detail.UpdatedCookies, metadata, time.Now().Unix()); err != nil {
+ return nil, fmt.Errorf("保存订单详情响应 Cookie: %w", err)
+ }
}
return &automation.OrderDetail{
Quantity: detail.Quantity, SpecName: detail.SpecName, SpecValue: detail.SpecValue,
@@ -333,7 +407,12 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
}, nil
}
-// localOrderDetail 命中本地完整订单时直接返回,避免不必要的浏览器抓取。
+func hasCompleteCookieSnapshot(metadata string) bool {
+ _, ok := cookierefresh.SnapshotFromMetadataOK(metadata)
+ return ok
+}
+
+// localOrderDetail 命中本地完整订单时直接返回,避免不必要的 MTOP 请求。
func (a *Adapter) localOrderDetail(ctx context.Context, orderID string) (*automation.OrderDetail, bool) {
order, err := a.store.Orders.Get(ctx, orderID)
if err != nil || order == nil {
@@ -348,98 +427,44 @@ func (a *Adapter) localOrderDetail(ctx context.Context, orderID string) (*automa
}, true
}
-// OnPasswordLoginRefresh 连续失败时恢复 Cookie。
-//
-// 恢复顺序是“轻量续期 -> 浏览器快速续期 -> 密码登录”。轻量续期/快速续期复用旧 Cookie
-// 刷新登录态;这比账号密码登录更轻,风控压力也更小。
-// 同一账号冷却 engine.PasswordLoginMinGap,避免短时间反复触发浏览器恢复。
+// OnPasswordLoginRefresh 是 engine 的历史回调名。Go 客户端只执行协议级
+// auto-login 续期;失败后要求重新扫码,不得启动 Chromium 密码登录或页面校验。
func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) bool {
cooldown := a.cooldown
if cooldown == nil {
cooldown = renewal.GlobalCooldown
}
if ok, remain, reason := cooldown.PasswordLoginAllowed(cookieID, engine.PasswordLoginMinGap); !ok {
- a.logger.Warn("密码登录刷新冷却中", "account", cookieID, "remain", remain.Round(time.Second))
- a.recordPasswordLogin(ctx, cookieID, 0, "skipped_cooldown", reason, fmt.Sprintf("密码登录刷新冷却中,还需等待 %s", remain.Round(time.Second)))
+ a.logger.Warn("协议续期冷却中", "account", cookieID, "remain", remain.Round(time.Second))
+ a.recordPasswordLogin(ctx, cookieID, 0, "skipped_cooldown", reason, fmt.Sprintf("协议续期冷却中,还需等待 %s", remain.Round(time.Second)))
return false
}
if !a.beginPasswordLogin(cookieID) {
- a.logger.Warn("密码登录刷新已在处理中", "account", cookieID)
+ a.logger.Warn("协议续期已在处理中", "account", cookieID)
return false
}
defer a.finishPasswordLogin(cookieID)
d, err := a.store.Cookies.GetDetails(ctx, cookieID)
if err != nil {
- a.logger.Warn("密码登录刷新失败:读取账号详情失败", "account", cookieID, "err", err)
+ a.logger.Warn("协议续期失败:读取账号详情失败", "account", cookieID, "err", err)
a.recordPasswordLogin(ctx, cookieID, 0, "failed", "account_lookup_failed", err.Error())
return false
}
- lightRenewed, lightRenewErr := a.tryLightRenewBeforePassword(ctx, d)
- if lightRenewed {
- a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "", "密码登录前轻量续期成功")
+ renewed, renewErr := a.tryProtocolCredentialRenew(ctx, d)
+ if renewed {
+ a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "", "Go 协议续期成功")
return true
}
- if errors.Is(lightRenewErr, browser.ErrSecurityVerification) {
- cooldown.MarkPasswordError(cookieID)
- message := "浏览器续期遇到闲鱼安全验证,已停止自动密码登录,请人工完成验证或重新扫码"
- a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn, "闲鱼要求安全验证", message)
- a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "verification_required", message)
- return false
+ message := "Go 协议续期未恢复登录凭证,请重新扫码登录"
+ if renewErr != nil {
+ message += ":" + renewErr.Error()
}
-
- if latest, err := a.store.Cookies.GetDetails(ctx, cookieID); err == nil && latest != nil && latest.Value != "" && latest.Value != d.Value {
- a.logger.Info("密码登录前检测到 DB Cookie 已被外部更新,跳过密码登录", "account", cookieID)
- if a.store.Tokens != nil {
- _ = a.store.Tokens.Clear(ctx, cookieID)
- }
- a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "cookie_already_updated_externally", "数据库中的 Cookie 已被外部更新,跳过密码登录")
- return true
- }
-
- if a.browser == nil {
- a.logger.Warn("密码登录刷新失败:浏览器自动化已禁用,接口轻量续期也未恢复", "account", cookieID)
- a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "browser_disabled", "浏览器自动化已禁用,接口轻量续期未恢复")
- return false
- }
-
- if strings.TrimSpace(d.Username) == "" || strings.TrimSpace(d.Password) == "" {
- msg := "账号已掉线且未配置账号密码"
- a.logger.Warn("密码登录刷新失败:账号未配置登录用户名或密码", "account", cookieID)
- if err := a.store.Cookies.SetStatusWithReason(ctx, cookieID, false, msg); err != nil {
- a.logger.Warn("未配置账号密码时停用账号失败", "account", cookieID, "err", err)
- }
- a.OnAccountEvent(ctx, cookieID, engine.EventAccountDisabled, engine.AlertLevelCritical, "账号已自动禁用", msg)
- a.recordPasswordLogin(ctx, cookieID, d.UserID, "no_credentials", "no_credentials", msg)
- return false
- }
- cookies, err := a.browser.PasswordLogin(ctx, d.Username, d.Password, cookieID, "", browser.ResolveHeadless(d.ShowBrowser))
- if err != nil {
- a.handlePasswordLoginError(ctx, cookieID, err)
- a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", passwordLoginFailureReason(err), err.Error())
- return false
- }
- cookieStr := browser.MarshalCookies(cookies)
- if strings.TrimSpace(cookieStr) == "" {
- a.logger.Warn("密码登录刷新失败:浏览器未返回 cookie", "account", cookieID)
- a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "empty_cookies", "浏览器未返回 cookie")
- return false
- }
- // 参考实现只在真实密码登录拿到 Cookie 后启动 60 秒冷却。
- cooldown.MarkPasswordLogin(cookieID)
- if err := a.store.Cookies.UpdateValueExisting(ctx, cookieID, cookieStr); err != nil {
- a.logger.Warn("密码登录刷新失败:保存 cookie 失败", "account", cookieID, "err", err)
- a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "cookie_update_failed", err.Error())
- return false
- }
- if a.store.Tokens != nil {
- _ = a.store.Tokens.Clear(ctx, cookieID)
- }
- _ = a.store.Cookies.MarkLogin(ctx, cookieID, "password", time.Now().Unix())
- a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "", "账号密码登录刷新成功")
- a.logger.Info("密码登录刷新 cookie 成功", "account", cookieID)
- return true
+ a.logger.Warn("协议续期未恢复账号", "account", cookieID, "err", renewErr)
+ a.OnAccountEvent(ctx, cookieID, engine.EventAccountOffline, engine.AlertLevelWarn, "账号需要重新扫码", message)
+ a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "qr_login_required", message)
+ return false
}
func (a *Adapter) beginPasswordLogin(cookieID string) bool {
@@ -468,7 +493,7 @@ func (a *Adapter) recordPasswordLogin(ctx context.Context, cookieID string, user
if err := a.store.LoginLogs.Add(ctx, db.AccountLoginLog{
CookieID: cookieID,
UserID: userID,
- Method: "password",
+ Method: "protocol",
Status: status,
Message: truncateMessage(message, 500),
TriggerReason: "令牌/Session过期",
@@ -478,28 +503,10 @@ func (a *Adapter) recordPasswordLogin(ctx context.Context, cookieID string, user
DurationMS: 0,
CreatedAt: time.Now().Unix(),
}); err != nil {
- a.logger.Warn("记录密码登录日志失败", "account", cookieID, "err", err)
+ a.logger.Warn("记录协议续期日志失败", "account", cookieID, "err", err)
}
}
-func passwordLoginFailureReason(err error) string {
- if err == nil {
- return ""
- }
- msg := err.Error()
- if isPasswordLoginBadCredentials(msg) {
- return "bad_credentials"
- }
- event := browser.PasswordLoginEventFromError(err)
- if event.Reason != "" {
- return event.Reason
- }
- if event.Status == browser.PasswordLoginStatusVerificationRequired {
- return "verification_required"
- }
- return "other"
-}
-
func truncateMessage(s string, n int) string {
if n <= 0 || len(s) <= n {
return s
@@ -507,145 +514,107 @@ func truncateMessage(s string, n int) string {
return s[:n]
}
-func (a *Adapter) tryLightRenewBeforePassword(ctx context.Context, d *db.CookieDetail) (bool, error) {
+func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookieDetail) (bool, error) {
if d == nil {
return false, nil
}
current := d.Value
api := a.renewSvc
- save := func(cookieStr string) {
- if strings.TrimSpace(cookieStr) == "" || cookieStr == current {
- return
+ save := func(cookieStr string, setCookies []string, completeSnapshot []cookierefresh.BrowserCookie) error {
+ if cookieStr == current && len(setCookies) == 0 && completeSnapshot == nil {
+ return nil
}
- if err := a.store.Cookies.UpdateRenewalCookie(ctx, d.ID, cookieStr, cookierefresh.MetadataWithoutSnapshot(d.MetadataJSON), time.Now().Unix()); err != nil {
+ metadata := cookierefresh.MetadataWithoutSnapshot(d.MetadataJSON)
+ if completeSnapshot != nil {
+ // API 在完整 Jar 基础上得到的快照是权威结果,包含
+ // 服务端删除和新的 Domain/Path/expiry 属性。
+ metadata = cookierefresh.MetadataWithSnapshot(d.MetadataJSON, completeSnapshot)
+ }
+ if err := a.store.Cookies.UpdateRenewalCookie(ctx, d.ID, cookieStr, metadata, time.Now().Unix()); err != nil {
a.logger.Warn("轻量续期保存 Cookie 失败", "account", d.ID, "err", err)
- return
+ return err
}
+ valueChanged := cookieStr != current
current = cookieStr
d.Value = cookieStr
- if a.store.Tokens != nil {
- _ = a.store.Tokens.Clear(ctx, d.ID)
+ d.MetadataJSON = metadata
+ if valueChanged && a.store.Tokens != nil {
+ if err := a.store.Tokens.Clear(ctx, d.ID); err != nil {
+ // Token 仅是运行期缓存;Cookie 已原子提交后不能再把整次
+ // 续期报告成失败,否则调用方可能用旧凭证重试并覆盖新 Jar。
+ a.logger.Warn("轻量续期清理旧 Token 缓存失败", "account", d.ID, "err", err)
+ }
}
+ return nil
}
- apiRenew := func(cookieStr string) (*xrenew.Result, error) {
- runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
- defer cancel()
- return api.RenewAPIFirst(runCtx, cookieStr)
- }
- browserRenew := func(cookieStr string) (string, error) {
- if a.browser == nil {
- return "", fmt.Errorf("浏览器自动化未启用")
+ // 官网始终先由 auto-login plugin 按 havana_lgc_exp/cookie3_bak_exp
+ // 决定是否调用 silentHasLogin。Go 客户端复刻该 HTTP 协议,不加载页面。
+ runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
+ defer cancel()
+ res, err := api.RenewAPIFirst(runCtx, current, cookierefresh.SnapshotFromMetadata(d.MetadataJSON))
+ if res != nil {
+ var completeSnapshot []cookierefresh.BrowserCookie
+ if res.CookieSnapshotComplete {
+ completeSnapshot = res.CookieSnapshot
+ if completeSnapshot == nil {
+ completeSnapshot = []cookierefresh.BrowserCookie{}
+ }
}
- if br, ok := a.browser.(browserQuickRenewer); ok {
- runCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
- defer cancel()
- return br.BrowserQuickRenew(runCtx, d.ID, cookieStr, browser.ResolveHeadless(d.ShowBrowser))
+ if saveErr := save(res.NewCookies, res.SetCookies, completeSnapshot); saveErr != nil {
+ return false, saveErr
}
- m, err := a.browser.CookieRenew(ctx, d.ID, cookieStr, browser.ResolveHeadless(d.ShowBrowser))
- if err != nil {
- return "", err
- }
- return browser.MarshalCookies(m), nil
- }
-
- hasLongLogin := strings.TrimSpace(protocol.TransCookies(current)["havana_lgc2_77"]) != ""
- if hasLongLogin {
- if renewed, err := browserRenew(current); err == nil && renewed != "" {
- save(renewed)
- a.logger.Info("密码登录前浏览器续期成功,跳过密码登录", "account", d.ID)
+ if res.HasPending() {
+ a.watchPendingProtocolRenew(d.ID, res)
+ // 官网 Promise 超时只记录错误,不把当前登录态判定为失效。
return true, nil
- } else if err != nil {
- if errors.Is(err, browser.ErrSecurityVerification) {
- return false, err
- }
- a.logger.Warn("密码登录前浏览器续期失败,继续尝试接口续期", "account", d.ID, "err", err)
}
- if res, err := apiRenew(current); err == nil && res != nil {
- save(res.NewCookies)
- if res.Success {
- a.logger.Info("密码登录前静默续期成功,跳过密码登录", "account", d.ID)
- return true, nil
- }
- }
- return false, nil
- }
-
- res, err := apiRenew(current)
- if err == nil && res != nil {
- save(res.NewCookies)
- if res.Success {
- a.logger.Info("密码登录前接口续期成功,跳过密码登录", "account", d.ID)
+ if err == nil && res.Success {
+ a.logger.Info("Go 协议续期成功", "account", d.ID)
return true, nil
}
}
- browserInput := current
- if res != nil && strings.TrimSpace(res.NewCookies) != "" {
- browserInput = res.NewCookies
- }
- browserCookies, err := browserRenew(browserInput)
- if err != nil || browserCookies == "" {
- if errors.Is(err, browser.ErrSecurityVerification) {
- return false, err
- }
- return false, nil
- }
- save(browserCookies)
- a.logger.Info("密码登录前浏览器续期成功,跳过密码登录", "account", d.ID)
- return true, nil
+ return false, err
}
-func (a *Adapter) handlePasswordLoginError(ctx context.Context, cookieID string, err error) {
- msg := err.Error()
- a.logger.Warn("密码登录刷新失败", "account", cookieID, "err", err)
- if isPasswordLoginDisableError(msg) {
- _ = a.store.Cookies.SetStatusWithReason(ctx, cookieID, false, msg)
- a.OnAccountEvent(ctx, cookieID, engine.EventAccountDisabled, engine.AlertLevelCritical, "账号已自动禁用", msg)
- if isPasswordLoginBadCredentials(msg) {
- a.markPasswordError(cookieID)
- }
+func (a *Adapter) watchPendingProtocolRenew(cookieID string, result *xrenew.Result) {
+ if result == nil || !result.HasPending() || a.store == nil || a.store.Cookies == nil {
return
}
- if isPasswordLoginRetryableVerification(msg) {
- a.markPasswordError(cookieID)
- }
-}
-
-func isPasswordLoginBadCredentials(msg string) bool {
- return strings.Contains(msg, "账密错误") ||
- strings.Contains(msg, "账号密码错误") ||
- strings.Contains(msg, "用户名或密码错误") ||
- strings.Contains(msg, "账号或密码错误") ||
- strings.Contains(msg, "密码错误")
-}
-
-func isPasswordLoginDisableError(msg string) bool {
- return isPasswordLoginBadCredentials(msg) ||
- strings.Contains(msg, "账号不存在") ||
- strings.Contains(msg, "账号已被冻结") ||
- strings.Contains(msg, "账号被冻结") ||
- strings.Contains(msg, "账户被冻结") ||
- strings.Contains(msg, "账号已锁定") ||
- strings.Contains(msg, "账户已锁定") ||
- strings.Contains(msg, "操作过于频繁") ||
- strings.Contains(msg, "登录过于频繁") ||
- strings.Contains(msg, "暂时无法登录")
-}
-
-func isPasswordLoginRetryableVerification(msg string) bool {
- event := browser.PasswordLoginEventFromMessage(msg)
- return event.Reason == "baxia_punish_captcha" ||
- event.Status == browser.PasswordLoginStatusVerificationRequired ||
- strings.Contains(msg, "人工验证") ||
- strings.Contains(msg, "人脸验证") ||
- strings.Contains(msg, "身份验证")
-}
-
-func (a *Adapter) markPasswordError(cookieID string) {
- cooldown := a.cooldown
- if cooldown == nil {
- cooldown = renewal.GlobalCooldown
- }
- cooldown.MarkPasswordError(cookieID)
+ go func() {
+ ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
+ defer cancel()
+ late, waitErr := result.AwaitPending(ctx)
+ if late == nil {
+ if waitErr != nil {
+ a.logger.Warn("等待协议续期底层响应失败", "account", cookieID, "err", waitErr)
+ }
+ return
+ }
+ unlock := a.store.LockAccountCredentials(cookieID)
+ defer unlock()
+ detail, getErr := a.store.Cookies.GetDetails(ctx, cookieID)
+ if getErr != nil || detail == nil {
+ if getErr == nil {
+ getErr = db.ErrNotFound
+ }
+ a.logger.Warn("保存协议续期迟到 Cookie 前读取账号失败", "account", cookieID, "err", getErr)
+ return
+ }
+ newCookies, metadata, changed := xrenew.RebaseResponseCookies(detail.Value, detail.MetadataJSON, late)
+ if changed {
+ if saveErr := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, metadata, time.Now().Unix()); saveErr != nil {
+ a.logger.Warn("保存协议续期迟到 Cookie 失败", "account", cookieID, "err", saveErr)
+ return
+ }
+ if a.store.Tokens != nil {
+ _ = a.store.Tokens.Clear(ctx, cookieID)
+ }
+ a.logger.Info("已异步接收协议续期迟到 Cookie", "account", cookieID)
+ }
+ if waitErr != nil {
+ a.logger.Warn("协议续期底层响应失败,已保存响应 Cookie", "account", cookieID, "err", waitErr)
+ }
+ }()
}
// 编译期保证 *Adapter 同时实现 engine.Handler 与 automation.OrderDetailFetcher。
diff --git a/internal/adapter/adapter_test.go b/internal/adapter/adapter_test.go
index bd51af5..885427c 100644
--- a/internal/adapter/adapter_test.go
+++ b/internal/adapter/adapter_test.go
@@ -8,12 +8,14 @@ import (
"path/filepath"
"strings"
"testing"
+ "time"
"xianyu-go/internal/automation"
"xianyu-go/internal/browser"
"xianyu-go/internal/db"
"xianyu-go/internal/engine"
"xianyu-go/internal/renewal"
+ "xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
xrenew "xianyu-go/internal/xianyu/renew"
)
@@ -53,6 +55,19 @@ type fakeBrowser struct {
providerUpdated string
}
+type fakeSnapshotBrowser struct {
+ fakeBrowser
+ snapshotCookies string
+ snapshot []cookierefresh.BrowserCookie
+ snapshotErr error
+ snapshotCalls int
+}
+
+func (f *fakeSnapshotBrowser) TokenCaptchaCookieSnapshot(context.Context, string, bool) (string, []cookierefresh.BrowserCookie, error) {
+ f.snapshotCalls++
+ return f.snapshotCookies, f.snapshot, f.snapshotErr
+}
+
func (f *fakeBrowser) FetchOrderDetail(_ context.Context, _, _, _ string, _ ...bool) (*browser.OrderDetail, error) {
return f.fetchDetail, f.fetchErr
}
@@ -82,6 +97,17 @@ type fakeCaptchaRequester struct {
gotDeviceID string
}
+type fakeOrderDetailClient struct {
+ detail *mtop.OrderDetailResult
+ err error
+ calls int
+}
+
+func (f *fakeOrderDetailClient) FetchOrderDetail(_ context.Context, _, _ string) (*mtop.OrderDetailResult, error) {
+ f.calls++
+ return f.detail, f.err
+}
+
func (f *fakeCaptchaRequester) RequestFreshCaptchaURLContext(_ context.Context, cookiesStr, deviceID string) (*mtop.FreshCaptchaResult, error) {
f.calls++
f.gotCookies = cookiesStr
@@ -108,8 +134,11 @@ func verifiedRenewService(t *testing.T) (xrenew.Service, func()) {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
- case "/hasLogin.do", "/silentHasLogin.do":
+ case "/hasLogin.do":
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
+ case "/silentHasLogin.do":
+ http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "verified"})
+ _, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
case "/setLoginSettings.do":
http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "verified"})
_, _ = w.Write([]byte(`{"content":{"success":true}}`))
@@ -225,6 +254,45 @@ func TestOnTokenCaptchaVerification_SavesCookiesAndRiskLog(t *testing.T) {
}
}
+func TestOnTokenCaptchaVerificationPersistsExactBrowserJar(t *testing.T) {
+ store, cleanup := newAdapterTestStore(t)
+ defer cleanup()
+ ctx := context.Background()
+ browserSnapshot := []cookierefresh.BrowserCookie{
+ {Name: "unb", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true, HTTPOnly: true},
+ {Name: "x5sec", Value: "fresh", Domain: ".goofish.com", Path: "/", Secure: true, HTTPOnly: true, Expires: float64(time.Now().Add(time.Hour).Unix())},
+ }
+ fb := &fakeSnapshotBrowser{
+ fakeBrowser: fakeBrowser{tokenCaptchaResult: "unb=1; x5sec=fresh"},
+ snapshotCookies: "unb=1; x5sec=fresh",
+ snapshot: browserSnapshot,
+ }
+ a := New(store, nil, nil)
+ a.SetBrowser(fb)
+ a.SetTokenCaptchaRequester(&fakeCaptchaRequester{})
+ result, ok := a.OnTokenCaptchaVerification(ctx, "cid", "unb=1", "https://passport.goofish.com/punish", "device")
+ if !ok || result == nil || !result.CookieSnapshotComplete || fb.snapshotCalls != 1 {
+ t.Fatalf("result=%+v ok=%v snapshot_calls=%d", result, ok, fb.snapshotCalls)
+ }
+ detail, err := store.Cookies.GetDetails(ctx, "cid")
+ if err != nil {
+ t.Fatal(err)
+ }
+ saved, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
+ if !complete || len(saved) != 2 || detail.Value != "unb=1; x5sec=fresh" {
+ t.Fatalf("滑块完整 Jar 未保存: value=%q complete=%v snapshot=%+v", detail.Value, complete, saved)
+ }
+ var exactX5 bool
+ for _, cookie := range saved {
+ if cookie.Name == "x5sec" && cookie.HTTPOnly && cookie.Secure && cookie.Expires > 0 {
+ exactX5 = true
+ }
+ }
+ if !exactX5 {
+ t.Fatalf("x5sec 属性被扁平化: %+v", saved)
+ }
+}
+
// TestHandleSystemEvent_UninjectedSafe 未注入 automation 时安全返回 nil。
func TestHandleSystemEvent_UninjectedSafe(t *testing.T) {
store, cleanup := newAdapterTestStore(t)
@@ -253,32 +321,33 @@ func TestFetchOrderDetail_LocalHitShortCircuits(t *testing.T) {
}
}
-// TestFetchOrderDetail_BrowserNilReturnsError 本地缺字段且浏览器未启用时返回明确错误。
-func TestFetchOrderDetail_BrowserNilReturnsError(t *testing.T) {
+// TestFetchOrderDetail_MTopNilReturnsError 本地缺字段且 MTOP 客户端未配置时返回明确错误。
+func TestFetchOrderDetail_MTopNilReturnsError(t *testing.T) {
store, cleanup := newAdapterTestStore(t)
defer cleanup()
a := New(store, nil, nil)
+ a.SetOrderDetailClient(nil)
_, err := a.FetchOrderDetail(context.Background(), "cid", "o-missing", "item-1", "buyer-1", "cookie")
if err == nil {
- t.Fatal("browser=nil 且本地缺失应返回错误")
+ t.Fatal("MTOP=nil 且本地缺失应返回错误")
}
}
-// TestFetchOrderDetail_BrowserFallback 本地缺失但有浏览器时调用浏览器抓取并保存刷新的 cookie。
-func TestFetchOrderDetail_BrowserFallback(t *testing.T) {
+// TestFetchOrderDetail_GoMTop 本地缺失时调用 Go MTOP 并保存响应 Cookie。
+func TestFetchOrderDetail_GoMTop(t *testing.T) {
store, cleanup := newAdapterTestStore(t)
defer cleanup()
ctx := context.Background()
a := New(store, nil, nil)
- a.SetBrowser(&fakeBrowser{
- fetchDetail: &browser.OrderDetail{
+ a.SetOrderDetailClient(&fakeOrderDetailClient{
+ detail: &mtop.OrderDetailResult{
Quantity: "2", SpecName: "套餐", SpecValue: "30天", Amount: "19.8",
UpdatedCookies: "unb=1; _m_h5_tk=newtoken;",
},
})
detail, err := a.FetchOrderDetail(ctx, "cid", "o-fallback", "item-1", "buyer-1", "old-cookie")
if err != nil {
- t.Fatalf("浏览器兜底应成功: %v", err)
+ t.Fatalf("Go MTOP 应成功: %v", err)
}
if detail.SpecValue != "30天" || detail.Amount != "19.8" {
t.Fatalf("detail=%+v", detail)
@@ -290,11 +359,35 @@ func TestFetchOrderDetail_BrowserFallback(t *testing.T) {
}
}
+func TestFetchOrderDetail_PersistsFlatGoMTopCookie(t *testing.T) {
+ store, cleanup := newAdapterTestStore(t)
+ defer cleanup()
+ ctx := context.Background()
+ a := New(store, nil, nil)
+ a.SetOrderDetailClient(&fakeOrderDetailClient{detail: &mtop.OrderDetailResult{
+ Quantity: "1", Amount: "9.9", UpdatedCookies: "unb=1; api_only=scoped",
+ }})
+ if _, err := a.FetchOrderDetail(ctx, "cid", "o-jar", "item-1", "buyer-1", "old-cookie"); err != nil {
+ t.Fatal(err)
+ }
+ detail, err := store.Cookies.GetDetails(ctx, "cid")
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
+ if complete || detail.Value != "unb=1; api_only=scoped" {
+ t.Fatalf("Go MTOP flat cookie not persisted: value=%q complete=%v", detail.Value, complete)
+ }
+}
+
// TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew 浏览器未启用时仍先尝试接口轻量续期。
func TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew(t *testing.T) {
store, cleanup := newAdapterTestStore(t)
defer cleanup()
a := New(store, nil, nil)
+ if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", "unb=1; _m_h5_tk=tk; havana_lgc2_77=lgc; havana_lgc_exp=9999999999999"); err != nil {
+ t.Fatal(err)
+ }
renewSvc, closeRenew := verifiedRenewService(t)
defer closeRenew()
a.SetRenewService(renewSvc)
@@ -322,8 +415,8 @@ func TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure(t *testing
t.Fatal("browser=nil 且接口续期失败时应返回 false")
}
logs, err := store.LoginLogs.ListByCookie(context.Background(), "cid", 10)
- if err != nil || len(logs) != 1 || logs[0].FailureReason != "browser_disabled" {
- t.Fatalf("浏览器不可用应记录 browser_disabled: logs=%#v err=%v", logs, err)
+ if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" || logs[0].Method != "protocol" {
+ t.Fatalf("协议续期失败应要求扫码: logs=%#v err=%v", logs, err)
}
}
@@ -340,17 +433,17 @@ func TestOnPasswordLoginRefresh_NoCredentialsReturnsFalse(t *testing.T) {
if a.OnPasswordLoginRefresh(ctx, "cid") {
t.Fatal("账号未配用户名/密码应返回 false")
}
- if store.Cookies.GetStatus(ctx, "cid") {
- t.Fatal("未配置账号密码应自动停用账号,避免持续重试")
+ if !store.Cookies.GetStatus(ctx, "cid") {
+ t.Fatal("Go 客户端不得因未配置密码停用账号")
}
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
- if err != nil || len(logs) != 1 || logs[0].Status != "no_credentials" || logs[0].FailureReason != "no_credentials" {
- t.Fatalf("无凭据应记录 no_credentials 日志: logs=%#v err=%v", logs, err)
+ if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" {
+ t.Fatalf("应记录重新扫码日志: logs=%#v err=%v", logs, err)
}
}
-// TestOnPasswordLoginRefresh_BrowserRenewSuccess 无账密时旧 Cookie 仍可快速续期,应保存新 Cookie 并跳过密码登录。
-func TestOnPasswordLoginRefresh_BrowserRenewSuccess(t *testing.T) {
+// TestOnPasswordLoginRefresh_DoesNotUseBrowserRenew 协议失败后不得调用浏览器续期。
+func TestOnPasswordLoginRefresh_DoesNotUseBrowserRenew(t *testing.T) {
store, cleanup := newAdapterTestStore(t)
defer cleanup()
ctx := context.Background()
@@ -364,30 +457,23 @@ func TestOnPasswordLoginRefresh_BrowserRenewSuccess(t *testing.T) {
defer closeRenew()
a.SetRenewService(renewSvc)
a.SetBrowser(fb)
- if !a.OnPasswordLoginRefresh(ctx, "cid") {
- t.Fatal("快速续期成功应返回 true")
+ if a.OnPasswordLoginRefresh(ctx, "cid") {
+ t.Fatal("协议续期失败应返回 false")
}
- if fb.renewCalls != 1 {
- t.Fatalf("CookieRenew 应调用一次,got %d", fb.renewCalls)
+ if fb.renewCalls != 0 {
+ t.Fatalf("不得调用浏览器 CookieRenew,got %d", fb.renewCalls)
}
if fb.loginCalls != 0 {
t.Fatalf("快速续期成功后不应密码登录,got %d", fb.loginCalls)
}
- saved, _ := store.Cookies.GetValue(ctx, "cid")
- if !strings.Contains(saved, "_m_h5_tk=renewed") || !strings.Contains(saved, "havana_lgc2_77=verified") {
- t.Fatalf("快速续期 cookie 未保存: %q", saved)
- }
- if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != "did-old" {
- t.Fatalf("Cookie 更新后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
- }
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
- if err != nil || len(logs) != 1 || logs[0].Status != "success" {
- t.Fatalf("快速续期应记录登录日志: logs=%#v err=%v", logs, err)
+ if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" {
+ t.Fatalf("应记录重新扫码日志: logs=%#v err=%v", logs, err)
}
}
-// TestOnPasswordLoginRefresh_Success 配好凭据后浏览器登录成功,cookie 被保存。
-func TestOnPasswordLoginRefresh_Success(t *testing.T) {
+// TestOnPasswordLoginRefresh_DoesNotUsePasswordLogin 配好密码也不得启动 Chromium 登录。
+func TestOnPasswordLoginRefresh_DoesNotUsePasswordLogin(t *testing.T) {
store, cleanup := newAdapterTestStore(t)
defer cleanup()
ctx := context.Background()
@@ -400,26 +486,22 @@ func TestOnPasswordLoginRefresh_Success(t *testing.T) {
defer closeRenew()
a.SetRenewService(renewSvc)
a.SetBrowser(fb)
- if !a.OnPasswordLoginRefresh(ctx, "cid") {
- t.Fatal("登录成功应返回 true")
+ if a.OnPasswordLoginRefresh(ctx, "cid") {
+ t.Fatal("协议续期失败应返回 false")
}
- if fb.loginCalls != 1 {
- t.Fatalf("PasswordLogin 应调用一次,got %d", fb.loginCalls)
- }
- saved, _ := store.Cookies.GetValue(ctx, "cid")
- if saved == "" {
- t.Fatal("刷新的 cookie 应已保存")
+ if fb.loginCalls != 0 {
+ t.Fatalf("不得调用 Chromium PasswordLogin,got %d", fb.loginCalls)
}
d, err := store.Cookies.GetDetails(ctx, "cid")
if err != nil {
t.Fatalf("GetDetails: %v", err)
}
- if d.LoginMethod != "password" || d.LastLoginAt == 0 {
- t.Fatalf("密码登录成功后应标记登录审计字段: %+v", d)
+ if d.LoginMethod == "password" {
+ t.Fatalf("不得标记密码登录: %+v", d)
}
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
- if err != nil || len(logs) != 1 || logs[0].Status != "success" {
- t.Fatalf("密码登录成功应记录日志: logs=%#v err=%v", logs, err)
+ if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" {
+ t.Fatalf("应记录重新扫码日志: logs=%#v err=%v", logs, err)
}
}
@@ -443,8 +525,8 @@ func TestOnPasswordLoginRefresh_LoginError(t *testing.T) {
t.Fatal("验证失败后的账密错误冷却期应返回 false")
}
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
- if err != nil || len(logs) != 2 || logs[0].Status != "skipped_cooldown" || logs[0].FailureReason != "password_error_cooldown" || logs[1].FailureReason != "verification_required" {
- t.Fatalf("密码登录失败应记录日志: logs=%#v err=%v", logs, err)
+ if err != nil || len(logs) != 2 || logs[0].FailureReason != "qr_login_required" || fb.loginCalls != 0 {
+ t.Fatalf("不得调用密码登录,应要求扫码: logs=%#v err=%v", logs, err)
}
}
@@ -464,8 +546,8 @@ func TestOnPasswordLoginRefresh_BaxiaFailureReason(t *testing.T) {
t.Fatal("风控失败应返回 false")
}
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
- if err != nil || len(logs) != 1 || logs[0].FailureReason != "baxia_punish_captcha" {
- t.Fatalf("baxia 风控应记录专用 failure_reason: logs=%#v err=%v", logs, err)
+ if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" || fb.loginCalls != 0 {
+ t.Fatalf("不得调用密码登录,应要求扫码: logs=%#v err=%v", logs, err)
}
if !store.Cookies.GetStatus(ctx, "cid") {
t.Fatal("baxia 风控只应冷却,不应停用账号")
@@ -487,8 +569,8 @@ func TestOnPasswordLoginRefresh_DisablesFrozenAccountError(t *testing.T) {
if a.OnPasswordLoginRefresh(ctx, "cid") {
t.Fatal("冻结账号登录失败应返回 false")
}
- if store.Cookies.GetStatus(ctx, "cid") {
- t.Fatal("冻结账号登录错误应停用账号")
+ if !store.Cookies.GetStatus(ctx, "cid") || fb.loginCalls != 0 {
+ t.Fatal("未执行密码登录时不得按浏览器页面错误停用账号")
}
}
@@ -521,18 +603,18 @@ func TestOnPasswordLoginRefresh_Cooldown(t *testing.T) {
defer closeRenew()
a.SetRenewService(renewSvc)
a.SetBrowser(fb)
- if !a.OnPasswordLoginRefresh(ctx, "cid") {
- t.Fatal("首次应成功")
+ if a.OnPasswordLoginRefresh(ctx, "cid") {
+ t.Fatal("协议续期失败应返回 false")
}
// 第二次在冷却期内,应被拒绝且不调用浏览器。
if a.OnPasswordLoginRefresh(ctx, "cid") {
t.Fatal("冷却期内应返回 false")
}
- if fb.loginCalls != 1 {
- t.Fatalf("冷却期内不应调用浏览器,got calls=%d", fb.loginCalls)
+ if fb.loginCalls != 0 {
+ t.Fatalf("任何一次都不应调用浏览器,got calls=%d", fb.loginCalls)
}
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
- if err != nil || len(logs) != 2 || logs[0].Status != "skipped_cooldown" || logs[0].FailureReason != "login_cooldown" {
- t.Fatalf("冷却拒绝应记录 skipped_cooldown 日志: logs=%#v err=%v", logs, err)
+ if err != nil || len(logs) != 2 || logs[0].FailureReason != "qr_login_required" {
+ t.Fatalf("协议失败应记录重新扫码日志: logs=%#v err=%v", logs, err)
}
}
diff --git a/internal/automation/center.go b/internal/automation/center.go
index f79ddde..a52a385 100644
--- a/internal/automation/center.go
+++ b/internal/automation/center.go
@@ -12,6 +12,7 @@ import (
"time"
"xianyu-go/internal/db"
+ "xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
)
@@ -732,28 +733,77 @@ func (c *Center) confirmShipment(ctx context.Context, task Task) error {
if !enabled && !task.ForceConfirmShipment {
return nil
}
- cookieStr := task.CookieStr
- if strings.TrimSpace(cookieStr) == "" {
- cookieStr, err = c.cookieValue(ctx, task.AccountID)
- if err != nil {
- return err
+ credentialUnlock := c.store.LockAccountCredentials(task.AccountID)
+ credentialLocked := true
+ defer func() {
+ if credentialLocked {
+ credentialUnlock()
}
- }
- ok, ret, updated, err := c.mtop.ConsignContext(ctx, cookieStr, task.OrderID)
+ }()
+ detail, err := c.store.Cookies.GetDetails(ctx, task.AccountID)
if err != nil {
- return uncertainAction(err)
+ return err
}
+ if detail == nil {
+ return db.ErrNotFound
+ }
+ _, completeSnapshot := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
+ if strings.TrimSpace(detail.Value) == "" && !completeSnapshot {
+ return fmt.Errorf("账号 %s Cookie 为空", task.AccountID)
+ }
+ cookieStr := detail.Value
+ var mtopCtx context.Context
+ var cookieSession *mtop.CookieSession
+ if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); ok {
+ mtopCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot)
+ } else {
+ mtopCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr)
+ }
+ ok, ret, updated, callErr := c.mtop.ConsignContext(mtopCtx, cookieStr, task.OrderID)
var persistenceErrs []error
- if updated != "" && updated != cookieStr {
- if saveErr := c.store.Cookies.UpdateValueExisting(ctx, task.AccountID, updated); saveErr != nil {
+ runtimeCookie := ""
+ runtimeCookieChanged := false
+ value, snapshot, changed := cookieSession.State()
+ // 完整 Jar 已接管时,即使响应没有 Cookie 变化,也不能因扁平字符串
+ // 格式差异回退覆盖并清除 Jar。
+ sessionHandled := snapshot != nil
+ if changed {
+ metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
+ if snapshot != nil {
+ metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
+ }
+ if saveErr := c.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, value, metadata, time.Now().Unix()); saveErr != nil {
+ persistenceErrs = append(persistenceErrs, fmt.Errorf("保存确认发货响应 Cookie Jar: %w", saveErr))
+ } else if value != cookieStr {
+ runtimeCookie = value
+ runtimeCookieChanged = true
+ }
+ }
+ if !sessionHandled && callErr == nil && updated != "" && updated != cookieStr {
+ // 注入 mock 或没有权威快照的历史账号保留扁平
+ // Cookie 兼容路径;扁平结果无法维护旧 Jar 的作用域,
+ // 因此不得继续保留可能已过期的 snapshot。
+ metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
+ if saveErr := c.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, updated, metadata, time.Now().Unix()); saveErr != nil {
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存刷新后的 Cookie: %w", saveErr))
+ } else {
+ runtimeCookie = updated
+ runtimeCookieChanged = true
}
- if c.senders != nil {
- if sender, running := c.senders.Sender(task.AccountID); running {
- sender.UpdateCookie(updated)
- }
+ }
+ credentialUnlock()
+ credentialLocked = false
+ if runtimeCookieChanged && c.senders != nil {
+ if sender, running := c.senders.Sender(task.AccountID); running {
+ sender.UpdateCookie(runtimeCookie)
}
}
+ if callErr != nil {
+ if len(persistenceErrs) > 0 {
+ callErr = errors.Join(callErr, errors.Join(persistenceErrs...))
+ }
+ return uncertainAction(callErr)
+ }
if !ok {
failure := fmt.Errorf("确认发货失败: %s", strings.Join(ret, "; "))
if len(persistenceErrs) > 0 {
diff --git a/internal/automation/center_mock_mtop_test.go b/internal/automation/center_mock_mtop_test.go
index 9e599ef..3706320 100644
--- a/internal/automation/center_mock_mtop_test.go
+++ b/internal/automation/center_mock_mtop_test.go
@@ -7,6 +7,7 @@ import (
"testing"
"xianyu-go/internal/db"
+ "xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
)
@@ -145,3 +146,79 @@ func TestConfirmShipmentQuarantinesKnownRemoteSuccessWhenLocalPersistenceFails(t
t.Fatal("failed local write must not be reported as persisted")
}
}
+
+func TestConfirmShipmentKeepsAuthoritativeSnapshotWhenSessionUnchanged(t *testing.T) {
+ store, cleanup := newAutomationTestStore(t)
+ defer cleanup()
+ ctx := context.Background()
+ initial := "unb=123; _m_h5_tk=old_1;"
+ metadata := cookierefresh.MetadataWithSnapshot(`{"preserved":true}`, []cookierefresh.BrowserCookie{
+ {Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "_m_h5_tk", Value: "old_1", Domain: ".goofish.com", Path: "/", Secure: true},
+ })
+ if err := store.Cookies.UpdateRenewalCookie(ctx, "cid", initial, metadata, 1); err != nil {
+ t.Fatal(err)
+ }
+ updated := "unb=123; _m_h5_tk=mock_new_2;"
+ sender := &testSender{}
+ center := New(store, testSenderProvider{sender: sender}, nil)
+ center.SetMTop(&fakeMTop{consignOk: false, consignRet: []string{"FAIL_SHIP"}, consignUpdated: updated})
+ err := center.confirmShipment(ctx, Task{
+ AccountID: "cid", OrderID: "flat-mock-fallback", ForceConfirmShipment: true,
+ })
+ if err == nil || !strings.Contains(err.Error(), "FAIL_SHIP") {
+ t.Fatalf("mock 业务失败应保留原返回语义: %v", err)
+ }
+ detail, getErr := store.Cookies.GetDetails(ctx, "cid")
+ if getErr != nil {
+ t.Fatal(getErr)
+ }
+ if detail.Value != initial {
+ t.Fatalf("完整 Jar 未变化时不得被扁平/mock 返回覆盖: %q", detail.Value)
+ }
+ if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); !ok || len(snapshot) != 2 {
+ t.Fatalf("完整 Jar 未变化时必须继续保留: ok=%v snapshot=%+v metadata=%s", ok, snapshot, detail.MetadataJSON)
+ }
+ if !strings.Contains(detail.MetadataJSON, `"preserved":true`) {
+ t.Fatalf("保留 snapshot 时丢失其他 metadata: %s", detail.MetadataJSON)
+ }
+ if len(sender.cookieUpdates) != 0 {
+ t.Fatalf("被忽略的扁平/mock 返回不得同步运行实例: %+v", sender.cookieUpdates)
+ }
+}
+
+func TestConfirmShipmentKeepsFlatMockFallbackWithoutSnapshot(t *testing.T) {
+ store, cleanup := newAutomationTestStore(t)
+ defer cleanup()
+ ctx := context.Background()
+ initial := "unb=123; _m_h5_tk=old_1;"
+ if err := store.Cookies.UpdateRenewalCookie(ctx, "cid", initial, `{"preserved":true}`, 1); err != nil {
+ t.Fatal(err)
+ }
+ updated := "unb=123; _m_h5_tk=mock_new_2;"
+ sender := &testSender{}
+ center := New(store, testSenderProvider{sender: sender}, nil)
+ center.SetMTop(&fakeMTop{consignOk: false, consignRet: []string{"FAIL_SHIP"}, consignUpdated: updated})
+ err := center.confirmShipment(ctx, Task{
+ AccountID: "cid", OrderID: "flat-mock-fallback", ForceConfirmShipment: true,
+ })
+ if err == nil || !strings.Contains(err.Error(), "FAIL_SHIP") {
+ t.Fatalf("mock 业务失败应保留原返回语义: %v", err)
+ }
+ detail, getErr := store.Cookies.GetDetails(ctx, "cid")
+ if getErr != nil {
+ t.Fatal(getErr)
+ }
+ if detail.Value != updated {
+ t.Fatalf("无完整 Jar 时未保留扁平/mock 写回路径: %q", detail.Value)
+ }
+ if _, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); ok {
+ t.Fatalf("扁平 mock 结果不得伪装成权威 Jar: %s", detail.MetadataJSON)
+ }
+ if !strings.Contains(detail.MetadataJSON, `"preserved":true`) {
+ t.Fatalf("扁平写回时丢失其他 metadata: %s", detail.MetadataJSON)
+ }
+ if len(sender.cookieUpdates) != 1 || sender.cookieUpdates[0] != updated {
+ t.Fatalf("扁平/mock 更新未同步运行实例: %+v", sender.cookieUpdates)
+ }
+}
diff --git a/internal/automation/center_test.go b/internal/automation/center_test.go
index 6f56ac5..1e115a3 100644
--- a/internal/automation/center_test.go
+++ b/internal/automation/center_test.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "io"
"net/http"
"net/http/httptest"
"path/filepath"
@@ -14,18 +15,27 @@ import (
"time"
"xianyu-go/internal/db"
+ "xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
)
+type automationRoundTripperFunc func(*http.Request) (*http.Response, error)
+
+func (f automationRoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
+ return f(req)
+}
+
type testSenderProvider struct{ sender *testSender }
func (p testSenderProvider) Sender(string) (MessageSender, bool) { return p.sender, true }
type testSender struct {
- texts []string
- events *[]string
- err error
- failAfter int
+ texts []string
+ cookieUpdates []string
+ onCookieUpdate func(string)
+ events *[]string
+ err error
+ failAfter int
}
func (s *testSender) SendText(_ context.Context, _, _, text string) error {
@@ -68,7 +78,12 @@ func TestPartialAutomationRunIsQuarantined(t *testing.T) {
}
}
func (s *testSender) SendImage(context.Context, string, string, string, int64) error { return nil }
-func (s *testSender) UpdateCookie(string) {}
+func (s *testSender) UpdateCookie(cookieStr string) {
+ s.cookieUpdates = append(s.cookieUpdates, cookieStr)
+ if s.onCookieUpdate != nil {
+ s.onCookieUpdate(cookieStr)
+ }
+}
type testFetcher struct{ detail *OrderDetail }
@@ -654,6 +669,149 @@ func TestCenterOrderPaidSendsCardBeforeConfirmShipment(t *testing.T) {
}
}
+func TestConfirmShipmentPersistsAuthoritativeSessionBeforeParseError(t *testing.T) {
+ store, cleanup := newAutomationTestStore(t)
+ defer cleanup()
+ ctx := context.Background()
+ initialValue := "flat_leak=must-not-send; unb=123; _m_h5_tk=flat_old_1"
+ snapshot := []cookierefresh.BrowserCookie{
+ {Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "_m_h5_tk", Value: "snapshot_old_1", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "document_only", Value: "doc", Domain: "www.goofish.com", Path: "/im", Secure: true},
+ {Name: "api_only", Value: "api", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
+ }
+ metadata := cookierefresh.MetadataWithSnapshot(`{"preserved":"yes"}`, snapshot)
+ if err := store.Cookies.UpdateRenewalCookie(ctx, "cid", initialValue, metadata, 1); err != nil {
+ t.Fatal(err)
+ }
+
+ var requestCookie string
+ client := &http.Client{Transport: automationRoundTripperFunc(func(req *http.Request) (*http.Response, error) {
+ requestCookie = req.Header.Get("Cookie")
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Set-Cookie": []string{
+ "_m_h5_tk=snapshot_new_2; Domain=.goofish.com; Path=/; Secure",
+ "consign_scope=new; Path=/h5; Secure; HttpOnly",
+ }},
+ Body: io.NopCloser(strings.NewReader(`{"ret":`)),
+ Request: req,
+ }, nil
+ })}
+ lockReleasedBeforeRuntimeUpdate := false
+ sender := &testSender{onCookieUpdate: func(string) {
+ acquired := make(chan struct{})
+ go func() {
+ unlock := store.LockAccountCredentials("cid")
+ unlock()
+ close(acquired)
+ }()
+ select {
+ case <-acquired:
+ lockReleasedBeforeRuntimeUpdate = true
+ case <-time.After(500 * time.Millisecond):
+ }
+ }}
+ center := New(store, testSenderProvider{sender: sender}, nil)
+ center.SetMTop(&mtop.ClientImpl{HTTPClient: client, ConsignURL: mtop.ConsignAPI})
+ err := center.confirmShipment(ctx, Task{
+ AccountID: "cid", OrderID: "session-parse-error", ForceConfirmShipment: true,
+ })
+ var uncertain *uncertainActionError
+ if !errors.As(err, &uncertain) {
+ t.Fatalf("远程响应解析失败应进入人工核对: %v", err)
+ }
+ for _, want := range []string{"unb=123", "_m_h5_tk=snapshot_old_1", "api_only=api"} {
+ if !strings.Contains(requestCookie, want) {
+ t.Fatalf("发货请求 Cookie %q 未使用加锁后重读的权威 Jar,缺少 %q", requestCookie, want)
+ }
+ }
+ for _, unwanted := range []string{"flat_leak=", "document_only="} {
+ if strings.Contains(requestCookie, unwanted) {
+ t.Fatalf("发货请求 Cookie %q 泄漏了错误作用域 %q", requestCookie, unwanted)
+ }
+ }
+
+ detail, getErr := store.Cookies.GetDetails(ctx, "cid")
+ if getErr != nil {
+ t.Fatal(getErr)
+ }
+ if !strings.Contains(detail.Value, "_m_h5_tk=snapshot_new_2") || strings.Contains(detail.Value, "flat_leak=") {
+ t.Fatalf("正文解析失败后未优先持久化响应 Cookie Jar: %q", detail.Value)
+ }
+ if !strings.Contains(detail.MetadataJSON, `"preserved":"yes"`) {
+ t.Fatalf("持久化 Jar 时丢失原 metadata: %s", detail.MetadataJSON)
+ }
+ gotSnapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
+ if !ok {
+ t.Fatalf("响应后权威 snapshot 丢失: %s", detail.MetadataJSON)
+ }
+ values := make(map[string]string, len(gotSnapshot))
+ for _, cookie := range gotSnapshot {
+ values[cookie.Name+"|"+cookie.Domain+"|"+cookie.Path] = cookie.Value
+ }
+ if values["_m_h5_tk|.goofish.com|/"] != "snapshot_new_2" ||
+ values["consign_scope|h5api.m.goofish.com|/h5"] != "new" ||
+ values["document_only|www.goofish.com|/im"] != "doc" {
+ t.Fatalf("响应后 snapshot 作用域不完整: %+v", gotSnapshot)
+ }
+ if len(sender.cookieUpdates) != 1 || !strings.Contains(sender.cookieUpdates[0], "_m_h5_tk=snapshot_new_2") {
+ t.Fatalf("运行实例未同步已持久化的 Cookie: %+v", sender.cookieUpdates)
+ }
+ if !lockReleasedBeforeRuntimeUpdate {
+ t.Fatal("运行实例 Cookie 必须在账号凭证锁外更新")
+ }
+}
+
+func TestConfirmShipmentPropagatesAuthoritativeEmptySession(t *testing.T) {
+ store, cleanup := newAutomationTestStore(t)
+ defer cleanup()
+ ctx := context.Background()
+ initialValue := "unb=123; _m_h5_tk=old_1"
+ metadata := cookierefresh.MetadataWithSnapshot(`{"preserved":true}`, []cookierefresh.BrowserCookie{
+ {Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "_m_h5_tk", Value: "old_1", Domain: ".goofish.com", Path: "/", Secure: true},
+ })
+ if err := store.Cookies.UpdateRenewalCookie(ctx, "cid", initialValue, metadata, 1); err != nil {
+ t.Fatal(err)
+ }
+ client := &http.Client{Transport: automationRoundTripperFunc(func(req *http.Request) (*http.Response, error) {
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Set-Cookie": []string{
+ "unb=; Max-Age=-1; Domain=.goofish.com; Path=/; Secure",
+ "_m_h5_tk=; Max-Age=-1; Domain=.goofish.com; Path=/; Secure",
+ }},
+ Body: io.NopCloser(strings.NewReader(`{"ret":`)),
+ Request: req,
+ }, nil
+ })}
+ sender := &testSender{}
+ center := New(store, testSenderProvider{sender: sender}, nil)
+ center.SetMTop(&mtop.ClientImpl{HTTPClient: client, ConsignURL: mtop.ConsignAPI})
+ err := center.confirmShipment(ctx, Task{
+ AccountID: "cid", OrderID: "authoritative-empty-session", ForceConfirmShipment: true,
+ })
+ var uncertain *uncertainActionError
+ if !errors.As(err, &uncertain) {
+ t.Fatalf("删除凭证后的解析失败应进入人工核对: %v", err)
+ }
+ detail, getErr := store.Cookies.GetDetails(ctx, "cid")
+ if getErr != nil {
+ t.Fatal(getErr)
+ }
+ if detail.Value != "" {
+ t.Fatalf("权威空 Jar 未持久化: %q", detail.Value)
+ }
+ snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
+ if !ok || snapshot == nil || len(snapshot) != 0 {
+ t.Fatalf("权威空 snapshot 语义丢失: ok=%v snapshot=%#v metadata=%s", ok, snapshot, detail.MetadataJSON)
+ }
+ if len(sender.cookieUpdates) != 1 || sender.cookieUpdates[0] != "" {
+ t.Fatalf("权威空 Jar 未在锁外通知运行实例: %#v", sender.cookieUpdates)
+ }
+}
+
func TestManualFullDeliveryIsImmediateIdempotentAndForcesConfirmation(t *testing.T) {
store, cleanup := newAutomationTestStore(t)
defer cleanup()
diff --git a/internal/browser/cookierenew.go b/internal/browser/cookierenew.go
index a339d3c..9a4b2d6 100644
--- a/internal/browser/cookierenew.go
+++ b/internal/browser/cookierenew.go
@@ -7,6 +7,7 @@ import (
"os"
"path/filepath"
"strings"
+ "sync/atomic"
"time"
"github.com/playwright-community/playwright-go"
@@ -18,6 +19,9 @@ const (
quickRenewPageLoadWait = 3 * time.Second
quickRenewAfterClick = 5 * time.Second
quickRenewTimeoutMS = 30000
+ officialAutoLoginWait = 10 * time.Second
+ officialFetchDrainWait = 30 * time.Second
+ officialReloadWait = 5 * time.Second
)
var (
@@ -102,68 +106,22 @@ func passwordPersistentContextOptions(headless bool) playwright.BrowserTypeLaunc
// BrowserQuickRenew 使用持久化浏览器上下文执行“快速进入”Cookie 续期。
func (m *Manager) BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error) {
- if cookieStr == "" {
- return "", fmt.Errorf("Cookie为空,无法浏览器续期")
- }
-
- bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, nil, quickRenewHeadless(headless))
- if err != nil {
- return "", err
- }
- defer release()
-
- page, err := bctx.NewPage()
- if err != nil {
- return "", fmt.Errorf("新建 page 失败: %w", err)
- }
- defer func() { _ = page.Close() }()
-
- if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
- WaitUntil: playwright.WaitUntilStateDomcontentloaded,
- Timeout: playwright.Float(quickRenewTimeoutMS),
- }); err != nil {
- m.logger.Warn("浏览器续期访问首页异常", "cookieID", cookieID, "err", err)
- }
- time.Sleep(quickRenewPageLoadWait)
-
- hasQuickEnter := false
- if err := verifyHomeLoginState(page); err != nil {
- if errors.Is(err, ErrSecurityVerification) {
- return "", err
- }
- hasQuickEnter = clickQuickEnter(page)
- if !hasQuickEnter {
- return "", err
- }
- time.Sleep(quickRenewAfterClick)
- if err := verifyHomeLoginState(page); err != nil {
- return "", err
- }
- }
-
- all, err := bctx.Cookies()
- if err != nil {
- return "", fmt.Errorf("提取 cookie 失败: %w", err)
- }
- newSnapshot := cookieSnapshotFromPlaywright(all)
- if len(newSnapshot) == 0 {
- return "", fmt.Errorf("点击[快速进入]后未获取到浏览器Cookie")
- }
- cookieFromBrowser := cookierefresh.CookieStringFromSnapshot(newSnapshot)
- merged := cookierefresh.MergeOriginalFields(cookieStr, cookieFromBrowser)
- m.logger.Info("浏览器续期成功", "cookieID", cookieID, "has_quick_enter", hasQuickEnter, "cookie_count", len(newSnapshot))
- return merged, nil
+ newCookies, _, err := m.BrowserQuickRenewSnapshot(ctx, cookieID, cookieStr, nil, headless)
+ return newCookies, err
}
-// CookiesRefreshSnapshot executes the optional browser-backed renewal in the
-// account's persistent profile. One ordinary page load is enough to run the
-// site's own auto-login plugin; repeated reloads create an avoidable risk
-// signal and are deliberately not used.
-func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error) {
- if cookieStr == "" && len(snapshot) == 0 {
- return "", nil, fmt.Errorf("Cookie为空,且无完整Cookie快照,无法执行续期")
+// BrowserQuickRenewSnapshot is the full-fidelity variant of BrowserQuickRenew.
+// Callers that persist cookie metadata should use it directly: Chromium's final
+// jar is authoritative for both deletions and attributes such as expiry/path.
+func (m *Manager) BrowserQuickRenewSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error) {
+ if cookieStr == "" && snapshot == nil {
+ return "", nil, fmt.Errorf("Cookie为空,且无完整Cookie快照,无法浏览器续期")
}
- bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, snapshot, cookiesRefreshHeadless(headless))
+ // 持久化的扁平值始终以消息页为 canonical scope;这里也必须按 /im
+ // 解释,避免漏掉或错误映射 Path=/im 的连接凭证。
+ effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL)
+
+ bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, quickRenewHeadless(headless))
if err != nil {
return "", nil, err
}
@@ -177,31 +135,212 @@ func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieSt
if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
- Timeout: playwright.Float(60000),
+ Timeout: playwright.Float(quickRenewTimeoutMS),
}); err != nil {
- m.logger.Warn("COOKIES续期访问首页异常", "cookieID", cookieID, "err", err)
+ m.logger.Warn("浏览器续期访问首页异常", "cookieID", cookieID, "err", err)
}
time.Sleep(quickRenewPageLoadWait)
+
+ hasQuickEnter := false
+ var renewErr error
if err := verifyHomeLoginState(page); err != nil {
- return "", nil, err
+ if errors.Is(err, ErrSecurityVerification) {
+ renewErr = err
+ } else {
+ hasQuickEnter = clickQuickEnter(page)
+ if !hasQuickEnter {
+ renewErr = err
+ } else {
+ time.Sleep(quickRenewAfterClick)
+ renewErr = verifyHomeLoginState(page)
+ }
+ }
}
+ newCookies, newSnapshot, err := readAuthoritativeCookieJar(bctx, goofishIMURL)
+ if err != nil {
+ return "", nil, errors.Join(renewErr, err)
+ }
+ if len(newSnapshot) == 0 {
+ renewErr = errors.Join(renewErr, fmt.Errorf("点击[快速进入]后浏览器 Cookie Jar 为空"))
+ }
+ if renewErr != nil {
+ return newCookies, newSnapshot, renewErr
+ }
+ m.logger.Info("浏览器续期成功", "cookieID", cookieID, "has_quick_enter", hasQuickEnter, "cookie_count", len(newSnapshot))
+ return newCookies, newSnapshot, nil
+}
+
+// CookiesRefreshSnapshot executes the optional browser-backed renewal in the
+// account's persistent profile. One ordinary page load is enough to run the
+// site's own auto-login plugin; repeated reloads create an avoidable risk
+// signal and are deliberately not used.
+func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, bool, error) {
+ if cookieStr == "" && snapshot == nil {
+ return "", nil, false, fmt.Errorf("Cookie为空,且无完整Cookie快照,无法执行续期")
+ }
+ effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL)
+ bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, cookiesRefreshHeadless(headless))
+ if err != nil {
+ return "", nil, false, err
+ }
+ defer release()
+
+ page, err := bctx.NewPage()
+ if err != nil {
+ return "", nil, false, fmt.Errorf("新建 page 失败: %w", err)
+ }
+ defer func() { _ = page.Close() }()
+
+ reloaded, renewErr := navigateOfficialRenewPage(ctx, page)
+ if renewErr == nil {
+ renewErr = verifyHomeLoginState(page)
+ }
+
+ newCookies, newSnapshot, err := readAuthoritativeCookieJar(bctx, goofishIMURL)
+ if err != nil {
+ return "", nil, reloaded, errors.Join(renewErr, err)
+ }
+ if len(newSnapshot) == 0 {
+ renewErr = errors.Join(renewErr, fmt.Errorf("消息页执行后浏览器 Cookie Jar 为空"))
+ }
+ if renewErr != nil {
+ return newCookies, newSnapshot, reloaded, renewErr
+ }
+ m.logger.Info("COOKIES续期成功", "cookieID", cookieID, "cookie_count", len(newSnapshot), "official_reload", reloaded)
+ return newCookies, newSnapshot, reloaded, nil
+}
+
+func navigateOfficialRenewPage(ctx context.Context, page playwright.Page) (bool, error) {
+ silentStarted := make(chan struct{}, 1)
+ silentSettled := make(chan bool, 1)
+ reloadCommitted := make(chan struct{}, 1)
+ var navigationArmed atomic.Bool
+ page.OnRequest(func(request playwright.Request) {
+ if isSilentHasLoginURL(request.URL()) {
+ select {
+ case silentStarted <- struct{}{}:
+ default:
+ }
+ }
+ })
+ page.OnFrameNavigated(func(frame playwright.Frame) {
+ if navigationArmed.Load() && frame.ParentFrame() == nil && strings.HasPrefix(frame.URL(), goofishIMURL) {
+ select {
+ case reloadCommitted <- struct{}{}:
+ default:
+ }
+ }
+ })
+ page.OnRequestFinished(func(request playwright.Request) {
+ if isSilentHasLoginURL(request.URL()) {
+ select {
+ case silentSettled <- true:
+ default:
+ }
+ }
+ })
+ page.OnRequestFailed(func(request playwright.Request) {
+ if isSilentHasLoginURL(request.URL()) {
+ select {
+ case silentSettled <- false:
+ default:
+ }
+ }
+ })
+
+ if _, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
+ WaitUntil: playwright.WaitUntilStateDomcontentloaded,
+ Timeout: playwright.Float(60000),
+ }); err != nil {
+ return false, fmt.Errorf("COOKIES续期访问消息页: %w", err)
+ }
+ navigationArmed.Store(true)
+ // The plugin starts after the SPA hydrates, then waits 2s before issuing
+ // silentHasLogin. Observe the actual request instead of assuming hydration
+ // completed at DOMContentLoaded; navigation Set-Cookie may also change the
+ // sdkSilent/long-login branch.
+ observeTimer := time.NewTimer(officialAutoLoginWait)
+ requestStarted := false
+ select {
+ case <-ctx.Done():
+ observeTimer.Stop()
+ return false, ctx.Err()
+ case <-silentStarted:
+ requestStarted = true
+ observeTimer.Stop()
+ case <-observeTimer.C:
+ }
+ if requestStarted {
+ // The plugin's 2s Promise timeout does not abort fetch. Keep the page
+ // alive until Chromium finishes the response body (and applies Set-Cookie), while
+ // leaving reload/no-reload entirely to the official JavaScript.
+ drainTimer := time.NewTimer(officialFetchDrainWait)
+ requestFinished := false
+ select {
+ case requestFinished = <-silentSettled:
+ drainTimer.Stop()
+ case <-ctx.Done():
+ drainTimer.Stop()
+ return false, ctx.Err()
+ case <-drainTimer.C:
+ }
+ if requestFinished {
+ reloadTimer := time.NewTimer(officialReloadWait)
+ select {
+ case <-reloadCommitted:
+ reloadTimer.Stop()
+ if err := page.WaitForLoadState(playwright.PageWaitForLoadStateOptions{
+ State: playwright.LoadStateDomcontentloaded, Timeout: playwright.Float(10000),
+ }); err != nil {
+ return true, fmt.Errorf("等待官网续期 reload 完成: %w", err)
+ }
+ return true, nil
+ case <-ctx.Done():
+ reloadTimer.Stop()
+ return false, ctx.Err()
+ case <-reloadTimer.C:
+ }
+ }
+ }
+ // Absence of a reload is the official outcome for fatigue, timeout or a
+ // non-100 business result.
+ return false, nil
+}
+
+func readAuthoritativeCookieJar(bctx playwright.BrowserContext, rawURL string) (string, []cookierefresh.BrowserCookie, error) {
all, err := bctx.Cookies()
if err != nil {
- return "", nil, fmt.Errorf("提取 cookie 失败: %w", err)
+ return "", nil, fmt.Errorf("提取浏览器 Cookie Jar: %w", err)
}
- newSnapshot := cookieSnapshotFromPlaywright(all)
- if len(newSnapshot) == 0 {
- return "", nil, fmt.Errorf("页面刷新完成,但未获取到浏览器Cookie")
+ snapshot := cookieSnapshotFromPlaywright(all)
+ if snapshot == nil {
+ snapshot = []cookierefresh.BrowserCookie{}
}
- newCookies := cookierefresh.CookieStringFromSnapshot(newSnapshot)
- m.logger.Info("COOKIES续期成功", "cookieID", cookieID, "cookie_count", len(newSnapshot))
- return newCookies, newSnapshot, nil
+ return currentCookieHeader(snapshot, rawURL), snapshot, nil
+}
+
+func isSilentHasLoginURL(rawURL string) bool {
+ return strings.Contains(rawURL, "/newlogin/silentHasLogin.do")
+}
+
+func reconcileSnapshotWithCurrentCookie(snapshot []cookierefresh.BrowserCookie, cookieStr, rawURL string) []cookierefresh.BrowserCookie {
+ if snapshot == nil {
+ return nil
+ }
+ if len(snapshot) == 0 {
+ return []cookierefresh.BrowserCookie{}
+ }
+ if strings.TrimSpace(cookieStr) == "" {
+ return cookierefresh.NormalizeSnapshot(snapshot)
+ }
+ return credentialCookieSnapshotForURL(snapshot, parseCookieStr(cookieStr), rawURL)
}
// CookieRenewSnapshot 兼容旧调用,等价于定时 COOKIES 快照续期。
func (m *Manager) CookieRenewSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error) {
- return m.CookiesRefreshSnapshot(ctx, cookieID, cookieStr, snapshot, headless)
+ cookies, refreshed, _, err := m.CookiesRefreshSnapshot(ctx, cookieID, cookieStr, snapshot, headless)
+ return cookies, refreshed, err
}
func clickQuickEnter(page playwright.Page) bool {
@@ -237,10 +376,6 @@ var quickEnterSelectors = []string{
`.fn-button:has-text("快速进入")`,
}
-func checkAlreadyLoggedIn(page playwright.Page) bool {
- return verifyHomeLoginState(page) == nil
-}
-
func verifyHomeLoginState(page playwright.Page) error {
if pageHasSecurityVerification(page) {
return ErrSecurityVerification
@@ -368,7 +503,7 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
if err := bctx.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil {
m.logger.Warn("注入 stealth 脚本失败", "err", err)
}
- if len(snapshot) > 0 {
+ if snapshot != nil {
if err := bctx.ClearCookies(); err != nil {
_ = bctx.Close()
releaseSlot()
diff --git a/internal/browser/cookierenew_test.go b/internal/browser/cookierenew_test.go
new file mode 100644
index 0000000..727a1d3
--- /dev/null
+++ b/internal/browser/cookierenew_test.go
@@ -0,0 +1,89 @@
+package browser
+
+import (
+ "testing"
+
+ "xianyu-go/internal/xianyu/cookierefresh"
+)
+
+func TestCredentialCookieSnapshotUsesCurrentFlatCookieAsAuthority(t *testing.T) {
+ existing := []cookierefresh.BrowserCookie{
+ {Name: "session", Value: "stale", Domain: ".goofish.com", Path: "/", Expires: 123, HTTPOnly: true, Secure: true, SameSite: "Lax"},
+ {Name: "removed", Value: "old", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "passport", Value: "keep", Domain: ".taobao.com", Path: "/", Secure: true},
+ }
+ got := credentialCookieSnapshot(existing, map[string]string{
+ "session": "fresh",
+ "new": "value",
+ })
+ if len(got) != 3 {
+ t.Fatalf("snapshot len=%d, want 3: %+v", len(got), got)
+ }
+ byName := make(map[string]cookierefresh.BrowserCookie, len(got))
+ for _, cookie := range got {
+ byName[cookie.Name] = cookie
+ }
+ session := byName["session"]
+ if session.Value != "fresh" || session.Expires != 123 || !session.HTTPOnly || session.SameSite != "Lax" {
+ t.Fatalf("existing attributes or fresh value were lost: %+v", session)
+ }
+ if _, exists := byName["removed"]; exists {
+ t.Fatalf("cookie absent from current flat value was resurrected: %+v", got)
+ }
+ if passport := byName["passport"]; passport.Value != "keep" || passport.Domain != ".taobao.com" {
+ t.Fatalf("out-of-scope cookie was lost: %+v", passport)
+ }
+ added := byName["new"]
+ if added.Value != "value" || added.Domain != goofishDot || added.Path != "/" || !added.Secure {
+ t.Fatalf("new cookie defaults mismatch: %+v", added)
+ }
+}
+
+func TestCredentialCookieSnapshotPreservesAmbiguousSameNameScopes(t *testing.T) {
+ existing := []cookierefresh.BrowserCookie{
+ {Name: "token", Value: "old-root", Domain: ".goofish.com", Path: "/"},
+ {Name: "token", Value: "old-im", Domain: "www.goofish.com", Path: "/im", HTTPOnly: true},
+ }
+ got := credentialCookieSnapshot(existing, map[string]string{"token": "fresh"})
+ if len(got) != 2 {
+ t.Fatalf("same-name scoped cookies collapsed: %+v", got)
+ }
+ values := map[string]string{}
+ for _, cookie := range got {
+ values[cookie.Path] = cookie.Value
+ }
+ if values["/"] != "old-root" || values["/im"] != "old-im" {
+ t.Fatalf("ambiguous flat value corrupted scoped cookies: %+v", got)
+ }
+}
+
+func TestReconcileSnapshotWithCurrentCookie(t *testing.T) {
+ snapshot := []cookierefresh.BrowserCookie{{Name: "session", Value: "old", Domain: ".goofish.com", Path: "/", Expires: 456}}
+
+ got := reconcileSnapshotWithCurrentCookie(snapshot, "session=new", goofishIMURL)
+ if len(got) != 1 || got[0].Value != "new" || got[0].Expires != 456 {
+ t.Fatalf("flat cookie did not update snapshot without losing attributes: %+v", got)
+ }
+
+ got = reconcileSnapshotWithCurrentCookie(snapshot, "", goofishIMURL)
+ if len(got) != 1 || got[0].Value != "old" {
+ t.Fatalf("snapshot-only renewal input was discarded: %+v", got)
+ }
+
+ got = reconcileSnapshotWithCurrentCookie([]cookierefresh.BrowserCookie{}, "session=stale", goofishIMURL)
+ if got == nil || len(got) != 0 {
+ t.Fatalf("authoritative empty snapshot must not fall back to flat cookies: %#v", got)
+ }
+ if got := reconcileSnapshotWithCurrentCookie(nil, "session=legacy", goofishIMURL); got != nil {
+ t.Fatalf("missing snapshot should preserve the legacy flat-cookie fallback: %#v", got)
+ }
+}
+
+func TestSilentHasLoginURLMatcher(t *testing.T) {
+ if !isSilentHasLoginURL("https://passport.goofish.com/newlogin/silentHasLogin.do?appName=xianyu") {
+ t.Fatal("official silentHasLogin request was not recognized")
+ }
+ if isSilentHasLoginURL("https://passport.goofish.com/newlogin/hasLogin.do") {
+ t.Fatal("ordinary hasLogin request must not be treated as silentHasLogin")
+ }
+}
diff --git a/internal/browser/cookies.go b/internal/browser/cookies.go
index a7b446a..a8016b8 100644
--- a/internal/browser/cookies.go
+++ b/internal/browser/cookies.go
@@ -81,6 +81,9 @@ func snapshotToOptionalCookies(snapshot []cookierefresh.BrowserCookie) []playwri
if c.Expires > 0 {
oc.Expires = playwright.Float(c.Expires)
}
+ if c.PartitionKey != "" {
+ oc.PartitionKey = playwright.String(c.PartitionKey)
+ }
switch c.SameSite {
case "Strict":
oc.SameSite = playwright.SameSiteAttributeStrict
@@ -109,6 +112,9 @@ func cookieSnapshotFromPlaywright(cs []playwright.Cookie) []cookierefresh.Browse
if c.SameSite != nil {
bc.SameSite = string(*c.SameSite)
}
+ if c.PartitionKey != nil {
+ bc.PartitionKey = *c.PartitionKey
+ }
out = append(out, bc)
}
return cookierefresh.NormalizeSnapshot(out)
diff --git a/internal/browser/credential_cookies.go b/internal/browser/credential_cookies.go
new file mode 100644
index 0000000..6635bf5
--- /dev/null
+++ b/internal/browser/credential_cookies.go
@@ -0,0 +1,104 @@
+package browser
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/playwright-community/playwright-go"
+
+ "xianyu-go/internal/xianyu/cookierefresh"
+)
+
+// TokenCaptchaCookieSnapshot 在滑块引擎退出并释放持久化 Profile 后,重新打开
+// 同一 Profile 读取最终 Cookie Jar。它不访问任何业务页面,只用于把滑块验证
+// 已经产生的精确 Domain/Path/HttpOnly/Expires 属性交回 Go 凭证层。
+func (m *Manager) TokenCaptchaCookieSnapshot(ctx context.Context, cookieID string, headless bool) (string, []cookierefresh.BrowserCookie, error) {
+ bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, "", nil, quickRenewHeadless(headless), true)
+ if err != nil {
+ return "", nil, err
+ }
+ defer release()
+ return readAuthoritativeCookieJar(bctx, goofishIMURL)
+}
+
+// syncCredentialCookies 为 token 滑块上下文同步 Cookie。普通登录、
+// 续期、MTOP、Token 和 WebSocket 生产流程不得调用 Chromium。
+func syncCredentialCookies(bctx playwright.BrowserContext, cookieStr string, snapshots ...[]cookierefresh.BrowserCookie) error {
+ if len(snapshots) > 0 && snapshots[0] != nil {
+ preserved := cookierefresh.NormalizeSnapshot(snapshots[0])
+ if err := bctx.ClearCookies(); err != nil {
+ return err
+ }
+ if len(preserved) == 0 {
+ return nil
+ }
+ return bctx.AddCookies(snapshotToOptionalCookies(preserved))
+ }
+ incoming := parseCookieStr(cookieStr)
+ if len(incoming) == 0 {
+ return fmt.Errorf("Cookie为空或格式错误")
+ }
+ existing, err := bctx.Cookies()
+ if err != nil {
+ return err
+ }
+ preserved := credentialCookieSnapshotForURL(cookieSnapshotFromPlaywright(existing), incoming, goofishIMURL)
+ if err := bctx.ClearCookies(); err != nil {
+ return err
+ }
+ return bctx.AddCookies(snapshotToOptionalCookies(preserved))
+}
+
+func credentialCookieSnapshot(existing []cookierefresh.BrowserCookie, incoming map[string]string) []cookierefresh.BrowserCookie {
+ return credentialCookieSnapshotForURL(existing, incoming, goofishIMURL)
+}
+
+func credentialCookieSnapshotForURL(existing []cookierefresh.BrowserCookie, incoming map[string]string, rawURL string) []cookierefresh.BrowserCookie {
+ preserved := make([]cookierefresh.BrowserCookie, 0, len(existing)+len(incoming))
+ matched := make(map[string]bool, len(incoming))
+ counts := make(map[string]int, len(existing))
+ for _, cookie := range cookierefresh.NormalizeSnapshot(existing) {
+ counts[cookie.Name]++
+ }
+ for _, cookie := range existing {
+ if !cookieScopeMatches(cookie, rawURL) {
+ if value, ok := incoming[cookie.Name]; ok {
+ if counts[cookie.Name] == 1 && cookie.PartitionKey == "" {
+ cookie.Value = value
+ }
+ matched[cookie.Name] = true
+ }
+ preserved = append(preserved, cookie)
+ continue
+ }
+ value, ok := incoming[cookie.Name]
+ if !ok {
+ continue
+ }
+ if counts[cookie.Name] == 1 {
+ cookie.Value = value
+ }
+ preserved = append(preserved, cookie)
+ matched[cookie.Name] = true
+ }
+ for name, value := range incoming {
+ if matched[name] {
+ continue
+ }
+ preserved = append(preserved, cookierefresh.BrowserCookie{
+ Name: name, Value: value, Domain: goofishDot, Path: "/", Secure: true,
+ })
+ }
+ return cookierefresh.NormalizeSnapshot(preserved)
+}
+
+func cookieScopeMatches(cookie cookierefresh.BrowserCookie, rawURL string) bool {
+ header, _ := cookierefresh.ScopedCookieHeaderForRequest([]cookierefresh.BrowserCookie{cookie}, rawURL, "https://goofish.com", time.Unix(0, 0))
+ return header != ""
+}
+
+func currentCookieHeader(snapshot []cookierefresh.BrowserCookie, rawURL string) string {
+ header, _ := cookierefresh.ScopedCookieHeaderForRequest(snapshot, rawURL, "https://goofish.com", time.Now())
+ return header
+}
diff --git a/internal/browser/lifecycle.go b/internal/browser/lifecycle.go
index 64cf890..61779ad 100644
--- a/internal/browser/lifecycle.go
+++ b/internal/browser/lifecycle.go
@@ -87,10 +87,12 @@ type Manager struct {
}
type poolEntry struct {
- cookieID string
- browser playwright.Browser
- context playwright.BrowserContext
- lastUsed time.Time
+ cookieID string
+ browser playwright.Browser
+ context playwright.BrowserContext
+ lastUsed time.Time
+ active int
+ initialLeaseAvailable bool
}
// NewManager 构造。logger 为 nil 用默认。
@@ -257,6 +259,7 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
page, err := entry.context.NewPage()
if err != nil {
// context 损坏,丢弃重建一次。
+ m.releaseEntry(cookieID, entry)
m.evict(cookieID)
entry, err = m.acquireEntry(cookieID, cookieStr, headless)
if err != nil {
@@ -264,12 +267,14 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
}
page, err = entry.context.NewPage()
if err != nil {
+ m.releaseEntry(cookieID, entry)
+ m.evict(cookieID)
return nil, nil, fmt.Errorf("新建 page 失败: %w", err)
}
}
release := func() {
_ = page.Close()
- m.touch(cookieID)
+ m.releaseEntry(cookieID, entry)
}
return page, release, nil
}
@@ -277,7 +282,7 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) {
m.mu.Lock()
if e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() {
- e.lastUsed = time.Now()
+ m.claimEntryLocked(e)
m.mu.Unlock()
return e, nil
}
@@ -286,7 +291,6 @@ func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*pool
created, err, _ := m.creates.Do(cookieID, func() (any, error) {
m.mu.Lock()
if e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() {
- e.lastUsed = time.Now()
m.mu.Unlock()
return e, nil
}
@@ -302,9 +306,38 @@ func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*pool
if !ok || entry == nil {
return nil, fmt.Errorf("浏览器池创建返回异常")
}
+ m.mu.Lock()
+ if current := m.pool[cookieID]; current == entry {
+ m.claimEntryLocked(entry)
+ m.mu.Unlock()
+ } else {
+ m.mu.Unlock()
+ return nil, fmt.Errorf("浏览器池条目在获取期间已失效")
+ }
return entry, nil
}
+func (m *Manager) claimEntryLocked(entry *poolEntry) {
+ entry.lastUsed = time.Now()
+ if entry.initialLeaseAvailable {
+ entry.initialLeaseAvailable = false
+ return
+ }
+ entry.active++
+}
+
+func (m *Manager) releaseEntry(cookieID string, entry *poolEntry) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if current := m.pool[cookieID]; current != entry {
+ return
+ }
+ if entry.active > 0 {
+ entry.active--
+ }
+ entry.lastUsed = time.Now()
+}
+
func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) {
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
Headless: playwright.Bool(headless),
@@ -334,10 +367,12 @@ func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolE
}
}
entry := &poolEntry{
- cookieID: cookieID,
- browser: browser,
- context: context,
- lastUsed: time.Now(),
+ cookieID: cookieID,
+ browser: browser,
+ context: context,
+ lastUsed: time.Now(),
+ active: 1,
+ initialLeaseAvailable: true,
}
m.mu.Lock()
m.pool[cookieID] = entry
@@ -356,6 +391,10 @@ func (m *Manager) touch(cookieID string) {
func (m *Manager) evict(cookieID string) {
m.mu.Lock()
e, ok := m.pool[cookieID]
+ if ok && e.active > 0 {
+ m.mu.Unlock()
+ return
+ }
delete(m.pool, cookieID)
m.mu.Unlock()
if ok {
@@ -372,12 +411,17 @@ func (m *Manager) evictIfNeeded() {
var oldest *poolEntry
var oldestID string
for id, e := range m.pool {
+ if e.active > 0 {
+ continue
+ }
if oldest == nil || e.lastUsed.Before(oldest.lastUsed) {
oldest = e
oldestID = id
}
}
- delete(m.pool, oldestID)
+ if oldest != nil {
+ delete(m.pool, oldestID)
+ }
m.mu.Unlock()
if oldest != nil {
closeEntry(oldest, m.logger)
@@ -390,7 +434,7 @@ func (m *Manager) CleanupIdle() {
m.mu.Lock()
var toClose []*poolEntry
for id, e := range m.pool {
- if now.Sub(e.lastUsed) > m.idleTTL {
+ if e.active == 0 && now.Sub(e.lastUsed) > m.idleTTL {
toClose = append(toClose, e)
delete(m.pool, id)
}
diff --git a/internal/browser/lifecycle_test.go b/internal/browser/lifecycle_test.go
index 18d93ae..64a2353 100644
--- a/internal/browser/lifecycle_test.go
+++ b/internal/browser/lifecycle_test.go
@@ -91,6 +91,44 @@ func TestEvictIfNeededNoopWhenUnderLimit(t *testing.T) {
}
}
+func TestEvictIfNeededSkipsActiveEntries(t *testing.T) {
+ m := newTestManager(2)
+ m.pool["active-old"] = &poolEntry{cookieID: "active-old", lastUsed: time.Now().Add(-2 * time.Hour), active: 1}
+ m.pool["idle-new"] = &poolEntry{cookieID: "idle-new", lastUsed: time.Now()}
+ m.evictIfNeeded()
+ if _, ok := m.pool["active-old"]; !ok {
+ t.Fatal("正在执行 token 请求的条目不得被淘汰")
+ }
+ if _, ok := m.pool["idle-new"]; ok {
+ t.Fatal("池满时应优先淘汰空闲条目")
+ }
+}
+
+func TestEvictIfNeededAllowsTemporaryOverflowWhenAllActive(t *testing.T) {
+ m := newTestManager(2)
+ m.pool["active-1"] = &poolEntry{cookieID: "active-1", lastUsed: time.Now().Add(-2 * time.Hour), active: 1}
+ m.pool["active-2"] = &poolEntry{cookieID: "active-2", lastUsed: time.Now().Add(-time.Hour), active: 1}
+ m.evictIfNeeded()
+ if len(m.pool) != 2 {
+ t.Fatalf("所有条目活跃时不得强制淘汰,pool=%d", len(m.pool))
+ }
+}
+
+func TestCleanupIdleSkipsActiveEntries(t *testing.T) {
+ m := newTestManager(3)
+ m.idleTTL = time.Minute
+ old := time.Now().Add(-time.Hour)
+ m.pool["active"] = &poolEntry{cookieID: "active", lastUsed: old, active: 1}
+ m.pool["idle"] = &poolEntry{cookieID: "idle", lastUsed: old}
+ m.CleanupIdle()
+ if _, ok := m.pool["active"]; !ok {
+ t.Fatal("CleanupIdle 不得关闭仍有租约的条目")
+ }
+ if _, ok := m.pool["idle"]; ok {
+ t.Fatal("CleanupIdle 应清理过期空闲条目")
+ }
+}
+
// TestMarshalCookies 导出包装器等价 cookieMarshal。
func TestMarshalCookies(t *testing.T) {
got := MarshalCookies(map[string]string{"unb": "1", "cna": "xx"})
diff --git a/internal/browser/orders.go b/internal/browser/orders.go
index 68afce6..8f265be 100644
--- a/internal/browser/orders.go
+++ b/internal/browser/orders.go
@@ -11,6 +11,7 @@ import (
"github.com/playwright-community/playwright-go"
+ "xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
)
@@ -18,13 +19,15 @@ const mtopOrderDetailURL = "mtop.idle.web.trade.order.detail"
// OrderDetail 订单详情(对齐 engine.OrderDetail)。
type OrderDetail struct {
- OrderID string `json:"order_id"`
- Quantity string `json:"quantity"`
- SpecName string `json:"spec_name"`
- SpecValue string `json:"spec_value"`
- OrderStatus string `json:"order_status"`
- Amount string `json:"amount"`
- UpdatedCookies string `json:"-"`
+ OrderID string `json:"order_id"`
+ Quantity string `json:"quantity"`
+ SpecName string `json:"spec_name"`
+ SpecValue string `json:"spec_value"`
+ OrderStatus string `json:"order_status"`
+ Amount string `json:"amount"`
+ UpdatedCookies string `json:"-"`
+ CookieSnapshot []cookierefresh.BrowserCookie `json:"-"`
+ CookieSnapshotComplete bool `json:"-"`
}
// orderStatusMap 移植自 order_fetcher_optimized._parse_api_response。纯映射,可单测。
@@ -48,6 +51,12 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
} else if directErr != nil {
m.logger.Warn("MTop 订单详情获取失败,回退浏览器", "order_id", orderID, "err", directErr)
}
+ // A shared Chromium context owns one mutable Cookie Jar. Serialize browser
+ // fallback refreshes for the account so concurrent batch rows cannot clear
+ // and re-inject different snapshots underneath each other.
+ browserCredentialLock := m.accountRenewLock("order_credential_" + cookieID)
+ browserCredentialLock.Lock()
+ defer browserCredentialLock.Unlock()
if err := m.init(); err != nil {
return nil, err
}
@@ -56,6 +65,11 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
return nil, err
}
defer release()
+ if session := mtop.CookieSessionFromContext(ctx); session != nil {
+ if err := syncCredentialCookies(page.Context(), cookieValue, session.Snapshot()); err != nil {
+ return nil, fmt.Errorf("订单详情同步完整 Cookie Jar: %w", err)
+ }
+ }
var mu sync.Mutex
var apiBody map[string]any
@@ -121,6 +135,19 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
// DOM 补充(金额 / SKU)。
parseDOMContent(page, od)
+ allCookies, cookieErr := page.Context().Cookies()
+ if cookieErr != nil {
+ return nil, fmt.Errorf("读取订单详情浏览器 Cookie Jar: %w", cookieErr)
+ }
+ od.CookieSnapshot = cookieSnapshotFromPlaywright(allCookies)
+ if od.CookieSnapshot == nil {
+ od.CookieSnapshot = []cookierefresh.BrowserCookie{}
+ }
+ od.CookieSnapshotComplete = true
+ od.UpdatedCookies = currentCookieHeader(od.CookieSnapshot, goofishIMURL)
+ if session := mtop.CookieSessionFromContext(ctx); session != nil {
+ session.ReplaceSnapshot(od.CookieSnapshot)
+ }
if od.Amount == "" {
title, _ := page.Title()
m.logger.Warn("订单详情未解析到实付金额", "order_id", orderID, "page_title", title, "page_url", page.URL(), "api_captured", body != nil, "observed_apis", observedAPIs)
diff --git a/internal/browser/token_request.go b/internal/browser/token_request.go
deleted file mode 100644
index 34d7e96..0000000
--- a/internal/browser/token_request.go
+++ /dev/null
@@ -1,78 +0,0 @@
-package browser
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "strings"
-
- "github.com/playwright-community/playwright-go"
-
- "xianyu-go/internal/xianyu/cookierefresh"
- "xianyu-go/internal/xianyu/mtop"
- "xianyu-go/internal/xianyu/protocol"
-)
-
-// ExecuteTokenRequest sends the signed token request from a real Chromium page
-// so TLS, UA, Client Hints, Origin, Referer and the browser cookie jar all agree.
-func (m *Manager) ExecuteTokenRequest(ctx context.Context, req mtop.TokenBrowserRequest) (*mtop.TokenBrowserResponse, error) {
- if strings.TrimSpace(req.URL) == "" || strings.TrimSpace(req.Cookies) == "" {
- return nil, fmt.Errorf("浏览器 token 请求参数不完整")
- }
- unb := protocol.TransCookies(req.Cookies)["unb"]
- if unb == "" {
- return nil, fmt.Errorf("浏览器 token 请求缺少 unb")
- }
- bctx, release, err := m.newPersistentRenewContext(ctx, unb, req.Cookies, nil, true, true)
- if err != nil {
- return nil, err
- }
- defer release()
- page, err := bctx.NewPage()
- if err != nil {
- return nil, fmt.Errorf("浏览器 token 请求新建页面: %w", err)
- }
- defer func() { _ = page.Close() }()
- if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
- WaitUntil: playwright.WaitUntilStateDomcontentloaded,
- Timeout: playwright.Float(15000),
- }); err != nil {
- return nil, fmt.Errorf("浏览器 token 请求初始化站点: %w", err)
- }
- value, err := page.Evaluate(`async ({url, body}) => {
- const response = await fetch(url, {
- method: 'POST',
- credentials: 'include',
- headers: {
- 'accept': 'application/json',
- 'content-type': 'application/x-www-form-urlencoded'
- },
- body
- });
- return {status: response.status, body: await response.text()};
- }`, map[string]any{"url": req.URL, "body": req.Body})
- if err != nil {
- return nil, fmt.Errorf("浏览器执行 token fetch: %w", err)
- }
- raw, err := json.Marshal(value)
- if err != nil {
- return nil, err
- }
- var result struct {
- Status int `json:"status"`
- Body string `json:"body"`
- }
- if err := json.Unmarshal(raw, &result); err != nil {
- return nil, fmt.Errorf("解析浏览器 token 响应: %w", err)
- }
- all, err := bctx.Cookies()
- if err != nil {
- return nil, fmt.Errorf("读取浏览器 token Cookie: %w", err)
- }
- browserCookies := cookierefresh.CookieStringFromSnapshot(cookieSnapshotFromPlaywright(all))
- return &mtop.TokenBrowserResponse{
- Status: result.Status,
- Body: []byte(result.Body),
- UpdatedCookies: cookierefresh.MergeOriginalFields(req.Cookies, browserCookies),
- }, nil
-}
diff --git a/internal/browser/token_request_test.go b/internal/browser/token_request_test.go
new file mode 100644
index 0000000..405b4d6
--- /dev/null
+++ b/internal/browser/token_request_test.go
@@ -0,0 +1,32 @@
+package browser
+
+import (
+ "testing"
+
+ "xianyu-go/internal/xianyu/cookierefresh"
+)
+
+func TestCredentialCookieSnapshotPreservesChromiumAttributes(t *testing.T) {
+ existing := []cookierefresh.BrowserCookie{
+ {Name: "cookie2", Value: "old", Domain: ".taobao.com", Path: "/", Expires: 12345, HTTPOnly: true, Secure: true, SameSite: "None"},
+ {Name: "stale", Value: "remove", Domain: ".goofish.com", Path: "/"},
+ }
+ got := credentialCookieSnapshot(existing, map[string]string{"cookie2": "new", "unb": "1"})
+ if len(got) != 2 {
+ t.Fatalf("snapshot length=%d want=2: %+v", len(got), got)
+ }
+ byName := map[string]cookierefresh.BrowserCookie{}
+ for _, cookie := range got {
+ byName[cookie.Name] = cookie
+ }
+ cookie2 := byName["cookie2"]
+ if cookie2.Value != "new" || cookie2.Domain != ".taobao.com" || cookie2.Expires != 12345 || !cookie2.HTTPOnly || !cookie2.Secure || cookie2.SameSite != "None" {
+ t.Fatalf("preserved cookie=%+v", cookie2)
+ }
+ if unb := byName["unb"]; unb.Domain != goofishDot || unb.Path != "/" {
+ t.Fatalf("new cookie defaults=%+v", unb)
+ }
+ if _, ok := byName["stale"]; ok {
+ t.Fatal("cookie absent from current snapshot must be removed")
+ }
+}
diff --git a/internal/db/account_tokens.go b/internal/db/account_tokens.go
index 80f2006..c0c7c03 100644
--- a/internal/db/account_tokens.go
+++ b/internal/db/account_tokens.go
@@ -7,16 +7,15 @@ import (
"fmt"
)
-// AccountToken 持久化的账号登录凭证缓存(device_id + accessToken)。
-//
-// 设计动机(参考 xianyu-auto-reply 的 xy_token_cache):
-// - device_id 跨进程重启复用,避免每次重启换新设备 ID 触发阿里端设备绑定/风控;
-// - accessToken 缓存后,短重启可复用、瞬时 mtop 失败可回退到上次有效 token,不掉线。
+// AccountToken 持久化最近一次页面运行实例的 device_id 和 token 请求元数据。
+// accessToken 不用于后续 WebSocket 注册;官方消息页在每次 loginV2/reConnect
+// 前都会重新获取 token,页面重载后也会生成新的 device_id。
type AccountToken struct {
- CookieID string
- DeviceID string
- AccessToken string
- ExpireAt int64 // unix 秒,0 表示无有效 token
+ CookieID string
+ DeviceID string
+ AccessToken string
+ ExpireAt int64 // unix 秒,0 表示无有效 token
+ CookieFingerprint string
}
// AccountTokens 读写 account_tokens 表。
@@ -31,8 +30,8 @@ func (t *AccountTokens) Get(ctx context.Context, cookieID string) (AccountToken,
var tk AccountToken
tk.CookieID = cookieID
err := t.DB.QueryRowContext(ctx,
- `SELECT device_id, access_token, expire_at FROM account_tokens WHERE cookie_id=?`,
- cookieID).Scan(&tk.DeviceID, &tk.AccessToken, &tk.ExpireAt)
+ `SELECT device_id, access_token, expire_at, cookie_fingerprint FROM account_tokens WHERE cookie_id=?`,
+ cookieID).Scan(&tk.DeviceID, &tk.AccessToken, &tk.ExpireAt, &tk.CookieFingerprint)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return AccountToken{}, ErrNotFound
@@ -52,13 +51,12 @@ func (t *AccountTokens) Get(ctx context.Context, cookieID string) (AccountToken,
// Save upsert 缓存的 device_id + accessToken + expire_at。
func (t *AccountTokens) Save(ctx context.Context, cookieID, deviceID, accessToken string, expireAt int64) error {
- // device_id is an account identity, not part of the expiring token cache.
- // Once stored, token refreshes must never replace it.
- if existing, err := t.Get(ctx, cookieID); err == nil && existing.DeviceID != "" {
- deviceID = existing.DeviceID
- } else if err != nil && !errors.Is(err, ErrNotFound) {
- return err
- }
+ return t.SaveBound(ctx, cookieID, deviceID, accessToken, expireAt, "")
+}
+
+// SaveBound persists an access token together with the page-runtime device ID
+// and canonical Cookie state from which it was issued.
+func (t *AccountTokens) SaveBound(ctx context.Context, cookieID, deviceID, accessToken string, expireAt int64, cookieFingerprint string) error {
encryptedDeviceID, err := t.codec.encrypt("device-id", cookieID, deviceID)
if err != nil {
return err
@@ -68,15 +66,16 @@ func (t *AccountTokens) Save(ctx context.Context, cookieID, deviceID, accessToke
return err
}
_, err = t.DB.ExecContext(ctx,
- `INSERT INTO account_tokens (cookie_id, device_id, access_token, expire_at, updated_at)
- VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)`+
+ `INSERT INTO account_tokens (cookie_id, device_id, access_token, expire_at, cookie_fingerprint, updated_at)
+ VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`+
dialectUpsert(t.Dialect, []string{"cookie_id"}, map[string]string{
- "device_id": "excluded.device_id",
- "access_token": "excluded.access_token",
- "expire_at": "excluded.expire_at",
- "updated_at": "CURRENT_TIMESTAMP",
+ "device_id": "excluded.device_id",
+ "access_token": "excluded.access_token",
+ "expire_at": "excluded.expire_at",
+ "cookie_fingerprint": "excluded.cookie_fingerprint",
+ "updated_at": "CURRENT_TIMESTAMP",
}),
- cookieID, encryptedDeviceID, encryptedToken, expireAt)
+ cookieID, encryptedDeviceID, encryptedToken, expireAt, cookieFingerprint)
if err != nil {
return fmt.Errorf("保存 account_tokens: %w", err)
}
@@ -123,7 +122,7 @@ func (t *AccountTokens) Clear(ctx context.Context, cookieID string) error {
return err
}
_, err = t.DB.ExecContext(ctx,
- `UPDATE account_tokens SET access_token=?, expire_at=0, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=?`,
+ `UPDATE account_tokens SET access_token=?, expire_at=0, cookie_fingerprint='', updated_at=CURRENT_TIMESTAMP WHERE cookie_id=?`,
encryptedToken, cookieID)
return err
}
diff --git a/internal/db/account_tokens_test.go b/internal/db/account_tokens_test.go
index a7093af..c4b70d8 100644
--- a/internal/db/account_tokens_test.go
+++ b/internal/db/account_tokens_test.go
@@ -26,34 +26,34 @@ func TestAccountTokens_CRUD(t *testing.T) {
t.Fatalf("不存在应返回 ErrNotFound,got %v", err)
}
- // Save(首次写入)。
+ // SaveBound(首次写入)。
expire := time.Now().Add(time.Hour).Unix()
- if err := store.Tokens.Save(ctx, "cid", "dev-1", "tok-1", expire); err != nil {
+ if err := store.Tokens.SaveBound(ctx, "cid", "dev-1", "tok-1", expire, "cookie-hash-1"); err != nil {
t.Fatalf("Save: %v", err)
}
tk, err := store.Tokens.Get(ctx, "cid")
if err != nil {
t.Fatalf("Get: %v", err)
}
- if tk.DeviceID != "dev-1" || tk.AccessToken != "tok-1" || tk.ExpireAt != expire {
+ if tk.DeviceID != "dev-1" || tk.AccessToken != "tok-1" || tk.ExpireAt != expire || tk.CookieFingerprint != "cookie-hash-1" {
t.Fatalf("Get 返回不匹配: %+v", tk)
}
- // 再次 Save 更新 token,但永久 device ID 不允许覆盖。
- if err := store.Tokens.Save(ctx, "cid", "dev-2", "tok-2", expire+1); err != nil {
+ // 页面运行实例变化后,再次 Save 同步更新 device ID 和 token。
+ if err := store.Tokens.SaveBound(ctx, "cid", "dev-2", "tok-2", expire+1, "cookie-hash-2"); err != nil {
t.Fatalf("Save upsert: %v", err)
}
tk, _ = store.Tokens.Get(ctx, "cid")
- if tk.DeviceID != "dev-1" || tk.AccessToken != "tok-2" || tk.ExpireAt != expire+1 {
+ if tk.DeviceID != "dev-2" || tk.AccessToken != "tok-2" || tk.ExpireAt != expire+1 || tk.CookieFingerprint != "cookie-hash-2" {
t.Fatalf("upsert 后字段应更新: %+v", tk)
}
- // Clear 只清 token,永久 device ID 必须保留。
+ // Clear 只清 token,保留最近一次页面运行实例的 device ID。
if err := store.Tokens.Clear(ctx, "cid"); err != nil {
t.Fatalf("Clear: %v", err)
}
tk, err = store.Tokens.Get(ctx, "cid")
- if err != nil || tk.DeviceID != "dev-1" || tk.AccessToken != "" || tk.ExpireAt != 0 {
+ if err != nil || tk.DeviceID != "dev-2" || tk.AccessToken != "" || tk.ExpireAt != 0 || tk.CookieFingerprint != "" {
t.Fatalf("Clear 后 device ID 应保留且 token 清空: tk=%+v err=%v", tk, err)
}
@@ -63,7 +63,7 @@ func TestAccountTokens_CRUD(t *testing.T) {
}
}
-func TestAccountTokens_DeviceIDSurvivesTokenLifecycle(t *testing.T) {
+func TestAccountTokens_SaveTracksLatestRuntimeDeviceID(t *testing.T) {
store, cleanup := newTestDB(t)
defer cleanup()
ctx := context.Background()
@@ -83,8 +83,8 @@ func TestAccountTokens_DeviceIDSurvivesTokenLifecycle(t *testing.T) {
t.Fatal(err)
}
afterRestart, err := store.Tokens.GetOrCreateDeviceID(ctx, "cid", "device-after-restart")
- if err != nil || first != "device-first" || afterRestart != first {
- t.Fatalf("device ID changed across token lifecycle: first=%q after=%q err=%v", first, afterRestart, err)
+ if err != nil || first != "device-first" || afterRestart != "device-replacement" {
+ t.Fatalf("未保留最近一次运行时 device ID: first=%q after=%q err=%v", first, afterRestart, err)
}
}
diff --git a/internal/db/cookies.go b/internal/db/cookies.go
index 69d101a..644f6b9 100644
--- a/internal/db/cookies.go
+++ b/internal/db/cookies.go
@@ -3,6 +3,7 @@ package db
import (
"context"
"database/sql"
+ "encoding/json"
"errors"
"fmt"
"strings"
@@ -43,7 +44,8 @@ func (c *Cookies) UpdateSettings(ctx context.Context, cookieID string, input Acc
}
defer tx.Rollback()
var ownerID int64
- if err := tx.QueryRowContext(ctx, `SELECT user_id FROM cookies WHERE id=?`, cookieID).Scan(&ownerID); err != nil {
+ var metadataJSON string
+ if err := tx.QueryRowContext(ctx, c.cookieSelectForUpdate(`user_id,COALESCE(metadata_json,'')`), cookieID).Scan(&ownerID, &metadataJSON); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return 0, ErrNotFound
}
@@ -62,6 +64,16 @@ func (c *Cookies) UpdateSettings(ctx context.Context, cookieID string, input Acc
}
assignments = append(assignments, "value=?")
args = append(args, encrypted)
+ plainMetadata, err := c.codec.decrypt(cookieMetadataScope, cookieID, metadataJSON)
+ if err != nil {
+ return 0, err
+ }
+ cleanMetadata, err := c.codec.encrypt(cookieMetadataScope, cookieID, stripCookieSnapshotMetadata(plainMetadata))
+ if err != nil {
+ return 0, err
+ }
+ assignments = append(assignments, "metadata_json=?")
+ args = append(args, cleanMetadata)
}
if input.Remark != nil {
assignments = append(assignments, "remark=?")
@@ -186,20 +198,14 @@ func (c *Cookies) UpdateValueOwned(ctx context.Context, cookieID, cookieValue st
if err != nil {
return err
}
- res, err := c.DB.ExecContext(ctx,
- `UPDATE cookies SET value=?,updated_at=CURRENT_TIMESTAMP WHERE id=? AND user_id=?`,
- encrypted, cookieID, userID)
+ tx, err := c.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
- if n, rowsErr := res.RowsAffected(); rowsErr != nil {
- return rowsErr
- } else if n == 1 {
- return nil
- }
-
+ defer tx.Rollback()
var existingOwner int64
- if err := c.DB.QueryRowContext(ctx, `SELECT user_id FROM cookies WHERE id=?`, cookieID).Scan(&existingOwner); err != nil {
+ var rawMetadata string
+ if err := tx.QueryRowContext(ctx, c.cookieSelectForUpdate(`user_id,COALESCE(metadata_json,'')`), cookieID).Scan(&existingOwner, &rawMetadata); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return ErrNotFound
}
@@ -208,7 +214,22 @@ func (c *Cookies) UpdateValueOwned(ctx context.Context, cookieID, cookieValue st
if existingOwner != userID {
return ErrForbidden
}
- return ErrNotFound
+ metadata, err := c.metadataWithoutCookieSnapshotValue(cookieID, rawMetadata)
+ if err != nil {
+ return err
+ }
+ res, err := tx.ExecContext(ctx,
+ `UPDATE cookies SET value=?,metadata_json=?,updated_at=CURRENT_TIMESTAMP WHERE id=? AND user_id=?`,
+ encrypted, metadata, cookieID, userID)
+ if err != nil {
+ return err
+ }
+ if n, rowsErr := res.RowsAffected(); rowsErr != nil {
+ return rowsErr
+ } else if n > 1 {
+ return fmt.Errorf("更新 cookie 影响了 %d 行", n)
+ }
+ return tx.Commit()
}
// UpdateValueExisting 供续期和运行时写回使用,只能更新现存账号。
@@ -221,8 +242,24 @@ func (c *Cookies) UpdateValueExisting(ctx context.Context, cookieID, cookieValue
if err != nil {
return err
}
- res, err := c.DB.ExecContext(ctx,
- `UPDATE cookies SET value=?,updated_at=CURRENT_TIMESTAMP WHERE id=?`, encrypted, cookieID)
+ tx, err := c.DB.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ var rawMetadata string
+ if err := tx.QueryRowContext(ctx, c.cookieSelectForUpdate(`COALESCE(metadata_json,'')`), cookieID).Scan(&rawMetadata); err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return ErrNotFound
+ }
+ return err
+ }
+ metadata, err := c.metadataWithoutCookieSnapshotValue(cookieID, rawMetadata)
+ if err != nil {
+ return err
+ }
+ res, err := tx.ExecContext(ctx,
+ `UPDATE cookies SET value=?,metadata_json=?,updated_at=CURRENT_TIMESTAMP WHERE id=?`, encrypted, metadata, cookieID)
if err != nil {
return err
}
@@ -230,10 +267,44 @@ func (c *Cookies) UpdateValueExisting(ctx context.Context, cookieID, cookieValue
if err != nil {
return err
}
- if n != 1 {
- return ErrNotFound
+ if n > 1 {
+ return fmt.Errorf("更新 cookie 影响了 %d 行", n)
}
- return nil
+ return tx.Commit()
+}
+
+func (c *Cookies) cookieSelectForUpdate(columns string) string {
+ query := `SELECT ` + columns + ` FROM cookies WHERE id=?`
+ if c.Dialect == DialectMySQL || c.Dialect == DialectPostgres {
+ query += ` FOR UPDATE`
+ }
+ return query
+}
+
+func (c *Cookies) metadataWithoutCookieSnapshotValue(cookieID, raw string) (string, error) {
+ plain, err := c.codec.decrypt(cookieMetadataScope, cookieID, raw)
+ if err != nil {
+ return "", err
+ }
+ return c.codec.encrypt(cookieMetadataScope, cookieID, stripCookieSnapshotMetadata(plain))
+}
+
+func stripCookieSnapshotMetadata(metadata string) string {
+ if strings.TrimSpace(metadata) == "" {
+ return ""
+ }
+ var values map[string]any
+ if err := json.Unmarshal([]byte(metadata), &values); err != nil {
+ // 无法解析的历史 metadata 本来也不能被当作快照使用,原样保留。
+ return metadata
+ }
+ delete(values, "cookies_refresh_snapshot")
+ delete(values, "cookie_refresh_snapshot")
+ raw, err := json.Marshal(values)
+ if err != nil {
+ return metadata
+ }
+ return string(raw)
}
// Save 保留给历史调用和测试夹具使用。新业务代码应选择 CreateOwned、
@@ -364,6 +435,10 @@ func (c *Cookies) GetDetails(ctx context.Context, cookieID string) (*CookieDetai
if err != nil {
return nil, err
}
+ d.MetadataJSON, err = c.codec.decrypt(cookieMetadataScope, d.ID, d.MetadataJSON)
+ if err != nil {
+ return nil, err
+ }
d.Password, err = c.codec.decrypt("login-password", d.ID, d.Password)
if err != nil {
return nil, err
@@ -497,20 +572,28 @@ func (c *Cookies) GetStatus(ctx context.Context, cookieID string) bool {
// Status 返回账号启用状态;没有 cookie_status 记录时按启用处理,数据库错误不再静默放行。
func (c *Cookies) Status(ctx context.Context, cookieID string) (bool, error) {
+ enabled, _, err := c.StatusWithReason(ctx, cookieID)
+ return enabled, err
+}
+
+// StatusWithReason 原子语义地读取账号当前启用状态和禁用原因;调用方应在
+// Store.LockAccountCredentials 保护下使用,以复核列表查询后的最新状态。
+func (c *Cookies) StatusWithReason(ctx context.Context, cookieID string) (bool, string, error) {
var exists bool
if err := c.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM cookies WHERE id=?)`, cookieID).Scan(&exists); err != nil {
- return false, err
+ return false, "", err
}
if !exists {
- return false, ErrNotFound
+ return false, "", ErrNotFound
}
var enabled int
- err := c.DB.QueryRowContext(ctx, `SELECT enabled FROM cookie_status WHERE cookie_id=?`, cookieID).Scan(&enabled)
+ var reason string
+ err := c.DB.QueryRowContext(ctx, `SELECT enabled,COALESCE(disable_reason,'') FROM cookie_status WHERE cookie_id=?`, cookieID).Scan(&enabled, &reason)
if errors.Is(err, sql.ErrNoRows) {
- return true, nil
+ return true, "", nil
}
if err != nil {
- return false, err
+ return false, "", err
}
- return enabled != 0, nil
+ return enabled != 0, reason, nil
}
diff --git a/internal/db/migrate_test.go b/internal/db/migrate_test.go
index 06595db..df63dfa 100644
--- a/internal/db/migrate_test.go
+++ b/internal/db/migrate_test.go
@@ -125,8 +125,8 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
t.Fatalf("goose dialect: %v", err)
}
goose.SetBaseFS(migrationsFS)
- // 依次回滚 21 到 14,再整体升级。
- for i := 0; i < 8; i++ {
+ // 依次回滚 22 到 14,再整体升级。
+ for i := 0; i < 9; i++ {
if err := goose.Down(d, "migrations/sqlite"); err != nil {
t.Fatalf("down migration #%d: %v", i+1, err)
}
@@ -140,6 +140,9 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
if columnExists(t, d, "default_reply_records", "status") {
t.Fatal("default_reply_records.status should be removed after migration 16 down")
}
+ if columnExists(t, d, "account_tokens", "cookie_fingerprint") {
+ t.Fatal("account_tokens.cookie_fingerprint should be removed after migration 22 down")
+ }
if err := goose.Up(d, "migrations/sqlite"); err != nil {
t.Fatalf("up after down: %v", err)
@@ -156,6 +159,7 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) {
{"risk_control_logs", "processing_status"},
{"default_reply_records", "status"},
{"default_reply_records", "text_sent"},
+ {"account_tokens", "cookie_fingerprint"},
} {
if !columnExists(t, d, c.table, c.col) {
t.Fatalf("column missing after re-up: %s.%s", c.table, c.col)
diff --git a/internal/db/migrations/mysql/00022_token_cookie_binding.sql b/internal/db/migrations/mysql/00022_token_cookie_binding.sql
new file mode 100644
index 0000000..f2dc711
--- /dev/null
+++ b/internal/db/migrations/mysql/00022_token_cookie_binding.sql
@@ -0,0 +1,5 @@
+-- +goose Up
+ALTER TABLE account_tokens ADD COLUMN cookie_fingerprint VARCHAR(64) NOT NULL DEFAULT '';
+
+-- +goose Down
+ALTER TABLE account_tokens DROP COLUMN cookie_fingerprint;
diff --git a/internal/db/migrations/postgres/00022_token_cookie_binding.sql b/internal/db/migrations/postgres/00022_token_cookie_binding.sql
new file mode 100644
index 0000000..639cf41
--- /dev/null
+++ b/internal/db/migrations/postgres/00022_token_cookie_binding.sql
@@ -0,0 +1,5 @@
+-- +goose Up
+ALTER TABLE account_tokens ADD COLUMN cookie_fingerprint TEXT NOT NULL DEFAULT '';
+
+-- +goose Down
+ALTER TABLE account_tokens DROP COLUMN cookie_fingerprint;
diff --git a/internal/db/migrations/sqlite/00022_token_cookie_binding.sql b/internal/db/migrations/sqlite/00022_token_cookie_binding.sql
new file mode 100644
index 0000000..639cf41
--- /dev/null
+++ b/internal/db/migrations/sqlite/00022_token_cookie_binding.sql
@@ -0,0 +1,5 @@
+-- +goose Up
+ALTER TABLE account_tokens ADD COLUMN cookie_fingerprint TEXT NOT NULL DEFAULT '';
+
+-- +goose Down
+ALTER TABLE account_tokens DROP COLUMN cookie_fingerprint;
diff --git a/internal/db/multidb_test.go b/internal/db/multidb_test.go
index 119c2f8..060ad37 100644
--- a/internal/db/multidb_test.go
+++ b/internal/db/multidb_test.go
@@ -641,7 +641,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
t.Fatalf("set goose dialect: %v", err)
}
goose.SetBaseFS(migrationsFS)
- for i := 0; i < 8; i++ {
+ for i := 0; i < 9; i++ {
if err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil {
t.Fatalf("migration down #%d: %v", i+1, err)
}
@@ -655,6 +655,9 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
if columnExistsForDialect(t, tg.store.DB, tg.dialect, "default_reply_records", "status") {
t.Fatal("default_reply_records.status should be removed after down")
}
+ if columnExistsForDialect(t, tg.store.DB, tg.dialect, "account_tokens", "cookie_fingerprint") {
+ t.Fatal("account_tokens.cookie_fingerprint should be removed after down")
+ }
if err := goose.Up(tg.store.DB, "migrations/"+subdir); err != nil {
t.Fatalf("migration up after down: %v", err)
@@ -673,6 +676,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) {
{"default_reply_records", "text_sent"},
{"automation_runs", "action_cursor"},
{"automation_runs", "action_started"},
+ {"account_tokens", "cookie_fingerprint"},
} {
if !columnExistsForDialect(t, tg.store.DB, tg.dialect, c.table, c.col) {
t.Fatalf("column missing after re-up: %s.%s", c.table, c.col)
diff --git a/internal/db/orders.go b/internal/db/orders.go
index 07a7da9..3a82868 100644
--- a/internal/db/orders.go
+++ b/internal/db/orders.go
@@ -201,6 +201,9 @@ func orderUpsertAssignments(opts OrderUpsertOpts) ([]string, []any) {
if opts.SystemShipped != nil {
add("system_shipped", boolToInt(*opts.SystemShipped), true)
}
+ if opts.IsBargain != nil {
+ add("is_bargain", boolToInt(*opts.IsBargain), true)
+ }
add("chat_id", opts.ChatID, opts.ChatID != "")
add("item_id", opts.ItemID, opts.ItemID != "")
add("buyer_id", opts.BuyerID, opts.BuyerID != "")
@@ -277,6 +280,7 @@ type OrderUpsertOpts struct {
ReceiverAddr string
ReceiverCity string
ChatID string
+ IsBargain *bool
SystemShipped *bool
}
diff --git a/internal/db/renewal.go b/internal/db/renewal.go
index 0801acf..5e9abd6 100644
--- a/internal/db/renewal.go
+++ b/internal/db/renewal.go
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"errors"
+ "fmt"
"strings"
"time"
)
@@ -70,7 +71,7 @@ func (c *Cookies) AllRenewalAccounts(ctx context.Context) ([]RenewalAccount, err
return nil, err
}
defer rows.Close()
- return scanRenewalAccounts(rows)
+ return c.scanRenewalAccounts(rows)
}
// ActiveRenewalAccounts 返回启用账号,用于 WS/API 续期类任务。
@@ -87,10 +88,10 @@ func (c *Cookies) ActiveRenewalAccounts(ctx context.Context) ([]RenewalAccount,
return nil, err
}
defer rows.Close()
- return scanRenewalAccounts(rows)
+ return c.scanRenewalAccounts(rows)
}
-func scanRenewalAccounts(rows *sql.Rows) ([]RenewalAccount, error) {
+func (c *Cookies) scanRenewalAccounts(rows *sql.Rows) ([]RenewalAccount, error) {
var out []RenewalAccount
for rows.Next() {
var a RenewalAccount
@@ -100,6 +101,19 @@ func scanRenewalAccounts(rows *sql.Rows) ([]RenewalAccount, error) {
}
a.Enabled = enabled != 0
a.ShowBrowser = showBrowser != 0
+ var err error
+ a.Value, err = c.codec.decrypt("cookie", a.ID, a.Value)
+ if err != nil {
+ return nil, fmt.Errorf("解密账号 %s Cookie: %w", a.ID, err)
+ }
+ a.Password, err = c.codec.decrypt("login-password", a.ID, a.Password)
+ if err != nil {
+ return nil, fmt.Errorf("解密账号 %s 登录密码: %w", a.ID, err)
+ }
+ a.MetadataJSON, err = c.codec.decrypt(cookieMetadataScope, a.ID, a.MetadataJSON)
+ if err != nil {
+ return nil, fmt.Errorf("解密账号 %s Cookie metadata: %w", a.ID, err)
+ }
out = append(out, a)
}
return out, rows.Err()
@@ -107,17 +121,46 @@ func scanRenewalAccounts(rows *sql.Rows) ([]RenewalAccount, error) {
// UpdateRenewalCookie 保存续期后的 Cookie,同时写入浏览器快照和最后续期时间。
func (c *Cookies) UpdateRenewalCookie(ctx context.Context, cookieID, cookieValue, metadataJSON string, lastRefreshAt int64) error {
+ if strings.TrimSpace(cookieID) == "" {
+ return errors.New("账号 ID 不能为空")
+ }
if lastRefreshAt <= 0 {
lastRefreshAt = time.Now().Unix()
}
- _, err := c.DB.ExecContext(ctx,
+ encryptedCookie, err := c.codec.encrypt("cookie", cookieID, cookieValue)
+ if err != nil {
+ return fmt.Errorf("加密 Cookie: %w", err)
+ }
+ encryptedMetadata, err := c.codec.encrypt(cookieMetadataScope, cookieID, metadataJSON)
+ if err != nil {
+ return fmt.Errorf("加密 Cookie metadata: %w", err)
+ }
+ res, err := c.DB.ExecContext(ctx,
`UPDATE cookies
SET value=?, metadata_json=?, last_refresh_at=?, updated_at=CURRENT_TIMESTAMP
WHERE id=?`,
- cookieValue, metadataJSON, lastRefreshAt, cookieID)
+ encryptedCookie, encryptedMetadata, lastRefreshAt, cookieID)
if err != nil {
return err
}
+ rows, err := res.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if rows > 1 {
+ return fmt.Errorf("更新续期 Cookie 影响了 %d 行", rows)
+ }
+ if rows == 0 {
+ // MySQL 默认报告“实际变更行数”,同值且同秒更新可能返回 0;
+ // 只有记录确实不存在时才应映射为 ErrNotFound。
+ var exists bool
+ if err := c.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM cookies WHERE id=?)`, cookieID).Scan(&exists); err != nil {
+ return err
+ }
+ if !exists {
+ return ErrNotFound
+ }
+ }
return nil
}
diff --git a/internal/db/renewal_test.go b/internal/db/renewal_test.go
new file mode 100644
index 0000000..d9f954e
--- /dev/null
+++ b/internal/db/renewal_test.go
@@ -0,0 +1,125 @@
+package db
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+)
+
+func TestUpdateRenewalCookieEncryptsCookieAndMetadataAtRest(t *testing.T) {
+ t.Setenv("XIANYU_DATA_KEY", "renewal-encryption-key")
+ store, cleanup := newTestDB(t)
+ defer cleanup()
+ ctx := context.Background()
+ if ok, err := store.Users.Create(ctx, "renewal-owner", "renewal-owner@example.com", "pw"); err != nil || !ok {
+ t.Fatalf("create owner: ok=%v err=%v", ok, err)
+ }
+ owner, _ := store.Users.GetByUsername(ctx, "renewal-owner")
+ if err := store.Cookies.CreateOwned(ctx, "renewal-cookie", "old=1", owner.ID); err != nil {
+ t.Fatal(err)
+ }
+ metadata := `{"cookies_refresh_snapshot":[{"name":"token","value":"metadata-secret","domain":".goofish.com","path":"/"}],"other":true}`
+ if err := store.Cookies.UpdateRenewalCookie(ctx, "renewal-cookie", "token=cookie-secret", metadata, 12345); err != nil {
+ t.Fatal(err)
+ }
+
+ var rawCookie, rawMetadata string
+ if err := store.DB.QueryRowContext(ctx, `SELECT value,metadata_json FROM cookies WHERE id=?`, "renewal-cookie").Scan(&rawCookie, &rawMetadata); err != nil {
+ t.Fatal(err)
+ }
+ for name, raw := range map[string]string{"cookie": rawCookie, "metadata": rawMetadata} {
+ if !strings.HasPrefix(raw, encryptedValuePrefix) || strings.Contains(raw, "secret") {
+ t.Fatalf("%s was not encrypted at rest: %q", name, raw)
+ }
+ }
+ detail, err := store.Cookies.GetDetails(ctx, "renewal-cookie")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if detail.Value != "token=cookie-secret" || detail.MetadataJSON != metadata || detail.LastRefreshAt != 12345 {
+ t.Fatalf("detail=%+v", detail)
+ }
+ accounts, err := store.Cookies.ActiveRenewalAccounts(ctx)
+ if err != nil || len(accounts) != 1 {
+ t.Fatalf("accounts=%+v err=%v", accounts, err)
+ }
+ if accounts[0].Value != detail.Value || accounts[0].MetadataJSON != metadata {
+ t.Fatalf("renewal account not decrypted: %+v", accounts[0])
+ }
+}
+
+func TestUpdateRenewalCookieRejectsMissingAccount(t *testing.T) {
+ store, cleanup := newTestDB(t)
+ defer cleanup()
+ err := store.Cookies.UpdateRenewalCookie(context.Background(), "missing", "a=1", `{}`, 1)
+ if !errors.Is(err, ErrNotFound) {
+ t.Fatalf("err=%v want ErrNotFound", err)
+ }
+}
+
+func TestFlatCookieUpdateClearsSnapshotAndPreservesOtherMetadata(t *testing.T) {
+ t.Setenv("XIANYU_DATA_KEY", "flat-update-metadata-key")
+ store, cleanup := newTestDB(t)
+ defer cleanup()
+ ctx := context.Background()
+ if ok, err := store.Users.Create(ctx, "flat-owner", "flat-owner@example.com", "pw"); err != nil || !ok {
+ t.Fatalf("create owner: ok=%v err=%v", ok, err)
+ }
+ owner, _ := store.Users.GetByUsername(ctx, "flat-owner")
+ if err := store.Cookies.CreateOwned(ctx, "flat-cookie", "sid=old", owner.ID); err != nil {
+ t.Fatal(err)
+ }
+ metadata := `{"cookies_refresh_snapshot":[{"name":"sid","value":"old","domain":".goofish.com","path":"/"}],"other":true}`
+ if err := store.Cookies.UpdateRenewalCookie(ctx, "flat-cookie", "sid=old", metadata, 1); err != nil {
+ t.Fatal(err)
+ }
+ if err := store.Cookies.UpdateValueExisting(ctx, "flat-cookie", "sid=fresh"); err != nil {
+ t.Fatal(err)
+ }
+ detail, err := store.Cookies.GetDetails(ctx, "flat-cookie")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if detail.Value != "sid=fresh" || strings.Contains(detail.MetadataJSON, "cookies_refresh_snapshot") || !strings.Contains(detail.MetadataJSON, `"other":true`) {
+ t.Fatalf("detail=%+v", detail)
+ }
+ var rawMetadata string
+ if err := store.DB.QueryRowContext(ctx, `SELECT metadata_json FROM cookies WHERE id=?`, "flat-cookie").Scan(&rawMetadata); err != nil {
+ t.Fatal(err)
+ }
+ if !strings.HasPrefix(rawMetadata, encryptedValuePrefix) || strings.Contains(rawMetadata, "other") {
+ t.Fatalf("metadata not encrypted at rest: %q", rawMetadata)
+ }
+}
+
+func TestEncryptLegacySecretsMigratesCookieMetadata(t *testing.T) {
+ t.Setenv("XIANYU_DATA_KEY", "metadata-migration-key")
+ store, cleanup := newTestDB(t)
+ defer cleanup()
+ ctx := context.Background()
+ if ok, err := store.Users.Create(ctx, "metadata-owner", "metadata-owner@example.com", "pw"); err != nil || !ok {
+ t.Fatalf("create owner: ok=%v err=%v", ok, err)
+ }
+ owner, _ := store.Users.GetByUsername(ctx, "metadata-owner")
+ metadata := `{"cookies_refresh_snapshot":[{"name":"sid","value":"legacy-secret"}]}`
+ if _, err := store.DB.ExecContext(ctx,
+ `INSERT INTO cookies (id,value,user_id,metadata_json) VALUES (?,?,?,?)`,
+ "legacy-metadata", "legacy-cookie", owner.ID, metadata); err != nil {
+ t.Fatal(err)
+ }
+ if err := store.EncryptLegacySecrets(ctx); err != nil {
+ t.Fatal(err)
+ }
+ var raw string
+ if err := store.DB.QueryRowContext(ctx, `SELECT metadata_json FROM cookies WHERE id=?`, "legacy-metadata").Scan(&raw); err != nil {
+ t.Fatal(err)
+ }
+ if !strings.HasPrefix(raw, encryptedValuePrefix) || strings.Contains(raw, "legacy-secret") {
+ t.Fatalf("legacy metadata was not encrypted: %q", raw)
+ }
+ detail, err := store.Cookies.GetDetails(ctx, "legacy-metadata")
+ if err != nil || detail.MetadataJSON != metadata {
+ t.Fatalf("detail=%+v err=%v", detail, err)
+ }
+}
diff --git a/internal/db/secrets.go b/internal/db/secrets.go
index 97511a2..d89d8cc 100644
--- a/internal/db/secrets.go
+++ b/internal/db/secrets.go
@@ -14,7 +14,10 @@ import (
"strings"
)
-const encryptedValuePrefix = "enc:v1:"
+const (
+ encryptedValuePrefix = "enc:v1:"
+ cookieMetadataScope = "cookie-metadata"
+)
// secretCodec 对数据库敏感字段做 AES-256-GCM 信封加密。未配置密钥时保持
// 明文兼容;已加密数据若缺少/使用错误密钥会明确报错,绝不把密文当凭证使用。
@@ -77,15 +80,15 @@ func (s *Store) EncryptLegacySecrets(ctx context.Context) error {
}
defer tx.Rollback()
- type cookieSecret struct{ id, value, password string }
- rows, err := tx.QueryContext(ctx, `SELECT id,value,COALESCE(password,'') FROM cookies`)
+ type cookieSecret struct{ id, value, password, metadata string }
+ rows, err := tx.QueryContext(ctx, `SELECT id,value,COALESCE(password,''),COALESCE(metadata_json,'') FROM cookies`)
if err != nil {
return err
}
var cookies []cookieSecret
for rows.Next() {
var row cookieSecret
- if err := rows.Scan(&row.id, &row.value, &row.password); err != nil {
+ if err := rows.Scan(&row.id, &row.value, &row.password, &row.metadata); err != nil {
rows.Close()
return err
}
@@ -103,8 +106,12 @@ func (s *Store) EncryptLegacySecrets(ctx context.Context) error {
if err != nil {
return fmt.Errorf("校验账号 %s 登录密码: %w", row.id, err)
}
- if value != row.value || password != row.password {
- if _, err := tx.ExecContext(ctx, `UPDATE cookies SET value=?,password=? WHERE id=?`, value, password, row.id); err != nil {
+ 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 := tx.ExecContext(ctx, `UPDATE cookies SET value=?,password=?,metadata_json=? WHERE id=?`, value, password, metadata, row.id); err != nil {
return err
}
}
diff --git a/internal/db/store.go b/internal/db/store.go
index 0f1588f..8738070 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -1,6 +1,9 @@
package db
-import "database/sql"
+import (
+ "database/sql"
+ "sync"
+)
// Store 聚合各 repository,供上层(HTTP server、account supervisor 等)统一持有。
type Store struct {
@@ -25,32 +28,57 @@ type Store struct {
Renewal *RenewalStore
LoginLogs *AccountLoginLogs
RiskLogs *RiskControlLogs
+
+ credentialMu sync.Mutex
+ credentialLocks map[string]*sync.Mutex
}
// NewStore 基于 *sql.DB 构造聚合 store。dialect 用于业务 SQL 方言分支。
func NewStore(db *sql.DB, dialect Dialect) *Store {
codec := secretCodecFromEnvironment()
return &Store{
- DB: db,
- Dialect: dialect,
- Users: &Users{DB: db},
- Sessions: &Sessions{DB: db},
- Cookies: &Cookies{DB: db, Dialect: dialect, codec: codec},
- Items: &Items{DB: db, Dialect: dialect},
- Cards: &Cards{DB: db, Dialect: dialect},
- Automation: &AutomationRules{DB: db, Dialect: dialect},
- Orders: &Orders{DB: db, Dialect: dialect},
- Keywords: &Keywords{DB: db, Dialect: dialect},
- DefaultReps: &DefaultReplies{DB: db, Dialect: dialect},
- ItemReps: &ItemReplies{DB: db, Dialect: dialect},
- AIReply: &AIReply{DB: db, codec: codec},
- Notifications: &Notifications{DB: db, Dialect: dialect, codec: codec},
- Settings: &SystemSettings{DB: db, Dialect: dialect, codec: codec},
- WSMessages: &WSMessageStore{DB: db},
- PublishBatches: &ItemPublishBatches{DB: db},
- Tokens: &AccountTokens{DB: db, Dialect: dialect, codec: codec},
- Renewal: &RenewalStore{DB: db, Dialect: dialect},
- LoginLogs: &AccountLoginLogs{DB: db},
- RiskLogs: &RiskControlLogs{DB: db, Dialect: dialect},
+ DB: db,
+ Dialect: dialect,
+ Users: &Users{DB: db},
+ Sessions: &Sessions{DB: db},
+ Cookies: &Cookies{DB: db, Dialect: dialect, codec: codec},
+ Items: &Items{DB: db, Dialect: dialect},
+ Cards: &Cards{DB: db, Dialect: dialect},
+ Automation: &AutomationRules{DB: db, Dialect: dialect},
+ Orders: &Orders{DB: db, Dialect: dialect},
+ Keywords: &Keywords{DB: db, Dialect: dialect},
+ DefaultReps: &DefaultReplies{DB: db, Dialect: dialect},
+ ItemReps: &ItemReplies{DB: db, Dialect: dialect},
+ AIReply: &AIReply{DB: db, codec: codec},
+ Notifications: &Notifications{DB: db, Dialect: dialect, codec: codec},
+ Settings: &SystemSettings{DB: db, Dialect: dialect, codec: codec},
+ WSMessages: &WSMessageStore{DB: db},
+ PublishBatches: &ItemPublishBatches{DB: db},
+ Tokens: &AccountTokens{DB: db, Dialect: dialect, codec: codec},
+ Renewal: &RenewalStore{DB: db, Dialect: dialect},
+ LoginLogs: &AccountLoginLogs{DB: db},
+ RiskLogs: &RiskControlLogs{DB: db, Dialect: dialect},
+ credentialLocks: make(map[string]*sync.Mutex),
}
}
+
+// LockAccountCredentials serializes Cookie/token state transitions for one
+// account across the IM runtime and renewal scheduler. The returned function
+// must be called exactly once.
+func (s *Store) LockAccountCredentials(cookieID string) func() {
+ if s == nil {
+ return func() {}
+ }
+ s.credentialMu.Lock()
+ if s.credentialLocks == nil {
+ s.credentialLocks = make(map[string]*sync.Mutex)
+ }
+ lock := s.credentialLocks[cookieID]
+ if lock == nil {
+ lock = &sync.Mutex{}
+ s.credentialLocks[cookieID] = lock
+ }
+ s.credentialMu.Unlock()
+ lock.Lock()
+ return lock.Unlock
+}
diff --git a/internal/engine/account.go b/internal/engine/account.go
index c7029bc..0763629 100644
--- a/internal/engine/account.go
+++ b/internal/engine/account.go
@@ -18,6 +18,7 @@ import (
"xianyu-go/internal/automation"
"xianyu-go/internal/db"
+ "xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
"xianyu-go/internal/xianyu/protocol"
"xianyu-go/internal/xianyu/renew"
@@ -26,29 +27,19 @@ import (
// 账号运行时参数。
const (
- MaxConnectionFailures = 5 // 连续失败上限,触发密码登录刷新
- TokenFetchDisableThreshold = 100 // 参考实现:连续真实 token 故障 100 次后禁用
- MessageSemaphoreSize = 100 // 并发消息处理上限
- MessageDebounceDelay = 1 * time.Second // 防抖延迟:用户停止发送 1s 后回复
- MessageExpireTime = time.Hour // 去重有效期
- ProcessedIDsMaxSize = 10000 // 去重表上限,超限清理
- HeartbeatInterval = 15 * time.Second
- // 与参考实现保持一致:token_refresh_loop 默认 20 小时一次;cookieRefreshLoop
- // 每 180 秒检查一次登录凭证。Cookie 循环优先复用 5-10 小时的 token 缓存,
- // 只有缓存未命中时才请求 mtop,不能把“检查间隔”误做成“接口请求间隔”。
- TokenRefreshInterval = 20 * time.Hour
- CookieRefreshInterval = 180 * time.Second
- CookieRefreshCheckInterval = 60 * time.Second
- MessageCooldown = 5 * time.Minute // 收到消息后 5 分钟内不刷 cookie
- PasswordLoginMinGap = 60 * time.Second
- MaxNetworkFailures = 20
- FrequentDisconnectLimit = 5
- FrequentDisconnectWindow = 5 * time.Minute
+ MaxConnectionFailures = 5 // 仅保留给显式人工恢复入口和兼容测试
+ TokenFetchDisableThreshold = 100 // 兼容常量;官网运行时不会按次数自动禁用账号
+ MessageSemaphoreSize = 100 // 并发消息处理上限
+ MessageDebounceDelay = 1 * time.Second // 防抖延迟:用户停止发送 1s 后回复
+ MessageExpireTime = time.Hour // 去重有效期
+ ProcessedIDsMaxSize = 10000 // 去重表上限,超限清理
+ HeartbeatInterval = 15 * time.Second
+ PasswordLoginMinGap = 60 * time.Second
+ MaxNetworkFailures = 20
+ FrequentDisconnectLimit = 5
+ FrequentDisconnectWindow = 5 * time.Minute
+ TokenCaptchaFailureCooldown = 5 * time.Minute
- // TokenCacheTTLMin/Max 控制缓存 accessToken 的随机有效期。短重启 / 瞬时
- // mtop 失败时回退到此缓存不掉线;在线 Cookie 保活由 cookieRefreshLoop 续期。
- TokenCacheTTLMin = 5 * time.Hour
- TokenCacheTTLMax = 10 * time.Hour
// ShortConnectionThreshold 仅用于统计频繁短连接;已经建立后的网络断线
// 不会清 Token 缓存。
ShortConnectionThreshold = 30 * time.Second
@@ -79,7 +70,8 @@ type Handler interface {
// HandleSystemEvent 处理平台系统事件。系统卡片永远不进入 AI 回复链,
// 这里只把事件交给自动化中心,由自动化规则决定是否执行。
HandleSystemEvent(ctx context.Context, task automation.Task) error
- // OnPasswordLoginRefresh 连续失败时触发浏览器密码登录刷新;返回是否成功。
+ // OnPasswordLoginRefresh 是历史接口名;连续失败时只触发 Go 协议续期,
+ // 不得启动浏览器密码登录。
OnPasswordLoginRefresh(ctx context.Context, cookieID string) bool
// OnAccountAlert 账号告警通知(token 失效/自动恢复失败/风控验证等)。
// level 取 AlertLevel* 常量。实现方应把告警推送到该账号绑定的通知渠道。
@@ -97,7 +89,6 @@ type tokenCaptchaHandler interface {
const (
tokenRefreshStarted = "started"
tokenRefreshSuccess = "success"
- tokenRefreshSuccessFromCache = "success_from_cache"
tokenRefreshFailedCaptcha = "failed_captcha"
tokenRefreshFailedCaptchaError = "failed_captcha_exception"
tokenRefreshFailedTimeout = "failed_timeout"
@@ -107,6 +98,8 @@ const (
tokenRefreshSkippedCooldown = "skipped_cooldown"
)
+var errTokenCaptchaCooldown = errors.New("token 风控验证冷却中")
+
// ChatMessage 防抖后投递给业务层的一条聊天消息。
type ChatMessage struct {
AccountID string // cookie_id
@@ -149,7 +142,7 @@ type Account struct {
store *db.Store
mtop mtop.Client
renewer cookieRenewer
- wsDialer wsDialer
+ wsDialer WSDialer
handler Handler
logger *slog.Logger
@@ -163,8 +156,8 @@ type Account struct {
shortDisconnects []time.Time
lastMsgReceived time.Time
lastTokenRefresh time.Time
+ lastCaptchaFailure time.Time
lastTokenStatus string
- lastCookieRefresh time.Time
runtimeState string
runtimeMessage string
runtimeUpdatedAt time.Time
@@ -177,6 +170,8 @@ type Account struct {
offlineSince time.Time
lastOfflineReason string
tokenFetchFailures int
+ credentialFP string // 当前内存扁平 Cookie + 权威 Jar 的完整状态指纹
+ tokenCredentialFP string // currentToken 获取完成时绑定的完整凭证状态
// 去重
dedupMu sync.Mutex
@@ -197,6 +192,9 @@ type Account struct {
accepting bool
reply *ReplyService
+
+ wsRecordOnce sync.Once
+ wsRecordQueue chan db.WSMessage
}
type debounceEntry struct {
@@ -208,33 +206,37 @@ type debounceEntry struct {
// WSConn 是 Account 对 ws 连接的最小契约。*ws.Conn 实现该接口;
// 测试可注入 fakeWSConn 以隔离真实 WS 握手与网络。
type WSConn interface {
+ Register(ctx context.Context, deviceID, accessToken string) error
HeartbeatLoop(ctx context.Context, interval time.Duration) error
ReceiveLoop(ctx context.Context, onMessage func(map[string]any)) error
Close() error
- SetAccessToken(token string)
SendText(ctx context.Context, myID, cid, toID, text string) error
SendImage(ctx context.Context, myID, cid, toID, imageURL string, width, height int) error
}
-// wsDialer 抽象 ws.Dial,便于测试替身。
-type wsDialer interface {
+// WSDialer 抽象 WebSocket 打开阶段,便于测试隔离真实网络。
+type WSDialer interface {
Dial(ctx context.Context, cfg ws.Config, logger *slog.Logger) (WSConn, error)
}
type defaultDialer struct{}
func (defaultDialer) Dial(ctx context.Context, cfg ws.Config, logger *slog.Logger) (WSConn, error) {
- return ws.Dial(ctx, cfg, logger)
+ return ws.Open(ctx, cfg, logger)
}
type cookieRenewer interface {
- RenewAPIFirst(ctx context.Context, cookiesStr string) (*renew.Result, error)
+ RenewAPIFirst(ctx context.Context, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*renew.Result, error)
}
type loginStatusChecker interface {
CheckLoginStatusContext(ctx context.Context, cookiesStr string) (*mtop.LoginStatusResult, error)
}
+type scopedTokenClient interface {
+ RefreshTokenWithCredentialContext(ctx context.Context, cookiesStr, deviceID string, snapshot []cookierefresh.BrowserCookie) (*mtop.RefreshResult, error)
+}
+
type loginStatusCheckResult struct {
recovered bool
riskRequired bool
@@ -252,6 +254,8 @@ type Config struct {
MTop mtop.Client
// Renewer 可选:注入 Cookie 接口续期服务以便测试 mock。nil 时使用默认实现。
Renewer cookieRenewer
+ // WSDialer 可选:用于测试隔离原生 WebSocket 握手。
+ WSDialer WSDialer
}
// New 构造单账号运行时(未启动)。
@@ -271,6 +275,10 @@ func New(cfg Config) *Account {
}
cookies := protocol.TransCookies(cfg.CookieStr)
myid := cookies["unb"]
+ wsDialer := cfg.WSDialer
+ if wsDialer == nil {
+ wsDialer = defaultDialer{}
+ }
a := &Account{
CookieID: cfg.CookieID,
CookieStr: cfg.CookieStr,
@@ -278,7 +286,7 @@ func New(cfg Config) *Account {
store: cfg.Store,
mtop: mtopClient,
renewer: renewer,
- wsDialer: defaultDialer{},
+ wsDialer: wsDialer,
handler: cfg.Handler,
logger: logger.With("account", cfg.CookieID),
deviceID: protocol.GenerateDeviceID(myid),
@@ -289,17 +297,13 @@ func New(cfg Config) *Account {
runtimeState: RuntimeStarting,
runtimeMessage: "正在启动账号服务",
runtimeUpdatedAt: time.Now(),
- }
- if cfg.Store != nil && cfg.Store.Tokens != nil {
- deviceID, err := cfg.Store.Tokens.GetOrCreateDeviceID(context.Background(), cfg.CookieID, a.deviceID)
- if err != nil {
- logger.Error("读取或保存账号 device ID 失败", "account", cfg.CookieID, "err", err)
- } else {
- a.deviceID = deviceID
- }
+ credentialFP: credentialStateFingerprint(cfg.CookieStr, ""),
}
if cfg.Store != nil {
a.reply = NewReplyService(cfg.CookieID, cfg.Store, a, nil, NewAIReplier(cfg.CookieID, cfg.Store, logger), logger)
+ if cfg.Store.WSMessages != nil {
+ a.wsRecordQueue = make(chan db.WSMessage, 256)
+ }
}
return a
}
@@ -308,12 +312,7 @@ func New(cfg Config) *Account {
// 调用方应在独立 goroutine 中运行;Stop 可优雅停止。
func (a *Account) Run(parent context.Context) error {
ctx, cancel := context.WithCancel(parent)
- var backgroundWG sync.WaitGroup
- backgroundStarted := false
- defer func() {
- cancel()
- backgroundWG.Wait()
- }()
+ defer cancel()
a.mu.Lock()
a.stopFn = cancel
a.mu.Unlock()
@@ -321,7 +320,23 @@ func (a *Account) Run(parent context.Context) error {
a.runtimeCtx = ctx
a.accepting = true
a.taskMu.Unlock()
-
+ a.startWSRecorder(ctx)
+ if a.store != nil && a.store.Cookies != nil && !a.store.Cookies.GetStatus(ctx, a.CookieID) {
+ a.logger.Info("账号在启动续期前已禁用")
+ return nil
+ }
+ // 官网 /im 启动时执行 auto-login plugin;成功后 location.reload() 会重建
+ // FishEngine 和页面级 device ID。Go 客户端用 HTTP 复刻续期,并在成功时
+ // 只重建这一本地运行时身份。续期失败不能用网页 DOM 阻断 token + WS;
+ // Chromium 仅用于读取本机指纹和处理 token 滑块。
+ if a.renewer != nil {
+ if a.tryAPIRenew(ctx) {
+ a.rotatePageDeviceID()
+ }
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ }
for {
if ctx.Err() != nil {
return ctx.Err()
@@ -332,13 +347,33 @@ func (a *Account) Run(parent context.Context) error {
return nil
}
- // 1) 必须先检查 token 缓存。只有缓存未命中时,refreshToken 才读取 DB cookie;
- // 定时续期写入 DB 不得让一个仍有效的 IM token 失效。
- // 参考实现先构造 WS Cookie 头,再获取/刷新 Token。Token API 返回的
- // Set-Cookie 会更新后续轮次,但不回写本轮已经构造好的握手头。
- wsCookieStr := a.currentCookieStr()
- token, cookieStr, err := a.acquireRuntimeToken(ctx)
+ // 每次新建 IM 连接前吸收数据库中的最新 Cookie。健康连接不会被续期任务
+ // 主动打断;Cookie 变化只会使本次重连放弃旧 token 并重新派生。
+ a.reloadCookieFromDB(ctx)
+
+ // 官网先完成原生 WebSocket 握手,再从 authTokenCallback 获取本次
+ // 连接专用 token,最后发送 /reg。
+ conn, err := a.wsDialer.Dial(ctx, ws.Config{Recorder: a.wsRecorder()}, a.logger)
if err != nil {
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ a.logger.Error("WS 握手失败", "err", err)
+ if retryErr := a.handleWSConnectFailure(ctx, err); retryErr != nil {
+ return retryErr
+ }
+ continue
+ }
+ // The official web client calls
+ // mtop.taobao.idlemessage.pc.login.token from authTokenCallback for every
+ // loginV2/reConnect attempt. Do the same here: an access token belongs to
+ // one connection attempt and must never be reused for a later /reg.
+ token, cookieStr, err := a.acquireFreshConnectionToken(ctx)
+ if err != nil {
+ _ = conn.Close()
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
a.logger.Error("获取 token 失败", "err", err)
a.mu.Lock()
status := a.lastTokenStatus
@@ -349,37 +384,27 @@ func (a *Account) Run(parent context.Context) error {
tokenFailures := a.tokenFetchFailures
a.mu.Unlock()
a.setRuntimeError(ctx, err)
- if !nonCounted && tokenFailures >= TokenFetchDisableThreshold {
- reason := fmt.Sprintf("连续 %d 次获取 token 失败,最后错误:%s", TokenFetchDisableThreshold, errString(err))
- a.disableForTokenFailures(ctx, reason)
- return nil
- }
+ _ = tokenFailures // 仅用于诊断;官网不会按次数永久禁用账号。
if mtop.IsRiskVerificationErr(err) {
- a.logger.Warn("闲鱼要求安全验证,等待 5 秒后重试", "err", err)
+ a.logger.Warn("闲鱼要求安全验证,停止本次消息登录", "err", err)
a.alertEvent(ctx, EventSecurityVerification, AlertLevelWarn, "闲鱼要求安全验证",
- "账号触发闲鱼风控验证(滑块/人脸等),系统会按参考策略继续重试。")
- if sleepCtx(ctx, 5*time.Second) != nil {
- return ctx.Err()
- }
- continue
+ "账号触发闲鱼风控验证(滑块/人脸等),需要重新登录或完成人工验证。")
+ return err
}
if mtop.IsSessionExpiredErr(err) {
- a.logger.Warn("session 已失效,进入一次密码登录恢复链", "err", err)
+ reason := "登录凭证已失效,请重新登录"
+ a.logger.Warn("session 已失效,停止消息登录", "err", err)
a.clearTokenCache(ctx)
- a.notifyOffline(ctx, "token/session 已失效:"+errString(err))
- if err := a.handleMaxFailures(ctx); err != nil {
- return err
- }
- continue
+ a.setRuntimeState(RuntimeAuthExpired, reason)
+ a.notifyOffline(ctx, reason+":"+errString(err))
+ return err
}
- delay := 5 * time.Second
- if status == tokenRefreshSkippedCooldown {
- delay = 5 * time.Minute
- }
- if sleepCtx(ctx, delay) != nil {
- return ctx.Err()
- }
- continue
+ // authTokenCallback 的任意 reject 都被官方 loginV2 映射为
+ // CONN_ERROR=5,页面不会自动 reConnect。
+ reason := "获取消息凭证失败,请重新登录"
+ a.setRuntimeState(RuntimeAuthExpired, reason)
+ a.notifyOffline(ctx, reason+":"+errString(err))
+ return err
}
a.mu.Lock()
a.currentToken = token
@@ -389,54 +414,32 @@ func (a *Account) Run(parent context.Context) error {
a.setRuntimeState(RuntimeConnecting, "登录凭证有效,正在连接消息服务")
a.logger.Info("token 刷新成功")
- // 2) 连接 WS + 注册。
- var recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string)
- if a.store != nil && a.store.WSMessages != nil {
- recorder = func(direction, rawText, parsedJSON, parseStatus, errMsg string) {
- if err := a.store.WSMessages.Add(context.Background(), db.WSMessage{
- CookieID: a.CookieID,
- Direction: direction,
- RawText: rawText,
- ParsedJSON: parsedJSON,
- MessageKind: "",
- ParseStatus: parseStatus,
- Error: errMsg,
- }); err != nil {
- a.logger.Error("记录 WS 报文失败", "cookie_id", a.CookieID, "err", err)
- }
- }
- }
+ // 2) 使用刚获得的 token 注册已经打开的 WS。
a.mu.Lock()
deviceID := a.deviceID
+ tokenCredentialFP := a.tokenCredentialFP
a.mu.Unlock()
- attemptStartedAt := time.Now()
- conn, err := a.wsDialer.Dial(ctx, ws.Config{
- CookieStr: wsCookieStr,
- DeviceID: deviceID,
- AccessToken: token,
- Recorder: recorder,
- }, a.logger)
+ credentialUnlock := func() {}
+ if a.store != nil {
+ credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
+ }
+ if !a.cookieSnapshotMatchesDB(ctx, tokenCredentialFP) {
+ credentialUnlock()
+ _ = conn.Close()
+ a.reloadCookieFromDB(ctx)
+ continue
+ }
+ err = conn.Register(ctx, deviceID, token)
+ credentialUnlock()
if err != nil {
- a.logger.Error("WS 连接失败", "err", err)
- a.mu.Lock()
- a.connFailures++
- a.currentToken = ""
- failures := a.connFailures
- a.mu.Unlock()
- if time.Since(attemptStartedAt) < 15*time.Second {
- a.logger.Warn("连接建立阶段快速失败,清除 token 缓存", "duration", time.Since(attemptStartedAt).Round(time.Millisecond))
- a.clearTokenCache(ctx)
- }
- a.setRuntimeState(RuntimeReconnecting, "消息服务连接失败,稍后自动重试")
- if failures >= MaxConnectionFailures {
- if err := a.handleMaxFailures(ctx); err != nil {
- return err
- }
- continue
- }
- if sleepCtx(ctx, a.retryDelay("ws_dial")) != nil {
+ _ = conn.Close()
+ if ctx.Err() != nil {
return ctx.Err()
}
+ a.logger.Error("WS 注册失败", "err", err)
+ if retryErr := a.handleWSConnectFailure(ctx, err); retryErr != nil {
+ return retryErr
+ }
continue
}
a.mu.Lock()
@@ -451,30 +454,19 @@ func (a *Account) Run(parent context.Context) error {
a.offlineSince = time.Time{}
a.lastOfflineReason = ""
a.mu.Unlock()
- if !backgroundStarted {
- backgroundStarted = true
- backgroundWG.Add(2)
- go func() {
- defer backgroundWG.Done()
- a.tokenRefreshLoop(ctx, nil)
- }()
- go func() {
- defer backgroundWG.Done()
- a.cookieRefreshLoop(ctx, nil)
- }()
- }
a.setRuntimeState(RuntimeOnline, "消息服务连接正常")
if shouldRecovered {
a.alertEvent(ctx, EventAccountRecovered, AlertLevelInfo, "账号已恢复在线",
fmt.Sprintf("账号 %s 已重新连接闲鱼消息服务。掉线开始时间:%s。", a.CookieID, formatTimeOrUnknown(offlineSince)))
}
- // 3) 心跳随连接重建;token/cookie 任务属于账号生命周期,网络重连时不取消。
+ // 3) 健康连接只维持心跳和收包;token 只在下一次注册前更新。
hbCtx, hbCancel := context.WithCancel(ctx)
var hbErr error
hbDone := make(chan struct{})
go func() {
hbErr = conn.HeartbeatLoop(hbCtx, HeartbeatInterval)
+ _ = conn.Close()
hbCancel()
close(hbDone)
}()
@@ -494,63 +486,126 @@ func (a *Account) Run(parent context.Context) error {
a.conn = nil
a.mu.Unlock()
connectedDuration := time.Since(startedAt)
+ if ws.IsConnectLimitError(recvErr) {
+ a.clearConnectionToken(ctx)
+ reason := "消息会话已被服务端移除"
+ a.setRuntimeState(RuntimeAuthExpired, reason)
+ a.notifyOffline(ctx, reason)
+ return nil
+ }
+ if ws.IsAuthenticationError(recvErr) {
+ // 官网把 /push/kickout 转成 UNCONNECTED,页面监听器随后立即
+ // reConnect,并由 authTokenCallback 获取新的连接凭证。
+ a.clearConnectionToken(ctx)
+ a.setRuntimeState(RuntimeReconnecting, "消息会话被服务端踢下线,正在重新连接")
+ continue
+ }
+ // 心跳失败会先关闭连接,ReceiveLoop 往往只观察到 context canceled。
+ // 官网以心跳 Promise 的 reject 为真实断线原因并立即 reConnect。
+ if hbErr != nil && !errors.Is(hbErr, context.Canceled) &&
+ (recvErr == nil || errors.Is(recvErr, context.Canceled)) {
+ recvErr = hbErr
+ }
// 正常 close 的 async-for 会直接进入下一轮,不计任何失败。
if recvErr == nil {
+ a.clearConnectionToken(ctx)
a.setRuntimeState(RuntimeReconnecting, "消息连接已结束,正在重新连接")
continue
}
- if isEstablishedNetworkError(recvErr) {
- a.mu.Lock()
- a.networkFailures++
- networkFailures := a.networkFailures
- a.mu.Unlock()
- if a.recordShortDisconnect(connectedDuration) {
- reason := "未知原因频繁断开连接"
- a.disableForFrequentDisconnects(ctx, reason)
- return nil
- }
- a.setRuntimeState(RuntimeReconnecting, "网络连接已断开,稍后自动重连")
- a.logger.Warn("WS 网络连接结束", "err", recvErr, "network_failures", networkFailures, "connected_duration", connectedDuration.Round(time.Second), "heartbeat_err", hbErr)
- if networkFailures >= MaxNetworkFailures {
- a.mu.Lock()
- a.networkFailures = 0
- a.mu.Unlock()
- if sleepCtx(ctx, 120*time.Second) != nil {
- return ctx.Err()
- }
- continue
- }
- if sleepCtx(ctx, a.networkRetryDelay()) != nil {
- return ctx.Err()
- }
+ if isEstablishedNetworkError(recvErr) || errors.Is(recvErr, context.Canceled) {
+ a.clearConnectionToken(ctx)
+ a.setRuntimeState(RuntimeReconnecting, "网络连接已断开,正在重新连接")
+ a.logger.Warn("WS 网络连接结束", "err", recvErr, "connected_duration", connectedDuration.Round(time.Second), "heartbeat_err", hbErr)
+ // 官网当前页面在 CONN_UNCONNECTED 事件后立即调用 reConnect。
continue
}
- a.mu.Lock()
- a.currentToken = ""
- a.connFailures++
- failures := a.connFailures
- a.mu.Unlock()
- if time.Since(attemptStartedAt) < 15*time.Second {
- a.clearTokenCache(ctx)
- }
- a.setRuntimeState(RuntimeReconnecting, "消息连接已断开,稍后自动重连")
- a.logger.Warn("WS 连接结束", "err", recvErr, "failures", failures, "heartbeat_err", hbErr)
+ // 其他已经建立后的非认证错误同样进入 UNCONNECTED;不升级为
+ // 密码登录、指数退避或永久禁用。
+ a.clearConnectionToken(ctx)
+ a.setRuntimeState(RuntimeReconnecting, "消息连接已断开,正在重新连接")
+ a.logger.Warn("WS 连接结束", "err", recvErr, "heartbeat_err", hbErr)
+ continue
+ }
+}
- if failures >= MaxConnectionFailures {
- if err := a.handleMaxFailures(ctx); err != nil {
- return err
- }
- continue
+func (a *Account) wsRecorder() func(direction, rawText, parsedJSON, parseStatus, errMsg string) {
+ if a.store == nil || a.store.WSMessages == nil || a.wsRecordQueue == nil {
+ return nil
+ }
+ return func(direction, rawText, parsedJSON, parseStatus, errMsg string) {
+ message := db.WSMessage{
+ CookieID: a.CookieID,
+ Direction: direction,
+ RawText: rawText,
+ ParsedJSON: parsedJSON,
+ MessageKind: "",
+ ParseStatus: parseStatus,
+ Error: errMsg,
}
- if sleepCtx(ctx, a.retryDelay(errString(recvErr))) != nil {
- return ctx.Err()
+ select {
+ case a.wsRecordQueue <- message:
+ default:
+ a.logger.Warn("WS 报文记录队列已满,丢弃诊断记录", "cookie_id", a.CookieID, "direction", direction)
}
}
}
+func (a *Account) startWSRecorder(ctx context.Context) {
+ if a.store == nil || a.store.WSMessages == nil || a.wsRecordQueue == nil {
+ return
+ }
+ a.wsRecordOnce.Do(func() {
+ go func() {
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case message := <-a.wsRecordQueue:
+ writeCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
+ err := a.store.WSMessages.Add(writeCtx, message)
+ cancel()
+ if err != nil && ctx.Err() == nil {
+ a.logger.Warn("记录 WS 报文失败", "cookie_id", a.CookieID, "err", err)
+ }
+ }
+ }
+ }()
+ })
+}
+
+func (a *Account) handleWSConnectFailure(ctx context.Context, err error) error {
+ a.clearConnectionToken(ctx)
+ reason := "消息凭证被拒绝,请重新登录"
+ if ws.IsConnectLimitError(err) {
+ reason = "消息会话已被服务端移除"
+ } else if !ws.IsInvalidTokenError(err) && !ws.IsAuthenticationError(err) {
+ // 原生握手 CONNECT_FAILED 和 INVALID_TOKEN 一样进入官网 CONN_ERROR=5;
+ // /im 页面不会对该状态自动 reConnect,而是展示重新登录入口。
+ reason = "消息服务连接失败,请重新登录"
+ }
+ a.setRuntimeState(RuntimeAuthExpired, reason)
+ a.notifyOffline(ctx, reason)
+ return err
+}
+
+// acquireFreshConnectionToken mirrors the official web message client:
+// authTokenCallback obtains a fresh login.token result before every WebSocket
+// loginV2/reConnect and the returned accessToken is used only for that /reg.
+func (a *Account) acquireFreshConnectionToken(ctx context.Context) (string, string, error) {
+ return a.refreshToken(ctx)
+}
+
+// clearConnectionToken ends the lifetime of the token used by the previous
+// WebSocket attempt. The page-runtime device ID remains stable until a Cookie
+// update maps to an official page reload.
+func (a *Account) clearConnectionToken(ctx context.Context) {
+ a.clearCurrentToken()
+ a.clearTokenCache(ctx)
+}
+
// Stop 优雅停止。
func (a *Account) Stop() {
a.mu.Lock()
@@ -610,15 +665,22 @@ func (a *Account) beginTask() (context.Context, bool) {
return ctx, true
}
-// handleMaxFailures 连续失败达上限:尝试密码登录刷新;失败则返回 err 触发上层重启实例。
+// handleMaxFailures 是历史兼容恢复入口;只尝试 Go 协议续期,不执行密码登录。
func (a *Account) handleMaxFailures(ctx context.Context) error {
- a.logger.Warn("连续失败达上限,触发密码登录刷新", "failures", MaxConnectionFailures)
- a.notifyOffline(ctx, fmt.Sprintf("消息服务连续认证/连接失败 %d 次,开始自动恢复", MaxConnectionFailures))
+ credentialUnlock := func() {}
+ if a.store != nil {
+ credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
+ }
+ defer credentialUnlock()
+ a.logger.Warn("连续失败达上限,触发 Go 协议续期", "failures", MaxConnectionFailures)
+ a.notifyRecoveringOffline(ctx, fmt.Sprintf("消息服务连续认证/连接失败 %d 次,开始自动恢复", MaxConnectionFailures))
if a.handler != nil && a.handler.OnPasswordLoginRefresh(ctx, a.CookieID) {
if d, err := a.store.Cookies.GetDetails(ctx, a.CookieID); err == nil && d != nil && d.Value != "" {
a.replaceCookieStr(d.Value)
+ a.clearCurrentToken()
+ a.clearTokenCache(ctx)
}
- a.logger.Info("密码登录刷新成功,重置失败计数")
+ a.logger.Info("Go 协议续期成功,重置失败计数")
a.setRuntimeState(RuntimeConnecting, "登录凭证已刷新,正在重新连接")
a.resetFailures()
return sleepCtx(ctx, 2*time.Second)
@@ -645,40 +707,32 @@ func (a *Account) markAuthExpired() bool {
}
func (a *Account) notifyOffline(ctx context.Context, reason string) {
+ if !a.markOfflineNotified(reason) {
+ return
+ }
+ a.alertEvent(ctx, EventAccountOffline, AlertLevelWarn, "账号已掉线,需要重新登录",
+ fmt.Sprintf("账号 %s 的闲鱼消息连接已进入不可自动重连状态。原因:%s。请更新登录信息或重新登录后再启动账号。", a.CookieID, reason))
+}
+
+func (a *Account) notifyRecoveringOffline(ctx context.Context, reason string) {
+ if !a.markOfflineNotified(reason) {
+ return
+ }
+ a.alertEvent(ctx, EventAccountOffline, AlertLevelWarn, "账号已掉线,正在自动恢复",
+ fmt.Sprintf("账号 %s 出现登录凭证过期或认证掉线。原因:%s。系统会先发送本通知,再继续尝试 Go 协议续期;如仍失败则需要重新扫码登录。", a.CookieID, reason))
+}
+
+func (a *Account) markOfflineNotified(reason string) bool {
a.mu.Lock()
if a.offlineNotified {
a.mu.Unlock()
- return
+ return false
}
a.offlineNotified = true
a.offlineSince = time.Now()
a.lastOfflineReason = reason
a.mu.Unlock()
- a.alertEvent(ctx, EventAccountOffline, AlertLevelWarn, "账号已掉线,正在自动恢复",
- fmt.Sprintf("账号 %s 出现登录凭证过期或认证掉线。原因:%s。系统会先发送本通知,再继续尝试轻量续期、浏览器续期或密码登录恢复。", a.CookieID, reason))
-}
-
-func (a *Account) disableForTokenFailures(ctx context.Context, reason string) {
- a.logger.Error("连续获取 token 失败,自动禁用账号", "account", a.CookieID, "reason", reason)
- if a.store != nil && a.store.Cookies != nil {
- if err := a.store.Cookies.SetStatusWithReason(ctx, a.CookieID, false, reason); err != nil {
- a.logger.Error("自动禁用账号失败", "account", a.CookieID, "err", err)
- }
- }
- a.clearTokenCache(ctx)
- a.setRuntimeState(RuntimeStopped, "连续获取 token 失败,账号已自动禁用")
- a.alertEvent(ctx, EventAccountDisabled, AlertLevelCritical, "账号已自动禁用", reason)
-}
-
-func (a *Account) disableForFrequentDisconnects(ctx context.Context, reason string) {
- a.logger.Error("频繁短连接断开,自动禁用账号", "account", a.CookieID, "reason", reason)
- if a.store != nil && a.store.Cookies != nil {
- if err := a.store.Cookies.SetStatusWithReason(ctx, a.CookieID, false, reason); err != nil {
- a.logger.Error("自动禁用账号失败", "account", a.CookieID, "err", err)
- }
- }
- a.setRuntimeState(RuntimeStopped, "频繁断开连接,账号已自动禁用")
- a.alertEvent(ctx, EventAccountDisabled, AlertLevelCritical, "账号已自动禁用", reason)
+ return true
}
// alert 触发账号告警通知。handler 未注入或为 nil 时静默跳过。
@@ -711,7 +765,7 @@ func formatTimeOrUnknown(t time.Time) string {
}
// tryLoginStatusCheck 调用 mtop.taobao.idlemessage.pc.loginuser.get 做轻量登录态确认。
-// 这个接口的成本低于完整 token 刷新和浏览器动作,且可能顺手下发新的签名 Cookie;
+// 这个接口的成本低于完整 token 刷新,且可能顺手下发新的签名 Cookie;
// 因此在 session 失效后、接口续期前先跑一遍,避免已实现的登录态检查能力闲置。
func (a *Account) tryLoginStatusCheck(ctx context.Context) loginStatusCheckResult {
checker, ok := a.mtop.(loginStatusChecker)
@@ -742,48 +796,188 @@ func (a *Account) tryLoginStatusCheck(ctx context.Context) loginStatusCheckResul
return loginStatusCheckResult{}
}
-// tryAPIRenew 是密码登录前的轻量恢复层。
-// 闲鱼很多“登录态滑向过期”的场景会先允许 hasLogin/silentHasLogin/
-// setLoginSettings 刷新一批 Cookie;直接上密码登录更重,也更容易触发风控。
-// 因此这里先尝试接口续期:只有 setLoginSettings 确认成功才短路后续恢复;
-// 如果只拿到部分 Cookie,仍会保存并清 token,但继续降级到浏览器/密码登录。
+// tryAPIRenew 是密码登录前的轻量恢复层,只执行官网 auto-login plugin 的
+// 单次 silentHasLogin 流程。如果只拿到部分 Cookie,仍先保存并清 token,
+// 但继续按 Go 协议执行后续恢复;仍失败时由上层要求重新扫码登录。
func (a *Account) tryAPIRenew(ctx context.Context) bool {
if a.renewer == nil {
return false
}
+ renewed, _ := a.tryAPIRenewUsing(ctx, func(runCtx context.Context, cookieStr string, snapshot []cookierefresh.BrowserCookie) (*renew.Result, error) {
+ return a.renewer.RenewAPIFirst(runCtx, cookieStr, snapshot)
+ })
+ return renewed
+}
+
+func (a *Account) tryAPIRenewUsing(ctx context.Context, call func(context.Context, string, []cookierefresh.BrowserCookie) (*renew.Result, error)) (bool, error) {
+ a.refreshMu.Lock()
+ defer a.refreshMu.Unlock()
+ credentialUnlock := func() {}
+ if a.store != nil {
+ credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
+ }
+ defer credentialUnlock()
+ if a.store != nil && a.store.Cookies != nil && !a.store.Cookies.GetStatus(ctx, a.CookieID) {
+ return false, nil
+ }
a.mu.Lock()
cookieStr := a.CookieStr
a.mu.Unlock()
- res, err := a.renewer.RenewAPIFirst(ctx, cookieStr)
- if err != nil {
- a.logger.Warn("接口续期失败", "err", err)
- return false
+ var snapshot []cookierefresh.BrowserCookie
+ if a.store != nil && a.store.Cookies != nil {
+ detail, detailErr := a.store.Cookies.GetDetails(ctx, a.CookieID)
+ if detailErr != nil || detail == nil {
+ if detailErr == nil {
+ detailErr = db.ErrNotFound
+ }
+ a.logger.Warn("接口续期前读取最新 Cookie 失败", "err", detailErr)
+ return false, detailErr
+ }
+ if detail.Value != cookieStr {
+ cookieStr = detail.Value
+ a.replaceCookieStr(cookieStr)
+ a.clearCurrentToken()
+ a.clearTokenCache(ctx)
+ }
+ snapshot = cookierefresh.SnapshotFromMetadata(detail.MetadataJSON)
}
+ res, err := call(ctx, cookieStr, snapshot)
if res == nil {
- return false
+ if err != nil {
+ a.logger.Warn("接口续期失败", "err", err)
+ }
+ return false, err
+ }
+ if res.HasPending() {
+ a.watchPendingAPIRenew(res)
}
updated := false
- if res.NewCookies != "" && res.NewCookies != cookieStr {
- updated = a.adoptRecoveredCookie(ctx, res.NewCookies, "接口续期")
+ persisted := false
+ if res.CookieSnapshotComplete && a.store != nil && a.store.Cookies != nil {
+ detail, detailErr := a.store.Cookies.GetDetails(ctx, a.CookieID)
+ if detailErr != nil || detail == nil {
+ if detailErr == nil {
+ detailErr = db.ErrNotFound
+ }
+ a.logger.Warn("保存续期 Cookie 快照失败", "err", detailErr)
+ return false, detailErr
+ }
+ metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, res.CookieSnapshot)
+ if err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, res.NewCookies, metadata, time.Now().Unix()); err != nil {
+ a.logger.Warn("保存续期 Cookie 快照失败", "err", err)
+ return false, err
+ }
+ persisted = true
+ } else if len(res.SetCookies) > 0 && a.store != nil && a.store.Cookies != nil {
+ if err := a.persistRenewFlatCookie(ctx, res.NewCookies); err != nil {
+ a.logger.Warn("保存接口续期扁平 Cookie 失败", "err", err)
+ return false, err
+ }
+ persisted = true
+ }
+ credentialChanged := res.NewCookies != cookieStr && (res.CookieSnapshotComplete || len(res.SetCookies) > 0 || res.NewCookies != "")
+ if credentialChanged {
+ if persisted || a.store == nil || a.store.Cookies == nil {
+ a.replaceCookieStr(res.NewCookies)
+ a.clearCurrentToken()
+ a.clearTokenCache(ctx)
+ a.setRuntimeState(RuntimeConnecting, "接口续期已更新登录凭证,正在重新连接")
+ updated = true
+ } else {
+ updated = a.adoptRecoveredCookie(ctx, res.NewCookies, "接口续期")
+ }
+ }
+ if err != nil {
+ a.logger.Warn("接口续期失败,已保存响应 Cookie", "err", err)
+ return false, err
}
if res.Success {
if !updated {
a.setRuntimeState(RuntimeConnecting, "登录凭证已接口续期,正在重新连接")
}
a.logger.Info("接口续期成功", "method", res.RenewMethod, "updated", strings.Join(res.UpdatedCookieNames, ","))
- return true
+ return true, nil
}
if updated {
a.logger.Info("接口续期返回部分 Cookie 更新,继续降级恢复", "updated", strings.Join(res.UpdatedCookieNames, ","))
- return false
+ return false, nil
}
a.logger.Info("接口续期未产生可用恢复", "success", res.Success, "message", res.Message)
- return false
+ return false, nil
}
-// adoptRecoveredCookie 统一接收“轻量检查/接口续期/浏览器恢复”拿到的新 Cookie。
-// Cookie 变更意味着旧 accessToken 与 session 绑定关系失效,必须清 token 缓存,
-// 让下一轮 acquireToken 使用新 Cookie 重新派生凭证。
+func (a *Account) persistRenewFlatCookie(ctx context.Context, newCookies string) error {
+ if a.store == nil || a.store.Cookies == nil {
+ return nil
+ }
+ detail, err := a.store.Cookies.GetDetails(ctx, a.CookieID)
+ if err != nil || detail == nil {
+ if err != nil {
+ return err
+ }
+ return db.ErrNotFound
+ }
+ // 没有权威 Jar 时,接口 Set-Cookie 只能更新兼容扁平值。不能把
+ // Domain/Path/HttpOnly/PartitionKey 均未知的 Cookie 伪造成完整快照。
+ metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
+ return a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, newCookies, metadata, time.Now().Unix())
+}
+
+func (a *Account) watchPendingAPIRenew(result *renew.Result) {
+ if result == nil || !result.HasPending() {
+ return
+ }
+ go func() {
+ ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
+ defer cancel()
+ late, waitErr := result.AwaitPending(ctx)
+ if late == nil {
+ if waitErr != nil {
+ a.logger.Warn("等待静默续期底层响应失败", "err", waitErr)
+ }
+ return
+ }
+ if persistErr := a.persistPendingRenewCookies(ctx, late); persistErr != nil {
+ a.logger.Warn("保存静默续期迟到 Cookie 失败", "err", persistErr)
+ return
+ }
+ if waitErr != nil {
+ a.logger.Warn("静默续期底层响应失败,已保存响应 Cookie", "err", waitErr)
+ }
+ }()
+}
+
+func (a *Account) persistPendingRenewCookies(ctx context.Context, result *renew.Result) error {
+ if result == nil || len(result.SetCookies) == 0 || a.store == nil || a.store.Cookies == nil {
+ return nil
+ }
+ a.refreshMu.Lock()
+ defer a.refreshMu.Unlock()
+ credentialUnlock := a.store.LockAccountCredentials(a.CookieID)
+ defer credentialUnlock()
+ detail, err := a.store.Cookies.GetDetails(ctx, a.CookieID)
+ if err != nil || detail == nil {
+ if err == nil {
+ err = db.ErrNotFound
+ }
+ return err
+ }
+ newCookies, metadata, changed := renew.RebaseResponseCookies(detail.Value, detail.MetadataJSON, result)
+ if !changed {
+ return nil
+ }
+ if err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, newCookies, metadata, time.Now().Unix()); err != nil {
+ return err
+ }
+ a.replaceCredentialState(newCookies, credentialStateFingerprint(newCookies, metadata))
+ a.clearTokenCache(ctx)
+ a.logger.Info("已异步接收官网静默续期迟到 Cookie", "updated", strings.Join(result.UpdatedCookieNames, ","))
+ return nil
+}
+
+// adoptRecoveredCookie 统一接收“轻量检查/接口续期”拿到的新 Cookie。
+// 官网页面在普通 Set-Cookie 更新后保持当前 FishEngine/device ID 与健康 WS;
+// 下一次重连才使用新 Cookie 获取新的连接级 accessToken。
func (a *Account) adoptRecoveredCookie(ctx context.Context, newCookies, source string) bool {
if strings.TrimSpace(newCookies) == "" {
return false
@@ -794,12 +988,14 @@ func (a *Account) adoptRecoveredCookie(ctx context.Context, newCookies, source s
if newCookies == oldCookies {
return false
}
- a.replaceCookieStr(newCookies)
if a.store != nil && a.store.Cookies != nil {
if err := a.store.Cookies.UpdateValueExisting(ctx, a.CookieID, newCookies); err != nil {
a.logger.Error(source+"后保存 cookie 失败", "cookie_id", a.CookieID, "err", err)
+ return false
}
}
+ a.replaceCookieStr(newCookies)
+ a.clearCurrentToken()
a.clearTokenCache(ctx)
a.setRuntimeState(RuntimeConnecting, source+"已更新登录凭证,正在重新连接")
return true
@@ -901,8 +1097,8 @@ func (a *Account) recordShortDisconnect(connectedDuration time.Duration) bool {
}
// refreshToken 调 mtop token API,返回 (accessToken, 更新后的 cookie)。
-// 成功时把 token + device_id 缓存到 DB(saveTokenCache),供进程重启复用与
-// 稳态重连时跳过 mtop(acquireToken 命中缓存即直接返回)。
+// 成功时记录 token 的服务端过期时间并保持 device_id 持久化,但连接流程
+// 不会复用该 token;下一次 loginV2/reConnect 仍会重新调用本方法。
func (a *Account) refreshToken(ctx context.Context) (string, string, error) {
return a.refreshTokenWithMinGap(ctx, false)
}
@@ -912,21 +1108,26 @@ func (a *Account) refreshToken(ctx context.Context) (string, string, error) {
func (a *Account) refreshTokenWithMinGap(ctx context.Context, _ bool) (string, string, error) {
a.refreshMu.Lock()
defer a.refreshMu.Unlock()
+ credentialUnlock := func() {}
+ if a.store != nil {
+ credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
+ }
+ defer credentialUnlock()
+
+ // refreshMu serializes the complete token/Cookie update transaction for an
+ // account. A failed automatic verification also suppresses repeated token API
+ // calls until the caller-side cooldown expires.
+ if remaining := a.tokenCaptchaCooldownRemaining(); remaining > 0 {
+ a.setLastTokenStatus(tokenRefreshSkippedCooldown)
+ return "", "", fmt.Errorf("%w,剩余 %s", errTokenCaptchaCooldown, remaining.Round(time.Second))
+ }
- // 只有 acquireToken 已确认缓存未命中后,才读取数据库里的最新 Cookie。
a.reloadCookieFromDB(ctx)
a.mu.Lock()
cookieStr := a.CookieStr
- lastMsg := a.lastMsgReceived
a.lastTokenRefresh = time.Now()
a.lastTokenStatus = tokenRefreshStarted
- if !lastMsg.IsZero() && time.Since(lastMsg) < MessageCooldown {
- a.lastTokenStatus = tokenRefreshSkippedCooldown
- a.mu.Unlock()
- a.logger.Info("收到消息冷却中,跳过 token/cookie 刷新", "cooldown", MessageCooldown)
- return "", "", fmt.Errorf("收到消息冷却中,跳过 token/cookie 刷新")
- }
a.mu.Unlock()
deviceID := strings.TrimSpace(a.deviceID)
@@ -939,9 +1140,28 @@ func (a *Account) refreshTokenWithMinGap(ctx context.Context, _ bool) (string, s
}
}
for captchaRetry := 0; captchaRetry < 3; captchaRetry++ {
- res, err := a.mtop.RefreshTokenWithDeviceIDContext(ctx, cookieStr, deviceID)
- // 参考实现无论业务结果为何,都先合并并持久化响应 Set-Cookie。
- cookieStr = a.adoptTokenResponseCookies(ctx, cookieStr, res)
+ var res *mtop.RefreshResult
+ var err error
+ if scoped, ok := a.mtop.(scopedTokenClient); ok {
+ var snapshot []cookierefresh.BrowserCookie
+ if a.store != nil && a.store.Cookies != nil {
+ if detail, detailErr := a.store.Cookies.GetDetails(ctx, a.CookieID); detailErr == nil && detail != nil {
+ snapshot = cookierefresh.SnapshotFromMetadata(detail.MetadataJSON)
+ }
+ }
+ res, err = scoped.RefreshTokenWithCredentialContext(ctx, cookieStr, deviceID, snapshot)
+ } else {
+ res, err = a.mtop.RefreshTokenWithDeviceIDContext(ctx, cookieStr, deviceID)
+ }
+ // 参考实现无论业务结果为何,都先合并响应 Set-Cookie。本地还必须先把
+ // 完整 Jar 持久化成功,避免当前 /reg 成功而下次重连回滚到旧凭证。
+ var persistErr error
+ cookieStr, persistErr = a.adoptTokenResponseCookies(ctx, cookieStr, res)
+ if persistErr != nil {
+ a.setLastTokenStatus(tokenRefreshFailedAPI)
+ a.clearCurrentToken()
+ return "", "", fmt.Errorf("保存 token 响应 Cookie: %w", persistErr)
+ }
if err != nil && mtop.IsRiskVerificationErr(err) {
if recovered, ok := a.tryTokenCaptchaRecovery(ctx, cookieStr, deviceID, err); ok {
cookieStr = recovered.UpdatedCookies
@@ -949,6 +1169,7 @@ func (a *Account) refreshTokenWithMinGap(ctx context.Context, _ bool) (string, s
// 它会清缓存后重新走一次标准 token 请求。
continue
}
+ a.markTokenCaptchaFailure()
a.setLastTokenStatus(tokenRefreshFailedCaptcha)
a.clearCurrentToken()
a.clearTokenCache(ctx)
@@ -969,9 +1190,19 @@ func (a *Account) refreshTokenWithMinGap(ctx context.Context, _ bool) (string, s
a.clearTokenCache(ctx)
return "", "", fmt.Errorf("token API 未返回结果")
}
- a.saveTokenCache(ctx, deviceID, res.AccessToken)
+ credentialFP, fingerprintErr := a.databaseCredentialFingerprint(ctx, cookieStr)
+ if fingerprintErr != nil {
+ a.setLastTokenStatus(tokenRefreshFailedAPI)
+ a.clearCurrentToken()
+ a.clearTokenCache(ctx)
+ return "", "", fmt.Errorf("绑定 token 凭证状态: %w", fingerprintErr)
+ }
+ a.saveTokenCache(ctx, deviceID, res.AccessToken, res.AccessTokenExpireAt, credentialFP)
a.mu.Lock()
+ a.credentialFP = credentialFP
+ a.tokenCredentialFP = credentialFP
a.lastMsgReceived = time.Time{}
+ a.lastCaptchaFailure = time.Time{}
a.tokenFetchFailures = 0
a.lastTokenStatus = tokenRefreshSuccess
a.mu.Unlock()
@@ -987,20 +1218,53 @@ func (a *Account) refreshTokenWithMinGap(ctx context.Context, _ bool) (string, s
func (a *Account) clearCurrentToken() {
a.mu.Lock()
a.currentToken = ""
+ a.tokenCredentialFP = ""
a.mu.Unlock()
}
-func (a *Account) adoptTokenResponseCookies(ctx context.Context, cookieStr string, res *mtop.RefreshResult) string {
- if res == nil || strings.TrimSpace(res.UpdatedCookies) == "" || res.UpdatedCookies == cookieStr {
- return cookieStr
+func (a *Account) adoptTokenResponseCookies(ctx context.Context, cookieStr string, res *mtop.RefreshResult) (string, error) {
+ if res == nil {
+ return cookieStr, nil
+ }
+ if !res.CookieSnapshotComplete && !res.CookieStateChanged && strings.TrimSpace(res.UpdatedCookies) == "" {
+ return cookieStr, nil
+ }
+ if !res.CookieSnapshotComplete && !res.CookieStateChanged && res.UpdatedCookies == cookieStr && len(res.CookieSnapshot) == 0 {
+ return cookieStr, nil
}
- a.replaceCookieStr(res.UpdatedCookies)
if a.store != nil && a.store.Cookies != nil {
- if err := a.store.Cookies.UpdateValueExisting(ctx, a.CookieID, res.UpdatedCookies); err != nil {
- a.logger.Error("token 响应后保存 cookie 失败", "cookie_id", a.CookieID, "err", err)
+ detail, detailErr := a.store.Cookies.GetDetails(ctx, a.CookieID)
+ if detailErr != nil {
+ return cookieStr, detailErr
}
+ if detail == nil {
+ return cookieStr, db.ErrNotFound
+ }
+ metadata := detail.MetadataJSON
+ if res.CookieSnapshotComplete {
+ snapshot := cookierefresh.NormalizeSnapshot(res.CookieSnapshot)
+ if snapshot == nil {
+ snapshot = []cookierefresh.BrowserCookie{}
+ }
+ metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot)
+ } else if snapshot, snapshotOK := cookierefresh.SnapshotFromMetadataOK(metadata); snapshotOK {
+ // 扁平结果不能凭空证明 Jar 完整;仅在已有权威 Jar 时按已知
+ // Domain/Path 身份对值做兼容合并。
+ snapshot = cookierefresh.ReconcileSnapshotWithCookieString(snapshot, res.UpdatedCookies)
+ metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot)
+ } else {
+ metadata = cookierefresh.MetadataWithoutSnapshot(metadata)
+ }
+ if err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, res.UpdatedCookies, metadata, time.Now().Unix()); err != nil {
+ return cookieStr, err
+ }
+ a.replaceCredentialState(res.UpdatedCookies, credentialStateFingerprint(res.UpdatedCookies, metadata))
+ return res.UpdatedCookies, nil
}
- return res.UpdatedCookies
+ if res.UpdatedCookies != cookieStr {
+ a.replaceCookieStr(res.UpdatedCookies)
+ }
+ return res.UpdatedCookies, nil
}
func (a *Account) tryTokenCaptchaRecovery(ctx context.Context, cookieStr, deviceID string, err error) (*mtop.RefreshResult, bool) {
@@ -1018,51 +1282,55 @@ func (a *Account) tryTokenCaptchaRecovery(ctx context.Context, cookieStr, device
if !ok || result == nil || strings.TrimSpace(result.UpdatedCookies) == "" {
return nil, false
}
- a.replaceCookieStr(result.UpdatedCookies)
- if a.store != nil && a.store.Cookies != nil {
- if err := a.store.Cookies.UpdateValueExisting(ctx, a.CookieID, result.UpdatedCookies); err != nil {
- a.logger.Error("滑块验证后保存 cookie 失败", "cookie_id", a.CookieID, "err", err)
- return nil, false
- }
+ updatedCookies, persistErr := a.adoptTokenResponseCookies(ctx, cookieStr, result)
+ if persistErr != nil {
+ a.logger.Error("滑块验证后保存 cookie 失败", "cookie_id", a.CookieID, "err", persistErr)
+ return nil, false
}
+ result.UpdatedCookies = updatedCookies
+ a.replaceCookieStr(updatedCookies)
a.clearTokenCache(ctx)
a.setRuntimeState(RuntimeConnecting, tokenRiskRecoveryMessage)
return result, true
}
-// acquireToken 取用于 WS /reg 的 accessToken:缓存命中且未过期则跳过 mtop(降低风控
-// 与瞬时失败影响),否则调 refreshToken 重新派生并落库缓存。
-//
-// 设计:稳态重连时复用未过期缓存 token,避免每次重连都打 mtop(降低风控触发)。
-// 缓存 token 若已被服务端失效,dial 后会短连接断开 → clearTokenCache → 下轮重新派生,自愈。
+func (a *Account) markTokenCaptchaFailure() {
+ a.mu.Lock()
+ a.lastCaptchaFailure = time.Now()
+ a.mu.Unlock()
+}
+
+func (a *Account) tokenCaptchaCooldownRemaining() time.Duration {
+ a.mu.Lock()
+ lastFailure := a.lastCaptchaFailure
+ a.mu.Unlock()
+ if lastFailure.IsZero() {
+ return 0
+ }
+ remaining := TokenCaptchaFailureCooldown - time.Since(lastFailure)
+ if remaining < 0 {
+ return 0
+ }
+ return remaining
+}
+
+// acquireToken is kept for internal callers and tests, but intentionally does
+// not reuse the persisted accessToken. Official web reconnects always invoke
+// the login.token API before /reg.
func (a *Account) acquireToken(ctx context.Context) (string, string, error) {
return a.acquireTokenWithMinGap(ctx, false)
}
-// acquireRuntimeToken 对齐参考主循环:网络重连时只要内存 token 仍存在就直接
-// 复用;只有认证分支明确清空它后,才重新检查数据库缓存或调用 Token API。
+// acquireRuntimeToken is retained as a compatibility wrapper for focused
+// tests and older internal callers. It follows the same fresh-token rule.
func (a *Account) acquireRuntimeToken(ctx context.Context) (string, string, error) {
- a.mu.Lock()
- token := a.currentToken
- cookieStr := a.CookieStr
- a.mu.Unlock()
- if strings.TrimSpace(token) != "" {
- return token, cookieStr, nil
- }
- return a.acquireToken(ctx)
+ return a.acquireFreshConnectionToken(ctx)
}
func (a *Account) acquireTokenWithMinGap(ctx context.Context, _ bool) (string, string, error) {
- if token, ok := a.cachedTokenIfFresh(ctx); ok {
- a.mu.Lock()
- a.currentToken = token
- a.lastTokenRefresh = time.Now()
- a.lastTokenStatus = tokenRefreshSuccessFromCache
- cookieStr := a.CookieStr
- a.mu.Unlock()
- a.logger.Info("使用缓存的 accessToken,跳过 mtop 刷新")
- return token, cookieStr, nil
- }
+ // Invalidate any access token left by an older process/attempt before asking
+ // MTOP for the token that will be bound to this connection.
+ a.clearTokenCache(ctx)
return a.refreshToken(ctx)
}
@@ -1098,37 +1366,20 @@ func tokenFailureIsNonCounted(status string) bool {
}
}
-// cachedTokenIfFresh 返回未过期的缓存 accessToken。无缓存 / 已过期返回 ok=false。
-func (a *Account) cachedTokenIfFresh(ctx context.Context) (string, bool) {
- if a.store == nil || a.store.Tokens == nil {
- return "", false
- }
- tk, err := a.store.Tokens.Get(ctx, a.CookieID)
- if err != nil {
- return "", false
- }
- if tk.AccessToken == "" || tk.ExpireAt <= time.Now().Unix() {
- // 参考实现发现过期缓存后立即删除整行,再进入标准 token 请求。
- if tk.ExpireAt <= time.Now().Unix() {
- a.clearTokenCache(ctx)
- }
- return "", false
- }
- // 命中缓存时同步复用其 device_id,保证 token 与 /reg.did 一致。
- if tk.DeviceID != "" {
- a.mu.Lock()
- a.deviceID = tk.DeviceID
- a.mu.Unlock()
- }
- return tk.AccessToken, true
-}
-
-// saveTokenCache 把 accessToken + device_id 缓存到 DB(expire_at = now + tokenCacheTTL)。
-func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken string) {
+// saveTokenCache records the server expiry and current page-runtime identity.
+// It is diagnostic state only: acquireToken never reads the accessToken back
+// for a later WebSocket registration.
+func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken string, serverExpireAt int64, credentialFP string) {
if a.store == nil || a.store.Tokens == nil || accessToken == "" {
return
}
- if err := a.store.Tokens.Save(ctx, a.CookieID, deviceID, accessToken, time.Now().Add(tokenCacheTTL()).Unix()); err != nil {
+ expireAt := effectiveTokenExpireAt(serverExpireAt, time.Now())
+ if expireAt == 0 {
+ a.logger.Warn("token API 未返回可用过期时间,本次 token 不持久化")
+ a.clearTokenCache(ctx)
+ return
+ }
+ if err := a.store.Tokens.SaveBound(ctx, a.CookieID, deviceID, accessToken, expireAt, credentialFP); err != nil {
a.logger.Warn("缓存 accessToken 失败", "err", err)
}
}
@@ -1143,164 +1394,84 @@ func (a *Account) clearTokenCache(ctx context.Context) {
}
}
-// reloadCookieFromDB 复读 DB cookie:与内存不同则采纳,并清 token 缓存(新 cookie 对应
-// 新 session,旧 token 作废)。让运行中账号吸收外部更新(人工重新扫码 / refreshAccountProfile)。
-func (a *Account) reloadCookieFromDB(ctx context.Context) {
+// databaseCredentialFingerprint returns the complete DB credential state that
+// produced cookieStr. It must be called while the account credential lock is
+// held when a Store is present.
+func (a *Account) databaseCredentialFingerprint(ctx context.Context, cookieStr string) (string, error) {
if a.store == nil || a.store.Cookies == nil {
- return
+ return credentialStateFingerprint(cookieStr, ""), nil
+ }
+ detail, err := a.store.Cookies.GetDetails(ctx, a.CookieID)
+ if err != nil {
+ return "", err
+ }
+ if detail == nil {
+ return "", db.ErrNotFound
+ }
+ _, snapshotComplete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
+ if strings.TrimSpace(detail.Value) == "" && !snapshotComplete {
+ return "", fmt.Errorf("数据库 Cookie 为空且没有权威 Jar")
+ }
+ if credentialCookieFingerprint(detail.Value) != credentialCookieFingerprint(cookieStr) {
+ return "", fmt.Errorf("token 请求期间数据库 Cookie 已变化")
+ }
+ return credentialStateFingerprint(detail.Value, detail.MetadataJSON), nil
+}
+
+// reloadCookieFromDB 复读 DB cookie:与内存不同则采纳,并清 token 缓存。普通 Cookie
+// 更新不轮换页面生命周期内的 device ID;显式登录由 Manager 重建 Account。
+func (a *Account) reloadCookieFromDB(ctx context.Context) bool {
+ if a.store == nil || a.store.Cookies == nil {
+ return false
}
d, err := a.store.Cookies.GetDetails(ctx, a.CookieID)
- if err != nil || d == nil || d.Value == "" {
- return
+ if err != nil || d == nil {
+ return false
}
+ if strings.TrimSpace(d.Value) == "" {
+ if _, complete := cookierefresh.SnapshotFromMetadataOK(d.MetadataJSON); !complete {
+ return false
+ }
+ }
+ databaseFP := credentialStateFingerprint(d.Value, d.MetadataJSON)
a.mu.Lock()
- cur := a.CookieStr
+ currentFP := a.credentialFP
+ if currentFP == "" {
+ currentFP = credentialStateFingerprint(a.CookieStr, "")
+ }
a.mu.Unlock()
- if d.Value == cur {
- return
+ if databaseFP == currentFP {
+ return false
}
a.logger.Info("检测到 DB cookie 已更新,重新加载", "account", a.CookieID)
- a.replaceCookieStr(d.Value)
+ a.replaceCredentialState(d.Value, databaseFP)
+ a.clearCurrentToken()
a.clearTokenCache(ctx)
-}
-
-func (a *Account) activeConnection(fallback WSConn) WSConn {
- if fallback != nil {
- return fallback
- }
a.mu.Lock()
- defer a.mu.Unlock()
- return a.conn
+ a.lastCaptchaFailure = time.Time{}
+ a.mu.Unlock()
+ return true
}
-// tokenRefreshLoop 在 WS 在线期间按 TokenRefreshInterval 定时刷新 token。
-// 刷新失败不重连(让心跳/接收循环去判定),仅记录日志;session 过期会触发
-// 接收循环断开,主循环再走 handleMaxFailures 兜底。
-func (a *Account) tokenRefreshLoop(ctx context.Context, conn WSConn) {
- ticker := time.NewTicker(TokenRefreshInterval)
- defer ticker.Stop()
- for {
- select {
- case <-ctx.Done():
- return
- case <-ticker.C:
- }
- if ctx.Err() != nil {
- return
- }
- token, _, err := a.refreshToken(ctx)
- if err != nil {
- a.logger.Warn("定时刷新 token 失败", "err", err)
- if mtop.IsSessionExpiredErr(err) {
- // session 失效:清缓存,让接收循环尽快断开走兜底,主动关闭连接。
- a.mu.Lock()
- a.currentToken = ""
- a.mu.Unlock()
- a.clearTokenCache(ctx)
- if currentConn := a.activeConnection(conn); currentConn != nil {
- _ = currentConn.Close()
- }
- }
- continue
- }
- a.applyOnlineToken(a.activeConnection(conn), token, false)
- a.logger.Info("定时刷新 token 成功")
- }
-}
-
-// cookieRefreshLoop 与参考实现保持一致:每 60 秒检查一次,满 180 秒检查登录
-// 凭证;收到消息后 5 分钟内跳过;失败 5 秒后只重试一次。检查优先命中
-// 5-10 小时 token 缓存,不会每 180 秒请求 mtop。
-func (a *Account) cookieRefreshLoop(ctx context.Context, conn WSConn) {
- for {
- if ctx.Err() != nil {
- return
- }
- a.mu.Lock()
- lastRefresh := a.lastCookieRefresh
- lastMsg := a.lastMsgReceived
- a.mu.Unlock()
- if time.Since(lastRefresh) >= CookieRefreshInterval {
- if !lastMsg.IsZero() && time.Since(lastMsg) < MessageCooldown {
- a.logger.Info("收到消息冷却中,跳过在线 cookie 刷新", "cooldown", MessageCooldown)
- } else if !a.runOnlineCookieRefresh(ctx, conn, 5*time.Second) {
- return
- }
- }
- // 参考实现每轮处理完成后再等待 60 秒,而不是启动后先等待。
- if sleepCtx(ctx, CookieRefreshCheckInterval) != nil {
- return
- }
- }
-}
-
-// runOnlineCookieRefresh 完成参考实现的一轮在线检查。第一次失败后只在 5 秒后
-// 重试一次;第二次仍失败也推进 lastCookieRefresh,防止之后每 60 秒重复触发。
-// 返回 false 仅表示 context 已取消,调用方应退出循环。
-func (a *Account) runOnlineCookieRefresh(ctx context.Context, conn WSConn, retryDelay time.Duration) bool {
- defer func() {
- a.mu.Lock()
- a.lastMsgReceived = time.Time{}
- a.mu.Unlock()
- }()
- if a.refreshOnlineCookie(ctx, conn, true) {
+func (a *Account) cookieSnapshotMatchesDB(ctx context.Context, expectedFP string) bool {
+ if a.store == nil || a.store.Cookies == nil {
return true
}
- if sleepCtx(ctx, retryDelay) != nil {
+ detail, err := a.store.Cookies.GetDetails(ctx, a.CookieID)
+ if err != nil || detail == nil {
+ a.logger.Warn("WS 注册前读取最新 Cookie 失败,放弃本次连接", "err", err)
return false
}
- if !a.refreshOnlineCookie(ctx, conn, false) {
- a.mu.Lock()
- a.lastCookieRefresh = time.Now()
- a.mu.Unlock()
- }
- return true
-}
-
-func (a *Account) refreshOnlineCookie(ctx context.Context, conn WSConn, enforceMinGap bool) bool {
- // 参考实现的 refresh_token 会先查 5-10 小时缓存;这里必须走 acquireToken,
- // 不能直接 refreshToken,否则 180 秒检查会退化为 180 秒一次 mtop 请求。
- token, _, err := a.acquireTokenWithMinGap(ctx, enforceMinGap)
- if err != nil {
- a.logger.Warn("在线 cookie 刷新失败", "err", err)
- if mtop.IsSessionExpiredErr(err) {
- a.mu.Lock()
- a.currentToken = ""
- a.mu.Unlock()
- a.clearTokenCache(ctx)
- if currentConn := a.activeConnection(conn); currentConn != nil {
- _ = currentConn.Close()
- }
- }
+ _, snapshotComplete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
+ if strings.TrimSpace(detail.Value) == "" && !snapshotComplete {
+ a.logger.Warn("WS 注册前最新 Cookie 为空且没有权威 Jar,放弃本次连接")
return false
}
- a.applyOnlineToken(a.activeConnection(conn), token, true)
- a.logger.Info("在线 cookie 刷新成功")
- return true
-}
-
-// applyOnlineToken 把刷新后的 token 应用到当前 WS。在线刷新 goroutine 会在
-// Run 清理 a.conn 之前退出,因此连接仍存在且状态仍是本轮风控恢复提示时,可以
-// 安全恢复为 online;这不改变 token 获取、续期或重试时序。
-func (a *Account) applyOnlineToken(conn WSConn, token string, markCookieRefresh bool) {
- a.mu.Lock()
- a.currentToken = token
- if markCookieRefresh {
- a.lastCookieRefresh = time.Now()
- }
- a.mu.Unlock()
-
- if conn != nil {
- conn.SetAccessToken(token)
- }
-
- a.mu.Lock()
- defer a.mu.Unlock()
- if a.conn != nil && a.runtimeState == RuntimeConnecting && a.runtimeMessage == tokenRiskRecoveryMessage {
- a.runtimeState = RuntimeOnline
- a.runtimeMessage = "消息服务连接正常"
- a.runtimeUpdatedAt = time.Now()
+ if expectedFP == "" {
+ a.logger.Warn("WS 注册 token 缺少绑定的凭证状态,放弃本次连接")
+ return false
}
+ return credentialStateFingerprint(detail.Value, detail.MetadataJSON) == expectedFP
}
// RuntimeStatus 返回账号当前连接状态的线程安全快照。
@@ -1326,7 +1497,9 @@ func (a *Account) setRuntimeState(state, message string) {
func (a *Account) setRuntimeError(ctx context.Context, err error) {
msg := strings.ToLower(errString(err))
+ a.mu.Lock()
prev := a.runtimeState
+ a.mu.Unlock()
switch {
case strings.Contains(msg, "验证"), strings.Contains(msg, "captcha"), strings.Contains(msg, "risk"), strings.Contains(msg, "rgv587"), strings.Contains(msg, "fail_sys_user_validate"):
a.setRuntimeState(RuntimeVerificationRequired, "闲鱼要求安全验证,请重新扫码并完成验证")
@@ -1392,18 +1565,71 @@ func (a *Account) currentSenderState() (WSConn, string, error) {
}
func (a *Account) replaceCookieStr(cookieStr string) {
+ a.replaceCredentialState(cookieStr, credentialStateFingerprint(cookieStr, ""))
+}
+
+func (a *Account) replaceCredentialState(cookieStr, credentialFP string) {
a.mu.Lock()
defer a.mu.Unlock()
a.CookieStr = cookieStr
+ a.credentialFP = credentialFP
if unb := protocol.TransCookies(cookieStr)["unb"]; unb != "" {
a.UserID = unb
}
}
+// rotatePageDeviceID 对应官网 auto-login 成功后的 location.reload():
+// 新 FishEngine 使用新的 UUID-userID,普通 Set-Cookie 与自然重连不会调用它。
+func (a *Account) rotatePageDeviceID() {
+ a.mu.Lock()
+ userID := a.UserID
+ if userID == "" {
+ userID = protocol.TransCookies(a.CookieStr)["unb"]
+ }
+ a.deviceID = protocol.GenerateDeviceID(userID)
+ a.mu.Unlock()
+}
+
// UpdateCookie 用外部刷新得到的新 cookie 更新运行时状态。
func (a *Account) UpdateCookie(cookieStr string) {
- if strings.TrimSpace(cookieStr) == "" {
+ if strings.TrimSpace(cookieStr) == "" && (a.store == nil || a.store.Cookies == nil) {
return
}
- a.replaceCookieStr(cookieStr)
+ a.refreshMu.Lock()
+ defer a.refreshMu.Unlock()
+ credentialUnlock := func() {}
+ if a.store != nil {
+ credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
+ }
+ defer credentialUnlock()
+ // 外部调用通常发生在一次网络请求写回之后。调用排队期间可能已有更新的
+ // Cookie 落库,因此参数只作为无 Store 场景的兼容值;有 Store 时始终
+ // 复读权威数据库,绝不把较旧的请求结果重新写回运行时。
+ metadataJSON := ""
+ if a.store != nil && a.store.Cookies != nil {
+ detail, err := a.store.Cookies.GetDetails(context.Background(), a.CookieID)
+ if err != nil || detail == nil {
+ a.logger.Warn("同步运行时 Cookie 前读取数据库失败", "err", err)
+ return
+ }
+ if strings.TrimSpace(detail.Value) == "" {
+ if _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); !complete {
+ a.logger.Warn("同步运行时 Cookie 时数据库值为空且无权威 Jar")
+ return
+ }
+ }
+ cookieStr = detail.Value
+ metadataJSON = detail.MetadataJSON
+ }
+ credentialFP := credentialStateFingerprint(cookieStr, metadataJSON)
+ a.mu.Lock()
+ changed := credentialFP != a.credentialFP
+ a.mu.Unlock()
+ if !changed {
+ return
+ }
+ a.replaceCredentialState(cookieStr, credentialFP)
+ // Cookie Jar 的普通更新不会打断已经认证的 IMPaaS 连接。新 Cookie
+ // 会在下一次自然重连前被重新读取并用于获取新的 accessToken。
+ a.clearTokenCache(context.Background())
}
diff --git a/internal/engine/account_extra_test.go b/internal/engine/account_extra_test.go
index a481446..95af357 100644
--- a/internal/engine/account_extra_test.go
+++ b/internal/engine/account_extra_test.go
@@ -4,12 +4,16 @@ import (
"context"
"errors"
"fmt"
+ "net/http"
+ "net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"xianyu-go/internal/automation"
+ "xianyu-go/internal/xianyu"
+ "xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
xrenew "xianyu-go/internal/xianyu/renew"
)
@@ -22,7 +26,7 @@ type riskCountingMTop struct {
func (m *riskCountingMTop) RefreshTokenWithDeviceIDContext(context.Context, string, string) (*mtop.RefreshResult, error) {
m.calls++
if m.calls > 1 {
- return &mtop.RefreshResult{AccessToken: "standard-token", UpdatedCookies: "unb=123; _m_h5_tk=recovered;"}, nil
+ return &mtop.RefreshResult{AccessToken: "standard-token", AccessTokenExpireAt: time.Now().Add(time.Hour).Unix(), UpdatedCookies: "unb=123; _m_h5_tk=recovered;"}, nil
}
return nil, &mtop.RiskVerificationError{Ret: []string{"FAIL_SYS_USER_VALIDATE"}, VerificationURL: "https://verify.example"}
}
@@ -33,6 +37,16 @@ func (h *tokenRecoveredHandler) OnTokenCaptchaVerification(context.Context, stri
return &mtop.RefreshResult{AccessToken: "recovered-token", UpdatedCookies: "unb=123; _m_h5_tk=recovered;"}, true
}
+type rejectingTokenCaptchaHandler struct {
+ recordingHandler
+ calls int
+}
+
+func (h *rejectingTokenCaptchaHandler) OnTokenCaptchaVerification(context.Context, string, string, string, string) (*mtop.RefreshResult, bool) {
+ h.calls++
+ return nil, false
+}
+
type capturingCaptchaHandler struct {
recordingHandler
cookieStr string
@@ -70,7 +84,7 @@ func (m *responseCookieRiskMTop) RefreshTokenWithDeviceIDContext(_ context.Conte
Ret: []string{"FAIL_SYS_USER_VALIDATE"}, VerificationURL: "https://verify.example/punish",
}
}
- return &mtop.RefreshResult{AccessToken: "standard-after-captcha", UpdatedCookies: cookieStr}, nil
+ return &mtop.RefreshResult{AccessToken: "standard-after-captcha", AccessTokenExpireAt: time.Now().Add(time.Hour).Unix(), UpdatedCookies: cookieStr}, nil
}
func TestRefreshTokenRetriesStandardRequestAfterCaptchaRecovery(t *testing.T) {
@@ -93,6 +107,25 @@ func TestRefreshTokenRetriesStandardRequestAfterCaptchaRecovery(t *testing.T) {
}
}
+func TestRefreshTokenCaptchaFailureEntersCallerCooldown(t *testing.T) {
+ acc, _, _, cleanup := newAccountForTest(t)
+ defer cleanup()
+ client := &riskCountingMTop{}
+ handler := &rejectingTokenCaptchaHandler{}
+ acc.mtop = client
+ acc.handler = handler
+
+ if _, _, err := acc.refreshToken(context.Background()); !mtop.IsRiskVerificationErr(err) {
+ t.Fatalf("first refresh error=%v want risk verification", err)
+ }
+ if _, _, err := acc.refreshToken(context.Background()); !errors.Is(err, errTokenCaptchaCooldown) {
+ t.Fatalf("second refresh error=%v want cooldown", err)
+ }
+ if client.calls != 1 || handler.calls != 1 {
+ t.Fatalf("cooldown must suppress repeated API/solver calls: api=%d solver=%d", client.calls, handler.calls)
+ }
+}
+
func TestRefreshTokenPersistsResponseCookiesBeforeCaptchaRecovery(t *testing.T) {
acc, _, store, cleanup := newRunAccount(t, &responseCookieRiskMTop{})
defer cleanup()
@@ -212,7 +245,7 @@ type stubCookieRenewer struct {
got string
}
-func (s *stubCookieRenewer) RenewAPIFirst(_ context.Context, cookiesStr string) (*xrenew.Result, error) {
+func (s *stubCookieRenewer) RenewAPIFirst(_ context.Context, cookiesStr string, _ ...[]cookierefresh.BrowserCookie) (*xrenew.Result, error) {
s.calls++
s.got = cookiesStr
return s.result, s.err
@@ -246,8 +279,8 @@ func TestTryAPIRenewSuccessShortCircuitsRecovery(t *testing.T) {
if saved != "unb=123; _m_h5_tk=tk_2;" {
t.Fatalf("DB cookie 未更新: %q", saved)
}
- if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
- t.Fatalf("接口续期后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
+ if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" {
+ t.Fatalf("接口续期后应清 token;数据库中的旧 device ID 不再参与运行时身份: tk=%+v err=%v", tk, err)
}
}
@@ -263,6 +296,7 @@ func TestTryAPIRenewPartialCookiesContinueRecovery(t *testing.T) {
RenewMethod: "none",
NewCookies: "unb=123; _m_h5_tk=partial;",
UpdatedCookieNames: []string{"_m_h5_tk"},
+ SetCookies: []string{"_m_h5_tk=partial; Domain=.goofish.com; Path=/; Secure; HttpOnly"},
Message: "setLoginSettings 未返回 Set-Cookie",
}}
acc.renewer = renewer
@@ -277,9 +311,94 @@ func TestTryAPIRenewPartialCookiesContinueRecovery(t *testing.T) {
if saved != "unb=123; _m_h5_tk=partial;" {
t.Fatalf("部分 cookie 应先保存到 DB: %q", saved)
}
- if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
- t.Fatalf("部分 cookie 更新后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
+ if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" {
+ t.Fatalf("部分 cookie 更新后应清 token: tk=%+v err=%v", tk, err)
}
+ detail, err := store.Cookies.GetDetails(ctx, "cid")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
+ t.Fatal("接口扁平 Cookie 更新不得伪造成完整浏览器 Jar")
+ }
+}
+
+func TestTryAPIRenewPersistsExplicitFlatCookieDeletionOnError(t *testing.T) {
+ acc, _, store, cleanup := newAccountForTest(t)
+ defer cleanup()
+ ctx := context.Background()
+ if err := store.Tokens.Save(ctx, "cid", "did-old", "tok-old", time.Now().Add(time.Hour).Unix()); err != nil {
+ t.Fatalf("save token: %v", err)
+ }
+ acc.renewer = &stubCookieRenewer{
+ result: &xrenew.Result{
+ NewCookies: "",
+ SetCookies: []string{
+ "unb=; Domain=.goofish.com; Path=/; Max-Age=0",
+ "_m_h5_tk=; Domain=.goofish.com; Path=/; Max-Age=0",
+ },
+ },
+ err: errors.New("续期响应正文损坏"),
+ }
+
+ if acc.tryAPIRenew(ctx) {
+ t.Fatal("失败响应即使带 Cookie 删除也不应视为续期成功")
+ }
+ if got := acc.currentCookieStr(); got != "" {
+ t.Fatalf("运行时应采用服务端明确删除后的空 Cookie,got %q", got)
+ }
+ detail, err := store.Cookies.GetDetails(ctx, "cid")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if detail.Value != "" {
+ t.Fatalf("数据库应保存明确删除后的空 Cookie,got %q", detail.Value)
+ }
+ if _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
+ t.Fatal("扁平删除结果不得伪造成完整浏览器 Jar")
+ }
+ if token, err := store.Tokens.Get(ctx, "cid"); err != nil || token.AccessToken != "" {
+ t.Fatalf("Cookie 删除后应清理旧 token: token=%+v err=%v", token, err)
+ }
+}
+
+func TestTryAPIRenewPersistsLatePromiseCookieWithoutRestart(t *testing.T) {
+ acc, _, store, cleanup := newAccountForTest(t)
+ defer cleanup()
+ ctx := context.Background()
+ oldFingerprint := xianyu.CurrentBrowserFingerprint()
+ xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "Mozilla/5.0 (Macintosh) Chrome/999.0.0.0 Safari/537.36"})
+ t.Cleanup(func() { xianyu.SetBrowserFingerprint(oldFingerprint) })
+ initial := "unb=123; havana_lgc_exp=" + fmt.Sprint(time.Now().Add(time.Hour).UnixMilli())
+ if err := store.Cookies.UpdateValueExisting(ctx, "cid", initial); err != nil {
+ t.Fatal(err)
+ }
+ acc.replaceCookieStr(initial)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ time.Sleep(60 * time.Millisecond)
+ http.SetCookie(w, &http.Cookie{Name: "sdkSilent", Value: fmt.Sprint(time.Now().Add(time.Hour).UnixMilli()), Path: "/"})
+ _, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
+ }))
+ defer srv.Close()
+ acc.renewer = xrenew.Service{
+ HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1,
+ PromiseTimeout: 10 * time.Millisecond,
+ }
+ if acc.tryAPIRenew(ctx) {
+ t.Fatal("Promise 超时不得伪装成同步续期成功")
+ }
+ deadline := time.Now().Add(time.Second)
+ for time.Now().Before(deadline) {
+ detail, err := store.Cookies.GetDetails(ctx, "cid")
+ if err == nil && detail != nil && strings.Contains(detail.Value, "sdkSilent=") {
+ if !strings.Contains(acc.currentCookieStr(), "sdkSilent=") {
+ t.Fatalf("迟到 Cookie 已入库但未更新运行时: %q", acc.currentCookieStr())
+ }
+ return
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ t.Fatal("迟到的 silentHasLogin Set-Cookie 未写回账号")
}
// TestSetRuntimeError_AllBranches 覆盖验证/captcha、token 失效、默认重连三分支
@@ -665,7 +784,7 @@ func TestReplaceCookieStr_NoUnbNoChange(t *testing.T) {
// TestUpdateCookie_IgnoresEmpty 纯空白/空字符串被忽略,不覆盖现有 cookie。
func TestUpdateCookie_IgnoresEmpty(t *testing.T) {
- acc, _, _, cleanup := newAccountForTest(t)
+ acc, _, store, cleanup := newAccountForTest(t)
defer cleanup()
orig := acc.currentCookieStr()
@@ -677,22 +796,187 @@ func TestUpdateCookie_IgnoresEmpty(t *testing.T) {
t.Errorf("空白 cookie 不应更新: got %q want %q", got, orig)
}
- // 非空(即使含首尾空白)应原样存储——UpdateCookie 只做空值检查,不做 trim。
- acc.UpdateCookie("unb=123; _m_h5_tk=tk_new;")
- if got := acc.currentCookieStr(); got != "unb=123; _m_h5_tk=tk_new;" {
+ acc.mu.Lock()
+ originalDevice := acc.deviceID
+ healthyConn := &fakeWSConn{}
+ acc.conn = healthyConn
+ acc.mu.Unlock()
+
+ // 非空(即使含首尾空白)应原样存储,但不能模拟页面 reload 去打断健康 WS。
+ updated := "unb=123; _m_h5_tk=tk_new;"
+ if err := store.Cookies.UpdateValueExisting(context.Background(), acc.CookieID, updated); err != nil {
+ t.Fatal(err)
+ }
+ acc.UpdateCookie(updated)
+ if got := acc.currentCookieStr(); got != updated {
t.Errorf("非空 cookie 应更新: got %q", got)
}
+ acc.mu.Lock()
+ currentDevice := acc.deviceID
+ acc.mu.Unlock()
+ healthyConn.mu.Lock()
+ closed := healthyConn.closed
+ healthyConn.mu.Unlock()
+ if currentDevice != originalDevice || closed {
+ t.Fatalf("普通 Cookie 更新不应轮换 device ID 或关闭健康连接: device=%q/%q closed=%v", currentDevice, originalDevice, closed)
+ }
+}
+
+func TestUpdateCookie_AcceptsAuthoritativeEmptySnapshot(t *testing.T) {
+ acc, _, store, cleanup := newAccountForTest(t)
+ defer cleanup()
+ metadata := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{})
+ if err := store.Cookies.UpdateRenewalCookie(context.Background(), acc.CookieID, "", metadata, time.Now().Unix()); err != nil {
+ t.Fatal(err)
+ }
+ acc.UpdateCookie("")
+ if got := acc.currentCookieStr(); got != "" {
+ t.Fatalf("权威空 Jar 应清空运行时 Cookie,got %q", got)
+ }
+}
+
+func TestReloadCookieFromDBDetectsMetadataOnlyCredentialRotation(t *testing.T) {
+ acc, _, store, cleanup := newAccountForTest(t)
+ defer cleanup()
+ ctx := context.Background()
+ flat := acc.currentCookieStr()
+ metadataA := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
+ {Name: "_m_h5_tk", Value: "path-a", Domain: ".goofish.com", Path: "/im"},
+ })
+ if err := store.Cookies.UpdateRenewalCookie(ctx, acc.CookieID, flat, metadataA, time.Now().Unix()); err != nil {
+ t.Fatal(err)
+ }
+ if !acc.reloadCookieFromDB(ctx) {
+ t.Fatal("首次权威 Jar 应同步到运行时")
+ }
+ acc.mu.Lock()
+ boundFP := acc.credentialFP
+ acc.currentToken = "old-token"
+ acc.tokenCredentialFP = boundFP
+ acc.mu.Unlock()
+ if err := store.Tokens.SaveBound(ctx, acc.CookieID, acc.deviceID, "old-token", time.Now().Add(time.Hour).Unix(), boundFP); err != nil {
+ t.Fatal(err)
+ }
+
+ metadataB := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
+ {Name: "_m_h5_tk", Value: "path-b", Domain: ".goofish.com", Path: "/im"},
+ })
+ if err := store.Cookies.UpdateRenewalCookie(ctx, acc.CookieID, flat, metadataB, time.Now().Unix()); err != nil {
+ t.Fatal(err)
+ }
+ if !acc.reloadCookieFromDB(ctx) {
+ t.Fatal("扁平 Cookie 未变但权威 Jar 已变化时必须重新加载")
+ }
+ acc.mu.Lock()
+ currentToken := acc.currentToken
+ currentFP := acc.credentialFP
+ acc.mu.Unlock()
+ if currentToken != "" {
+ t.Fatalf("Jar 变化后应清内存 token,got %q", currentToken)
+ }
+ if currentFP != credentialStateFingerprint(flat, metadataB) {
+ t.Fatal("运行时未绑定到最新完整凭证状态")
+ }
+ if cached, err := store.Tokens.Get(ctx, acc.CookieID); err != nil || cached.AccessToken != "" {
+ t.Fatalf("Jar 变化后应清数据库 token: cached=%+v err=%v", cached, err)
+ }
+}
+
+func TestCookieSnapshotMatchesDBUsesCompleteCredentialState(t *testing.T) {
+ acc, _, store, cleanup := newAccountForTest(t)
+ defer cleanup()
+ ctx := context.Background()
+ flat := acc.currentCookieStr()
+ metadataA := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
+ {Name: "sgcookie", Value: "a", Domain: ".goofish.com", Path: "/"},
+ })
+ if err := store.Cookies.UpdateRenewalCookie(ctx, acc.CookieID, flat, metadataA, time.Now().Unix()); err != nil {
+ t.Fatal(err)
+ }
+ expected := credentialStateFingerprint(flat, metadataA)
+ if !acc.cookieSnapshotMatchesDB(ctx, expected) {
+ t.Fatal("相同扁平 Cookie 与权威 Jar 应允许 /reg")
+ }
+ metadataB := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
+ {Name: "sgcookie", Value: "b", Domain: ".goofish.com", Path: "/"},
+ })
+ if err := store.Cookies.UpdateRenewalCookie(ctx, acc.CookieID, flat, metadataB, time.Now().Unix()); err != nil {
+ t.Fatal(err)
+ }
+ if acc.cookieSnapshotMatchesDB(ctx, expected) {
+ t.Fatal("token 获取后 Jar 变化时必须拒绝 /reg")
+ }
+ emptyMetadata := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{})
+ if err := store.Cookies.UpdateRenewalCookie(ctx, acc.CookieID, "", emptyMetadata, time.Now().Unix()); err != nil {
+ t.Fatal(err)
+ }
+ if !acc.cookieSnapshotMatchesDB(ctx, credentialStateFingerprint("", emptyMetadata)) {
+ t.Fatal("完整空 Jar 是权威状态,不应因扁平值为空而被拒绝")
+ }
+}
+
+func TestAdoptIncompleteTokenCookiesDoesNotInventCompleteSnapshot(t *testing.T) {
+ acc, _, store, cleanup := newAccountForTest(t)
+ defer cleanup()
+ ctx := context.Background()
+ updated := "unb=123; _m_h5_tk=flat-only; cookie2=next"
+ got, err := acc.adoptTokenResponseCookies(ctx, acc.currentCookieStr(), &mtop.RefreshResult{
+ UpdatedCookies: updated,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != updated {
+ t.Fatalf("adopted Cookie=%q want %q", got, updated)
+ }
+ detail, err := store.Cookies.GetDetails(ctx, acc.CookieID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
+ t.Fatal("仅有扁平 token 响应时不得伪造成完整浏览器 Jar")
+ }
+}
+
+func TestAdoptTokenResponseCookiesPersistsExplicitDeletionToEmpty(t *testing.T) {
+ acc, _, store, cleanup := newAccountForTest(t)
+ defer cleanup()
+ ctx := context.Background()
+ got, err := acc.adoptTokenResponseCookies(ctx, acc.currentCookieStr(), &mtop.RefreshResult{
+ UpdatedCookies: "",
+ CookieStateChanged: true,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != "" || acc.currentCookieStr() != "" {
+ t.Fatalf("明确删除后的 Cookie 未同步: got=%q runtime=%q", got, acc.currentCookieStr())
+ }
+ detail, err := store.Cookies.GetDetails(ctx, acc.CookieID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if detail.Value != "" {
+ t.Fatalf("数据库 Cookie=%q want empty", detail.Value)
+ }
+ if _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
+ t.Fatal("扁平 token 删除不得伪造成完整浏览器 Jar")
+ }
}
// TestCurrentCookieStr 线程安全返回当前 CookieStr。
func TestCurrentCookieStr(t *testing.T) {
- acc, _, _, cleanup := newAccountForTest(t)
+ acc, _, store, cleanup := newAccountForTest(t)
defer cleanup()
if got := acc.currentCookieStr(); got != "unb=123; _m_h5_tk=tk_1;" {
t.Errorf("currentCookieStr=%q", got)
}
- acc.UpdateCookie("unb=1; x=2;")
- if got := acc.currentCookieStr(); got != "unb=1; x=2;" {
+ updated := "unb=1; x=2;"
+ if err := store.Cookies.UpdateValueExisting(context.Background(), acc.CookieID, updated); err != nil {
+ t.Fatal(err)
+ }
+ acc.UpdateCookie(updated)
+ if got := acc.currentCookieStr(); got != updated {
t.Errorf("更新后 currentCookieStr=%q", got)
}
}
diff --git a/internal/engine/ai.go b/internal/engine/ai.go
index 42ec1dd..0737833 100644
--- a/internal/engine/ai.go
+++ b/internal/engine/ai.go
@@ -54,6 +54,11 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
if err != nil || cfg == nil || !cfg.AIEnabled {
return nil, nil // 未启用 AI
}
+ // AI 设置面向砍价场景。普通未命中消息继续交给默认回复,避免 AI
+ // 抢答问候、售后等与砍价无关的消息。
+ if !bargainMessageRe.MatchString(strings.ToLower(m.Text)) {
+ return nil, nil
+ }
aiCfg, err := a.globalAIConfig(ctx)
if err != nil {
return nil, fmt.Errorf("读取全局 AI 配置失败: %w", err)
diff --git a/internal/engine/ai_test.go b/internal/engine/ai_test.go
index 413728e..5161643 100644
--- a/internal/engine/ai_test.go
+++ b/internal/engine/ai_test.go
@@ -76,7 +76,7 @@ func TestAIReply_DisabledReturnsNil(t *testing.T) {
a := NewAIReplier("cid", s, nil)
// 无配置记录 → 未启用 → nil。
- res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
+ res, err := a.Reply(ctx, chatMsg("能便宜点吗", "item1", "chat1"))
if err != nil || res != nil {
t.Fatalf("未配置应返回 nil,nil: res=%+v err=%v", res, err)
}
@@ -97,7 +97,7 @@ func TestAIReply_NoAPIKeyReturnsNil(t *testing.T) {
s.DB.ExecContext(ctx, `INSERT INTO ai_reply_settings (cookie_id, ai_enabled, custom_prompts) VALUES ('cid', 1, '')`)
a := NewAIReplier("cid", s, nil)
- res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
+ res, err := a.Reply(ctx, chatMsg("能便宜点吗", "item1", "chat1"))
if err != nil || res != nil {
t.Fatalf("无 APIKey 应返回 nil,nil: res=%+v err=%v", res, err)
}
@@ -137,7 +137,7 @@ func TestAIReply_HTTPErrorDegrades(t *testing.T) {
s.Settings.Set(ctx, "ai_api_url", srv.URL)
a := NewAIReplier("cid", s, nil)
- res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
+ res, err := a.Reply(ctx, chatMsg("还能优惠吗", "item1", "chat1"))
if err == nil {
t.Fatalf("HTTP 500 应返回错误,got res=%+v", res)
}
@@ -165,7 +165,7 @@ func TestAIReply_EmptyChoicesReturnsNil(t *testing.T) {
s.Settings.Set(ctx, "ai_api_url", srv.URL)
a := NewAIReplier("cid", s, nil)
- res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
+ res, err := a.Reply(ctx, chatMsg("可以便宜一点吗", "item1", "chat1"))
if err != nil || res != nil {
t.Fatalf("空 choices 应返回 nil,nil: res=%+v err=%v", res, err)
}
@@ -182,7 +182,7 @@ func TestAIReply_SuccessReturnsContent(t *testing.T) {
s.Settings.Set(ctx, "ai_api_url", srv.URL)
a := NewAIReplier("cid", s, nil)
- res, err := a.Reply(ctx, chatMsg("在吗", "item1", "chat1"))
+ res, err := a.Reply(ctx, chatMsg("最低多少钱", "item1", "chat1"))
if err != nil {
t.Fatalf("成功调用不应报错: %v", err)
}
@@ -191,6 +191,20 @@ func TestAIReply_SuccessReturnsContent(t *testing.T) {
}
}
+func TestAIReply_NonBargainMessageFallsThrough(t *testing.T) {
+ s, cleanup := newAIStore(t)
+ defer cleanup()
+ ctx := context.Background()
+ s.DB.ExecContext(ctx, `INSERT INTO ai_reply_settings (cookie_id, ai_enabled, custom_prompts) VALUES ('cid', 1, '')`)
+ s.Settings.Set(ctx, "ai_api_key", "sk-test")
+ s.Settings.Set(ctx, "ai_api_url", "http://127.0.0.1:1")
+
+ res, err := NewAIReplier("cid", s, nil).Reply(ctx, chatMsg("在吗,什么时候发货", "item1", "chat1"))
+ if err != nil || res != nil {
+ t.Fatalf("非砍价消息应交给默认回复: res=%+v err=%v", res, err)
+ }
+}
+
// TestGlobalAIConfig 默认值兜底 + 显式设置覆盖。
func TestGlobalAIConfig(t *testing.T) {
s, cleanup := newAIStore(t)
diff --git a/internal/engine/keepalive_test.go b/internal/engine/keepalive_test.go
index 8fcc8e0..2e2d980 100644
--- a/internal/engine/keepalive_test.go
+++ b/internal/engine/keepalive_test.go
@@ -8,6 +8,7 @@ import (
"testing"
"time"
+ "xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
@@ -19,7 +20,7 @@ type countingMtop struct {
func (c *countingMtop) RefreshTokenWithDeviceIDContext(_ context.Context, _ string, _ string) (*mtop.RefreshResult, error) {
atomic.AddInt32(&c.calls, 1)
- return &mtop.RefreshResult{AccessToken: c.token}, nil
+ return &mtop.RefreshResult{AccessToken: c.token, AccessTokenExpireAt: time.Now().Add(time.Hour).Unix()}, nil
}
type statusMtop struct {
@@ -39,170 +40,12 @@ func (c *failingCountingMtop) RefreshTokenWithDeviceIDContext(_ context.Context,
return nil, c.err
}
-func TestRiskSensitiveRefreshIntervals(t *testing.T) {
- if CookieRefreshInterval != 180*time.Second {
- t.Fatalf("在线 Cookie 检查间隔应与参考实现保持 180 秒,got %s", CookieRefreshInterval)
- }
- if CookieRefreshCheckInterval != time.Minute {
- t.Fatalf("在线 Cookie 循环检查频率应与参考实现保持 60 秒,got %s", CookieRefreshCheckInterval)
- }
- if PasswordLoginMinGap != 60*time.Second {
- t.Fatalf("自动密码登录冷却应与参考运行时保持 60 秒,got %s", PasswordLoginMinGap)
- }
-}
-
-func TestRefreshOnlineCookie_CacheHitSkipsMtop(t *testing.T) {
- mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}}
- acc, _, store, cleanup := newRunAccount(t, mtopClient)
- defer cleanup()
-
- if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok",
- time.Now().Add(time.Hour).Unix()); err != nil {
+func saveBoundToken(t *testing.T, store *db.Store, acc *Account, token string, expireAt int64) {
+ t.Helper()
+ if err := store.Tokens.SaveBound(context.Background(), acc.CookieID, acc.deviceID, token, expireAt,
+ credentialCookieFingerprint(acc.currentCookieStr())); err != nil {
t.Fatal(err)
}
- conn := &fakeWSConn{}
- if !acc.refreshOnlineCookie(context.Background(), conn, true) {
- t.Fatal("缓存命中时在线 Cookie 检查应成功")
- }
- if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 {
- t.Fatalf("180 秒检查命中缓存时不应请求 mtop,got %d", calls)
- }
- acc.mu.Lock()
- currentToken := acc.currentToken
- lastRefresh := acc.lastCookieRefresh
- acc.mu.Unlock()
- if currentToken != "cached-tok" || lastRefresh.IsZero() {
- t.Fatalf("应采用缓存 token 并更新时间,token=%q last_refresh=%s", currentToken, lastRefresh)
- }
-}
-
-func TestCookieRefreshLoopRunsInitialCacheCheckImmediately(t *testing.T) {
- mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}}
- acc, _, store, cleanup := newRunAccount(t, mtopClient)
- defer cleanup()
- if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok",
- time.Now().Add(time.Hour).Unix()); err != nil {
- t.Fatal(err)
- }
- acc.mu.Lock()
- acc.lastCookieRefresh = time.Time{}
- acc.lastMsgReceived = time.Now().Add(-MessageCooldown - time.Second)
- acc.mu.Unlock()
-
- ctx, cancel := context.WithCancel(context.Background())
- done := make(chan struct{})
- go func() {
- defer close(done)
- acc.cookieRefreshLoop(ctx, nil)
- }()
- deadline := time.Now().Add(time.Second)
- for time.Now().Before(deadline) {
- acc.mu.Lock()
- lastRefresh := acc.lastCookieRefresh
- lastMessage := acc.lastMsgReceived
- acc.mu.Unlock()
- if !lastRefresh.IsZero() {
- if !lastMessage.IsZero() {
- t.Fatalf("刷新轮次结束后应清空消息冷却标识: %s", lastMessage)
- }
- break
- }
- time.Sleep(5 * time.Millisecond)
- }
- cancel()
- <-done
- acc.mu.Lock()
- lastRefresh := acc.lastCookieRefresh
- acc.mu.Unlock()
- if lastRefresh.IsZero() {
- t.Fatal("Cookie 刷新循环启动后应立即完成首次缓存检查")
- }
- if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 {
- t.Fatalf("首次检查命中缓存时不应请求 mtop, got %d", calls)
- }
-}
-
-func TestRefreshOnlineCookie_RiskRecoveryRestoresOnlineRuntimeState(t *testing.T) {
- mtopClient := &riskCountingMTop{}
- acc, _, _, cleanup := newRunAccount(t, mtopClient)
- defer cleanup()
- acc.handler = &tokenRecoveredHandler{}
- conn := &fakeWSConn{}
- acc.mu.Lock()
- acc.conn = conn
- acc.runtimeState = RuntimeOnline
- acc.runtimeMessage = "消息服务连接正常"
- acc.runtimeUpdatedAt = time.Now()
- acc.mu.Unlock()
-
- if !acc.refreshOnlineCookie(context.Background(), conn, true) {
- t.Fatal("风控自动恢复成功后在线 Cookie 刷新应成功")
- }
- status := acc.RuntimeStatus()
- if status.State != RuntimeOnline || !status.Connected || status.Message != "消息服务连接正常" {
- t.Fatalf("在线风控恢复后运行态未收敛: %+v", status)
- }
- conn.mu.Lock()
- defer conn.mu.Unlock()
- if len(conn.tokens) != 1 || conn.tokens[0] != "standard-token" {
- t.Fatalf("恢复 token 未更新到现有连接: %+v", conn.tokens)
- }
-}
-
-func TestApplyOnlineToken_PeriodicRefreshRestoresRuntimeWithoutChangingCookieSchedule(t *testing.T) {
- acc, _, _, cleanup := newRunAccount(t, &fakeRunMtop{token: "unused"})
- defer cleanup()
- conn := &fakeWSConn{}
- acc.mu.Lock()
- acc.conn = conn
- acc.runtimeState = RuntimeConnecting
- acc.runtimeMessage = tokenRiskRecoveryMessage
- acc.lastCookieRefresh = time.Time{}
- acc.mu.Unlock()
-
- acc.applyOnlineToken(conn, "periodic-token", false)
-
- status := acc.RuntimeStatus()
- if status.State != RuntimeOnline || !status.Connected || status.Message != "消息服务连接正常" {
- t.Fatalf("定时 token 风控恢复后运行态未收敛: %+v", status)
- }
- acc.mu.Lock()
- lastCookieRefresh := acc.lastCookieRefresh
- acc.mu.Unlock()
- if !lastCookieRefresh.IsZero() {
- t.Fatalf("定时 token 刷新不应改变 180 秒 Cookie 检查时间: %s", lastCookieRefresh)
- }
- conn.mu.Lock()
- defer conn.mu.Unlock()
- if len(conn.tokens) != 1 || conn.tokens[0] != "periodic-token" {
- t.Fatalf("定时刷新 token 未更新到现有连接: %+v", conn.tokens)
- }
-}
-
-func TestRunOnlineCookieRefresh_RetriesOnceAndPacesFailure(t *testing.T) {
- mtopClient := &failingCountingMtop{
- fakeRunMtop: fakeRunMtop{token: "unused"},
- err: errors.New("temporary token failure"),
- }
- acc, _, _, cleanup := newRunAccount(t, mtopClient)
- defer cleanup()
-
- started := time.Now()
- if !acc.runOnlineCookieRefresh(context.Background(), &fakeWSConn{}, 0) {
- t.Fatal("未取消的刷新轮次不应要求退出")
- }
- if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 {
- t.Fatalf("失败后应且只应重试一次,got %d calls", calls)
- }
- if elapsed := time.Since(started); elapsed >= time.Second {
- t.Fatalf("参考实现没有额外一分钟防抖,零延迟测试不应阻塞,elapsed=%s", elapsed)
- }
- acc.mu.Lock()
- lastRefresh := acc.lastCookieRefresh
- acc.mu.Unlock()
- if lastRefresh.Before(started) {
- t.Fatalf("第二次失败后必须重新开始 180 秒计时,last_refresh=%s started=%s", lastRefresh, started)
- }
}
func TestRefreshTokenNetworkFailureClearsMemoryButPreservesFreshCache(t *testing.T) {
@@ -212,10 +55,7 @@ func TestRefreshTokenNetworkFailureClearsMemoryButPreservesFreshCache(t *testing
}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
- if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok",
- time.Now().Add(time.Hour).Unix()); err != nil {
- t.Fatal(err)
- }
+ saveBoundToken(t, store, acc, "cached-tok", time.Now().Add(time.Hour).Unix())
acc.mu.Lock()
acc.currentToken = "old-memory-token"
acc.mu.Unlock()
@@ -240,10 +80,7 @@ func TestRefreshTokenBusinessFailureClearsMemoryAndCache(t *testing.T) {
}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
- if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok",
- time.Now().Add(time.Hour).Unix()); err != nil {
- t.Fatal(err)
- }
+ saveBoundToken(t, store, acc, "cached-tok", time.Now().Add(time.Hour).Unix())
acc.mu.Lock()
acc.currentToken = "old-memory-token"
acc.mu.Unlock()
@@ -268,10 +105,7 @@ func TestAcquireTokenDeletesExpiredCacheBeforeNetworkAttempt(t *testing.T) {
}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
- if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "expired-tok",
- time.Now().Add(-time.Minute).Unix()); err != nil {
- t.Fatal(err)
- }
+ saveBoundToken(t, store, acc, "expired-tok", time.Now().Add(-time.Minute).Unix())
if _, _, err := acc.acquireToken(context.Background()); err == nil {
t.Fatal("后续网络请求失败应返回错误")
}
@@ -284,35 +118,51 @@ func (s *statusMtop) CheckLoginStatusContext(context.Context, string) (*mtop.Log
return s.result, s.err
}
-// TestAcquireToken_CacheHitSkipsMtop 缓存命中且未过期时跳过 mtop 调用。
-func TestAcquireToken_CacheHitSkipsMtop(t *testing.T) {
+// TestAcquireToken_CacheHitStillFetchesFreshToken matches the official web
+// client: every connection attempt calls login.token even when a persisted
+// token has not reached its advertised expiry.
+func TestAcquireToken_CacheHitStillFetchesFreshToken(t *testing.T) {
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
- if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok",
- time.Now().Add(time.Hour).Unix()); err != nil {
- t.Fatal(err)
- }
- if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", "unb=123; _m_h5_tk=db-new;"); err != nil {
- t.Fatal(err)
- }
+ saveBoundToken(t, store, acc, "cached-tok", time.Now().Add(time.Hour).Unix())
token, cookies, err := acc.acquireToken(context.Background())
if err != nil {
t.Fatalf("acquireToken: %v", err)
}
- if token != "cached-tok" {
- t.Fatalf("应使用缓存 token,got %s", token)
+ if token != "tok-mtop" {
+ t.Fatalf("应使用新获取 token,got %s", token)
}
- if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 {
- t.Fatalf("缓存命中不应调用 mtop,got %d", calls)
+ if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
+ t.Fatalf("每次连接都应调用 mtop,got %d", calls)
}
- if strings.Contains(cookies, "db-new") {
- t.Fatalf("缓存命中时不应提前重载 DB Cookie: %q", cookies)
+ if !strings.Contains(cookies, "_m_h5_tk=tk_1") {
+ t.Fatalf("缓存命中应返回其绑定的 Cookie: %q", cookies)
}
}
-func TestAcquireRuntimeTokenPreservesMemoryTokenWithoutDatabaseCache(t *testing.T) {
+func TestAcquireToken_RejectsCacheBoundToDifferentCookie(t *testing.T) {
+ mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "fresh-token"}}
+ acc, _, store, cleanup := newRunAccount(t, mtopClient)
+ defer cleanup()
+ saveBoundToken(t, store, acc, "stale-token", time.Now().Add(time.Hour).Unix())
+ newCookie := "unb=123; _m_h5_tk=renewed_2; cookie2=new"
+ if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", newCookie); err != nil {
+ t.Fatal(err)
+ }
+ acc.replaceCookieStr(newCookie)
+
+ token, _, err := acc.acquireToken(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if token != "fresh-token" || atomic.LoadInt32(&mtopClient.calls) != 1 {
+ t.Fatalf("token=%q calls=%d want fresh token", token, atomic.LoadInt32(&mtopClient.calls))
+ }
+}
+
+func TestAcquireRuntimeTokenReplacesMemoryToken(t *testing.T) {
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
@@ -320,11 +170,11 @@ func TestAcquireRuntimeTokenPreservesMemoryTokenWithoutDatabaseCache(t *testing.
_ = store.Tokens.Clear(context.Background(), "cid")
token, _, err := acc.acquireRuntimeToken(context.Background())
- if err != nil || token != "runtime-token" {
+ if err != nil || token != "tok-mtop" {
t.Fatalf("runtime token=%q err=%v", token, err)
}
- if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 {
- t.Fatalf("网络重连复用内存 token 时不应调用 mtop,calls=%d", calls)
+ if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
+ t.Fatalf("网络重连应获取新 token,calls=%d", calls)
}
}
@@ -370,10 +220,8 @@ func TestTryLoginStatusCheck_AdoptsUpdatedCookie(t *testing.T) {
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
- if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "old-tok",
- time.Now().Add(time.Hour).Unix()); err != nil {
- t.Fatal(err)
- }
+ oldDeviceID := acc.deviceID
+ saveBoundToken(t, store, acc, "old-tok", time.Now().Add(time.Hour).Unix())
res := acc.tryLoginStatusCheck(context.Background())
if !res.recovered || res.riskRequired {
t.Fatalf("登录态检查应恢复 Cookie,got %+v", res)
@@ -385,8 +233,8 @@ func TestTryLoginStatusCheck_AdoptsUpdatedCookie(t *testing.T) {
if err != nil || saved != newCookie {
t.Fatalf("DB Cookie 未更新: got %q err=%v", saved, err)
}
- if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
- t.Fatalf("Cookie 更新后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
+ if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != oldDeviceID || acc.deviceID != oldDeviceID {
+ t.Fatalf("Cookie 更新后应清 token 并保持页面 device ID: runtime=%q tk=%+v err=%v", acc.deviceID, tk, err)
}
}
@@ -421,10 +269,8 @@ func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) {
acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
defer cleanup()
// 预置旧 session 的 token 缓存。
- if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "old-tok",
- time.Now().Add(time.Hour).Unix()); err != nil {
- t.Fatal(err)
- }
+ oldDeviceID := acc.deviceID
+ saveBoundToken(t, store, acc, "old-tok", time.Now().Add(time.Hour).Unix())
// 外部更新 DB cookie(模拟重新扫码),userID=0 复用现有 user_id。
newCookie := "unb=123; _m_h5_tk=newtk_2; sgcookie=abc"
if err := store.Cookies.Save(context.Background(), "cid", newCookie, 0); err != nil {
@@ -434,9 +280,9 @@ func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) {
if got := acc.CurrentCookieStr(); got != newCookie {
t.Fatalf("应采纳 DB 新 cookie,got %s", got)
}
- // 新 cookie 对应新 session,旧 token 应清除但 device ID 必须保留。
- if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != acc.deviceID {
- t.Fatalf("cookie 变更后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
+ // 普通 Cookie Jar 更新不等于页面 reload:旧 token 清除,device ID 保持。
+ if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != oldDeviceID || acc.deviceID != oldDeviceID {
+ t.Fatalf("cookie 变更后应清 token 并保持运行时 device ID: runtime=%q tk=%+v err=%v", acc.deviceID, tk, err)
}
}
diff --git a/internal/engine/run_test.go b/internal/engine/run_test.go
index 2ee44d8..bbab3b2 100644
--- a/internal/engine/run_test.go
+++ b/internal/engine/run_test.go
@@ -3,6 +3,7 @@ package engine
import (
"context"
"errors"
+ "fmt"
"log/slog"
"path/filepath"
"sync"
@@ -12,6 +13,7 @@ import (
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
+ xrenew "xianyu-go/internal/xianyu/renew"
"xianyu-go/internal/xianyu/ws"
)
@@ -34,7 +36,7 @@ func (f *fakeRunMtop) PublishItem(context.Context, string, mtop.PublishItemReque
return nil, nil
}
func (f *fakeRunMtop) RefreshTokenWithDeviceIDContext(_ context.Context, _ string, _ string) (*mtop.RefreshResult, error) {
- return &mtop.RefreshResult{AccessToken: f.token}, nil
+ return &mtop.RefreshResult{AccessToken: f.token, AccessTokenExpireAt: time.Now().Add(time.Hour).Unix()}, nil
}
type fakeFailTokenMtop struct{ err error }
@@ -58,11 +60,33 @@ func (f *fakeFailTokenMtop) RefreshTokenWithDeviceIDContext(context.Context, str
return nil, f.err
}
+type sequencedTokenMtop struct {
+ fakeRunMtop
+ mu sync.Mutex
+ devices []string
+ cookies []string
+ calls int
+}
+
+func (s *sequencedTokenMtop) RefreshTokenWithDeviceIDContext(_ context.Context, cookieStr, deviceID string) (*mtop.RefreshResult, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.calls++
+ s.devices = append(s.devices, deviceID)
+ s.cookies = append(s.cookies, cookieStr)
+ return &mtop.RefreshResult{
+ AccessToken: fmt.Sprintf("fresh-%d", s.calls),
+ AccessTokenExpireAt: time.Now().Add(time.Hour).Unix(),
+ }, nil
+}
+
// fakeWSConn 实现 WSConn,可控地投递消息并阻塞到 ctx 取消。
type fakeWSConn struct {
mu sync.Mutex
closed bool
- tokens []string
+ registerErr error
+ registeredDID string
+ registeredTok string
sentTexts []string
sentImages []string
heartbeatDone chan struct{}
@@ -73,6 +97,15 @@ type fakeWSConn struct {
recvErr error
}
+func (f *fakeWSConn) Register(_ context.Context, deviceID, accessToken string) error {
+ f.mu.Lock()
+ f.registeredDID = deviceID
+ f.registeredTok = accessToken
+ err := f.registerErr
+ f.mu.Unlock()
+ return err
+}
+
func (f *fakeWSConn) HeartbeatLoop(ctx context.Context, _ time.Duration) error {
<-ctx.Done()
if f.heartbeatDone != nil {
@@ -99,12 +132,6 @@ func (f *fakeWSConn) Close() error {
return nil
}
-func (f *fakeWSConn) SetAccessToken(token string) {
- f.mu.Lock()
- f.tokens = append(f.tokens, token)
- f.mu.Unlock()
-}
-
func (f *fakeWSConn) SendText(_ context.Context, _, _, _, text string) error {
f.mu.Lock()
f.sentTexts = append(f.sentTexts, text)
@@ -125,6 +152,7 @@ type fakeDialer struct {
results []dialResult // 每次.Dial 的结果
calls int
conns []*fakeWSConn
+ configs []ws.Config
lastCfg ws.Config // 记录最后一次 Dial 的配置(含 AccessToken)
}
@@ -137,6 +165,7 @@ func (d *fakeDialer) Dial(_ context.Context, cfg ws.Config, _ *slog.Logger) (WSC
d.mu.Lock()
defer d.mu.Unlock()
d.lastCfg = cfg
+ d.configs = append(d.configs, cfg)
idx := d.calls
d.calls++
if idx >= len(d.results) {
@@ -226,13 +255,12 @@ func TestRun_ConnectsAndDispatchesMessage(t *testing.T) {
time.Sleep(50 * time.Millisecond)
}
- // 初始 token 应通过 ws.Config.AccessToken 传给 Dial(非 SetAccessToken)。
- d := acc.wsDialer.(*fakeDialer)
- d.mu.Lock()
- gotToken := d.lastCfg.AccessToken == "tok-1"
- d.mu.Unlock()
+ // token 必须在握手成功后通过 Register 发送,而不是在 Dial 前获得。
+ conn.mu.Lock()
+ gotToken := conn.registeredTok == "tok-1"
+ conn.mu.Unlock()
if !gotToken {
- t.Fatal("Dial 未收到 ws.Config.AccessToken=tok-1")
+ t.Fatal("Register 未收到 token=tok-1")
}
// 取消 ctx → Run 应退出。
@@ -247,37 +275,31 @@ func TestRun_ConnectsAndDispatchesMessage(t *testing.T) {
}
}
-// TestRun_DialFailureIncrementsFailures 拨号失败时 connFailures 递增,
-// ctx 在重试 sleep 期间取消 → Run 返回 ctx.Err。
-func TestRun_DialFailureIncrementsFailures(t *testing.T) {
+// TestRun_DialFailureRequiresRelogin mirrors the web page: native
+// CONNECT_FAILED enters CONN_ERROR and does not auto-reconnect.
+func TestRun_DialFailureRequiresRelogin(t *testing.T) {
acc, _, _, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
defer cleanup()
// 拨号始终失败。
acc.wsDialer = &fakeDialer{results: []dialResult{{err: errFakeDial}}}
- ctx, cancel := context.WithCancel(context.Background())
runDone := make(chan error, 1)
- go func() { runDone <- acc.Run(ctx) }()
-
- // 等待首次拨号失败 + 进入重试 sleep。
- time.Sleep(300 * time.Millisecond)
- cancel()
+ go func() { runDone <- acc.Run(context.Background()) }()
select {
- case <-runDone:
- // Run 应已退出。
- case <-time.After(3 * time.Second):
- t.Fatal("拨号失败 + ctx 取消后 Run 未退出")
+ case err := <-runDone:
+ if !errors.Is(err, errFakeDial) {
+ t.Fatalf("Run error=%v,期望拨号错误", err)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("拨号失败后 Run 未退出")
}
- acc.mu.Lock()
- failures := acc.connFailures
- acc.mu.Unlock()
- if failures < 1 {
- t.Fatalf("拨号失败应使 connFailures>=1,got %d", failures)
+ if status := acc.RuntimeStatus(); status.State != RuntimeAuthExpired {
+ t.Fatalf("runtime state=%q,期望 %q", status.State, RuntimeAuthExpired)
}
}
-// TestRun_ReceiveLoopEndsTriggersReconnect 正常结束后直接重连,并复用当前内存 token。
+// TestRun_ReceiveLoopEndsTriggersReconnect 正常结束后直接重连,并重新获取 token。
func TestRun_ReceiveLoopEndsTriggersReconnect(t *testing.T) {
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-1"}}
acc, _, _, cleanup := newRunAccount(t, mtopClient)
@@ -316,44 +338,81 @@ func TestRun_ReceiveLoopEndsTriggersReconnect(t *testing.T) {
case <-time.After(3 * time.Second):
t.Fatal("重连后 ctx 取消 Run 未退出")
}
- if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
- t.Fatalf("正常重连应复用内存 token,不应重复请求 mtop: calls=%d", calls)
+ if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 {
+ t.Fatalf("正常重连应重新请求 mtop: calls=%d", calls)
}
}
-func TestRun_EstablishedNetworkErrorPreservesTokenAndCache(t *testing.T) {
- mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-1"}}
- acc, _, store, cleanup := newRunAccount(t, mtopClient)
+func TestRun_ReconnectUsesFreshTokenAndStableDeviceID(t *testing.T) {
+ mtopClient := &sequencedTokenMtop{fakeRunMtop: fakeRunMtop{token: "unused"}}
+ acc, _, _, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
- conn := &fakeWSConn{recvErr: errors.New("connection reset by peer")}
- acc.wsDialer = &fakeDialer{results: []dialResult{{conn: conn}}}
+ first := &fakeWSConn{recvBlock: false}
+ second := &fakeWSConn{recvBlock: true}
+ dialer := &fakeDialer{results: []dialResult{
+ {conn: first},
+ {conn: second},
+ }}
+ acc.wsDialer = dialer
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- acc.Run(ctx) }()
- deadline := time.Now().Add(2 * time.Second)
- for time.Now().Before(deadline) {
- acc.mu.Lock()
- failures := acc.networkFailures
- acc.mu.Unlock()
- if failures == 1 {
- break
- }
- time.Sleep(10 * time.Millisecond)
+ waitForDialCalls(t, dialer, 2)
+ waitForRegisteredToken(t, second, "fresh-2")
+ cancel()
+ <-done
+
+ dialer.mu.Lock()
+ conns := append([]*fakeWSConn(nil), dialer.conns...)
+ dialer.mu.Unlock()
+ if len(conns) < 2 {
+ t.Fatalf("dial conns=%d want>=2", len(conns))
}
+ conns[0].mu.Lock()
+ firstToken := conns[0].registeredTok
+ conns[0].mu.Unlock()
+ conns[1].mu.Lock()
+ secondToken := conns[1].registeredTok
+ conns[1].mu.Unlock()
+ if firstToken != "fresh-1" || secondToken != "fresh-2" {
+ t.Fatalf("reconnect tokens=%v", []string{firstToken, secondToken})
+ }
+ mtopClient.mu.Lock()
+ devices := append([]string(nil), mtopClient.devices...)
+ mtopClient.mu.Unlock()
+ if len(devices) != 2 || devices[0] == "" || devices[0] != devices[1] {
+ t.Fatalf("device IDs must remain stable: %v", devices)
+ }
+}
+
+func TestRun_EstablishedNetworkErrorReconnectsWithFreshToken(t *testing.T) {
+ mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-1"}}
+ acc, _, store, cleanup := newRunAccount(t, mtopClient)
+ defer cleanup()
+ first := &fakeWSConn{recvErr: errors.New("connection reset by peer")}
+ second := &fakeWSConn{recvBlock: true}
+ dialer := &fakeDialer{results: []dialResult{{conn: first}, {conn: second}}}
+ acc.wsDialer = dialer
+
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan error, 1)
+ go func() { done <- acc.Run(ctx) }()
+ waitForDialCalls(t, dialer, 2)
+ waitForRegisteredToken(t, second, "tok-1")
acc.mu.Lock()
currentToken := acc.currentToken
networkFailures := acc.networkFailures
acc.mu.Unlock()
- if networkFailures != 1 || currentToken != "tok-1" {
+ if networkFailures != 0 || currentToken != "tok-1" {
cancel()
<-done
- t.Fatalf("网络断线不应清空内存 token: failures=%d token=%q", networkFailures, currentToken)
+ t.Fatalf("网络断线后应立即用新凭证恢复连接: failures=%d token=%q", networkFailures, currentToken)
}
if cached, err := store.Tokens.Get(context.Background(), "cid"); err != nil || cached.AccessToken != "tok-1" {
cancel()
<-done
- t.Fatalf("网络断线不应删除 token 缓存: cached=%+v err=%v", cached, err)
+ t.Fatalf("重连成功后应缓存新连接凭证: cached=%+v err=%v", cached, err)
}
cancel()
select {
@@ -361,11 +420,112 @@ func TestRun_EstablishedNetworkErrorPreservesTokenAndCache(t *testing.T) {
case <-time.After(2 * time.Second):
t.Fatal("取消后 Run 未退出")
}
- if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
- t.Fatalf("网络断线前只应获取一次 token: calls=%d", calls)
+ if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 {
+ t.Fatalf("官网重连会重新获取连接凭证: calls=%d", calls)
}
}
+func TestRun_InvalidRegTokenRequiresRelogin(t *testing.T) {
+ mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "fresh-token"}}
+ acc, _, _, cleanup := newRunAccount(t, mtopClient)
+ defer cleanup()
+ dialer := &fakeDialer{results: []dialResult{
+ {conn: &fakeWSConn{registerErr: &ws.RegError{Kind: ws.RegErrorInvalidToken, Code: 401, Reason: "invalid token"}}},
+ }}
+ acc.wsDialer = dialer
+
+ done := make(chan error, 1)
+ go func() { done <- acc.Run(context.Background()) }()
+ select {
+ case err := <-done:
+ if !ws.IsInvalidTokenError(err) {
+ t.Fatalf("Run error=%v", err)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("invalid /reg 后 Run 未退出")
+ }
+
+ if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
+ t.Fatalf("invalid /reg 不应在页面要求重新登录时静默重试: calls=%d", calls)
+ }
+ if dialer.calls != 1 {
+ t.Fatalf("invalid /reg dial calls=%d want 1", dialer.calls)
+ }
+ if status := acc.RuntimeStatus(); status.State != RuntimeAuthExpired {
+ t.Fatalf("runtime state=%q want %q", status.State, RuntimeAuthExpired)
+ }
+}
+
+func TestRun_ReloadsDatabaseCookieBeforeNaturalReconnect(t *testing.T) {
+ mtopClient := &sequencedTokenMtop{fakeRunMtop: fakeRunMtop{token: "token"}}
+ acc, _, store, cleanup := newRunAccount(t, mtopClient)
+ defer cleanup()
+ newCookie := "unb=123; _m_h5_tk=db-renewed_2; cookie2=new"
+ first := &fakeWSConn{recvBlock: false, onReceive: func(func(map[string]any)) {
+ if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", newCookie); err != nil {
+ t.Errorf("update Cookie: %v", err)
+ }
+ }}
+ dialer := &fakeDialer{results: []dialResult{
+ {conn: first},
+ {conn: &fakeWSConn{recvBlock: true}},
+ }}
+ acc.wsDialer = dialer
+
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan error, 1)
+ go func() { done <- acc.Run(ctx) }()
+ waitForDialCalls(t, dialer, 2)
+ cancel()
+ <-done
+
+ mtopClient.mu.Lock()
+ cookies := append([]string(nil), mtopClient.cookies...)
+ mtopClient.mu.Unlock()
+ if len(cookies) < 2 || cookies[1] != newCookie {
+ t.Fatalf("second token Cookie=%v want=%q", cookies, newCookie)
+ }
+ if calls := mtopClient.calls; calls != 2 {
+ t.Fatalf("Cookie change should invalidate token for reconnect, calls=%d", calls)
+ }
+}
+
+func waitForDialCalls(t *testing.T, dialer *fakeDialer, want int) {
+ t.Helper()
+ deadline := time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) {
+ dialer.mu.Lock()
+ calls := dialer.calls
+ dialer.mu.Unlock()
+ if calls >= want {
+ return
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ dialer.mu.Lock()
+ calls := dialer.calls
+ dialer.mu.Unlock()
+ t.Fatalf("dial calls=%d want>=%d", calls, want)
+}
+
+func waitForRegisteredToken(t *testing.T, conn *fakeWSConn, want string) {
+ t.Helper()
+ deadline := time.Now().Add(10 * time.Second)
+ for time.Now().Before(deadline) {
+ conn.mu.Lock()
+ token := conn.registeredTok
+ conn.mu.Unlock()
+ if token == want {
+ return
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ conn.mu.Lock()
+ token := conn.registeredTok
+ conn.mu.Unlock()
+ t.Fatalf("registered token=%q want=%q", token, want)
+}
+
// TestRun_DisabledAccountExits 账号被禁用时 Run 立即退出。
func TestRun_DisabledAccountExits(t *testing.T) {
acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
@@ -387,9 +547,82 @@ func TestRun_DisabledAccountExits(t *testing.T) {
}
}
-func TestRun_TokenFetchThresholdDisablesAccount(t *testing.T) {
+func TestRun_APIRenewFailureDoesNotBlockTokenAndWebSocket(t *testing.T) {
+ acc, _, _, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-after-renew-error"})
+ defer cleanup()
+
+ renewer := &stubCookieRenewer{err: errors.New("startup API renewal failed")}
+ acc.renewer = renewer
+ conn := &fakeWSConn{recvBlock: true}
+ acc.wsDialer = &fakeDialer{results: []dialResult{{conn: conn}}}
+
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan error, 1)
+ go func() { done <- acc.Run(ctx) }()
+
+ waitForRegisteredToken(t, conn, "tok-after-renew-error")
+ if renewer.calls != 1 {
+ t.Fatalf("启动时协议续期调用次数=%d want=1", renewer.calls)
+ }
+ cancel()
+ select {
+ case err := <-done:
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("Run error=%v want context canceled", err)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("Run did not stop after cancellation")
+ }
+}
+
+func TestRun_APIRenewSuccessRebuildsOfficialPageDeviceID(t *testing.T) {
+ tokenClient := &sequencedTokenMtop{}
+ acc, _, _, cleanup := newRunAccount(t, tokenClient)
+ defer cleanup()
+
+ acc.mu.Lock()
+ initialDeviceID := acc.deviceID
+ acc.mu.Unlock()
+ acc.renewer = &stubCookieRenewer{result: &xrenew.Result{
+ Success: true,
+ RenewMethod: "auto_login_plugin",
+ NewCookies: "unb=123; _m_h5_tk=tk_1;",
+ }}
+ conn := &fakeWSConn{recvBlock: true}
+ acc.wsDialer = &fakeDialer{results: []dialResult{{conn: conn}}}
+
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan error, 1)
+ go func() { done <- acc.Run(ctx) }()
+
+ waitForRegisteredToken(t, conn, "fresh-1")
+ conn.mu.Lock()
+ registeredDeviceID := conn.registeredDID
+ conn.mu.Unlock()
+ if registeredDeviceID == initialDeviceID {
+ t.Fatal("官网 auto-login 成功后的逻辑 reload 必须重建页面级 device ID")
+ }
+ tokenClient.mu.Lock()
+ if len(tokenClient.devices) != 1 || tokenClient.devices[0] != registeredDeviceID {
+ t.Fatalf("token 与 /reg 必须绑定同一新 device ID: token=%v reg=%q", tokenClient.devices, registeredDeviceID)
+ }
+ tokenClient.mu.Unlock()
+
+ cancel()
+ select {
+ case err := <-done:
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("Run error=%v want context canceled", err)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("Run did not stop after cancellation")
+ }
+}
+
+func TestRun_TokenFetchThresholdDoesNotDisableAccount(t *testing.T) {
acc, _, store, cleanup := newRunAccount(t, &fakeFailTokenMtop{err: errFakeDial})
defer cleanup()
+ acc.wsDialer = &fakeDialer{results: []dialResult{{conn: &fakeWSConn{recvBlock: true}}}}
h := &failingRefreshHandler{}
acc.handler = h
acc.mu.Lock()
@@ -400,17 +633,22 @@ func TestRun_TokenFetchThresholdDisablesAccount(t *testing.T) {
go func() { done <- acc.Run(context.Background()) }()
select {
case err := <-done:
- if err != nil {
- t.Fatalf("threshold disable should exit nil, got %v", err)
+ if !errors.Is(err, errFakeDial) {
+ t.Fatalf("token callback reject should enter CONN_ERROR, got %v", err)
}
case <-time.After(2 * time.Second):
- t.Fatal("token failure threshold should disable without retry sleep")
+ t.Fatal("Run did not stop after token callback reject")
}
- if store.Cookies.GetStatus(context.Background(), "cid") {
- t.Fatal("token failure threshold should disable account")
+ if !store.Cookies.GetStatus(context.Background(), "cid") {
+ t.Fatal("token failure threshold must not disable account")
}
- if len(h.events) == 0 || h.events[len(h.events)-1] != EventAccountDisabled {
- t.Fatalf("disable event not emitted: events=%+v alerts=%+v", h.events, h.alerts)
+ for _, event := range h.events {
+ if event == EventAccountDisabled {
+ t.Fatalf("unexpected disable event: events=%+v alerts=%+v", h.events, h.alerts)
+ }
+ }
+ if status := acc.RuntimeStatus(); status.State != RuntimeAuthExpired {
+ t.Fatalf("runtime state=%q want %q", status.State, RuntimeAuthExpired)
}
}
diff --git a/internal/engine/token_cache.go b/internal/engine/token_cache.go
index 9fc9cc0..75f896f 100644
--- a/internal/engine/token_cache.go
+++ b/internal/engine/token_cache.go
@@ -1,45 +1,63 @@
package engine
import (
- "crypto/rand"
- "math/big"
- "os"
- "strconv"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
"strings"
"time"
+
+ "xianyu-go/internal/xianyu/cookierefresh"
)
-const tokenCacheTTLGranularity = time.Second
+const tokenExpirySafetyMargin = time.Minute
-func tokenCacheTTL() time.Duration {
- minTTL, minOK := tokenCacheTTLEnv("TOKEN_CACHE_TTL_MIN_HOURS", TokenCacheTTLMin)
- maxTTL, maxOK := tokenCacheTTLEnv("TOKEN_CACHE_TTL_MAX_HOURS", TokenCacheTTLMax)
- if !minOK || !maxOK || minTTL > maxTTL {
- minTTL = TokenCacheTTLMin
- maxTTL = TokenCacheTTLMax
+func effectiveTokenExpireAt(serverExpireAt int64, now time.Time) int64 {
+ ttl := time.Unix(serverExpireAt, 0).Sub(now)
+ if ttl <= 0 {
+ return 0
}
- if maxTTL == minTTL {
- return minTTL
+ margin := tokenExpirySafetyMargin
+ if ttl <= 2*margin {
+ margin = ttl / 10
}
- steps := int64((maxTTL - minTTL) / tokenCacheTTLGranularity)
- if steps <= 0 {
- return minTTL
- }
- n, err := rand.Int(rand.Reader, big.NewInt(steps+1))
- if err != nil {
- return minTTL
- }
- return minTTL + time.Duration(n.Int64())*tokenCacheTTLGranularity
+ return now.Add(ttl - margin).Unix()
}
-func tokenCacheTTLEnv(key string, fallback time.Duration) (time.Duration, bool) {
- raw := strings.TrimSpace(os.Getenv(key))
- if raw == "" {
- return fallback, true
+func credentialCookieFingerprint(cookieStr string) string {
+ var canonical strings.Builder
+ for _, part := range strings.Split(cookieStr, ";") {
+ key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
+ key = strings.TrimSpace(key)
+ if !ok || key == "" {
+ continue
+ }
+ canonical.WriteString(key)
+ canonical.WriteByte(0)
+ canonical.WriteString(strings.TrimSpace(value))
+ canonical.WriteByte(0)
}
- hours, err := strconv.ParseFloat(raw, 64)
- if err != nil || hours <= 0 {
- return fallback, false
+ sum := sha256.Sum256([]byte(canonical.String()))
+ return hex.EncodeToString(sum[:])
+}
+
+// credentialStateFingerprint binds a connection token to both the exact flat
+// Cookie header and the authoritative browser Jar that produced it. The flat
+// fingerprint deliberately retains duplicate names and their order because
+// lib-mtop reads the first path-ordered _m_h5_tk entry. A present empty Jar is
+// distinct from legacy metadata that has no complete snapshot.
+func credentialStateFingerprint(cookieStr, metadataJSON string) string {
+ var canonical strings.Builder
+ canonical.WriteString("flat\x00")
+ canonical.WriteString(credentialCookieFingerprint(cookieStr))
+ canonical.WriteString("\x00snapshot\x00")
+ if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(metadataJSON); complete {
+ canonical.WriteByte('1')
+ raw, _ := json.Marshal(cookierefresh.NormalizeSnapshot(snapshot))
+ canonical.Write(raw)
+ } else {
+ canonical.WriteByte('0')
}
- return time.Duration(hours * float64(time.Hour)), true
+ sum := sha256.Sum256([]byte(canonical.String()))
+ return hex.EncodeToString(sum[:])
}
diff --git a/internal/engine/token_cache_test.go b/internal/engine/token_cache_test.go
index 25bd568..050feda 100644
--- a/internal/engine/token_cache_test.go
+++ b/internal/engine/token_cache_test.go
@@ -3,39 +3,60 @@ package engine
import (
"testing"
"time"
+
+ "xianyu-go/internal/xianyu/cookierefresh"
)
-func TestTokenCacheTTLFixedEnv(t *testing.T) {
- t.Setenv("TOKEN_CACHE_TTL_MIN_HOURS", "2")
- t.Setenv("TOKEN_CACHE_TTL_MAX_HOURS", "2")
- if got := tokenCacheTTL(); got != 2*time.Hour {
- t.Fatalf("tokenCacheTTL=%s want 2h", got)
+func TestEffectiveTokenExpireAtUsesServerDeadlineWithSafetyMargin(t *testing.T) {
+ now := time.Unix(1_700_000_000, 0)
+ got := effectiveTokenExpireAt(now.Add(2*time.Hour).Unix(), now)
+ want := now.Add(2*time.Hour - tokenExpirySafetyMargin).Unix()
+ if got != want {
+ t.Fatalf("effective expiry=%d want=%d", got, want)
}
}
-func TestTokenCacheTTLMaxBelowMinFallsBackToDefaultRange(t *testing.T) {
- t.Setenv("TOKEN_CACHE_TTL_MIN_HOURS", "4")
- t.Setenv("TOKEN_CACHE_TTL_MAX_HOURS", "2")
- got := tokenCacheTTL()
- if got < TokenCacheTTLMin || got > TokenCacheTTLMax {
- t.Fatalf("tokenCacheTTL=%s want within [%s,%s]", got, TokenCacheTTLMin, TokenCacheTTLMax)
+func TestEffectiveTokenExpireAtRejectsMissingOrExpiredDeadline(t *testing.T) {
+ now := time.Unix(1_700_000_000, 0)
+ for _, expireAt := range []int64{0, now.Add(-time.Second).Unix()} {
+ if got := effectiveTokenExpireAt(expireAt, now); got != 0 {
+ t.Fatalf("effective expiry=%d want=0 for server expiry %d", got, expireAt)
+ }
}
}
-func TestTokenCacheTTLInvalidEnvFallsBackToDefaultRange(t *testing.T) {
- t.Setenv("TOKEN_CACHE_TTL_MIN_HOURS", "bad")
- t.Setenv("TOKEN_CACHE_TTL_MAX_HOURS", "also-bad")
- got := tokenCacheTTL()
- if got < TokenCacheTTLMin || got > TokenCacheTTLMax {
- t.Fatalf("tokenCacheTTL=%s want within [%s,%s]", got, TokenCacheTTLMin, TokenCacheTTLMax)
+func TestCredentialCookieFingerprintPreservesHeaderOrderAndDuplicates(t *testing.T) {
+ left := credentialCookieFingerprint("unb=1; cookie2=abc; _m_h5_tk=tk_1")
+ right := credentialCookieFingerprint("_m_h5_tk=tk_1; unb=1; cookie2=abc")
+ if left == "" || left == right {
+ t.Fatalf("Cookie Header 顺序变化必须改变指纹: %q == %q", left, right)
+ }
+ if left == credentialCookieFingerprint("unb=1; cookie2=changed; _m_h5_tk=tk_1") {
+ t.Fatal("credential change must alter fingerprint")
+ }
+ if left != credentialCookieFingerprint(" unb = 1 ; cookie2=abc;_m_h5_tk = tk_1 ;") {
+ t.Fatal("无语义空白不应改变指纹")
+ }
+ firstPathToken := credentialCookieFingerprint("_m_h5_tk=first; _m_h5_tk=second; unb=1")
+ secondPathToken := credentialCookieFingerprint("_m_h5_tk=second; _m_h5_tk=first; unb=1")
+ if firstPathToken == secondPathToken {
+ t.Fatal("同名 Cookie 的路径顺序会影响首值签名,不能折叠")
}
}
-func TestTokenCacheTTLPartiallyInvalidEnvFallsBackToDefaultRange(t *testing.T) {
- t.Setenv("TOKEN_CACHE_TTL_MIN_HOURS", "2")
- t.Setenv("TOKEN_CACHE_TTL_MAX_HOURS", "bad")
- got := tokenCacheTTL()
- if got < TokenCacheTTLMin || got > TokenCacheTTLMax {
- t.Fatalf("tokenCacheTTL=%s want within [%s,%s]", got, TokenCacheTTLMin, TokenCacheTTLMax)
+func TestCredentialStateFingerprintIncludesAuthoritativeSnapshot(t *testing.T) {
+ flat := "unb=1; _m_h5_tk=tk_1"
+ metadataA := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
+ {Name: "_m_h5_tk", Value: "path-a", Domain: ".goofish.com", Path: "/"},
+ })
+ metadataB := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
+ {Name: "_m_h5_tk", Value: "path-b", Domain: ".goofish.com", Path: "/"},
+ })
+ if credentialStateFingerprint(flat, metadataA) == credentialStateFingerprint(flat, metadataB) {
+ t.Fatal("权威 Jar 变化必须改变完整凭证指纹")
+ }
+ emptyJar := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{})
+ if credentialStateFingerprint("", emptyJar) == credentialStateFingerprint("", "") {
+ t.Fatal("权威空 Jar 必须与没有快照的历史状态区分")
}
}
diff --git a/internal/notify/notifier.go b/internal/notify/notifier.go
index 5d7fad7..44e9c34 100644
--- a/internal/notify/notifier.go
+++ b/internal/notify/notifier.go
@@ -597,15 +597,15 @@ func (n *Notifier) sendTelegram(cfg map[string]any, message string) error {
func (n *Notifier) sendEmail(cfg map[string]any, message string) error {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
- server := n.configOrSetting(ctx, cfg, "smtp_server", "")
- port := n.configOrSetting(ctx, cfg, "smtp_port", "587")
- user := n.configOrSetting(ctx, cfg, "smtp_user", "")
- pass := n.configOrSetting(ctx, cfg, "smtp_password", "")
- useTLS := parseConfigBool(n.configOrSetting(ctx, cfg, "smtp_use_tls", "true"), true)
- useSSL := parseConfigBool(n.configOrSetting(ctx, cfg, "smtp_use_ssl", "false"), false)
- fromAddress := n.configOrSetting(ctx, cfg, "smtp_from_address", "")
- fromName := n.configOrSetting(ctx, cfg, "smtp_from_name", "")
- legacyFrom := n.configOrSetting(ctx, cfg, "smtp_from", "")
+ server := n.smtpConfigValue(ctx, cfg, "smtp_server", "")
+ port := n.smtpConfigValue(ctx, cfg, "smtp_port", "587")
+ user := n.smtpConfigValue(ctx, cfg, "smtp_user", "")
+ pass := n.smtpConfigValue(ctx, cfg, "smtp_password", "")
+ useTLS := parseConfigBool(n.smtpConfigValue(ctx, cfg, "smtp_use_tls", "true"), true)
+ useSSL := parseConfigBool(n.smtpConfigValue(ctx, cfg, "smtp_use_ssl", "false"), false)
+ fromAddress := n.smtpConfigValue(ctx, cfg, "smtp_from_address", "")
+ fromName := n.smtpConfigValue(ctx, cfg, "smtp_from_name", "")
+ legacyFrom := n.smtpConfigValue(ctx, cfg, "smtp_from", "")
to := strOr(cfg, "to_email", strOr(cfg, "email", ""))
if server == "" || user == "" || to == "" {
return fmt.Errorf("邮件配置不完整:请配置系统 SMTP 或在邮件渠道中覆盖 SMTP,并填写收件邮箱")
@@ -751,6 +751,27 @@ func (n *Notifier) configOrSetting(ctx context.Context, cfg map[string]any, key,
return fallbackValue
}
+// smtpConfigValue keeps legacy per-field fallback behavior for existing rows,
+// while new rows use an explicit all-system or all-channel SMTP mode.
+func (n *Notifier) smtpConfigValue(ctx context.Context, cfg map[string]any, key, fallbackValue string) string {
+ modeValue, hasExplicitMode := cfg["use_custom_smtp"]
+ if !hasExplicitMode {
+ return n.configOrSetting(ctx, cfg, key, fallbackValue)
+ }
+ if parseConfigBool(fmt.Sprintf("%v", modeValue), false) {
+ if value := strings.TrimSpace(strOr(cfg, key, "")); value != "" {
+ return value
+ }
+ return fallbackValue
+ }
+ if n.store != nil && n.store.Settings != nil {
+ if value, err := n.store.Settings.Get(ctx, key); err == nil && strings.TrimSpace(value) != "" {
+ return strings.TrimSpace(value)
+ }
+ }
+ return fallbackValue
+}
+
// postJSON 通用 JSON POST。
func (n *Notifier) postJSON(url string, payload any) error {
body, err := json.Marshal(payload)
diff --git a/internal/notify/notifier_channels_test.go b/internal/notify/notifier_channels_test.go
index 0f63d7a..eb28877 100644
--- a/internal/notify/notifier_channels_test.go
+++ b/internal/notify/notifier_channels_test.go
@@ -568,6 +568,33 @@ func TestSendEmail_UsesSystemSMTPFallback(t *testing.T) {
}
}
+func TestSMTPConfigValueUsesExclusiveExplicitModes(t *testing.T) {
+ store, cleanup := newNotifyStoreBare(t)
+ defer cleanup()
+ ctx := context.Background()
+ if err := store.Settings.Set(ctx, "smtp_server", "system.example.com"); err != nil {
+ t.Fatal(err)
+ }
+ n := New("cid", store, nil)
+
+ if got := n.smtpConfigValue(ctx, map[string]any{
+ "use_custom_smtp": false,
+ "smtp_server": "stale-channel.example.com",
+ }, "smtp_server", ""); got != "system.example.com" {
+ t.Fatalf("system mode mixed in channel override: %q", got)
+ }
+ if got := n.smtpConfigValue(ctx, map[string]any{
+ "use_custom_smtp": true,
+ }, "smtp_server", ""); got != "" {
+ t.Fatalf("custom mode inherited system value: %q", got)
+ }
+ if got := n.smtpConfigValue(ctx, map[string]any{
+ "smtp_server": "legacy-channel.example.com",
+ }, "smtp_server", ""); got != "legacy-channel.example.com" {
+ t.Fatalf("legacy channel override compatibility lost: %q", got)
+ }
+}
+
// TestSendEmail_IncompleteConfig 配置不完整应报错。
func TestSendEmail_IncompleteConfig(t *testing.T) {
n := New("cid", nil, nil)
diff --git a/internal/renewal/scheduler.go b/internal/renewal/scheduler.go
index e9725be..7a26081 100644
--- a/internal/renewal/scheduler.go
+++ b/internal/renewal/scheduler.go
@@ -4,15 +4,13 @@ import (
"context"
crand "crypto/rand"
"encoding/hex"
+ "errors"
"fmt"
"log/slog"
- "math/big"
- "reflect"
"strconv"
"strings"
"time"
- "xianyu-go/internal/browser"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
@@ -20,17 +18,13 @@ import (
)
const (
- loginRenewInterval = 600 * time.Second
- cookiesRefreshInterval = 600 * time.Second
- apiCookieRenewInterval = 3600 * time.Second
- accountRequestInterval = time.Second
- browserInitialDelayMax = 30 * time.Minute
- browserSuccessDelayMin = 18 * time.Hour
- browserSuccessDelayRange = 6 * time.Hour
- disabledFailureLimit = 10
- sessionExpiredCooldown = 300 * time.Second
- passwordLoginCooldown = 300 * time.Second
- passwordErrorCooldown = 5 * time.Hour
+ loginRenewInterval = 600 * time.Second
+ cookiesRefreshInterval = 600 * time.Second
+ apiCookieRenewInterval = 3600 * time.Second
+ accountRequestInterval = time.Second
+ sessionExpiredCooldown = 300 * time.Second
+ passwordLoginCooldown = 300 * time.Second
+ passwordErrorCooldown = 5 * time.Hour
)
const (
@@ -46,9 +40,8 @@ type AccountStarter interface {
Start(ctx context.Context, cookieID, cookieValue string) error
}
-type BrowserRenewer interface {
- BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error)
- CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error)
+type accountRestarter interface {
+ Restart(ctx context.Context, cookieID string) error
}
type PasswordRefresher interface {
@@ -58,7 +51,6 @@ type PasswordRefresher interface {
type Scheduler struct {
store *db.Store
starter AccountStarter
- browser BrowserRenewer
refresher PasswordRefresher
logger *slog.Logger
mtop *mtop.ClientImpl
@@ -66,14 +58,13 @@ type Scheduler struct {
cooldown *CooldownManager
}
-func NewScheduler(store *db.Store, starter AccountStarter, browser BrowserRenewer, refresher PasswordRefresher, logger *slog.Logger) *Scheduler {
+func NewScheduler(store *db.Store, starter AccountStarter, refresher PasswordRefresher, logger *slog.Logger) *Scheduler {
if logger == nil {
logger = slog.Default()
}
return &Scheduler{
store: store,
starter: starter,
- browser: browserRenewerOrNil(browser),
refresher: refresher,
logger: logger,
mtop: mtop.NewClient(),
@@ -82,27 +73,17 @@ func NewScheduler(store *db.Store, starter AccountStarter, browser BrowserRenewe
}
}
-func browserRenewerOrNil(browser BrowserRenewer) BrowserRenewer {
- if browser == nil {
- return nil
- }
- v := reflect.ValueOf(browser)
- switch v.Kind() {
- case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
- if v.IsNil() {
- return nil
- }
- }
- return browser
-}
-
func (s *Scheduler) Run(ctx context.Context) {
if s == nil || s.store == nil {
return
}
go s.runFixed(ctx, "login_renew", loginRenewEnabledSetting, loginRenewIntervalSetting, false, loginRenewInterval, s.executeLoginRenew)
- go s.runFixed(ctx, "api_cookie_renew", apiCookieRenewEnabledSetting, apiCookieRenewIntervalSetting, true, apiCookieRenewInterval, s.executeAPICookieRenew)
- go s.runFixed(ctx, "cookies_refresh", cookiesRefreshEnabledSetting, cookiesRefreshIntervalSetting, false, cookiesRefreshInterval, s.executeBrowserCookieRefresh)
+ // 官网静默插件只在页面/账号运行时启动时执行,不做每小时轮询。保留
+ // 调度器入口供显式兼容配置使用,但默认关闭。
+ go s.runFixed(ctx, "api_cookie_renew", apiCookieRenewEnabledSetting, apiCookieRenewIntervalSetting, false, apiCookieRenewInterval, s.executeAPICookieRenew)
+ // 兼容原 cookies_refresh 配置名,但执行同一套 Go HTTP auto-login
+ // 协议;Chromium 不参与普通 Cookie 续期。
+ go s.runFixed(ctx, "cookies_refresh", cookiesRefreshEnabledSetting, cookiesRefreshIntervalSetting, false, cookiesRefreshInterval, s.executeAPICookieRenew)
}
func (s *Scheduler) runFixed(ctx context.Context, name, settingKey, intervalKey string, defaultEnabled bool, defaultInterval time.Duration, fn func(context.Context)) {
@@ -147,25 +128,72 @@ func (s *Scheduler) executeLoginRenew(ctx context.Context) {
}
func (s *Scheduler) loginRenewOne(ctx context.Context, batchID string, account db.RenewalAccount) {
+ credentialUnlock := s.store.LockAccountCredentials(account.ID)
+ defer credentialUnlock()
started := time.Now()
+ latest, err := s.reloadRenewalAccount(ctx, account)
+ if err != nil {
+ s.addLoginLog(ctx, batchID, account.ID, "failed", "重读账号凭证失败: "+err.Error(), nil, time.Since(started))
+ return
+ }
+ account = latest
+ if !account.Enabled {
+ return
+ }
runCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
- res, err := s.mtop.CheckLoginStatusContext(runCtx, account.Value)
- if err != nil {
- s.addLoginLog(ctx, batchID, account.ID, "failed", err.Error(), nil, time.Since(started))
- s.logger.Warn("login_renew 失败", "account", account.ID, "err", err)
+ var mtopCtx context.Context
+ var cookieSession *mtop.CookieSession
+ if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(account.MetadataJSON); ok {
+ mtopCtx, cookieSession = mtop.WithCookieSnapshot(runCtx, snapshot)
+ } else {
+ mtopCtx, cookieSession = mtop.WithFlatCookieSession(runCtx, account.Value)
+ }
+ res, callErr := s.mtop.CheckLoginStatusContext(mtopCtx, account.Value)
+
+ // 对齐浏览器在响应头到达时立即应用 Set-Cookie 的时序。权威 session
+ // 因此必须在处理请求或解析错误之前持久化,否则下次请求会
+ // 从数据库回滚到旧 Jar。
+ updated := []string(nil)
+ value, snapshot, changed := cookieSession.State()
+ // 完整 Jar 即使本轮没有变化也已经权威接管请求;不能因扁平 Cookie
+ // 的顺序或尾分号不同回退写入并清掉快照。
+ sessionHandled := snapshot != nil
+ if changed {
+ updated = cookierefresh.ChangedCookieNames(account.Value, value)
+ metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
+ if snapshot != nil {
+ metadata = cookierefresh.MetadataWithSnapshot(account.MetadataJSON, snapshot)
+ }
+ if persistErr := s.store.Cookies.UpdateRenewalCookie(ctx, account.ID, value, metadata, time.Now().Unix()); persistErr != nil {
+ if callErr != nil {
+ persistErr = errors.Join(callErr, fmt.Errorf("保存 loginuser.get 响应 Cookie Jar: %w", persistErr))
+ }
+ s.addLoginLog(ctx, batchID, account.ID, "failed", persistErr.Error(), updated, time.Since(started))
+ s.logger.Warn("login_renew 保存响应 Cookie Jar 失败", "account", account.ID, "err", persistErr)
+ return
+ }
+ }
+ if callErr != nil {
+ s.addLoginLog(ctx, batchID, account.ID, "failed", callErr.Error(), updated, time.Since(started))
+ s.logger.Warn("login_renew 失败", "account", account.ID, "err", callErr)
return
}
if res == nil {
s.addLoginLog(ctx, batchID, account.ID, "failed", "loginuser.get 未返回结果", nil, time.Since(started))
return
}
- updated := cookierefresh.ChangedCookieNames(account.Value, res.UpdatedCookies)
- if res.UpdatedCookies != "" && res.UpdatedCookies != account.Value {
- metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
- if err := s.store.Cookies.UpdateRenewalCookie(ctx, account.ID, res.UpdatedCookies, metadata, time.Now().Unix()); err != nil {
- s.addLoginLog(ctx, batchID, account.ID, "failed", "保存 Cookie 失败: "+err.Error(), updated, time.Since(started))
- return
+ if !sessionHandled {
+ updated = cookierefresh.ChangedCookieNames(account.Value, res.UpdatedCookies)
+ if res.UpdatedCookies != "" && res.UpdatedCookies != account.Value {
+ // 注入 mock 或没有权威快照的历史账号仍走扁平
+ // Cookie 兼容路径。扁平值无法证明旧 snapshot 的
+ // Domain/Path/expiry 仍有效,因此必须清除旧快照。
+ metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
+ if err := s.store.Cookies.UpdateRenewalCookie(ctx, account.ID, res.UpdatedCookies, metadata, time.Now().Unix()); err != nil {
+ s.addLoginLog(ctx, batchID, account.ID, "failed", "保存 Cookie 失败: "+err.Error(), updated, time.Since(started))
+ return
+ }
}
}
s.addLoginLog(ctx, batchID, account.ID, res.Status, res.Message, updated, time.Since(started))
@@ -191,29 +219,70 @@ func (s *Scheduler) executeAPICookieRenew(ctx context.Context) {
}
func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, account db.RenewalAccount) {
+ credentialUnlock := s.store.LockAccountCredentials(account.ID)
+ credentialLocked := true
+ defer func() {
+ if credentialLocked {
+ credentialUnlock()
+ }
+ }()
started := time.Now()
- res, err := s.renewAPI(ctx, account.Value)
+ latest, err := s.reloadRenewalAccount(ctx, account)
if err != nil {
- s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: err.Error(), RenewMethod: "auto_login_plugin", DurationMS: time.Since(started).Milliseconds()})
- s.logger.Warn("api_cookie_renew 失败", "account", account.ID, "err", err)
+ s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "重读账号凭证失败: " + err.Error(), RenewMethod: "auto_login_plugin"})
return
}
- if res == nil {
- s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "接口续期未返回结果", RenewMethod: "auto_login_plugin", DurationMS: time.Since(started).Milliseconds()})
+ account = latest
+ if !account.Enabled {
return
}
+ res, callErr := s.renewAPI(ctx, account.Value, cookierefresh.SnapshotFromMetadata(account.MetadataJSON))
+ if res == nil {
+ message := "接口续期未返回结果"
+ if callErr != nil {
+ message = callErr.Error()
+ }
+ s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: message, RenewMethod: "auto_login_plugin", DurationMS: time.Since(started).Milliseconds()})
+ return
+ }
+ if res.HasPending() {
+ s.watchPendingAPIRenew(account.ID, res)
+ }
stepDetails := make([]string, 0, len(res.StepDetails)+1)
for _, step := range res.StepDetails {
stepDetails = append(stepDetails, fmt.Sprintf("%s: http=%d business_ok=%v set_cookie=%d", step.Name, step.HTTPStatus, step.BusinessOK, step.SetCookieCount))
}
stepDetails = append(stepDetails, fmt.Sprintf("result: success=%v skipped=%v reason=%s", res.Success, res.Skipped, res.SkipReason))
updated := cookierefresh.ChangedCookieNames(account.Value, res.NewCookies)
- if res.NewCookies != "" && res.NewCookies != account.Value {
- if !s.saveRenewedCookies(ctx, account.ID, res.NewCookies, cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)) {
+ if res.CookieSnapshotComplete || len(res.SetCookies) > 0 || res.NewCookies != account.Value {
+ metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
+ if res.CookieSnapshotComplete {
+ metadata = cookierefresh.MetadataWithSnapshot(account.MetadataJSON, res.CookieSnapshot)
+ }
+ if !s.saveRenewedCookies(ctx, account.ID, res.NewCookies, metadata) {
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存 Cookie 失败", UpdatedCookieNames: updated, StepDetails: strings.Join(stepDetails, " | "), RenewMethod: res.RenewMethod, DurationMS: time.Since(started).Milliseconds(), RequestCount: res.RequestCount})
return
}
}
+ if callErr != nil {
+ s.addAPILog(ctx, db.RenewalLog{
+ BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: callErr.Error(),
+ UpdatedCookieNames: updated, StepDetails: strings.Join(stepDetails, " | "), RenewMethod: res.RenewMethod,
+ DurationMS: time.Since(started).Milliseconds(), RequestCount: res.RequestCount,
+ })
+ s.logger.Warn("api_cookie_renew 失败,已保存响应头 Cookie", "account", account.ID, "err", callErr)
+ return
+ }
+ if res.Success && account.Enabled {
+ credentialUnlock()
+ credentialLocked = false
+ if restarter, ok := s.starter.(accountRestarter); ok {
+ if err := restarter.Restart(ctx, account.ID); err != nil {
+ s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "重建消息连接失败: " + err.Error(), UpdatedCookieNames: updated, StepDetails: strings.Join(stepDetails, " | "), RenewMethod: res.RenewMethod, DurationMS: time.Since(started).Milliseconds(), RequestCount: res.RequestCount})
+ return
+ }
+ }
+ }
status := "failed"
if res.Skipped {
status = "skipped"
@@ -236,115 +305,75 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
})
}
-func (s *Scheduler) executeBrowserCookieRefresh(ctx context.Context) {
- s.cleanupExpiredLogs(ctx)
- batchID := newBatchID()
- accounts, err := s.store.Cookies.AllRenewalAccounts(ctx)
- if err != nil {
- s.logger.Warn("cookies_refresh 加载账号失败", "err", err)
- return
- }
- now := time.Now().Unix()
- for _, account := range accounts {
- if !account.Enabled && account.DisableReason == db.DisableReasonManual {
- continue
- }
- if !account.Enabled && s.disabledAccountShouldSkip(ctx, account.ID) {
- continue
- }
- schedule, err := s.store.Renewal.GetCookieRefreshSchedule(ctx, account.ID)
- if err != nil {
- expireAt := now + int64(randomDuration(browserInitialDelayMax).Seconds())
- schedule = &db.CookieRefreshSchedule{CookieID: account.ID, ExpireAt: expireAt, LastStatus: "initialized"}
- _ = s.store.Renewal.UpsertCookieRefreshSchedule(ctx, *schedule)
- _ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{
- BatchID: batchID,
- CookieID: account.ID,
- Status: "initialized",
- Message: "首次初始化续期时间",
- NextExpireAt: expireAt,
- })
- continue
- }
- if schedule.Disabled || schedule.ExpireAt > now {
- _ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{
- BatchID: batchID,
- CookieID: account.ID,
- Status: "success",
- Message: fmt.Sprintf("未到期,跳过,剩余 %d 秒", schedule.ExpireAt-now),
- NextExpireAt: schedule.ExpireAt,
- })
- continue
- }
- s.browserCookieRefreshOne(ctx, batchID, account, *schedule)
- }
-}
-
-func (s *Scheduler) browserCookieRefreshOne(ctx context.Context, batchID string, account db.RenewalAccount, schedule db.CookieRefreshSchedule) {
- started := time.Now()
- if s.browser == nil {
- schedule.LastStatus = "failed"
- schedule.LastErrorMessage = "浏览器自动化未启用"
- _ = s.store.Renewal.UpsertCookieRefreshSchedule(ctx, schedule)
- _ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: schedule.LastErrorMessage, RenewMethod: "browser", StepDetails: "browser disabled", DurationMS: time.Since(started).Milliseconds()})
- return
- }
- runCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
- defer cancel()
- oldSnapshot := cookierefresh.SnapshotFromMetadata(account.MetadataJSON)
- newCookies, newSnapshot, err := s.browser.CookiesRefreshSnapshot(runCtx, account.ID, account.Value, oldSnapshot, browser.ResolveHeadless(account.ShowBrowser))
- if err != nil {
- schedule.ConsecutiveFailures++
- schedule.LastStatus = "failed"
- schedule.LastError = err.Error()
- schedule.LastErrorMessage = err.Error()
- _ = s.store.Renewal.UpsertCookieRefreshSchedule(ctx, schedule)
- _ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: err.Error(), NextExpireAt: schedule.ExpireAt, RenewMethod: "browser", StepDetails: fmt.Sprintf("snapshot=%v reload=3", len(oldSnapshot) > 0), DurationMS: time.Since(started).Milliseconds(), RequestCount: 4})
- s.logger.Warn("cookies_refresh 失败", "account", account.ID, "err", err)
- return
- }
- metadata := cookierefresh.MetadataWithSnapshot(account.MetadataJSON, newSnapshot)
- updated := cookierefresh.ChangedSnapshotLabels(oldSnapshot, newSnapshot)
- if err := s.store.Cookies.UpdateRenewalCookie(ctx, account.ID, newCookies, metadata, time.Now().Unix()); err != nil {
- _ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存 Cookie 失败: " + err.Error(), UpdatedCookieNames: updated, RenewMethod: "browser", StepDetails: fmt.Sprintf("snapshot=%v reload=3", len(oldSnapshot) > 0), DurationMS: time.Since(started).Milliseconds(), RequestCount: 4})
- return
- }
- if !account.Enabled {
- if err := s.store.Cookies.SetStatusWithReason(ctx, account.ID, true, ""); err != nil {
- s.logger.Warn("cookies_refresh 自动启用账号失败", "account", account.ID, "err", err)
- } else if s.starter != nil {
- if err := s.starter.Start(ctx, account.ID, newCookies); err != nil {
- s.logger.Warn("cookies_refresh 启动账号失败", "account", account.ID, "err", err)
- }
- }
- }
- nextExpire := time.Now().Add(browserSuccessDelay()).Unix()
- schedule.Disabled = false
- schedule.ConsecutiveFailures = 0
- schedule.LastError = ""
- schedule.LastStatus = "success"
- schedule.LastErrorMessage = ""
- schedule.LastRefreshAt = time.Now().Unix()
- schedule.ExpireAt = nextExpire
- _ = s.store.Renewal.UpsertCookieRefreshSchedule(ctx, schedule)
- _ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{
- BatchID: batchID,
- CookieID: account.ID,
- Status: "success",
- Message: fmt.Sprintf("页面校验通过,全量获取到 %d 个浏览器Cookie", len(newSnapshot)),
- UpdatedCookieNames: updated,
- NextExpireAt: nextExpire,
- RenewMethod: "browser",
- StepDetails: fmt.Sprintf("snapshot=%v reload=3 modal_check=true", len(oldSnapshot) > 0),
- DurationMS: time.Since(started).Milliseconds(),
- RequestCount: 4,
- })
-}
-
-func (s *Scheduler) renewAPI(ctx context.Context, cookieStr string) (*apirenew.Result, error) {
+func (s *Scheduler) renewAPI(ctx context.Context, cookieStr string, snapshot []cookierefresh.BrowserCookie) (*apirenew.Result, error) {
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
defer cancel()
- return s.api.RenewAPIFirst(runCtx, cookieStr)
+ return s.api.RenewAPIFirst(runCtx, cookieStr, snapshot)
+}
+
+func (s *Scheduler) watchPendingAPIRenew(cookieID string, result *apirenew.Result) {
+ if result == nil || !result.HasPending() || s.store == nil || s.store.Cookies == nil {
+ return
+ }
+ go func() {
+ ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
+ defer cancel()
+ late, waitErr := result.AwaitPending(ctx)
+ if late == nil {
+ if waitErr != nil {
+ s.logger.Warn("等待定时静默续期底层响应失败", "account", cookieID, "err", waitErr)
+ }
+ return
+ }
+ unlock := s.store.LockAccountCredentials(cookieID)
+ defer unlock()
+ detail, getErr := s.store.Cookies.GetDetails(ctx, cookieID)
+ if getErr != nil || detail == nil {
+ if getErr == nil {
+ getErr = db.ErrNotFound
+ }
+ s.logger.Warn("保存定时静默续期迟到 Cookie 前读取账号失败", "account", cookieID, "err", getErr)
+ return
+ }
+ newCookies, metadata, changed := apirenew.RebaseResponseCookies(detail.Value, detail.MetadataJSON, late)
+ if changed {
+ if saveErr := s.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, metadata, time.Now().Unix()); saveErr != nil {
+ s.logger.Warn("保存定时静默续期迟到 Cookie 失败", "account", cookieID, "err", saveErr)
+ return
+ }
+ if s.store.Tokens != nil {
+ _ = s.store.Tokens.Clear(ctx, cookieID)
+ }
+ s.logger.Info("已异步接收定时静默续期迟到 Cookie", "account", cookieID)
+ }
+ if waitErr != nil {
+ s.logger.Warn("定时静默续期底层响应失败,已保存响应 Cookie", "account", cookieID, "err", waitErr)
+ }
+ }()
+}
+
+func (s *Scheduler) reloadRenewalAccount(ctx context.Context, account db.RenewalAccount) (db.RenewalAccount, error) {
+ detail, err := s.store.Cookies.GetDetails(ctx, account.ID)
+ if err != nil || detail == nil {
+ if err == nil {
+ err = db.ErrNotFound
+ }
+ return db.RenewalAccount{}, err
+ }
+ enabled, reason, err := s.store.Cookies.StatusWithReason(ctx, account.ID)
+ if err != nil {
+ return db.RenewalAccount{}, err
+ }
+ account.Value = detail.Value
+ account.UserID = detail.UserID
+ account.Enabled = enabled
+ account.DisableReason = reason
+ account.Username = detail.Username
+ account.Password = detail.Password
+ account.ShowBrowser = detail.ShowBrowser
+ account.MetadataJSON = detail.MetadataJSON
+ account.LastRefreshAt = detail.LastRefreshAt
+ return account, nil
}
func (s *Scheduler) saveRenewedCookies(ctx context.Context, cookieID, cookieStr, metadata string) bool {
@@ -392,26 +421,6 @@ func (s *Scheduler) isSessionCooled(cookieID string) bool {
return ok
}
-func (s *Scheduler) triggerPasswordLoginAsync(cookieID string) {
- if s.refresher == nil {
- return
- }
- go s.refresher.OnPasswordLoginRefresh(context.Background(), cookieID)
-}
-
-func (s *Scheduler) disabledAccountShouldSkip(ctx context.Context, cookieID string) bool {
- statuses, err := s.store.Renewal.RecentBrowserCookieRenewStatuses(ctx, cookieID, disabledFailureLimit)
- if err != nil || len(statuses) < disabledFailureLimit {
- return false
- }
- for _, status := range statuses {
- if status != "failed" {
- return false
- }
- }
- return true
-}
-
func (s *Scheduler) settingEnabled(ctx context.Context, key string, defaultEnabled bool) bool {
if s.store == nil || s.store.Settings == nil {
return defaultEnabled
@@ -463,21 +472,6 @@ func (s *Scheduler) settingInt(ctx context.Context, key string, defaultValue int
return n
}
-func browserSuccessDelay() time.Duration {
- return browserSuccessDelayMin + randomDuration(browserSuccessDelayRange)
-}
-
-func randomDuration(max time.Duration) time.Duration {
- if max <= 0 {
- return 0
- }
- n, err := crand.Int(crand.Reader, big.NewInt(int64(max)))
- if err != nil {
- return 0
- }
- return time.Duration(n.Int64())
-}
-
func newBatchID() string {
var b [16]byte
if _, err := crand.Read(b[:]); err != nil {
@@ -486,15 +480,6 @@ func newBatchID() string {
return hex.EncodeToString(b[:])
}
-func firstNonEmpty(values ...string) string {
- for _, value := range values {
- if strings.TrimSpace(value) != "" {
- return value
- }
- }
- return ""
-}
-
func sleepCtx(ctx context.Context, d time.Duration) error {
if d <= 0 {
return nil
diff --git a/internal/renewal/scheduler_test.go b/internal/renewal/scheduler_test.go
index 86d6f83..6b8343a 100644
--- a/internal/renewal/scheduler_test.go
+++ b/internal/renewal/scheduler_test.go
@@ -2,10 +2,11 @@ package renewal
import (
"context"
- "errors"
+ "io"
"net/http"
"net/http/httptest"
"path/filepath"
+ "strconv"
"strings"
"sync/atomic"
"testing"
@@ -17,6 +18,12 @@ import (
apirenew "xianyu-go/internal/xianyu/renew"
)
+type schedulerRoundTripperFunc func(*http.Request) (*http.Response, error)
+
+func (f schedulerRoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
+ return f(req)
+}
+
func newSchedulerTestStore(t *testing.T) (*db.Store, func()) {
t.Helper()
d, _, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "renewal.db"))
@@ -26,64 +33,30 @@ func newSchedulerTestStore(t *testing.T) (*db.Store, func()) {
return db.NewStore(d, db.DialectSQLite), func() { d.Close() }
}
-type schedulerFakeBrowser struct {
- quickCookies string
- quickErr error
- quickCalls int
- quickInputs []string
+type schedulerFakeStarter struct {
+ starts atomic.Int32
+ restarts atomic.Int32
}
-type schedulerRefreshBrowser struct {
- refreshCalls int
+func (f *schedulerFakeStarter) Start(context.Context, string, string) error {
+ f.starts.Add(1)
+ return nil
}
-func (f *schedulerRefreshBrowser) BrowserQuickRenew(context.Context, string, string, bool) (string, error) {
- return "", errors.New("not implemented")
-}
-
-func (f *schedulerRefreshBrowser) CookiesRefreshSnapshot(_ context.Context, _ string, cookieStr string, snapshot []cookierefresh.BrowserCookie, _ bool) (string, []cookierefresh.BrowserCookie, error) {
- f.refreshCalls++
- return cookieStr, snapshot, nil
-}
-
-func (f *schedulerFakeBrowser) BrowserQuickRenew(_ context.Context, _ string, cookieStr string, _ bool) (string, error) {
- f.quickCalls++
- f.quickInputs = append(f.quickInputs, cookieStr)
- return f.quickCookies, f.quickErr
-}
-
-func (f *schedulerFakeBrowser) CookiesRefreshSnapshot(_ context.Context, _, _ string, _ []cookierefresh.BrowserCookie, _ bool) (string, []cookierefresh.BrowserCookie, error) {
- return "", nil, errors.New("not implemented")
+func (f *schedulerFakeStarter) Restart(context.Context, string) error {
+ f.restarts.Add(1)
+ return nil
}
type schedulerFakePasswordRefresher struct {
calls atomic.Int32
- ch chan string
}
-func (f *schedulerFakePasswordRefresher) OnPasswordLoginRefresh(_ context.Context, cookieID string) bool {
+func (f *schedulerFakePasswordRefresher) OnPasswordLoginRefresh(_ context.Context, _ string) bool {
f.calls.Add(1)
- if f.ch != nil {
- select {
- case f.ch <- cookieID:
- default:
- }
- }
return true
}
-func (f *schedulerFakePasswordRefresher) waitCookie(t *testing.T, want string) {
- t.Helper()
- select {
- case got := <-f.ch:
- if got != want {
- t.Fatalf("password refresher cookieID=%q want %q", got, want)
- }
- case <-time.After(time.Second):
- t.Fatalf("password refresher 未触发")
- }
-}
-
type apiRenewLogSnapshot struct {
status string
message string
@@ -157,7 +130,7 @@ func TestSchedulerDefaultsMatchUpstreamConfig(t *testing.T) {
store, cleanup := newSchedulerTestStore(t)
defer cleanup()
ctx := context.Background()
- s := NewScheduler(store, nil, nil, nil, nil)
+ s := NewScheduler(store, nil, nil, nil)
if s.settingEnabled(ctx, loginRenewEnabledSetting, false) {
t.Fatal("login_renew 未配置时应默认关闭")
@@ -184,7 +157,7 @@ func TestLoginRenewPreservesValidTokenCache(t *testing.T) {
}))
defer srv.Close()
- s := NewScheduler(store, nil, nil, nil, nil)
+ s := NewScheduler(store, nil, nil, nil)
s.mtop = &mtop.ClientImpl{HTTPClient: srv.Client(), LoginUserURL: srv.URL}
s.loginRenewOne(ctx, "batch-login-renew", account)
@@ -198,61 +171,73 @@ func TestLoginRenewPreservesValidTokenCache(t *testing.T) {
}
}
-func TestBrowserCookieRefreshSkipsManuallyDisabledAccount(t *testing.T) {
+func TestLoginRenewPersistsAuthoritativeSessionBeforeParseError(t *testing.T) {
store, cleanup := newSchedulerTestStore(t)
defer cleanup()
ctx := context.Background()
- account := createSchedulerAccount(t, store, "cid-manual-disabled", "unb=1; cookie2=c2")
- if err := store.Cookies.SetStatusWithReason(ctx, account.ID, false, db.DisableReasonManual); err != nil {
+ account := createSchedulerAccount(t, store, "cid-login-session-error",
+ "flat_leak=must-not-send; unb=1; _m_h5_tk=flat_old_1")
+ snapshot := []cookierefresh.BrowserCookie{
+ {Name: "unb", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "_m_h5_tk", Value: "snapshot_old_1", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "document_only", Value: "doc", Domain: "www.goofish.com", Path: "/im", Secure: true},
+ {Name: "api_only", Value: "api", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
+ }
+ metadata := cookierefresh.MetadataWithSnapshot(`{"preserved":"yes"}`, snapshot)
+ if err := store.Cookies.UpdateRenewalCookie(ctx, account.ID, account.Value, metadata, 1); err != nil {
t.Fatal(err)
}
- accounts, err := store.Cookies.AllRenewalAccounts(ctx)
- if err != nil || len(accounts) != 1 {
- t.Fatalf("accounts=%+v err=%v", accounts, err)
- }
- if accounts[0].DisableReason != db.DisableReasonManual {
- t.Fatalf("disable reason=%q", accounts[0].DisableReason)
- }
- browser := &schedulerRefreshBrowser{}
- s := NewScheduler(store, nil, browser, nil, nil)
- s.executeBrowserCookieRefresh(ctx)
- if browser.refreshCalls != 0 {
- t.Fatalf("manual disabled account refreshed %d times", browser.refreshCalls)
- }
- if store.Cookies.GetStatus(ctx, account.ID) {
- t.Fatal("manual disabled account must remain disabled")
- }
-}
-func TestNewSchedulerTreatsTypedNilBrowserAsDisabled(t *testing.T) {
- store, cleanup := newSchedulerTestStore(t)
- defer cleanup()
- ctx := context.Background()
- account := createSchedulerAccount(t, store, "cid-typed-nil-browser", "unb=1; cookie2=c2")
- refresher := &schedulerFakePasswordRefresher{ch: make(chan string, 1)}
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch r.URL.Path {
- case "/hasLogin.do", "/silentHasLogin.do", "/setLoginSettings.do":
- _, _ = w.Write([]byte(`{"content":{"success":true}}`))
- default:
- http.NotFound(w, r)
+ var requestCookie string
+ client := &http.Client{Transport: schedulerRoundTripperFunc(func(req *http.Request) (*http.Response, error) {
+ requestCookie = req.Header.Get("Cookie")
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Set-Cookie": []string{
+ "_m_h5_tk=snapshot_new_2; Domain=.goofish.com; Path=/; Secure",
+ "api_rotated=new; Path=/h5; Secure; HttpOnly",
+ }},
+ Body: io.NopCloser(strings.NewReader(`{"ret":`)),
+ Request: req,
+ }, nil
+ })}
+ s := NewScheduler(store, nil, nil, nil)
+ s.mtop = &mtop.ClientImpl{HTTPClient: client, LoginUserURL: mtop.LoginUserAPI}
+ s.loginRenewOne(ctx, "batch-login-session-error", account)
+
+ for _, want := range []string{"unb=1", "_m_h5_tk=snapshot_old_1", "api_only=api"} {
+ if !strings.Contains(requestCookie, want) {
+ t.Fatalf("请求 Cookie %q 未使用加锁后重读的权威 Jar,缺少 %q", requestCookie, want)
+ }
+ }
+ for _, unwanted := range []string{"flat_leak=", "document_only="} {
+ if strings.Contains(requestCookie, unwanted) {
+ t.Fatalf("请求 Cookie %q 泄漏了错误作用域 %q", requestCookie, unwanted)
}
- }))
- defer srv.Close()
-
- var typedNilBrowser *schedulerFakeBrowser
- s := NewScheduler(store, nil, typedNilBrowser, refresher, nil)
- if s.browser != nil {
- t.Fatal("typed nil BrowserRenewer 应被规范化为 nil")
}
- s.api = schedulerRenewServiceFromServer(srv)
- s.cooldown = NewCooldownManager()
- s.apiCookieRenewOne(ctx, "batch-typed-nil-browser", account)
- refresher.waitCookie(t, "cid-typed-nil-browser")
- log := lastAPIRenewLog(t, store, "cid-typed-nil-browser")
- if log.status != "need_password_login" || !strings.Contains(log.errorMessage, "浏览器自动化未启用") {
- t.Fatalf("typed nil browser 应按浏览器禁用处理: %+v", log)
+ detail, err := store.Cookies.GetDetails(ctx, account.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(detail.Value, "_m_h5_tk=snapshot_new_2") || strings.Contains(detail.Value, "flat_leak=") {
+ t.Fatalf("正文解析失败后未优先持久化响应 Cookie Jar: %q", detail.Value)
+ }
+ if !strings.Contains(detail.MetadataJSON, `"preserved":"yes"`) {
+ t.Fatalf("持久化 Jar 时丢失原 metadata: %s", detail.MetadataJSON)
+ }
+ gotSnapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
+ if !ok {
+ t.Fatalf("响应后权威 snapshot 丢失: %s", detail.MetadataJSON)
+ }
+ values := make(map[string]string, len(gotSnapshot))
+ for _, cookie := range gotSnapshot {
+ values[cookie.Name+"|"+cookie.Domain+"|"+cookie.Path] = cookie.Value
+ }
+ if values["_m_h5_tk|.goofish.com|/"] != "snapshot_new_2" ||
+ values["api_rotated|h5api.m.goofish.com|/h5"] != "new" ||
+ values["document_only|www.goofish.com|/im"] != "doc" {
+ t.Fatalf("响应后 snapshot 作用域不完整: %+v", gotSnapshot)
}
}
@@ -260,7 +245,7 @@ func TestSchedulerSettingEnabledOverrides(t *testing.T) {
store, cleanup := newSchedulerTestStore(t)
defer cleanup()
ctx := context.Background()
- s := NewScheduler(store, nil, nil, nil, nil)
+ s := NewScheduler(store, nil, nil, nil)
if err := store.Settings.Set(ctx, loginRenewEnabledSetting, "enabled"); err != nil {
t.Fatalf("Set enabled: %v", err)
@@ -280,7 +265,7 @@ func TestSchedulerSettingIntervalOverrides(t *testing.T) {
store, cleanup := newSchedulerTestStore(t)
defer cleanup()
ctx := context.Background()
- s := NewScheduler(store, nil, nil, nil, nil)
+ s := NewScheduler(store, nil, nil, nil)
if got := s.settingInterval(ctx, loginRenewIntervalSetting, loginRenewInterval); got != loginRenewInterval {
t.Fatalf("未配置间隔应返回默认值: %s", got)
@@ -309,7 +294,7 @@ func TestSchedulerSettingIntOverrides(t *testing.T) {
store, cleanup := newSchedulerTestStore(t)
defer cleanup()
ctx := context.Background()
- s := NewScheduler(store, nil, nil, nil, nil)
+ s := NewScheduler(store, nil, nil, nil)
if got := s.settingInt(ctx, "missing_int", 10); got != 10 {
t.Fatalf("missing setting=%d want 10", got)
@@ -352,7 +337,7 @@ func TestRenewalCleanupLogsUsesRetentionDays(t *testing.T) {
if err := store.Settings.Set(ctx, "renewal_log_retention_days", "10"); err != nil {
t.Fatalf("set retention: %v", err)
}
- s := NewScheduler(store, nil, nil, nil, nil)
+ s := NewScheduler(store, nil, nil, nil)
s.cleanupExpiredLogs(ctx)
for _, table := range []string{
"scheduled_cookies_refresh_log",
@@ -372,169 +357,56 @@ func TestRenewalCleanupLogsUsesRetentionDays(t *testing.T) {
}
}
-func TestAPICookieRenewOneSavesPartialCookiesBeforePasswordLogin(t *testing.T) {
+func TestAPICookieRenewOneSkipsExpiredLongLoginWithoutEscalation(t *testing.T) {
store, cleanup := newSchedulerTestStore(t)
defer cleanup()
ctx := context.Background()
- account := createSchedulerAccount(t, store, "cid-partial", "unb=1; cookie2=c2")
- refresher := &schedulerFakePasswordRefresher{ch: make(chan string, 1)}
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch r.URL.Path {
- case "/hasLogin.do":
- http.SetCookie(w, &http.Cookie{Name: "sgcookie", Value: "s1"})
- _, _ = w.Write([]byte(`{"content":{"success":true}}`))
- case "/silentHasLogin.do":
- http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "tk_1"})
- _, _ = w.Write([]byte(`{"content":{"success":true},"marker":"silent-partial"}`))
- case "/setLoginSettings.do":
- _, _ = w.Write([]byte(`{"content":{"success":false}}`))
- default:
- http.NotFound(w, r)
- }
- }))
- defer srv.Close()
+ account := createSchedulerAccount(t, store, "cid-expired", "unb=1; cookie2=c2")
+ refresher := &schedulerFakePasswordRefresher{}
+ s := NewScheduler(store, nil, refresher, nil)
+ s.apiCookieRenewOne(ctx, "batch-expired", account)
- s := NewScheduler(store, nil, nil, refresher, nil)
- s.api = schedulerRenewServiceFromServer(srv)
- s.cooldown = NewCooldownManager()
- s.apiCookieRenewOne(ctx, "batch-partial", account)
- refresher.waitCookie(t, "cid-partial")
-
- got, err := store.Cookies.GetValue(ctx, "cid-partial")
- if err != nil {
- t.Fatalf("GetValue: %v", err)
+ if refresher.calls.Load() != 0 {
+ t.Fatalf("proactive renewal escalated to account recovery: %d", refresher.calls.Load())
}
- for _, want := range []string{"sgcookie=s1", "_m_h5_tk=tk_1"} {
- if !strings.Contains(got, want) {
- t.Fatalf("部分 Cookie 未保存,缺少 %s: %q", want, got)
- }
- }
- log := lastAPIRenewLog(t, store, "cid-partial")
- if log.status != "need_password_login" {
- t.Fatalf("status=%q want need_password_login, log=%+v", log.status, log)
- }
- if !strings.Contains(log.updatedCookieNames, "sgcookie") || !strings.Contains(log.updatedCookieNames, "_m_h5_tk") {
- t.Fatalf("updated_cookie_names 未记录部分更新: %+v", log)
- }
- if !strings.Contains(log.responseContent, "silent-partial") {
- t.Fatalf("response_content 应记录 silentHasLogin 响应: %+v", log)
+ log := lastAPIRenewLog(t, store, account.ID)
+ if log.status != "skipped" || !strings.Contains(log.stepDetails, "long_login_expired") {
+ t.Fatalf("expired long login log=%+v", log)
}
}
-func TestAPICookieRenewOneSavesBrowserCookiesWhenVerifyFails(t *testing.T) {
+func TestAPICookieRenewOneUsesSingleSilentRequestAndSavesCookies(t *testing.T) {
store, cleanup := newSchedulerTestStore(t)
defer cleanup()
ctx := context.Background()
- account := createSchedulerAccount(t, store, "cid-browser-fail", "unb=1; cookie2=c2")
- browser := &schedulerFakeBrowser{quickCookies: "unb=1; cookie2=c2; sgcookie=s1; _m_h5_tk=tk_1; browser=b1"}
- refresher := &schedulerFakePasswordRefresher{ch: make(chan string, 1)}
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch r.URL.Path {
- case "/hasLogin.do":
- http.SetCookie(w, &http.Cookie{Name: "sgcookie", Value: "s1"})
- _, _ = w.Write([]byte(`{"content":{"success":true}}`))
- case "/silentHasLogin.do":
- http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "tk_1"})
- _, _ = w.Write([]byte(`{"content":{"success":true},"marker":"silent-browser-fail"}`))
- case "/setLoginSettings.do":
- _, _ = w.Write([]byte(`{"content":{"success":true}}`))
- default:
- http.NotFound(w, r)
- }
+ expire := strconv.FormatInt(time.Now().Add(time.Hour).UnixMilli(), 10)
+ account := createSchedulerAccount(t, store, "cid-silent", "unb=1; cookie2=c2; havana_lgc_exp="+expire)
+ refresher := &schedulerFakePasswordRefresher{}
+ starter := &schedulerFakeStarter{}
+ var requests atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ requests.Add(1)
+ http.SetCookie(w, &http.Cookie{Name: "sdkSilent", Value: strconv.FormatInt(time.Now().Add(time.Hour).UnixMilli(), 10)})
+ _, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}},"marker":"single-silent"}`))
}))
defer srv.Close()
- s := NewScheduler(store, nil, browser, refresher, nil)
+ s := NewScheduler(store, starter, refresher, nil)
s.api = schedulerRenewServiceFromServer(srv)
- s.cooldown = NewCooldownManager()
- s.apiCookieRenewOne(ctx, "batch-browser-fail", account)
- refresher.waitCookie(t, "cid-browser-fail")
+ s.apiCookieRenewOne(ctx, "batch-silent", account)
- if browser.quickCalls != 1 {
- t.Fatalf("BrowserQuickRenew calls=%d want 1", browser.quickCalls)
+ if requests.Load() != 1 || refresher.calls.Load() != 0 {
+ t.Fatalf("requests=%d recovery=%d", requests.Load(), refresher.calls.Load())
}
- if len(browser.quickInputs) != 1 || !strings.Contains(browser.quickInputs[0], "sgcookie=s1") || !strings.Contains(browser.quickInputs[0], "_m_h5_tk=tk_1") {
- t.Fatalf("浏览器续期输入未使用接口部分更新: %#v", browser.quickInputs)
+ if starter.restarts.Load() != 1 || starter.starts.Load() != 0 {
+ t.Fatalf("官网静默续期成功应模拟 reload 重建运行时: starts=%d restarts=%d", starter.starts.Load(), starter.restarts.Load())
}
- got, err := store.Cookies.GetValue(ctx, "cid-browser-fail")
- if err != nil {
- t.Fatalf("GetValue: %v", err)
+ got, err := store.Cookies.GetValue(ctx, account.ID)
+ if err != nil || !strings.Contains(got, "sdkSilent=") {
+ t.Fatalf("silent Cookie not saved: value=%q err=%v", got, err)
}
- for _, want := range []string{"sgcookie=s1", "_m_h5_tk=tk_1", "browser=b1"} {
- if !strings.Contains(got, want) {
- t.Fatalf("浏览器 Cookie 未保存,缺少 %s: %q", want, got)
- }
- }
- log := lastAPIRenewLog(t, store, "cid-browser-fail")
- if log.status != "need_password_login" {
- t.Fatalf("status=%q want need_password_login, log=%+v", log.status, log)
- }
- if !strings.Contains(log.updatedCookieNames, "browser") {
- t.Fatalf("updated_cookie_names 未记录浏览器更新: %+v", log)
- }
-}
-
-func TestAPICookieRenewOneBrowserRenewedAfterVerifySuccess(t *testing.T) {
- store, cleanup := newSchedulerTestStore(t)
- defer cleanup()
- ctx := context.Background()
- account := createSchedulerAccount(t, store, "cid-browser-ok", "unb=1; cookie2=c2")
- if err := store.Tokens.Save(ctx, account.ID, "did-stable", "cached-token", time.Now().Add(time.Hour).Unix()); err != nil {
- t.Fatalf("Save token: %v", err)
- }
- browser := &schedulerFakeBrowser{quickCookies: "unb=1; cookie2=c2; browser=b1"}
- var setLoginCalls atomic.Int32
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch r.URL.Path {
- case "/hasLogin.do":
- _, _ = w.Write([]byte(`{"content":{"success":true}}`))
- case "/silentHasLogin.do":
- _, _ = w.Write([]byte(`{"content":{"success":true},"marker":"silent-browser-ok"}`))
- case "/setLoginSettings.do":
- if setLoginCalls.Add(1) == 2 {
- http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "lgc"})
- }
- _, _ = w.Write([]byte(`{"content":{"success":true}}`))
- default:
- http.NotFound(w, r)
- }
- }))
- defer srv.Close()
-
- s := NewScheduler(store, nil, browser, nil, nil)
- s.api = schedulerRenewServiceFromServer(srv)
- s.cooldown = NewCooldownManager()
- s.apiCookieRenewOne(ctx, "batch-browser-ok", account)
- if token, err := store.Tokens.Get(ctx, account.ID); err != nil || token.AccessToken != "cached-token" {
- t.Fatalf("定时续期不得删除有效 token 缓存: token=%+v err=%v", token, err)
- }
-
- if browser.quickCalls != 1 || setLoginCalls.Load() != 2 {
- t.Fatalf("browser calls=%d setLoginCalls=%d", browser.quickCalls, setLoginCalls.Load())
- }
- got, err := store.Cookies.GetValue(ctx, "cid-browser-ok")
- if err != nil {
- t.Fatalf("GetValue: %v", err)
- }
- for _, want := range []string{"browser=b1", "havana_lgc2_77=lgc"} {
- if !strings.Contains(got, want) {
- t.Fatalf("最终 Cookie 缺少 %s: %q", want, got)
- }
- }
- log := lastAPIRenewLog(t, store, "cid-browser-ok")
- if log.status != "browser_renewed" {
- t.Fatalf("status=%q want browser_renewed, log=%+v", log.status, log)
- }
- if !strings.Contains(log.responseContent, "silent-browser-ok") {
- t.Fatalf("response_content 应记录验证阶段 silentHasLogin 响应: %+v", log)
- }
- if log.renewMethod != "browser+api" || log.requestCount != 6 {
- t.Fatalf("浏览器兜底日志应记录方法和请求数: %+v", log)
- }
- if !strings.Contains(log.stepDetails, "browser: quick_enter") || !strings.Contains(log.stepDetails, "api_verify") {
- t.Fatalf("step_details 未记录浏览器兜底步骤: %+v", log)
- }
- if log.durationMS < 0 {
- t.Fatalf("duration_ms 不应为负数: %+v", log)
+ log := lastAPIRenewLog(t, store, account.ID)
+ if log.status != "cookie_updated" || log.requestCount != 1 || !strings.Contains(log.responseContent, "single-silent") {
+ t.Fatalf("silent renewal log=%+v", log)
}
}
diff --git a/internal/server/automation_handlers.go b/internal/server/automation_handlers.go
index a81d61f..dc1319f 100644
--- a/internal/server/automation_handlers.go
+++ b/internal/server/automation_handlers.go
@@ -266,8 +266,8 @@ func (s *Server) normalizeAutomationRuleRequest(r *http.Request, userID int64, r
if act.DeliveryCount <= 0 {
act.DeliveryCount = 1
}
- if act.DelaySeconds < 0 || act.DelaySeconds > 86400 {
- return db.AutomationRuleInput{}, errStr("动作延时必须在 0 到 86400 秒之间")
+ if act.DelaySeconds < 0 || act.DelaySeconds > 3600 {
+ return db.AutomationRuleInput{}, errStr("动作延时必须在 0 到 3600 秒之间")
}
if act.ConfigJSON == "" {
act.ConfigJSON = "{}"
diff --git a/internal/server/card_batch_handlers.go b/internal/server/card_batch_handlers.go
index 68173d8..314c17d 100644
--- a/internal/server/card_batch_handlers.go
+++ b/internal/server/card_batch_handlers.go
@@ -92,8 +92,8 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
continue
}
delaySeconds := atoiPublishDefault(firstImportString(m, "delay_seconds", "延迟秒"), 0)
- if delaySeconds < 0 || delaySeconds > 86400 {
- results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "延时发货必须在 0 到 86400 秒之间"})
+ if delaySeconds < 0 || delaySeconds > 3600 {
+ results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "延时发货必须在 0 到 3600 秒之间"})
failed++
continue
}
diff --git a/internal/server/card_handlers.go b/internal/server/card_handlers.go
index 4920486..35758f8 100644
--- a/internal/server/card_handlers.go
+++ b/internal/server/card_handlers.go
@@ -136,8 +136,8 @@ func decodeCard(r *http.Request) (*db.CardFull, error) {
default:
return nil, errStr("类型必须为 text、data、image 或 api")
}
- if req.DelaySeconds < 0 || req.DelaySeconds > 86400 {
- return nil, errStr("延时发货必须在 0 到 86400 秒之间")
+ if req.DelaySeconds < 0 || req.DelaySeconds > 3600 {
+ return nil, errStr("延时发货必须在 0 到 3600 秒之间")
}
switch req.Type {
case "text":
diff --git a/internal/server/cookie_handlers.go b/internal/server/cookie_handlers.go
index 97724d8..fa7ea94 100644
--- a/internal/server/cookie_handlers.go
+++ b/internal/server/cookie_handlers.go
@@ -3,6 +3,7 @@ package server
import (
"context"
"errors"
+ "fmt"
"net/http"
"strings"
"time"
@@ -13,6 +14,8 @@ import (
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
"xianyu-go/internal/engine"
+ "xianyu-go/internal/xianyu/cookierefresh"
+ xrenew "xianyu-go/internal/xianyu/renew"
)
// mountCookies 账号 cookie 管理端点。
@@ -24,6 +27,8 @@ func (s *Server) mountCookies(r chi.Router) {
r.Put("/cookies/{cid}", s.updateCookie)
r.Put("/cookies/{cid}/login-info", s.updateCookieLoginInfo)
r.Put("/cookies/{cid}/settings", s.updateCookieSettings)
+ r.Get("/cookies/{cid}/long-login", s.getLongLoginSettings)
+ r.Put("/cookies/{cid}/long-login", s.setLongLoginSettings)
r.Post("/cookies/{cid}/refresh-profile", s.refreshCookieProfile)
r.Get("/cookie/{cid}/details", s.getCookieDetails)
r.Put("/cookies/{cid}/status", s.setCookieStatus)
@@ -35,6 +40,169 @@ func (s *Server) mountCookies(r chi.Router) {
r.Get("/cookies/{cid}/pause-duration", s.getCookiePauseDuration)
}
+func (s *Server) getLongLoginSettings(w http.ResponseWriter, r *http.Request) {
+ cid := chi.URLParam(r, "cid")
+ ownedDetail, ok := s.requireCookieOwner(w, r, cid)
+ if !ok {
+ return
+ }
+ credentialUnlock := s.Store.LockAccountCredentials(cid)
+ detail, err := s.Store.Cookies.GetDetails(r.Context(), cid)
+ if err != nil || detail == nil || detail.UserID != ownedDetail.UserID {
+ credentialUnlock()
+ writeErr(w, http.StatusNotFound, "账号不存在")
+ return
+ }
+ requestCookies := scopedCookieHeader(detail, xrenew.QueryLoginSettingsURL)
+ var result *xrenew.LongLoginSettings
+ var requestErr error
+ if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
+ result, requestErr = s.CookieRenew.QueryLongLoginSettings(r.Context(), requestCookies, snapshot)
+ } else {
+ result, requestErr = s.CookieRenew.QueryLongLoginSettings(r.Context(), requestCookies)
+ }
+ credentialChanged, persistErr := s.persistLongLoginCookies(r.Context(), detail, result, xrenew.QueryLoginSettingsURL)
+ credentialUnlock()
+ if persistErr != nil {
+ writeErr(w, http.StatusInternalServerError, "保存续期 Cookie 失败")
+ return
+ }
+ if credentialChanged {
+ s.updateRunningCookie(r.Context(), cid, result.NewCookies)
+ }
+ if requestErr != nil {
+ writeErr(w, http.StatusBadGateway, requestErr.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, result)
+}
+
+func (s *Server) setLongLoginSettings(w http.ResponseWriter, r *http.Request) {
+ cid := chi.URLParam(r, "cid")
+ ownedDetail, ok := s.requireCookieOwner(w, r, cid)
+ if !ok {
+ return
+ }
+ var req struct {
+ Enabled *bool `json:"enabled"`
+ }
+ if err := decodeJSON(r, &req); err != nil || req.Enabled == nil {
+ writeErr(w, http.StatusBadRequest, "请求格式错误")
+ return
+ }
+ credentialUnlock := s.Store.LockAccountCredentials(cid)
+ detail, err := s.Store.Cookies.GetDetails(r.Context(), cid)
+ if err != nil || detail == nil || detail.UserID != ownedDetail.UserID {
+ credentialUnlock()
+ writeErr(w, http.StatusNotFound, "账号不存在")
+ return
+ }
+ requestCookies := scopedCookieHeader(detail, xrenew.SetLoginSettingsURL)
+ var result *xrenew.LongLoginSettings
+ var requestErr error
+ if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
+ result, requestErr = s.CookieRenew.SetLongLoginSettings(r.Context(), requestCookies, *req.Enabled, snapshot)
+ } else {
+ result, requestErr = s.CookieRenew.SetLongLoginSettings(r.Context(), requestCookies, *req.Enabled)
+ }
+ credentialChanged, persistErr := s.persistLongLoginCookies(r.Context(), detail, result, xrenew.SetLoginSettingsURL)
+ credentialUnlock()
+ if persistErr != nil {
+ writeErr(w, http.StatusInternalServerError, "保存续期 Cookie 失败")
+ return
+ }
+ if credentialChanged {
+ s.updateRunningCookie(r.Context(), cid, result.NewCookies)
+ }
+ if requestErr != nil {
+ writeErr(w, http.StatusBadGateway, requestErr.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, result)
+}
+
+// persistLongLoginCookies 必须在账号凭证锁内调用。它只更新持久化状态;
+// 运行中实例的 Cookie 更新必须等调用方释放凭证锁后再执行。
+func (s *Server) persistLongLoginCookies(ctx context.Context, detail *db.CookieDetail, result *xrenew.LongLoginSettings, requestURL string) (bool, error) {
+ if result == nil || detail == nil {
+ return false, nil
+ }
+ metadata := detail.MetadataJSON
+ snapshot, hasSnapshot := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
+ if result.CookieSnapshotComplete {
+ snapshot = cookierefresh.NormalizeSnapshot(result.CookieSnapshot)
+ if snapshot == nil {
+ snapshot = []cookierefresh.BrowserCookie{}
+ }
+ result.NewCookies, _ = cookierefresh.ScopedCookieHeaderForRequest(
+ snapshot, "https://www.goofish.com/im", "https://goofish.com", time.Now(),
+ )
+ metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot)
+ } else if hasSnapshot {
+ // 兼容非标准 Service 实现:只有未返回最终 Jar 时才按当前请求 URL
+ // 应用响应头;官方 Service 会在 SET→QUERY 间逐请求维护完整 Jar。
+ snapshot = cookierefresh.ApplySetCookies(snapshot, requestURL, result.SetCookies, time.Now(), "https://goofish.com")
+ if snapshot == nil {
+ snapshot = []cookierefresh.BrowserCookie{}
+ }
+ result.NewCookies, _ = cookierefresh.ScopedCookieHeaderForRequest(
+ snapshot, "https://www.goofish.com/im", "https://goofish.com", time.Now(),
+ )
+ metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot)
+ } else {
+ // 历史账号只有扁平 Cookie 时只能合并兼容值,不能凭空推断完整
+ // Domain/Path/HttpOnly/PartitionKey 属性。
+ result.NewCookies = xrenew.MergeSetCookies(detail.Value, result.SetCookies)
+ metadata = cookierefresh.MetadataWithoutSnapshot(metadata)
+ }
+ credentialChanged := result.NewCookies != detail.Value || metadata != detail.MetadataJSON
+ if !credentialChanged && len(result.SetCookies) == 0 {
+ return false, nil
+ }
+ if err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, result.NewCookies, metadata, time.Now().Unix()); err != nil {
+ s.Logger.Warn("保存长登录 Cookie 失败", "cookie_id", detail.ID, "err", err)
+ return false, err
+ }
+ if credentialChanged && s.Store.Tokens != nil {
+ if err := s.Store.Tokens.Clear(ctx, detail.ID); err != nil {
+ s.Logger.Warn("长登录 Cookie 保存后清理旧连接凭证失败", "cookie_id", detail.ID, "err", err)
+ }
+ }
+ return credentialChanged, nil
+}
+
+// updateFlatCookieOwnedLocked 用新的扁平 Cookie 覆盖账号时同步移除旧浏览器
+// 快照,避免下一次浏览器取 token 又把旧 Cookie 注入回来。调用方必须持有
+// 对应账号的凭证锁,并已验证 detail 的归属。
+func (s *Server) updateFlatCookieOwnedLocked(ctx context.Context, detail *db.CookieDetail, value string) error {
+ if detail == nil {
+ return db.ErrNotFound
+ }
+ metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
+ return s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix())
+}
+
+func (s *Server) updateRunningCookie(ctx context.Context, cookieID, value string) {
+ if s.Manager == nil || !s.Store.Cookies.GetStatus(ctx, cookieID) {
+ return
+ }
+ if sender, ok := s.Manager.GetInstance(cookieID); ok {
+ sender.UpdateCookie(value)
+ }
+}
+
+func scopedCookieHeader(detail *db.CookieDetail, requestURL string) string {
+ if detail == nil {
+ return ""
+ }
+ if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); ok {
+ if header, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, "https://goofish.com", time.Now()); authoritative {
+ return header
+ }
+ }
+ return detail.Value
+}
+
type updateCookieSettingsRequest struct {
Cookie *string `json:"cookie"`
Remark *string `json:"remark"`
@@ -76,6 +244,15 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
return
}
+ credentialUnlock := s.Store.LockAccountCredentials(cid)
+ latestDetail, err := s.Store.Cookies.GetDetails(r.Context(), cid)
+ if err != nil || latestDetail == nil || latestDetail.UserID != detail.UserID {
+ credentialUnlock()
+ writeErr(w, http.StatusNotFound, "账号不存在")
+ return
+ }
+ detail = latestDetail
+
input := db.AccountSettingsUpdate{
UserID: detail.UserID,
Value: req.Cookie,
@@ -107,6 +284,7 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
}
pausedUntil, err := s.Store.Cookies.UpdateSettings(r.Context(), cid, input)
if err != nil {
+ credentialUnlock()
switch {
case errors.Is(err, db.ErrForbidden):
writeErr(w, http.StatusForbidden, "账号设置包含无权限使用的资源")
@@ -117,9 +295,16 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
}
return
}
- if req.Cookie != nil && s.Store.Tokens != nil {
- _ = s.Store.Tokens.Clear(r.Context(), cid)
+ if req.Cookie != nil {
+ // UpdateSettings 已在同一事务中写入 Cookie 并清除旧快照,不能再做
+ // 第二次非原子覆盖。
+ if s.Store.Tokens != nil {
+ if err := s.Store.Tokens.Clear(r.Context(), cid); err != nil {
+ s.Logger.Warn("账号设置保存后清理旧连接凭证失败", "cookie_id", cid, "err", err)
+ }
+ }
}
+ credentialUnlock()
if req.Cookie != nil && s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), cid) {
if err := s.Manager.Restart(r.Context(), cid); err != nil {
s.Logger.Error("账号设置保存后重启失败", "cookie_id", cid, "err", err)
@@ -277,7 +462,9 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
return
}
sess := auth.SessionFromContext(r.Context())
+ credentialUnlock := s.Store.LockAccountCredentials(req.ID)
if err := s.Store.Cookies.CreateOwned(r.Context(), req.ID, req.Value, sess.UserID); err != nil {
+ credentialUnlock()
if errors.Is(err, db.ErrForbidden) {
writeErr(w, http.StatusForbidden, "该账号ID已存在且不属于当前用户")
return
@@ -290,16 +477,19 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
return
}
if s.Store.Tokens != nil {
- _ = s.Store.Tokens.Clear(r.Context(), req.ID)
- }
- if d, err := s.Store.Cookies.GetDetails(r.Context(), req.ID); err == nil {
- s.refreshAccountProfile(r.Context(), d)
+ if err := s.Store.Tokens.Clear(r.Context(), req.ID); err != nil {
+ s.Logger.Warn("新增账号后清理旧连接凭证失败", "cookie_id", req.ID, "err", err)
+ }
}
loginMethod := normalizeLoginMethod(req.LoginMethod)
if loginMethod == "" {
loginMethod = loginMethodManual
}
s.markSuccessfulLogin(r.Context(), req.ID, sess.UserID, loginMethod, "账号登录成功")
+ credentialUnlock()
+ if d, err := s.Store.Cookies.GetDetails(r.Context(), req.ID); err == nil {
+ s.refreshAccountProfile(r.Context(), d)
+ }
if s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), req.ID) {
if err := s.Manager.Restart(r.Context(), req.ID); err != nil {
s.Logger.Error("更新后重启账号失败", "cookie_id", req.ID, "err", err)
@@ -311,7 +501,8 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
// updateCookie 更新 cookie 值。
func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
- if _, ok := s.requireCookieOwner(w, r, cid); !ok {
+ ownedDetail, ok := s.requireCookieOwner(w, r, cid)
+ if !ok {
return
}
var req struct {
@@ -323,7 +514,15 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
return
}
sess := auth.SessionFromContext(r.Context())
- if err := s.Store.Cookies.UpdateValueOwned(r.Context(), cid, req.Value, sess.UserID); err != nil {
+ credentialUnlock := s.Store.LockAccountCredentials(cid)
+ detail, err := s.Store.Cookies.GetDetails(r.Context(), cid)
+ if err != nil || detail == nil || detail.UserID != ownedDetail.UserID || detail.UserID != sess.UserID {
+ credentialUnlock()
+ writeErr(w, http.StatusNotFound, "账号不存在")
+ return
+ }
+ if err := s.updateFlatCookieOwnedLocked(r.Context(), detail, req.Value); err != nil {
+ credentialUnlock()
if errors.Is(err, db.ErrForbidden) {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return
@@ -332,14 +531,17 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
return
}
if s.Store.Tokens != nil {
- _ = s.Store.Tokens.Clear(r.Context(), cid)
- }
- if d, err := s.Store.Cookies.GetDetails(r.Context(), cid); err == nil {
- s.refreshAccountProfile(r.Context(), d)
+ if err := s.Store.Tokens.Clear(r.Context(), cid); err != nil {
+ s.Logger.Warn("更新账号后清理旧连接凭证失败", "cookie_id", cid, "err", err)
+ }
}
if loginMethod := normalizeLoginMethod(req.LoginMethod); loginMethod != "" {
s.markSuccessfulLogin(r.Context(), cid, sess.UserID, loginMethod, "账号登录成功")
}
+ credentialUnlock()
+ if d, err := s.Store.Cookies.GetDetails(r.Context(), cid); err == nil {
+ s.refreshAccountProfile(r.Context(), d)
+ }
if s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), cid) {
if err := s.Manager.Restart(r.Context(), cid); err != nil {
s.Logger.Error("更新后重启账号失败", "cookie_id", cid, "err", err)
@@ -385,7 +587,8 @@ func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
// setCookieStatus 启用/禁用账号。
func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
- if _, ok := s.requireCookieOwner(w, r, cid); !ok {
+ ownedDetail, ok := s.requireCookieOwner(w, r, cid)
+ if !ok {
return
}
var req struct {
@@ -399,10 +602,19 @@ func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
if !req.Enabled {
reason = db.DisableReasonManual
}
+ credentialUnlock := s.Store.LockAccountCredentials(cid)
+ latest, err := s.Store.Cookies.GetDetails(r.Context(), cid)
+ if err != nil || latest == nil || latest.UserID != ownedDetail.UserID {
+ credentialUnlock()
+ writeErr(w, http.StatusNotFound, "账号不存在")
+ return
+ }
if err := s.Store.Cookies.SetStatusWithReason(r.Context(), cid, req.Enabled, reason); err != nil {
+ credentialUnlock()
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
+ credentialUnlock()
// 启停引擎实例。
if s.Manager != nil {
if req.Enabled {
@@ -422,16 +634,28 @@ func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
// deleteCookie 删除账号。
func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
- if _, ok := s.requireCookieOwner(w, r, cid); !ok {
+ ownedDetail, ok := s.requireCookieOwner(w, r, cid)
+ if !ok {
return
}
- if s.Manager != nil {
- s.Manager.Stop(cid)
+ credentialUnlock := s.Store.LockAccountCredentials(cid)
+ latest, err := s.Store.Cookies.GetDetails(r.Context(), cid)
+ if err != nil || latest == nil || latest.UserID != ownedDetail.UserID {
+ credentialUnlock()
+ writeErr(w, http.StatusNotFound, "账号不存在")
+ return
}
if err := s.Store.Cookies.Delete(r.Context(), cid); err != nil {
+ credentialUnlock()
writeErr(w, http.StatusInternalServerError, "删除失败")
return
}
+ credentialUnlock()
+ // Stop 会等待 Account.Run 退出,而 Run 可能正在等待同一凭证锁,因此必须
+ // 在删除事务完成并释放锁后调用。
+ if s.Manager != nil {
+ s.Manager.Stop(cid)
+ }
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
@@ -540,19 +764,57 @@ func (s *Server) refreshAccountProfile(ctx context.Context, d *db.CookieDetail)
return cachedAccountNickname(d), d.AvatarURL, "账号资料客户端未初始化"
}
- profile, err := s.MTop.FetchUserProfile(ctx, d.Value)
- if err != nil {
- if s.Logger != nil {
- s.Logger.Warn("刷新账号资料失败", "account", d.ID, "err", err)
+ credentialUnlock := s.Store.LockAccountCredentials(d.ID)
+ latest, latestErr := s.Store.Cookies.GetDetails(ctx, d.ID)
+ if latestErr != nil || latest == nil || latest.UserID != d.UserID {
+ credentialUnlock()
+ if latestErr == nil {
+ latestErr = db.ErrNotFound
}
- return cachedAccountNickname(d), d.AvatarURL, truncate(err.Error(), 180)
+ return cachedAccountNickname(d), d.AvatarURL, truncate(latestErr.Error(), 180)
}
-
- if profile.UpdatedCookies != "" && profile.UpdatedCookies != d.Value {
- if err := s.Store.Cookies.UpdateValueOwned(ctx, d.ID, profile.UpdatedCookies, d.UserID); err != nil && s.Logger != nil {
- s.Logger.Warn("保存账号刷新 cookie 失败", "account", d.ID, "err", err)
+ mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
+ profile, callErr := s.MTop.FetchUserProfile(mtopCtx, latest.Value)
+ runtimeCookie := ""
+ runtimeCookieChanged := false
+ value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
+ if persistErr != nil {
+ if s.Logger != nil {
+ s.Logger.Warn("保存账号资料响应 Cookie Jar 失败", "account", d.ID, "err", persistErr)
}
- d.Value = profile.UpdatedCookies
+ callErr = errors.Join(callErr, fmt.Errorf("保存账号资料响应凭证: %w", persistErr))
+ } else if handled {
+ if valueChanged {
+ runtimeCookie = value
+ runtimeCookieChanged = true
+ }
+ d.Value = value
+ } else if callErr == nil && profile != nil && profile.UpdatedCookies != "" && profile.UpdatedCookies != latest.Value {
+ // 注入 mock 或没有权威快照的历史账号继续沿用扁平 Cookie 路径;
+ // 该路径必须清除旧 snapshot,不能伪造完整 Jar。
+ if err := s.updateFlatCookieOwnedLocked(ctx, latest, profile.UpdatedCookies); err != nil {
+ if s.Logger != nil {
+ s.Logger.Warn("保存账号刷新 cookie 失败", "account", d.ID, "err", err)
+ }
+ callErr = errors.Join(callErr, fmt.Errorf("保存账号资料响应凭证: %w", err))
+ } else {
+ runtimeCookie = profile.UpdatedCookies
+ runtimeCookieChanged = true
+ d.Value = profile.UpdatedCookies
+ }
+ }
+ credentialUnlock()
+ if runtimeCookieChanged {
+ s.updateRunningCookie(ctx, d.ID, runtimeCookie)
+ }
+ if callErr != nil {
+ if s.Logger != nil {
+ s.Logger.Warn("刷新账号资料失败", "account", d.ID, "err", callErr)
+ }
+ return cachedAccountNickname(d), d.AvatarURL, truncate(callErr.Error(), 180)
+ }
+ if profile == nil {
+ return cachedAccountNickname(d), d.AvatarURL, "账号资料接口未返回结果"
}
apiNickname := strings.TrimSpace(profile.Nickname)
diff --git a/internal/server/cookie_handlers_test.go b/internal/server/cookie_handlers_test.go
index e2d1ee2..7b4d3a6 100644
--- a/internal/server/cookie_handlers_test.go
+++ b/internal/server/cookie_handlers_test.go
@@ -11,8 +11,195 @@ import (
"time"
"xianyu-go/internal/db"
+ "xianyu-go/internal/xianyu/cookierefresh"
+ xrenew "xianyu-go/internal/xianyu/renew"
)
+func seedStaleCookieSnapshot(t *testing.T, store *db.Store, cookieID string) {
+ t.Helper()
+ ctx := context.Background()
+ detail, err := store.Cookies.GetDetails(ctx, cookieID)
+ if err != nil {
+ t.Fatalf("GetDetails before seeding snapshot: %v", err)
+ }
+ metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, []cookierefresh.BrowserCookie{{
+ Name: "stale_snapshot", Value: "old", Domain: ".goofish.com", Path: "/",
+ }})
+ if err := store.Cookies.UpdateRenewalCookie(ctx, cookieID, detail.Value, metadata, time.Now().Unix()); err != nil {
+ t.Fatalf("seed stale snapshot: %v", err)
+ }
+}
+
+func requireCookieSnapshotCleared(t *testing.T, store *db.Store, cookieID string) {
+ t.Helper()
+ detail, err := store.Cookies.GetDetails(context.Background(), cookieID)
+ if err != nil {
+ t.Fatalf("GetDetails after cookie overwrite: %v", err)
+ }
+ if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); ok {
+ t.Fatalf("扁平 Cookie 覆盖后必须清除旧快照: %+v", snapshot)
+ }
+}
+
+func TestLongLoginSettingsProxyAndPersistCookieSnapshot(t *testing.T) {
+ passport := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Query().Get("fromSite") != "77" || r.URL.Query().Get("appName") != "xianyu" || r.URL.Query().Get("bizEntrance") != "web" {
+ t.Fatalf("query=%s", r.URL.RawQuery)
+ }
+ requestCookies := r.Header.Get("Cookie")
+ if !strings.Contains(requestCookies, "passport_only=allowed") || strings.Contains(requestCookies, "www_only=blocked") {
+ http.Error(w, "Cookie 未按 passport 域作用域发送: "+requestCookies, http.StatusBadRequest)
+ return
+ }
+ if strings.Contains(r.URL.Path, "set") {
+ if err := r.ParseForm(); err != nil || r.Form.Get("status") != "0" {
+ t.Fatalf("form=%v err=%v", r.Form, err)
+ }
+ }
+ w.Header().Add("Set-Cookie", "havana_lgc_exp=4102444800000; Domain=.goofish.com; Path=/; Secure; HttpOnly; SameSite=None")
+ if strings.Contains(r.URL.Path, "set") {
+ _, _ = w.Write([]byte(`{"data":{"success":true}}`))
+ return
+ }
+ _, _ = w.Write([]byte(`{"content":{"data":{"returnValue":{"canOpenLongLogin":true,"hasLongTokenLogin":true}}}}`))
+ }))
+ defer passport.Close()
+
+ srv, store, cleanup := newTestServer(t)
+ defer cleanup()
+ srv.CookieRenew = xrenew.Service{
+ HTTPClient: passport.Client(),
+ QueryLoginSettingsURL: passport.URL + "/queryLoginSettings.do",
+ SetLoginSettingsURL: passport.URL + "/setLoginSettings.do",
+ }
+ detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ snapshot := cookierefresh.SnapshotFromCookieString(detail.Value, ".goofish.com")
+ snapshot = append(snapshot,
+ cookierefresh.BrowserCookie{Name: "passport_only", Value: "allowed", Domain: ".goofish.com", Path: "/", Secure: true},
+ cookierefresh.BrowserCookie{Name: "www_only", Value: "blocked", Domain: "www.goofish.com", Path: "/", Secure: true},
+ )
+ metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
+ if err := store.Cookies.UpdateRenewalCookie(context.Background(), "acc1", detail.Value, metadata, time.Now().Unix()); err != nil {
+ t.Fatal(err)
+ }
+ h := srv.Router()
+ session := loginHelper(t, h)
+
+ for _, request := range []*http.Request{
+ httptest.NewRequest(http.MethodGet, "/cookies/acc1/long-login", nil),
+ httptest.NewRequest(http.MethodPut, "/cookies/acc1/long-login", strings.NewReader(`{"enabled":true}`)),
+ } {
+ request.AddCookie(session)
+ recorder := httptest.NewRecorder()
+ h.ServeHTTP(recorder, request)
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("%s status=%d body=%s", request.Method, recorder.Code, recorder.Body.String())
+ }
+ var result xrenew.LongLoginSettings
+ if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil || !result.CanOpenLongLogin || !result.Enabled {
+ t.Fatalf("result=%+v err=%v", result, err)
+ }
+ }
+
+ detail, err = store.Cookies.GetDetails(context.Background(), "acc1")
+ if err != nil || !strings.Contains(detail.Value, "havana_lgc_exp=4102444800000") {
+ t.Fatalf("cookie detail=%+v err=%v", detail, err)
+ }
+ snapshot = cookierefresh.SnapshotFromMetadata(detail.MetadataJSON)
+ var longLoginCookie *cookierefresh.BrowserCookie
+ for i := range snapshot {
+ if snapshot[i].Name == "havana_lgc_exp" {
+ longLoginCookie = &snapshot[i]
+ break
+ }
+ }
+ if longLoginCookie == nil || longLoginCookie.Domain != ".goofish.com" || !longLoginCookie.Secure || !longLoginCookie.HTTPOnly {
+ t.Fatalf("未保留 Set-Cookie 属性: %+v", snapshot)
+ }
+}
+
+func TestLongLoginFailureStillPersistsResponseCookiesWithoutInventingSnapshot(t *testing.T) {
+ passport := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Add("Set-Cookie", "rotated=fresh; Domain=.goofish.com; Path=/; Secure; HttpOnly")
+ _, _ = w.Write([]byte(`not-json`))
+ }))
+ defer passport.Close()
+
+ srv, store, cleanup := newTestServer(t)
+ defer cleanup()
+ srv.CookieRenew = xrenew.Service{
+ HTTPClient: passport.Client(),
+ QueryLoginSettingsURL: passport.URL + "/queryLoginSettings.do",
+ }
+ h := srv.Router()
+ session := loginHelper(t, h)
+ req := httptest.NewRequest(http.MethodGet, "/cookies/acc1/long-login", nil)
+ req.AddCookie(session)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusBadGateway {
+ t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
+ }
+ detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(detail.Value, "rotated=fresh") {
+ t.Fatalf("失败响应头的 Cookie 未持久化: %q", detail.Value)
+ }
+ if _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
+ t.Fatal("历史扁平 Cookie 不得因长登录响应伪造成完整浏览器 Jar")
+ }
+}
+
+func TestLongLoginAuthoritativeSnapshotCanBeDeletedToEmpty(t *testing.T) {
+ passport := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Add("Set-Cookie", "only_cookie=; Domain=.goofish.com; Path=/; Max-Age=0; Secure")
+ _, _ = w.Write([]byte(`{"content":{"data":{"returnValue":{"canOpenLongLogin":true,"hasLongTokenLogin":true}}}}`))
+ }))
+ defer passport.Close()
+
+ srv, store, cleanup := newTestServer(t)
+ defer cleanup()
+ detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, []cookierefresh.BrowserCookie{{
+ Name: "only_cookie", Value: "old", Domain: ".goofish.com", Path: "/", Secure: true,
+ }})
+ if err := store.Cookies.UpdateRenewalCookie(context.Background(), "acc1", "only_cookie=old", metadata, time.Now().Unix()); err != nil {
+ t.Fatal(err)
+ }
+ srv.CookieRenew = xrenew.Service{
+ HTTPClient: passport.Client(),
+ QueryLoginSettingsURL: passport.URL + "/queryLoginSettings.do",
+ }
+ h := srv.Router()
+ session := loginHelper(t, h)
+ req := httptest.NewRequest(http.MethodGet, "/cookies/acc1/long-login", nil)
+ req.AddCookie(session)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
+ }
+ detail, err = store.Cookies.GetDetails(context.Background(), "acc1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if detail.Value != "" {
+ t.Fatalf("权威 Jar 删除后扁平值=%q want empty", detail.Value)
+ }
+ snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
+ if !complete || len(snapshot) != 0 {
+ t.Fatalf("应保留权威空 Jar,complete=%v snapshot=%+v", complete, snapshot)
+ }
+}
+
// TestListCookies 列表 cookie_id。
func TestListCookies(t *testing.T) {
srv, _, cleanup := newTestServer(t)
@@ -161,6 +348,7 @@ func TestUpdateCookieSettingsClearsTokenButKeepsDeviceID(t *testing.T) {
if err := store.Tokens.Save(ctx, "acc1", "permanent-device", "old-token", time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
+ seedStaleCookieSnapshot(t, store, "acc1")
h := srv.Router()
cookie := loginHelper(t, h)
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1/settings", strings.NewReader(`{"cookie":"unb=123; _m_h5_tk=new_1;"}`))
@@ -174,6 +362,7 @@ func TestUpdateCookieSettingsClearsTokenButKeepsDeviceID(t *testing.T) {
if err != nil || token.DeviceID != "permanent-device" || token.AccessToken != "" || token.ExpireAt != 0 {
t.Fatalf("token=%+v err=%v", token, err)
}
+ requireCookieSnapshotCleared(t, store, "acc1")
}
func jsonInt(value int64) string { return strconv.FormatInt(value, 10) }
@@ -204,6 +393,7 @@ func TestUpdateCookie(t *testing.T) {
if err := store.Tokens.Save(ctx, "acc1", "permanent-device", "old-token", time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
+ seedStaleCookieSnapshot(t, store, "acc1")
body := `{"value":"unb=123; _m_h5_tk=newtoken_2;"}`
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1", strings.NewReader(body))
@@ -224,6 +414,7 @@ func TestUpdateCookie(t *testing.T) {
if err != nil || token.DeviceID != "permanent-device" || token.AccessToken != "" || token.ExpireAt != 0 {
t.Fatalf("token=%+v err=%v", token, err)
}
+ requireCookieSnapshotCleared(t, store, "acc1")
}
func TestUpdateCookieQRLoginEnablesAccount(t *testing.T) {
@@ -285,6 +476,88 @@ func TestSetCookieStatusRecordsManualDisableReason(t *testing.T) {
}
}
+func TestSetCookieStatusWaitsForCredentialTransition(t *testing.T) {
+ srv, store, cleanup := newTestServer(t)
+ defer cleanup()
+ srv.Manager = nil
+ h := srv.Router()
+ cookie := loginHelper(t, h)
+
+ credentialUnlock := store.LockAccountCredentials("acc1")
+ done := make(chan *httptest.ResponseRecorder, 1)
+ go func() {
+ req := httptest.NewRequest(http.MethodPut, "/cookies/acc1/status", strings.NewReader(`{"enabled":false}`))
+ req.AddCookie(cookie)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ done <- rec
+ }()
+ select {
+ case rec := <-done:
+ credentialUnlock()
+ t.Fatalf("状态更新绕过了账号凭证锁: status=%d body=%s", rec.Code, rec.Body.String())
+ case <-time.After(50 * time.Millisecond):
+ }
+ credentialUnlock()
+ select {
+ case rec := <-done:
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("释放凭证锁后状态更新未完成")
+ }
+}
+
+func TestDeleteCookieRechecksOwnershipInsideCredentialLock(t *testing.T) {
+ srv, store, cleanup := newTestServer(t)
+ defer cleanup()
+ srv.Manager = nil
+ ctx := context.Background()
+ if ok, err := store.Users.Create(ctx, "member-delete", "member-delete@example.com", "pw"); err != nil || !ok {
+ t.Fatalf("create replacement owner: ok=%v err=%v", ok, err)
+ }
+ replacementOwner, err := store.Users.GetByUsername(ctx, "member-delete")
+ if err != nil {
+ t.Fatal(err)
+ }
+ h := srv.Router()
+ cookie := loginHelper(t, h)
+
+ credentialUnlock := store.LockAccountCredentials("acc1")
+ done := make(chan *httptest.ResponseRecorder, 1)
+ go func() {
+ req := httptest.NewRequest(http.MethodDelete, "/cookies/acc1", nil)
+ req.AddCookie(cookie)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ done <- rec
+ }()
+ select {
+ case rec := <-done:
+ credentialUnlock()
+ t.Fatalf("删除绕过了账号凭证锁: status=%d body=%s", rec.Code, rec.Body.String())
+ case <-time.After(50 * time.Millisecond):
+ }
+ if err := store.Cookies.Delete(ctx, "acc1"); err != nil {
+ credentialUnlock()
+ t.Fatal(err)
+ }
+ if err := store.Cookies.CreateOwned(ctx, "acc1", "unb=replacement; _m_h5_tk=fresh", replacementOwner.ID); err != nil {
+ credentialUnlock()
+ t.Fatal(err)
+ }
+ credentialUnlock()
+ rec := <-done
+ if rec.Code == http.StatusOK {
+ t.Fatalf("旧 owner 的并发请求不得删除新 owner 账号: body=%s", rec.Body.String())
+ }
+ detail, err := store.Cookies.GetDetails(ctx, "acc1")
+ if err != nil || detail.UserID != replacementOwner.ID {
+ t.Fatalf("替换后的账号被误删: detail=%+v err=%v", detail, err)
+ }
+}
+
// TestUpdateCookieBadJSON 非法 JSON 400。
func TestUpdateCookieBadJSON(t *testing.T) {
srv, _, cleanup := newTestServer(t)
diff --git a/internal/server/handler_errors_test.go b/internal/server/handler_errors_test.go
index 22d4012..8975334 100644
--- a/internal/server/handler_errors_test.go
+++ b/internal/server/handler_errors_test.go
@@ -78,7 +78,7 @@ func TestCreateCardRejectsUnsupportedAPITypeAndInvalidDelay(t *testing.T) {
for _, body := range []string{
`{"name":"API 卡密","type":"api","enabled":true}`,
`{"name":"非法类型","type":"unknown","enabled":true}`,
- `{"name":"延时错误","type":"text","text_content":"x","delay_seconds":86401,"enabled":true}`,
+ `{"name":"延时错误","type":"text","text_content":"x","delay_seconds":3601,"enabled":true}`,
`{"name":"空文本","type":"text","text_content":" ","enabled":true}`,
`{"name":"空库存","type":"data","data_content":"\n","enabled":true}`,
`{"name":"空图片","type":"image","image_url":"","enabled":true}`,
diff --git a/internal/server/item_handlers.go b/internal/server/item_handlers.go
index 72d4b51..4cc4936 100644
--- a/internal/server/item_handlers.go
+++ b/internal/server/item_handlers.go
@@ -53,7 +53,7 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "请选择发布账号")
return
}
- cookieValue, userID, ok := s.cookieForCurrentUser(w, r, cookieID)
+ _, userID, ok := s.cookieForCurrentUser(w, r, cookieID)
if !ok {
return
}
@@ -88,10 +88,19 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
+ credentialUnlock := s.Store.LockAccountCredentials(cookieID)
+ latest, err := s.Store.Cookies.GetDetails(r.Context(), cookieID)
+ if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
+ credentialUnlock()
+ writeErr(w, http.StatusConflict, "账号凭证已变化,请重试")
+ return
+ }
+ cookieValue := latest.Value
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
defer cancel()
client := s.mtopClient()
- res, err := client.PublishItem(ctx, cookieValue, mtop.PublishItemRequest{
+ mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
+ res, callErr := client.PublishItem(mtopCtx, cookieValue, mtop.PublishItemRequest{
Title: title,
Description: description,
PriceCents: priceCents,
@@ -101,9 +110,37 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
PostageCents: postageCents,
Images: images,
})
- if err != nil {
+ runtimeCookie := ""
+ runtimeCookieChanged := false
+ var responseCookieErr error
+ value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
+ if persistErr != nil {
+ s.Logger.Error("保存发布响应 Cookie Jar 失败", "cookie_id", cookieID, "err", persistErr)
+ responseCookieErr = persistErr
+ } else if handled {
+ if valueChanged {
+ runtimeCookie = value
+ runtimeCookieChanged = true
+ }
+ } else if callErr == nil && res != nil && res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
+ if saveErr := s.Store.Cookies.UpdateValueOwned(r.Context(), cookieID, res.UpdatedCookies, userID); saveErr != nil {
+ s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", cookieID, "err", saveErr)
+ responseCookieErr = saveErr
+ } else {
+ runtimeCookie = res.UpdatedCookies
+ runtimeCookieChanged = true
+ }
+ }
+ credentialUnlock()
+ if runtimeCookieChanged {
+ s.updateRunningCookie(r.Context(), cookieID, runtimeCookie)
+ }
+ if callErr != nil {
+ if responseCookieErr != nil {
+ callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", responseCookieErr))
+ }
var perr *mtop.PublishError
- if errors.As(err, &perr) {
+ if errors.As(callErr, &perr) {
status := http.StatusBadGateway
msg := perr.Error()
if perr.Code == mtop.PublishErrorStockPermissionMissing {
@@ -118,7 +155,7 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
})
return
}
- writeErr(w, http.StatusBadGateway, err.Error())
+ writeErr(w, http.StatusBadGateway, callErr.Error())
return
}
if res == nil || strings.TrimSpace(res.ItemID) == "" {
@@ -129,11 +166,6 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
})
return
}
- if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
- if err := s.Store.Cookies.UpdateValueOwned(r.Context(), cookieID, res.UpdatedCookies, userID); err != nil {
- s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", cookieID, "err", err)
- }
- }
detail := map[string]any{
"item_image": res.ImageURL,
"web_url": res.ItemURL,
@@ -164,6 +196,16 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
})
return
}
+ if responseCookieErr != nil {
+ writeJSON(w, http.StatusInternalServerError, map[string]any{
+ "success": false,
+ "code": "remote_published_cookie_save_failed",
+ "message": "商品已在平台发布并保存到本地,但登录凭证更新保存失败,请勿重复发布并尽快重新登录",
+ "item_id": res.ItemID,
+ "item_url": res.ItemURL,
+ })
+ return
+ }
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"message": "商品发布成功",
@@ -267,6 +309,14 @@ func (s *Server) listItems(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
+ cookieID := strings.TrimSpace(r.URL.Query().Get("cookie_id"))
+ if cookieID != "" {
+ if _, ok := all[cookieID]; !ok {
+ writeErr(w, http.StatusForbidden, "无权限操作该账号")
+ return
+ }
+ all = map[string]string{cookieID: all[cookieID]}
+ }
result := []map[string]any{}
for cid := range all {
items, _ := s.Store.Items.AllForCookie(r.Context(), cid)
@@ -287,25 +337,74 @@ func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "缺少 cookie_id 参数")
return
}
- cookieValue, userID, ok := s.cookieForCurrentUser(w, r, req.CookieID)
+ _, userID, ok := s.cookieForCurrentUser(w, r, req.CookieID)
if !ok {
return
}
+ credentialUnlock := s.Store.LockAccountCredentials(req.CookieID)
+ latest, err := s.Store.Cookies.GetDetails(r.Context(), req.CookieID)
+ if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
+ credentialUnlock()
+ writeErr(w, http.StatusConflict, "账号凭证已变化,请重试")
+ return
+ }
+ cookieValue := latest.Value
if req.PageSize <= 0 {
req.PageSize = 20
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
defer cancel()
client := s.mtopClient()
- res, err := client.FetchAllItems(ctx, cookieValue, req.PageSize, req.MaxPages)
- if err != nil {
- writeErr(w, http.StatusBadGateway, err.Error())
+ mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
+ res, callErr := client.FetchAllItems(mtopCtx, cookieValue, req.PageSize, req.MaxPages)
+ if callErr == nil && res == nil {
+ callErr = errors.New("商品列表接口未返回结果")
+ }
+ if callErr != nil {
+ value, valueChanged, _, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
+ credentialUnlock()
+ if persistErr != nil {
+ s.Logger.Error("保存商品同步响应 Cookie Jar 失败", "cookie_id", req.CookieID, "err", persistErr)
+ writeErr(w, http.StatusInternalServerError, "商品同步响应凭证保存失败")
+ return
+ } else if valueChanged {
+ s.updateRunningCookie(r.Context(), req.CookieID, value)
+ }
+ writeErr(w, http.StatusBadGateway, callErr.Error())
return
}
- if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
- if err := s.Store.Cookies.UpdateValueOwned(r.Context(), req.CookieID, res.UpdatedCookies, userID); err != nil {
- s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", err)
+ detailCookies := cookieValue
+ if res.UpdatedCookies != "" {
+ detailCookies = res.UpdatedCookies
+ }
+ s.enrichSyncedItemMultiSpec(mtopCtx, client, detailCookies, req.CookieID, res.Items)
+ runtimeCookie := ""
+ runtimeCookieChanged := false
+ value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
+ if persistErr != nil {
+ s.Logger.Error("保存商品同步响应 Cookie Jar 失败", "cookie_id", req.CookieID, "err", persistErr)
+ credentialUnlock()
+ writeErr(w, http.StatusInternalServerError, "商品同步响应凭证保存失败")
+ return
+ } else if handled {
+ if valueChanged {
+ runtimeCookie = value
+ runtimeCookieChanged = true
}
+ } else if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
+ if saveErr := s.Store.Cookies.UpdateValueOwned(r.Context(), req.CookieID, res.UpdatedCookies, userID); saveErr != nil {
+ s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", saveErr)
+ credentialUnlock()
+ writeErr(w, http.StatusInternalServerError, "商品同步响应凭证保存失败")
+ return
+ } else {
+ runtimeCookie = res.UpdatedCookies
+ runtimeCookieChanged = true
+ }
+ }
+ credentialUnlock()
+ if runtimeCookieChanged {
+ s.updateRunningCookie(r.Context(), req.CookieID, runtimeCookie)
}
saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items)
writeJSON(w, http.StatusOK, map[string]any{
@@ -327,22 +426,71 @@ func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request
writeErr(w, http.StatusBadRequest, "缺少 cookie_id 参数")
return
}
- cookieValue, userID, ok := s.cookieForCurrentUser(w, r, req.CookieID)
+ _, userID, ok := s.cookieForCurrentUser(w, r, req.CookieID)
if !ok {
return
}
+ credentialUnlock := s.Store.LockAccountCredentials(req.CookieID)
+ latest, err := s.Store.Cookies.GetDetails(r.Context(), req.CookieID)
+ if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
+ credentialUnlock()
+ writeErr(w, http.StatusConflict, "账号凭证已变化,请重试")
+ return
+ }
+ cookieValue := latest.Value
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
client := s.mtopClient()
- res, err := client.FetchItemsPage(ctx, cookieValue, req.PageNumber, req.PageSize)
- if err != nil {
- writeErr(w, http.StatusBadGateway, err.Error())
+ mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
+ res, callErr := client.FetchItemsPage(mtopCtx, cookieValue, req.PageNumber, req.PageSize)
+ if callErr == nil && res == nil {
+ callErr = errors.New("商品列表接口未返回结果")
+ }
+ if callErr != nil {
+ value, valueChanged, _, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
+ credentialUnlock()
+ if persistErr != nil {
+ s.Logger.Error("保存商品分页响应 Cookie Jar 失败", "cookie_id", req.CookieID, "err", persistErr)
+ writeErr(w, http.StatusInternalServerError, "商品分页响应凭证保存失败")
+ return
+ } else if valueChanged {
+ s.updateRunningCookie(r.Context(), req.CookieID, value)
+ }
+ writeErr(w, http.StatusBadGateway, callErr.Error())
return
}
- if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
- if err := s.Store.Cookies.UpdateValueOwned(r.Context(), req.CookieID, res.UpdatedCookies, userID); err != nil {
- s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", err)
+ detailCookies := cookieValue
+ if res.UpdatedCookies != "" {
+ detailCookies = res.UpdatedCookies
+ }
+ s.enrichSyncedItemMultiSpec(mtopCtx, client, detailCookies, req.CookieID, res.Items)
+ runtimeCookie := ""
+ runtimeCookieChanged := false
+ value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
+ if persistErr != nil {
+ s.Logger.Error("保存商品分页响应 Cookie Jar 失败", "cookie_id", req.CookieID, "err", persistErr)
+ credentialUnlock()
+ writeErr(w, http.StatusInternalServerError, "商品分页响应凭证保存失败")
+ return
+ } else if handled {
+ if valueChanged {
+ runtimeCookie = value
+ runtimeCookieChanged = true
}
+ } else if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
+ if saveErr := s.Store.Cookies.UpdateValueOwned(r.Context(), req.CookieID, res.UpdatedCookies, userID); saveErr != nil {
+ s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", saveErr)
+ credentialUnlock()
+ writeErr(w, http.StatusInternalServerError, "商品分页响应凭证保存失败")
+ return
+ } else {
+ runtimeCookie = res.UpdatedCookies
+ runtimeCookieChanged = true
+ }
+ }
+ credentialUnlock()
+ if runtimeCookieChanged {
+ s.updateRunningCookie(r.Context(), req.CookieID, runtimeCookie)
}
saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items)
writeJSON(w, http.StatusOK, map[string]any{
@@ -391,6 +539,11 @@ func (s *Server) saveSyncedItems(ctx context.Context, cookieID string, items []m
ItemDetail: item.ItemDetail,
})
if err == nil {
+ if item.IsMultiSpec {
+ if multiErr := s.Store.Items.SetMultiSpec(ctx, cookieID, item.ID, true); multiErr != nil && s.Logger != nil {
+ s.Logger.Warn("保存商品多规格状态失败", "cookie_id", cookieID, "item_id", item.ID, "err", multiErr)
+ }
+ }
saved++
} else if s.Logger != nil {
s.Logger.Warn("保存商品失败", "cookie_id", cookieID, "item_id", item.ID, "err", err)
@@ -399,6 +552,27 @@ func (s *Server) saveSyncedItems(ctx context.Context, cookieID string, items []m
return saved
}
+func (s *Server) enrichSyncedItemMultiSpec(ctx context.Context, client mtop.Client, cookies, cookieID string, items []mtop.ItemListItem) {
+ fetcher, ok := client.(mtop.ItemDetailFetcher)
+ if !ok {
+ return
+ }
+ for index := range items {
+ if items[index].IsMultiSpec || s.Store.Items.IsMultiSpec(ctx, cookieID, items[index].ID) {
+ items[index].IsMultiSpec = true
+ continue
+ }
+ isMultiSpec, err := fetcher.DetectItemMultiSpec(ctx, cookies, items[index].ID)
+ if err != nil {
+ if s.Logger != nil {
+ s.Logger.Warn("识别商品多规格状态失败", "cookie_id", cookieID, "item_id", items[index].ID, "err", err)
+ }
+ continue
+ }
+ items[index].IsMultiSpec = isMultiSpec
+ }
+}
+
func (s *Server) listItemsByCookie(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cookie_id")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
diff --git a/internal/server/item_handlers_test.go b/internal/server/item_handlers_test.go
index 4650a6b..40b182c 100644
--- a/internal/server/item_handlers_test.go
+++ b/internal/server/item_handlers_test.go
@@ -357,6 +357,33 @@ func TestSyncItemsFromAccountSuccess(t *testing.T) {
}
}
+func TestSyncItemsFromAccountDetectsMultiSpecFromDetail(t *testing.T) {
+ srv, store, cleanup := newTestServer(t)
+ defer cleanup()
+ srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ body := `{"ret":["SUCCESS::调用成功"],"data":{}}`
+ if strings.Contains(req.URL.String(), "mtop.idle.web.xyh.item.list") {
+ body = `{"ret":["SUCCESS::调用成功"],"data":{"cardList":[{"cardData":{"id":"multi-item","title":"多规格商品","detailParams":{"itemId":"multi-item"}}}]}}`
+ } else if strings.Contains(req.URL.String(), "mtop.taobao.idle.pc.detail") {
+ body = `{"ret":["SUCCESS::调用成功"],"data":{"multiSKU":true,"skuDO":{"skuList":[{"id":"a"},{"id":"b"}]}}}`
+ }
+ return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
+ }))
+ h := srv.Router()
+ cookie := loginHelper(t, h)
+ req := httptest.NewRequest(http.MethodPost, "/items/get-all-from-account", strings.NewReader(`{"cookie_id":"acc1","page_size":10}`))
+ req.AddCookie(cookie)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
+ }
+ item, err := store.Items.Get(context.Background(), "acc1", "multi-item")
+ if err != nil || !item.IsMultiSpec {
+ t.Fatalf("item=%+v err=%v", item, err)
+ }
+}
+
// TestSyncItemsFromAccountFail mtop 返回非成功 → 502。
func TestSyncItemsFromAccountFail(t *testing.T) {
srv, _, cleanup := newTestServer(t)
@@ -595,6 +622,39 @@ func TestItemCRUD(t *testing.T) {
}
}
+func TestListItemsFiltersByOwnedAccount(t *testing.T) {
+ srv, store, cleanup := newTestServer(t)
+ defer cleanup()
+ ctx := context.Background()
+ admin, _ := store.Users.GetByUsername(ctx, "admin")
+ if err := store.Cookies.Save(ctx, "acc2", "unb=456; _m_h5_tk=tk2_1;", admin.ID); err != nil {
+ t.Fatal(err)
+ }
+ _, _ = store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id,item_id,item_title) VALUES ('acc1','item-a','商品A'),('acc2','item-b','商品B')`)
+ h := srv.Router()
+ cookie := loginHelper(t, h)
+
+ req := httptest.NewRequest(http.MethodGet, "/items?cookie_id=acc2", nil)
+ req.AddCookie(cookie)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ var rows []map[string]any
+ if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &rows) != nil {
+ t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
+ }
+ if len(rows) != 1 || rows[0]["cookie_id"] != "acc2" || rows[0]["item_id"] != "item-b" {
+ t.Fatalf("rows=%+v", rows)
+ }
+
+ forbidden := httptest.NewRequest(http.MethodGet, "/items?cookie_id=not-owned", nil)
+ forbidden.AddCookie(cookie)
+ forbiddenRec := httptest.NewRecorder()
+ h.ServeHTTP(forbiddenRec, forbidden)
+ if forbiddenRec.Code != http.StatusForbidden {
+ t.Fatalf("status=%d body=%s", forbiddenRec.Code, forbiddenRec.Body.String())
+ }
+}
+
// TestItemGetNotFound 不存在商品 404。
func TestItemGetNotFound(t *testing.T) {
srv, _, cleanup := newTestServer(t)
diff --git a/internal/server/item_publish_batch_handlers.go b/internal/server/item_publish_batch_handlers.go
index 44a4c10..7a309a7 100644
--- a/internal/server/item_publish_batch_handlers.go
+++ b/internal/server/item_publish_batch_handlers.go
@@ -103,7 +103,11 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
return
}
defaultCookieID := strings.TrimSpace(r.FormValue("default_cookie_id"))
- if defaultCookieID != "" && !s.cookieOwnedByUser(r.Context(), sess.UserID, defaultCookieID) {
+ if defaultCookieID == "" {
+ writeErr(w, http.StatusBadRequest, "请选择默认发布账号")
+ return
+ }
+ if !s.cookieOwnedByUser(r.Context(), sess.UserID, defaultCookieID) {
writeErr(w, http.StatusForbidden, "默认账号不属于当前用户")
return
}
@@ -771,6 +775,7 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
origCents, _ := parseMoneyCents(row.OriginalPrice)
postageCents, _ := parseMoneyCents(row.Postage)
res := &mtop.PublishItemResult{ItemID: row.ItemID, ItemURL: row.ItemURL, Title: row.Title, PriceText: row.Price, Quantity: row.Quantity}
+ var responseCookieErr error
if row.ItemID == "" {
images, err := loadBatchPublishImages(ctx, batch.UploadDir, row)
if err != nil {
@@ -782,18 +787,68 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
if markErr != nil || !remoteStarted {
return fmt.Errorf("保存远端发布前检查点失败: %w", firstError(markErr, errors.New("批次租约已失效")))
}
- pctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
- res, err = client.PublishItem(pctx, cookieValue, mtop.PublishItemRequest{
- Title: row.Title,
- Description: firstNonEmpty(row.Description, row.Title),
- PriceCents: priceCents,
- OriginalPriceCents: origCents,
- Quantity: row.Quantity,
- PostageMode: row.PostageMode,
- PostageCents: postageCents,
- Images: images,
- })
- cancel()
+ runtimeCookie := ""
+ runtimeCookieChanged := false
+ res, err = func() (*mtop.PublishItemResult, error) {
+ credentialUnlock := s.Store.LockAccountCredentials(row.CookieID)
+ defer credentialUnlock()
+ latest, latestErr := s.Store.Cookies.GetDetails(ctx, row.CookieID)
+ if latestErr != nil {
+ return nil, latestErr
+ }
+ if latest == nil || latest.UserID != userID {
+ return nil, db.ErrForbidden
+ }
+ if !hasStoredCookieCredential(latest) {
+ return nil, errors.New("账号 Cookie 为空")
+ }
+ cookieValue = latest.Value
+ pctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
+ defer cancel()
+ mtopCtx, cookieSession := withMTopCookieSnapshot(pctx, latest)
+ published, publishErr := client.PublishItem(mtopCtx, cookieValue, mtop.PublishItemRequest{
+ Title: row.Title,
+ Description: firstNonEmpty(row.Description, row.Title),
+ PriceCents: priceCents,
+ OriginalPriceCents: origCents,
+ Quantity: row.Quantity,
+ PostageMode: row.PostageMode,
+ PostageCents: postageCents,
+ Images: images,
+ })
+ value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
+ if persistErr != nil {
+ cookieErr := fmt.Errorf("发布商品后保存响应 Cookie Jar: %w", persistErr)
+ if publishErr != nil {
+ return published, errors.Join(publishErr, cookieErr)
+ }
+ responseCookieErr = cookieErr
+ } else if handled {
+ if valueChanged {
+ runtimeCookie = value
+ runtimeCookieChanged = true
+ }
+ } else if publishErr == nil && published != nil && published.UpdatedCookies != "" && published.UpdatedCookies != cookieValue {
+ if saveErr := s.Store.Cookies.UpdateValueOwned(ctx, row.CookieID, published.UpdatedCookies, userID); saveErr != nil {
+ responseCookieErr = fmt.Errorf("发布商品后保存响应 Cookie: %w", saveErr)
+ } else {
+ runtimeCookie = published.UpdatedCookies
+ runtimeCookieChanged = true
+ }
+ }
+ if publishErr != nil {
+ return published, publishErr
+ }
+ if published == nil {
+ return nil, errors.New("发布商品接口未返回结果")
+ }
+ return published, nil
+ }()
+ if runtimeCookieChanged && s.Manager != nil {
+ if account, running := s.Manager.GetInstance(row.CookieID); running {
+ account.UpdateCookie(runtimeCookie)
+ }
+ }
if err != nil {
if ctx.Err() != nil {
return &uncertainRemotePublishError{err: fmt.Errorf("取消时远端发布结果未知: %w", err)}
@@ -814,6 +869,9 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
if saveErr != nil || !saved {
return &uncertainRemotePublishError{err: fmt.Errorf("保存远端发布结果失败: %w", firstError(saveErr, errors.New("批次租约已失效")))}
}
+ if responseCookieErr != nil {
+ return &postPublishError{err: responseCookieErr}
+ }
} else if strings.TrimSpace(row.RawJSON) != "" {
_ = json.Unmarshal([]byte(row.RawJSON), &res.RawData)
}
@@ -824,11 +882,6 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
if err != nil || currentBatch.Status == "canceled" || currentBatch.WorkerToken != workerToken {
return &postPublishError{err: context.Canceled}
}
- if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
- if err := s.Store.Cookies.UpdateValueOwned(ctx, row.CookieID, res.UpdatedCookies, userID); err != nil {
- s.Logger.Error("发布商品后保存刷新 cookie 失败", "cookie_id", row.CookieID, "err", err)
- }
- }
if res.ItemID != "" {
detail := map[string]any{
"item_image": res.ImageURL,
@@ -1111,8 +1164,8 @@ func (s *Server) validatePublishAutomation(ctx context.Context, userID int64, cf
if action.DeliveryCount <= 0 {
errs = append(errs, prefix+"每件份数必须大于0")
}
- if action.DelaySeconds < 0 || action.DelaySeconds > 86400 {
- errs = append(errs, prefix+"延迟秒必须在 0 到 86400 之间")
+ if action.DelaySeconds < 0 || action.DelaySeconds > 3600 {
+ errs = append(errs, prefix+"延迟秒必须在 0 到 3600 之间")
}
}
}
diff --git a/internal/server/mtop_cookie_session.go b/internal/server/mtop_cookie_session.go
new file mode 100644
index 0000000..0ca244b
--- /dev/null
+++ b/internal/server/mtop_cookie_session.go
@@ -0,0 +1,65 @@
+package server
+
+import (
+ "context"
+ "time"
+
+ "xianyu-go/internal/db"
+ "xianyu-go/internal/xianyu/cookierefresh"
+ "xianyu-go/internal/xianyu/mtop"
+)
+
+// withMTopCookieSnapshot 为一次业务 MTOP 流程挂载账号 Cookie 会话。有完整
+// Jar 时保持所有作用域;历史账号则使用不冒充完整 Jar 的 flat session,仍能
+// 在成功或失败路径观察并持久化 Set-Cookie。
+func withMTopCookieSnapshot(ctx context.Context, detail *db.CookieDetail) (context.Context, *mtop.CookieSession) {
+ if detail == nil {
+ return ctx, nil
+ }
+ snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
+ if !ok {
+ return mtop.WithFlatCookieSession(ctx, detail.Value)
+ }
+ return mtop.WithCookieSnapshot(ctx, snapshot)
+}
+
+func hasStoredCookieCredential(detail *db.CookieDetail) bool {
+ if detail == nil {
+ return false
+ }
+ if detail.Value != "" {
+ return true
+ }
+ _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
+ return complete
+}
+
+// persistMTopCookieSessionLocked 原子保存业务 MTOP 响应后的完整 Cookie Jar。
+// 调用方必须持有账号凭证锁,并且 detail 必须是加锁后重读的最新记录。
+// handled 表示本次请求由完整 Cookie Jar 接管,或 session 已产生可持久化更新;
+// 此时即使 Jar 未变化,也不得因扁平 Cookie 的顺序/尾分号差异退回
+// UpdatedCookies 写回,否则会把刚保存的完整 Jar 清掉。
+func (s *Server) persistMTopCookieSessionLocked(
+ ctx context.Context,
+ detail *db.CookieDetail,
+ session *mtop.CookieSession,
+) (value string, valueChanged, handled bool, err error) {
+ if detail == nil || session == nil {
+ return "", false, false, nil
+ }
+ value, snapshot, changed := session.State()
+ if !changed {
+ if snapshot != nil {
+ return detail.Value, false, true, nil
+ }
+ return "", false, false, nil
+ }
+ metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
+ if snapshot != nil {
+ metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
+ }
+ if err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix()); err != nil {
+ return value, value != detail.Value, true, err
+ }
+ return value, value != detail.Value, true, nil
+}
diff --git a/internal/server/mtop_cookie_session_test.go b/internal/server/mtop_cookie_session_test.go
new file mode 100644
index 0000000..50af63e
--- /dev/null
+++ b/internal/server/mtop_cookie_session_test.go
@@ -0,0 +1,137 @@
+package server
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "xianyu-go/internal/xianyu/cookierefresh"
+ "xianyu-go/internal/xianyu/mtop"
+)
+
+type stubProfileMTop struct {
+ mtop.Client
+ profile func(context.Context, string) (*mtop.UserProfileResult, error)
+}
+
+func (s *stubProfileMTop) FetchUserProfile(ctx context.Context, cookies string) (*mtop.UserProfileResult, error) {
+ return s.profile(ctx, cookies)
+}
+
+func TestRefreshAccountProfilePersistsCookieSessionOnResponseError(t *testing.T) {
+ srv, store, cleanup := newTestServer(t)
+ defer cleanup()
+
+ ctx := context.Background()
+ detail, err := store.Cookies.GetDetails(ctx, "acc1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ snapshot := []cookierefresh.BrowserCookie{
+ {Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "_m_h5_tk", Value: "tk1_1", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "keep", Value: "yes", Domain: "www.goofish.com", Path: "/im", Secure: true},
+ }
+ metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
+ if err := store.Cookies.UpdateRenewalCookie(ctx, detail.ID, detail.Value, metadata, time.Now().Unix()); err != nil {
+ t.Fatal(err)
+ }
+
+ client := mtop.NewClient()
+ client.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ header := make(http.Header)
+ header.Add("Set-Cookie", "rotated=fresh; Domain=.goofish.com; Path=/; Secure; HttpOnly")
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: header,
+ Body: io.NopCloser(strings.NewReader(`{"ret":`)),
+ Request: req,
+ }, nil
+ })}
+ srv.MTop = client
+
+ detail, err = store.Cookies.GetDetails(ctx, "acc1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, _, message := srv.refreshAccountProfile(ctx, detail)
+ if message == "" {
+ t.Fatal("无效响应应返回解析错误")
+ }
+
+ updated, err := store.Cookies.GetDetails(ctx, "acc1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(updated.Value, "rotated=fresh") {
+ t.Fatalf("响应错误时仍应保存 canonical Cookie: %q", updated.Value)
+ }
+ updatedSnapshot, ok := cookierefresh.SnapshotFromMetadataOK(updated.MetadataJSON)
+ if !ok {
+ t.Fatal("响应错误时不应清除权威 Cookie Jar")
+ }
+ values := make(map[string]string, len(updatedSnapshot))
+ for _, cookie := range updatedSnapshot {
+ values[cookie.Name+"@"+cookie.Domain+cookie.Path] = cookie.Value
+ }
+ if values["rotated@.goofish.com/"] != "fresh" || values["keep@www.goofish.com/im"] != "yes" {
+ t.Fatalf("Cookie Jar 写回不完整: %+v", updatedSnapshot)
+ }
+}
+
+func TestRefreshAccountProfileKeepsAuthoritativeSnapshotWithFlatMock(t *testing.T) {
+ srv, store, cleanup := newTestServer(t)
+ defer cleanup()
+ seedStaleCookieSnapshot(t, store, "acc1")
+
+ srv.MTop = &stubProfileMTop{profile: func(context.Context, string) (*mtop.UserProfileResult, error) {
+ return &mtop.UserProfileResult{
+ Nickname: "mock-profile",
+ UpdatedCookies: "unb=123; _m_h5_tk=mockfresh_2",
+ }, nil
+ }}
+ detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv.refreshAccountProfile(context.Background(), detail)
+
+ updated, err := store.Cookies.GetDetails(context.Background(), "acc1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(updated.Value, "_m_h5_tk=mockfresh_2") {
+ t.Fatalf("完整 Jar 不得被 mock 扁平 Cookie 覆盖: %q", updated.Value)
+ }
+ if _, complete := cookierefresh.SnapshotFromMetadataOK(updated.MetadataJSON); !complete {
+ t.Fatalf("完整 Jar 未发生变化时不得清除: %s", updated.MetadataJSON)
+ }
+}
+
+func TestRefreshAccountProfileKeepsFlatMockFallbackWithoutSnapshot(t *testing.T) {
+ srv, store, cleanup := newTestServer(t)
+ defer cleanup()
+
+ srv.MTop = &stubProfileMTop{profile: func(context.Context, string) (*mtop.UserProfileResult, error) {
+ return &mtop.UserProfileResult{
+ Nickname: "mock-profile",
+ UpdatedCookies: "unb=123; _m_h5_tk=mockfresh_2",
+ }, nil
+ }}
+ detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv.refreshAccountProfile(context.Background(), detail)
+
+ updated, err := store.Cookies.GetDetails(context.Background(), "acc1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(updated.Value, "_m_h5_tk=mockfresh_2") {
+ t.Fatalf("无完整 Jar 时 mock 扁平 Cookie 未沿用兼容写回: %q", updated.Value)
+ }
+}
diff --git a/internal/server/order_handlers.go b/internal/server/order_handlers.go
index 868f4bb..e786b82 100644
--- a/internal/server/order_handlers.go
+++ b/internal/server/order_handlers.go
@@ -2,6 +2,7 @@ package server
import (
"context"
+ "errors"
"fmt"
"net/http"
"strconv"
@@ -12,15 +13,22 @@ import (
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
+ "xianyu-go/internal/xianyu/cookierefresh"
+ "xianyu-go/internal/xianyu/mtop"
)
const refreshOrderChunkSize = 100
+const maxSoldOrderPages = 100
type refreshTarget struct {
OrderID string
CurrentStatus string
}
+type orderDetailMTop interface {
+ FetchOrderDetail(ctx context.Context, cookiesStr, orderID string) (*mtop.OrderDetailResult, error)
+}
+
// mountOrders 订单端点(真实实现)。
func (s *Server) mountOrdersReal(r chi.Router) {
r.Get("/api/orders", s.listOrders)
@@ -162,10 +170,6 @@ func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
}
func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
- if s.Browser == nil {
- writeErr(w, http.StatusServiceUnavailable, "浏览器自动化未启用,无法刷新订单")
- return
- }
sess := auth.SessionFromContext(r.Context())
all, err := s.Store.Cookies.AllForUser(r.Context(), sess.UserID)
if err != nil {
@@ -183,6 +187,57 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
all = map[string]string{cookieID: value}
}
+ discovered, listUpdated, failed := 0, 0, 0
+ results := []map[string]any{}
+ newOrderIDs := make(map[string]struct{})
+ if fetcher, ok := s.mtopClient().(mtop.SoldOrderFetcher); ok {
+ for cid := range all {
+ credentialUnlock := s.Store.LockAccountCredentials(cid)
+ latest, latestErr := s.Store.Cookies.GetDetails(r.Context(), cid)
+ if latestErr != nil || latest == nil || latest.UserID != sess.UserID || !hasStoredCookieCredential(latest) {
+ credentialUnlock()
+ if latestErr == nil {
+ latestErr = errors.New("账号凭证已变化")
+ }
+ failed++
+ results = append(results, map[string]any{
+ "cookie_id": cid, "stage": "discover", "success": false, "error": latestErr.Error(),
+ })
+ continue
+ }
+ all[cid] = latest.Value
+ mtopCtx, cookieSession := withMTopCookieSnapshot(r.Context(), latest)
+ accountDiscovered, accountUpdated, accountNewIDs, discoveryErr := s.discoverSoldOrders(mtopCtx, fetcher, cid, latest.Value)
+ value, valueChanged, _, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
+ if persistErr != nil {
+ discoveryErr = errors.Join(discoveryErr, fmt.Errorf("保存订单列表响应 Cookie Jar: %w", persistErr))
+ } else if valueChanged {
+ all[cid] = value
+ }
+ credentialUnlock()
+ if persistErr == nil && valueChanged {
+ s.updateRunningCookie(r.Context(), cid, value)
+ }
+ discovered += accountDiscovered
+ listUpdated += accountUpdated
+ for orderID := range accountNewIDs {
+ newOrderIDs[orderID] = struct{}{}
+ }
+ result := map[string]any{
+ "cookie_id": cid, "stage": "discover", "success": discoveryErr == nil,
+ "discovered": accountDiscovered, "updated": accountUpdated,
+ }
+ if discoveryErr != nil {
+ failed++
+ result["error"] = discoveryErr.Error()
+ }
+ results = append(results, result)
+ }
+ } else {
+ failed++
+ results = append(results, map[string]any{"stage": "discover", "success": false, "error": "当前 MTop 客户端不支持订单列表发现"})
+ }
+
ordersByCookie := map[string][]refreshTarget{}
for cid := range all {
for offset := 0; ; offset += 500 {
@@ -196,7 +251,8 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
continue
}
// 稳定状态无需反复抓取;但历史订单若缺少实付金额,仍需补全详情。
- if isStableOrderStatus(currentStatus) && strings.TrimSpace(row.Amount) != "" {
+ _, isNewOrder := newOrderIDs[row.OrderID]
+ if !isNewOrder && isStableOrderStatus(currentStatus) && strings.TrimSpace(row.Amount) != "" {
continue
}
ordersByCookie[cid] = append(ordersByCookie[cid], refreshTarget{OrderID: row.OrderID, CurrentStatus: currentStatus})
@@ -211,100 +267,193 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
for _, targets := range ordersByCookie {
total += len(targets)
}
+ detailFetcher, detailSupported := s.mtopClient().(orderDetailMTop)
+ if !detailSupported {
+ message := "订单列表同步完成"
+ if discovered > 0 {
+ message = fmt.Sprintf("订单列表同步完成,发现并导入 %d 个新订单", discovered)
+ }
+ if total > 0 {
+ message += fmt.Sprintf(";当前 Go MTOP 客户端不支持详情接口,已跳过 %d 个订单", total)
+ }
+ writeJSON(w, http.StatusOK, map[string]any{
+ "success": failed == 0,
+ "message": message,
+ "summary": map[string]int{
+ "discovered": discovered, "list_updated": listUpdated, "detail_total": total,
+ "total": total, "updated": 0, "no_change": 0, "failed": failed,
+ },
+ "results": results,
+ })
+ return
+ }
if total == 0 {
writeJSON(w, http.StatusOK, map[string]any{
- "success": true,
- "message": "没有需要刷新的订单",
- "summary": map[string]int{"total": 0, "updated": 0, "no_change": 0, "failed": 0},
- "results": []any{},
+ "success": failed == 0,
+ "message": fmt.Sprintf("订单列表同步完成,发现 %d 个新订单;没有需要补全详情的订单", discovered),
+ "summary": map[string]int{
+ "discovered": discovered, "list_updated": listUpdated, "detail_total": 0,
+ "total": 0, "updated": 0, "no_change": 0, "failed": failed,
+ },
+ "results": results,
})
return
}
- updated, noChange, failed := 0, 0, 0
- results := []map[string]any{}
+ updated, noChange := 0, 0
for cid, targets := range ordersByCookie {
- cookieValue := all[cid]
- if cookieValue == "" {
- failed += len(targets)
- continue
- }
for _, chunk := range chunkRefreshTargets(targets, refreshOrderChunkSize) {
- orderIDs := make([]string, 0, len(chunk))
- currentStatus := make(map[string]string, len(chunk))
- for _, target := range chunk {
- orderIDs = append(orderIDs, target.OrderID)
- currentStatus[target.OrderID] = target.CurrentStatus
- }
- ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute)
- batch, err := s.Browser.BatchRefreshOrders(ctx, orderIDs, cid, cookieValue)
- cancel()
- if err != nil {
+ credentialUnlock := s.Store.LockAccountCredentials(cid)
+ latest, latestErr := s.Store.Cookies.GetDetails(r.Context(), cid)
+ if latestErr != nil || latest == nil || latest.UserID != sess.UserID || !hasStoredCookieCredential(latest) {
+ credentialUnlock()
failed += len(chunk)
- results = append(results, map[string]any{"cookie_id": cid, "success": false, "error": err.Error()})
+ results = append(results, map[string]any{"cookie_id": cid, "success": false, "error": "账号凭证已变化"})
continue
}
- rawOrders, _ := batch["orders"].([]map[string]any)
- seen := make(map[string]struct{}, len(rawOrders))
- for _, raw := range rawOrders {
- orderID := stringFromAny(raw["order_id"])
- if _, expected := currentStatus[orderID]; !expected {
- continue
- }
- seen[orderID] = struct{}{}
- if raw["success"] == false {
+ ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute)
+ mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
+ for _, target := range chunk {
+ detail, fetchErr := detailFetcher.FetchOrderDetail(mtopCtx, latest.Value, target.OrderID)
+ if fetchErr != nil || detail == nil {
failed++
+ message := "订单详情接口未返回结果"
+ if fetchErr != nil {
+ message = fetchErr.Error()
+ }
results = append(results, map[string]any{
- "order_id": orderID,
+ "order_id": target.OrderID,
"success": false,
- "error": stringFromAny(raw["error"]),
+ "error": message,
})
continue
}
- newStatus := db.NormalizeOrderStatus(stringFromAny(raw["order_status"]))
+ newStatus := db.NormalizeOrderStatus(detail.OrderStatus)
if !validEditableOrderStatus(newStatus) {
- newStatus = currentStatus[orderID]
+ newStatus = target.CurrentStatus
}
- err := s.Store.Orders.Upsert(r.Context(), orderID, db.OrderUpsertOpts{
+ err := s.Store.Orders.Upsert(r.Context(), target.OrderID, db.OrderUpsertOpts{
CookieID: cid,
OrderStatus: newStatus,
- SpecName: stringFromAny(raw["spec_name"]),
- SpecValue: stringFromAny(raw["spec_value"]),
- Quantity: stringFromAny(raw["quantity"]),
- Amount: stringFromAny(raw["amount"]),
+ SpecName: detail.SpecName,
+ SpecValue: detail.SpecValue,
+ Quantity: detail.Quantity,
+ Amount: detail.Amount,
})
if err != nil {
failed++
- results = append(results, map[string]any{"order_id": orderID, "success": false, "error": "更新数据库失败"})
+ results = append(results, map[string]any{"order_id": target.OrderID, "success": false, "error": "更新数据库失败"})
continue
}
- changed := newStatus != "" && newStatus != currentStatus[orderID]
+ changed := newStatus != "" && newStatus != target.CurrentStatus
if changed {
updated++
} else {
noChange++
}
results = append(results, map[string]any{
- "order_id": orderID,
+ "order_id": target.OrderID,
"success": true,
- "old_status": currentStatus[orderID],
+ "old_status": target.CurrentStatus,
"new_status": newStatus,
})
}
- for _, orderID := range missingRefreshTargetIDs(chunk, seen) {
+ cancel()
+ value, valueChanged, _, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
+ credentialUnlock()
+ if persistErr != nil {
failed++
- results = append(results, map[string]any{"order_id": orderID, "success": false, "error": "浏览器未返回该订单的刷新结果"})
+ results = append(results, map[string]any{"cookie_id": cid, "stage": "persist_cookie", "success": false, "error": persistErr.Error()})
+ } else if valueChanged {
+ s.updateRunningCookie(r.Context(), cid, value)
}
}
}
writeJSON(w, http.StatusOK, map[string]any{
- "success": true,
- "message": "订单刷新完成",
- "summary": map[string]int{"total": total, "updated": updated, "no_change": noChange, "failed": failed},
+ "success": failed == 0,
+ "message": fmt.Sprintf("订单同步完成,发现 %d 个新订单", discovered),
+ "summary": map[string]int{
+ "discovered": discovered, "list_updated": listUpdated, "detail_total": total,
+ "total": total, "updated": updated, "no_change": noChange, "failed": failed,
+ },
"results": results,
})
}
+func (s *Server) discoverSoldOrders(ctx context.Context, fetcher mtop.SoldOrderFetcher, cookieID, cookies string) (int, int, map[string]struct{}, error) {
+ discovered, updated := 0, 0
+ newOrderIDs := make(map[string]struct{})
+ for pageNumber := 1; pageNumber <= maxSoldOrderPages; pageNumber++ {
+ page, err := fetcher.FetchSoldOrdersPage(ctx, cookies, pageNumber, 30)
+ if err != nil {
+ return discovered, updated, newOrderIDs, err
+ }
+ pageChanged := false
+ for _, remote := range page.Items {
+ if normalizedAmount, ok := db.NormalizeOrderAmount(remote.Amount); ok {
+ remote.Amount = normalizedAmount
+ }
+ existing, getErr := s.Store.Orders.Get(ctx, remote.OrderID)
+ isNew := errors.Is(getErr, db.ErrNotFound)
+ if getErr != nil && !isNew {
+ return discovered, updated, newOrderIDs, fmt.Errorf("读取订单 %s 失败: %w", remote.OrderID, getErr)
+ }
+ changed := isNew || soldOrderChanged(existing, remote)
+ status := remote.OrderStatus
+ if !isNew && status == "unknown" {
+ status = ""
+ }
+ var isBargain *bool
+ if remote.IsBargain {
+ value := true
+ isBargain = &value
+ }
+ if err := s.Store.Orders.Upsert(ctx, remote.OrderID, db.OrderUpsertOpts{
+ ItemID: remote.ItemID, BuyerID: remote.BuyerID, CookieID: cookieID,
+ OrderStatus: status, Quantity: remote.Quantity, Amount: remote.Amount,
+ ReceiverName: remote.ReceiverName, ReceiverPhone: remote.ReceiverPhone,
+ ReceiverAddr: remote.ReceiverAddr, ReceiverCity: remote.ReceiverCity,
+ IsBargain: isBargain,
+ }); err != nil {
+ return discovered, updated, newOrderIDs, fmt.Errorf("保存订单 %s 失败: %w", remote.OrderID, err)
+ }
+ if isNew {
+ discovered++
+ newOrderIDs[remote.OrderID] = struct{}{}
+ } else if changed {
+ updated++
+ }
+ pageChanged = pageChanged || changed
+ }
+ if !page.NextPage || len(page.Items) == 0 {
+ return discovered, updated, newOrderIDs, nil
+ }
+ // 卖家列表按新到旧排列。一整页都已存在且字段未变化时,更早页也无需重复扫描。
+ if !pageChanged {
+ return discovered, updated, newOrderIDs, nil
+ }
+ }
+ return discovered, updated, newOrderIDs, fmt.Errorf("订单列表超过 %d 页,已停止继续同步", maxSoldOrderPages)
+}
+
+func soldOrderChanged(existing *db.Order, remote mtop.SoldOrder) bool {
+ if existing == nil {
+ return true
+ }
+ statusChanged := remote.OrderStatus != "" && remote.OrderStatus != "unknown" &&
+ db.NormalizeOrderStatus(existing.OrderStatus) != remote.OrderStatus
+ return statusChanged ||
+ (remote.ItemID != "" && existing.ItemID != remote.ItemID) ||
+ (remote.BuyerID != "" && existing.BuyerID != remote.BuyerID) ||
+ (remote.Quantity != "" && existing.Quantity != remote.Quantity) ||
+ (remote.Amount != "" && existing.Amount != remote.Amount) ||
+ (remote.ReceiverName != "" && existing.ReceiverName != remote.ReceiverName) ||
+ (remote.ReceiverPhone != "" && existing.ReceiverPhone != remote.ReceiverPhone) ||
+ (remote.ReceiverAddr != "" && existing.ReceiverAddr != remote.ReceiverAddr) ||
+ (remote.ReceiverCity != "" && existing.ReceiverCity != remote.ReceiverCity) ||
+ (remote.IsBargain && existing.IsBargain == 0)
+}
+
func chunkRefreshTargets(targets []refreshTarget, size int) [][]refreshTarget {
if size <= 0 {
size = refreshOrderChunkSize
@@ -331,37 +480,69 @@ func missingRefreshTargetIDs(targets []refreshTarget, seen map[string]struct{})
}
func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) {
- if s.Browser == nil {
- writeErr(w, http.StatusServiceUnavailable, "浏览器自动化未启用,无法刷新订单")
- return
- }
orderID := chi.URLParam(r, "order_id")
order, ok := s.requireOrderOwner(w, r, orderID)
if !ok {
return
}
- cookieID := order.CookieID
- cookieValue, _, ok := s.cookieForCurrentUser(w, r, cookieID)
+ detailFetcher, ok := s.mtopClient().(orderDetailMTop)
if !ok {
+ writeErr(w, http.StatusServiceUnavailable, "当前 Go MTOP 客户端不支持订单详情接口")
return
}
+ cookieID := order.CookieID
+ credentialUnlock := s.Store.LockAccountCredentials(cookieID)
+ credentialLocked := true
+ defer func() {
+ if credentialLocked {
+ credentialUnlock()
+ }
+ }()
+ sess := auth.SessionFromContext(r.Context())
+ latest, err := s.Store.Cookies.GetDetails(r.Context(), cookieID)
+ if err != nil || latest == nil || latest.UserID != sess.UserID || !hasStoredCookieCredential(latest) {
+ writeErr(w, http.StatusConflict, "账号凭证已变化,请重试")
+ return
+ }
+ cookieValue := latest.Value
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
- detail, err := s.Browser.FetchOrderDetail(ctx, orderID, cookieID, cookieValue, s.Store.Items.IsMultiSpec(ctx, cookieID, order.ItemID))
- if err != nil {
- writeErr(w, http.StatusBadGateway, err.Error())
- return
+ mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
+ detail, callErr := detailFetcher.FetchOrderDetail(mtopCtx, cookieValue, orderID)
+ if callErr == nil && detail == nil {
+ callErr = errors.New("订单详情接口未返回结果")
}
- if detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieValue {
- if err := s.Store.Cookies.UpdateValueExisting(r.Context(), cookieID, detail.UpdatedCookies); err != nil {
- s.Logger.Error("保存订单详情刷新后的 cookie 失败", "cookie_id", cookieID, "err", err)
+ runtimeCookie := ""
+ runtimeCookieChanged := false
+ value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
+ if persistErr != nil {
+ s.Logger.Error("保存订单详情响应 Cookie Jar 失败", "cookie_id", cookieID, "err", persistErr)
+ callErr = errors.Join(callErr, fmt.Errorf("保存订单详情响应 Cookie Jar: %w", persistErr))
+ } else if handled {
+ if valueChanged {
+ runtimeCookie = value
+ runtimeCookieChanged = true
}
- if s.Manager != nil {
- if account, running := s.Manager.GetInstance(cookieID); running {
- account.UpdateCookie(detail.UpdatedCookies)
- }
+ } else if callErr == nil && detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieValue {
+ metadata := cookierefresh.MetadataWithoutSnapshot(latest.MetadataJSON)
+ if saveErr := s.Store.Cookies.UpdateRenewalCookie(r.Context(), cookieID, detail.UpdatedCookies, metadata, time.Now().Unix()); saveErr != nil {
+ s.Logger.Error("保存订单详情刷新后的 cookie 失败", "cookie_id", cookieID, "err", saveErr)
+ } else {
+ runtimeCookie = detail.UpdatedCookies
+ runtimeCookieChanged = true
}
}
+ credentialUnlock()
+ credentialLocked = false
+ if runtimeCookieChanged && s.Manager != nil {
+ if account, running := s.Manager.GetInstance(cookieID); running {
+ account.UpdateCookie(runtimeCookie)
+ }
+ }
+ if callErr != nil {
+ writeErr(w, http.StatusBadGateway, callErr.Error())
+ return
+ }
status := db.NormalizeOrderStatus(detail.OrderStatus)
if !validEditableOrderStatus(status) {
status = db.NormalizeOrderStatus(order.OrderStatus)
@@ -553,7 +734,7 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "订单不存在"})
continue
}
- cookieValue, ok := userCookies[order.CookieID]
+ _, ok := userCookies[order.CookieID]
if !ok {
failedCount++
results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "无权操作此订单"})
@@ -597,23 +778,18 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "mtop 客户端未初始化"})
continue
}
- ok, ret, updatedCookies, err := s.MTop.ConsignContext(r.Context(), cookieValue, orderID)
- if err != nil {
+ ok, ret, runtimeCookie, runtimeCookieChanged, err := s.consignWithCurrentCookie(r.Context(), order.CookieID, orderID, sess.UserID)
+ if runtimeCookieChanged && s.Manager != nil {
+ if acc, running := s.Manager.GetInstance(order.CookieID); running {
+ acc.UpdateCookie(runtimeCookie)
+ }
+ }
+ if err != nil && !ok {
failedCount++
results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "确认发货异常: " + err.Error()})
s.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, "手动确认发货异常: "+err.Error())
continue
}
- if updatedCookies != "" && updatedCookies != cookieValue {
- if err := s.Store.Cookies.UpdateValueOwned(r.Context(), order.CookieID, updatedCookies, sess.UserID); err != nil {
- s.Logger.Error("保存发货刷新后的 cookie 失败", "cookie_id", order.CookieID, "err", err)
- }
- if s.Manager != nil {
- if acc, running := s.Manager.GetInstance(order.CookieID); running {
- acc.UpdateCookie(updatedCookies)
- }
- }
- }
if !ok {
failedCount++
msg := "确认发货失败"
@@ -644,7 +820,13 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
s.Logger.Error("更新订单为系统已发货失败", "order_id", orderID, "err", err)
}
successCount++
- results = append(results, map[string]any{"order_id": orderID, "success": true, "message": "已成功修改闲鱼发货状态"})
+ message := "已成功修改闲鱼发货状态"
+ credentialWarning := ""
+ if err != nil {
+ message += ";但登录凭证更新保存失败,请尽快重新登录(请勿重复确认发货)"
+ credentialWarning = err.Error()
+ }
+ results = append(results, map[string]any{"order_id": orderID, "success": true, "message": message, "credential_warning": credentialWarning})
s.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID,
fmt.Sprintf("手动确认发货成功(订单 %s)", orderID))
}
@@ -657,6 +839,48 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
})
}
+func (s *Server) consignWithCurrentCookie(ctx context.Context, cookieID, orderID string, userID int64) (bool, []string, string, bool, error) {
+ credentialUnlock := s.Store.LockAccountCredentials(cookieID)
+ defer credentialUnlock()
+ detail, err := s.Store.Cookies.GetDetails(ctx, cookieID)
+ if err != nil {
+ return false, nil, "", false, err
+ }
+ if detail == nil || detail.UserID != userID {
+ return false, nil, "", false, db.ErrForbidden
+ }
+ if !hasStoredCookieCredential(detail) {
+ return false, nil, "", false, errors.New("账号 Cookie 为空")
+ }
+ mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, detail)
+ ok, ret, updatedCookies, callErr := s.MTop.ConsignContext(mtopCtx, detail.Value, orderID)
+ value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, detail, cookieSession)
+ if persistErr != nil {
+ persistErr = fmt.Errorf("保存发货响应 Cookie Jar: %w", persistErr)
+ if callErr != nil {
+ return ok, ret, "", false, errors.Join(callErr, persistErr)
+ }
+ return ok, ret, "", false, persistErr
+ }
+ if handled {
+ runtimeCookie := ""
+ if valueChanged {
+ runtimeCookie = value
+ }
+ return ok, ret, runtimeCookie, valueChanged, callErr
+ }
+ if callErr != nil {
+ return false, ret, "", false, callErr
+ }
+ if updatedCookies == "" || updatedCookies == detail.Value {
+ return ok, ret, "", false, nil
+ }
+ if err := s.Store.Cookies.UpdateValueOwned(ctx, cookieID, updatedCookies, userID); err != nil {
+ return ok, ret, "", false, fmt.Errorf("保存发货响应 Cookie: %w", err)
+ }
+ return ok, ret, updatedCookies, true, nil
+}
+
func (s *Server) importOrders(w http.ResponseWriter, r *http.Request) {
orders, err := parseImportedOrders(w, r)
if err != nil {
diff --git a/internal/server/order_handlers_extra_test.go b/internal/server/order_handlers_extra_test.go
index 85eb24f..b3bd542 100644
--- a/internal/server/order_handlers_extra_test.go
+++ b/internal/server/order_handlers_extra_test.go
@@ -4,13 +4,14 @@ import (
"context"
"encoding/json"
"fmt"
+ "io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
-// TestRefreshOrdersNoBrowser 浏览器未启用时应 503。
+// TestRefreshOrdersNoBrowser 浏览器未启用时仍应完成订单列表发现。
func TestRefreshOrdersNoBrowser(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
@@ -21,8 +22,42 @@ func TestRefreshOrdersNoBrowser(t *testing.T) {
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
- if rec.Code != http.StatusServiceUnavailable {
- t.Fatalf("无浏览器应 503,got %d body=%s", rec.Code, rec.Body.String())
+ if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "订单列表同步完成") {
+ t.Fatalf("无浏览器仍应同步列表,got %d body=%s", rec.Code, rec.Body.String())
+ }
+}
+
+func TestRefreshOrdersDiscoversNewOrdersWithoutBrowser(t *testing.T) {
+ srv, store, cleanup := newTestServer(t)
+ defer cleanup()
+ srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ if strings.Contains(req.URL.Query().Get("api"), "order.detail") {
+ body := `{"ret":["SUCCESS::调用成功"],"data":{"utArgs":{"orderStatus":"待发货"},"components":[{"render":"orderInfoVO","data":{"itemInfo":{"buyAmount":"2"},"priceInfo":{"amount":{"value":"19.90"}}}}]}}`
+ return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
+ }
+ body := `{"ret":["SUCCESS::调用成功"],"data":{"module":{"nextPage":"false","totalCount":"1","items":[{` +
+ `"commonData":{"orderId":"sold-new-1","itemId":"item-new","orderStatus":"待发货","inRefund":"false"},` +
+ `"buyerInfoVO":{"buyerId":"buyer-1","name":"张三","phone":"13800000000","address":"上海市"},` +
+ `"priceVO":{"totalPrice":"19.90","buyNum":"2"},` +
+ `"rightVO":{"btnList":[{"tradeAction":"SKIP_PIN"}]}}]}}}`
+ return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
+ }))
+ h := srv.Router()
+ cookie := loginHelper(t, h)
+ req := httptest.NewRequest(http.MethodPost, "/api/orders/refresh", nil)
+ req.AddCookie(cookie)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"discovered":1`) {
+ t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
+ }
+ order, err := store.Orders.Get(context.Background(), "sold-new-1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if order.CookieID != "acc1" || order.ItemID != "item-new" || order.OrderStatus != "pending_ship" ||
+ order.Amount != "19.90" || order.Quantity != "2" || order.IsBargain != 1 || order.ReceiverName != "张三" {
+ t.Fatalf("discovered order=%+v", order)
}
}
@@ -34,10 +69,14 @@ func TestMissingRefreshResultsAreCounted(t *testing.T) {
}
}
-// TestRefreshSingleOrderNoBrowser 单订单刷新无浏览器时 503。
-func TestRefreshSingleOrderNoBrowser(t *testing.T) {
+// TestRefreshSingleOrderUsesGoMTop 单订单刷新不依赖浏览器。
+func TestRefreshSingleOrderUsesGoMTop(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
+ srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ body := `{"ret":["SUCCESS::调用成功"],"data":{"utArgs":{"orderStatus":"待发货"},"components":[{"render":"orderInfoVO","data":{"itemInfo":{"buyAmount":"2","specName":"套餐","specValue":"30天"},"priceInfo":{"amount":{"value":"19.90"}}}}]}}`
+ return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
+ }))
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, cookie_id, order_status) VALUES ('ord-x','item1','acc1','2')`)
h := srv.Router()
@@ -47,8 +86,8 @@ func TestRefreshSingleOrderNoBrowser(t *testing.T) {
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
- if rec.Code != http.StatusServiceUnavailable {
- t.Fatalf("无浏览器应 503,got %d", rec.Code)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("Go MTOP 刷新应成功,got %d body=%s", rec.Code, rec.Body.String())
}
}
diff --git a/internal/server/password_login_handlers.go b/internal/server/password_login_handlers.go
index e811a24..0739383 100644
--- a/internal/server/password_login_handlers.go
+++ b/internal/server/password_login_handlers.go
@@ -1,446 +1,23 @@
package server
import (
- "context"
- "crypto/rand"
- "encoding/base64"
- "errors"
- "fmt"
"net/http"
- "strconv"
- "strings"
- "time"
"github.com/go-chi/chi/v5"
-
- "xianyu-go/internal/auth"
- "xianyu-go/internal/browser"
- "xianyu-go/internal/db"
)
-type passwordLoginRunner interface {
- PasswordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool) (map[string]string, error)
-}
-
-type passwordLoginEventRunner interface {
- PasswordLoginWithEvents(ctx context.Context, account, password, cookieID, userDataDir string, headless bool, onEvent browser.PasswordLoginEventHandler) (map[string]string, error)
-}
-
-const (
- passwordLoginSessionMaxAge = time.Hour
- passwordLoginProcessingTimeout = 5 * time.Minute
- passwordLoginBaxiaPunishReason = "baxia_punish_captcha"
- passwordLoginBaxiaPunishCooldown = 5
-)
-
-type passwordLoginSession struct {
- ID string
- AccountID string
- Account string
- UserID int64
- Status string
- Message string
- Error string
- Reason string
- VerificationURL string
- ScreenshotPath string
- QRCodeURL string
- CooldownHours int
- IsNewAccount bool
- CookieCount int
- ShowBrowser bool
- CreatedAt time.Time
- cancel context.CancelFunc
-}
-
+// mountPasswordLogin 保留历史 API 路径,避免旧前端收到 404。Go 客户端的
+// 登录凭证只允许由扫码流程产生;这里永远不会调用 Chromium 密码登录。
func (s *Server) mountPasswordLogin(r chi.Router) {
- r.Post("/password-login", s.startPasswordLogin)
- r.Get("/password-login/check/{session_id}", s.checkPasswordLogin)
- r.Delete("/password-login/cancel/{session_id}", s.cancelPasswordLogin)
+ r.Post("/password-login", s.passwordLoginDisabled)
+ r.Get("/password-login/check/{session_id}", s.passwordLoginDisabled)
+ r.Delete("/password-login/cancel/{session_id}", s.passwordLoginDisabled)
}
-func (s *Server) startPasswordLogin(w http.ResponseWriter, r *http.Request) {
- var req struct {
- AccountID string `json:"account_id"`
- CookieID string `json:"cookie_id"`
- Account string `json:"account"`
- Username string `json:"username"`
- Password string `json:"password"`
- ShowBrowser bool `json:"show_browser"`
- }
- if err := decodeJSON(r, &req); err != nil {
- writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "请求格式错误"})
- return
- }
- accountID := firstNonEmpty(req.AccountID, req.CookieID)
- account := firstNonEmpty(req.Account, req.Username)
- accountID = strings.TrimSpace(accountID)
- account = strings.TrimSpace(account)
- if accountID == "" || account == "" || req.Password == "" {
- writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "账号ID、登录账号和密码不能为空"})
- return
- }
- if s.PasswordLogin == nil {
- writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "浏览器登录服务不可用"})
- return
- }
- sess := auth.SessionFromContext(r.Context())
- if sess == nil {
- writeErr(w, http.StatusUnauthorized, "未授权访问")
- return
- }
- if ok, message := s.canStartPasswordLogin(r.Context(), sess.UserID, accountID); !ok {
- writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": message})
- return
- }
- s.cleanupExpiredPasswordLoginSessions()
- if sid := s.currentPasswordLoginSession(sess.UserID, accountID); sid != "" {
- writeJSON(w, http.StatusOK, map[string]any{
- "success": true,
- "session_id": sid,
- "status": "processing",
- "message": "账号正在处理中,请稍候...",
- })
- return
- }
-
- sessionID, err := newPasswordSessionID()
- if err != nil {
- writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "创建登录会话失败"})
- return
- }
- ctx, cancel := context.WithTimeout(s.lifecycleContext(), passwordLoginProcessingTimeout)
- loginSession := &passwordLoginSession{
- ID: sessionID,
- AccountID: accountID,
- Account: account,
- UserID: sess.UserID,
- Status: "processing",
- Message: "登录处理中,请稍候...",
- ShowBrowser: req.ShowBrowser,
- CreatedAt: time.Now(),
- cancel: cancel,
- }
- s.passwordMu.Lock()
- s.passwordSessions[sessionID] = loginSession
- s.passwordProcessing[passwordProcessingKey(sess.UserID, accountID)] = sessionID
- s.passwordMu.Unlock()
-
- workerDone := s.beginWorker()
- go func() {
- defer workerDone()
- s.runPasswordLoginSession(ctx, loginSession, req.Password)
- }()
-
+func (s *Server) passwordLoginDisabled(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
- "success": true,
- "session_id": sessionID,
- "status": "processing",
- "message": "登录任务已启动,请等待...",
+ "success": false,
+ "status": "disabled",
+ "message": "Go 客户端仅支持扫码登录,密码登录已禁用",
})
}
-
-func (s *Server) checkPasswordLogin(w http.ResponseWriter, r *http.Request) {
- sessionID := chi.URLParam(r, "session_id")
- s.cleanupExpiredPasswordLoginSessions()
-
- s.passwordMu.Lock()
- session, ok := s.passwordSessions[sessionID]
- if !ok {
- s.passwordMu.Unlock()
- writeJSON(w, http.StatusOK, map[string]any{"status": "not_found", "message": "会话不存在或已过期"})
- return
- }
- requestSession := auth.SessionFromContext(r.Context())
- if requestSession == nil || session.UserID != requestSession.UserID {
- s.passwordMu.Unlock()
- writeJSON(w, http.StatusOK, map[string]any{"status": "not_found", "message": "会话不存在或已过期"})
- return
- }
- response := passwordSessionResponse(session)
- s.passwordMu.Unlock()
- writeJSON(w, http.StatusOK, response)
-}
-
-func (s *Server) cancelPasswordLogin(w http.ResponseWriter, r *http.Request) {
- sessionID := chi.URLParam(r, "session_id")
- s.passwordMu.Lock()
- session, ok := s.passwordSessions[sessionID]
- if !ok {
- s.passwordMu.Unlock()
- writeJSON(w, http.StatusOK, map[string]any{"success": false, "code": 404, "message": "会话不存在", "data": nil})
- return
- }
- requestSession := auth.SessionFromContext(r.Context())
- if requestSession == nil || session.UserID != requestSession.UserID {
- s.passwordMu.Unlock()
- writeJSON(w, http.StatusOK, map[string]any{"success": false, "code": 404, "message": "会话不存在", "data": nil})
- return
- }
- if session.cancel != nil {
- session.cancel()
- }
- delete(s.passwordSessions, sessionID)
- delete(s.passwordProcessing, passwordProcessingKey(session.UserID, session.AccountID))
- s.passwordMu.Unlock()
- writeJSON(w, http.StatusOK, map[string]any{"success": true, "code": 200, "message": "登录会话已取消", "data": nil})
-}
-
-func (s *Server) runPasswordLoginSession(ctx context.Context, session *passwordLoginSession, password string) {
- var (
- cookies map[string]string
- err error
- )
- headless := browser.ResolveHeadless(session.ShowBrowser)
- if runner, ok := s.PasswordLogin.(passwordLoginEventRunner); ok {
- cookies, err = runner.PasswordLoginWithEvents(ctx, session.Account, password, session.AccountID, "", headless, func(event browser.PasswordLoginEvent) {
- s.applyPasswordLoginEvent(session, event)
- })
- } else {
- cookies, err = s.PasswordLogin.PasswordLogin(ctx, session.Account, password, session.AccountID, "", headless)
- }
- if err != nil {
- event := browser.PasswordLoginEventFromError(err)
- status := event.Status
- if status == "" {
- status = "failed"
- }
- reason := passwordLoginReason(err)
- s.addLoginLog(context.Background(), session.AccountID, session.UserID, loginMethodPassword, loginStatusFailed, reason, err.Error(), 0)
- s.failPasswordLoginSession(session, status, err.Error(), reason, event.CooldownHours)
- return
- }
- accountID, isNew, err := s.savePasswordLoginCookies(ctx, session, password, cookies)
- if err != nil {
- s.addLoginLog(context.Background(), session.AccountID, session.UserID, loginMethodPassword, loginStatusFailed, "cookie_update_failed", err.Error(), 0)
- s.failPasswordLoginSession(session, "failed", "保存登录结果失败: "+err.Error(), "", 0)
- return
- }
- s.completePasswordLoginSession(session, func(current *passwordLoginSession) {
- current.Status = "success"
- current.Message = "账号 " + accountID + " 登录成功"
- current.AccountID = accountID
- current.IsNewAccount = isNew
- current.CookieCount = len(cookies)
- })
-}
-
-func (s *Server) savePasswordLoginCookies(ctx context.Context, session *passwordLoginSession, password string, cookies map[string]string) (string, bool, error) {
- if len(cookies) == 0 {
- return "", false, errors.New("浏览器未返回 cookie")
- }
- accountID := cookieAccountID(cookies, session.AccountID)
- if accountID != session.AccountID {
- return "", false, fmt.Errorf("登录结果账号 %s 与正在编辑的账号 %s 不一致,已拒绝覆盖", accountID, session.AccountID)
- }
- cookieValue := browser.MarshalCookies(cookies)
- _, err := s.Store.Cookies.GetDetails(ctx, accountID)
- isNew := errors.Is(err, db.ErrNotFound)
- if err != nil && !errors.Is(err, db.ErrNotFound) {
- return "", false, err
- }
- if err := s.Store.Cookies.UpdateValueOwned(ctx, accountID, cookieValue, session.UserID); err != nil {
- return "", false, err
- }
- if err := s.Store.Cookies.UpdateLoginInfo(ctx, accountID, session.Account, password, session.ShowBrowser); err != nil {
- return "", false, err
- }
- s.markSuccessfulLogin(ctx, accountID, session.UserID, loginMethodPassword, "账号密码登录成功")
- if s.Store.Tokens != nil {
- _ = s.Store.Tokens.Clear(ctx, accountID)
- }
- if d, err := s.Store.Cookies.GetDetails(ctx, accountID); err == nil {
- s.refreshAccountProfile(ctx, d)
- }
- if s.Manager != nil && s.Store.Cookies.GetStatus(ctx, accountID) {
- if err := s.Manager.Restart(ctx, accountID); err != nil && s.Logger != nil {
- s.Logger.Warn("密码登录后重启账号失败", "cookie_id", accountID, "err", err)
- }
- }
- return accountID, isNew, nil
-}
-
-func (s *Server) canStartPasswordLogin(ctx context.Context, userID int64, accountID string) (bool, string) {
- d, err := s.Store.Cookies.GetDetails(ctx, accountID)
- if err == nil {
- if d.UserID != userID {
- return false, "无权限操作该账号"
- }
- if !s.Store.Cookies.GetStatus(ctx, accountID) {
- return false, "账号已禁用,请先在账号管理中启用"
- }
- return true, ""
- }
- if errors.Is(err, db.ErrNotFound) {
- return true, ""
- }
- return false, "查询账号失败"
-}
-
-func passwordProcessingKey(userID int64, accountID string) string {
- return strconv.FormatInt(userID, 10) + ":" + accountID
-}
-
-func (s *Server) currentPasswordLoginSession(userID int64, accountID string) string {
- s.passwordMu.Lock()
- defer s.passwordMu.Unlock()
- return s.passwordProcessing[passwordProcessingKey(userID, accountID)]
-}
-
-func (s *Server) completePasswordLoginSession(session *passwordLoginSession, mutate func(*passwordLoginSession)) {
- s.finishPasswordLoginSession(session, mutate)
-}
-
-func (s *Server) updatePasswordLoginSession(session *passwordLoginSession, mutate func(*passwordLoginSession)) bool {
- s.passwordMu.Lock()
- defer s.passwordMu.Unlock()
- current, ok := s.passwordSessions[session.ID]
- if !ok || current != session {
- return false
- }
- mutate(current)
- return true
-}
-
-func (s *Server) finishPasswordLoginSession(session *passwordLoginSession, mutate func(*passwordLoginSession)) {
- s.passwordMu.Lock()
- defer s.passwordMu.Unlock()
- current, ok := s.passwordSessions[session.ID]
- if !ok || current != session {
- return
- }
- originalAccountID := current.AccountID
- mutate(current)
- delete(s.passwordProcessing, passwordProcessingKey(current.UserID, originalAccountID))
- delete(s.passwordProcessing, passwordProcessingKey(current.UserID, current.AccountID))
-}
-
-func (s *Server) applyPasswordLoginEvent(session *passwordLoginSession, event browser.PasswordLoginEvent) {
- if event.Status == "" {
- return
- }
- apply := func(current *passwordLoginSession) {
- current.Status = event.Status
- current.Message = firstNonEmpty(event.Message, current.Message)
- current.Error = firstNonEmpty(event.Error, current.Error)
- current.Reason = firstNonEmpty(event.Reason, current.Reason)
- current.VerificationURL = firstNonEmpty(event.VerificationURL, current.VerificationURL)
- current.ScreenshotPath = firstNonEmpty(event.ScreenshotPath, current.ScreenshotPath)
- current.QRCodeURL = firstNonEmpty(event.QRCodeURL, current.QRCodeURL)
- if event.CooldownHours > 0 {
- current.CooldownHours = event.CooldownHours
- }
- }
- if passwordLoginEventIsTerminal(event.Status) {
- s.finishPasswordLoginSession(session, apply)
- return
- }
- s.updatePasswordLoginSession(session, apply)
-}
-
-func (s *Server) failPasswordLoginSession(session *passwordLoginSession, status, message, reason string, cooldownHours int) {
- s.completePasswordLoginSession(session, func(current *passwordLoginSession) {
- current.Status = status
- current.Message = message
- current.Error = message
- current.Reason = reason
- current.CooldownHours = cooldownHours
- })
-}
-
-func passwordLoginEventIsTerminal(status string) bool {
- return status == "success" || status == browser.PasswordLoginStatusFailed
-}
-
-func (s *Server) cleanupExpiredPasswordLoginSessions() {
- now := time.Now()
- s.passwordMu.Lock()
- defer s.passwordMu.Unlock()
- for sessionID, session := range s.passwordSessions {
- age := now.Sub(session.CreatedAt)
- if session.Status == "processing" && age > passwordLoginProcessingTimeout {
- if session.cancel != nil {
- session.cancel()
- }
- session.Status = "failed"
- session.Message = "登录处理超时,请稍后重试"
- session.Error = session.Message
- delete(s.passwordProcessing, passwordProcessingKey(session.UserID, session.AccountID))
- }
- if age <= passwordLoginSessionMaxAge {
- continue
- }
- if session.cancel != nil {
- session.cancel()
- }
- delete(s.passwordSessions, sessionID)
- delete(s.passwordProcessing, passwordProcessingKey(session.UserID, session.AccountID))
- }
-}
-
-func passwordSessionResponse(session *passwordLoginSession) map[string]any {
- resp := map[string]any{
- "status": session.Status,
- "message": session.Message,
- }
- if session.Status == "success" {
- resp["account_id"] = session.AccountID
- resp["is_new_account"] = session.IsNewAccount
- resp["cookie_count"] = session.CookieCount
- }
- if session.Status == "failed" {
- resp["error"] = session.Error
- if session.Reason != "" {
- resp["reason"] = session.Reason
- }
- if session.CooldownHours > 0 {
- resp["cooldown_hours"] = session.CooldownHours
- }
- }
- if session.Status == "verification_required" {
- resp["verification_url"] = session.VerificationURL
- resp["screenshot_path"] = session.ScreenshotPath
- resp["qr_code_url"] = session.QRCodeURL
- resp["error"] = session.Error
- if session.CooldownHours > 0 {
- resp["cooldown_hours"] = session.CooldownHours
- }
- }
- return resp
-}
-
-func newPasswordSessionID() (string, error) {
- var b [18]byte
- if _, err := rand.Read(b[:]); err != nil {
- return "", err
- }
- return base64.RawURLEncoding.EncodeToString(b[:]), nil
-}
-
-func cookieAccountID(cookies map[string]string, fallback string) string {
- for k, v := range cookies {
- if strings.EqualFold(strings.TrimSpace(k), "unb") && strings.TrimSpace(v) != "" {
- return strings.TrimSpace(v)
- }
- }
- return fallback
-}
-
-func passwordLoginReason(err error) string {
- if err == nil {
- return ""
- }
- msg := err.Error()
- if strings.Contains(msg, "账密错误") || strings.Contains(msg, "账号密码错误") ||
- strings.Contains(msg, "用户名或密码错误") || strings.Contains(msg, "密码错误") {
- return "bad_credentials"
- }
- event := browser.PasswordLoginEventFromError(err)
- if event.Reason != "" {
- return event.Reason
- }
- if event.Status == browser.PasswordLoginStatusVerificationRequired {
- return "verification_required"
- }
- return "other"
-}
diff --git a/internal/server/password_login_handlers_test.go b/internal/server/password_login_handlers_test.go
index 430f0aa..234f23c 100644
--- a/internal/server/password_login_handlers_test.go
+++ b/internal/server/password_login_handlers_test.go
@@ -1,462 +1,37 @@
package server
import (
- "context"
"encoding/json"
- "errors"
"net/http"
"net/http/httptest"
"strings"
- "sync"
"testing"
- "time"
-
- "xianyu-go/internal/browser"
- "xianyu-go/internal/db"
)
-type fakePasswordLoginRunner struct {
- mu sync.Mutex
- cookies map[string]string
- err error
- block chan struct{}
- events []browser.PasswordLoginEvent
- calls int
- lastAccount string
- lastHeadless bool
-}
-
-func (f *fakePasswordLoginRunner) PasswordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool) (map[string]string, error) {
- f.mu.Lock()
- f.calls++
- f.lastAccount = account
- f.lastHeadless = headless
- f.mu.Unlock()
- if f.block != nil {
- select {
- case <-f.block:
- case <-ctx.Done():
- return nil, ctx.Err()
- }
- }
- return f.cookies, f.err
-}
-
-func (f *fakePasswordLoginRunner) PasswordLoginWithEvents(ctx context.Context, account, password, cookieID, userDataDir string, headless bool, onEvent browser.PasswordLoginEventHandler) (map[string]string, error) {
- for _, event := range f.events {
- onEvent(event)
- }
- return f.PasswordLogin(ctx, account, password, cookieID, userDataDir, headless)
-}
-
-func (f *fakePasswordLoginRunner) snapshot() (int, string, bool) {
- f.mu.Lock()
- defer f.mu.Unlock()
- return f.calls, f.lastAccount, f.lastHeadless
-}
-
-func loginForPasswordTest(t *testing.T, h http.Handler) *http.Cookie {
- t.Helper()
- req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`))
- rec := httptest.NewRecorder()
- h.ServeHTTP(rec, req)
- if rec.Code != http.StatusOK || len(rec.Result().Cookies()) == 0 {
- t.Fatalf("login status=%d body=%s", rec.Code, rec.Body.String())
- }
- return rec.Result().Cookies()[0]
-}
-
-func startPasswordLoginForTest(t *testing.T, h http.Handler, cookie *http.Cookie, body string) map[string]any {
- t.Helper()
- req := httptest.NewRequest(http.MethodPost, "/password-login", strings.NewReader(body))
- req.AddCookie(cookie)
- rec := httptest.NewRecorder()
- h.ServeHTTP(rec, req)
- if rec.Code != http.StatusOK {
- t.Fatalf("start status=%d body=%s", rec.Code, rec.Body.String())
- }
- var out map[string]any
- if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
- t.Fatalf("decode start: %v body=%s", err, rec.Body.String())
- }
- return out
-}
-
-func checkPasswordLoginForTest(t *testing.T, h http.Handler, cookie *http.Cookie, sessionID string) map[string]any {
- t.Helper()
- req := httptest.NewRequest(http.MethodGet, "/password-login/check/"+sessionID, nil)
- req.AddCookie(cookie)
- rec := httptest.NewRecorder()
- h.ServeHTTP(rec, req)
- if rec.Code != http.StatusOK {
- t.Fatalf("check status=%d body=%s", rec.Code, rec.Body.String())
- }
- var out map[string]any
- if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
- t.Fatalf("decode check: %v body=%s", err, rec.Body.String())
- }
- return out
-}
-
-func cancelPasswordLoginForTest(t *testing.T, h http.Handler, cookie *http.Cookie, sessionID string) {
- t.Helper()
- req := httptest.NewRequest(http.MethodDelete, "/password-login/cancel/"+sessionID, nil)
- req.AddCookie(cookie)
- rec := httptest.NewRecorder()
- h.ServeHTTP(rec, req)
- if rec.Code != http.StatusOK {
- t.Fatalf("cancel status=%d body=%s", rec.Code, rec.Body.String())
- }
-}
-
-func waitPasswordLoginStatus(t *testing.T, h http.Handler, cookie *http.Cookie, sessionID, want string) map[string]any {
- t.Helper()
- var out map[string]any
- for i := 0; i < 50; i++ {
- out = checkPasswordLoginForTest(t, h, cookie, sessionID)
- if out["status"] == want {
- return out
- }
- time.Sleep(10 * time.Millisecond)
- }
- t.Fatalf("status did not reach %q, last=%+v", want, out)
- return nil
-}
-
-func waitLoginLogCount(t *testing.T, store *db.Store, cookieID string, want int) []db.AccountLoginLog {
- t.Helper()
- var logs []db.AccountLoginLog
- var err error
- for i := 0; i < 50; i++ {
- logs, err = store.LoginLogs.ListByCookie(context.Background(), cookieID, 10)
- if err == nil && len(logs) >= want {
- return logs
- }
- time.Sleep(10 * time.Millisecond)
- }
- t.Fatalf("login logs did not reach %d: logs=%#v err=%v", want, logs, err)
- return nil
-}
-
-func TestPasswordLoginSessionSuccessSavesCookiesAndAudit(t *testing.T) {
- srv, store, cleanup := newTestServer(t)
- defer cleanup()
- srv.Manager = nil
- fake := &fakePasswordLoginRunner{cookies: map[string]string{"unb": "acc1", "_m_h5_tk": "fresh"}}
- srv.PasswordLogin = fake
- h := srv.Router()
- cookie := loginForPasswordTest(t, h)
- if err := store.Tokens.Save(context.Background(), "acc1", "did", "token", time.Now().Add(time.Hour).Unix()); err != nil {
- t.Fatalf("save token: %v", err)
- }
-
- start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"login-user","password":"secret","show_browser":false}`)
- if start["success"] != true || start["status"] != "processing" {
- t.Fatalf("start response=%+v", start)
- }
- sessionID, _ := start["session_id"].(string)
- if sessionID == "" {
- t.Fatalf("missing session_id: %+v", start)
- }
- done := waitPasswordLoginStatus(t, h, cookie, sessionID, "success")
- if done["account_id"] != "acc1" || done["is_new_account"] != false {
- t.Fatalf("success response=%+v", done)
- }
- calls, account, headless := fake.snapshot()
- if calls != 1 || account != "login-user" || !headless {
- t.Fatalf("PasswordLogin 调用异常: calls=%d account=%q headless=%v", calls, account, headless)
- }
- saved, _ := store.Cookies.GetValue(context.Background(), "acc1")
- if !strings.Contains(saved, "_m_h5_tk=fresh") {
- t.Fatalf("cookie 未保存: %q", saved)
- }
- d, err := store.Cookies.GetDetails(context.Background(), "acc1")
- if err != nil {
- t.Fatalf("GetDetails: %v", err)
- }
- if d.Username != "login-user" || d.Password != "secret" || d.ShowBrowser || d.LoginMethod != "password" || d.LastLoginAt == 0 {
- t.Fatalf("登录信息/审计字段异常: %+v", d)
- }
- if tk, err := store.Tokens.Get(context.Background(), "acc1"); err != nil || tk.AccessToken != "" || tk.DeviceID != "did" {
- t.Fatalf("密码登录成功应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
- }
- logs, err := store.LoginLogs.ListByCookie(context.Background(), "acc1", 10)
- if err != nil || len(logs) != 1 || logs[0].Status != "success" {
- t.Fatalf("登录日志异常: logs=%#v err=%v", logs, err)
- }
-}
-
-func TestPasswordLoginRejectsMismatchedReturnedAccount(t *testing.T) {
- srv, store, cleanup := newTestServer(t)
- defer cleanup()
- srv.Manager = nil
- srv.PasswordLogin = &fakePasswordLoginRunner{cookies: map[string]string{"unb": "other-account", "_m_h5_tk": "wrong"}}
- h := srv.Router()
- cookie := loginForPasswordTest(t, h)
-
- start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"login-user","password":"secret"}`)
- done := waitPasswordLoginStatus(t, h, cookie, start["session_id"].(string), "failed")
- if !strings.Contains(done["error"].(string), "不一致") {
- t.Fatalf("mismatch error=%+v", done)
- }
- if saved, err := store.Cookies.GetValue(context.Background(), "acc1"); err != nil || strings.Contains(saved, "wrong") {
- t.Fatalf("target cookie must remain unchanged: value=%q err=%v", saved, err)
- }
- if _, err := store.Cookies.GetValue(context.Background(), "other-account"); !errors.Is(err, db.ErrNotFound) {
- t.Fatalf("mismatched account must not be created: %v", err)
- }
-}
-
-func TestPasswordLoginTerminalResultCanBePolledAgain(t *testing.T) {
- srv, _, cleanup := newTestServer(t)
- defer cleanup()
- srv.Manager = nil
- srv.PasswordLogin = &fakePasswordLoginRunner{cookies: map[string]string{"unb": "acc1", "_m_h5_tk": "fresh"}}
- h := srv.Router()
- cookie := loginHelper(t, h)
- start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"login-user","password":"secret"}`)
- sessionID := start["session_id"].(string)
- first := waitPasswordLoginStatus(t, h, cookie, sessionID, "success")
- second := checkPasswordLoginForTest(t, h, cookie, sessionID)
- if first["account_id"] != "acc1" || second["status"] != "success" || second["account_id"] != "acc1" {
- t.Fatalf("terminal result must remain idempotently readable: first=%+v second=%+v", first, second)
- }
-}
-
-func TestPasswordLoginUnavailableWhenBrowserManagerNil(t *testing.T) {
+func TestPasswordLoginAPIsArePermanentlyDisabled(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
- cookie := loginForPasswordTest(t, h)
+ authCookie := loginHelper(t, h)
- start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
- if start["success"] != false || start["message"] != "浏览器登录服务不可用" {
- t.Fatalf("nil 浏览器应返回不可用且不启动登录: %+v", start)
- }
-}
-
-func TestPasswordLoginSessionShowBrowserRunsVisibleAndSavesPreference(t *testing.T) {
- srv, store, cleanup := newTestServer(t)
- defer cleanup()
- srv.Manager = nil
- fake := &fakePasswordLoginRunner{cookies: map[string]string{"unb": "acc1", "_m_h5_tk": "fresh"}}
- srv.PasswordLogin = fake
- h := srv.Router()
- cookie := loginForPasswordTest(t, h)
-
- start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"login-user","password":"secret","show_browser":true}`)
- sessionID, _ := start["session_id"].(string)
- if sessionID == "" {
- t.Fatalf("missing session_id: %+v", start)
- }
- waitPasswordLoginStatus(t, h, cookie, sessionID, "success")
-
- calls, account, headless := fake.snapshot()
- if calls != 1 || account != "login-user" || headless {
- t.Fatalf("show_browser=true 应使用可视浏览器: calls=%d account=%q headless=%v", calls, account, headless)
- }
- d, err := store.Cookies.GetDetails(context.Background(), "acc1")
- if err != nil {
- t.Fatalf("GetDetails: %v", err)
- }
- if !d.ShowBrowser {
- t.Fatalf("show_browser=true 应按原请求落库: %+v", d)
- }
-}
-
-func TestPasswordLoginDuplicateStartReturnsProcessingSession(t *testing.T) {
- srv, store, cleanup := newTestServer(t)
- defer cleanup()
- srv.Manager = nil
- fake := &fakePasswordLoginRunner{block: make(chan struct{}), cookies: map[string]string{"unb": "acc1"}}
- srv.PasswordLogin = fake
- h := srv.Router()
- cookie := loginForPasswordTest(t, h)
-
- first := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
- second := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
- if first["session_id"] == "" || second["session_id"] != first["session_id"] || second["status"] != "processing" {
- t.Fatalf("重复启动应返回同一 processing 会话: first=%+v second=%+v", first, second)
- }
-
- cancelPasswordLoginForTest(t, h, cookie, first["session_id"].(string))
- waitLoginLogCount(t, store, "acc1", 1)
-}
-
-func TestPasswordLoginSessionCannotBeCheckedOrCanceledByAnotherUser(t *testing.T) {
- srv, store, cleanup := newTestServer(t)
- defer cleanup()
- srv.Manager = nil
- if ok, err := store.Users.Create(context.Background(), "member", "member@example.com", "memberpw"); err != nil || !ok {
- t.Fatalf("create member: ok=%v err=%v", ok, err)
- }
- fake := &fakePasswordLoginRunner{block: make(chan struct{}), cookies: map[string]string{"unb": "acc1"}}
- srv.PasswordLogin = fake
- h := srv.Router()
- adminCookie := loginForPasswordTest(t, h)
- memberCookie := loginAsHelper(t, h, "member", "memberpw")
-
- start := startPasswordLoginForTest(t, h, adminCookie, `{"account_id":"acc1","account":"u","password":"p"}`)
- sessionID, _ := start["session_id"].(string)
- if sessionID == "" {
- t.Fatalf("missing session: %+v", start)
- }
- checked := checkPasswordLoginForTest(t, h, memberCookie, sessionID)
- if checked["status"] != "not_found" {
- t.Fatalf("cross-user check exposed session: %+v", checked)
- }
-
- cancelReq := httptest.NewRequest(http.MethodDelete, "/password-login/cancel/"+sessionID, nil)
- cancelReq.AddCookie(memberCookie)
- cancelRec := httptest.NewRecorder()
- h.ServeHTTP(cancelRec, cancelReq)
- var canceled map[string]any
- if err := json.Unmarshal(cancelRec.Body.Bytes(), &canceled); err != nil {
- t.Fatal(err)
- }
- if canceled["success"] != false {
- t.Fatalf("cross-user cancel should be hidden: %+v", canceled)
- }
- if owner := checkPasswordLoginForTest(t, h, adminCookie, sessionID); owner["status"] != "processing" {
- t.Fatalf("owner session was canceled by another user: %+v", owner)
- }
- cancelPasswordLoginForTest(t, h, adminCookie, sessionID)
- waitLoginLogCount(t, store, "acc1", 1)
-}
-
-func TestPasswordLoginVerificationRequiredKeepsProcessingLock(t *testing.T) {
- srv, store, cleanup := newTestServer(t)
- defer cleanup()
- srv.Manager = nil
- fake := &fakePasswordLoginRunner{
- block: make(chan struct{}),
- events: []browser.PasswordLoginEvent{{
- Status: browser.PasswordLoginStatusVerificationRequired,
- Message: "需要人脸验证,请查看验证截图",
- Error: "需要人脸验证",
- ScreenshotPath: "/tmp/face.png",
- }},
- cookies: map[string]string{"unb": "acc1"},
- }
- srv.PasswordLogin = fake
- h := srv.Router()
- cookie := loginForPasswordTest(t, h)
-
- first := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
- sessionID := first["session_id"].(string)
- waitPasswordLoginStatus(t, h, cookie, sessionID, "verification_required")
- second := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
- if second["session_id"] != sessionID {
- t.Fatalf("验证码等待期间应继续复用同一会话: first=%+v second=%+v", first, second)
- }
- if calls, _, _ := fake.snapshot(); calls != 1 {
- t.Fatalf("验证码等待期间不应启动第二个浏览器任务,calls=%d", calls)
- }
-
- cancelPasswordLoginForTest(t, h, cookie, sessionID)
- waitLoginLogCount(t, store, "acc1", 1)
-}
-
-func TestPasswordLoginProcessingTimeoutReleasesAccount(t *testing.T) {
- srv, store, cleanup := newTestServer(t)
- defer cleanup()
- srv.Manager = nil
- fake := &fakePasswordLoginRunner{block: make(chan struct{}), cookies: map[string]string{"unb": "acc1"}}
- srv.PasswordLogin = fake
- h := srv.Router()
- cookie := loginForPasswordTest(t, h)
-
- first := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
- sessionID := first["session_id"].(string)
- srv.passwordMu.Lock()
- srv.passwordSessions[sessionID].CreatedAt = time.Now().Add(-(passwordLoginProcessingTimeout + time.Second))
- srv.passwordMu.Unlock()
-
- second := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
- if second["session_id"] == "" || second["session_id"] == sessionID {
- t.Fatalf("processing 超时后应创建新会话: first=%+v second=%+v", first, second)
- }
- oldStatus := checkPasswordLoginForTest(t, h, cookie, sessionID)
- if oldStatus["status"] != "failed" {
- t.Fatalf("超时旧会话应标记 failed: %+v", oldStatus)
- }
- cancelPasswordLoginForTest(t, h, cookie, second["session_id"].(string))
- waitLoginLogCount(t, store, "acc1", 2)
-}
-
-func TestPasswordLoginSessionExpiresAfterOneHour(t *testing.T) {
- srv, store, cleanup := newTestServer(t)
- defer cleanup()
- srv.Manager = nil
- fake := &fakePasswordLoginRunner{block: make(chan struct{}), cookies: map[string]string{"unb": "acc1"}}
- srv.PasswordLogin = fake
- h := srv.Router()
- cookie := loginForPasswordTest(t, h)
-
- start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
- sessionID := start["session_id"].(string)
- srv.passwordMu.Lock()
- srv.passwordSessions[sessionID].CreatedAt = time.Now().Add(-(passwordLoginSessionMaxAge + time.Second))
- srv.passwordMu.Unlock()
-
- done := checkPasswordLoginForTest(t, h, cookie, sessionID)
- if done["status"] != "not_found" {
- t.Fatalf("1小时后会话应过期: %+v", done)
- }
- waitLoginLogCount(t, store, "acc1", 1)
-}
-
-func TestPasswordLoginVerificationRequired(t *testing.T) {
- srv, store, cleanup := newTestServer(t)
- defer cleanup()
- srv.Manager = nil
- srv.PasswordLogin = &fakePasswordLoginRunner{
- events: []browser.PasswordLoginEvent{{
- Status: browser.PasswordLoginStatusVerificationRequired,
- Message: "需要人脸验证,请查看验证截图",
- Error: "需要人脸验证",
- ScreenshotPath: "/tmp/face.png",
- }},
- err: errors.New("需要人脸验证"),
- }
- h := srv.Router()
- cookie := loginForPasswordTest(t, h)
-
- start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
- sessionID := start["session_id"].(string)
- done := waitPasswordLoginStatus(t, h, cookie, sessionID, "verification_required")
- if done["error"] == "" {
- t.Fatalf("verification_required 应带 error: %+v", done)
- }
- if done["screenshot_path"] != "/tmp/face.png" {
- t.Fatalf("verification_required 应带截图: %+v", done)
- }
- again := checkPasswordLoginForTest(t, h, cookie, sessionID)
- if again["status"] != "verification_required" {
- t.Fatalf("验证态会话应保留: %+v", again)
- }
- logs := waitLoginLogCount(t, store, "acc1", 1)
- if logs[0].FailureReason != "verification_required" {
- t.Fatalf("验证态应记录 failure_reason: %#v", logs)
- }
-}
-
-func TestPasswordLoginBaxiaReason(t *testing.T) {
- srv, store, cleanup := newTestServer(t)
- defer cleanup()
- srv.Manager = nil
- srv.PasswordLogin = &fakePasswordLoginRunner{err: errors.New("baxia-punish 风控图形验证")}
- h := srv.Router()
- cookie := loginForPasswordTest(t, h)
-
- start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
- sessionID := start["session_id"].(string)
- done := waitPasswordLoginStatus(t, h, cookie, sessionID, "failed")
- if done["reason"] != "baxia_punish_captcha" || done["cooldown_hours"] != float64(5) {
- t.Fatalf("baxia 错误应带 reason/cooldown: %+v", done)
- }
- logs, err := store.LoginLogs.ListByCookie(context.Background(), "acc1", 10)
- if err != nil || len(logs) != 1 || logs[0].FailureReason != "baxia_punish_captcha" {
- t.Fatalf("baxia 错误应记录专用 failure_reason: logs=%#v err=%v", logs, err)
+ requests := []*http.Request{
+ httptest.NewRequest(http.MethodPost, "/password-login", strings.NewReader(`{"account_id":"acc1","account":"u","password":"p"}`)),
+ httptest.NewRequest(http.MethodGet, "/password-login/check/legacy", nil),
+ httptest.NewRequest(http.MethodDelete, "/password-login/cancel/legacy", nil),
+ }
+ for _, req := range requests {
+ req.AddCookie(authCookie)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("%s %s status=%d body=%s", req.Method, req.URL.Path, rec.Code, rec.Body.String())
+ }
+ var result map[string]any
+ if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
+ t.Fatal(err)
+ }
+ if result["success"] != false || result["status"] != "disabled" {
+ t.Fatalf("%s %s 应永久禁用: %+v", req.Method, req.URL.Path, result)
+ }
}
}
diff --git a/internal/server/publish_batch_test.go b/internal/server/publish_batch_test.go
index aba1e36..d539416 100644
--- a/internal/server/publish_batch_test.go
+++ b/internal/server/publish_batch_test.go
@@ -122,6 +122,27 @@ func TestPreviewItemPublishBatchNoFile(t *testing.T) {
}
}
+func TestPreviewItemPublishBatchRequiresDefaultAccount(t *testing.T) {
+ srv, _, cleanup := newTestServer(t)
+ defer cleanup()
+ h := srv.Router()
+ cookie := loginHelper(t, h)
+
+ var buf bytes.Buffer
+ mw := multipart.NewWriter(&buf)
+ file, _ := mw.CreateFormFile("file", "products.csv")
+ file.Write([]byte("标题,价格,图片\n商品A,12.50,https://example.com/a.png\n"))
+ _ = mw.Close()
+ req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
+ req.Header.Set("Content-Type", mw.FormDataContentType())
+ req.AddCookie(cookie)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "请选择默认发布账号") {
+ t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
+ }
+}
+
// TestPreviewItemPublishBatchBadDefaultCookie 默认账号不属于当前用户 403。
func TestPreviewItemPublishBatchBadDefaultCookie(t *testing.T) {
srv, _, cleanup := newTestServer(t)
diff --git a/internal/server/qrlogin_handlers.go b/internal/server/qrlogin_handlers.go
index ea6425f..b7c89b5 100644
--- a/internal/server/qrlogin_handlers.go
+++ b/internal/server/qrlogin_handlers.go
@@ -12,6 +12,7 @@ import (
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
+ "xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/protocol"
)
@@ -144,11 +145,17 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
}
sess := auth.SessionFromContext(r.Context())
if sess != nil {
- persisted, persistErr := s.persistQRLoginSuccessFor(r.Context(), sess.UserID, sessionID, map[string]any{
+ result := map[string]any{
"status": "success",
"cookies": cookies,
"unb": unb,
- }, req.TargetAccountID)
+ }
+ if current := s.QRLogin.GetSessionStatus(sessionID); current != nil {
+ if snapshot, ok := current["cookie_snapshot"]; ok {
+ result["cookie_snapshot"] = snapshot
+ }
+ }
+ persisted, persistErr := s.persistQRLoginSuccessFor(r.Context(), sess.UserID, sessionID, result, req.TargetAccountID)
if persistErr != nil {
if s.Logger != nil {
s.Logger.Warn("保存扫码验证结果失败", "session_id", sessionID, "err", persistErr)
@@ -187,6 +194,7 @@ func (s *Server) persistQRLoginSuccessFor(ctx context.Context, userID int64, ses
}
s.qrMu.Unlock()
cookies := qrString(result, "cookies")
+ cookieSnapshot, snapshotComplete := qrCookieSnapshot(result)
scannedAccountID := strings.TrimSpace(firstNonEmpty(qrString(result, "unb"), protocol.TransCookies(cookies)["unb"]))
if cookies == "" || scannedAccountID == "" {
return qrLoginPersistence{}, errors.New("扫码结果缺少 cookies 或 unb")
@@ -194,30 +202,57 @@ func (s *Server) persistQRLoginSuccessFor(ctx context.Context, userID int64, ses
accountID := strings.TrimSpace(targetAccountID)
if accountID == "" {
accountID = scannedAccountID
- } else {
- if accountID != scannedAccountID {
- return qrLoginPersistence{}, errors.New("扫码账号与待重新授权账号不一致,已拒绝覆盖")
- }
- target, err := s.Store.Cookies.GetDetails(ctx, accountID)
- if err != nil {
- return qrLoginPersistence{}, errors.New("待重新授权账号不存在")
- }
- if target.UserID != userID {
- return qrLoginPersistence{}, errors.New("待重新授权账号不属于当前用户")
- }
+ } else if accountID != scannedAccountID {
+ return qrLoginPersistence{}, errors.New("扫码账号与待重新授权账号不一致,已拒绝覆盖")
}
- _, err := s.Store.Cookies.GetDetails(ctx, accountID)
- isNew := errors.Is(err, db.ErrNotFound)
- if err != nil && !errors.Is(err, db.ErrNotFound) {
- return qrLoginPersistence{}, err
- }
- var saveErr error
- if isNew {
- saveErr = s.Store.Cookies.CreateOwned(ctx, accountID, cookies, userID)
- } else {
- saveErr = s.Store.Cookies.UpdateValueOwned(ctx, accountID, cookies, userID)
- }
+ isNew := false
+ credentialUnlock := s.Store.LockAccountCredentials(accountID)
+ saveErr := func() error {
+ defer credentialUnlock()
+ detail, err := s.Store.Cookies.GetDetails(ctx, accountID)
+ switch {
+ case errors.Is(err, db.ErrNotFound):
+ if targetAccountID != "" {
+ return errors.New("待重新授权账号不存在")
+ }
+ isNew = true
+ if err := s.Store.Cookies.CreateOwned(ctx, accountID, cookies, userID); err != nil {
+ return err
+ }
+ if snapshotComplete {
+ metadata := cookierefresh.MetadataWithSnapshot("", cookieSnapshot)
+ if err := s.Store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix()); err != nil {
+ return err
+ }
+ }
+ case err != nil:
+ return err
+ case detail == nil:
+ return db.ErrNotFound
+ case detail.UserID != userID:
+ if targetAccountID != "" {
+ return errors.New("待重新授权账号不属于当前用户")
+ }
+ return db.ErrForbidden
+ default:
+ if snapshotComplete {
+ metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, cookieSnapshot)
+ if err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, cookies, metadata, time.Now().Unix()); err != nil {
+ return err
+ }
+ } else if err := s.updateFlatCookieOwnedLocked(ctx, detail, cookies); err != nil {
+ return err
+ }
+ }
+ s.markSuccessfulLogin(ctx, accountID, userID, loginMethodQRScan, "扫码登录成功")
+ if s.Store.Tokens != nil {
+ if err := s.Store.Tokens.Clear(ctx, accountID); err != nil {
+ s.Logger.Warn("扫码登录保存后清理旧连接凭证失败", "cookie_id", accountID, "err", err)
+ }
+ }
+ return nil
+ }()
if saveErr != nil {
if errors.Is(saveErr, db.ErrForbidden) {
return qrLoginPersistence{}, errors.New("该账号ID已存在且不属于当前用户")
@@ -227,10 +262,6 @@ func (s *Server) persistQRLoginSuccessFor(ctx context.Context, userID int64, ses
}
return qrLoginPersistence{}, saveErr
}
- s.markSuccessfulLogin(ctx, accountID, userID, loginMethodQRScan, "扫码登录成功")
- if s.Store.Tokens != nil {
- _ = s.Store.Tokens.Clear(ctx, accountID)
- }
if d, err := s.Store.Cookies.GetDetails(ctx, accountID); err == nil {
s.refreshAccountProfile(ctx, d)
}
@@ -307,6 +338,7 @@ func cloneQRStatus(src map[string]any) map[string]any {
func publicQRStatus(src map[string]any) map[string]any {
dst := cloneQRStatus(src)
delete(dst, "cookies")
+ delete(dst, "cookie_snapshot")
return dst
}
@@ -319,3 +351,19 @@ func qrString(result map[string]any, key string) string {
value, _ := result[key].(string)
return strings.TrimSpace(value)
}
+
+func qrCookieSnapshot(result map[string]any) ([]cookierefresh.BrowserCookie, bool) {
+ raw, ok := result["cookie_snapshot"]
+ if !ok {
+ return nil, false
+ }
+ snapshot, ok := raw.([]cookierefresh.BrowserCookie)
+ if !ok || snapshot == nil {
+ return nil, false
+ }
+ normalized := cookierefresh.NormalizeSnapshot(snapshot)
+ if normalized == nil {
+ normalized = []cookierefresh.BrowserCookie{}
+ }
+ return normalized, true
+}
diff --git a/internal/server/qrlogin_keyword_test.go b/internal/server/qrlogin_keyword_test.go
index 91e8cf1..6585910 100644
--- a/internal/server/qrlogin_keyword_test.go
+++ b/internal/server/qrlogin_keyword_test.go
@@ -11,6 +11,7 @@ import (
"time"
"xianyu-go/internal/db"
+ "xianyu-go/internal/xianyu/cookierefresh"
)
type fakeQRLoginService struct {
@@ -113,6 +114,7 @@ func TestQRLoginStatusNeverExposesCookies(t *testing.T) {
srv.Manager = nil
srv.QRLogin = &fakeQRLoginService{status: map[string]any{
"status": "success", "cookies": "unb=acc1; secret=value", "unb": "acc1",
+ "cookie_snapshot": []cookierefresh.BrowserCookie{{Name: "secret", Value: "value", Domain: ".goofish.com", Path: "/"}},
}}
ownQRSession(t, srv, store, "redacted")
h := srv.Router()
@@ -133,6 +135,9 @@ func TestQRLoginStatusNeverExposesCookies(t *testing.T) {
if _, exists := res["cookies"]; exists {
t.Fatalf("%s must redact cookies: %+v", path, res)
}
+ if _, exists := res["cookie_snapshot"]; exists {
+ t.Fatalf("%s must redact cookie snapshot: %+v", path, res)
+ }
}
}
@@ -208,7 +213,14 @@ func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) {
"status": "success",
"cookies": "unb=qr-new; _m_h5_tk=qr-token;",
"unb": "qr-new",
+ "cookie_snapshot": []cookierefresh.BrowserCookie{
+ {Name: "unb", Value: "qr-new", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "_m_h5_tk", Value: "qr-token", Domain: ".goofish.com", Path: "/", Secure: true, HTTPOnly: true},
+ },
}}
+ if snapshot, ok := qrCookieSnapshot(srv.QRLogin.GetSessionStatus("s1")); !ok || len(snapshot) != 2 {
+ t.Fatalf("测试扫码 Cookie 快照异常: ok=%v snapshot=%+v", ok, snapshot)
+ }
ownQRSession(t, srv, store, "s1")
h := srv.Router()
cookie := loginHelper(t, h)
@@ -237,6 +249,9 @@ func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) {
if d.LoginMethod != "qr_scan" || d.LastLoginAt == 0 {
t.Fatalf("扫码登录应标记登录审计字段: %+v", d)
}
+ if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(d.MetadataJSON); !ok || len(snapshot) != 2 {
+ t.Fatalf("纯 Go 扫码完整 Cookie Jar 未持久化: ok=%v snapshot=%+v metadata=%s", ok, snapshot, d.MetadataJSON)
+ }
logs, err := store.LoginLogs.ListByCookie(context.Background(), "qr-new", 10)
if err != nil || len(logs) != 1 || logs[0].Status != "success" || logs[0].Method != "qr_scan" {
t.Fatalf("重复轮询不应重复记录登录日志: logs=%#v err=%v", logs, err)
@@ -259,6 +274,7 @@ func TestCompleteQRVerificationPersistsAndReenablesAccount(t *testing.T) {
if err := store.Tokens.Save(ctx, "acc1", "did", "token", 9999999999); err != nil {
t.Fatalf("Save token: %v", err)
}
+ seedStaleCookieSnapshot(t, store, "acc1")
h := srv.Router()
cookie := loginHelper(t, h)
@@ -282,6 +298,7 @@ func TestCompleteQRVerificationPersistsAndReenablesAccount(t *testing.T) {
if !store.Cookies.GetStatus(ctx, "acc1") {
t.Fatal("扫码验证成功后应重新启用账号")
}
+ requireCookieSnapshotCleared(t, store, "acc1")
if tk, err := store.Tokens.Get(ctx, "acc1"); err != nil || tk.AccessToken != "" || tk.DeviceID != "did" {
t.Fatalf("扫码验证成功后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
}
diff --git a/internal/server/server.go b/internal/server/server.go
index a1cf555..88a6707 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -21,12 +21,12 @@ import (
"xianyu-go/internal/account"
"xianyu-go/internal/auth"
"xianyu-go/internal/automation"
- "xianyu-go/internal/browser"
"xianyu-go/internal/db"
"xianyu-go/internal/notify"
"xianyu-go/internal/webui"
"xianyu-go/internal/xianyu/mtop"
"xianyu-go/internal/xianyu/qrlogin"
+ xrenew "xianyu-go/internal/xianyu/renew"
)
type qrLoginService interface {
@@ -55,18 +55,17 @@ type publishBatchWorker struct {
// Server 聚合 HTTP 服务依赖。Automation 与 Notifier 由构造函数注入,
// 不再允许外部直接改字段,避免运行时被替换成 nil。
type Server struct {
- Store *db.Store
- Auth *auth.Service
- Manager *account.Manager
- automation *automation.Center
- Browser *browser.Manager
- PasswordLogin passwordLoginRunner
- notifier *notify.Notifier
- MTop mtop.Client
- QRLogin qrLoginService
- Logger *slog.Logger
- WebDir string // 前端静态资源目录(含 index.html)
- Addr string
+ Store *db.Store
+ Auth *auth.Service
+ Manager *account.Manager
+ automation *automation.Center
+ notifier *notify.Notifier
+ MTop mtop.Client
+ CookieRenew xrenew.Service
+ QRLogin qrLoginService
+ Logger *slog.Logger
+ WebDir string // 前端静态资源目录(含 index.html)
+ Addr string
publishMu sync.Mutex
publishCancels map[string]publishBatchWorker
@@ -76,10 +75,6 @@ type Server struct {
lifecycleMu sync.RWMutex
lifecycleCtx context.Context
- passwordMu sync.Mutex
- passwordSessions map[string]*passwordLoginSession
- passwordProcessing map[string]string
-
qrMu sync.Mutex
qrPersisted map[string]qrLoginPersistence
qrOwners map[string]qrLoginOwner
@@ -91,48 +86,33 @@ type Server struct {
// New 构造。autoCenter/notifier 由调用方完成创建后注入(创建顺序:
// adapter → manager → automation → notifier → server)。
-func New(store *db.Store, manager *account.Manager, bm *browser.Manager, secure bool, webDir, addr string, logger *slog.Logger, autoCenter *automation.Center, notifier *notify.Notifier) *Server {
+func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr string, logger *slog.Logger, autoCenter *automation.Center, notifier *notify.Notifier) *Server {
if logger == nil {
logger = slog.New(slog.NewTextHandler(os.Stdout, nil))
}
qrMgr := qrlogin.NewManager(logger)
- if bm != nil {
- qrMgr.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
- return bm.QRCookieRefresh(ctx, tmpCookies, verificationURL, onScreenshot)
- })
- }
return &Server{
- Store: store,
- Auth: &auth.Service{Store: store, Logger: logger, Secure: secure},
- Manager: manager,
- automation: autoCenter,
- Browser: bm,
- PasswordLogin: passwordLoginRunnerForBrowser(bm),
- notifier: notifier,
- MTop: mtop.NewClient(),
- QRLogin: qrMgr,
- Logger: logger,
- WebDir: webDir,
- Addr: addr,
+ Store: store,
+ Auth: &auth.Service{Store: store, Logger: logger, Secure: secure},
+ Manager: manager,
+ automation: autoCenter,
+ notifier: notifier,
+ MTop: mtop.NewClient(),
+ CookieRenew: xrenew.Service{},
+ QRLogin: qrMgr,
+ Logger: logger,
+ WebDir: webDir,
+ Addr: addr,
- publishCancels: make(map[string]publishBatchWorker),
- workersDone: closedSignal(),
- lifecycleCtx: context.Background(),
- passwordSessions: make(map[string]*passwordLoginSession),
- passwordProcessing: make(map[string]string),
- qrPersisted: make(map[string]qrLoginPersistence),
- qrOwners: make(map[string]qrLoginOwner),
- loginLimiter: newLoginFailureLimiter(),
+ publishCancels: make(map[string]publishBatchWorker),
+ workersDone: closedSignal(),
+ lifecycleCtx: context.Background(),
+ qrPersisted: make(map[string]qrLoginPersistence),
+ qrOwners: make(map[string]qrLoginOwner),
+ loginLimiter: newLoginFailureLimiter(),
}
}
-func passwordLoginRunnerForBrowser(bm *browser.Manager) passwordLoginRunner {
- if bm == nil {
- return nil
- }
- return bm
-}
-
// mtopClient 返回注入的 mtop 客户端;未注入时退回默认 HTTP 实现(保证零值可用)。
func (s *Server) mtopClient() mtop.Client {
if s.MTop != nil {
diff --git a/internal/server/server_test.go b/internal/server/server_test.go
index c91124e..963fedb 100644
--- a/internal/server/server_test.go
+++ b/internal/server/server_test.go
@@ -32,7 +32,7 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) {
store.Cookies.Save(context.Background(), "acc1", "unb=123; _m_h5_tk=tk1_1;", admin.ID)
mgr := account.NewManager(store, noopHandler{}, nil)
- srv := New(store, mgr, nil, false, "", ":0", nil, nil, nil)
+ srv := New(store, mgr, false, "", ":0", nil, nil, nil)
mtopClient := mtop.NewClient()
mtopClient.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
return &http.Response{
diff --git a/internal/webui/static/assets/icons-vendor-BhUPp6x7.js b/internal/webui/static/assets/icons-vendor-RenKjhri.js
similarity index 72%
rename from internal/webui/static/assets/icons-vendor-BhUPp6x7.js
rename to internal/webui/static/assets/icons-vendor-RenKjhri.js
index 2b2be20..20980d2 100644
--- a/internal/webui/static/assets/icons-vendor-BhUPp6x7.js
+++ b/internal/webui/static/assets/icons-vendor-RenKjhri.js
@@ -23,329 +23,339 @@ import{r as s}from"./react-vendor-DZnRGM0-.js";/**
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const m=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],L1=e("activity",m);/**
+ */const m=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],P1=e("activity",m);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const u=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],V1=e("arrow-right",u);/**
+ */const u=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],S1=e("arrow-right",u);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const w=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],P1=e("bell",w);/**
+ */const w=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],U1=e("bell",w);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const $=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],S1=e("bot",$);/**
+ */const $=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],E1=e("bot",$);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const N=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],U1=e("box",N);/**
+ */const N=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],B1=e("box",N);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const f=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],E1=e("check",f);/**
+ */const f=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],D1=e("check",f);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const b=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],B1=e("chevron-down",b);/**
+ */const b=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],R1=e("chevron-down",b);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const C=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],D1=e("chevron-left",C);/**
+ */const q=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],T1=e("chevron-left",q);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const q=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],R1=e("chevron-right",q);/**
+ */const z=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Z1=e("chevron-right",z);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const z=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],T1=e("circle-alert",z);/**
+ */const A=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],F1=e("circle-alert",A);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const A=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Z1=e("circle-check",A);/**
+ */const C=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],I1=e("circle-check",C);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const j=[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]],I1=e("circle-dashed",j);/**
+ */const H=[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]],K1=e("circle-dashed",H);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const H=[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],K1=e("clock-3",H);/**
+ */const j=[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],O1=e("clock-3",j);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const L=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],O1=e("clock",L);/**
+ */const L=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],W1=e("clock",L);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const V=[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]],W1=e("cloud-upload",V);/**
+ */const V=[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]],G1=e("cloud-upload",V);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const P=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],F1=e("code",P);/**
+ */const P=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Q1=e("code",P);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const S=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],G1=e("copy",S);/**
+ */const S=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],J1=e("copy",S);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const U=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],Q1=e("credit-card",U);/**
+ */const U=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],X1=e("credit-card",U);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const E=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],J1=e("database",E);/**
+ */const E=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Y1=e("database",E);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const B=[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]],X1=e("dollar-sign",B);/**
+ */const B=[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]],e0=e("dollar-sign",B);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const D=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Y1=e("external-link",D);/**
+ */const D=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],a0=e("external-link",D);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const R=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],e0=e("eye-off",R);/**
+ */const R=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],t0=e("eye-off",R);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const T=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],a0=e("eye",T);/**
+ */const T=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],o0=e("eye",T);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const Z=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]],t0=e("file-down",Z);/**
+ */const Z=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]],c0=e("file-down",Z);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const I=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],o0=e("file-text",I);/**
+ */const F=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],h0=e("file-text",F);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const K=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]],c0=e("gift",K);/**
+ */const I=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],s0=e("funnel",I);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const O=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],h0=e("image",O);/**
+ */const K=[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]],n0=e("gift",K);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const W=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],s0=e("key",W);/**
+ */const O=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],d0=e("image",O);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const F=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],n0=e("layers",F);/**
+ */const W=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],y0=e("key",W);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const G=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],d0=e("layout-dashboard",G);/**
+ */const G=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],k0=e("layers",G);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const Q=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],y0=e("link-2",Q);/**
+ */const Q=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],r0=e("layout-dashboard",Q);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const J=[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 19H3",key:"zzsher"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]],k0=e("list-plus",J);/**
+ */const J=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],i0=e("link-2",J);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const X=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],r0=e("loader-circle",X);/**
+ */const X=[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 19H3",key:"zzsher"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]],p0=e("list-plus",X);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const Y=[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]],i0=e("lock-keyhole",Y);/**
+ */const Y=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],l0=e("loader-circle",Y);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const e1=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],p0=e("lock",e1);/**
+ */const e1=[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]],_0=e("lock-keyhole",e1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const a1=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],l0=e("log-out",a1);/**
+ */const a1=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]],M0=e("lock",a1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const t1=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],_0=e("mail",t1);/**
+ */const t1=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],v0=e("log-out",t1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const o1=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],M0=e("message-circle",o1);/**
+ */const o1=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],x0=e("mail",o1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const c1=[["path",{d:"m16 16 2 2 4-4",key:"gfu2re"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],v0=e("package-check",c1);/**
+ */const c1=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],g0=e("message-circle",c1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const h1=[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M19 13v6",key:"85cyf1"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],x0=e("package-plus",h1);/**
+ */const h1=[["path",{d:"m16 16 2 2 4-4",key:"gfu2re"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],m0=e("package-check",h1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const s1=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],g0=e("package",s1);/**
+ */const s1=[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M19 13v6",key:"85cyf1"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]],u0=e("package-plus",s1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const n1=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],m0=e("pen",n1);/**
+ */const n1=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],w0=e("package",n1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const d1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],u0=e("plus",d1);/**
+ */const d1=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],$0=e("pen",d1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const y1=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],w0=e("power",y1);/**
+ */const y1=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],N0=e("plus",y1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const k1=[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]],$0=e("qr-code",k1);/**
+ */const k1=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],f0=e("power",k1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const r1=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],N0=e("refresh-cw",r1);/**
+ */const r1=[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]],b0=e("qr-code",r1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const i1=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],f0=e("save",i1);/**
+ */const i1=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],q0=e("refresh-cw",i1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const p1=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],b0=e("search",p1);/**
+ */const p1=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],z0=e("save",p1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const l1=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],C0=e("send",l1);/**
+ */const l1=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],A0=e("search",l1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const _1=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],q0=e("settings",_1);/**
+ */const _1=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],C0=e("send",_1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const M1=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],z0=e("shield-check",M1);/**
+ */const M1=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],H0=e("settings",M1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const v1=[["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}],["path",{d:"M3.103 6.034h17.794",key:"awc11p"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z",key:"o988cm"}]],A0=e("shopping-bag",v1);/**
+ */const v1=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],j0=e("shield-check",v1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const x1=[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]],j0=e("shopping-cart",x1);/**
+ */const x1=[["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}],["path",{d:"M3.103 6.034h17.794",key:"awc11p"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z",key:"o988cm"}]],L0=e("shopping-bag",x1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const g1=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],H0=e("sparkles",g1);/**
+ */const g1=[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]],V0=e("shopping-cart",g1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const m1=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],L0=e("square-pen",m1);/**
+ */const m1=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],P0=e("sliders-horizontal",m1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const u1=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],V0=e("trash-2",u1);/**
+ */const u1=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],S0=e("sparkles",u1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const w1=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],P0=e("trending-up",w1);/**
+ */const w1=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],U0=e("square-pen",w1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const $1=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],S0=e("triangle-alert",$1);/**
+ */const $1=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],E0=e("trash-2",$1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const N1=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]],U0=e("truck",N1);/**
+ */const N1=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],B0=e("trending-up",N1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const f1=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],E0=e("upload",f1);/**
+ */const f1=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],D0=e("triangle-alert",f1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const b1=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],B0=e("user-round",b1);/**
+ */const b1=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]],R0=e("truck",b1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const C1=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],D0=e("user",C1);/**
+ */const q1=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],T0=e("upload",q1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const q1=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],R0=e("users",q1);/**
+ */const z1=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],Z0=e("user-round",z1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const z1=[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]],T0=e("webhook",z1);/**
+ */const A1=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],F0=e("user",A1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const A1=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Z0=e("x",A1);/**
+ */const C1=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],I0=e("users",C1);/**
* @license lucide-react v0.562.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
- */const j1=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],I0=e("zap",j1);export{J1 as $,L1 as A,U1 as B,Q1 as C,X1 as D,Y1 as E,G1 as F,o0 as G,k0 as H,h0 as I,t0 as J,s0 as K,d0 as L,F1 as M,x0 as N,W1 as O,g0 as P,$0 as Q,N0 as R,A0 as S,P0 as T,R0 as U,Z1 as V,I1 as W,Z0 as X,y0 as Y,I0 as Z,V1 as _,P1 as a,B1 as a0,z0 as a1,i0 as a2,B0 as a3,M0 as a4,K1 as a5,c0 as a6,n0 as a7,C0 as a8,_0 as a9,T0 as aa,p0 as ab,q0 as b,H0 as c,l0 as d,T1 as e,j0 as f,v0 as g,S0 as h,r0 as i,D0 as j,E1 as k,S1 as l,O1 as m,m0 as n,w0 as o,V0 as p,e0 as q,a0 as r,f0 as s,u0 as t,U0 as u,b0 as v,L0 as w,D1 as x,R1 as y,E0 as z};
+ */const H1=[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]],K0=e("webhook",H1);/**
+ * @license lucide-react v0.562.0 - ISC
+ *
+ * This source code is licensed under the ISC license.
+ * See the LICENSE file in the root directory of this source tree.
+ */const j1=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],O0=e("x",j1);/**
+ * @license lucide-react v0.562.0 - ISC
+ *
+ * This source code is licensed under the ISC license.
+ * See the LICENSE file in the root directory of this source tree.
+ */const L1=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],W0=e("zap",L1);export{i0 as $,P1 as A,B1 as B,X1 as C,e0 as D,a0 as E,P0 as F,J1 as G,h0 as H,d0 as I,p0 as J,y0 as K,r0 as L,c0 as M,Q1 as N,s0 as O,w0 as P,b0 as Q,q0 as R,L0 as S,B0 as T,I0 as U,u0 as V,G1 as W,O0 as X,I1 as Y,W0 as Z,K1 as _,U1 as a,S1 as a0,Y1 as a1,R1 as a2,j0 as a3,_0 as a4,Z0 as a5,g0 as a6,O1 as a7,n0 as a8,k0 as a9,C0 as aa,x0 as ab,K0 as ac,M0 as ad,H0 as b,S0 as c,v0 as d,F1 as e,V0 as f,m0 as g,D0 as h,l0 as i,F0 as j,D1 as k,E1 as l,W1 as m,$0 as n,f0 as o,E0 as p,t0 as q,o0 as r,z0 as s,N0 as t,R0 as u,A0 as v,U0 as w,T1 as x,Z1 as y,T0 as z};
diff --git a/internal/webui/static/assets/index-2Xnmtmdh.js b/internal/webui/static/assets/index-2Xnmtmdh.js
deleted file mode 100644
index 9b4b10a..0000000
--- a/internal/webui/static/assets/index-2Xnmtmdh.js
+++ /dev/null
@@ -1,19 +0,0 @@
-import{j as e,r as n,b as ke,c as Qt,d as Kt}from"./react-vendor-DZnRGM0-.js";import{L as Yt,U as wt,S as kt,C as Fs,B as Ct,Z as Ts,a as is,b as zs,c as St,d as Xt,e as os,A as Xs,D as Zt,f as Zs,P as At,g as gs,E as It,T as Ht,h as ea,i as Le,Q as Ss,j as Os,k as We,l as rs,m as Hs,R as qe,n as Rt,o as sa,p as Ve,X as Ne,K as ta,q as ns,r as es,s as Je,t as Ge,u as et,v as aa,w as cs,x as la,y as ra,z as hs,F as na,G as st,I as tt,H as ia,J as oa,M as ca,N as As,O as ys,V as $t,W as da,Y as xa,_ as qs,$ as ma,a0 as ua,a1 as Ms,a2 as at,a3 as pa,a4 as _s,a5 as Lt,a6 as ha,a7 as ga,a8 as Us,a9 as Pt,aa as ba,ab as ya}from"./icons-vendor-BhUPp6x7.js";import{R as fs,B as fa,X as lt,Y as rt,T as Is,a as ja,C as Rs,A as Na,b as va,c as _a,P as nt,d as it,L as wa}from"./charts-vendor-B_BfwiL0.js";import"./vendor-w5t2K9ux.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const u of document.querySelectorAll('link[rel="modulepreload"]'))d(u);new MutationObserver(u=>{for(const b of u)if(b.type==="childList")for(const k of b.addedNodes)k.tagName==="LINK"&&k.rel==="modulepreload"&&d(k)}).observe(document,{childList:!0,subtree:!0});function l(u){const b={};return u.integrity&&(b.integrity=u.integrity),u.referrerPolicy&&(b.referrerPolicy=u.referrerPolicy),u.crossOrigin==="use-credentials"?b.credentials="include":u.crossOrigin==="anonymous"?b.credentials="omit":b.credentials="same-origin",b}function d(u){if(u.ep)return;u.ep=!0;const b=l(u);fetch(u.href,b)}})();const ka=({activeTab:s,isAdmin:t=!1,onNavigate:l,onLogout:d})=>{const u=[{id:"dashboard",icon:Yt,label:"仪表盘"},{id:"accounts",icon:wt,label:"账号管理"},{id:"orders",icon:kt,label:"订单管理"},{id:"cards",icon:Fs,label:"卡密库存"},{id:"items",icon:Ct,label:"商品列表"},{id:"rules",icon:Ts,label:"自动化规则"},{id:"notifications",icon:is,label:"通知设置"},...t?[{id:"settings",icon:zs,label:"系统与AI"}]:[]];return e.jsxs("div",{className:"w-64 h-screen fixed left-0 top-0 bg-white border-r border-gray-100 flex flex-col justify-between z-20 shadow-[4px_0_24px_rgba(0,0,0,0.02)]",children:[e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-12 px-2",children:[e.jsx("div",{className:"w-10 h-10 bg-[#0094f7] squircle flex items-center justify-center shrink-0 p-1.5",style:{filter:"drop-shadow(0 4px 12px rgba(0,148,247,0.25))"},children:e.jsx("img",{src:"/static/ydisks-logo.svg",alt:"Ydisks",className:"w-full h-full"})}),e.jsxs("h1",{className:"text-xl font-extrabold tracking-tight text-gray-900",children:["Ydisks闲鱼助手 ",e.jsx("span",{className:"text-xs bg-[#0094f7] text-white px-1.5 py-0.5 rounded ml-1",children:"PRO"})]})]}),e.jsx("nav",{className:"space-y-2",children:u.map(b=>{const k=b.icon,O=s===b.id;return e.jsxs("button",{onClick:()=>l(b.id),className:`w-full flex items-center gap-3 px-4 py-3.5 rounded-2xl transition-all duration-300 group relative overflow-hidden ${O?"bg-[#0094f7] text-white font-bold shadow-lg shadow-blue-100 transform scale-[1.02]":"text-gray-500 hover:bg-gray-50 hover:text-gray-900"}`,children:[e.jsx(k,{className:`w-5 h-5 transition-colors ${O?"text-white":"text-gray-400 group-hover:text-gray-600"}`}),e.jsx("span",{className:"text-sm tracking-wide",children:b.label}),O&&e.jsx(St,{className:"w-4 h-4 absolute right-3 text-white/30 animate-pulse"})]},b.id)})})]}),e.jsx("div",{className:"p-6 border-t border-gray-50",children:e.jsxs("button",{onClick:d,className:"w-full flex items-center gap-3 px-4 py-3 text-gray-500 hover:text-red-500 hover:bg-red-50 rounded-2xl transition-all duration-200 font-medium",children:[e.jsx(Xt,{className:"w-5 h-5"}),e.jsx("span",{className:"text-sm",children:"退出登录"})]})})]})},Ca=3e4,Sa=10*6e4;let $s=!1;const Et=()=>{$s||typeof window>"u"||($s=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{$s=!1}))},Aa=s=>{if(!s)return"";const t=new URLSearchParams;for(const[d,u]of Object.entries(s))u!=null&&t.set(d,String(u));const l=t.toString();return l?`?${l}`:""},Cs=async(s,t,l={})=>{var R;const d=Aa(l.params),u=`${t}${d}`,b=Dt(l.signal,l.timeoutMs??Ca);let k;try{k=await fetch(u,{method:s,credentials:"include",signal:b.signal,headers:{...l.body===void 0?{}:{"Content-Type":"application/json"}},body:l.body===void 0?void 0:JSON.stringify(l.body)})}catch(f){throw b.signal.aborted?new Error((R=l.signal)!=null&&R.aborted?"请求已取消":"请求超时,请稍后重试"):f}finally{b.cleanup()}const p=(k.headers.get("content-type")||"").includes("application/json");if(!k.ok){k.status===401&&!l.skipAuthLogout&&Et();const f=p?await k.json().catch(()=>{}):await k.text().catch(()=>{}),Q=typeof f=="string"?f:(f==null?void 0:f.detail)||(f==null?void 0:f.message)||(f==null?void 0:f.msg);throw new Error(Q||`请求失败: ${k.status}`)}return p?await k.json():await k.text()},ge=async(s,t,l)=>Cs("GET",s,{params:t,...l}),pe=async(s,t,l)=>Cs("POST",s,{body:t,...l}),Ee=async(s,t,l)=>Cs("PUT",s,{body:t,...l}),Me=async(s,t,l)=>Cs("DELETE",s,{params:t,...l}),bs=async(s,t,l={})=>{var p;const d=Dt(l.signal,l.timeoutMs??Sa);let u;try{u=await fetch(s,{method:"POST",credentials:"include",signal:d.signal,body:t})}catch(R){throw d.signal.aborted?new Error((p=l.signal)!=null&&p.aborted?"请求已取消":"上传超时,请稍后重试"):R}finally{d.cleanup()}const O=(u.headers.get("content-type")||"").includes("application/json")?await u.json().catch(()=>{}):await u.text().catch(()=>{});if(!u.ok){u.status===401&&Et();const R=typeof O=="string"?O:(O==null?void 0:O.detail)||(O==null?void 0:O.message)||(O==null?void 0:O.msg),f=new Error(R||"请求失败: "+u.status);throw f.payload=O,f}return O},Dt=(s,t)=>{const l=new AbortController,d=()=>l.abort(s==null?void 0:s.reason);s!=null&&s.aborted?d():s==null||s.addEventListener("abort",d,{once:!0});const u=globalThis.setTimeout(()=>l.abort(new DOMException("timeout","TimeoutError")),Math.max(1,t));return{signal:l.signal,cleanup:()=>{globalThis.clearTimeout(u),s==null||s.removeEventListener("abort",d)}}},ws=s=>{const t=s.getFullYear(),l=String(s.getMonth()+1).padStart(2,"0"),d=String(s.getDate()).padStart(2,"0");return`${t}-${l}-${d}`},Ws=(s,t)=>{const l=new Date(s);return l.setHours(12,0,0,0),l.setDate(l.getDate()+t),l},Bs=(s,t)=>({startDate:ws(Ws(s,-(t-1))),endDate:ws(s)}),ot=(s,t=new Date,l="",d="")=>{if(s==="custom"&&l&&d){if(l>d)throw new Error("开始日期不能晚于结束日期");return{startDate:l,endDate:d}}return s==="yesterday"?Bs(Ws(t,-1),1):Bs(t,s==="3days"?3:s==="30days"?30:s==="today"?1:7)},Ia=s=>{const t=new Date(`${s.startDate}T12:00:00`),l=new Date(`${s.endDate}T12:00:00`),d=Math.round((l.getTime()-t.getTime())/864e5)+1,u=Ws(t,-1);return Bs(u,d)},Ra=s=>{const t={...s};if("renewal_log_retention_days"in t){const l=Number(t.renewal_log_retention_days);t.renewal_log_retention_days=Number.isFinite(l)?l:10}return t},$a=async s=>pe("/login",s,{skipAuthLogout:!0}),Ft=async()=>ge("/verify"),La=async()=>pe("/logout",{}),Pa=async s=>Ee("/account/credentials",s),Ea=(s,t)=>{const l=s.avatar_url||"";if(!l)return"";try{const d=new URL(l,window.location.origin);return d.hostname.endsWith("alicdn.com")&&d.searchParams.set("_v",t),d.toString()}catch{return l}},Vs=async s=>{const t=await ge("/cookies/details",void 0,s),l=Date.now().toString();return t.map(d=>({id:d.id,value:"",cookie:"",enabled:d.enabled,auto_confirm:d.auto_confirm,remark:d.remark,note:d.remark,pause_duration:d.pause_duration,paused_until:Number(d.paused_until||0),paused:d.paused===!0,username:d.username||"",login_password:"",show_browser:d.show_browser===!0||d.show_browser===1||d.show_browser==="1"||d.show_browser==="true",nickname:d.nickname||d.remark||`账号 ${d.id.substring(0,6)}`,avatar_url:Ea(d,l),profile_error:d.profile_error||"",ai_enabled:!1}))},Da=async s=>ge("/cookies/runtime-status",void 0,s),Fa=async s=>pe("/qr-login/generate",void 0,s),Ta=async(s,t)=>ge(`/qr-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),Oa=async(s,t)=>pe(`/qr-login/complete-verification/${s}`,{target_account_id:t||""}),qa=async(s,t)=>Ee(`/cookies/${s}/status`,{enabled:t}),Ma=async s=>Me(`/cookies/${s}`),Ba=async(s,t)=>Ee(`/cookies/${s}/pause-duration`,{pause_duration:t}),za=async(s,t)=>Ee(`/cookies/${s}/settings`,t),Ua=async s=>pe("/password-login",s),Wa=async(s,t)=>ge(`/password-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),Va=async s=>Me(`/password-login/cancel/${s}`),Ga=async s=>pe(`/cookies/${s}/refresh-profile`,{}),Ja=async s=>ge("/ai-reply-settings",void 0,s),Tt=s=>{const t=String(s||"");return t==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(t)?t:"unknown"},Qa=async(s,t,l=1,d=20,u)=>{const b={page:l,page_size:d};t&&t!=="all"&&(b.status=t),u!=null&&u.trim()&&(b.search=u.trim());const k=await ge("/api/orders",b),p=(k.orders||k.data||[]).map(R=>({...R,id:R.id||R.order_id,status:Tt(R.status||R.order_status),quantity:Number(R.quantity||1)}));return{success:!0,data:p,total:k.total||p.length,page:k.page||l,page_size:k.page_size||d,total_pages:k.total_pages||1}},Ka=async(s,t)=>Ee(`/api/orders/${s}`,t),Ya=async s=>Me(`/api/orders/${s}`),Xa=async(s,t)=>{const l=new FormData;return bs("/api/orders/refresh",l)},Za=async s=>pe(`/api/orders/${s}/refresh`),Ha=async(s,t)=>pe("/api/orders/manual-ship",{order_ids:s,ship_mode:t}),el=async s=>s instanceof FormData?bs("/api/orders/import",s):pe("/api/orders/import",s),sl=async()=>ge("/dashboard/stats"),ct=async(s=7)=>{let t;if(typeof s=="number"){const l=new Date,d=new Date;d.setDate(d.getDate()-s),t={start_date:ws(d),end_date:ws(l)}}else t=s;return ge("/analytics/orders",{...t,timezone_offset_minutes:-new Date().getTimezoneOffset()})},tl=async s=>{const t=await ge("/analytics/orders/valid",{start_date:s.start_date,end_date:s.end_date,timezone_offset_minutes:-new Date().getTimezoneOffset()}),d=(Array.isArray(t)?t:t.orders||[]).map(u=>({...u,id:u.id||u.order_id,status:Tt(u.status||u.order_status),quantity:Number(u.quantity||1)}));return{orders:d,total:Array.isArray(t)?d.length:Number(t.total??d.length),truncated:Array.isArray(t)?!1:t.truncated===!0}},al=s=>{let t=s.api_config;if(typeof t=="string"&&t.trim())try{t=JSON.parse(t)}catch{t=void 0}return{...s,api_config:t||void 0}},Ot=s=>({...s,api_config:s.api_config?JSON.stringify(s.api_config):""}),Ue=async()=>{const s=await ge("/cards");return(Array.isArray(s)?s:s.cards||[]).map(al)},ll=async s=>pe("/cards",Ot(s)),dt=async(s,t)=>Ee(`/cards/${s}`,Ot(t)),rl=async s=>Me(`/cards/${s}`),nl=async s=>{const t=new FormData;return t.append("file",s),bs("/cards/batch",t)},il=async(s,t)=>pe(`/cards/${s}/append-data`,{content:t}),Ls=s=>s===!0||s===1||s==="1",ds=async()=>{const s=await ge("/items");return(Array.isArray(s)?s:s.items||[]).map(l=>({...l,id:l.id||`${l.cookie_id}-${l.item_id}`,is_multi_spec:Ls(l.is_multi_spec),is_multi_qty_ship:Ls(l.is_multi_qty_ship??l.multi_quantity_delivery),multi_quantity_delivery:Ls(l.multi_quantity_delivery??l.is_multi_qty_ship)}))},ol=async s=>pe("/items/get-all-from-account",{cookie_id:s}),cl=async(s,t)=>Me(`/items/${s}/${t}`),dl=async(s,t)=>pe(`/items/${s}`,t),xl=async s=>{const t=new FormData;t.set("cookie_id",s.cookie_id),t.set("title",s.title),t.set("description",s.description),t.set("price",s.price),t.set("original_price",s.original_price||""),t.set("quantity",String(s.quantity)),t.set("postage_mode",s.postage_mode),t.set("postage",s.postage||"");for(const l of s.images)t.append("images",l);return bs("/items/publish",t)},ml=async s=>{const t=new FormData;return t.set("file",s.file),s.imagesZip&&t.set("images_zip",s.imagesZip),s.defaultCookieId&&t.set("default_cookie_id",s.defaultCookieId),bs("/items/publish-batches/preview",t)},ul=async s=>pe("/items/publish-batches",{preview_id:s}),as=async s=>ge(`/items/publish-batches/${s}`),xt=async(s=20)=>{const t=await ge("/items/publish-batches",{limit:s});return Array.isArray(t)?t:t.batches||[]},pl=async s=>Me(`/items/publish-batches/${s}`),hl=async s=>pe(`/items/publish-batches/${s}/cancel`,{}),gl=async s=>pe(`/items/publish-batches/${s}/retry-failed`,{}),bl=async(s,t,l)=>Ee(`/items/${s}/${t}`,l),ks=async()=>{const s=await ge("/automation-rules");return(Array.isArray(s)?s:s.data||s.rules||[]).map(l=>{var d,u;return{id:String(l.id),name:l.name||"",trigger_type:l.trigger_type||"order_paid",item_keyword:l.item_title||l.item_id||"",cookie_id:l.cookie_id||"",item_id:l.item_id||"",item_title:l.item_title||"",card_group_id:Number(((d=(l.actions||[]).find(b=>b.action_type==="send_card"))==null?void 0:d.card_id)||0),card_group_name:((u=(l.actions||[]).find(b=>b.action_type==="send_card"))==null?void 0:u.card_name)||"",priority:l.priority||100,enabled:l.enabled||!1,config_json:l.config_json||"{}",actions:(l.actions||[]).map(b=>({id:b.id?String(b.id):void 0,action_type:b.action_type,card_id:Number(b.card_id||0),card_name:b.card_name||"",delivery_count:Number(b.delivery_count||1),message_template:b.message_template||"",delay_seconds:Number(b.delay_seconds||0),config_json:b.config_json||"{}",enabled:b.enabled!==!1,sort_order:Number(b.sort_order||0)})),variants:(l.actions||[]).filter(b=>b.action_type==="send_card").map(b=>{let k={};try{k=JSON.parse(b.config_json||"{}")}catch{}return{id:b.id?String(b.id):void 0,spec_name:k.spec_name||"",spec_value:k.spec_value||"",card_id:Number(b.card_id||0),card_name:b.card_name||"",delivery_count:Number(b.delivery_count||1),enabled:b.enabled!==!1,delay_override:k.delay_override===!0,delay_seconds:Number(b.delay_seconds||0),config_json:b.config_json||"{}"}})}})},yl=(s,t)=>{if(s!=="order_paid")return t.map((u,b)=>({...u,sort_order:u.sort_order||b+1}));const l=t.filter(u=>u.action_type==="send_card").map((u,b)=>({...u,sort_order:b+1})),d=t.filter(u=>u.action_type!=="send_card"&&u.action_type!=="confirm_shipment");return[...l,...d.map((u,b)=>({...u,sort_order:l.length+b+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:l.length+d.length+1}]},mt=async s=>{const t=s.trigger_type||"order_paid",d=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[t]||"自动化规则",s.item_title||s.item_id||s.cookie_id||""].filter(Boolean).join(" - "),u=(s.actions||[]).filter(p=>p.action_type!=="send_card"&&p.action_type!=="confirm_shipment"),b=s.variants&&s.variants.length>0?[...s.variants.map((p,R)=>({action_type:"send_card",card_id:p.card_id,delivery_count:p.delivery_count||1,enabled:p.enabled!==!1,sort_order:R+1,delay_seconds:p.delay_seconds||0,config_json:JSON.stringify({spec_name:p.spec_name||"",spec_value:p.spec_value||"",delay_override:p.delay_override===!0})})),...u]:s.actions&&s.actions.length>0?s.actions:[{action_type:"send_card",card_id:s.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],k=yl(t,b),O={cookie_id:s.cookie_id||"",item_id:s.item_id||"",name:(s.name||"").trim()||d||"自动化规则",trigger_type:t,enabled:s.enabled??!0,priority:s.priority||100,config_json:s.config_json||"{}",actions:k.map((p,R)=>({action_type:p.action_type,card_id:p.card_id||0,delivery_count:p.delivery_count||1,message_template:p.message_template||"",delay_seconds:p.delay_seconds||0,config_json:p.config_json||"{}",enabled:p.enabled!==!1,sort_order:p.sort_order||R+1}))};return s.id?Ee(`/automation-rules/${s.id}`,O):pe("/automation-rules",O)},fl=async s=>Me(`/automation-rules/${s}`),jl=async()=>{const s=await ge("/automation-issues");return{runs:Array.isArray(s==null?void 0:s.runs)?s.runs:[],pending_tasks:Array.isArray(s==null?void 0:s.pending_tasks)?s.pending_tasks:[]}},Nl=async(s,t)=>pe(`/automation-runs/${s}/resolve`,{resolution:t}),vl=async(s,t)=>pe(`/automation-pending-tasks/${s}/resolve`,{resolution:t}),_l=s=>({id:String((s==null?void 0:s.id)||""),keyword:(s==null?void 0:s.keyword)||"",reply:(s==null?void 0:s.reply)||"",item_id:(s==null?void 0:s.item_id)||"",type:(s==null?void 0:s.type)==="image"?"image":"text",image_url:(s==null?void 0:s.image_url)||""}),wl=async s=>{const t=await ge(`/keywords-with-type/${s}`);return Array.isArray(t)?t.map(_l):[]},kl=async s=>s?(await wl(s)).map(l=>({id:l.id,keyword:l.keyword||"",reply_content:l.reply||"",match_type:"fuzzy",enabled:!0,item_id:l.item_id||"",type:l.type==="image"?"image":"text",image_url:l.image_url||""})):[],Cl=async(s,t)=>{const l=s.type||"text",d={keyword:s.keyword||"",reply:l==="text"&&s.reply_content||"",item_id:s.item_id||"",type:l,image_url:l==="image"&&s.image_url||""};return s.id?Ee(`/keywords-with-type/${t}/${s.id}`,d):pe(`/keywords-with-item-id/${t}`,d)},Sl=async(s,t)=>Me(`/keywords-with-type/${t}/${s}`),qt=async()=>{const s=await ge("/system-settings");return Ra(s.data||s)},Mt=async s=>{const t=Object.fromEntries(Object.entries(s).filter(([,l])=>l!=null));return Ee("/system-settings",t)},Al=async(s,t)=>ge(`/ai-reply-settings/${s}`,void 0,t),Il=async(s,t)=>{const l={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return Ee(`/ai-reply-settings/${s}`,l)},Rl=async(s,t="")=>(await pe("/ai-models",{base_url:s,api_key:t})).models||[],$l=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},Bt=s=>{const t=Array.from(new Set((s||[]).filter(Boolean)));return t.length>0?JSON.stringify(t):""},zt=async s=>({success:!0,data:(await ge("/notification-channels",void 0,s)||[]).map(d=>{let u;try{u=typeof d.config=="string"?JSON.parse(d.config):d.config}catch{u={}}return{id:String(d.id),name:d.name,type:d.type==="ding_talk"?"dingtalk":d.type==="lark"?"feishu":d.type,config:u,event_types:$l(d.event_types),enabled:d.enabled,created_at:d.created_at,updated_at:d.updated_at}})}),Ll=async s=>pe("/notification-channels",{...s,config:JSON.stringify(s.config),event_types:Bt(s.event_types)}),ut=async(s,t)=>{const l={...t};return"config"in t&&(l.config=JSON.stringify(t.config)),"event_types"in t&&(l.event_types=Bt(t.event_types)),Ee(`/notification-channels/${s}`,l)},Pl=async s=>Me(`/notification-channels/${s}`),El=async(s,t)=>{const l=await ge(`/message-notifications/${s}`,void 0,t);return(l==null?void 0:l.channel_ids)||[]},Dl=async s=>pe(`/notification-channels/${s}/test`,{}),pt=async()=>ge("/api/default-replies"),Fl=async s=>{const t=await ge(`/api/default-reply/${s}`);return{cookie_id:s,enabled:t.enabled||!1,reply_content:t.reply_content||"",reply_once:t.reply_once||!1,reply_image_url:t.reply_image_url||""}},Tl=async(s,t)=>Ee(`/api/default-reply/${s}`,{enabled:t.enabled??!1,reply_content:t.reply_content||"",reply_once:t.reply_once??!1,reply_image_url:t.reply_image_url||""}),Ol=async s=>Me(`/api/default-reply/${s}`),ql=async s=>pe(`/api/default-reply/${s}/clear-records`,{}),Ml=({status:s})=>{const t={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:l[s]||s})},js=({title:s,value:t,icon:l,colorClass:d,trend:u})=>e.jsxs("div",{className:"ios-card p-6 rounded-xl flex flex-col justify-between hover:translate-y-[-4px] transition-all duration-300 h-full relative overflow-hidden group border-0",children:[e.jsx("div",{className:`absolute -right-6 -top-6 w-32 h-32 ${d} opacity-10 rounded-full group-hover:scale-125 transition-transform duration-500 blur-2xl`}),e.jsxs("div",{className:"flex justify-between items-start mb-6",children:[e.jsx("div",{className:`p-4 rounded-2xl ${d} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(l,{className:`w-6 h-6 ${d.replace("bg-","text-")}`})}),u&&e.jsxs("span",{className:"text-xs font-bold text-white bg-[#0094f7] px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm",children:[e.jsx(Ht,{className:"w-3 h-3"})," ",u]})]}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("h3",{className:"text-3xl font-extrabold text-gray-900 tracking-tight font-feature-settings-tnum",children:t}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:s})]})]}),Ps=()=>{var ie,H;const[s,t]=n.useState(null),[l,d]=n.useState(null),[u,b]=n.useState(""),[k,O]=n.useState("7days"),[p,R]=n.useState(""),[f,Q]=n.useState(""),[se,U]=n.useState(null),[J,S]=n.useState(""),[K,de]=n.useState([]),[le,ne]=n.useState(0),[q,B]=n.useState(!1),[D,Z]=n.useState(!1),[W,A]=n.useState([]),[Y,L]=n.useState({}),te=n.useRef(0),T=["#0094f7","#3B82F6","#10B981","#F59E0B","#8B5CF6"],h=async c=>{let C;try{C=ot(c,new Date,p,f)}catch(fe){b(fe instanceof Error?fe.message:"日期范围无效");return}const{startDate:oe,endDate:be}=C,ye={start_date:oe,end_date:be},Se=Ia(C),ve=++te.current;Z(!0),b("");try{const[fe,De,ue]=await Promise.all([ct(ye),ct({start_date:Se.startDate,end_date:Se.endDate}),tl(ye)]);if(ve!==te.current)return;d(fe),U(De),de(ue.orders),ne(ue.total),B(ue.truncated)}catch(fe){ve===te.current&&b(fe instanceof Error?fe.message:"经营数据加载失败")}finally{ve===te.current&&Z(!1)}},$=()=>{if(!l||!se)return null;const c=l.revenue_stats.total_amount,C=se.revenue_stats.total_amount;if(C===0)return c>0?"+100%":"0%";const oe=(c-C)/C*100;return`${oe>=0?"+":""}${oe.toFixed(1)}%`};if(n.useEffect(()=>{let c=!1;return Promise.all([sl(),ds()]).then(([C,oe])=>{if(c)return;t(C),A(oe);const be={};oe.forEach(ye=>{be[ye.item_id]=ye.item_title||ye.item_id}),L(be)}).catch(C=>{c||b(C instanceof Error?C.message:"概览加载失败")}),()=>{c=!0}},[]),n.useEffect(()=>{k!=="custom"&&h(k)},[k]),u&&(!s||!l))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(os,{className:"w-8 h-8"}),e.jsx("span",{children:u}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:()=>window.location.reload(),children:"重新加载"})]});if(!s||!l)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx(Xs,{className:"w-8 h-8 animate-spin text-[#0094f7]"})});const z=((ie=l.daily_stats)==null?void 0:ie.map(c=>({name:c.date.slice(5),amount:c.amount,orders:c.order_count,avgAmount:c.order_count>0?(c.amount/c.order_count).toFixed(2):0})))||[],X=l.item_stats||[],m=l.revenue_stats.total_orders||0,_=l.revenue_stats.total_amount||0,N=X.length>0?X.map(c=>({name:(Y[c.item_id]||c.item_id).length>12?(Y[c.item_id]||c.item_id).substring(0,12)+"...":Y[c.item_id]||c.item_id,sales:c.order_count})).sort((c,C)=>C.sales-c.sales).slice(0,10):[],y=Math.max(...N.map(c=>c.sales),1),P=X.length>0?X.map(c=>({name:(Y[c.item_id]||c.item_id).length>10?(Y[c.item_id]||c.item_id).substring(0,10)+"...":Y[c.item_id]||c.item_id,value:c.order_count,percent:m>0?c.order_count/m*100:0})).sort((c,C)=>C.value-c.value).slice(0,6).map((c,C)=>({...c,color:T[C%T.length]})):[],M=X.length>0?X.map(c=>({name:(Y[c.item_id]||c.item_id).length>12?(Y[c.item_id]||c.item_id).substring(0,12)+"...":Y[c.item_id]||c.item_id,value:c.total_amount,orderCount:c.order_count,percentage:_>0?c.total_amount/_*100:0})).sort((c,C)=>C.value-c.value).slice(0,5).map((c,C)=>({...c,color:T[C%T.length],percentage:c.percentage.toFixed(1)})):[],i=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}],E=((H=i.find(c=>c.key===k))==null?void 0:H.label)||"所选范围";let w;try{w=ot(k,new Date,p,f)}catch{w={startDate:p,endDate:f}}const G=J.trim().toLowerCase(),me=K.filter(c=>{var C,oe,be,ye;return((C=c.order_id)==null?void 0:C.toLowerCase().includes(G))||((oe=c.item_id)==null?void 0:oe.toLowerCase().includes(G))||((be=c.item_title)==null?void 0:be.toLowerCase().includes(G))||((ye=c.buyer_id)==null?void 0:ye.toLowerCase().includes(G))});return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"运营概览"}),e.jsx("p",{className:"text-gray-500 mt-2 text-base",children:"欢迎回来,以下是闲鱼店铺的实时经营数据。"})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"text-sm font-bold text-gray-700 bg-white px-5 py-2.5 rounded-full shadow-sm border border-gray-100 flex items-center gap-2",children:[e.jsx("span",{className:"w-2.5 h-2.5 bg-green-500 rounded-full animate-pulse"}),"系统正常运行"]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[i.map(c=>e.jsx("button",{onClick:()=>O(c.key),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${k===c.key?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:c.label},c.key)),k==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:p,onChange:c=>R(c.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-[#0094f7]"}),e.jsx("span",{className:"self-center text-gray-400",children:"-"}),e.jsx("input",{type:"date",value:f,onChange:c=>Q(c.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-[#0094f7]"}),e.jsx("button",{onClick:()=>{try{b(""),h("custom")}catch(c){b(c instanceof Error?c.message:"日期范围无效")}},className:"px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors",children:"应用"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6",children:[e.jsx(js,{title:"累计营收 (CNY)",value:`¥${l.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:Zt,colorClass:"bg-blue-400",trend:$()||void 0}),e.jsx(js,{title:"活跃账号 / 总数",value:`${s.active_cookies} / ${s.total_cookies}`,icon:wt,colorClass:"bg-blue-500"}),e.jsx(js,{title:"订单数",value:l.revenue_stats.total_orders.toLocaleString(),icon:Zs,colorClass:"bg-blue-500"}),e.jsx(js,{title:"库存卡密余量",value:s.available_card_stock,icon:At,colorClass:"bg-purple-500"})]}),e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[E,"的销售额走势"]})]}),e.jsx("div",{className:"h-[350px] w-full",children:z.length===0||l.revenue_stats.total_amount===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(Zs,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):z.length<=2?e.jsx(fs,{width:"100%",height:"100%",children:e.jsxs(fa,{data:z,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(lt,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:"#374151",fontSize:14,fontWeight:600},dy:10}),e.jsx(rt,{axisLine:!1,tickLine:!1,tick:{fill:"#9CA3AF",fontSize:13,fontWeight:500},tickFormatter:c=>`¥${c}`}),e.jsx(Is,{contentStyle:{backgroundColor:"#fff",borderRadius:"8px",border:"1px solid #e5e7eb",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.1)",padding:"12px 16px"},labelStyle:{color:"#6b7280",fontWeight:500},itemStyle:{color:"#0094f7",fontWeight:600},cursor:{fill:"rgba(0, 148, 247, 0.08)"},formatter:c=>[`¥${Number(c).toFixed(2)}`,"营收"]}),e.jsx(ja,{dataKey:"amount",fill:"#0094f7",maxBarSize:72,radius:[12,12,0,0],stroke:"#000000",strokeWidth:0,children:z.map((c,C)=>e.jsx(Rs,{fill:["#0094f7","#FCD34D","#0071e3"][C%3]},`cell-${C}`))})]})}):e.jsx(fs,{width:"100%",height:"100%",children:e.jsxs(Na,{data:z,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"#0094f7",stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:"#0094f7",stopOpacity:0})]})}),e.jsx(lt,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:"#9CA3AF",fontSize:13,fontWeight:500},dy:15}),e.jsx(rt,{axisLine:!1,tickLine:!1,tick:{fill:"#9CA3AF",fontSize:13,fontWeight:500}}),e.jsx(va,{vertical:!1,stroke:"#F3F4F6",strokeDasharray:"3 3"}),e.jsx(Is,{contentStyle:{backgroundColor:"#fff",borderRadius:"8px",border:"1px solid #e5e7eb",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.1)",padding:"12px 16px"},labelStyle:{color:"#6b7280",fontWeight:500},itemStyle:{color:"#0094f7",fontWeight:600},cursor:{stroke:"#0094f7",strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(_a,{type:"monotone",dataKey:"amount",stroke:"#0094f7",strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:"#fff",stroke:"#0094f7",strokeWidth:2}})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品销量排行"}),e.jsx("div",{className:"h-[280px]",children:N.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsx("div",{className:"h-full space-y-4 overflow-y-auto pr-2",children:N.map((c,C)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:`w-7 h-7 rounded-xl flex items-center justify-center text-xs font-extrabold ${C<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:C+1}),e.jsx("span",{className:"font-bold text-gray-800 text-sm truncate",children:c.name})]}),e.jsxs("span",{className:"font-mono text-sm font-extrabold text-gray-900",children:[c.sales," 单"]})]}),e.jsx("div",{className:"h-3 rounded-full bg-gray-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-[#0094f7]",style:{width:`${Math.max(8,c.sales/y*100)}%`}})})]},`${c.name}-${C}`))})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品下单占比"}),e.jsx("div",{className:"h-[280px]",children:P.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsx(fs,{width:"100%",height:"100%",children:e.jsxs(nt,{children:[e.jsx(it,{data:P,cx:"50%",cy:"50%",innerRadius:60,outerRadius:90,paddingAngle:2,dataKey:"value",label:({name:c,payload:C})=>`${c} ${Number((C==null?void 0:C.percent)||0).toFixed(1)}%`,labelLine:!1,children:P.map((c,C)=>e.jsx(Rs,{fill:c.color},`cell-${C}`))}),e.jsx(wa,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:c=>e.jsx("span",{style:{color:"#6B7280",fontWeight:500},children:c})})]})})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2 ios-card p-0 rounded-xl border-0 bg-white overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"p-6 border-b border-gray-50 flex justify-between items-center bg-[#FAFAFA]",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900",children:"参与统计的订单"}),q&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",K.length," / ",le," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:J,onChange:c=>S(c.target.value),className:"pl-4 pr-4 py-2 rounded-xl bg-white border border-gray-100 text-sm focus:border-blue-400 outline-none w-48",type:"text"})})]}),e.jsx("div",{className:"overflow-x-auto flex-1 max-h-[400px]",children:D?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx(Xs,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):me.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-8 text-center",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-gray-100 flex items-center justify-center mb-4",children:e.jsx(gs,{className:"w-7 h-7 text-gray-300"})}),G?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"没有匹配的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-md",children:["当前共有 ",K.length," 单参与统计,但没有订单号、商品、买家匹配“",J,"”。"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"当前范围内没有参与统计的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-lg leading-6",children:["日期范围:",w.startDate," 至 ",w.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",l.revenue_stats.total_orders," 单。"]})]})]}):e.jsxs("table",{className:"w-full text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-4",children:"订单信息"}),e.jsx("th",{className:"px-6 py-4",children:"买家信息"}),e.jsx("th",{className:"px-6 py-4",children:"金额"}),e.jsx("th",{className:"px-6 py-4",children:"状态"}),e.jsx("th",{className:"px-6 py-4 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:me.map(c=>e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:e.jsx(gs,{className:"w-full h-full text-gray-300 p-2"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm line-clamp-1",children:c.item_title||c.item_id||"未知商品"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:c.order_id}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",c.quantity||1]})]})]})}),e.jsxs("td",{className:"px-6 py-4",children:[e.jsx("div",{className:"text-sm font-bold text-gray-800",children:c.buyer_id}),c.created_at&&e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:c.created_at})]}),e.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",c.amount||"0.00"]}),e.jsx("td",{className:"px-6 py-4",children:e.jsx(Ml,{status:c.status||c.order_status||"unknown"})}),e.jsx("td",{className:"px-6 py-4 text-right",children:e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${c.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(It,{className:"w-4 h-4"})})})]},c.order_id))})]})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl bg-white",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品金额分析 (TOP5)"}),M.length===0?e.jsx("div",{className:"flex items-center justify-center h-[300px] text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-[300px] relative",children:e.jsx(fs,{width:"100%",height:"100%",children:e.jsxs(nt,{children:[e.jsx(it,{data:M,cx:"50%",cy:"50%",innerRadius:60,outerRadius:100,paddingAngle:2,dataKey:"value",label:({name:c,payload:C})=>`${c} ${(C==null?void 0:C.percentage)||"0.0"}%`,children:M.map((c,C)=>e.jsx(Rs,{fill:c.color||T[C%T.length]},`cell-${C}`))}),e.jsx(Is,{contentStyle:{backgroundColor:"#fff",border:"1px solid #e5e7eb",borderRadius:"6px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1)"},formatter:c=>`¥${Number(c||0).toLocaleString()}`})]})})}),e.jsx("div",{className:"space-y-3 mt-4",children:M.map(c=>e.jsxs("div",{className:"flex justify-between items-center text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:c.color||T[M.indexOf(c)%T.length]}}),e.jsx("span",{className:"text-gray-600 font-medium",children:c.name})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"font-bold text-gray-900",children:["¥",c.value.toLocaleString()]}),e.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[c.percentage,"%"]})]})]},c.name))})]})]})]})]})},Bl=(s,t)=>{const l=t.pause_duration||0;return s!==l},zl=(s,t)=>{const l=t.username!==(s.username||""),d=t.show_browser!==(s.show_browser||!1),u=t.login_password!=="",b=t.clear_password===!0;if(!l&&!d&&!u&&!b)return null;const k={username:t.username,show_browser:t.show_browser};return b?k.clear_password=!0:u&&(k.login_password=t.login_password),k},Ul=(s,t)=>s&&t,Wl=(s,t)=>{if(!s||!t)return!1;const l=Date.parse(s),d=Date.parse(t);return Number.isFinite(l)&&Number.isFinite(d)&&ds.map(l=>{const d=t[l.id];return!d||Wl(l.runtime_updated_at,d.updated_at)?l:{...l,runtime_state:d.state,runtime_message:d.message||"",runtime_connected:d.connected,runtime_updated_at:d.updated_at}}),Gl=new Set(["expired","cancelled","error","not_found"]),Ns=()=>{let s=0;return{next:()=>(s+=1,s),cancel:()=>{s+=1},isCurrent:t=>t===s}},Jl=(s={setInterval:globalThis.setInterval.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis)})=>{let t=null,l=null,d=-1,u=0;const b=()=>{u+=1,l==null||l.abort(),l=null,t!==null&&(s.clearInterval(t),t=null)};return{start:(O,p,R,f=2e3)=>{b();const Q=u;l=new AbortController;const se=l.signal;t=s.setInterval(()=>{d===Q||Q!==u||(d=Q,(async()=>{var U,J;try{const S=await p(O,se);if(S.status==="success"){b(),await R.onSuccess(S);return}if(S.status==="scanned"){(U=R.onScanned)==null||U.call(R,S);return}if(S.status==="verification_required"){(J=R.onVerificationRequired)==null||J.call(R,S);return}S.status&&Gl.has(S.status)&&(b(),R.onTerminalError(S))}catch(S){if(se.aborted||Q!==u)return;b(),R.onPollError(S)}finally{d===Q&&(d=-1)}})())},f)},stop:b,isActive:()=>t!==null}},Ql=({faceQrUrl:s,verificationScreenshot:t})=>e.jsxs("div",{className:"w-full min-w-0 max-h-[min(64vh,28rem)] overflow-y-auto overscroll-contain px-1 py-2 text-center",children:[e.jsx("div",{className:"mx-auto mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-amber-100 text-amber-700",children:e.jsx(ea,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsx("h4",{className:"break-words text-base font-extrabold leading-6 text-amber-900",children:"需要完成安全风控验证"}),e.jsx("p",{className:"mx-auto mt-1 max-w-[15rem] break-words text-xs leading-5 text-amber-800",children:"当前账号触发了闲鱼平台风控。请使用手机闲鱼 App 扫描下方二维码,并按 App 提示完成人脸识别。"}),e.jsx("div",{className:"mx-auto mt-3 flex min-h-36 w-full max-w-[12rem] items-center justify-center overflow-hidden rounded-xl border border-amber-200 bg-white p-2 shadow-sm",children:s?e.jsx("img",{src:s,alt:"闲鱼安全风控验证二维码",className:"block max-h-44 w-full object-contain"}):t?e.jsx("img",{src:t,alt:"闲鱼风控验证页面",className:"block max-h-44 w-full object-contain"}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-amber-700",children:[e.jsx(Le,{className:"h-6 w-6 animate-spin","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-bold",children:"正在准备风控二维码…"})]})}),e.jsx("p",{className:"mx-auto mt-2 max-w-[15rem] break-words text-[11px] leading-4 text-gray-500",children:"请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。"})]}),ht=({src:s,alt:t,className:l=""})=>e.jsx("img",{src:s,alt:t,className:`block aspect-square h-auto w-full object-contain ${l}`.trim()}),Kl=()=>{const[s,t]=n.useState([]),[l,d]=n.useState(!0),[u,b]=n.useState(""),[k,O]=n.useState(""),[p,R]=n.useState(!1),[f,Q]=n.useState(""),[se,U]=n.useState("pending"),[J,S]=n.useState(""),[K,de]=n.useState(""),[le,ne]=n.useState(null),[q,B]=n.useState(null),[D,Z]=n.useState(null),[W,A]=n.useState([]),[Y,L]=n.useState([]),[te,T]=n.useState(!1),[h,$]=n.useState(!1),[z,X]=n.useState(!1),[m,_]=n.useState(""),[N,y]=n.useState({remark:"",cookie:"",auto_confirm:!1,pause_duration:0,username:"",login_password:"",show_browser:!1,showLoginPassword:!1,clear_password:!1}),[P,M]=n.useState({ai_enabled:!1,max_discount_percent:10,max_discount_amount:100,max_bargain_rounds:3,custom_prompts:""}),[i,E]=n.useState(!1),[w,G]=n.useState({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),me=n.useRef(null),ie=n.useRef(null),H=n.useRef(null),c=n.useRef(null),C=n.useRef(null),oe=n.useRef(null),be=n.useRef(null),ye=n.useRef(null),Se=n.useRef(null),ve=n.useRef(null),fe=n.useRef(null),De=n.useRef(null),ue=n.useRef(0);me.current===null&&(me.current=Jl()),ie.current===null&&(ie.current=Ns()),H.current===null&&(H.current=Ns()),c.current===null&&(c.current=Ns()),C.current===null&&(C.current=Ns());const Ae=()=>{fe.current!==null&&(window.clearTimeout(fe.current),fe.current=null)},Re=()=>{De.current!==null&&(window.clearTimeout(De.current),De.current=null)},Fe=()=>{var o;(o=me.current)==null||o.stop()},Ke=()=>{var o,j;(o=Se.current)==null||o.abort(),(j=ie.current)==null||j.cancel(),Fe(),Ae(),R(!1)},Ye=()=>{Ae(),fe.current=window.setTimeout(()=>{fe.current=null,R(!1),x()},1e3)},x=async()=>{var F,ae,re,_e,$e;const o=H.current.next();(F=oe.current)==null||F.abort();const j=new AbortController;oe.current=j,d(!0);try{const we={signal:j.signal},[Pe,Xe]=await Promise.allSettled([Vs(we),Ja(we)]);if(!((ae=H.current)!=null&&ae.isCurrent(o)))return;if(Pe.status==="rejected")throw Pe.reason;const Oe=Pe.value,xs=Xe.status==="fulfilled"?Xe.value:{};Xe.status==="rejected"&&console.error("Failed to load AI settings:",Xe.reason);const Jt=Oe.map(ts=>{var Gs,Js,Qs,Ks,Ys;return{...ts,ai_enabled:((Gs=xs[ts.id])==null?void 0:Gs.ai_enabled)??!1,max_discount_percent:((Js=xs[ts.id])==null?void 0:Js.max_discount_percent)??10,max_discount_amount:((Qs=xs[ts.id])==null?void 0:Qs.max_discount_amount)??100,max_bargain_rounds:((Ks=xs[ts.id])==null?void 0:Ks.max_bargain_rounds)??3,custom_prompts:((Ys=xs[ts.id])==null?void 0:Ys.custom_prompts)??""}});(re=H.current)!=null&&re.isCurrent(o)&&t(Jt)}catch(we){(_e=H.current)!=null&&_e.isCurrent(o)&&!j.signal.aborted&&console.error("Failed to load accounts:",we)}finally{($e=H.current)!=null&&$e.isCurrent(o)&&d(!1)}};n.useEffect(()=>{let o=!1,j=null;const F=new AbortController,ae=async()=>{try{const re=await Da({signal:F.signal,timeoutMs:1e4});o||t(_e=>Vl(_e,re))}catch(re){o||console.error("Failed to load account runtime statuses:",re)}finally{o||(j=window.setTimeout(()=>void ae(),2e3))}};return x().finally(()=>{o||ae()}),()=>{o=!0,F.abort(),j!==null&&window.clearTimeout(j)}},[]),n.useEffect(()=>()=>{var o,j,F,ae,re,_e,$e,we,Pe;Fe(),(o=ie.current)==null||o.cancel(),(j=H.current)==null||j.cancel(),(F=c.current)==null||F.cancel(),(ae=C.current)==null||ae.cancel(),(re=oe.current)==null||re.abort(),(_e=be.current)==null||_e.abort(),($e=ye.current)==null||$e.abort(),(we=Se.current)==null||we.abort(),(Pe=ve.current)==null||Pe.abort(),Ae(),ue.current+=1,Re()},[]);const V=o=>{if(!o.enabled||o.runtime_state==="disabled")return{label:"已停用",badge:"bg-gray-100 text-gray-500",dot:"bg-gray-300"};switch(o.runtime_state){case"online":return{label:"在线",badge:"bg-green-100 text-green-700",dot:"bg-green-500"};case"starting":case"connecting":return{label:"连接中",badge:"bg-blue-100 text-blue-700",dot:"bg-blue-500"};case"reconnecting":return{label:"重连中",badge:"bg-amber-100 text-amber-700",dot:"bg-amber-500"};case"auth_expired":return{label:"登录已失效",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};case"verification_required":return{label:"需要验证",badge:"bg-orange-100 text-orange-700",dot:"bg-orange-500"};case"error":case"stopped":return{label:"运行异常",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};default:return{label:"状态检测中",badge:"bg-gray-100 text-gray-600",dot:"bg-gray-400"}}},he=async(o,j)=>{await qa(o,!j),x()},Ce=async o=>{confirm("确认删除该账号吗?")&&(await Ma(o),x())},Be=async o=>{O(o.id);try{const j=await Ga(o.id);j!=null&&j.profile_error&&alert("资料刷新失败:"+j.profile_error),await x()}catch(j){console.error("刷新账号资料失败:",j),alert((j==null?void 0:j.message)||"刷新账号资料失败,请先重新授权该账号")}finally{O("")}},Te=async o=>{var _e,$e;const j=c.current.next();(_e=be.current)==null||_e.abort();const F=new AbortController;be.current=F,$(!0),T(!1),X(!1),_("");const[ae,re]=await Promise.allSettled([zt({signal:F.signal}),El(o,{signal:F.signal})]);($e=c.current)!=null&&$e.isCurrent(j)&&(ae.status==="fulfilled"?A(ae.value.data||[]):(A([]),_("通知渠道列表加载失败,请重试")),re.status==="fulfilled"?(L(re.value||[]),T(!0)):(L([]),_("通知绑定加载失败;本次保存不会修改现有绑定")),$(!1))},r=async o=>{var j;ue.current+=1,(j=ve.current)==null||j.abort(),Re(),G({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),Z(o),y({remark:o.remark||o.note||"",cookie:o.cookie||o.value||"",auto_confirm:o.auto_confirm||!1,pause_duration:o.pause_duration||0,username:o.username||"",login_password:o.login_password||"",show_browser:o.show_browser||!1,showLoginPassword:!1,clear_password:!1}),B("edit"),await Te(o.id)},I=async o=>{var ae,re,_e,$e;const j=C.current.next();(ae=ye.current)==null||ae.abort();const F=new AbortController;ye.current=F,Z(o),B("ai-settings"),E(!0);try{const we=await Al(o.id,{signal:F.signal});if(!((re=C.current)!=null&&re.isCurrent(j)))return;M({ai_enabled:we.ai_enabled??!1,max_discount_percent:we.max_discount_percent??10,max_discount_amount:we.max_discount_amount??100,max_bargain_rounds:we.max_bargain_rounds??3,custom_prompts:we.custom_prompts??""})}catch(we){(_e=C.current)!=null&&_e.isCurrent(j)&&console.error("Failed to load AI settings:",we)}finally{($e=C.current)!=null&&$e.isCurrent(j)&&E(!1)}},ce=async()=>{if(D){E(!0);try{const o={};N.remark!==(D.remark||D.note||"")&&(o.remark=N.remark),N.cookie&&N.cookie!==(D.cookie||D.value||"")&&(o.cookie=N.cookie),N.auto_confirm!==D.auto_confirm&&(o.auto_confirm=N.auto_confirm),Bl(N.pause_duration,D)&&(o.pause_duration=N.pause_duration);const j=zl(D,N);j&&Object.assign(o,j),Ul(te,z)&&(o.channel_ids=Y),Object.keys(o).length>0&&await za(D.id,o),B(null),x()}catch(o){console.error("更新账号失败:",o),alert("更新失败,请重试")}finally{E(!1)}}},Qe=async()=>{if(!(!D||N.pause_duration<=0)){E(!0);try{const o=await Ba(D.id,N.pause_duration);Z({...D,pause_duration:N.pause_duration,paused:(o==null?void 0:o.paused)===!0,paused_until:Number((o==null?void 0:o.paused_until)||0)}),await x()}catch(o){alert(o instanceof Error?o.message:"重新暂停失败")}finally{E(!1)}}},ze=async()=>{if(D){E(!0);try{await Il(D.id,P),B(null),x()}catch(o){console.error("更新AI设置失败:",o),alert("更新失败,请重试")}finally{E(!1)}}},Ie=async(o,j)=>{var ae;(ae=ve.current)==null||ae.abort();const F=new AbortController;ve.current=F;try{const re=await Wa(o,F.signal);if(j!==ue.current)return;if(re.status==="success"){Re(),G({sessionId:o,status:"success",message:re.message||"账号密码登录成功,授权信息已更新",qrCodeUrl:""}),y(_e=>({..._e,login_password:"",showLoginPassword:!1})),await x();return}if(re.status==="processing"||re.status==="verification_required"){G({sessionId:o,status:re.status,message:re.message||(re.status==="verification_required"?"账号触发风控,需要完成人脸识别":"登录处理中"),qrCodeUrl:re.qr_code_url||""}),Re(),De.current=window.setTimeout(()=>void Ie(o,j),1500);return}Re(),G({sessionId:o,status:"failed",message:re.error||re.message||"密码登录失败,请检查账号信息后重试",qrCodeUrl:""})}catch(re){if(j!==ue.current)return;Re(),G({sessionId:o,status:"failed",message:re instanceof Error?re.message:"查询密码登录状态失败",qrCodeUrl:""})}},ss=async()=>{var F;if(!D)return;const o=N.username.trim();if(!o||!N.login_password){alert("请先填写登录账号和本次登录密码");return}Re(),(F=ve.current)==null||F.abort();const j=++ue.current;G({sessionId:"",status:"processing",message:"正在启动密码登录…",qrCodeUrl:""});try{const ae=await Ua({account_id:D.id,account:o,password:N.login_password,show_browser:N.show_browser});if(j!==ue.current)return;if(!ae.success||!ae.session_id)throw new Error(ae.message||"无法启动密码登录");G({sessionId:ae.session_id,status:"processing",message:ae.message||"登录处理中",qrCodeUrl:""}),await Ie(ae.session_id,j)}catch(ae){if(j!==ue.current)return;G({sessionId:"",status:"failed",message:ae instanceof Error?ae.message:"启动密码登录失败",qrCodeUrl:""})}},a=async()=>{var j;const o=w.sessionId;if(ue.current+=1,(j=ve.current)==null||j.abort(),Re(),o)try{await Va(o)}catch(F){console.error("取消密码登录失败",F)}G({sessionId:"",status:"idle",message:"",qrCodeUrl:""})},g=async()=>{var o,j;(o=c.current)==null||o.cancel(),(j=be.current)==null||j.abort(),(w.status==="processing"||w.status==="verification_required")&&await a(),B(null)},v=()=>{var o,j;(o=C.current)==null||o.cancel(),(j=ye.current)==null||j.abort(),B(null)},ee=async(o,j)=>{const F=await Oa(o,j==null?void 0:j.id);if(!F.success||!F.account_id)throw new Error(F.message||"保存扫码授权失败");return F.account_id},xe=async o=>{var re,_e,$e,we;Fe(),(re=Se.current)==null||re.abort();const j=new AbortController;Se.current=j;const F=ie.current.next();Ae();const ae=o||null;ne(ae),R(!0),U("loading"),Q(""),S(""),de("");try{const Pe=await Fa({signal:j.signal});if(!((_e=ie.current)!=null&&_e.isCurrent(F)))return;if(Pe.success&&Pe.qr_code_url&&Pe.session_id){const Xe=Pe.session_id;Q(Pe.qr_code_url),U("waiting"),($e=me.current)==null||$e.start(Xe,Ta,{onSuccess:async()=>{try{if(!await ee(Xe,ae)){U("error");return}}catch(Oe){console.error("保存扫码授权失败",Oe),U("error");return}U("success"),Ye()},onScanned:()=>{U("waiting")},onTerminalError:()=>{U("error")},onPollError:Oe=>{console.error("轮询扫码状态失败",Oe),U("error")},onVerificationRequired:Oe=>{U("verification"),Oe.face_qr_url&&de(Oe.face_qr_url),Oe.verification_screenshot&&S(Oe.verification_screenshot)}})}}catch{if(!((we=ie.current)!=null&&we.isCurrent(F)))return;U("error")}};if(l)return e.jsx("div",{className:"p-20 flex justify-center",children:e.jsx(Le,{className:"w-8 h-8 text-[#0094f7] animate-spin"})});const je=s.filter(o=>{const j=u.trim().toLowerCase();return j?[o.id,o.nickname,o.remark,o.note,o.username,o.runtime_message].some(F=>(F||"").toLowerCase().includes(j)):!0});return e.jsxs("div",{className:"space-y-8 animate-fade-in relative",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"账号管理"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理您的闲鱼授权账号及设置。建议给账号填写备注,便于多账号区分。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx("input",{value:u,onChange:o=>b(o.target.value),placeholder:"搜索昵称 / 备注 / 账号ID",className:"ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"}),e.jsxs("button",{onClick:()=>xe(),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(Ss,{className:"w-5 h-5"}),"扫码添加新账号"]})]})]}),e.jsxs("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 px-5 py-4 text-sm text-blue-900 flex flex-col md:flex-row md:items-center md:justify-between gap-2",children:[e.jsxs("div",{className:"font-bold",children:["当前显示 ",je.length," / ",s.length," 个账号"]}),e.jsx("div",{className:"text-blue-700",children:"如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[je.map(o=>{const j=V(o),F=o.runtime_state==="auth_expired"||o.runtime_state==="verification_required";return e.jsxs("div",{className:"ios-card p-6 rounded-xl flex flex-col lg:flex-row lg:items-center justify-between gap-5 group hover:border-[#0094f7] transition-all duration-300",children:[e.jsxs("div",{className:"flex items-center gap-5 sm:gap-8 min-w-0",children:[e.jsxs("div",{className:"relative",children:[o.avatar_url?e.jsx("img",{src:o.avatar_url,alt:o.nickname||"账号头像",className:"w-20 h-20 rounded-full object-cover shadow-md ring-4 ring-white bg-gray-100"}):e.jsx("div",{className:"w-20 h-20 rounded-full bg-gray-100 text-gray-400 shadow-md ring-4 ring-white flex items-center justify-center",children:e.jsx(Os,{className:"w-9 h-9"})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-6 h-6 rounded-full border-4 border-white flex items-center justify-center ${j.dot}`,children:o.runtime_state==="online"&&e.jsx(We,{className:"w-3 h-3 text-white"})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-1",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900 break-words",children:o.nickname||o.remark||`账号 ${o.id.substring(0,6)}...`}),e.jsx("span",{className:`px-2.5 py-0.5 rounded-lg text-xs font-bold ${j.badge}`,children:j.label}),o.ai_enabled&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-purple-100 text-purple-700 text-xs font-bold flex items-center gap-1",children:[e.jsx(rs,{className:"w-3 h-3"})," AI"]}),o.profile_error&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-amber-100 text-amber-700 text-xs font-bold flex items-center gap-1",title:o.profile_error,children:[e.jsx(os,{className:"w-3 h-3"})," 资料未同步"]})]}),e.jsxs("div",{className:"text-sm text-gray-500 font-medium mb-3 space-y-1",children:[e.jsx("p",{children:o.remark||o.note||"暂无备注"}),e.jsxs("p",{className:"font-mono text-xs text-gray-400",children:["ID: ",o.id]})]}),o.runtime_message&&o.runtime_state!=="online"&&o.runtime_state!=="disabled"&&e.jsxs("div",{className:`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${F?"text-red-700":"text-amber-700"}`,children:[e.jsx(os,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{children:o.runtime_message}),F&&e.jsxs("button",{type:"button",onClick:()=>xe(o),className:"inline-flex items-center gap-1.5 rounded-lg bg-red-50 px-2.5 py-1 text-xs font-bold text-red-700 hover:bg-red-100",children:[e.jsx(Ss,{className:"w-3.5 h-3.5"})," 重新授权"]})]}),e.jsxs("div",{className:"flex gap-2",children:[o.auto_confirm&&e.jsxs("span",{className:"text-xs bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg font-bold flex items-center gap-1.5",children:[e.jsx(We,{className:"w-3 h-3"})," 自动确认发货"]}),o.paused&&e.jsxs("span",{className:"text-xs bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg font-bold flex items-center gap-1.5",children:[e.jsx(Hs,{className:"w-3 h-3"})," 暂停处理中"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 self-end lg:self-auto flex-shrink-0",children:[e.jsx("button",{onClick:()=>Be(o),disabled:k===o.id,className:"p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50",title:"刷新昵称和头像",children:e.jsx(qe,{className:`w-5 h-5 ${k===o.id?"animate-spin":""}`})}),e.jsx("button",{onClick:()=>xe(o),className:`p-3 rounded-xl transition-colors ${F?"text-red-600 bg-red-50 hover:bg-red-100":"text-blue-600 hover:bg-blue-50"}`,title:"重新扫码授权当前账号",children:e.jsx(Ss,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>r(o),className:"p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600",title:"编辑账号",children:e.jsx(Rt,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>I(o),className:"p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600",title:"AI设置",children:e.jsx(rs,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>he(o.id,o.enabled),className:`p-3 rounded-xl transition-colors ${o.enabled?"text-green-600 hover:bg-green-50":"text-gray-400 hover:bg-gray-100"}`,title:o.enabled?"停用账号":"启用账号",children:e.jsx(sa,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Ce(o.id),className:"p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500",children:e.jsx(Ve,{className:"w-5 h-5"})})]})]},o.id)}),s.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(Os,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"暂无账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"请点击右上角扫码添加您的闲鱼账号"})]}),s.length>0&&je.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"没有匹配的账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"换一个关键词搜索昵称、备注或账号ID。"})]})]}),p&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container relative",style:{maxWidth:"26rem"},children:[e.jsx("button",{onClick:Ke,className:"absolute top-4 right-4 z-10 w-9 h-9 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-full transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900 mb-2",children:le?"重新授权账号":"扫码添加账号"}),e.jsx("p",{className:"text-gray-500 mb-8 font-medium",children:le?`请用闲鱼APP扫码,为「${le.nickname||le.remark||le.id}」刷新授权`:"请打开闲鱼APP扫描下方二维码"}),e.jsxs("div",{className:`w-full bg-[#F7F8FA] rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${se==="verification"?"max-w-72 min-h-64 h-auto p-2":"max-w-64 aspect-square"}`,children:[se==="loading"&&e.jsx(Le,{className:"w-10 h-10 text-[#0094f7] animate-spin"}),se==="waiting"&&e.jsx(ht,{src:f,alt:"闲鱼登录二维码",className:"p-2"}),se==="success"&&e.jsxs("div",{className:"absolute inset-0 bg-white/95 flex flex-col items-center justify-center text-green-600 animate-fade-in",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(We,{className:"w-8 h-8"})}),e.jsx("span",{className:"font-bold text-lg",children:"登录成功"})]}),se==="error"&&e.jsxs("div",{className:"px-5 text-center",children:[e.jsx("span",{className:"block text-red-600 font-bold",children:"二维码获取失败"}),e.jsx("span",{className:"mt-2 block text-xs leading-5 text-gray-500",children:"请关闭窗口后重新发起扫码登录。"})]}),se==="verification"&&e.jsx(Ql,{faceQrUrl:K,verificationScreenshot:J})]}),se!=="verification"&&e.jsx("p",{className:"text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl",children:"二维码有效期为5分钟,请尽快扫码。"})]})})]})}),document.body),q==="edit"&&D&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑账号"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:D.nickname||D.remark||D.id})]}),e.jsx("button",{onClick:()=>void g(),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"账号ID"}),e.jsx("input",{type:"text",value:D.id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注"}),e.jsx("input",{type:"text",value:N.remark,onChange:o=>y({...N,remark:o.target.value}),placeholder:"为账号添加备注",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"Cookie"}),e.jsx("textarea",{value:N.cookie,onChange:o=>y({...N,cookie:o.target.value}),placeholder:"更新账号Cookie",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none font-mono text-xs"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["当前Cookie长度: ",N.cookie.length," 字符"]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(We,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:()=>y({...N,auto_confirm:!N.auto_confirm}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${N.auto_confirm?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${N.auto_confirm?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2 flex items-center gap-2",children:[e.jsx(Hs,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:N.pause_duration,onChange:o=>y({...N,pause_duration:parseInt(o.target.value)||0}),placeholder:"0",min:"0",max:"1440",className:"w-full ios-input px-4 py-3 rounded-xl"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"设置后会暂停处理该账号的订单,到时间后自动恢复"}),N.pause_duration>0&&!D.paused&&N.pause_duration===(D.pause_duration||0)&&e.jsx("button",{type:"button",disabled:i,onClick:()=>void Qe(),className:"mt-3 px-4 py-2 rounded-xl bg-amber-50 text-amber-700 hover:bg-amber-100 text-sm font-bold disabled:opacity-50",children:"立即按当前时长重新暂停"})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-4 flex items-center gap-2",children:[e.jsx(ta,{className:"w-5 h-5 text-blue-500"}),"登录信息"]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"用户名"}),e.jsx("input",{type:"text",value:N.username,onChange:o=>y({...N,username:o.target.value}),placeholder:"闲鱼账号/手机号",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"登录密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:N.showLoginPassword?"text":"password",value:N.login_password,onChange:o=>y({...N,login_password:o.target.value,clear_password:!1}),placeholder:"用于自动登录",className:"w-full ios-input px-4 py-3 rounded-xl pr-12"}),e.jsx("button",{type:"button",onClick:()=>y({...N,showLoginPassword:!N.showLoginPassword}),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:N.showLoginPassword?e.jsx(ns,{className:"w-5 h-5"}):e.jsx(es,{className:"w-5 h-5"})})]}),e.jsxs("label",{className:"mt-3 flex items-center gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:N.clear_password,onChange:o=>y({...N,clear_password:o.target.checked,login_password:o.target.checked?"":N.login_password}),className:"w-4 h-4 accent-[#0094f7]"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:"清空已保存密码"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"登录时显示浏览器"}),e.jsx("div",{className:"text-xs text-gray-500",children:"调试时可开启查看登录过程"})]}),e.jsx("button",{type:"button",onClick:()=>y({...N,show_browser:!N.show_browser}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${N.show_browser?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${N.show_browser?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-blue-950",children:"立即执行账号密码登录"}),e.jsx("div",{className:"text-xs text-blue-700 mt-1",children:"需要在上方重新输入本次登录密码;成功后后端会更新 Cookie 和保存的登录信息。"})]}),w.status==="processing"||w.status==="verification_required"?e.jsx("button",{type:"button",onClick:a,className:"px-4 py-2 rounded-xl bg-white text-red-600 font-bold text-sm border border-red-100",children:"取消登录"}):e.jsx("button",{type:"button",onClick:ss,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),w.message&&e.jsx("div",{className:`text-sm font-medium ${w.status==="failed"?"text-red-700":w.status==="success"?"text-green-700":"text-blue-800"}`,children:w.message}),w.status==="verification_required"&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-amber-900",children:[e.jsx("div",{className:"font-extrabold",children:"账号已触发平台风控,需要完成人脸识别"}),e.jsx("div",{className:"text-xs mt-1 leading-5",children:"请在闲鱼 App 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),w.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(ht,{src:w.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(W.length>0||h||m)&&e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-1 flex items-center gap-2",children:[e.jsx(is,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),h&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(Le,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),m&&!h&&e.jsxs("div",{className:"mb-3 rounded-xl bg-amber-50 p-3 text-sm text-amber-800 flex items-center justify-between gap-3",children:[e.jsx("span",{children:m}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:()=>Te(D.id),children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:W.map(o=>{const j=Y.includes(Number(o.id));return e.jsxs("label",{className:"flex items-center gap-3 p-3 rounded-xl border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors",children:[e.jsx("button",{type:"button",onClick:()=>{te&&(L(F=>j?F.filter(ae=>ae!==Number(o.id)):[...F,Number(o.id)]),X(!0))},disabled:!te,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${j?"bg-[#0094f7] border-[#0094f7]":"bg-white border-gray-300"}`,children:j&&e.jsx(We,{className:"w-3.5 h-3.5 text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:o.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[o.type,o.enabled?"":" · 已停用"]})]})]},o.id)})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>void g(),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:i,children:"取消"}),e.jsxs("button",{onClick:ce,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:i,children:[i?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(Je,{className:"w-4 h-4"}),i?"保存中...":"保存"]})]})})]})}),document.body),q==="ai-settings"&&D&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-2xl font-extrabold text-gray-900 flex items-center gap-2",children:[e.jsx(rs,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:D.nickname||D.remark||D.id})]}),e.jsx("button",{onClick:v,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-purple-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(rs,{className:"w-4 h-4 text-purple-500"}),"启用AI自动回复"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"AI将自动处理买家的砍价消息"})]}),e.jsx("button",{type:"button",onClick:()=>M({...P,ai_enabled:!P.ai_enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${P.ai_enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${P.ai_enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900 mb-4",children:"砍价策略"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣比例 (%)"}),e.jsx("input",{type:"number",value:P.max_discount_percent,onChange:o=>M({...P,max_discount_percent:parseInt(o.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"100"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:10 表示最多降价 10%;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣金额 (元)"}),e.jsx("input",{type:"number",value:P.max_discount_amount,onChange:o=>M({...P,max_discount_amount:parseInt(o.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:100 表示最多降价 100 元;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大砍价轮次"}),e.jsx("input",{type:"number",value:P.max_bargain_rounds,onChange:o=>M({...P,max_bargain_rounds:parseInt(o.target.value)||1}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"10"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"买家最多可以砍价的次数"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"自定义提示词(可选)"}),e.jsx("textarea",{value:P.custom_prompts,onChange:o=>M({...P,custom_prompts:o.target.value}),placeholder:`输入自定义的AI回复规则或风格指引...
-
-例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(zs,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:v,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:i,children:"取消"}),e.jsxs("button",{onClick:ze,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:i,children:[i?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(Je,{className:"w-4 h-4"}),i?"保存中...":"保存"]})]})})]})}),document.body)]})},Yl=s=>({total:Number((s==null?void 0:s.total)||0),success_count:Number((s==null?void 0:s.success_count)||0),failed_count:Number((s==null?void 0:s.failed_count)||0),results:Array.isArray(s==null?void 0:s.results)?s.results.map(t=>({order_id:String((t==null?void 0:t.order_id)||"unknown"),success:(t==null?void 0:t.success)===!0,message:String((t==null?void 0:t.message)||"")})):[]}),Xl=s=>(s==null?void 0:s.results.filter(t=>!t.success))||[],gt=({status:s})=>{const t={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:l[s]||s})},Zl=()=>{const[s,t]=n.useState([]),[l,d]=n.useState([]),[u,b]=n.useState({}),[k,O]=n.useState("all"),[p,R]=n.useState(""),[f,Q]=n.useState(""),se=n.useRef(0),[U,J]=n.useState(1),[S,K]=n.useState(1),[de,le]=n.useState(!1),[ne,q]=n.useState(!1),[B,D]=n.useState(!1),[Z,W]=n.useState(!1),[A,Y]=n.useState(null),[L,te]=n.useState(null),[T,h]=n.useState({}),[$,z]=n.useState(!1),[X,m]=n.useState(""),[_,N]=n.useState(!1),[y,P]=n.useState(null),[M,i]=n.useState(null),[E,w]=n.useState(null),[G,me]=n.useState(!1),[ie,H]=n.useState(null),[c,C]=n.useState(null),oe=async()=>{const x=++se.current;le(!0);try{const V=await Qa(void 0,k,U,20,f);if(x!==se.current)return;t(V.data),K(V.total_pages)}catch(V){console.error("加载订单失败:",V)}finally{x===se.current&&le(!1)}},be=(x,V)=>{if(V&&V.trim())return V;if(u[x])return u[x];const he=l.find(Ce=>{if(V&&Ce.item_title){const Be=V.toLowerCase(),Te=Ce.item_title.toLowerCase();return Te.includes(Be)||Be.includes(Te)}return!1});return he!=null&&he.item_title?he.item_title:"未知商品"},ye=x=>{const V={};x.forEach(he=>{he.item_id&&(V[he.item_id]=he.item_title||he.item_id)}),b(V)};n.useEffect(()=>{const x=window.setTimeout(()=>{J(1),Q(p.trim())},300);return()=>window.clearTimeout(x)},[p]),n.useEffect(()=>{oe()},[k,U,f]),n.useEffect(()=>{ds().then(x=>{d(x),ye(x)}).catch(x=>{console.error("加载商品列表失败:",x)})},[]);const Se=async()=>{le(!0);try{const x=await Xa();await oe(),x!=null&&x.message&&alert(x.message)}catch(x){console.error("同步订单失败:",x),alert((x==null?void 0:x.message)||"同步失败,请重试")}finally{le(!1)}},ve=x=>{m(x),P(null),z(!0)},fe=async x=>{var V;N(!0),P(null);try{const he=await Ha([X],x),Ce=(V=he==null?void 0:he.results)==null?void 0:V[0];Ce!=null&&Ce.success?(P({success:!0,message:Ce.message}),oe()):P({success:!1,message:(Ce==null?void 0:Ce.message)||"发货失败"})}catch(he){P({success:!1,message:(he==null?void 0:he.message)||"请求失败"})}finally{N(!1)}},De=x=>{Y(x),q(!0)},ue=x=>{te({...x}),D(!0)},Ae=async()=>{if(!(!L||!L.order_id))try{const x={};L.status!==void 0&&(x.order_status=L.status),L.buyer_id!==void 0&&(x.buyer_id=L.buyer_id),L.amount!==void 0&&(x.amount=L.amount),L.receiver_name!==void 0&&(x.receiver_name=L.receiver_name),L.receiver_phone!==void 0&&(x.receiver_phone=L.receiver_phone),L.receiver_address!==void 0&&(x.receiver_address=L.receiver_address),L.item_id!==void 0&&(x.item_id=L.item_id),L.quantity!==void 0&&(x.quantity=L.quantity),L.item_title!==void 0&&(x.item_title=L.item_title),await Ka(L.order_id,x),D(!1),te(null),oe()}catch(x){console.error("更新订单失败:",x),alert("更新失败,请重试")}},Re=async()=>{if(M){me(!0);try{const x=new FormData;x.append("file",M);const V=Yl(await el(x));w(V),i(null),await oe(),V.failed_count===0&&(W(!1),w(null),alert(`订单导入成功,共 ${V.success_count} 条`))}catch(x){alert((x==null?void 0:x.message)||"导入失败,请检查文件格式")}finally{me(!1)}}},Fe=()=>{G||(W(!1),i(null),w(null))},Ke=async x=>{H(x);try{const V=await Za(x);V.success?await oe():alert(V.message||"同步失败")}catch(V){console.error("同步订单失败:",V),alert((V==null?void 0:V.message)||"同步失败,请重试")}finally{H(null)}},Ye=async x=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){C(x);try{await Ya(x),s.length===1&&U>1?J(V=>V-1):await oe()}catch(V){console.error("删除订单失败:",V),alert((V==null?void 0:V.message)||"删除失败,请重试"),await oe()}finally{C(null)}}};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"订单中心"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"查看所有闲鱼交易记录与状态。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:oe,className:"p-3 rounded-2xl bg-white border border-gray-100 text-gray-600 hover:bg-gray-50 hover:text-black transition-colors shadow-sm",children:e.jsx(qe,{className:`w-5 h-5 ${de?"animate-spin":""}`})}),e.jsxs("button",{onClick:()=>{w(null),W(!0)},className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors text-sm flex items-center gap-2 shadow-lg",children:[e.jsx(Ge,{className:"w-4 h-4"}),"插入订单"]}),e.jsxs("button",{onClick:Se,className:"ios-btn-primary px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 text-sm flex items-center gap-2",children:[e.jsx(et,{className:"w-5 h-5"}),"一键同步订单"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-[#FAFAFA]",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:[{k:"all",v:"全部"},{k:"processing",v:"处理中"},{k:"shipped",v:"已发货"},{k:"pending_ship",v:"待发货"},{k:"completed",v:"已完成"},{k:"cancelled",v:"已取消"},{k:"refunding",v:"退款中"}].map(x=>e.jsx("button",{onClick:()=>{O(x.k),J(1),R("")},className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${k===x.k?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:x.v},x.k))}),e.jsxs("div",{className:"relative w-full md:w-auto group",children:[e.jsx(aa,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-[#0094f7] transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:p,onChange:x=>{R(x.target.value),J(1)},className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]}),e.jsx("div",{className:"overflow-x-auto min-h-[400px]",children:e.jsxs("table",{className:"w-full text-left border-collapse table-fixed",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-5",style:{width:"28%"},children:"订单信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"26%"},children:"买家信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"11%"},children:"实付金额"}),e.jsx("th",{className:"px-6 py-5",style:{width:"13%"},children:"当前状态"}),e.jsx("th",{className:"px-6 py-5 text-right",style:{width:"22%"},children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:s.map(x=>e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx("div",{className:"w-14 h-14 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:x.item_image?e.jsx("img",{src:x.item_image,alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(gs,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:be(x.item_id,x.item_title)}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",x.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",x.quantity," • ",x.created_at]})]})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("div",{className:"text-xs text-gray-500",children:"买家ID"}),e.jsx("div",{className:"text-sm font-bold text-gray-800",children:x.buyer_id}),x.receiver_name&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货人"}),e.jsx("div",{className:"text-xs text-gray-600",children:x.receiver_name})]}),x.receiver_phone&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"联系电话"}),e.jsx("div",{className:"text-xs text-gray-600 font-mono",children:x.receiver_phone})]}),x.receiver_address&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货地址"}),e.jsx("div",{className:"text-xs text-gray-600 line-clamp-1",children:x.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:x.amount?`¥${x.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(gt,{status:x.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[x.status==="pending_ship"&&e.jsx("button",{onClick:()=>ve(x.order_id),className:"mr-2 text-white bg-black hover:bg-gray-800 shadow-lg shadow-gray-200 text-xs font-bold px-3 py-2 rounded-xl transition-all active:scale-95",children:"立即发货"}),e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${x.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"mr-2 inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(It,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>De(x),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(es,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>ue(x),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(cs,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>Ke(x.order_id),disabled:ie===x.order_id,className:"mr-2 text-gray-400 hover:text-green-600 p-2 rounded-xl hover:bg-green-50 transition-colors disabled:opacity-50",title:"同步订单",children:e.jsx(qe,{className:`w-4 h-4 ${ie===x.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:()=>Ye(x.order_id),disabled:c===x.order_id,className:"text-gray-400 hover:text-red-500 p-2 rounded-xl hover:bg-red-50 transition-colors disabled:opacity-50",title:"删除订单",children:e.jsx(Ve,{className:"w-4 h-4"})})]})]},x.id))})]})}),e.jsxs("div",{className:"p-4 border-t border-gray-50 flex items-center justify-between bg-white",children:[e.jsxs("div",{className:"text-sm text-gray-500 font-medium pl-2",children:["第 ",U," 页 / 共 ",S," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:U<=1,onClick:()=>J(x=>x-1),className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(la,{className:"w-5 h-5"})}),e.jsx("button",{disabled:U>=S,onClick:()=>J(x=>x+1),className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(ra,{className:"w-5 h-5"})})]})]})]}),ne&&A&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"订单详情"}),e.jsx("button",{onClick:()=>q(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"订单信息"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"订单号"}),e.jsx("div",{className:"font-mono text-sm font-bold text-gray-900",children:A.order_id})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(gt,{status:A.status})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"实付金额"}),e.jsx("div",{className:"text-lg font-extrabold text-gray-900",children:A.amount?`¥${A.amount}`:"待获取"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"数量"}),e.jsx("div",{className:"font-bold text-gray-900",children:A.quantity})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"创建时间"}),e.jsx("div",{className:"text-sm font-medium text-gray-700",children:A.created_at})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"商品信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl flex items-center gap-4",children:[A.item_image&&e.jsx("img",{src:A.item_image,alt:"",className:"w-20 h-20 rounded-xl object-cover border border-gray-200"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-bold text-gray-900 mb-1",children:be(A.item_id,A.item_title)}),e.jsxs("div",{className:"text-sm text-gray-500",children:["商品ID: ",A.item_id]}),A.item_price&&e.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:["标价: ¥",A.item_price]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"买家信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"买家ID"}),e.jsx("div",{className:"font-bold text-gray-900",children:A.buyer_id})]}),A.receiver_name&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货人"}),e.jsx("div",{className:"font-medium text-gray-700",children:A.receiver_name})]}),A.receiver_phone&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"联系电话"}),e.jsx("div",{className:"font-mono text-sm text-gray-700",children:A.receiver_phone})]}),A.receiver_address&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货地址"}),e.jsx("div",{className:"text-sm text-gray-700",children:A.receiver_address})]})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>q(!1),className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"关闭"}),A.status==="pending_ship"&&e.jsx("button",{onClick:()=>{q(!1),ve(A.order_id)},className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200",children:"立即发货"})]})})]})}),document.body),Z&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:Fe,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:x=>{var V;return i(((V=x.target.files)==null?void 0:V[0])||null)},className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),M&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:M.name})]})}),E&&E.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",E.success_count," 条,失败 ",E.failed_count," 条"]}),e.jsx("div",{className:"max-h-64 overflow-y-auto rounded-xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"订单ID"}),e.jsx("th",{className:"px-3 py-2",children:"失败原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:Xl(E).map((x,V)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:x.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:x.message||"导入失败"})]},`${x.order_id}-${V}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:Fe,disabled:G,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"取消"}),e.jsx("button",{onClick:Re,disabled:!M||G,className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:G?"正在导入…":"导入订单"})]})})]})}),document.body),$&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"480px"},children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"立即发货"}),e.jsx("button",{onClick:()=>{z(!1),P(null)},className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600",children:"请选择发货方式:"}),e.jsx("button",{onClick:()=>fe("status_only"),disabled:_,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-gray-400 hover:bg-gray-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(et,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"仅修改闲鱼发货状态"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:'不实际扣除或发送卡券,仅在闲鱼平台将订单标记为"已发货"。 适用于已经给客户发过货、只是忘记在闲鱼修改状态的情况。'})]})]})}),e.jsx("button",{onClick:()=>fe("full_delivery"),disabled:_,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-[#0094f7] hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(gs,{className:"w-5 h-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"完整发货(匹配卡券并发送)"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),_&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(qe,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),y&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${y.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[y.success?"✓ ":"✗ ",y.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:()=>{z(!1),P(null)},className:"w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:y!=null&&y.success?"完成":"取消"})})]})}),document.body),B&&L&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑订单"}),e.jsx("button",{onClick:()=>D(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单号"}),e.jsx("input",{type:"text",value:L.order_id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单状态"}),e.jsxs("select",{value:L.status,onChange:x=>te({...L,status:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"processing",children:"处理中"}),e.jsx("option",{value:"pending_ship",children:"待发货"}),e.jsx("option",{value:"shipped",children:"已发货"}),e.jsx("option",{value:"completed",children:"已完成"}),e.jsx("option",{value:"cancelled",children:"已取消"}),e.jsx("option",{value:"refunding",children:"退款中"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"买家ID"}),e.jsx("input",{type:"text",value:L.buyer_id,onChange:x=>te({...L,buyer_id:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"实付金额"}),e.jsx("input",{type:"number",value:L.amount,onChange:x=>te({...L,amount:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货人"}),e.jsx("input",{type:"text",value:L.receiver_name||"",onChange:x=>te({...L,receiver_name:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"联系电话"}),e.jsx("input",{type:"text",value:L.receiver_phone||"",onChange:x=>te({...L,receiver_phone:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货地址"}),e.jsx("textarea",{value:L.receiver_address||"",onChange:x=>te({...L,receiver_address:x.target.value}),rows:2,className:"w-full ios-input px-4 py-3 rounded-xl resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"商品标题"}),e.jsx("input",{type:"text",value:L.item_title||"",onChange:x=>te({...L,item_title:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>D(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:Ae,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})},bt=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),Hl=()=>{const[s,t]=n.useState([]),[l,d]=n.useState(!1),[u,b]=n.useState(!1),[k,O]=n.useState(null),[p,R]=n.useState({}),[f,Q]=n.useState(bt),[se,U]=n.useState(!1),[J,S]=n.useState("create"),[K,de]=n.useState(null),[le,ne]=n.useState(null),[q,B]=n.useState(!1),[D,Z]=n.useState(""),[W,A]=n.useState(""),[Y,L]=n.useState(null);n.useEffect(()=>{Ue().then(t)},[]);const te=({type:i})=>{switch(i){case"text":return e.jsx(st,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(tt,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(ca,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(Fs,{className:"w-5 h-5 text-gray-500"})}},T=i=>{var E,w,G,me,ie;O(i),R({id:i.id,name:i.name||"",type:i.type||"text",api_url:((E=i.api_config)==null?void 0:E.url)||"",api_method:((w=i.api_config)==null?void 0:w.method)||"GET",api_timeout:((G=i.api_config)==null?void 0:G.timeout)||10,api_headers:((me=i.api_config)==null?void 0:me.headers)||"",api_params:((ie=i.api_config)==null?void 0:ie.params)||"",text_content:i.text_content||"",data_content:i.data_content||"",image_url:i.image_url||"",delay_seconds:i.delay_seconds||0,description:i.description||"",enabled:i.enabled}),d(!0)},h=async()=>{var i,E,w,G,me,ie,H,c;if(k){if(!((i=p.name)!=null&&i.trim())){alert("请输入卡密名称");return}if(!p.type){alert("请选择卡密类型");return}try{const C={name:p.name.trim(),type:p.type,description:(E=p.description)==null?void 0:E.trim(),delay_seconds:p.delay_seconds||0,enabled:p.enabled??!0};p.type==="api"?C.api_config={url:((w=p.api_url)==null?void 0:w.trim())||"",method:p.api_method,timeout:p.api_timeout||10,headers:((G=p.api_headers)==null?void 0:G.trim())||void 0,params:((me=p.api_params)==null?void 0:me.trim())||void 0}:p.type==="text"?C.text_content=((ie=p.text_content)==null?void 0:ie.trim())||"":p.type==="data"?C.data_content=((H=p.data_content)==null?void 0:H.trim())||"":p.type==="image"&&(C.image_url=((c=p.image_url)==null?void 0:c.trim())||""),await dt(k.id,C),d(!1),Ue().then(t)}catch(C){console.error("更新卡密失败:",C),alert("更新失败,请重试")}}},$=async i=>{if(confirm("确认删除该卡密吗?"))try{await rl(i),Ue().then(t)}catch(E){console.error("删除卡密失败:",E),alert("删除失败,请重试")}},z=async()=>{if(!f.name.trim()){alert("请输入卡密名称");return}if(!f.content.trim()){alert(f.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const i={name:f.name.trim(),type:f.type,description:f.description.trim(),enabled:f.enabled,delay_seconds:f.delay_seconds};f.type==="text"&&(i.text_content=f.content.trim()),f.type==="data"&&(i.data_content=f.content.trim()),f.type==="image"&&(i.image_url=f.content.trim()),f.type==="api"&&(i.api_config={url:f.content.trim(),method:f.api_method,timeout:f.api_timeout,headers:f.api_headers.trim()||void 0,params:f.api_params.trim()||void 0}),await ll(i),b(!1),Q(bt()),Ue().then(t)}catch(i){console.error("添加卡密失败:",i),alert("添加失败,请重试")}},X=async i=>{try{await dt(i.id,{...i,enabled:!i.enabled}),Ue().then(t)}catch(E){console.error("切换状态失败:",E)}},m=async i=>{try{await navigator.clipboard.writeText(String(i)),alert(`已复制卡密组ID:${i}`)}catch{prompt("复制卡密组ID",String(i))}},_=s.filter(i=>i.type==="data"),N=()=>{const w=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001
-VIP-MONTH-002
-VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(H=>H.map(c=>`"${String(c).replace(/"/g,'""')}"`).join(",")).join(`
-`),G=new Blob(["\uFEFF"+w],{type:"text/csv;charset=utf-8"}),me=URL.createObjectURL(G),ie=document.createElement("a");ie.href=me,ie.download="卡密组批量导入模板.csv",document.body.appendChild(ie),ie.click(),ie.remove(),URL.revokeObjectURL(me)},y=async()=>{if(K){B(!0),ne(null);try{const i=await nl(K);if(ne(i),i.created>0){const E=await Ue();t(E)}}catch(i){ne({error:(i==null?void 0:i.message)||"上传失败"})}finally{B(!1)}}},P=async()=>{if(!(!D||!W.trim())){B(!0),L(null);try{const i=await il(D,W);L({added:i.added}),A("");const E=await Ue();t(E)}catch(i){alert("追加失败:"+((i==null?void 0:i.message)||"未知错误"))}finally{B(!1)}}},M=()=>{var i;S("create"),de(null),ne(null),Z((i=_[0])!=null&&i.id?String(_[0].id):""),A(""),L(null),U(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:M,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(hs,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>b(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(Ge,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-8 py-5 w-[18%]",children:"卡密名称"}),e.jsx("th",{className:"px-6 py-5 w-[12%]",children:"卡密组ID"}),e.jsx("th",{className:"px-6 py-5 w-[10%]",children:"类型"}),e.jsx("th",{className:"px-6 py-5 w-[22%]",children:"内容/库存"}),e.jsx("th",{className:"px-6 py-5 w-[18%]",children:"描述"}),e.jsx("th",{className:"px-6 py-5 w-[10%]",children:"状态"}),e.jsx("th",{className:"px-6 py-5 w-[10%] text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:s.map(i=>{let E="";return i.type==="data"&&i.data_content?E=`库存: ${i.data_content.split(`
-`).filter(G=>G.trim()).length} 条`:i.type==="text"&&i.text_content?E=i.text_content.substring(0,20)+(i.text_content.length>20?"...":""):i.type==="api"&&i.api_config?E=i.api_config.url:i.type==="image"&&i.image_url&&(E="图片链接"),e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-8 py-5",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-gray-50 rounded-xl group-hover:bg-white transition-colors",children:e.jsx(te,{type:i.type})}),e.jsx("span",{className:"font-bold text-gray-900",children:i.name})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("button",{onClick:()=>m(i.id),className:"inline-flex items-center gap-2 rounded-xl bg-gray-100 px-3 py-2 font-mono text-xs font-extrabold text-gray-700 hover:bg-gray-200 transition-colors",title:"复制卡密组ID,用于批量铺货表格",children:[i.id,e.jsx(na,{className:"w-3.5 h-3.5"})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${i.type==="text"?"bg-blue-50 text-blue-600":i.type==="data"?"bg-purple-50 text-purple-600":i.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:i.type==="text"?"文本":i.type==="data"?"批量":i.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:"text-sm text-gray-600 font-mono block truncate",title:E,children:E})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("span",{className:"text-sm text-gray-500 block max-w-[200px] truncate",title:i.description||"-",children:i.description||"-"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx("button",{onClick:()=>X(i),className:`w-12 h-8 rounded-full relative transition-colors ${i.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${i.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("button",{onClick:()=>T(i),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(cs,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>$(i.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",children:e.jsx(Ve,{className:"w-5 h-5"})})]})})]},i.id)})})]})}),s.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(At,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:"暂无卡密配置,请点击右上角添加。"})]})]}),l&&k&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>d(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:p.name||"",onChange:i=>R({...p,name:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:p.type||"text",onChange:i=>R({...p,type:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(k==null?void 0:k.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),p.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:p.api_url||"",onChange:i=>R({...p,api_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求方法"}),e.jsxs("select",{value:p.api_method||"GET",onChange:i=>R({...p,api_method:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"超时时间(秒)"}),e.jsx("input",{type:"number",value:p.api_timeout||10,onChange:i=>R({...p,api_timeout:parseInt(i.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"60"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求头(JSON 格式)"}),e.jsx("textarea",{value:p.api_headers||"",onChange:i=>R({...p,api_headers:i.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"}'})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求参数(JSON 格式)"}),e.jsx("textarea",{value:p.api_params||"",onChange:i=>R({...p,api_params:i.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}'})]})]}),p.type==="text"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"固定文字配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"文字内容"}),e.jsx("textarea",{value:p.text_content||"",onChange:i=>R({...p,text_content:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none",placeholder:"请输入要发送的固定文字内容..."})]})]}),p.type==="data"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"批量数据配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"数据内容(一行一个)"}),e.jsx("textarea",{value:p.data_content||"",onChange:i=>R({...p,data_content:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-80 resize-none font-mono text-sm",placeholder:`请输入数据,每行一个:
-卡号1:密码1
-卡号2:密码2
-或者
-兑换码1
-兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:p.data_content?p.data_content.split(`
-`).filter(i=>i.trim()).length:0})," 条"]})]})]}),p.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:p.image_url||"",onChange:i=>R({...p,image_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),p.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:p.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:i=>{i.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:p.delay_seconds||0,onChange:i=>R({...p,delay_seconds:parseInt(i.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:p.description||"",onChange:i=>R({...p,description:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>R({...p,enabled:!p.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${p.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${p.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>d(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:h,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),u&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>b(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:f.name,onChange:i=>Q({...f,name:i.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>Q({...f,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(Fs,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>Q({...f,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(st,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>Q({...f,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${f.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(tt,{className:"w-5 h-5 mx-auto mb-1"}),"图片"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:f.type==="data"?"库存内容(一行一个)":f.type==="text"?"固定回复内容":f.type==="image"?"图片 URL":"API 地址"}),f.type==="api"?e.jsx("input",{type:"url",value:f.content,onChange:i=>Q({...f,content:i.target.value}),placeholder:"https://api.example.com/get-code",className:"w-full ios-input px-4 py-3 rounded-xl"}):f.type==="image"?e.jsx("input",{type:"url",value:f.content,onChange:i=>Q({...f,content:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://example.com/card.png"}):e.jsx("textarea",{value:f.content,onChange:i=>Q({...f,content:i.target.value}),className:`w-full ios-input px-4 py-3 rounded-xl resize-none text-sm ${f.type==="data"?"h-48 font-mono":"h-32"}`,placeholder:f.type==="data"?`CODE-123456
-CODE-789012
-...`:"请输入每次发货时发送的固定文字"}),f.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-[#0094f7]",children:f.content.split(`
-`).filter(i=>i.trim()).length})," 条"]})]}),f.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:f.api_method,onChange:i=>Q({...f,api_method:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:f.api_timeout,onChange:i=>Q({...f,api_timeout:parseInt(i.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:f.api_headers,onChange:i=>Q({...f,api_headers:i.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"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:f.api_params,onChange:i=>Q({...f,api_params:i.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}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:f.description,onChange:i=>Q({...f,description:i.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:f.delay_seconds,onChange:i=>Q({...f,delay_seconds:parseInt(i.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>b(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:z,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ge,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),se&&ke.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>U(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>S("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${J==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(ia,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>S("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${J==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(hs,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),J==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:N,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm transition-colors",children:[e.jsx(oa,{className:"w-4 h-4"}),"下载模板"]}),e.jsxs("label",{className:"flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm cursor-pointer transition-colors",children:[e.jsx(hs,{className:"w-4 h-4"}),K?K.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:i=>{var E;return de(((E=i.target.files)==null?void 0:E[0])||null)}})]})]}),le&&!le.error&&e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-2",children:[e.jsxs("div",{className:"text-sm font-bold text-gray-900",children:["共 ",le.total," 行 · 成功 ",le.created," · 失败 ",le.failed]}),le.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:le.rows.filter(i=>!i.success).map(i=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",i.row_no," 行「",i.name,"」:",i.error]},i.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:_.length===0?e.jsx("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800",children:"暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"选择卡密组"}),e.jsx("select",{value:D,onChange:i=>Z(i.target.value),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:_.map(i=>e.jsxs("option",{value:String(i.id),children:[i.name,"(ID: ",i.id,")"]},i.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"卡密号(每行一个)"}),e.jsx("textarea",{value:W,onChange:i=>A(i.target.value),placeholder:`VIP-001
-VIP-002
-VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),Y&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",Y.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>U(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),J==="create"?e.jsxs("button",{onClick:y,disabled:!K||q,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[q?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(hs,{className:"w-4 h-4"}),q?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:P,disabled:!D||!W.trim()||q||_.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[q?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(Ge,{className:"w-4 h-4"}),q?"处理中...":"追加卡密"]})]})]})}),document.body)]})},er=s=>s.find(t=>t.status==="running"||t.status==="canceling"),sr=s=>{const t=String(s||"").trim();return t?/^[¥¥]/.test(t)?t:`¥${t}`:"-"},tr=({onConfigureDelivery:s})=>{const[t,l]=n.useState([]),[d,u]=n.useState([]),[b,k]=n.useState([]),[O,p]=n.useState(""),[R,f]=n.useState(!1),[Q,se]=n.useState(!1),[U,J]=n.useState(!1),[S,K]=n.useState(!1),[de,le]=n.useState(!1),[ne,q]=n.useState(!1),[B,D]=n.useState(!1),[Z,W]=n.useState("upload"),[A,Y]=n.useState(null),[L,te]=n.useState(null),[T,h]=n.useState(null),[$,z]=n.useState(null),[X,m]=n.useState(null),_=n.useRef(!1),[N,y]=n.useState(null),[P,M]=n.useState({}),[i,E]=n.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[w,G]=n.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[me,ie]=n.useState([]);n.useEffect(()=>{if(!ne||w.images.length===0){ie([]);return}const r=w.images.map((I,ce)=>({key:I.name+ce,url:URL.createObjectURL(I)}));return ie(r),()=>{r.forEach(I=>URL.revokeObjectURL(I.url))}},[ne,w.images]);const H=async()=>{const r=await ds();l(r)},c=async()=>{u(await ks())};n.useEffect(()=>{Promise.all([Vs(),ds(),ks(),xt(20)]).then(([r,I,ce,Qe])=>{k(r),l(I),u(ce);const ze=Qe.find(Ie=>["running","canceling"].includes(Ie.status))||Qe.find(Ie=>Ie.status!=="preview");m(ze||null)}).catch(r=>console.error("加载商品配置失败:",r))},[]),n.useEffect(()=>{if(!B||!($!=null&&$.id)||!["running","canceling"].includes($.status))return;const r=window.setInterval(async()=>{if(!_.current){_.current=!0;try{const I=await as($.id);z(I),m(I),["running","canceling"].includes(I.status)||(W("done"),await H(),await c())}catch(I){console.error("刷新批量铺货进度失败:",I)}finally{_.current=!1}}},3e3);return()=>{window.clearInterval(r)}},[B,$==null?void 0:$.id,$==null?void 0:$.status]);const C=async()=>{if(!O)return alert("请先选择账号");f(!0);try{const r=await ol(O);await H(),alert((r==null?void 0:r.message)||"商品同步完成")}catch(r){console.error("同步商品失败:",r),alert((r==null?void 0:r.message)||"同步失败,请重试")}finally{f(!1)}},oe=r=>{y(r),M({...r}),K(!0)},be=async()=>{if(N)try{await bl(N.cookie_id,N.item_id,{item_title:P.item_title||"",item_description:P.item_description||"",item_category:P.item_category||"",item_price:P.item_price||"",item_detail:P.item_detail||N.item_detail||""}),await H(),await c(),K(!1),y(null)}catch(r){console.error("更新商品失败:",r),alert("更新失败,请重试")}},ye=async r=>{if(confirm(`确认删除商品"${r.item_title}"吗?`))try{await cl(r.cookie_id,r.item_id),l(I=>I.filter(ce=>!(ce.cookie_id===r.cookie_id&&ce.item_id===r.item_id)))}catch(I){console.error("删除商品失败:",I),alert("删除失败,请重试")}},Se=async()=>{try{if(!i.cookie_id||!i.item_id){alert("请选择账号并填写商品ID");return}await dl(i.cookie_id,{item_id:i.item_id,item_title:i.item_title,item_price:i.item_price,item_detail:i.item_image?JSON.stringify({item_image:i.item_image}):""}),await H(),le(!1),E({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(r){console.error("添加商品失败:",r),alert("添加失败,请重试")}},ve=async()=>{if(!w.cookie_id)return alert("请选择发布账号");if(!w.title.trim())return alert("请填写商品标题");if(!w.price.trim())return alert("请填写商品价格");if(!w.quantity||Number(w.quantity)<=0)return alert("库存数量必须大于 0");if(w.images.length===0)return alert("至少上传 1 张商品图片");if(w.postage_mode==="fixed"&&!w.postage.trim())return alert("请填写一口价邮费");se(!0);try{const r=await xl(w);if(await H(),q(!1),G({cookie_id:O||"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),r!=null&&r.item_id){const I={id:r.item_id,cookie_id:w.cookie_id,item_id:r.item_id,item_title:r.item_title||w.title,item_price:r.item_price||w.price,item_image:r.item_image};s(I),alert("商品发布成功,ID: "+r.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(r){console.error("发布商品失败:",r);const I=r==null?void 0:r.payload;if((I==null?void 0:I.code)==="stock_permission_missing"){alert("发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。");return}alert((r==null?void 0:r.message)||"发布失败,请重试")}finally{se(!1)}},fe=async()=>{W("upload"),h(null),z(null),Y(null),te(null),D(!0),J(!0);try{const r=await xt(20),I=er(r);if(I!=null&&I.id){const ce=await as(I.id);m(ce),z(ce),W(["running","canceling"].includes(ce.status)?"running":"done")}}catch(r){console.error("恢复最近批量铺货任务失败:",r)}finally{J(!1)}},De=async()=>{if(X!=null&&X.id){J(!0),D(!0);try{const r=await as(X.id);z(r),W(["running","canceling"].includes(r.status)?"running":"done")}catch(r){console.error("加载最近批量铺货结果失败:",r)}finally{J(!1)}}},ue=async()=>{if(!A)return alert("请先上传商品表格");if(!O)return alert("请先选择默认发布账号");J(!0);try{const r=await ml({file:A,imagesZip:L,defaultCookieId:O});h(r),z(null),W("preview")}catch(r){console.error("批量铺货预检失败:",r),alert((r==null?void 0:r.message)||"预检失败,请检查表格和图片 zip")}finally{J(!1)}},Ae=async()=>{if(T!=null&&T.preview_id){if(T.valid<=0)return alert("没有可发布的商品行");J(!0);try{const r=await ul(T.preview_id),I=await as(r.batch_id||T.preview_id);z(I),m(I),W(I.status==="running"?"running":"done")}catch(r){console.error("启动批量铺货失败:",r),alert((r==null?void 0:r.message)||"启动发布任务失败")}finally{J(!1)}}},Re=async()=>{if($!=null&&$.id&&confirm("确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。")){J(!0);try{const r=await hl($.id),I=await as($.id);z(I),W((r==null?void 0:r.status)==="canceling"||I.status==="canceling"?"running":"done")}catch(r){alert((r==null?void 0:r.message)||"取消失败")}finally{J(!1)}}},Fe=async()=>{const r=T==null?void 0:T.preview_id;if(r&&Z==="preview")try{await pl(r)}catch(I){console.error("清理批量铺货预检失败:",I)}h(null),W("upload")},Ke=async()=>{await Fe(),D(!1)},Ye=async()=>{if($!=null&&$.id){J(!0);try{await gl($.id),z(await as($.id)),W("running")}catch(r){alert((r==null?void 0:r.message)||"重试失败")}finally{J(!1)}}},x=()=>{const ce=[["账号ID","标题","描述","价格","原价","库存","邮费模式","邮费","图片","付款发货启用","付款发货内容","评价赠品启用","评价赠品内容","求评价启用","求评价等待小时","求评价文案","求评价最多次数"],...[["","会员组合包自动发货","下单后发送主卡和附赠卡。","19.90","29.90","10","free","","images/bundle-1.jpg;images/bundle-2.jpg","是","101:1;102:1","是","201:1;202:2","是","72","亲,满意的话麻烦给个评价,谢谢~","1"],["","普通商品","仅发布商品,不创建自动化规则。","49.90","","10","fixed","8.00","https://example.com/product.jpg","否","","否","","否","","",""]]].map(ss=>ss.map(a=>`"${String(a).replace(/"/g,'""')}"`).join(",")).join(`
-`),Qe=new Blob(["\uFEFF"+ce],{type:"text/csv;charset=utf-8"}),ze=URL.createObjectURL(Qe),Ie=document.createElement("a");Ie.href=ze,Ie.download="批量铺货模板.csv",document.body.appendChild(Ie),Ie.click(),Ie.remove(),URL.revokeObjectURL(ze)},V=()=>{E(r=>({...r,cookie_id:O||r.cookie_id})),le(!0)},he=()=>{G(r=>({...r,cookie_id:O||r.cookie_id})),q(!0)},Ce=r=>d.filter(I=>I.cookie_id===r.cookie_id&&I.item_id===r.item_id).length>0?d.filter(I=>I.cookie_id===r.cookie_id&&I.item_id===r.item_id):d.filter(I=>I.cookie_id===r.cookie_id&&!I.item_id),Be=r=>{switch(r){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return r||"-"}},Te=r=>{switch(r){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("select",{className:"ios-input px-4 py-3 rounded-xl text-sm",value:O,onChange:r=>p(r.target.value),children:[e.jsx("option",{value:"",children:"选择账号以同步"}),b.map(r=>e.jsx("option",{value:r.id,children:r.nickname},r.id))]}),e.jsxs("button",{onClick:C,disabled:R||!O,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(qe,{className:`w-4 h-4 ${R?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:V,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(Ge,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:he,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-600 text-white hover:bg-emerald-700 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(As,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void fe(),className:"px-5 py-3 rounded-2xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(ys,{className:"w-4 h-4"}),X&&["running","canceling"].includes(X.status)?"继续批量任务":"批量铺货"]}),X&&!["running","canceling"].includes(X.status)&&e.jsx("button",{onClick:()=>void De(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[t.map(r=>{const I=Ce(r),ce=I.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-col",children:[e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[e.jsx("button",{onClick:()=>oe(r),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-[#0094f7] hover:text-white transition-colors",title:"编辑",children:e.jsx(cs,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>ye(r),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors",title:"删除",children:e.jsx(Ve,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"aspect-square bg-gray-100 rounded-xl mb-2.5 overflow-hidden relative",children:[r.item_image?e.jsx("img",{src:r.item_image,alt:"",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(Ct,{className:"w-8 h-8"})}),e.jsx("div",{className:"absolute top-1.5 left-1.5 bg-black/50 backdrop-blur-md text-white text-[10px] font-bold px-1.5 py-0.5 rounded-md",children:sr(r.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:r.item_title}),e.jsxs("div",{className:"flex justify-between items-center text-[10px] text-gray-500 mb-2",children:[e.jsxs("span",{className:"bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]",children:["ID: ",r.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${ce?"text-emerald-600":"text-amber-600"}`,children:[ce?e.jsx($t,{className:"w-3 h-3"}):e.jsx(da,{className:"w-3 h-3"}),ce?`${I.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:()=>s(r),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${ce?"bg-gray-900 text-white hover:bg-black":"bg-[#0094f7] text-white hover:bg-[#0071e3] shadow-md shadow-blue-100"}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(xa,{className:"w-3.5 h-3.5"}),ce?"查看发货规则":"关联发货规则"]}),e.jsx(qs,{className:"w-3.5 h-3.5"})]})})]},`${r.cookie_id}-${r.item_id}`)}),t.length===0&&e.jsxs("div",{className:"col-span-full py-20 text-center text-gray-400",children:[e.jsx(kt,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),"暂无商品数据,请选择账号进行同步"]})]}),S&&N&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"560px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"编辑商品"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["ID: ",N.item_id]})]}),e.jsx("button",{onClick:()=>K(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"商品标题",value:P.item_title||"",onChange:r=>M({...P,item_title:r.target.value})}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"价格",value:P.item_price||"",onChange:r=>M({...P,item_price:r.target.value})}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"分类",value:P.item_category||"",onChange:r=>M({...P,item_category:r.target.value})}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述",value:P.item_description||"",onChange:r=>M({...P,item_description:r.target.value})})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:be,className:"w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4"}),"保存"]})})]})}),document.body),de&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"720px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"添加商品"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"手动建立商品与自动发货规则的关联"})]}),e.jsx("button",{onClick:()=>le(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"所属账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:i.cookie_id,onChange:r=>E({...i,cookie_id:r.target.value}),children:[e.jsx("option",{value:"",children:"选择账号"}),b.map(r=>e.jsx("option",{value:r.id,children:r.nickname||r.remark||r.id},r.id))]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品 ID"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入闲鱼商品 ID",value:i.item_id,onChange:r=>E({...i,item_id:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品价格"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如 99.00",value:i.item_price,onChange:r=>E({...i,item_price:r.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品标题"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入商品标题",value:i.item_title,onChange:r=>E({...i,item_title:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"图片 URL"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://...",value:i.item_image,onChange:r=>E({...i,item_image:r.target.value})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:Se,className:"w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ge,{className:"w-4 h-4"}),"添加商品"]})})]})}),document.body),ne&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"820px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"发布商品到闲鱼"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"普通单规格发布;库存数量会写入闲鱼发布参数,用于判断账号库存能力。"})]}),e.jsx("button",{onClick:()=>q(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx("div",{className:"rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800 leading-6",children:"发布时必须填写库存。若账号没有库存发布能力,后端会返回明确的“库存权限不足”错误,不会误报为普通发布失败。"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"发布账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:w.cookie_id,onChange:r=>G({...w,cookie_id:r.target.value}),children:[e.jsx("option",{value:"",children:"选择账号"}),b.map(r=>e.jsx("option",{value:r.id,children:r.nickname||r.remark||r.id},r.id))]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品标题"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:会员月卡自动发货",value:w.title,onChange:r=>G({...w,title:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"库存数量"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",type:"number",min:"1",placeholder:"必须大于 0",value:w.quantity,onChange:r=>G({...w,quantity:r.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品描述"}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述会用于自动识别类目;留空时使用标题",value:w.description,onChange:r=>G({...w,description:r.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"售价"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"99.00",value:w.price,onChange:r=>G({...w,price:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"原价(可选)"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"129.00",value:w.original_price,onChange:r=>G({...w,original_price:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"运费方式"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:w.postage_mode,onChange:r=>G({...w,postage_mode:r.target.value}),children:[e.jsx("option",{value:"free",children:"包邮"}),e.jsx("option",{value:"distance",children:"按距离计费"}),e.jsx("option",{value:"fixed",children:"一口价邮费"}),e.jsx("option",{value:"none",children:"无需邮寄"})]})]})]}),w.postage_mode==="fixed"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"一口价邮费"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如 8.00",value:w.postage,onChange:r=>G({...w,postage:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品图片(1-9 张)"}),e.jsxs("label",{className:"flex min-h-[120px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50/50 transition-colors",children:[e.jsx(ys,{className:"w-8 h-8 text-emerald-600 mb-2"}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"选择图片"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:w.images.length?"已选择 "+w.images.length+" 张":"支持 JPG / PNG / GIF"}),e.jsx("input",{className:"hidden",type:"file",accept:"image/*",multiple:!0,onChange:r=>G({...w,images:Array.from(r.target.files||[]).slice(0,9)})})]}),me.length>0&&e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-3",children:me.map(r=>e.jsx("div",{className:"aspect-square rounded-xl bg-gray-100 overflow-hidden border border-gray-100",children:e.jsx("img",{src:r.url,alt:"",className:"w-full h-full object-cover"})},r.key))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{disabled:Q,onClick:ve,className:"w-full bg-emerald-600 hover:bg-emerald-700 disabled:opacity-60 text-white px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(As,{className:"w-4 h-4"}),Q?"正在发布...":"发布到闲鱼"]})})]})}),document.body),B&&ke.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"980px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量铺货"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"上传商品表格和图片 zip,先预检,再逐条发布到闲鱼。"})]}),e.jsx("button",{onClick:()=>void Ke(),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx("div",{className:"grid grid-cols-4 gap-2",children:[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]].map(([r,I])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${Z===r?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:I},r))}),Z==="upload"&&e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 p-4 text-sm text-blue-900 leading-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:"先下载模板,再按字段填写。"}),e.jsxs("div",{children:["图片字段写 zip 内相对路径,多个图片用英文分号分隔,例如 ",e.jsx("span",{className:"font-mono font-bold",children:"images/a.jpg;images/b.jpg"}),"。也支持直接填写图片 URL。"]})]}),e.jsx("button",{type:"button",onClick:x,className:"shrink-0 rounded-xl bg-blue-600 px-4 py-2 text-sm font-extrabold text-white hover:bg-blue-700",children:"下载CSV模板"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"默认发布账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:O,onChange:r=>p(r.target.value),children:[e.jsx("option",{value:"",children:"选择账号"}),b.map(r=>e.jsx("option",{value:r.id,children:r.nickname||r.remark||r.id},r.id))]}),e.jsx("p",{className:"text-xs text-gray-500",children:"表格中“账号ID”为空时,会使用这里选择的账号。"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-blue-300 hover:bg-blue-50 transition-colors",children:[e.jsx(ys,{className:"w-9 h-9 text-blue-600 mb-3"}),e.jsx("span",{className:"text-sm font-extrabold text-gray-900",children:"上传商品表格"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:A?A.name:"支持 .xlsx / .csv / .tsv"}),e.jsx("input",{className:"hidden",type:"file",accept:".xlsx,.csv,.tsv",onChange:r=>{var I;return Y(((I=r.target.files)==null?void 0:I[0])||null)}})]}),e.jsxs("label",{className:"flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50 transition-colors",children:[e.jsx(ys,{className:"w-9 h-9 text-emerald-600 mb-3"}),e.jsx("span",{className:"text-sm font-extrabold text-gray-900",children:"上传图片 zip(可选)"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:L?L.name:"表格图片字段使用 zip 内相对路径"}),e.jsx("input",{className:"hidden",type:"file",accept:".zip",onChange:r=>{var I;return te(((I=r.target.files)==null?void 0:I[0])||null)}})]})]}),e.jsxs("div",{className:"rounded-2xl bg-gray-50 border border-gray-100 p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"字段说明"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"照着下面的“什么时候填写”处理即可。预检发现问题时,会指出具体哪一行需要修改。"})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 text-xs text-blue-950",children:[e.jsx("div",{className:"text-sm font-extrabold",children:"“付款后发送的卡密”怎么填"}),e.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-3 lg:grid-cols-3",children:[e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101"}),e.jsx("p",{className:"mt-1 leading-5",children:"从卡密组 101 立即发送 1 份。卡密组 ID 可以在“卡密库存”页面查看。"})]}),e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101:2"}),e.jsx("p",{className:"mt-1 leading-5",children:"每购买 1 件,就从卡密组 101 发送 2 份。买家购买 3 件时会发送 6 份。"})]}),e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101:1:0;102:2:3"}),e.jsx("p",{className:"mt-1 leading-5",children:"先立即发送卡密组 101 的 1 份,再等待 3 秒发送卡密组 102 的 2 份。"})]})]}),e.jsxs("p",{className:"mt-3 leading-5 text-blue-800",children:["每一组依次写“卡密组 ID : 每件发送几份 : 等待几秒”。份数不写时按 1 份处理,等待时间不写时立即发送。需要发送多种卡密时,用英文分号 ",e.jsx("code",{className:"font-bold",children:";"})," 隔开。"]})]}),e.jsx("div",{className:"overflow-x-auto rounded-xl border border-gray-100 bg-white",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"字段"}),e.jsx("th",{className:"px-3 py-2",children:"什么时候填写"}),e.jsx("th",{className:"px-3 py-2",children:"填写方法"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50 text-gray-700",children:[["账号ID","没有在上方选择默认账号时填写","填写账号 ID;已经选择默认账号时可以留空"],["标题","每个商品都要填","填写买家能看到的商品标题"],["描述","可以留空","留空时会使用商品标题作为描述"],["价格","每个商品都要填","只填数字,例如 19.90"],["原价","可以留空","需要展示划线原价时填写,例如 29.90"],["库存","可以留空","留空按 1 件处理;填写时必须大于 0"],["邮费模式","可以留空","留空表示包邮;包邮填 free,固定邮费填 fixed"],["邮费","邮费模式填 fixed 时填写","只填数字,例如 8.00"],["图片","每个商品都要填","填写 zip 内图片路径或图片网址;多张图片用英文分号隔开"],["付款发货启用","需要付款后自动发货时填写","填“是”表示开启;不需要时填“否”或留空"],["付款发货内容","“付款发货启用”填“是”时填写","从“卡密库存”页面取得卡密组 ID,按上方示例填写"],["评价赠品启用","需要评价赠品时填写","填“是”表示开启;不需要时填“否”或留空"],["评价赠品内容","“评价赠品启用”填“是”时填写","格式和付款发货内容相同,也可以同时发送多个卡密组"],["求评价启用","需要自动求评价时填写","填“是”表示开启;不需要时填“否”或留空"],["求评价等待小时","“求评价启用”填“是”时填写","填写等待小时数;留空按 72 小时处理"],["求评价文案","“求评价启用”填“是”时填写","填写要发送给买家的求评价消息"],["求评价最多次数","可以留空","留空只提醒 1 次"]].map(([r,I,ce])=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-bold text-gray-900 whitespace-nowrap",children:r}),e.jsx("td",{className:`px-3 py-2 min-w-[210px] font-bold ${I==="每个商品都要填"?"text-red-600":I==="可以留空"?"text-gray-500":"text-amber-700"}`,children:I}),e.jsx("td",{className:"px-3 py-2 min-w-[260px]",children:ce})]},r))})]})})]})]}),Z==="preview"&&T&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"rounded-2xl bg-gray-50 p-4 border border-gray-100",children:[e.jsx("div",{className:"text-xs font-bold text-gray-500",children:"总行数"}),e.jsx("div",{className:"text-2xl font-extrabold text-gray-900 mt-1",children:T.total})]}),e.jsxs("div",{className:"rounded-2xl bg-emerald-50 p-4 border border-emerald-100",children:[e.jsx("div",{className:"text-xs font-bold text-emerald-700",children:"可发布"}),e.jsx("div",{className:"text-2xl font-extrabold text-emerald-700 mt-1",children:T.valid})]}),e.jsxs("div",{className:"rounded-2xl bg-red-50 p-4 border border-red-100",children:[e.jsx("div",{className:"text-xs font-bold text-red-700",children:"有问题"}),e.jsx("div",{className:"text-2xl font-extrabold text-red-700 mt-1",children:T.invalid})]})]}),e.jsx("div",{className:"max-h-[380px] overflow-y-auto rounded-2xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"行号"}),e.jsx("th",{className:"px-4 py-3",children:"状态"}),e.jsx("th",{className:"px-4 py-3",children:"标题"}),e.jsx("th",{className:"px-4 py-3",children:"价格/库存"}),e.jsx("th",{className:"px-4 py-3",children:"图片"}),e.jsx("th",{className:"px-4 py-3",children:"问题"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:T.rows.map(r=>{var I,ce;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:r.row_no}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${r.valid?"bg-emerald-50 text-emerald-700 border-emerald-100":"bg-red-50 text-red-700 border-red-100"}`,children:r.valid?"可发布":"需修正"})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[240px] truncate",children:r.title||"-"}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:["¥",r.price||"-"," / ",r.quantity||1]}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:[((I=r.images)==null?void 0:I.length)||0," 张"]}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[280px]",children:((ce=r.errors)==null?void 0:ce.join(";"))||"-"})]},r.row_no)})})]})})]}),(Z==="running"||Z==="done")&&$&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("div",{className:`rounded-2xl p-4 border ${Te($.status)}`,children:[e.jsx("div",{className:"text-xs font-bold opacity-70",children:"任务状态"}),e.jsx("div",{className:"text-xl font-extrabold mt-1",children:Be($.status)})]}),e.jsxs("div",{className:"rounded-2xl bg-gray-50 p-4 border border-gray-100",children:[e.jsx("div",{className:"text-xs font-bold text-gray-500",children:"总数"}),e.jsx("div",{className:"text-xl font-extrabold text-gray-900 mt-1",children:$.total})]}),e.jsxs("div",{className:"rounded-2xl bg-emerald-50 p-4 border border-emerald-100",children:[e.jsx("div",{className:"text-xs font-bold text-emerald-700",children:"成功"}),e.jsx("div",{className:"text-xl font-extrabold text-emerald-700 mt-1",children:$.success})]}),e.jsxs("div",{className:"rounded-2xl bg-red-50 p-4 border border-red-100",children:[e.jsx("div",{className:"text-xs font-bold text-red-700",children:"失败"}),e.jsx("div",{className:"text-xl font-extrabold text-red-700 mt-1",children:$.failed})]}),e.jsxs("div",{className:"rounded-2xl bg-blue-50 p-4 border border-blue-100",children:[e.jsx("div",{className:"text-xs font-bold text-blue-700",children:"等待"}),e.jsx("div",{className:"text-xl font-extrabold text-blue-700 mt-1",children:$.pending})]})]}),e.jsx("div",{className:"max-h-[420px] overflow-y-auto rounded-2xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"行号"}),e.jsx("th",{className:"px-4 py-3",children:"状态"}),e.jsx("th",{className:"px-4 py-3",children:"标题"}),e.jsx("th",{className:"px-4 py-3",children:"商品ID"}),e.jsx("th",{className:"px-4 py-3",children:"错误原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:$.rows.map(r=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:r.row_no}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${Te(r.status)}`,children:Be(r.status)})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[260px] truncate",children:r.title}),e.jsx("td",{className:"px-4 py-3 text-xs font-mono",children:r.item_url?e.jsx("a",{href:r.item_url,target:"_blank",rel:"noreferrer",className:"text-blue-600 hover:underline",children:r.item_id}):r.item_id||"-"}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[340px]",children:r.error_message||"-"})]},r.id))})]})})]})]}),e.jsxs("div",{className:"modal-footer",children:[Z==="upload"&&e.jsxs("button",{disabled:U||!A||!O,onClick:ue,className:"w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(qe,{className:`w-4 h-4 ${U?"animate-spin":""}`}),U?"正在预检...":"开始预检"]}),Z==="preview"&&T&&e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{disabled:U,onClick:()=>void Fe(),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold",children:"返回修改"}),e.jsxs("button",{disabled:U||T.valid<=0,onClick:Ae,className:"flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(As,{className:"w-4 h-4"}),U?"启动中...":`确认发布 ${T.valid} 个商品`]})]}),(Z==="running"||Z==="done")&&$&&e.jsxs("div",{className:"flex gap-3 w-full",children:[$.status==="running"?e.jsx("button",{disabled:U,onClick:Re,className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"取消任务"}):$.status==="canceling"?e.jsx("button",{disabled:!0,className:"flex-1 px-6 py-3.5 rounded-xl bg-amber-100 text-amber-800 font-bold",children:"正在保存远端结果并安全取消…"}):e.jsx("button",{onClick:()=>window.open(`/items/publish-batches/${$.id}/result.csv`,"_blank"),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"下载结果"}),$.retryable>0&&!["running","canceling"].includes($.status)&&e.jsxs("button",{disabled:U,onClick:Ye,className:"flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(qe,{className:`w-4 h-4 ${U?"animate-spin":""}`}),"重试失败项"]}),!["running","canceling"].includes($.status)&&e.jsx("button",{onClick:()=>{D(!1),H(),c()},className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold",children:"完成"})]})]})]})}),document.body)]})},yt="https://dashscope.aliyuncs.com/compatible-mode/v1",ar=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],lr=new Set(["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),rr=()=>{const[s,t]=n.useState(null),[l,d]=n.useState(!1),[u,b]=n.useState(""),[k,O]=n.useState(!1),[p,R]=n.useState([]),[f,Q]=n.useState(!1),[se,U]=n.useState(""),[J,S]=n.useState(!1),K=n.useRef(null),[de,le]=n.useState(!1),[ne,q]=n.useState(!1),[B,D]=n.useState(!1),[Z,W]=n.useState(!1),[A,Y]=n.useState(!1),[L,te]=n.useState(null),[T,h]=n.useState({new_username:"",current_password:"",new_password:"",confirm_password:""});n.useEffect(()=>{z(),Ft().then(y=>{y.username&&h(P=>({...P,new_username:y.username||""}))}).catch(()=>{})},[]),n.useEffect(()=>{const y=P=>{var M;(M=K.current)!=null&&M.contains(P.target)||S(!1)};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[]);const $=async(y,P=!1)=>{const M=y||s,i=(M==null?void 0:M.ai_api_url)||(M==null?void 0:M.ai_base_url)||yt;Q(!0),U("");try{const E=await Rl(i,(M==null?void 0:M.ai_api_key)||"");R(E),S(P&&E.length>0),!(M!=null&&M.ai_model)&&E.length>0&&t(w=>w&&{...w,ai_model:E[0]})}catch(E){R([]),S(!1),U(E.message||"读取模型失败")}finally{Q(!1)}},z=()=>{d(!0),b(""),qt().then(y=>{t(y),$(y)}).catch(y=>{t(null),b(y.message||"加载配置失败")}).finally(()=>d(!1))},X=async()=>{if(s){O(!0);try{const y=Object.fromEntries(Object.entries(s).filter(([P,M])=>!lr.has(P)&&M!==void 0&&M!==null));await Mt(y),alert("系统配置已保存")}catch(y){alert("保存失败:"+y.message)}finally{O(!1)}}},m=async y=>{y.preventDefault(),te(null);const P=T.new_username.trim();if(P.length<3){te({type:"error",text:"用户名至少需要 3 个字符"});return}if(!T.current_password){te({type:"error",text:"请输入当前密码确认身份"});return}if(T.new_password&&T.new_password.length<8){te({type:"error",text:"新密码至少需要 8 个字符"});return}if(T.new_password!==T.confirm_password){te({type:"error",text:"两次输入的新密码不一致"});return}Y(!0);try{const M=await Pa({current_password:T.current_password,new_username:P,new_password:T.new_password||void 0});if(!M.success){te({type:"error",text:M.message||"登录凭据更新失败"});return}te({type:"success",text:M.message||"登录凭据已更新"}),window.setTimeout(()=>window.location.reload(),1400)}catch(M){te({type:"error",text:M.message||"登录凭据更新失败"})}finally{Y(!1)}};if(!s)return e.jsx("div",{className:"p-8 text-center text-gray-400",children:u||(l?"加载配置中...":"暂无配置")});const _=s.ai_model||"",N=p;return e.jsxs("div",{className:"max-w-6xl mx-auto space-y-8 animate-fade-in pb-24",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 bg-gray-100 rounded-2xl flex items-center justify-center",children:e.jsx(zs,{className:"w-6 h-6 text-gray-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900",children:"系统设置"}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm font-medium",children:"配置全局自动化规则与系统参数"})]})]}),e.jsxs("button",{onClick:z,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(qe,{className:"w-4 h-4"}),"刷新"]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-100 text-gray-600",children:e.jsx(ma,{className:"w-4 h-4"})}),"基础设置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出等级"}),e.jsx("select",{value:s.log_level||"info",onChange:y=>t({...s,log_level:y.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:ar.map(y=>e.jsx("option",{value:y.value,children:y.label},y.value))}),e.jsx("p",{className:"text-xs text-gray-500",children:"等级越低输出越详细,Debug 适合排查问题"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出格式"}),e.jsxs("select",{value:s.log_format||"text",onChange:y=>t({...s,log_format:y.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"json",children:"JSON"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"JSON 适合接入集中式日志系统,保存后需重启服务生效"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"续期日志保留天数"}),e.jsx("input",{type:"number",value:s.renewal_log_retention_days??10,onChange:y=>t({...s,renewal_log_retention_days:parseInt(y.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"365"}),e.jsx("p",{className:"text-xs text-gray-500",children:"0 表示不自动清理续期日志"})]})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-[#0094f7] text-white",children:e.jsx(St,{className:"w-4 h-4"})}),"AI 智能回复配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API 地址"}),e.jsx("input",{type:"text",value:s.ai_api_url||yt,onChange:y=>t({...s,ai_api_url:y.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://api.openai.com/v1"}),e.jsx("p",{className:"text-xs text-gray-500",children:"无需补全 /chat/completions"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:de?"text":"password",value:s.ai_api_key||"",onChange:y=>t({...s,ai_api_key:y.target.value}),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",placeholder:"sk-..."}),e.jsx("button",{type:"button",onClick:()=>le(!de),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:de?e.jsx(ns,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"模型"}),e.jsxs("div",{ref:K,className:"relative flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{value:_,onFocus:()=>p.length>0&&S(!0),onChange:y=>{t({...s,ai_model:y.target.value}),p.length>0&&S(!0)},onKeyDown:y=>{y.key==="Escape"&&S(!1),y.key==="ArrowDown"&&p.length>0&&S(!0)},className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),e.jsx("button",{type:"button",onClick:()=>p.length>0&&S(y=>!y),disabled:p.length===0,className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 disabled:opacity-30","aria-label":"展开模型列表",children:e.jsx(ua,{className:`w-4 h-4 transition-transform ${J?"rotate-180":""}`})}),J&&e.jsx("div",{className:"absolute left-0 right-0 top-[calc(100%+6px)] z-40 max-h-64 overflow-y-auto rounded-xl border border-gray-200 bg-white shadow-xl shadow-gray-200/70 py-1",children:N.length>0?N.map(y=>e.jsxs("button",{type:"button",onClick:()=>{t({...s,ai_model:y}),S(!1)},className:"w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-[#0094f7] flex items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate",children:y}),y===_&&e.jsx(We,{className:"w-4 h-4 shrink-0 text-[#0094f7]"})]},y)):e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"没有匹配的模型"})})]}),e.jsxs("button",{type:"button",onClick:()=>$(void 0,!0),disabled:f,className:"px-4 py-3 rounded-xl bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-60 font-bold flex items-center justify-center gap-2 whitespace-nowrap",children:[e.jsx(qe,{className:`w-4 h-4 ${f?"animate-spin":""}`}),"读取模型"]})]}),se?e.jsx("p",{className:"text-xs text-red-500",children:se}):e.jsx("p",{className:"text-xs text-gray-500",children:p.length>0?`已从当前 API 地址读取到 ${p.length} 个模型`:"模型列表从当前 API 地址读取,也可以手动输入模型名"})]}),e.jsxs("div",{className:"p-3 bg-blue-50 rounded-xl text-xs text-blue-700",children:[e.jsx("strong",{children:"常见 AI 服务:"}),e.jsxs("ul",{className:"list-disc list-inside mt-1 space-y-0.5",children:[e.jsx("li",{children:"阿里云通义千问: https://dashscope.aliyuncs.com/compatible-mode/v1"}),e.jsx("li",{children:"OpenAI: https://api.openai.com/v1"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-amber-500 text-white",children:e.jsx(Ms,{className:"w-4 h-4"})}),"远程过滑块配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务地址"}),e.jsx("input",{type:"url",value:s["captcha.remote_service_url"]||"",onChange:y=>t({...s,"captcha.remote_service_url":y.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://example.com/internal/captcha/solve"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务秘钥"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:ne?"text":"password",value:s["captcha.remote_secret_key"]||"",onChange:y=>t({...s,"captcha.remote_secret_key":y.target.value}),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",autoComplete:"off"}),e.jsx("button",{type:"button",onClick:()=>q(!ne),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:ne?"隐藏秘钥":"显示秘钥",children:ne?e.jsx(ns,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-xl bg-amber-50 p-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:String(s["captcha.remote_pass_cookies"]||"").toLowerCase()==="true",onChange:y=>t({...s,"captcha.remote_pass_cookies":y.target.checked}),className:"mt-0.5 w-4 h-4 rounded border-gray-300"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-bold text-amber-900",children:"允许向远程服务传递账号 Cookie"}),e.jsx("span",{className:"block mt-1 text-xs text-amber-700",children:"默认关闭。仅在信任远程服务且需要由其自动重取过期验证链接时开启。"})]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"配置地址和秘钥后优先调用远程服务;只有网络不可用或超时才回退本机引擎,远程明确返回失败时不会重复触发本机验证。"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-900 text-white",children:e.jsx(at,{className:"w-4 h-4"})}),"登录凭据"]}),e.jsxs("form",{onSubmit:m,className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"登录用户名"}),e.jsxs("div",{className:"relative",children:[e.jsx(pa,{className:"absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",value:T.new_username,onChange:y=>h({...T,new_username:y.target.value}),className:"w-full ios-input pl-11 pr-4 py-3 rounded-xl text-sm",autoComplete:"username"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"当前密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:B?"text":"password",value:T.current_password,onChange:y=>h({...T,current_password:y.target.value}),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm",placeholder:"用于确认当前身份",autoComplete:"current-password"}),e.jsx("button",{type:"button",onClick:()=>D(!B),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:B?"隐藏密码":"显示密码",children:B?e.jsx(ns,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"新密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:Z?"text":"password",value:T.new_password,onChange:y=>h({...T,new_password:y.target.value}),className:"w-full ios-input px-4 py-3 pr-11 rounded-xl text-sm",placeholder:"不修改则留空",autoComplete:"new-password"}),e.jsx("button",{type:"button",onClick:()=>W(!Z),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:Z?"隐藏密码":"显示密码",children:Z?e.jsx(ns,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"确认新密码"}),e.jsx("input",{type:Z?"text":"password",value:T.confirm_password,onChange:y=>h({...T,confirm_password:y.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"再次输入新密码",autoComplete:"new-password"})]})]}),L&&e.jsxs("div",{className:`flex items-start gap-2 rounded-xl px-3 py-2.5 text-sm font-medium ${L.type==="success"?"bg-green-50 text-green-700":"bg-red-50 text-red-700"}`,children:[e.jsx(Ms,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:L.text})]}),e.jsxs("button",{type:"submit",disabled:A||!T.new_username||!T.current_password,className:"w-full bg-gray-900 hover:bg-black text-white px-5 py-3 rounded-xl font-bold text-sm flex items-center justify-center gap-2 transition-colors disabled:opacity-40",children:[e.jsx(at,{className:"w-4 h-4"}),A?"正在更新...":"更新登录凭据"]})]})]})]})]}),e.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:e.jsxs("button",{onClick:X,disabled:k,className:"ios-btn-primary px-10 py-5 rounded-xl text-lg shadow-2xl shadow-blue-200 flex items-center gap-3 transform hover:scale-105 active:scale-95 transition-all disabled:opacity-70",children:[e.jsx(Je,{className:"w-6 h-6"}),k?"保存中...":"保存所有配置"]})})]})},Es=(s,t)=>s.allowed_resolutions.includes(t),nr=(s,t)=>({runs:s.runs.filter(l=>!t||l.cookie_id===t),pending_tasks:s.pending_tasks.filter(l=>!t||l.cookie_id===t)}),ir=s=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[s]||"自动化异常",or=async s=>{const t=s.loadIssues().then(s.onIssues).catch(s.onIssuesError),l=await s.loadRules();s.onRules(l),await t},cr=(s,t,l,d,u,b)=>s!==t||l!==d?!1:(b(u),!0),He={order_paid:{label:"付款后自动发货",shortLabel:"自动发货",description:"闲鱼付款系统卡片进入自动化中心后,先发送卡密,成功后再确认发货。",flow:["付款系统卡片","匹配商品/规格","发送卡密","确认发货"],accent:"blue",icon:gs},buyer_reviewed:{label:"评价后发送赠品",shortLabel:"评价赠品",description:"闲鱼评价系统卡片进入自动化中心后,给买家发送赠品卡密。",flow:["评价系统卡片","匹配商品/规格","发送赠品"],accent:"emerald",icon:ha},review_missing_timeout:{label:"超时未评价求评价",shortLabel:"求评价",description:"计划任务扫描已发货未评价订单,到期后发送求评价文案。",flow:["计划任务扫描","已发货未评价","达到等待时间","发送提醒"],accent:"amber",icon:Lt}},Ds=["order_paid","buyer_reviewed","review_missing_timeout"],dr="亲,商品使用满意的话,麻烦给个评价,谢谢~",ms=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0,delay_override:!1,delay_seconds:0}),Ut=s=>{if(!s)return{};try{const t=JSON.parse(s);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}},Ze=(s,t={})=>{const l=Ut(s);return JSON.stringify({after_shipped_hours:Number(l.after_shipped_hours||72),repeat_interval_hours:Number(l.repeat_interval_hours||24),max_attempts:Number(l.max_attempts||1),...t})},us=(s,t)=>{var d;const l=((d=He[s])==null?void 0:d.label)||"自动化规则";return t?`${l} - ${t}`:l},ft=s=>{const t=(s||"").trim();return t?Object.values(He).some(l=>t===l.label||t.startsWith(`${l.label} -`)):!0},ps=(s,t=0)=>{if(s==="review_missing_timeout")return[{action_type:"send_text",message_template:dr,enabled:!0,sort_order:1}];const l={action_type:"send_card",card_id:t,delivery_count:1,enabled:!0,sort_order:1};return s==="order_paid"?[l,{action_type:"confirm_shipment",enabled:!0,sort_order:2}]:[l]},xr=s=>{var l,d;if(s.trigger_type==="review_missing_timeout")return((d=(l=s.actions)==null?void 0:l.find(u=>u.action_type==="send_text"))==null?void 0:d.message_template)||"发送求评价文案";const t=(s.actions||[]).filter(u=>u.action_type==="send_card");return t.length?t.map(u=>u.card_name||`卡密 ${u.card_id}`).join(" / "):"未配置卡密库存"},jt=(s,t=!1)=>{const l={blue:t?"border-blue-500 bg-blue-50 text-blue-700":"border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300",emerald:t?"border-emerald-500 bg-emerald-50 text-emerald-700":"border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300",amber:t?"border-amber-500 bg-amber-50 text-amber-700":"border-amber-100 bg-amber-50/60 text-amber-700 hover:border-amber-300"};return l[s]||l.blue},mr=s=>s?"bg-emerald-100 text-emerald-700":"bg-gray-200 text-gray-500",vs=s=>(s==null?void 0:s.nickname)||(s==null?void 0:s.remark)||(s==null?void 0:s.id)||"未知账号",ur=s=>s===!0||s===1||s==="1",pr=({initialDeliveryTarget:s,onDeliveryTargetHandled:t})=>{var ze,Ie,ss;const[l,d]=n.useState("automation"),[u,b]=n.useState([]),[k,O]=n.useState({runs:[],pending_tasks:[]}),[p,R]=n.useState([]),[f,Q]=n.useState({}),[se,U]=n.useState([]),[J,S]=n.useState([]),[K,de]=n.useState([]),[le,ne]=n.useState(!1),[q,B]=n.useState(""),D=n.useRef(0),Z=n.useRef("");Z.current=q;const[W,A]=n.useState(!1),[Y,L]=n.useState(!1),[te,T]=n.useState(!1),[h,$]=n.useState(null),[z,X]=n.useState(null),[m,_]=n.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""});se.find(a=>a.id===q);const N=n.useCallback(async()=>{const[a,g,v,ee]=await Promise.all([Vs(),Ue(),ds(),pt()]);U(a),S(g),de(v),Q(ee),B(xe=>{var je;return xe||((je=a[0])==null?void 0:je.id)||""})},[]),y=n.useCallback(async()=>{await or({loadRules:ks,loadIssues:jl,onRules:b,onIssues:O,onIssuesError:a=>console.warn("加载自动化异常列表失败,不阻断规则展示",a)})},[]),P=n.useCallback(async()=>{const a=q;if(a!==Z.current)return;const g=++D.current;if(R([]),!a)return;const v=await kl(a);cr(g,D.current,a,Z.current,v,R)},[q]),M=n.useCallback(async()=>{Q(await pt())},[]),i=n.useCallback(async()=>{ne(!0);try{l==="automation"?await y():l==="reply"?await P():await M()}finally{ne(!1)}},[l,y,M,P]);n.useEffect(()=>{N().catch(a=>console.error("加载规则参考数据失败",a))},[N]),n.useEffect(()=>{i().catch(a=>console.error("刷新规则页面失败",a))},[i]);const E=n.useMemo(()=>u.filter(a=>!q||a.cookie_id===q),[u,q]),w=n.useMemo(()=>nr(k,q),[k,q]),G=n.useMemo(()=>se.filter(a=>!q||a.id===q),[se,q]),me=n.useMemo(()=>{var g;const a={order_paid:[],buyer_reviewed:[],review_missing_timeout:[]};for(const v of E)(g=a[v.trigger_type])==null||g.push(v);return a},[E]),ie=n.useMemo(()=>{const a=(h==null?void 0:h.cookie_id)||q;return K.filter(g=>g.cookie_id===a)},[h==null?void 0:h.cookie_id,K,q]),H=n.useMemo(()=>{if(!(!(h!=null&&h.cookie_id)||!(h!=null&&h.item_id)))return K.find(a=>a.cookie_id===h.cookie_id&&a.item_id===h.item_id)},[h==null?void 0:h.cookie_id,h==null?void 0:h.item_id,K]),c=ur(H==null?void 0:H.is_multi_spec),C=(h==null?void 0:h.trigger_type)||"order_paid",oe=He[C],be=Ut(h==null?void 0:h.config_json),ye=n.useCallback((a="order_paid",g=q,v="")=>{const ee=K.find(je=>je.cookie_id===g&&je.item_id===v),xe=(ee==null?void 0:ee.item_title)||v;return{name:us(a,xe),trigger_type:a,cookie_id:g,item_id:v,item_title:(ee==null?void 0:ee.item_title)||"",item_keyword:xe,card_group_id:0,priority:100,enabled:!0,config_json:a==="review_missing_timeout"?Ze():"{}",actions:ps(a),variants:a==="review_missing_timeout"?[]:[ms()]}},[K,q]),Se=n.useCallback(a=>{var v,ee;const g=a.trigger_type||"order_paid";$({...a,trigger_type:g,config_json:g==="review_missing_timeout"?Ze(a.config_json):a.config_json||"{}",actions:(v=a.actions)!=null&&v.length?a.actions.map(xe=>({...xe})):ps(g,a.card_group_id),variants:(ee=a.variants)!=null&&ee.length?a.variants.map(xe=>({...xe})):g==="review_missing_timeout"?[]:[ms()]}),A(!0)},[]);n.useEffect(()=>{if(!s)return;let a=!1;return(async()=>{d("automation"),B(s.cookieId),ne(!0);try{const[v,ee,xe]=await Promise.all([ks(),ds(),Ue().catch(o=>(console.warn("加载卡密库存失败,不阻断打开自动化规则",o),[]))]);if(a)return;b(v),de(ee),S(xe);const je=v.find(o=>o.cookie_id===s.cookieId&&o.item_id===s.itemId&&o.trigger_type==="order_paid");if(je)Se(je);else{const o=ee.find(j=>j.cookie_id===s.cookieId&&j.item_id===s.itemId);$({...ye("order_paid",s.cookieId,s.itemId),item_title:(o==null?void 0:o.item_title)||"",item_keyword:(o==null?void 0:o.item_title)||s.itemId,name:us("order_paid",(o==null?void 0:o.item_title)||s.itemId)}),A(!0)}}catch(v){console.error("打开商品自动化规则失败",v),alert("无法加载该商品的自动化规则")}finally{a||(ne(!1),t==null||t())}})(),()=>{a=!0}},[ye,s,t,Se]);const ve=(a="order_paid")=>{if(!q){alert("请先选择账号");return}$(ye(a)),A(!0)},fe=a=>{var ee,xe,je,o,j;if(!h)return;const g=((xe=(ee=h.variants)==null?void 0:ee.find(F=>F.card_id))==null?void 0:xe.card_id)||((o=(je=h.actions)==null?void 0:je.find(F=>F.action_type==="send_card"))==null?void 0:o.card_id)||h.card_group_id||0,v=(H==null?void 0:H.item_title)||h.item_title||h.item_id||"";$({...h,trigger_type:a,name:ft(h.name)?us(a,v):h.name,card_group_id:g,config_json:a==="review_missing_timeout"?Ze(h.config_json):"{}",actions:ps(a,g),variants:a==="review_missing_timeout"?[]:(j=h.variants)!=null&&j.length?h.variants:[{...ms(),card_id:g}]})},De=a=>{if(!h)return;const g=K.find(ee=>ee.cookie_id===(h.cookie_id||q)&&ee.item_id===a),v=(g==null?void 0:g.item_title)||a;$({...h,item_id:a,item_title:(g==null?void 0:g.item_title)||"",item_keyword:v,name:ft(h.name)?us(C,v):h.name})},ue=(ze=h==null?void 0:h.variants)!=null&&ze.length?h.variants:[ms()],Ae=(a,g)=>{var ee;if(!h)return;const v=ue.map((xe,je)=>je===a?{...xe,...g}:xe);$({...h,variants:v,card_group_id:((ee=v[0])==null?void 0:ee.card_id)||0})},Re=()=>{if(!h)return;const a=ue[ue.length-1];$({...h,variants:[...ue,{...ms(),spec_name:c&&(a==null?void 0:a.spec_name)||"",spec_value:c&&(a==null?void 0:a.spec_value)||""}]})},Fe=async()=>{var ee,xe,je,o,j;if(!h)return;const a=h.trigger_type||"order_paid";if(!h.cookie_id){alert("请选择账号");return}const g=(ee=h.variants)!=null&&ee.length?h.variants:[];if(a!=="review_missing_timeout"){if(!g.length||g.some(F=>!F.card_id)){alert(a==="buyer_reviewed"?"请选择评价赠品卡密库存":"请选择发货卡密库存");return}if(c&&g.some(F=>!F.spec_name.trim()||!F.spec_value.trim())){alert("多规格商品必须填写每一行的规格名称和规格值");return}}if(a==="review_missing_timeout"&&!(((je=(xe=h.actions)==null?void 0:xe.find(ae=>ae.action_type==="send_text"))==null?void 0:je.message_template)||"").trim()){alert("请填写求评价文案");return}const v=a==="review_missing_timeout"?[]:g.map(F=>({...F,spec_name:c?F.spec_name.trim():"",spec_value:c?F.spec_value.trim():"",delivery_count:Math.max(1,Number(F.delivery_count)||1),enabled:F.enabled!==!1}));try{await mt({...h,trigger_type:a,name:(h.name||"").trim()||us(a,(H==null?void 0:H.item_title)||h.item_id||""),config_json:a==="review_missing_timeout"?Ze(h.config_json):h.config_json||"{}",actions:(o=h.actions)!=null&&o.length?h.actions:ps(a,((j=v[0])==null?void 0:j.card_id)||h.card_group_id||0),variants:v}),A(!1),await Promise.all([y(),N()]),alert("保存成功")}catch(F){console.error("保存自动化规则失败:",F),alert("保存失败:"+F.message)}},Ke=async a=>{if(confirm("确定删除该自动化规则吗?"))try{await fl(a),await y(),alert("删除成功")}catch(g){alert("删除失败:"+g.message)}},Ye=async a=>{try{await mt({...a,enabled:!a.enabled}),await y()}catch(g){alert("操作失败:"+g.message)}},x=async(a,g)=>{if(confirm(g==="continue"?"确认外部动作已经执行成功,并跳到下一步吗?":g==="retry"?"确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。":"确认终止该自动化运行吗?"))try{await Nl(a,g),await y()}catch(ee){alert("处理失败:"+ee.message)}},V=async(a,g)=>{if(confirm(g==="retry"?"确认重新执行该任务吗?":"确认忽略并删除该异常任务吗?"))try{await vl(a,g),await y()}catch(v){alert("处理失败:"+v.message)}},he=()=>{if(!q){alert("请先选择账号");return}X({keyword:"",reply_content:"",image_url:"",item_id:"",type:"text",match_type:"fuzzy",enabled:!0}),L(!0)},Ce=async()=>{var g,v,ee;if(!z||!q)return;const a=z.type==="image"?!!((g=z.image_url)!=null&&g.trim()):!!((v=z.reply_content)!=null&&v.trim());if(!((ee=z.keyword)!=null&&ee.trim())||!a){alert("请填写关键词和回复内容");return}try{await Cl({...z,match_type:"fuzzy",enabled:!0},q),L(!1),await P(),alert("保存成功")}catch(xe){alert("保存失败:"+xe.message)}},Be=async a=>{if(!(!q||!confirm("确定删除该回复规则吗?")))try{await Sl(a,q),await P(),alert("删除成功")}catch(g){alert("删除失败:"+g.message)}},Te=async(a=q)=>{if(!a){alert("请先选择账号");return}try{const g=await Fl(a);_({cookie_id:a,enabled:g.enabled,reply_content:g.reply_content,reply_once:g.reply_once,reply_image_url:g.reply_image_url||""})}catch{_({cookie_id:a,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""})}T(!0)},r=async()=>{if(!m.cookie_id){alert("请先选择账号");return}if(m.enabled&&!m.reply_content.trim()&&!m.reply_image_url.trim()){alert("启用默认回复时,请填写回复内容或图片 URL");return}try{await Tl(m.cookie_id,{enabled:m.enabled,reply_content:m.reply_content,reply_once:m.reply_once,reply_image_url:m.reply_image_url}),T(!1),await M(),alert("保存成功")}catch(a){alert("保存失败:"+a.message)}},I=async a=>{if(confirm("确定删除该账号默认回复吗?"))try{await Ol(a),await M(),alert("删除成功")}catch(g){alert("删除失败:"+g.message)}},ce=async a=>{if(confirm("确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。"))try{await ql(a),alert("清空成功")}catch(g){alert("清空失败:"+g.message)}},Qe=l==="automation"?"新建自动化":l==="reply"?"新增关键词":"编辑默认回复";return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"系统通知卡片只进入自动化判断;买家消息进入关键词、默认或 AI 回复。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("select",{value:q,onChange:a=>B(a.target.value),className:"ios-input px-4 py-3 rounded-2xl text-sm min-w-64",children:[e.jsx("option",{value:"",children:"全部账号"}),se.map(a=>e.jsx("option",{value:a.id,children:vs(a)},a.id))]}),e.jsxs("button",{onClick:i,className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 hover:bg-gray-200 text-gray-700 flex items-center justify-center gap-2 transition-colors",children:[e.jsx(qe,{className:`w-4 h-4 ${le?"animate-spin":""}`}),"刷新"]}),e.jsxs("button",{onClick:l==="automation"?()=>ve("order_paid"):l==="reply"?he:()=>void Te(),disabled:!q,className:"ios-btn-primary px-5 py-3 rounded-2xl text-sm font-extrabold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(Ge,{className:"w-4 h-4"}),Qe]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[{id:"automation",label:"交易自动化",icon:Ts},{id:"reply",label:"关键词回复",icon:_s},{id:"default",label:"账号默认回复",icon:rs}].map(a=>{const g=a.icon;return e.jsxs("button",{onClick:()=>d(a.id),className:`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${l===a.id?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:[e.jsx(g,{className:"w-4 h-4"}),a.label]},a.id)})}),l==="automation"&&(w.runs.length>0||w.pending_tasks.length>0)&&e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(os,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[w.runs.map(a=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",a.cookie_id," · 订单 ",a.order_id||"-"," · 已记录发送 ",a.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:ir(a.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:a.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Es(a,"continue")&&e.jsx("button",{onClick:()=>void x(a.id,"continue"),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Es(a,"retry")&&e.jsx("button",{onClick:()=>void x(a.id,"retry"),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Es(a,"cancel")&&e.jsx("button",{onClick:()=>void x(a.id,"cancel"),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${a.id}`)),w.pending_tasks.map(a=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",a.cookie_id," · 延迟任务重试已达 ",a.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:a.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:()=>void V(a.id,"retry"),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:()=>void V(a.id,"dismiss"),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${a.id}`))]})]}),l==="automation"&&e.jsxs("div",{className:"grid grid-cols-1 2xl:grid-cols-[360px_1fr] gap-6",children:[e.jsxs("aside",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsx("h3",{className:"font-black text-gray-900 mb-1",children:"新建规则"}),e.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"先选自动化类型,再配置对应动作。"}),e.jsx("div",{className:"space-y-3",children:Ds.map(a=>{const g=He[a],v=g.icon;return e.jsx("button",{type:"button",onClick:()=>ve(a),className:`w-full text-left rounded-2xl border p-4 transition-colors ${jt(g.accent)}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/80 flex items-center justify-center shrink-0",children:e.jsx(v,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:g.label}),e.jsx("div",{className:"text-xs opacity-75 mt-1 leading-5",children:g.description})]})]})},a)})})]}),e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsx("h3",{className:"font-black text-gray-900 mb-4",children:"规则概览"}),e.jsx("div",{className:"space-y-3",children:Ds.map(a=>{const g=He[a],v=g.icon;return e.jsxs("div",{className:"flex items-center justify-between rounded-2xl bg-gray-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(v,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:g.shortLabel})]}),e.jsx("span",{className:"text-sm font-black text-gray-900",children:me[a].length})]},a)})})]})]}),e.jsx("section",{className:"space-y-4",children:E.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center",children:[e.jsx(Ts,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-black text-gray-900",children:"还没有自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2",children:"从左侧选择一个模板开始配置。"})]}):E.map(a=>{const g=He[a.trigger_type],v=g.icon;return e.jsx("article",{className:"bg-white rounded-xl border border-gray-100 p-5 shadow-sm hover:shadow-lg transition-all",children:e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${jt(g.accent,!0)}`,children:e.jsx(v,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("h3",{className:"text-lg font-black text-gray-900 truncate",children:a.name}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold ${mr(a.enabled)}`,children:a.enabled?"已启用":"已禁用"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs font-bold",children:[e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:g.label}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:a.item_title||a.item_id||"账号级规则"}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-blue-50 text-blue-700",children:xr(a)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:()=>Se(a),className:"px-4 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-bold flex items-center gap-2",children:[e.jsx(cs,{className:"w-4 h-4"}),"编辑"]}),e.jsx("button",{onClick:()=>Ye(a),className:`px-4 py-2 rounded-xl text-sm font-bold ${a.enabled?"bg-amber-50 text-amber-700 hover:bg-amber-100":"bg-emerald-50 text-emerald-700 hover:bg-emerald-100"}`,children:a.enabled?"禁用":"启用"}),e.jsx("button",{onClick:()=>Ke(a.id),className:"p-2.5 rounded-xl text-red-500 hover:bg-red-50",title:"删除",children:e.jsx(Ve,{className:"w-4 h-4"})})]})]})},a.id)})})]}),l==="reply"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(os,{className:"w-4 h-4"}),"这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。"]}),e.jsxs("div",{className:"space-y-3",children:[p.map(a=>e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border border-gray-100 bg-[#F7F8FA] hover:bg-white hover:shadow-lg transition-all gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("span",{className:"px-3 py-1 bg-black text-white rounded-lg text-xs font-bold",children:"包含匹配"}),e.jsxs("h3",{className:"font-bold text-gray-900",children:["“",a.keyword,"”"]})]}),e.jsx("div",{className:"bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed",children:a.type==="image"&&a.image_url?a.image_url:a.reply_content})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:()=>{X({...a}),L(!0)},className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(cs,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>Be(a.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ve,{className:"w-5 h-5"})})]})]},a.id)),p.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无关键词回复规则"})]})]}),l==="default"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(os,{className:"w-4 h-4"}),"默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。"]}),e.jsxs("div",{className:"space-y-3",children:[G.map(a=>{const g=f[a.id],v=!!(g!=null&&g.enabled);return e.jsxs("div",{className:`flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border transition-all gap-4 ${v?"border-purple-100 bg-purple-50/50 hover:bg-white hover:shadow-lg":"border-gray-100 bg-[#F7F8FA] hover:bg-white hover:shadow-lg"}`,children:[e.jsxs("div",{className:"flex items-center gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center ${v?"bg-purple-600 text-white":"bg-gray-200 text-gray-400"}`,children:e.jsx(rs,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h3",{className:"font-bold text-gray-900 text-lg truncate",children:vs(a)}),e.jsx("span",{className:`px-2 py-0.5 rounded-lg text-xs font-bold ${v?"bg-green-100 text-green-700":"bg-gray-200 text-gray-500"}`,children:v?"已启用":"未启用"}),(g==null?void 0:g.reply_once)&&e.jsx("span",{className:"px-2 py-0.5 rounded-lg text-xs font-bold bg-purple-100 text-purple-700",children:"只回复一次"})]}),e.jsx("div",{className:"text-sm text-gray-600 line-clamp-2",children:v?g.reply_content||g.reply_image_url||"已配置默认回复":"未配置默认回复"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:()=>void Te(a.id),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(cs,{className:"w-4 h-4"})}),v&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>void ce(a.id),className:"px-3 py-2 text-xs font-bold text-blue-600 hover:bg-blue-50 rounded-xl transition-colors",children:"清空记录"}),e.jsx("button",{onClick:()=>void I(a.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Ve,{className:"w-5 h-5"})})]})]})]},a.id)}),G.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无账号"})]})]}),W&&h&&ke.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"72rem",maxHeight:"92vh"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-black text-gray-900",children:h.id?"编辑自动化规则":"新建自动化规则"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:oe.description})]}),e.jsx("button",{onClick:()=>A(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] min-h-0",children:[e.jsxs("aside",{className:"bg-slate-900 text-white p-5 overflow-y-auto",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"选择自动化类型"}),e.jsx("div",{className:"space-y-3",children:Ds.map(a=>{const g=He[a],v=g.icon,ee=C===a;return e.jsx("button",{type:"button",onClick:()=>fe(a),className:`w-full rounded-2xl p-4 text-left border transition-all ${ee?"bg-white text-slate-950 border-white":"bg-white/5 text-white border-white/10 hover:bg-white/10"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(v,{className:`w-5 h-5 mt-0.5 ${ee?"text-[#0094f7]":"text-white"}`}),e.jsxs("div",{children:[e.jsx("div",{className:"font-black",children:g.label}),e.jsx("div",{className:`text-xs mt-1 leading-5 ${ee?"text-gray-500":"text-gray-400"}`,children:g.description})]})]})},a)})}),e.jsxs("div",{className:"mt-6 rounded-2xl bg-white/5 border border-white/10 p-4",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"执行流程"}),e.jsx("div",{className:"space-y-3",children:oe.flow.map((a,g)=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-white text-slate-950 text-xs font-black flex items-center justify-center",children:g+1}),e.jsx("span",{className:"text-sm font-bold text-gray-100",children:a})]},a))})]})]}),e.jsx("div",{className:"p-6 overflow-y-auto bg-[#F7F8FA]",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx($t,{className:"w-5 h-5 text-[#0094f7]"}),e.jsx("h4",{className:"font-black text-gray-900",children:"生效范围"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"规则名称"}),e.jsx("input",{type:"text",value:h.name||"",onChange:a=>$({...h,name:a.target.value}),placeholder:"不填时按类型和商品自动生成",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:h.cookie_id||"",onChange:a=>$({...h,cookie_id:a.target.value,item_id:"",item_title:"",item_keyword:""}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),se.map(a=>e.jsx("option",{value:a.id,children:vs(a)},a.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:h.item_id||"",onChange:a=>De(a.target.value),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级规则(不限定商品)"}),ie.map(a=>e.jsx("option",{value:a.item_id,children:a.item_title||a.item_id},`${a.cookie_id}-${a.item_id}`))]})]})]}),H&&C!=="review_missing_timeout"&&e.jsxs("div",{className:"mt-4 rounded-2xl bg-gray-50 border border-gray-100 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("span",{className:"px-3 py-1.5 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:H.item_title||H.item_id}),e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${c?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-500"}`,children:c?"多规格商品":"普通商品"}),e.jsx("span",{className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-emerald-50 text-emerald-700",children:"按订单购买数量自动发货"})]}),e.jsx("p",{className:"text-xs leading-5 text-gray-500",children:"多规格状态来自闲鱼商品本身,发布后不能在这里修改;系统会在买家付款后读取订单详情,按实际购买规格和数量匹配下面的发货规则。"})]})]}),C!=="review_missing_timeout"?e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ga,{className:"w-5 h-5 text-[#0094f7]"}),e.jsx("h4",{className:"font-black text-gray-900",children:C==="buyer_reviewed"?"赠品库存":"发货库存"})]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:c?"每条发货内容绑定一个订单规格;同一规格可添加多条内容并全部发送。":"可添加多条发货内容,买家付款后会按顺序全部发送。"})]}),e.jsxs("button",{type:"button",onClick:Re,className:"px-3 py-2 rounded-xl bg-gray-900 text-white text-xs font-bold hover:bg-black flex items-center gap-1.5",children:[e.jsx(Ge,{className:"w-3.5 h-3.5"}),"添加发货内容"]})]}),e.jsx("div",{className:"space-y-3",children:ue.map((a,g)=>e.jsxs("div",{className:`grid grid-cols-1 gap-3 items-end rounded-2xl border border-gray-200 p-4 ${c?"md:grid-cols-[1fr_1fr_1.4fr_110px_40px]":"md:grid-cols-[1.4fr_110px_40px]"}`,children:[c&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格名称"}),e.jsx("input",{value:a.spec_name,onChange:v=>Ae(g,{spec_name:v.target.value}),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:套餐"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格值"}),e.jsx("input",{value:a.spec_value,onChange:v=>Ae(g,{spec_value:v.target.value}),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:30天"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"卡密库存"}),e.jsxs("select",{value:a.card_id||"",onChange:v=>Ae(g,{card_id:Number(v.target.value)}),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[e.jsx("option",{value:"",children:"请选择卡密库存"}),J.filter(v=>v.enabled&&v.type!=="api").map(v=>e.jsx("option",{value:v.id,children:v.name},v.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"每件份数"}),e.jsx("input",{type:"number",min:"1",max:"100",value:a.delivery_count,onChange:v=>Ae(g,{delivery_count:Math.max(1,Number(v.target.value)||1)}),className:"w-full ios-input px-3 py-2.5 rounded-lg"})]}),e.jsxs("div",{className:"md:col-span-full flex flex-wrap items-center gap-3 rounded-xl bg-gray-50 px-3 py-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold text-gray-600 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:a.delay_override===!0,onChange:v=>Ae(g,{delay_override:v.target.checked}),className:"accent-[#0094f7]"}),"覆盖卡密默认延时"]}),a.delay_override&&e.jsx("input",{type:"number",min:"0",max:"86400",value:a.delay_seconds||0,onChange:v=>Ae(g,{delay_seconds:Math.max(0,Number(v.target.value)||0)}),className:"w-28 ios-input px-2 py-1.5 rounded-lg text-xs","aria-label":"动作延时秒数"}),e.jsx("span",{className:"text-xs text-gray-500",children:a.delay_override?`本动作延时 ${a.delay_seconds||0} 秒`:"使用卡密默认延时"})]}),e.jsx("button",{type:"button",disabled:ue.length===1,onClick:()=>$({...h,variants:ue.filter((v,ee)=>ee!==g)}),className:"w-10 h-10 flex items-center justify-center rounded-lg text-red-500 hover:bg-red-50 disabled:opacity-25",title:"删除发货内容",children:e.jsx(Ve,{className:"w-4 h-4"})})]},a.id||g))})]}):e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Lt,{className:"w-5 h-5 text-amber-600"}),e.jsx("h4",{className:"font-black text-gray-900",children:"求评价计划"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"发货后等待小时"}),e.jsx("input",{type:"number",min:"1",value:Number(be.after_shipped_hours||72),onChange:a=>$({...h,config_json:Ze(h.config_json,{after_shipped_hours:Math.max(1,Number(a.target.value)||72)})}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"再次求评间隔小时"}),e.jsx("input",{type:"number",min:"1",value:Number(be.repeat_interval_hours||24),onChange:a=>$({...h,config_json:Ze(h.config_json,{repeat_interval_hours:Math.max(1,Number(a.target.value)||24)})}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最多求评次数"}),e.jsx("input",{type:"number",min:"1",value:Number(be.max_attempts||1),onChange:a=>$({...h,config_json:Ze(h.config_json,{max_attempts:Math.max(1,Number(a.target.value)||1)})}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"md:col-span-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"求评价文案"}),e.jsx("textarea",{value:((ss=(Ie=h.actions)==null?void 0:Ie.find(a=>a.action_type==="send_text"))==null?void 0:ss.message_template)||"",onChange:a=>{var g;return $({...h,actions:((g=h.actions)!=null&&g.length?h.actions:ps("review_missing_timeout")).map(v=>v.action_type==="send_text"?{...v,message_template:a.target.value}:v)})},className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none"})]})]})]}),e.jsx("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-[180px_1fr] gap-4 items-end",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"优先级"}),e.jsx("p",{className:"text-xs text-gray-500 mb-2",children:"数字越小优先级越高;同一账号、商品和触发条件只执行优先级最高的一条规则。"}),e.jsx("input",{type:"number",value:h.priority||100,onChange:a=>$({...h,priority:Number(a.target.value)||100}),min:"1",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"h-[48px] flex items-center gap-3 px-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsx("input",{type:"checkbox",checked:h.enabled!==!1,onChange:a=>$({...h,enabled:a.target.checked}),className:"w-4 h-4 rounded"}),"启用规则"]})]})})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 bg-white flex gap-3",children:[e.jsx("button",{onClick:()=>A(!1),className:"flex-1 px-6 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200",children:"取消"}),e.jsxs("button",{onClick:Fe,className:"flex-1 ios-btn-primary px-6 py-3 rounded-2xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4"}),"保存自动化规则"]})]})]})}),document.body),Y&&z&&ke.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:z.id?"编辑回复规则":"新增回复规则"}),e.jsx("button",{onClick:()=>L(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:z.item_id||"",onChange:a=>X({...z,item_id:a.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级回复"}),K.filter(a=>!q||a.cookie_id===q).map(a=>e.jsx("option",{value:a.item_id,children:a.item_title||a.item_id},`${a.cookie_id}-${a.item_id}`))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复类型"}),e.jsxs("select",{value:z.type||"text",onChange:a=>{const g=a.target.value;X({...z,type:g,reply_content:g==="text"?z.reply_content:"",image_url:g==="image"?z.image_url:""})},className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"文字"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关键词"}),e.jsx("input",{type:"text",value:z.keyword||"",onChange:a=>X({...z,keyword:a.target.value}),placeholder:"买家发送的关键词",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),z.type==="image"?e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{value:z.image_url||"",onChange:a=>X({...z,image_url:a.target.value}),placeholder:"https://...",className:"w-full ios-input px-4 py-3 rounded-xl"})]}):e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:z.reply_content||"",onChange:a=>X({...z,reply_content:a.target.value}),placeholder:"自动回复的内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:()=>L(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:Ce,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Us,{className:"w-4 h-4"}),"保存规则"]})]})]})]})}),document.body),te&&ke.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"账号默认回复"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"关键词和 AI 都未处理时,才会使用默认回复。"})]}),e.jsx("button",{onClick:()=>T(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",title:"关闭",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:m.cookie_id,onChange:a=>_({...m,cookie_id:a.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),se.map(a=>e.jsx("option",{value:a.id,children:vs(a)},a.id))]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"启用默认回复"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1",children:"启用后,未命中关键词时自动发送"})]}),e.jsx("button",{type:"button",onClick:()=>_({...m,enabled:!m.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${m.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${m.enabled?"translate-x-7":"translate-x-1"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:m.reply_content,onChange:a=>_({...m,reply_content:a.target.value}),placeholder:"输入默认回复内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复图片 URL(可选)"}),e.jsx("input",{type:"text",value:m.reply_image_url,onChange:a=>_({...m,reply_image_url:a.target.value}),placeholder:"https://example.com/image.jpg",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsxs("span",{children:["只回复一次",e.jsx("span",{className:"block text-xs text-gray-500 font-medium mt-1",children:"同一会话只发送一次默认回复"})]}),e.jsx("input",{type:"checkbox",checked:m.reply_once,onChange:a=>_({...m,reply_once:a.target.checked}),className:"w-4 h-4 rounded"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:()=>T(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:r,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Je,{className:"w-4 h-4"}),"保存默认回复"]})]})]})]})}),document.body)]})},hr=s=>{const t=String(s.smtp_from||"").trim(),l=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t);return{...s,smtp_from_name:s.smtp_from_name||(l?"":t),smtp_from_address:s.smtp_from_address||(l?t:s.smtp_user||""),smtp_use_tls:Nt(s.smtp_use_tls,!0),smtp_use_ssl:Nt(s.smtp_use_ssl,!1)}},Nt=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},ls={bark:{label:"Bark",icon:is,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app//这是测试推送内容","URL 路径里 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:_s,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:_s,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:_s,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:ba,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:Us,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的用户 ID",required:!0}],guide:{steps:["在 Telegram 搜索 @BotFather,发送 /newbot,按提示创建机器人,拿到 Bot Token","把你的 Bot 拉进一个群,或私聊它发一条消息","浏览器访问 https://api.telegram.org/bot<你的Token>/getUpdates",'从返回 JSON 里找 "chat":{"id":xxx},xxx 就是 Chat ID(群是负数,私聊是正数)'],urlFormat:"Bot Token: 123456:ABC-DEF... Chat ID: -1001234567890",note:"群聊需先把 Bot 设为管理员才能发消息。"}},email:{label:"邮件",icon:Pt,fields:[{key:"to_email",label:"收件邮箱",placeholder:"receiver@example.com",required:!0},{key:"smtp_server",label:"覆盖 SMTP 服务器",placeholder:"smtp.qq.com",help:"留空时使用上方系统级 SMTP 配置"},{key:"smtp_port",label:"覆盖 SMTP 端口",placeholder:"587",type:"number",help:"留空时使用系统级 SMTP 端口"},{key:"smtp_user",label:"覆盖发件邮箱",placeholder:"you@qq.com",help:"留空时使用系统级发件邮箱"},{key:"smtp_password",label:"覆盖密码 / 授权码",type:"password",help:"留空时使用系统级授权码"}],guide:{steps:["先在页面上方保存系统级 SMTP 服务器、端口、发件邮箱和授权码","邮件渠道只需要填写收件邮箱","如果某个渠道要使用不同发件邮箱,再填写下面的覆盖 SMTP 字段"],note:"收件邮箱会写入 to_email;SMTP 字段留空时后端会复用系统级 SMTP 配置。"}}},Wt=[{value:"account_offline",label:"掉线通知",description:"账号过期、断线或登录态失效"},{value:"account_recovered",label:"恢复通知",description:"自动恢复成功并重新在线"},{value:"account_disabled",label:"禁用通知",description:"连续失败、账密错误等导致账号停用"},{value:"security_verification",label:"风控验证",description:"滑块、人脸、扫码验证等安全校验"},{value:"delivery_result",label:"交易通知",description:"订单发货、卡密发送等交易结果"},{value:"token_renewal",label:"续期通知",description:"Cookie/token 续期和自动恢复过程"},{value:"system_error",label:"系统错误",description:"后台任务或系统级异常"}],gr=s=>!s||s.length===0?"全部事件":s.map(l=>{var d;return((d=Wt.find(u=>u.value===l))==null?void 0:d.label)||l}).join("、"),br=({isAdmin:s=!1})=>{const[t,l]=n.useState([]),[d,u]=n.useState(!0),[b,k]=n.useState(!1),[O,p]=n.useState(null),[R,f]=n.useState(!1),[Q,se]=n.useState(""),[U,J]=n.useState(null),[S,K]=n.useState({}),[de,le]=n.useState(!1),[ne,q]=n.useState(!1),[B,D]=n.useState({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),Z=async()=>{u(!0);try{const m=await zt();l(m.data||[])}catch(m){console.error("加载通知渠道失败",m)}finally{u(!1)}},W=async()=>{try{const m=await qt();K(hr(m||{}))}catch(m){console.error("加载 SMTP 配置失败",m)}},A=async()=>{le(!0);try{await Mt({smtp_server:S.smtp_server||"",smtp_port:S.smtp_port||587,smtp_user:S.smtp_user||"",smtp_password:S.smtp_password||"",smtp_from_name:S.smtp_from_name||"",smtp_from_address:S.smtp_from_address||S.smtp_user||"",smtp_use_tls:S.smtp_use_tls!==!1,smtp_use_ssl:S.smtp_use_ssl===!0}),Y("success","SMTP 配置已保存")}catch(m){Y("error",(m==null?void 0:m.message)||"保存失败")}finally{le(!1)}};n.useEffect(()=>{Z(),s?W():K({})},[s]);const Y=(m,_)=>{J({type:m,text:_}),window.setTimeout(()=>J(null),3e3)},L=()=>{p(null),D({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),k(!0)},te=m=>{p(m),D({name:m.name,type:m.type,enabled:m.enabled,config:{...m.config||{}},event_types:m.event_types||[]}),k(!0)},T=async()=>{const m=ls[B.type];for(const _ of m.fields)if(_.required&&!String(B.config[_.key]||"").trim()){Y("error",`请填写 ${_.label}`);return}if(!B.name.trim()){Y("error","请填写渠道名称");return}f(!0);try{const _={name:B.name.trim(),type:B.type,config:B.config,event_types:B.event_types,enabled:B.enabled};O?await ut(O.id,_):await Ll(_),k(!1),await Z(),Y("success",O?"已更新":"已创建")}catch(_){console.error("保存失败",_),Y("error",(_==null?void 0:_.message)||"保存失败")}finally{f(!1)}},h=async m=>{if(confirm(`确认删除渠道「${m.name}」吗?已绑定该渠道的账号会自动解绑。`))try{await Pl(m.id),await Z(),Y("success","已删除")}catch(_){Y("error",(_==null?void 0:_.message)||"删除失败")}},$=async m=>{try{await ut(m.id,{enabled:!m.enabled}),l(_=>_.map(N=>N.id===m.id?{...N,enabled:!N.enabled}:N))}catch(_){Y("error",(_==null?void 0:_.message)||"切换失败")}},z=async m=>{se(m.id);try{await Dl(m.id),Y("success","测试通知已发送,请检查对应渠道")}catch(_){Y("error",(_==null?void 0:_.message)||"发送失败")}finally{se("")}},X=ls[B.type];return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"通知设置"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"配置通知渠道,账号异常时主动推送告警"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:Z,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(qe,{className:"w-4 h-4"}),"刷新"]}),e.jsxs("button",{onClick:L,className:"ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2",children:[e.jsx(Ge,{className:"w-4 h-4"}),"新建渠道"]})]})]}),e.jsx("div",{className:"ios-card rounded-xl p-5 bg-blue-50/50 border border-blue-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(is,{className:"w-5 h-5 text-[#0094f7] mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm text-gray-700 leading-6",children:["配置通知渠道并在「账号管理 → 编辑」里绑定后,以下事件会主动推送到该账号绑定的渠道:",e.jsxs("ul",{className:"mt-2 space-y-1 text-gray-600",children:[e.jsxs("li",{children:["• ",e.jsx("strong",{children:"账号 session 失效"}),":系统正在尝试自动恢复(警告)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"自动恢复失败"}),":账号已停止,需人工处理(严重)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"触发风控验证"}),":可能需要扫码完成验证(警告)"]})]})]})]})}),d?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(Le,{className:"w-8 h-8 text-[#0094f7] animate-spin"})}):t.length===0?e.jsxs("div",{className:"ios-card rounded-xl p-12 bg-white text-center",children:[e.jsx(is,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"还没有配置任何通知渠道"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"点击右上角「新建渠道」开始配置"})]}):e.jsx("div",{className:"space-y-3",children:t.map(m=>{const _=ls[m.type]||ls.webhook,N=_.icon;return e.jsxs("div",{className:"ios-card rounded-xl p-5 bg-white flex items-center gap-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-gray-100 flex items-center justify-center flex-shrink-0",children:e.jsx(N,{className:"w-5 h-5 text-gray-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-bold text-gray-900 truncate",children:m.name}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium",children:_.label}),!m.enabled&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-400 font-medium",children:"已停用"})]}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 truncate",children:_.fields.map(y=>{var P;return(P=m.config)==null?void 0:P[y.key]}).filter(Boolean).map((y,P)=>e.jsx("span",{className:"mr-3",children:String(y).length>40?String(y).slice(0,40)+"…":String(y)},P))}),e.jsxs("div",{className:"text-xs text-gray-400 mt-1 truncate",children:["订阅:",gr(m.event_types)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:()=>$(m),className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${m.enabled?"bg-green-50 text-green-700 hover:bg-green-100":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:m.enabled?"启用中":"已停用"}),e.jsxs("button",{onClick:()=>z(m),disabled:Q===m.id,className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-[#0094f7] hover:bg-blue-100 transition-colors flex items-center gap-1 disabled:opacity-50",children:[Q===m.id?e.jsx(Le,{className:"w-3 h-3 animate-spin"}):e.jsx(Us,{className:"w-3 h-3"}),"测试"]}),e.jsx("button",{onClick:()=>te(m),className:"w-8 h-8 rounded-lg bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-600 transition-colors",title:"编辑",children:e.jsx(Rt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>h(m),className:"w-8 h-8 rounded-lg bg-red-50 hover:bg-red-100 flex items-center justify-center text-red-500 transition-colors",title:"删除",children:e.jsx(Ve,{className:"w-4 h-4"})})]})]},m.id)})}),s&&e.jsxs("section",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-extrabold text-gray-800",children:"SMTP 邮件配置"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"系统级邮件发送服务,供邮件通知渠道复用"})]}),e.jsx("div",{className:"p-2 rounded-xl bg-blue-50 text-blue-600",children:e.jsx(Pt,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 服务器"}),e.jsx("input",{type:"text",value:S.smtp_server||"",onChange:m=>K({...S,smtp_server:m.target.value}),placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 端口"}),e.jsx("input",{type:"number",value:S.smtp_port||587,onChange:m=>K({...S,smtp_port:parseInt(m.target.value)||587}),placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱"}),e.jsx("input",{type:"email",value:S.smtp_user||"",onChange:m=>K({...S,smtp_user:m.target.value}),placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"邮箱密码 / 授权码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:ne?"text":"password",value:S.smtp_password||"",onChange:m=>K({...S,smtp_password:m.target.value}),placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:()=>q(!ne),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:ne?e.jsx(ns,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件人显示名(可选)"}),e.jsx("input",{type:"text",value:S.smtp_from_name||"",onChange:m=>K({...S,smtp_from_name:m.target.value}),placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱地址"}),e.jsx("input",{type:"email",value:S.smtp_from_address||S.smtp_user||"",onChange:m=>K({...S,smtp_from_address:m.target.value}),placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:S.smtp_use_tls!==!1,onChange:m=>K({...S,smtp_use_tls:m.target.checked,smtp_use_ssl:m.target.checked?!1:S.smtp_use_ssl})}),"STARTTLS(常用于 587 端口)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:S.smtp_use_ssl===!0,onChange:m=>K({...S,smtp_use_ssl:m.target.checked,smtp_use_tls:m.target.checked?!1:S.smtp_use_tls})}),"SSL/TLS 直连(常用于 465 端口)"]})]}),e.jsxs("button",{onClick:A,disabled:de,className:"ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[de?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(Je,{className:"w-4 h-4"}),de?"保存中...":"保存 SMTP 配置"]})]}),b&&ke.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"36rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:O?"编辑通知渠道":"新建通知渠道"}),e.jsx("button",{onClick:()=>k(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(Ne,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道名称"}),e.jsx("input",{type:"text",value:B.name,onChange:m=>D({...B,name:m.target.value}),placeholder:"例如:我的 Bark",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道类型"}),e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2",children:Object.keys(ls).map(m=>{const _=ls[m],N=_.icon,y=B.type===m;return e.jsxs("button",{type:"button",onClick:()=>D({...B,type:m,config:{}}),className:`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${y?"border-[#0094f7] bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsx(N,{className:`w-5 h-5 ${y?"text-[#0094f7]":"text-gray-500"}`}),e.jsx("span",{className:`text-xs font-bold ${y?"text-[#0094f7]":"text-gray-600"}`,children:_.label})]},m)})})]}),e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(is,{className:"w-4 h-4 text-amber-600"}),e.jsxs("span",{className:"text-sm font-bold text-amber-800",children:["如何获取 ",X.label," 配置?"]})]}),e.jsx("ol",{className:"space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5",children:X.guide.steps.map((m,_)=>e.jsx("li",{children:m},_))}),X.guide.urlFormat&&e.jsxs("div",{className:"text-xs text-amber-900/90",children:[e.jsx("span",{className:"font-bold",children:"格式示例:"}),e.jsx("code",{className:"mt-1 block bg-amber-100/70 px-2.5 py-1.5 rounded-lg break-all font-mono text-[11px]",children:X.guide.urlFormat})]}),X.guide.note&&e.jsxs("p",{className:"text-xs text-amber-800/80 leading-5 pt-1",children:["💡 ",X.guide.note]})]}),e.jsx("div",{className:"space-y-3",children:X.fields.map(m=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:[m.label,m.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("input",{type:m.type==="password"?"password":m.type==="number"?"number":"text",value:String(B.config[m.key]||""),onChange:_=>D({...B,config:{...B.config,[m.key]:_.target.value}}),placeholder:m.placeholder,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),m.help&&e.jsx("p",{className:"text-xs text-gray-500",children:m.help})]},m.key))}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"通知内容"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"不选择表示接收全部通知;选择后仅接收勾选类型。"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:Wt.map(m=>{const _=B.event_types.includes(m.value);return e.jsxs("button",{type:"button",onClick:()=>{const N=_?B.event_types.filter(y=>y!==m.value):[...B.event_types,m.value];D({...B,event_types:N})},className:`text-left rounded-xl border px-3 py-2.5 transition-colors ${_?"border-[#0094f7] bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-4 h-4 rounded border flex items-center justify-center ${_?"bg-[#0094f7] border-[#0094f7]":"border-gray-300"}`,children:_&&e.jsx(We,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:`text-sm font-bold ${_?"text-[#0094f7]":"text-gray-800"}`,children:m.label})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 pl-6 leading-5",children:m.description})]},m.value)})})]}),e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("button",{type:"button",onClick:()=>D({...B,enabled:!B.enabled}),className:`relative w-11 h-6 rounded-full transition-colors ${B.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform ${B.enabled?"translate-x-5":""}`})}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"启用此渠道"})]})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>k(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"取消"}),e.jsxs("button",{onClick:T,disabled:R,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[R?e.jsx(Le,{className:"w-4 h-4 animate-spin"}):e.jsx(We,{className:"w-4 h-4"}),R?"保存中...":"保存"]})]})]})}),document.body),U&&e.jsxs("div",{className:"fixed bottom-8 left-1/2 -translate-x-1/2 z-[10000] px-5 py-3 rounded-xl shadow-lg font-bold text-sm flex items-center gap-2 animate-fade-in",style:{background:U.type==="success"?"#10b981":"#ef4444",color:"white"},children:[U.type==="success"?e.jsx(We,{className:"w-4 h-4"}):e.jsx(Ne,{className:"w-4 h-4"}),U.text]})]})},Vt={"/app/dashboard":"dashboard","/app/accounts":"accounts","/app/orders":"orders","/app/cards":"cards","/app/items":"items","/app/rules":"rules","/app/notifications":"notifications","/app/settings":"settings"},vt=Object.fromEntries(Object.entries(Vt).map(([s,t])=>[t,s])),_t=()=>Vt[window.location.pathname]||"dashboard",yr=/Win/i.test(navigator.platform||navigator.userAgent),fr=()=>{const[s,t]=n.useState(!1),[l,d]=n.useState(!1),[u,b]=n.useState(_t),[k,O]=n.useState(!0),[p,R]=n.useState(!1),[f,Q]=n.useState(""),[se,U]=n.useState(""),[J,S]=n.useState(!1),[K,de]=n.useState(""),[le,ne]=n.useState(),q=W=>{const A=W==="settings"&&!l?"dashboard":W,Y=vt[A];Y&&Y!==window.location.pathname&&window.history.pushState({},"",Y),b(A)};n.useEffect(()=>{const W=()=>b(_t());return window.addEventListener("popstate",W),()=>window.removeEventListener("popstate",W)},[]),n.useEffect(()=>{Ft().then(A=>{if((A==null?void 0:A.initialized)===!1){R(!0),t(!1),d(!1);return}R(!1),A!=null&&A.authenticated?(t(!0),d(A.is_admin===!0)):d(!1)}).catch(()=>{t(!1),d(!1)}).finally(()=>O(!1));const W=()=>{t(!1),d(!1)};return window.addEventListener("auth:logout",W),()=>window.removeEventListener("auth:logout",W)},[]),n.useEffect(()=>{!k&&s&&!l&&u==="settings"&&(window.history.replaceState({},"",vt.dashboard),b("dashboard"))},[k,s,l,u]);const B=async W=>{W.preventDefault(),S(!0),de("");try{const A=await $a({username:f,password:se});A.success?(t(!0),d(A.is_admin===!0)):de(A.message||"登录失败")}catch(A){const Y=A instanceof Error?A.message:String(A);de(Y||"登录失败")}finally{S(!1)}},D=async()=>{try{await La()}catch(W){console.error("退出登录失败",W)}finally{t(!1),d(!1)}};if(k)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f5f5f7]",children:e.jsx(Le,{className:"w-8 h-8 text-[#0094f7] animate-spin"})});if(p)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-[#F4F5F7] p-4 relative overflow-hidden font-sans",children:[e.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),e.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-xl border border-white relative z-10 animate-fade-in",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"w-24 h-24 bg-[#0094f7] squircle flex items-center justify-center mx-auto mb-6 transition-all duration-500 p-4",style:{filter:"drop-shadow(0 8px 20px rgba(0,148,247,0.3))"},children:e.jsx("img",{src:"/static/ydisks-logo.svg",alt:"Ydisks",className:"w-full h-full"})}),e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"系统尚未初始化"}),e.jsx("p",{className:"text-gray-600 font-medium",children:"为避免默认口令风险,管理员必须通过服务器本机 CLI 初始化。"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-4 rounded-2xl bg-gray-50 border border-gray-100",children:[e.jsx("div",{className:"text-sm font-bold text-gray-900 mb-2",children:"请在服务器上执行:"}),e.jsx("pre",{className:"text-xs bg-black text-white p-4 rounded-2xl overflow-x-auto",children:yr?'.\\xianyu-server.exe -init-admin -db data\\xianyu_data.db -admin-password "请设置密码"':"./xianyu-server -init-admin -db data/xianyu_data.db -admin-password '请设置密码'"}),e.jsx("div",{className:"text-xs text-gray-500 mt-2",children:"完成后刷新页面即可进入登录。"})]}),e.jsxs("button",{type:"button",onClick:()=>window.location.reload(),className:"w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group",children:["我已初始化,刷新 ",e.jsx(qs,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})]}),e.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100 text-center",children:e.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Secure Bootstrap"})})]})]});if(!s)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-[#F4F5F7] p-4 relative overflow-hidden font-sans",children:[e.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),e.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-lg border border-white relative z-10 animate-fade-in",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("div",{className:"w-24 h-24 bg-[#0094f7] squircle flex items-center justify-center mx-auto mb-6 transition-all duration-500 cursor-pointer group p-4",style:{filter:"drop-shadow(0 8px 20px rgba(0,148,247,0.3))"},children:e.jsx("img",{src:"/static/ydisks-logo.svg",alt:"Ydisks",className:"w-full h-full group-hover:scale-110 transition-transform"})}),e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"欢迎回来"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"Ydisks闲鱼助手 · 自动发货与管家系统"})]}),e.jsxs("form",{onSubmit:B,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative group",children:[e.jsx(Os,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),e.jsx("input",{type:"text",placeholder:"管理员账号",value:f,onChange:W=>Q(W.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(ya,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),e.jsx("input",{type:"password",placeholder:"密码",value:se,onChange:W=>U(W.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),K&&e.jsxs("div",{className:"p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2",children:[e.jsx(Ms,{className:"w-4 h-4"})," ",K]}),e.jsx("button",{type:"submit",disabled:J,className:"w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70",children:J?e.jsx(Le,{className:"w-5 h-5 animate-spin"}):e.jsxs(e.Fragment,{children:["立即登录 ",e.jsx(qs,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]}),e.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100",children:e.jsx("div",{className:"mt-6 text-center",children:e.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Ydisks闲鱼助手 v1.0"})})})]})]});const Z=()=>{switch(u){case"dashboard":return e.jsx(Ps,{});case"accounts":return e.jsx(Kl,{});case"orders":return e.jsx(Zl,{});case"cards":return e.jsx(Hl,{});case"items":return e.jsx(tr,{onConfigureDelivery:W=>{ne({cookieId:W.cookie_id,itemId:W.item_id,requestId:Date.now()}),q("rules")}});case"rules":return e.jsx(pr,{initialDeliveryTarget:le,onDeliveryTargetHandled:()=>ne(void 0)});case"notifications":return e.jsx(br,{isAdmin:l});case"settings":return l?e.jsx(rr,{}):e.jsx(Ps,{});default:return e.jsx(Ps,{})}};return e.jsxs("div",{className:"flex min-h-screen bg-[#F4F5F7] text-[#111]",children:[e.jsx(ka,{activeTab:u,isAdmin:l,onNavigate:q,onLogout:D}),e.jsxs("main",{className:"flex-1 ml-64 p-8 md:p-12 overflow-y-auto h-screen relative scroll-smooth",children:[e.jsx("div",{className:"fixed top-0 right-0 w-[800px] h-[800px] bg-gradient-to-bl from-blue-50 to-transparent rounded-full blur-[120px] pointer-events-none -z-10 opacity-60"}),e.jsx("div",{className:"max-w-[1400px] mx-auto pb-10",children:Z()})]})]})},Gt=document.getElementById("root");if(!Gt)throw new Error("Could not find root element to mount to");const jr=Qt.createRoot(Gt);jr.render(e.jsx(Kt.StrictMode,{children:e.jsx(fr,{})}));
diff --git a/internal/webui/static/assets/index-D0gOrWMZ.css b/internal/webui/static/assets/index-D0gOrWMZ.css
deleted file mode 100644
index 0a75a3a..0000000
--- a/internal/webui/static/assets/index-D0gOrWMZ.css
+++ /dev/null
@@ -1 +0,0 @@
-*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{top:0;right:0;bottom:0;left:0}.-bottom-1{bottom:-.25rem}.-right-1{right:-.25rem}.-right-6{right:-1.5rem}.-top-6{top:-1.5rem}.bottom-10{bottom:2.5rem}.bottom-8{bottom:2rem}.bottom-\[-10\%\]{bottom:-10%}.left-0{left:0}.left-0\.5{left:.125rem}.left-1{left:.25rem}.left-1\.5{left:.375rem}.left-1\/2{left:50%}.left-4{left:1rem}.left-5{left:1.25rem}.left-\[-10\%\]{left:-10%}.right-0{right:0}.right-10{right:2.5rem}.right-2{right:.5rem}.right-3{right:.75rem}.right-4{right:1rem}.right-\[-10\%\]{right:-10%}.top-0{top:0}.top-0\.5{top:.125rem}.top-1{top:.25rem}.top-1\.5{top:.375rem}.top-1\/2{top:50%}.top-2{top:.5rem}.top-4{top:1rem}.top-\[-10\%\]{top:-10%}.top-\[calc\(100\%\+6px\)\]{top:calc(100% + 6px)}.-z-10{z-index:-10}.z-10{z-index:10}.z-20{z-index:20}.z-30{z-index:30}.z-40{z-index:40}.z-\[10000\]{z-index:10000}.col-span-2{grid-column:span 2 / span 2}.col-span-full{grid-column:1 / -1}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-1\.5{margin-bottom:.375rem}.mb-10{margin-bottom:2.5rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-2\.5{margin-bottom:.625rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.ml-64{margin-left:16rem}.mr-2{margin-right:.5rem}.mr-3{margin-right:.75rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.mt-auto{margin-top:auto}.line-clamp-1{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.line-clamp-2{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.block{display:block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.contents{display:contents}.hidden{display:none}.aspect-square{aspect-ratio:1 / 1}.h-10{height:2.5rem}.h-11{height:2.75rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-2\.5{height:.625rem}.h-20{height:5rem}.h-24{height:6rem}.h-28{height:7rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-32{height:8rem}.h-4{height:1rem}.h-40{height:10rem}.h-48{height:12rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-80{height:20rem}.h-9{height:2.25rem}.h-\[280px\]{height:280px}.h-\[300px\]{height:300px}.h-\[350px\]{height:350px}.h-\[48px\]{height:48px}.h-\[60\%\]{height:60%}.h-\[800px\]{height:800px}.h-auto{height:auto}.h-full{height:100%}.h-screen{height:100vh}.max-h-44{max-height:11rem}.max-h-48{max-height:12rem}.max-h-64{max-height:16rem}.max-h-\[380px\]{max-height:380px}.max-h-\[400px\]{max-height:400px}.max-h-\[420px\]{max-height:420px}.max-h-\[min\(64vh\,28rem\)\]{max-height:min(64vh,28rem)}.min-h-0{min-height:0px}.min-h-36{min-height:9rem}.min-h-64{min-height:16rem}.min-h-\[120px\]{min-height:120px}.min-h-\[150px\]{min-height:150px}.min-h-\[400px\]{min-height:400px}.min-h-screen{min-height:100vh}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-12{width:3rem}.w-14{width:3.5rem}.w-16{width:4rem}.w-2\.5{width:.625rem}.w-20{width:5rem}.w-24{width:6rem}.w-28{width:7rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-32{width:8rem}.w-4{width:1rem}.w-48{width:12rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-7{width:1.75rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-\[10\%\]{width:10%}.w-\[12\%\]{width:12%}.w-\[18\%\]{width:18%}.w-\[22\%\]{width:22%}.w-\[60\%\]{width:60%}.w-\[800px\]{width:800px}.w-fit{width:-moz-fit-content;width:fit-content}.w-full{width:100%}.min-w-0{min-width:0px}.min-w-64{min-width:16rem}.min-w-\[210px\]{min-width:210px}.min-w-\[260px\]{min-width:260px}.max-w-64{max-width:16rem}.max-w-6xl{max-width:72rem}.max-w-72{max-width:18rem}.max-w-\[12rem\]{max-width:12rem}.max-w-\[1400px\]{max-width:1400px}.max-w-\[15rem\]{max-width:15rem}.max-w-\[200px\]{max-width:200px}.max-w-\[240px\]{max-width:240px}.max-w-\[260px\]{max-width:260px}.max-w-\[280px\]{max-width:280px}.max-w-\[340px\]{max-width:340px}.max-w-\[80px\]{max-width:80px}.max-w-full{max-width:100%}.max-w-lg{max-width:32rem}.max-w-md{max-width:28rem}.max-w-xl{max-width:36rem}.flex-1{flex:1 1 0%}.flex-shrink-0,.shrink-0{flex-shrink:0}.table-fixed{table-layout:fixed}.border-collapse{border-collapse:collapse}.-translate-x-1\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-1{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-5{--tw-translate-x: 1.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-6{--tw-translate-x: 1.5rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-7{--tw-translate-x: 1.75rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-\[1\.02\]{--tw-scale-x: 1.02;--tw-scale-y: 1.02;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}@keyframes spin{to{transform:rotate(360deg)}}.cursor-pointer{cursor:pointer}.resize-none{resize:none}.resize-y{resize:vertical}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-5{gap:1.25rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.25rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(2rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-gray-100>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(243 244 246 / var(--tw-divide-opacity, 1))}.divide-gray-50>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(249 250 251 / var(--tw-divide-opacity, 1))}.self-end{align-self:flex-end}.self-center{align-self:center}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.overscroll-contain{overscroll-behavior:contain}.scroll-smooth{scroll-behavior:smooth}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:6px}.rounded-2xl,.rounded-3xl{border-radius:10px}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:7px}.rounded-md{border-radius:6px}.rounded-xl{border-radius:8px}.border{border-width:1px}.border-0{border-width:0px}.border-2{border-width:2px}.border-4{border-width:4px}.border-b{border-bottom-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-none{border-style:none}.border-\[\#0094f7\]{--tw-border-opacity: 1;border-color:rgb(0 148 247 / var(--tw-border-opacity, 1))}.border-amber-100{--tw-border-opacity: 1;border-color:rgb(254 243 199 / var(--tw-border-opacity, 1))}.border-amber-200{--tw-border-opacity: 1;border-color:rgb(253 230 138 / var(--tw-border-opacity, 1))}.border-amber-500{--tw-border-opacity: 1;border-color:rgb(245 158 11 / var(--tw-border-opacity, 1))}.border-blue-100{--tw-border-opacity: 1;border-color:rgb(219 234 254 / var(--tw-border-opacity, 1))}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-blue-600{--tw-border-opacity: 1;border-color:rgb(37 99 235 / var(--tw-border-opacity, 1))}.border-emerald-100{--tw-border-opacity: 1;border-color:rgb(209 250 229 / var(--tw-border-opacity, 1))}.border-emerald-500{--tw-border-opacity: 1;border-color:rgb(16 185 129 / var(--tw-border-opacity, 1))}.border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-gray-50{--tw-border-opacity: 1;border-color:rgb(249 250 251 / var(--tw-border-opacity, 1))}.border-green-200{--tw-border-opacity: 1;border-color:rgb(187 247 208 / var(--tw-border-opacity, 1))}.border-purple-100{--tw-border-opacity: 1;border-color:rgb(243 232 255 / var(--tw-border-opacity, 1))}.border-red-100{--tw-border-opacity: 1;border-color:rgb(254 226 226 / var(--tw-border-opacity, 1))}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-white{--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.border-white\/10{border-color:#ffffff1a}.bg-\[\#0094f7\]{--tw-bg-opacity: 1;background-color:rgb(0 148 247 / var(--tw-bg-opacity, 1))}.bg-\[\#F4F5F7\]{--tw-bg-opacity: 1;background-color:rgb(244 245 247 / var(--tw-bg-opacity, 1))}.bg-\[\#F7F8FA\]{--tw-bg-opacity: 1;background-color:rgb(247 248 250 / var(--tw-bg-opacity, 1))}.bg-\[\#FAFAFA\]{--tw-bg-opacity: 1;background-color:rgb(250 250 250 / var(--tw-bg-opacity, 1))}.bg-\[\#f5f5f7\]{--tw-bg-opacity: 1;background-color:rgb(245 245 247 / var(--tw-bg-opacity, 1))}.bg-amber-100{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.bg-amber-100\/70{background-color:#fef3c7b3}.bg-amber-50{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.bg-amber-50\/60{background-color:#fffbeb99}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-black{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.bg-black\/50{background-color:#00000080}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-100\/70{background-color:#dbeafeb3}.bg-blue-200\/30{background-color:#bfdbfe4d}.bg-blue-200\/40{background-color:#bfdbfe66}.bg-blue-400{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-blue-50\/50{background-color:#eff6ff80}.bg-blue-50\/60{background-color:#eff6ff99}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-emerald-100{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.bg-emerald-50{--tw-bg-opacity: 1;background-color:rgb(236 253 245 / var(--tw-bg-opacity, 1))}.bg-emerald-50\/60{background-color:#ecfdf599}.bg-emerald-600{--tw-bg-opacity: 1;background-color:rgb(5 150 105 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-100\/50{background-color:#f3f4f680}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.bg-gray-200\/50{background-color:#e5e7eb80}.bg-gray-300{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.bg-gray-400{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-50{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-orange-100{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.bg-orange-500{--tw-bg-opacity: 1;background-color:rgb(249 115 22 / var(--tw-bg-opacity, 1))}.bg-pink-50{--tw-bg-opacity: 1;background-color:rgb(253 242 248 / var(--tw-bg-opacity, 1))}.bg-purple-100{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.bg-purple-50{--tw-bg-opacity: 1;background-color:rgb(250 245 255 / var(--tw-bg-opacity, 1))}.bg-purple-50\/50{background-color:#faf5ff80}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.bg-purple-600{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.bg-red-100{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-slate-900{--tw-bg-opacity: 1;background-color:rgb(15 23 42 / var(--tw-bg-opacity, 1))}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-white\/5{background-color:#ffffff0d}.bg-white\/80{background-color:#fffc}.bg-white\/90{background-color:#ffffffe6}.bg-white\/95{background-color:#fffffff2}.bg-opacity-10{--tw-bg-opacity: .1}.bg-gradient-to-bl{background-image:linear-gradient(to bottom left,var(--tw-gradient-stops))}.from-blue-50{--tw-gradient-from: #eff6ff var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 246 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.to-transparent{--tw-gradient-to: transparent var(--tw-gradient-to-position)}.object-contain{-o-object-fit:contain;object-fit:contain}.object-cover{-o-object-fit:cover;object-fit:cover}.p-0{padding:0}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-12{padding:3rem}.p-16{padding:4rem}.p-2{padding:.5rem}.p-2\.5{padding:.625rem}.p-20{padding:5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-10{padding-left:2.5rem;padding-right:2.5rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-16{padding-top:4rem;padding-bottom:4rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-20{padding-top:5rem;padding-bottom:5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-3\.5{padding-top:.875rem;padding-bottom:.875rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-5{padding-top:1.25rem;padding-bottom:1.25rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.pb-10{padding-bottom:2.5rem}.pb-24{padding-bottom:6rem}.pl-10{padding-left:2.5rem}.pl-11{padding-left:2.75rem}.pl-14{padding-left:3.5rem}.pl-2{padding-left:.5rem}.pl-4{padding-left:1rem}.pl-5{padding-left:1.25rem}.pl-6{padding-left:1.5rem}.pr-10{padding-right:2.5rem}.pr-11{padding-right:2.75rem}.pr-12{padding-right:3rem}.pr-2{padding-right:.5rem}.pr-4{padding-right:1rem}.pr-6{padding-right:1.5rem}.pt-1{padding-top:.25rem}.pt-4{padding-top:1rem}.pt-5{padding-top:1.25rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-black{font-weight:900}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.leading-4{line-height:1rem}.leading-5{line-height:1.25rem}.leading-6{line-height:1.5rem}.leading-relaxed{line-height:1.625}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.tracking-widest{letter-spacing:.1em}.text-\[\#0094f7\]{--tw-text-opacity: 1;color:rgb(0 148 247 / var(--tw-text-opacity, 1))}.text-\[\#111\]{--tw-text-opacity: 1;color:rgb(17 17 17 / var(--tw-text-opacity, 1))}.text-amber-600{--tw-text-opacity: 1;color:rgb(217 119 6 / var(--tw-text-opacity, 1))}.text-amber-700{--tw-text-opacity: 1;color:rgb(180 83 9 / var(--tw-text-opacity, 1))}.text-amber-800{--tw-text-opacity: 1;color:rgb(146 64 14 / var(--tw-text-opacity, 1))}.text-amber-800\/80{color:#92400ecc}.text-amber-900{--tw-text-opacity: 1;color:rgb(120 53 15 / var(--tw-text-opacity, 1))}.text-amber-900\/90{color:#78350fe6}.text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-blue-800{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.text-blue-900{--tw-text-opacity: 1;color:rgb(30 58 138 / var(--tw-text-opacity, 1))}.text-blue-950{--tw-text-opacity: 1;color:rgb(23 37 84 / var(--tw-text-opacity, 1))}.text-emerald-600{--tw-text-opacity: 1;color:rgb(5 150 105 / var(--tw-text-opacity, 1))}.text-emerald-700{--tw-text-opacity: 1;color:rgb(4 120 87 / var(--tw-text-opacity, 1))}.text-emerald-800{--tw-text-opacity: 1;color:rgb(6 95 70 / var(--tw-text-opacity, 1))}.text-gray-100{--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-700{--tw-text-opacity: 1;color:rgb(21 128 61 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-orange-700{--tw-text-opacity: 1;color:rgb(194 65 12 / var(--tw-text-opacity, 1))}.text-pink-600{--tw-text-opacity: 1;color:rgb(219 39 119 / var(--tw-text-opacity, 1))}.text-purple-500{--tw-text-opacity: 1;color:rgb(168 85 247 / var(--tw-text-opacity, 1))}.text-purple-600{--tw-text-opacity: 1;color:rgb(147 51 234 / var(--tw-text-opacity, 1))}.text-purple-700{--tw-text-opacity: 1;color:rgb(126 34 206 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-red-700{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-red-900{--tw-text-opacity: 1;color:rgb(127 29 29 / var(--tw-text-opacity, 1))}.text-slate-400{--tw-text-opacity: 1;color:rgb(148 163 184 / var(--tw-text-opacity, 1))}.text-slate-950{--tw-text-opacity: 1;color:rgb(2 6 23 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-white\/30{color:#ffffff4d}.accent-\[\#0094f7\]{accent-color:#0094f7}.opacity-0{opacity:0}.opacity-10{opacity:.1}.opacity-20{opacity:.2}.opacity-30{opacity:.3}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-75{opacity:.75}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_20px_60px_-15px_rgba\(0\,0\,0\,0\.05\)\]{--tw-shadow: 0 20px 60px -15px rgba(0,0,0,.05);--tw-shadow-colored: 0 20px 60px -15px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[4px_0_24px_rgba\(0\,0\,0\,0\.02\)\]{--tw-shadow: 4px 0 24px rgba(0,0,0,.02);--tw-shadow-colored: 4px 0 24px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-inner{--tw-shadow: inset 0 2px 4px 0 rgb(0 0 0 / .05);--tw-shadow-colored: inset 0 2px 4px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-blue-100{--tw-shadow-color: #dbeafe;--tw-shadow: var(--tw-shadow-colored)}.shadow-blue-200{--tw-shadow-color: #bfdbfe;--tw-shadow: var(--tw-shadow-colored)}.shadow-emerald-100{--tw-shadow-color: #d1fae5;--tw-shadow: var(--tw-shadow-colored)}.shadow-gray-200{--tw-shadow-color: #e5e7eb;--tw-shadow: var(--tw-shadow-colored)}.shadow-gray-200\/70{--tw-shadow-color: rgb(229 231 235 / .7);--tw-shadow: var(--tw-shadow-colored)}.outline-none{outline:2px solid transparent;outline-offset:2px}.ring-4{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-white{--tw-ring-opacity: 1;--tw-ring-color: rgb(255 255 255 / var(--tw-ring-opacity, 1))}.blur-2xl{--tw-blur: blur(40px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.blur-\[120px\]{--tw-blur: blur(120px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.drop-shadow{--tw-drop-shadow: drop-shadow(0 1px 2px rgb(0 0 0 / .1)) drop-shadow(0 1px 1px rgb(0 0 0 / .06));filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur{--tw-backdrop-blur: blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-3xl{--tw-backdrop-blur: blur(64px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.squircle{-webkit-mask-image:url(/static/assets/squircle-rb6SKa34.svg);mask-image:url(/static/assets/squircle-rb6SKa34.svg);-webkit-mask-size:contain;mask-size:contain;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-position:center;mask-position:center;border-radius:0}*{box-sizing:border-box;margin:0;padding:0}html,body,#root{height:100%;width:100%}body{font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;background-color:#f4f5f7;color:#fff;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.ios-card{background:#fff;border-radius:8px;border:1px solid rgba(0,0,0,.02);box-shadow:0 8px 24px #0000000a;transition:transform .2s ease,box-shadow .2s ease}.ios-card:hover{box-shadow:0 12px 32px #0000000f}.ios-input{background:#f7f8fa;border:1px solid transparent;transition:all .3s cubic-bezier(.25,.8,.25,1);color:#111;font-weight:500}.ios-input:focus{background:#fff;border-color:#0094f7;box-shadow:0 0 0 4px #0094f74d;outline:none}.ios-input::-moz-placeholder{color:#9ca3af;font-weight:400}.ios-input::placeholder{color:#9ca3af;font-weight:400}.ios-btn-primary{background:#0094f7;color:#fff;font-weight:700;border:none;transition:all .2s cubic-bezier(.25,.8,.25,1);cursor:pointer}.ios-btn-primary:hover:not(:disabled){background:#0071e3;transform:translateY(-1px);box-shadow:0 8px 20px #0094f74d}.ios-btn-primary:active:not(:disabled){transform:translateY(1px);box-shadow:0 2px 8px #0094f733}.ios-btn-primary:disabled{background:#f0f0f0;color:#aaa;box-shadow:none;transform:none;cursor:not-allowed}.ios-btn-secondary{background:#f7f8fa;color:#fff;font-weight:600;border:1px solid transparent;transition:all .2s ease;cursor:pointer}.ios-btn-secondary:hover{background:#e5e7eb;border-color:#d1d5db}.ios-btn-danger{background:#fee2e2;color:#dc2626;font-weight:600;border:1px solid transparent;transition:all .2s ease;cursor:pointer}.ios-btn-danger:hover{background:#fecaca;border-color:#fca5a5}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:#0000001a;border-radius:10px}::-webkit-scrollbar-thumb:hover{background:#0003}@keyframes fadeIn{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in{animation:fadeIn .5s cubic-bezier(.16,1,.3,1) forwards}@keyframes slideUp{0%{opacity:0;transform:translateY(30px) scale(.95)}to{opacity:1;transform:translateY(0) scale(1)}}.animate-slide-up{animation:slideUp .3s cubic-bezier(.16,1,.3,1) forwards}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}@keyframes pulse{0%,to{opacity:1}50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}::-moz-selection{background:#0094f7;color:#fff}::selection{background:#0094f7;color:#fff}.text-brand{color:#0094f7}.bg-brand{background-color:#0094f7}.border-brand{border-color:#0094f7}.status-badge{display:inline-flex;align-items:center;padding:4px 12px;border-radius:9999px;font-size:12px;font-weight:600}.status-badge-success{background-color:#d1fae5;color:#065f46}.status-badge-warning{background-color:#fef3c7;color:#92400e}.status-badge-error{background-color:#fee2e2;color:#991b1b}.status-badge-info{background-color:#dbeafe;color:#1e40af}.loading-skeleton{background:linear-gradient(90deg,#f3f4f6,#e5e7eb,#f3f4f6);background-size:200% 100%;animation:loading 1.5s ease-in-out infinite}@keyframes loading{0%{background-position:200% 0}to{background-position:-200% 0}}.modal-overlay{position:fixed;top:0;right:0;bottom:0;left:0;z-index:9999;display:flex;align-items:center;justify-content:center;background-color:#0006;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);padding:1rem;overflow-y:auto}.modal-container{position:relative;width:100%;max-width:42rem;max-height:85vh;margin:auto;display:flex;flex-direction:column;background-color:#fff;border-radius:10px;box-shadow:0 25px 50px -12px #00000040;overflow:hidden}.modal-header{flex-shrink:0;padding:2rem 2rem 1.5rem;border-bottom:1px solid #F3F4F6;background-color:#fff;z-index:10}.modal-body{flex:1 1 auto;overflow-y:auto;overflow-x:hidden;padding:2rem}.modal-footer{flex-shrink:0;padding:1.5rem 2rem 2rem;border-top:1px solid #F3F4F6;background-color:#fff;z-index:10}.modal-container-lg{max-width:64rem}.modal-overlay-centered{position:fixed;top:0;right:0;bottom:0;left:0;z-index:9999;display:flex;justify-content:center;background-color:#0006;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);padding:1rem;overflow-y:auto}.modal-overlay-centered .modal-container{position:relative;width:100%;max-width:42rem;max-height:85vh;margin:auto 0;display:flex;flex-direction:column;background-color:#fff;border-radius:10px;box-shadow:0 25px 50px -12px #00000040;overflow:hidden}@media(max-width:768px){.ios-card{border-radius:6px}.ios-input{font-size:16px}.modal-container{max-width:calc(100% - 2rem);max-height:90vh;border-radius:8px}.modal-header,.modal-body,.modal-footer{padding-left:1.5rem;padding-right:1.5rem}}.hover\:translate-y-\[-4px\]:hover{--tw-translate-y: -4px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:scale-105:hover{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:border-\[\#0094f7\]:hover{--tw-border-opacity: 1;border-color:rgb(0 148 247 / var(--tw-border-opacity, 1))}.hover\:border-amber-300:hover{--tw-border-opacity: 1;border-color:rgb(252 211 77 / var(--tw-border-opacity, 1))}.hover\:border-blue-300:hover{--tw-border-opacity: 1;border-color:rgb(147 197 253 / var(--tw-border-opacity, 1))}.hover\:border-emerald-300:hover{--tw-border-opacity: 1;border-color:rgb(110 231 183 / var(--tw-border-opacity, 1))}.hover\:border-gray-300:hover{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.hover\:border-gray-400:hover{--tw-border-opacity: 1;border-color:rgb(156 163 175 / var(--tw-border-opacity, 1))}.hover\:bg-\[\#0071e3\]:hover{--tw-bg-opacity: 1;background-color:rgb(0 113 227 / var(--tw-bg-opacity, 1))}.hover\:bg-\[\#0094f7\]:hover{--tw-bg-opacity: 1;background-color:rgb(0 148 247 / var(--tw-bg-opacity, 1))}.hover\:bg-\[\#FFFDE7\]\/50:hover{background-color:#fffde780}.hover\:bg-amber-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.hover\:bg-black:hover{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-100:hover{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-50:hover{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-100:hover{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-50:hover{--tw-bg-opacity: 1;background-color:rgb(236 253 245 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-50\/50:hover{background-color:#ecfdf580}.hover\:bg-emerald-700:hover{--tw-bg-opacity: 1;background-color:rgb(4 120 87 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-50:hover{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-800:hover{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.hover\:bg-green-100:hover{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.hover\:bg-green-50:hover{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.hover\:bg-purple-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.hover\:bg-red-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.hover\:bg-red-50:hover{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.hover\:bg-white:hover{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.hover\:bg-white\/10:hover{background-color:#ffffff1a}.hover\:text-\[\#0094f7\]:hover{--tw-text-opacity: 1;color:rgb(0 148 247 / var(--tw-text-opacity, 1))}.hover\:text-black:hover{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.hover\:text-blue-600:hover{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.hover\:text-gray-600:hover{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.hover\:text-gray-700:hover{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.hover\:text-gray-900:hover{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.hover\:text-green-600:hover{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.hover\:text-red-500:hover{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus\:border-blue-400:focus{--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-0:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-\[\#0094f7\]:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(0 148 247 / var(--tw-ring-opacity, 1))}.active\:scale-95:active{--tw-scale-x: .95;--tw-scale-y: .95;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-25:disabled{opacity:.25}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}.disabled\:opacity-70:disabled{opacity:.7}.group:focus-within .group-focus-within\:text-\[\#0094f7\]{--tw-text-opacity: 1;color:rgb(0 148 247 / var(--tw-text-opacity, 1))}.group:focus-within .group-focus-within\:text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:translate-x-1{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-105{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-110{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-125{--tw-scale-x: 1.25;--tw-scale-y: 1.25;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.group:hover .group-hover\:text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:opacity-100{opacity:1}@media(min-width:640px){.sm\:w-72{width:18rem}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.sm\:grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.sm\:grid-cols-\[1fr_180px\]{grid-template-columns:1fr 180px}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-8{gap:2rem}}@media(min-width:768px){.md\:col-span-2{grid-column:span 2 / span 2}.md\:col-span-3{grid-column:span 3 / span 3}.md\:col-span-full{grid-column:1 / -1}.md\:w-auto{width:auto}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.md\:grid-cols-\[1\.4fr_110px_40px\]{grid-template-columns:1.4fr 110px 40px}.md\:grid-cols-\[180px_1fr\]{grid-template-columns:180px 1fr}.md\:grid-cols-\[1fr_1fr_1\.4fr_110px_40px\]{grid-template-columns:1fr 1fr 1.4fr 110px 40px}.md\:flex-row{flex-direction:row}.md\:items-end{align-items:flex-end}.md\:items-center{align-items:center}.md\:justify-between{justify-content:space-between}.md\:border-l{border-left-width:1px}.md\:border-t-0{border-top-width:0px}.md\:p-12{padding:3rem}.md\:pl-6{padding-left:1.5rem}.md\:pt-0{padding-top:0}}@media(min-width:1024px){.lg\:col-span-2{grid-column:span 2 / span 2}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:grid-cols-\[320px_1fr\]{grid-template-columns:320px 1fr}.lg\:flex-row{flex-direction:row}.lg\:items-center{align-items:center}.lg\:self-auto{align-self:auto}}@media(min-width:1280px){.xl\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.xl\:flex-row{flex-direction:row}.xl\:items-end{align-items:flex-end}.xl\:justify-between{justify-content:space-between}}@media(min-width:1536px){.\32xl\:grid-cols-\[360px_1fr\]{grid-template-columns:360px 1fr}}
diff --git a/internal/webui/static/assets/index-DWScSBc3.js b/internal/webui/static/assets/index-DWScSBc3.js
new file mode 100644
index 0000000..e7ed37e
--- /dev/null
+++ b/internal/webui/static/assets/index-DWScSBc3.js
@@ -0,0 +1,19 @@
+import{j as e,r as n,b as Se,c as ra,d as na}from"./react-vendor-DZnRGM0-.js";import{L as ia,U as Pt,S as Tt,C as zs,B as Et,Z as Us,a as xs,b as Ys,c as Ft,d as oa,e as ms,A as rt,D as ca,f as nt,P as Dt,g as Ns,E as Mt,T as da,h as xa,i as Te,Q as Ps,j as ns,k as Ge,l as ds,m as it,R as qe,n as Ot,o as ma,p as Je,X as we,K as ua,q as rs,r as es,s as Ke,t as Qe,u as ot,v as qt,w as us,x as pa,y as ha,z as js,F as ga,G as ba,H as ct,I as dt,J as fa,M as ya,N as ja,O as Na,V as Ts,W as _s,Y as Bt,_ as va,$ as _a,a0 as Ws,a1 as wa,a2 as ka,a3 as Vs,a4 as xt,a5 as Ca,a6 as Ls,a7 as zt,a8 as Sa,a9 as La,aa as Zs,ab as Ut,ac as Aa,ad as Ia}from"./icons-vendor-RenKjhri.js";import{R as ws,B as $a,X as mt,Y as ut,T as Es,a as Ra,C as Fs,A as Pa,b as Ta,c as Ea,P as pt,d as ht,L as Fa}from"./charts-vendor-B_BfwiL0.js";import"./vendor-w5t2K9ux.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const h of document.querySelectorAll('link[rel="modulepreload"]'))c(h);new MutationObserver(h=>{for(const f of h)if(f.type==="childList")for(const L of f.addedNodes)L.tagName==="LINK"&&L.rel==="modulepreload"&&c(L)}).observe(document,{childList:!0,subtree:!0});function l(h){const f={};return h.integrity&&(f.integrity=h.integrity),h.referrerPolicy&&(f.referrerPolicy=h.referrerPolicy),h.crossOrigin==="use-credentials"?f.credentials="include":h.crossOrigin==="anonymous"?f.credentials="omit":f.credentials="same-origin",f}function c(h){if(h.ep)return;h.ep=!0;const f=l(h);fetch(h.href,f)}})();const Da=({className:s="w-full h-full text-white"})=>e.jsx("svg",{className:s,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),Gs=({sizeClass:s="w-12 h-12",logoClassName:t="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${s} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"#0094f7"}),e.jsx("stop",{offset:"100%",stopColor:"#287efe"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23.51 12.25 L 27.29 10.34 L 31.54 8.78 L 36.33 7.56 L 41.84 6.69 L 48.52 6.17 L 60.00 6.00 L 71.48 6.17 L 78.16 6.69 L 83.67 7.56 L 88.46 8.78 L 92.71 10.34 L 96.49 12.25 L 99.87 14.52 L 102.86 17.14 L 105.48 20.13 L 107.75 23.51 L 109.66 27.29 L 111.22 31.54 L 112.44 36.33 L 113.31 41.84 L 113.83 48.52 Z",fill:"url(#login-squircle-gradient)"})]}),e.jsx("div",{className:"relative z-10 flex items-center justify-center w-full h-full",children:e.jsx(Da,{className:t})})]})]}),Ma=({activeTab:s,isAdmin:t=!1,onNavigate:l,onLogout:c})=>{const h=[{id:"dashboard",icon:ia,label:"仪表盘"},{id:"accounts",icon:Pt,label:"账号管理"},{id:"orders",icon:Tt,label:"订单管理"},{id:"cards",icon:zs,label:"卡密库存"},{id:"items",icon:Et,label:"商品列表"},{id:"rules",icon:Us,label:"自动化规则"},{id:"notifications",icon:xs,label:"通知设置"},...t?[{id:"settings",icon:Ys,label:"系统与AI"}]:[]];return e.jsxs("div",{className:"w-64 h-screen fixed left-0 top-0 bg-white border-r border-gray-100 flex flex-col justify-between z-20 shadow-[4px_0_24px_rgba(0,0,0,0.02)]",children:[e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-12 px-2",children:[e.jsx("div",{className:"shrink-0",children:e.jsx(Gs,{sizeClass:"w-10 h-10"})}),e.jsxs("h1",{className:"text-xl font-extrabold tracking-tight text-gray-900",children:["Ydisks闲鱼助手 ",e.jsx("span",{className:"text-xs bg-[#0094f7] text-white px-1.5 py-0.5 rounded ml-1",children:"PRO"})]})]}),e.jsx("nav",{className:"space-y-2",children:h.map(f=>{const L=f.icon,F=s===f.id;return e.jsxs("button",{onClick:()=>l(f.id),className:`w-full flex items-center gap-3 px-4 py-3.5 rounded-2xl transition-all duration-300 group relative overflow-hidden ${F?"bg-[#0094f7] text-white font-bold shadow-lg shadow-blue-100 transform scale-[1.02]":"text-gray-500 hover:bg-gray-50 hover:text-gray-900"}`,children:[e.jsx(L,{className:`w-5 h-5 transition-colors ${F?"text-white":"text-gray-400 group-hover:text-gray-600"}`}),e.jsx("span",{className:"text-sm tracking-wide",children:f.label}),F&&e.jsx(Ft,{className:"w-4 h-4 absolute right-3 text-white/30 animate-pulse"})]},f.id)})})]}),e.jsx("div",{className:"p-6 border-t border-gray-50",children:e.jsxs("button",{onClick:c,className:"w-full flex items-center gap-3 px-4 py-3 text-gray-500 hover:text-red-500 hover:bg-red-50 rounded-2xl transition-all duration-200 font-medium",children:[e.jsx(oa,{className:"w-5 h-5"}),e.jsx("span",{className:"text-sm",children:"退出登录"})]})})]})},Oa=3e4,qa=10*6e4;let Ds=!1;const Wt=()=>{Ds||typeof window>"u"||(Ds=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{Ds=!1}))},Ba=s=>{if(!s)return"";const t=new URLSearchParams;for(const[c,h]of Object.entries(s))h!=null&&t.set(c,String(h));const l=t.toString();return l?`?${l}`:""},$s=async(s,t,l={})=>{var I;const c=Ba(l.params),h=`${t}${c}`,f=Vt(l.signal,l.timeoutMs??Oa);let L;try{L=await fetch(h,{method:s,credentials:"include",signal:f.signal,headers:{...l.body===void 0?{}:{"Content-Type":"application/json"}},body:l.body===void 0?void 0:JSON.stringify(l.body)})}catch(j){throw f.signal.aborted?new Error((I=l.signal)!=null&&I.aborted?"请求已取消":"请求超时,请稍后重试"):j}finally{f.cleanup()}const g=(L.headers.get("content-type")||"").includes("application/json");if(!L.ok){L.status===401&&!l.skipAuthLogout&&Wt();const j=g?await L.json().catch(()=>{}):await L.text().catch(()=>{}),G=typeof j=="string"?j:(j==null?void 0:j.detail)||(j==null?void 0:j.message)||(j==null?void 0:j.msg);throw new Error(G||`请求失败: ${L.status}`)}return g?await L.json():await L.text()},ge=async(s,t,l)=>$s("GET",s,{params:t,...l}),be=async(s,t,l)=>$s("POST",s,{body:t,...l}),Ee=async(s,t,l)=>$s("PUT",s,{body:t,...l}),Ue=async(s,t,l)=>$s("DELETE",s,{params:t,...l}),vs=async(s,t,l={})=>{var g;const c=Vt(l.signal,l.timeoutMs??qa);let h;try{h=await fetch(s,{method:"POST",credentials:"include",signal:c.signal,body:t})}catch(I){throw c.signal.aborted?new Error((g=l.signal)!=null&&g.aborted?"请求已取消":"上传超时,请稍后重试"):I}finally{c.cleanup()}const F=(h.headers.get("content-type")||"").includes("application/json")?await h.json().catch(()=>{}):await h.text().catch(()=>{});if(!h.ok){h.status===401&&Wt();const I=typeof F=="string"?F:(F==null?void 0:F.detail)||(F==null?void 0:F.message)||(F==null?void 0:F.msg),j=new Error(I||"请求失败: "+h.status);throw j.payload=F,j}return F},Vt=(s,t)=>{const l=new AbortController,c=()=>l.abort(s==null?void 0:s.reason);s!=null&&s.aborted?c():s==null||s.addEventListener("abort",c,{once:!0});const h=globalThis.setTimeout(()=>l.abort(new DOMException("timeout","TimeoutError")),Math.max(1,t));return{signal:l.signal,cleanup:()=>{globalThis.clearTimeout(h),s==null||s.removeEventListener("abort",c)}}},As=s=>{const t=s.getFullYear(),l=String(s.getMonth()+1).padStart(2,"0"),c=String(s.getDate()).padStart(2,"0");return`${t}-${l}-${c}`},Xs=(s,t)=>{const l=new Date(s);return l.setHours(12,0,0,0),l.setDate(l.getDate()+t),l},Js=(s,t)=>({startDate:As(Xs(s,-(t-1))),endDate:As(s)}),gt=(s,t=new Date,l="",c="")=>{if(s==="custom"&&l&&c){if(l>c)throw new Error("开始日期不能晚于结束日期");return{startDate:l,endDate:c}}return s==="yesterday"?Js(Xs(t,-1),1):Js(t,s==="3days"?3:s==="30days"?30:s==="today"?1:7)},za=s=>{const t=new Date(`${s.startDate}T12:00:00`),l=new Date(`${s.endDate}T12:00:00`),c=Math.round((l.getTime()-t.getTime())/864e5)+1,h=Xs(t,-1);return Js(h,c)},Ua=s=>{const t={...s};if("renewal_log_retention_days"in t){const l=Number(t.renewal_log_retention_days);t.renewal_log_retention_days=Number.isFinite(l)?l:10}return t},Wa=async s=>be("/login",s,{skipAuthLogout:!0}),Gt=async()=>ge("/verify"),Va=async()=>be("/logout",{}),Ga=async s=>Ee("/account/credentials",s),Ja=(s,t)=>{const l=s.avatar_url||"";if(!l)return"";try{const c=new URL(l,window.location.origin);return c.hostname.endsWith("alicdn.com")&&c.searchParams.set("_v",t),c.toString()}catch{return l}},Rs=async s=>{const t=await ge("/cookies/details",void 0,s),l=Date.now().toString();return t.map(c=>({id:c.id,value:"",cookie:"",enabled:c.enabled,auto_confirm:c.auto_confirm,remark:c.remark,note:c.remark,pause_duration:c.pause_duration,paused_until:Number(c.paused_until||0),paused:c.paused===!0,username:c.username||"",login_password:"",show_browser:c.show_browser===!0||c.show_browser===1||c.show_browser==="1"||c.show_browser==="true",nickname:c.nickname||c.remark||`账号 ${c.id.substring(0,6)}`,avatar_url:Ja(c,l),profile_error:c.profile_error||"",ai_enabled:!1}))},Qa=async s=>ge("/cookies/runtime-status",void 0,s),Ka=async s=>be("/qr-login/generate",void 0,s),Ya=async(s,t)=>ge(`/qr-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),Za=async(s,t)=>be(`/qr-login/complete-verification/${s}`,{target_account_id:t||""}),Xa=async(s,t)=>Ee(`/cookies/${s}/status`,{enabled:t}),Ha=async s=>Ue(`/cookies/${s}`),el=async(s,t)=>Ee(`/cookies/${s}/pause-duration`,{pause_duration:t}),sl=async(s,t)=>Ee(`/cookies/${s}/settings`,t),tl=async s=>ge(`/cookies/${s}/long-login`),al=async(s,t)=>Ee(`/cookies/${s}/long-login`,{enabled:t}),ll=async s=>be("/password-login",s),rl=async(s,t)=>ge(`/password-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),nl=async s=>Ue(`/password-login/cancel/${s}`),il=async s=>be(`/cookies/${s}/refresh-profile`,{}),ol=async s=>ge("/ai-reply-settings",void 0,s),Jt=s=>{const t=String(s||"");return t==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(t)?t:"unknown"},cl=async(s,t,l=1,c=20,h)=>{const f={page:l,page_size:c};s&&(f.cookie_id=s),t&&t!=="all"&&(f.status=t),h!=null&&h.trim()&&(f.search=h.trim());const L=await ge("/api/orders",f),g=(L.orders||L.data||[]).map(I=>({...I,id:I.id||I.order_id,status:Jt(I.status||I.order_status),quantity:Number(I.quantity||1)}));return{success:!0,data:g,total:L.total||g.length,page:L.page||l,page_size:L.page_size||c,total_pages:L.total_pages||1}},dl=async(s,t)=>Ee(`/api/orders/${s}`,t),xl=async s=>Ue(`/api/orders/${s}`),ml=async(s,t)=>{const l=new FormData;return s&&l.append("cookie_id",s),t&&l.append("status",t),vs("/api/orders/refresh",l)},ul=async s=>be(`/api/orders/${s}/refresh`),pl=async(s,t)=>be("/api/orders/manual-ship",{order_ids:s,ship_mode:t}),hl=async s=>s instanceof FormData?vs("/api/orders/import",s):be("/api/orders/import",s),gl=async()=>ge("/dashboard/stats"),bt=async(s=7)=>{let t;if(typeof s=="number"){const l=new Date,c=new Date;c.setDate(c.getDate()-s),t={start_date:As(c),end_date:As(l)}}else t=s;return ge("/analytics/orders",{...t,timezone_offset_minutes:-new Date().getTimezoneOffset()})},bl=async s=>{const t=await ge("/analytics/orders/valid",{start_date:s.start_date,end_date:s.end_date,timezone_offset_minutes:-new Date().getTimezoneOffset()}),c=(Array.isArray(t)?t:t.orders||[]).map(h=>({...h,id:h.id||h.order_id,status:Jt(h.status||h.order_status),quantity:Number(h.quantity||1)}));return{orders:c,total:Array.isArray(t)?c.length:Number(t.total??c.length),truncated:Array.isArray(t)?!1:t.truncated===!0}},fl=s=>{let t=s.api_config;if(typeof t=="string"&&t.trim())try{t=JSON.parse(t)}catch{t=void 0}return{...s,api_config:t||void 0}},Qt=s=>({...s,api_config:s.api_config?JSON.stringify(s.api_config):""}),Ve=async()=>{const s=await ge("/cards");return(Array.isArray(s)?s:s.cards||[]).map(fl)},yl=async s=>be("/cards",Qt(s)),ft=async(s,t)=>Ee(`/cards/${s}`,Qt(t)),jl=async s=>Ue(`/cards/${s}`),Nl=async s=>{const t=new FormData;return t.append("file",s),vs("/cards/batch",t)},vl=async(s,t)=>be(`/cards/${s}/append-data`,{content:t}),Ms=s=>s===!0||s===1||s==="1",ps=async s=>{const t=await ge("/items",void 0);return(Array.isArray(t)?t:t.items||[]).map(c=>({...c,id:c.id||`${c.cookie_id}-${c.item_id}`,is_multi_spec:Ms(c.is_multi_spec),is_multi_qty_ship:Ms(c.is_multi_qty_ship??c.multi_quantity_delivery),multi_quantity_delivery:Ms(c.multi_quantity_delivery??c.is_multi_qty_ship)}))},_l=async s=>be("/items/get-all-from-account",{cookie_id:s}),wl=async(s,t)=>Ue(`/items/${s}/${t}`),kl=async(s,t)=>be(`/items/${s}`,t),Cl=async s=>{const t=new FormData;t.set("cookie_id",s.cookie_id),t.set("title",s.title),t.set("description",s.description),t.set("price",s.price),t.set("original_price",s.original_price||""),t.set("quantity",String(s.quantity)),t.set("postage_mode",s.postage_mode),t.set("postage",s.postage||"");for(const l of s.images)t.append("images",l);return vs("/items/publish",t)},Sl=async s=>{const t=new FormData;return t.set("file",s.file),s.imagesZip&&t.set("images_zip",s.imagesZip),s.defaultCookieId&&t.set("default_cookie_id",s.defaultCookieId),vs("/items/publish-batches/preview",t)},Ll=async s=>be("/items/publish-batches",{preview_id:s}),os=async s=>ge(`/items/publish-batches/${s}`),yt=async(s=20)=>{const t=await ge("/items/publish-batches",{limit:s});return Array.isArray(t)?t:t.batches||[]},Al=async s=>Ue(`/items/publish-batches/${s}`),Il=async s=>be(`/items/publish-batches/${s}/cancel`,{}),$l=async s=>be(`/items/publish-batches/${s}/retry-failed`,{}),Rl=async(s,t,l)=>Ee(`/items/${s}/${t}`,l),Is=async()=>{const s=await ge("/automation-rules");return(Array.isArray(s)?s:s.data||s.rules||[]).map(l=>{var c,h;return{id:String(l.id),name:l.name||"",trigger_type:l.trigger_type||"order_paid",item_keyword:l.item_title||l.item_id||"",cookie_id:l.cookie_id||"",item_id:l.item_id||"",item_title:l.item_title||"",card_group_id:Number(((c=(l.actions||[]).find(f=>f.action_type==="send_card"))==null?void 0:c.card_id)||0),card_group_name:((h=(l.actions||[]).find(f=>f.action_type==="send_card"))==null?void 0:h.card_name)||"",priority:l.priority||100,enabled:l.enabled||!1,config_json:l.config_json||"{}",actions:(l.actions||[]).map(f=>({id:f.id?String(f.id):void 0,action_type:f.action_type,card_id:Number(f.card_id||0),card_name:f.card_name||"",delivery_count:Number(f.delivery_count||1),message_template:f.message_template||"",delay_seconds:Number(f.delay_seconds||0),config_json:f.config_json||"{}",enabled:f.enabled!==!1,sort_order:Number(f.sort_order||0)})),variants:(l.actions||[]).filter(f=>f.action_type==="send_card").map(f=>{let L={};try{L=JSON.parse(f.config_json||"{}")}catch{}return{id:f.id?String(f.id):void 0,spec_name:L.spec_name||"",spec_value:L.spec_value||"",card_id:Number(f.card_id||0),card_name:f.card_name||"",delivery_count:Number(f.delivery_count||1),enabled:f.enabled!==!1,delay_override:L.delay_override===!0,delay_seconds:Number(f.delay_seconds||0),config_json:f.config_json||"{}"}})}})},Pl=(s,t)=>{if(s!=="order_paid")return t.map((h,f)=>({...h,sort_order:h.sort_order||f+1}));const l=t.filter(h=>h.action_type==="send_card").map((h,f)=>({...h,sort_order:f+1})),c=t.filter(h=>h.action_type!=="send_card"&&h.action_type!=="confirm_shipment");return[...l,...c.map((h,f)=>({...h,sort_order:l.length+f+1})),{action_type:"confirm_shipment",enabled:!0,sort_order:l.length+c.length+1}]},jt=async s=>{const t=s.trigger_type||"order_paid",c=[{order_paid:"付款后自动发货",buyer_reviewed:"评价后发送赠品",review_missing_timeout:"超时未评价求评价"}[t]||"自动化规则",s.item_title||s.item_id||s.cookie_id||""].filter(Boolean).join(" - "),h=(s.actions||[]).filter(g=>g.action_type!=="send_card"&&g.action_type!=="confirm_shipment"),f=s.variants&&s.variants.length>0?[...s.variants.map((g,I)=>({action_type:"send_card",card_id:g.card_id,delivery_count:g.delivery_count||1,enabled:g.enabled!==!1,sort_order:I+1,delay_seconds:g.delay_seconds||0,config_json:JSON.stringify({spec_name:g.spec_name||"",spec_value:g.spec_value||"",delay_override:g.delay_override===!0})})),...h]:s.actions&&s.actions.length>0?s.actions:[{action_type:"send_card",card_id:s.card_group_id||0,delivery_count:1,enabled:!0,sort_order:1}],L=Pl(t,f),F={cookie_id:s.cookie_id||"",item_id:s.item_id||"",name:(s.name||"").trim()||c||"自动化规则",trigger_type:t,enabled:s.enabled??!0,priority:s.priority||100,config_json:s.config_json||"{}",actions:L.map((g,I)=>({action_type:g.action_type,card_id:g.card_id||0,delivery_count:g.delivery_count||1,message_template:g.message_template||"",delay_seconds:g.delay_seconds||0,config_json:g.config_json||"{}",enabled:g.enabled!==!1,sort_order:g.sort_order||I+1}))};return s.id?Ee(`/automation-rules/${s.id}`,F):be("/automation-rules",F)},Tl=async s=>Ue(`/automation-rules/${s}`),El=async()=>{const s=await ge("/automation-issues");return{runs:Array.isArray(s==null?void 0:s.runs)?s.runs:[],pending_tasks:Array.isArray(s==null?void 0:s.pending_tasks)?s.pending_tasks:[]}},Fl=async(s,t)=>be(`/automation-runs/${s}/resolve`,{resolution:t}),Dl=async(s,t)=>be(`/automation-pending-tasks/${s}/resolve`,{resolution:t}),Ml=s=>({id:String((s==null?void 0:s.id)||""),keyword:(s==null?void 0:s.keyword)||"",reply:(s==null?void 0:s.reply)||"",item_id:(s==null?void 0:s.item_id)||"",type:(s==null?void 0:s.type)==="image"?"image":"text",image_url:(s==null?void 0:s.image_url)||""}),Ol=async s=>{const t=await ge(`/keywords-with-type/${s}`);return Array.isArray(t)?t.map(Ml):[]},ql=async s=>s?(await Ol(s)).map(l=>({id:l.id,keyword:l.keyword||"",reply_content:l.reply||"",match_type:"fuzzy",enabled:!0,item_id:l.item_id||"",type:l.type==="image"?"image":"text",image_url:l.image_url||""})):[],Bl=async(s,t)=>{const l=s.type||"text",c={keyword:s.keyword||"",reply:l==="text"&&s.reply_content||"",item_id:s.item_id||"",type:l,image_url:l==="image"&&s.image_url||""};return s.id?Ee(`/keywords-with-type/${t}/${s.id}`,c):be(`/keywords-with-item-id/${t}`,c)},zl=async(s,t)=>Ue(`/keywords-with-type/${t}/${s}`),Kt=async()=>{const s=await ge("/system-settings");return Ua(s.data||s)},Yt=async s=>{const t=Object.fromEntries(Object.entries(s).filter(([,l])=>l!=null));return Ee("/system-settings",t)},Ul=async(s,t)=>ge(`/ai-reply-settings/${s}`,void 0,t),Wl=async(s,t)=>{const l={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return Ee(`/ai-reply-settings/${s}`,l)},Vl=async(s,t="")=>(await be("/ai-models",{base_url:s,api_key:t})).models||[],Gl=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},Zt=s=>{const t=Array.from(new Set((s||[]).filter(Boolean)));return t.length>0?JSON.stringify(t):""},Xt=async s=>({success:!0,data:(await ge("/notification-channels",void 0,s)||[]).map(c=>{let h;try{h=typeof c.config=="string"?JSON.parse(c.config):c.config}catch{h={}}return{id:String(c.id),name:c.name,type:c.type==="ding_talk"?"dingtalk":c.type==="lark"?"feishu":c.type,config:h,event_types:Gl(c.event_types),enabled:c.enabled,created_at:c.created_at,updated_at:c.updated_at}})}),Jl=async s=>be("/notification-channels",{...s,config:JSON.stringify(s.config),event_types:Zt(s.event_types)}),Nt=async(s,t)=>{const l={...t};return"config"in t&&(l.config=JSON.stringify(t.config)),"event_types"in t&&(l.event_types=Zt(t.event_types)),Ee(`/notification-channels/${s}`,l)},Ql=async s=>Ue(`/notification-channels/${s}`),Kl=async(s,t)=>{const l=await ge(`/message-notifications/${s}`,void 0,t);return(l==null?void 0:l.channel_ids)||[]},Yl=async s=>be(`/notification-channels/${s}/test`,{}),vt=async()=>ge("/api/default-replies"),Zl=async s=>{const t=await ge(`/api/default-reply/${s}`);return{cookie_id:s,enabled:t.enabled||!1,reply_content:t.reply_content||"",reply_once:t.reply_once||!1,reply_image_url:t.reply_image_url||""}},Xl=async(s,t)=>Ee(`/api/default-reply/${s}`,{enabled:t.enabled??!1,reply_content:t.reply_content||"",reply_once:t.reply_once??!1,reply_image_url:t.reply_image_url||""}),Hl=async s=>Ue(`/api/default-reply/${s}`),er=async s=>be(`/api/default-reply/${s}/clear-records`,{}),gs=s=>String(s).padStart(2,"0"),Qs=s=>{if(s==null||s==="")return"-";const t=s instanceof Date?s:new Date(s);return Number.isNaN(t.getTime())?"-":[t.getFullYear(),gs(t.getMonth()+1),gs(t.getDate())].join("-")+" "+[gs(t.getHours()),gs(t.getMinutes()),gs(t.getSeconds())].join(":")},sr=({status:s})=>{const t={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:l[s]||s})},ks=({title:s,value:t,icon:l,colorClass:c,trend:h})=>e.jsxs("div",{className:"ios-card p-6 rounded-xl flex flex-col justify-between hover:translate-y-[-4px] transition-all duration-300 h-full relative overflow-hidden group border-0",children:[e.jsx("div",{className:`absolute -right-6 -top-6 w-32 h-32 ${c} opacity-10 rounded-full group-hover:scale-125 transition-transform duration-500 blur-2xl`}),e.jsxs("div",{className:"flex justify-between items-start mb-6",children:[e.jsx("div",{className:`p-4 rounded-2xl ${c} bg-opacity-10 backdrop-blur-sm`,children:e.jsx(l,{className:`w-6 h-6 ${c.replace("bg-","text-")}`})}),h&&e.jsxs("span",{className:"text-xs font-bold text-white bg-[#0094f7] px-3 py-1.5 rounded-full flex items-center gap-1 shadow-sm",children:[e.jsx(da,{className:"w-3 h-3"})," ",h]})]}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("h3",{className:"text-3xl font-extrabold text-gray-900 tracking-tight font-feature-settings-tnum",children:t}),e.jsx("p",{className:"text-gray-500 text-sm font-medium mt-1",children:s})]})]}),Os=()=>{var i,q;const[s,t]=n.useState(null),[l,c]=n.useState(null),[h,f]=n.useState(""),[L,F]=n.useState("7days"),[g,I]=n.useState(""),[j,G]=n.useState(""),[Y,X]=n.useState(null),[de,C]=n.useState(""),[M,oe]=n.useState([]),[ee,xe]=n.useState(0),[O,le]=n.useState(!1),[D,N]=n.useState(!1),[$,T]=n.useState([]),[J,ue]=n.useState({}),Q=n.useRef(0),A=["#0094f7","#3B82F6","#10B981","#F59E0B","#8B5CF6"],b=async d=>{let _;try{_=gt(d,new Date,g,j)}catch(_e){f(_e instanceof Error?_e.message:"日期范围无效");return}const{startDate:te,endDate:Z}=_,pe={start_date:te,end_date:Z},Ne=za(_),ce=++Q.current;N(!0),f("");try{const[_e,Re,ye]=await Promise.all([bt(pe),bt({start_date:Ne.startDate,end_date:Ne.endDate}),bl(pe)]);if(ce!==Q.current)return;c(_e),X(Re),oe(ye.orders),xe(ye.total),le(ye.truncated)}catch(_e){ce===Q.current&&f(_e instanceof Error?_e.message:"经营数据加载失败")}finally{ce===Q.current&&N(!1)}},v=()=>{if(!l||!Y)return null;const d=l.revenue_stats.total_amount,_=Y.revenue_stats.total_amount;if(_===0)return d>0?"+100%":"0%";const te=(d-_)/_*100;return`${te>=0?"+":""}${te.toFixed(1)}%`};if(n.useEffect(()=>{let d=!1;return Promise.all([gl(),ps()]).then(([_,te])=>{if(d)return;t(_),T(te);const Z={};te.forEach(pe=>{Z[pe.item_id]=pe.item_title||pe.item_id}),ue(Z)}).catch(_=>{d||f(_ instanceof Error?_.message:"概览加载失败")}),()=>{d=!0}},[]),n.useEffect(()=>{L!=="custom"&&b(L)},[L]),h&&(!s||!l))return e.jsxs("div",{className:"p-8 flex flex-col items-center gap-3 text-red-600",children:[e.jsx(ms,{className:"w-8 h-8"}),e.jsx("span",{children:h}),e.jsx("button",{type:"button",className:"ios-btn-primary px-4 py-2 rounded-xl",onClick:()=>window.location.reload(),children:"重新加载"})]});if(!s||!l)return e.jsx("div",{className:"p-8 flex justify-center text-gray-400",children:e.jsx(rt,{className:"w-8 h-8 animate-spin text-[#0094f7]"})});const B=((i=l.daily_stats)==null?void 0:i.map(d=>({name:d.date.slice(5),amount:d.amount,orders:d.order_count,avgAmount:d.order_count>0?(d.amount/d.order_count).toFixed(2):0})))||[],R=l.item_stats||[],K=l.revenue_stats.total_orders||0,H=l.revenue_stats.total_amount||0,m=R.length>0?R.map(d=>({name:(J[d.item_id]||d.item_id).length>12?(J[d.item_id]||d.item_id).substring(0,12)+"...":J[d.item_id]||d.item_id,sales:d.order_count})).sort((d,_)=>_.sales-d.sales).slice(0,10):[],p=Math.max(...m.map(d=>d.sales),1),y=R.length>0?R.map(d=>({name:(J[d.item_id]||d.item_id).length>10?(J[d.item_id]||d.item_id).substring(0,10)+"...":J[d.item_id]||d.item_id,value:d.order_count,percent:K>0?d.order_count/K*100:0})).sort((d,_)=>_.value-d.value).slice(0,6).map((d,_)=>({...d,color:A[_%A.length]})):[],S=R.length>0?R.map(d=>({name:(J[d.item_id]||d.item_id).length>12?(J[d.item_id]||d.item_id).substring(0,12)+"...":J[d.item_id]||d.item_id,value:d.total_amount,orderCount:d.order_count,percentage:H>0?d.total_amount/H*100:0})).sort((d,_)=>_.value-d.value).slice(0,5).map((d,_)=>({...d,color:A[_%A.length],percentage:d.percentage.toFixed(1)})):[],U=[{key:"today",label:"今天"},{key:"yesterday",label:"昨天"},{key:"3days",label:"三天内"},{key:"7days",label:"7天内"},{key:"30days",label:"一个月内"},{key:"custom",label:"自定义"}],se=((q=U.find(d=>d.key===L))==null?void 0:q.label)||"所选范围";let z;try{z=gt(L,new Date,g,j)}catch{z={startDate:g,endDate:j}}const re=de.trim().toLowerCase(),E=M.filter(d=>{var _,te,Z,pe;return((_=d.order_id)==null?void 0:_.toLowerCase().includes(re))||((te=d.item_id)==null?void 0:te.toLowerCase().includes(re))||((Z=d.item_title)==null?void 0:Z.toLowerCase().includes(re))||((pe=d.buyer_id)==null?void 0:pe.toLowerCase().includes(re))});return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"运营概览"}),e.jsx("p",{className:"text-gray-500 mt-2 text-base",children:"欢迎回来,以下是闲鱼店铺的实时经营数据。"})]}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsxs("div",{className:"text-sm font-bold text-gray-700 bg-white px-5 py-2.5 rounded-full shadow-sm border border-gray-100 flex items-center gap-2",children:[e.jsx("span",{className:"w-2.5 h-2.5 bg-green-500 rounded-full animate-pulse"}),"系统正常运行"]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[U.map(d=>e.jsx("button",{onClick:()=>F(d.key),className:`px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${L===d.key?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:d.label},d.key)),L==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"date",value:g,onChange:d=>I(d.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-[#0094f7]"}),e.jsx("span",{className:"self-center text-gray-400",children:"-"}),e.jsx("input",{type:"date",value:j,onChange:d=>G(d.target.value),className:"px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-[#0094f7]"}),e.jsx("button",{onClick:()=>{try{f(""),b("custom")}catch(d){f(d instanceof Error?d.message:"日期范围无效")}},className:"px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors",children:"应用"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6",children:[e.jsx(ks,{title:"累计营收 (CNY)",value:`¥${l.revenue_stats.total_amount.toLocaleString("zh-CN",{minimumFractionDigits:2})}`,icon:ca,colorClass:"bg-blue-400",trend:v()||void 0}),e.jsx(ks,{title:"活跃账号 / 总数",value:`${s.active_cookies} / ${s.total_cookies}`,icon:Pt,colorClass:"bg-blue-500"}),e.jsx(ks,{title:"订单数",value:l.revenue_stats.total_orders.toLocaleString(),icon:nt,colorClass:"bg-blue-500"}),e.jsx(ks,{title:"库存卡密余量",value:s.available_card_stock,icon:Dt,colorClass:"bg-purple-500"})]}),e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[se,"的销售额走势"]})]}),e.jsx("div",{className:"h-[350px] w-full",children:B.length===0||l.revenue_stats.total_amount===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(nt,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):B.length<=2?e.jsx(ws,{width:"100%",height:"100%",children:e.jsxs($a,{data:B,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(mt,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:"#374151",fontSize:14,fontWeight:600},dy:10}),e.jsx(ut,{axisLine:!1,tickLine:!1,tick:{fill:"#9CA3AF",fontSize:13,fontWeight:500},tickFormatter:d=>`¥${d}`}),e.jsx(Es,{contentStyle:{backgroundColor:"#fff",borderRadius:"8px",border:"1px solid #e5e7eb",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.1)",padding:"12px 16px"},labelStyle:{color:"#6b7280",fontWeight:500},itemStyle:{color:"#0094f7",fontWeight:600},cursor:{fill:"rgba(0, 148, 247, 0.08)"},formatter:d=>[`¥${Number(d).toFixed(2)}`,"营收"]}),e.jsx(Ra,{dataKey:"amount",fill:"#0094f7",maxBarSize:72,radius:[12,12,0,0],stroke:"#000000",strokeWidth:0,children:B.map((d,_)=>e.jsx(Fs,{fill:["#0094f7","#FCD34D","#0071e3"][_%3]},`cell-${_}`))})]})}):e.jsx(ws,{width:"100%",height:"100%",children:e.jsxs(Pa,{data:B,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"#0094f7",stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:"#0094f7",stopOpacity:0})]})}),e.jsx(mt,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:"#9CA3AF",fontSize:13,fontWeight:500},dy:15}),e.jsx(ut,{axisLine:!1,tickLine:!1,tick:{fill:"#9CA3AF",fontSize:13,fontWeight:500}}),e.jsx(Ta,{vertical:!1,stroke:"#F3F4F6",strokeDasharray:"3 3"}),e.jsx(Es,{contentStyle:{backgroundColor:"#fff",borderRadius:"8px",border:"1px solid #e5e7eb",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.1)",padding:"12px 16px"},labelStyle:{color:"#6b7280",fontWeight:500},itemStyle:{color:"#0094f7",fontWeight:600},cursor:{stroke:"#0094f7",strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(Ea,{type:"monotone",dataKey:"amount",stroke:"#0094f7",strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:"#fff",stroke:"#0094f7",strokeWidth:2}})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品销量排行"}),e.jsx("div",{className:"h-[280px]",children:m.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsx("div",{className:"h-full space-y-4 overflow-y-auto pr-2",children:m.map((d,_)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("span",{className:`w-7 h-7 rounded-xl flex items-center justify-center text-xs font-extrabold ${_<3?"bg-blue-600 text-white":"bg-gray-100 text-gray-500"}`,children:_+1}),e.jsx("span",{className:"font-bold text-gray-800 text-sm truncate",children:d.name})]}),e.jsxs("span",{className:"font-mono text-sm font-extrabold text-gray-900",children:[d.sales," 单"]})]}),e.jsx("div",{className:"h-3 rounded-full bg-gray-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-[#0094f7]",style:{width:`${Math.max(8,d.sales/p*100)}%`}})})]},`${d.name}-${_}`))})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品下单占比"}),e.jsx("div",{className:"h-[280px]",children:y.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-gray-400",children:"暂无数据"}):e.jsx(ws,{width:"100%",height:"100%",children:e.jsxs(pt,{children:[e.jsx(ht,{data:y,cx:"50%",cy:"50%",innerRadius:60,outerRadius:90,paddingAngle:2,dataKey:"value",label:({name:d,payload:_})=>`${d} ${Number((_==null?void 0:_.percent)||0).toFixed(1)}%`,labelLine:!1,children:y.map((d,_)=>e.jsx(Fs,{fill:d.color},`cell-${_}`))}),e.jsx(Fa,{verticalAlign:"bottom",height:36,iconType:"circle",formatter:d=>e.jsx("span",{style:{color:"#6B7280",fontWeight:500},children:d})})]})})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2 ios-card p-0 rounded-xl border-0 bg-white overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"p-6 border-b border-gray-50 flex justify-between items-center bg-[#FAFAFA]",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900",children:"参与统计的订单"}),O&&e.jsxs("p",{className:"text-xs text-amber-700 mt-1",children:["当前显示最近 ",M.length," / ",ee," 条,搜索仅覆盖已加载明细。"]})]}),e.jsx("div",{className:"relative",children:e.jsx("input",{placeholder:"搜索订单号/商品/买家...",value:de,onChange:d=>C(d.target.value),className:"pl-4 pr-4 py-2 rounded-xl bg-white border border-gray-100 text-sm focus:border-blue-400 outline-none w-48",type:"text"})})]}),e.jsx("div",{className:"overflow-x-auto flex-1 max-h-[400px]",children:D?e.jsxs("div",{className:"flex items-center justify-center py-20 text-gray-400",children:[e.jsx(rt,{className:"w-6 h-6 animate-spin mr-2"}),"加载中..."]}):E.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-8 text-center",children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-gray-100 flex items-center justify-center mb-4",children:e.jsx(Ns,{className:"w-7 h-7 text-gray-300"})}),re?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"没有匹配的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-md",children:["当前共有 ",M.length," 单参与统计,但没有订单号、商品、买家匹配“",de,"”。"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"当前范围内没有参与统计的订单"}),e.jsxs("div",{className:"text-xs text-gray-400 mt-2 max-w-lg leading-6",children:["日期范围:",z.startDate," 至 ",z.endDate,"; 统计口径:待发货、已发货、已完成,且订单金额不为空。 当前统计卡片订单数:",l.revenue_stats.total_orders," 单。"]})]})]}):e.jsxs("table",{className:"w-full text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-4",children:"订单信息"}),e.jsx("th",{className:"px-6 py-4",children:"买家信息"}),e.jsx("th",{className:"px-6 py-4",children:"金额"}),e.jsx("th",{className:"px-6 py-4",children:"状态"}),e.jsx("th",{className:"px-6 py-4 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:E.map(d=>e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:e.jsx(Ns,{className:"w-full h-full text-gray-300 p-2"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm line-clamp-1",children:d.item_title||d.item_id||"未知商品"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 font-mono",children:d.order_id}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",d.quantity||1]})]})]})}),e.jsxs("td",{className:"px-6 py-4",children:[e.jsx("div",{className:"text-sm font-bold text-gray-800",children:d.buyer_id}),d.created_at&&e.jsx("div",{className:"text-xs text-gray-400 mt-1",children:Qs(d.created_at)})]}),e.jsxs("td",{className:"px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:["¥",d.amount||"0.00"]}),e.jsx("td",{className:"px-6 py-4",children:e.jsx(sr,{status:d.status||d.order_status||"unknown"})}),e.jsx("td",{className:"px-6 py-4 text-right",children:e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${d.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(Mt,{className:"w-4 h-4"})})})]},d.order_id))})]})})]}),e.jsxs("div",{className:"ios-card p-6 rounded-xl bg-white",children:[e.jsx("h3",{className:"font-bold text-lg text-gray-900 mb-6",children:"商品金额分析 (TOP5)"}),S.length===0?e.jsx("div",{className:"flex items-center justify-center h-[300px] text-gray-400",children:"暂无数据"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-[300px] relative",children:e.jsx(ws,{width:"100%",height:"100%",children:e.jsxs(pt,{children:[e.jsx(ht,{data:S,cx:"50%",cy:"50%",innerRadius:60,outerRadius:100,paddingAngle:2,dataKey:"value",label:({name:d,payload:_})=>`${d} ${(_==null?void 0:_.percentage)||"0.0"}%`,children:S.map((d,_)=>e.jsx(Fs,{fill:d.color||A[_%A.length]},`cell-${_}`))}),e.jsx(Es,{contentStyle:{backgroundColor:"#fff",border:"1px solid #e5e7eb",borderRadius:"6px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1)"},formatter:d=>`¥${Number(d||0).toLocaleString()}`})]})})}),e.jsx("div",{className:"space-y-3 mt-4",children:S.map(d=>e.jsxs("div",{className:"flex justify-between items-center text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:d.color||A[S.indexOf(d)%A.length]}}),e.jsx("span",{className:"text-gray-600 font-medium",children:d.name})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"font-bold text-gray-900",children:["¥",d.value.toLocaleString()]}),e.jsxs("span",{className:"text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded",children:[d.percentage,"%"]})]})]},d.name))})]})]})]})]})},tr=(s,t)=>{const l=t.pause_duration||0;return s!==l},ar=(s,t)=>{const l=t.username!==(s.username||""),c=t.show_browser!==(s.show_browser||!1),h=t.login_password!=="",f=t.clear_password===!0;if(!l&&!c&&!h&&!f)return null;const L={username:t.username,show_browser:t.show_browser};return f?L.clear_password=!0:h&&(L.login_password=t.login_password),L},lr=(s,t)=>s&&t,rr=(s,t)=>{if(!s||!t)return!1;const l=Date.parse(s),c=Date.parse(t);return Number.isFinite(l)&&Number.isFinite(c)&&cs.map(l=>{const c=t[l.id];return!c||rr(l.runtime_updated_at,c.updated_at)?l:{...l,runtime_state:c.state,runtime_message:c.message||"",runtime_connected:c.connected,runtime_updated_at:c.updated_at}}),ir=new Set(["expired","cancelled","error","not_found"]),Cs=()=>{let s=0;return{next:()=>(s+=1,s),cancel:()=>{s+=1},isCurrent:t=>t===s}},or=(s={setInterval:globalThis.setInterval.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis)})=>{let t=null,l=null,c=-1,h=0;const f=()=>{h+=1,l==null||l.abort(),l=null,t!==null&&(s.clearInterval(t),t=null)};return{start:(F,g,I,j=2e3)=>{f();const G=h;l=new AbortController;const Y=l.signal;t=s.setInterval(()=>{c===G||G!==h||(c=G,(async()=>{var X,de;try{const C=await g(F,Y);if(C.status==="success"){f(),await I.onSuccess(C);return}if(C.status==="scanned"){(X=I.onScanned)==null||X.call(I,C);return}if(C.status==="verification_required"){(de=I.onVerificationRequired)==null||de.call(I,C);return}C.status&&ir.has(C.status)&&(f(),I.onTerminalError(C))}catch(C){if(Y.aborted||G!==h)return;f(),I.onPollError(C)}finally{c===G&&(c=-1)}})())},j)},stop:f,isActive:()=>t!==null}},cr=({faceQrUrl:s,verificationScreenshot:t})=>e.jsxs("div",{className:"w-full min-w-0 max-h-[min(64vh,28rem)] overflow-y-auto overscroll-contain px-1 py-2 text-center",children:[e.jsx("div",{className:"mx-auto mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-amber-100 text-amber-700",children:e.jsx(xa,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsx("h4",{className:"break-words text-base font-extrabold leading-6 text-amber-900",children:"需要完成安全风控验证"}),e.jsx("p",{className:"mx-auto mt-1 max-w-[15rem] break-words text-xs leading-5 text-amber-800",children:"当前账号触发了闲鱼平台风控。请使用手机闲鱼 App 扫描下方二维码,并按 App 提示完成人脸识别。"}),e.jsx("div",{className:"mx-auto mt-3 flex min-h-36 w-full max-w-[12rem] items-center justify-center overflow-hidden rounded-xl border border-amber-200 bg-white p-2 shadow-sm",children:s?e.jsx("img",{src:s,alt:"闲鱼安全风控验证二维码",className:"block max-h-44 w-full object-contain"}):t?e.jsx("img",{src:t,alt:"闲鱼风控验证页面",className:"block max-h-44 w-full object-contain"}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-amber-700",children:[e.jsx(Te,{className:"h-6 w-6 animate-spin","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-bold",children:"正在准备风控二维码…"})]})}),e.jsx("p",{className:"mx-auto mt-2 max-w-[15rem] break-words text-[11px] leading-4 text-gray-500",children:"请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。"})]}),_t=({src:s,alt:t,className:l=""})=>e.jsx("img",{src:s,alt:t,className:`block aspect-square h-auto w-full object-contain ${l}`.trim()}),dr=()=>{const[s,t]=n.useState([]),[l,c]=n.useState(!0),[h,f]=n.useState(""),[L,F]=n.useState(""),[g,I]=n.useState(!1),[j,G]=n.useState(""),[Y,X]=n.useState("pending"),[de,C]=n.useState(""),[M,oe]=n.useState(""),[ee,xe]=n.useState(null),[O,le]=n.useState(null),[D,N]=n.useState(null),[$,T]=n.useState({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:""}),[J,ue]=n.useState([]),[Q,A]=n.useState([]),[b,v]=n.useState(!1),[B,R]=n.useState(!1),[K,H]=n.useState(!1),[m,p]=n.useState(""),[y,S]=n.useState({remark:"",cookie:"",auto_confirm:!1,pause_duration:0,username:"",login_password:"",show_browser:!1,showLoginPassword:!1,clear_password:!1}),[U,se]=n.useState({ai_enabled:!1,max_discount_percent:10,max_discount_amount:100,max_bargain_rounds:3,custom_prompts:""}),[z,re]=n.useState(!1),[E,i]=n.useState({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),q=n.useRef(null),d=n.useRef(null),_=n.useRef(null),te=n.useRef(null),Z=n.useRef(null),pe=n.useRef(null),Ne=n.useRef(null),ce=n.useRef(null),_e=n.useRef(null),Re=n.useRef(null),ye=n.useRef(null),Ae=n.useRef(null),Le=n.useRef(0);q.current===null&&(q.current=or()),d.current===null&&(d.current=Cs()),_.current===null&&(_.current=Cs()),te.current===null&&(te.current=Cs()),Z.current===null&&(Z.current=Cs());const Be=()=>{ye.current!==null&&(window.clearTimeout(ye.current),ye.current=null)},Ie=()=>{Ae.current!==null&&(window.clearTimeout(Ae.current),Ae.current=null)},Me=()=>{var o;(o=q.current)==null||o.stop()},We=()=>{var o,k;(o=_e.current)==null||o.abort(),(k=d.current)==null||k.cancel(),Me(),Be(),I(!1)},Ye=()=>{Be(),ye.current=window.setTimeout(()=>{ye.current=null,I(!1),$e()},1e3)},$e=async()=>{var V,ne,ie,ke,Pe;const o=_.current.next();(V=pe.current)==null||V.abort();const k=new AbortController;pe.current=k,c(!0);try{const Ce={signal:k.signal},[Fe,ts]=await Promise.allSettled([Rs(Ce),ol(Ce)]);if(!((ne=_.current)!=null&&ne.isCurrent(o)))return;if(Fe.status==="rejected")throw Fe.reason;const Oe=Fe.value,hs=ts.status==="fulfilled"?ts.value:{};ts.status==="rejected"&&console.error("Failed to load AI settings:",ts.reason);const la=Oe.map(is=>{var et,st,tt,at,lt;return{...is,ai_enabled:((et=hs[is.id])==null?void 0:et.ai_enabled)??!1,max_discount_percent:((st=hs[is.id])==null?void 0:st.max_discount_percent)??10,max_discount_amount:((tt=hs[is.id])==null?void 0:tt.max_discount_amount)??100,max_bargain_rounds:((at=hs[is.id])==null?void 0:at.max_bargain_rounds)??3,custom_prompts:((lt=hs[is.id])==null?void 0:lt.custom_prompts)??""}});(ie=_.current)!=null&&ie.isCurrent(o)&&t(la)}catch(Ce){(ke=_.current)!=null&&ke.isCurrent(o)&&!k.signal.aborted&&console.error("Failed to load accounts:",Ce)}finally{(Pe=_.current)!=null&&Pe.isCurrent(o)&&c(!1)}};n.useEffect(()=>{let o=!1,k=null;const V=new AbortController,ne=async()=>{try{const ie=await Qa({signal:V.signal,timeoutMs:1e4});o||t(ke=>nr(ke,ie))}catch(ie){o||console.error("Failed to load account runtime statuses:",ie)}finally{o||(k=window.setTimeout(()=>void ne(),2e3))}};return $e().finally(()=>{o||ne()}),()=>{o=!0,V.abort(),k!==null&&window.clearTimeout(k)}},[]),n.useEffect(()=>()=>{var o,k,V,ne,ie,ke,Pe,Ce,Fe;Me(),(o=d.current)==null||o.cancel(),(k=_.current)==null||k.cancel(),(V=te.current)==null||V.cancel(),(ne=Z.current)==null||ne.cancel(),(ie=pe.current)==null||ie.abort(),(ke=Ne.current)==null||ke.abort(),(Pe=ce.current)==null||Pe.abort(),(Ce=_e.current)==null||Ce.abort(),(Fe=Re.current)==null||Fe.abort(),Be(),Le.current+=1,Ie()},[]);const ss=o=>{if(!o.enabled||o.runtime_state==="disabled")return{label:"已停用",badge:"bg-gray-100 text-gray-500",dot:"bg-gray-300"};switch(o.runtime_state){case"online":return{label:"在线",badge:"bg-green-100 text-green-700",dot:"bg-green-500"};case"starting":case"connecting":return{label:"连接中",badge:"bg-blue-100 text-blue-700",dot:"bg-blue-500"};case"reconnecting":return{label:"重连中",badge:"bg-amber-100 text-amber-700",dot:"bg-amber-500"};case"auth_expired":return{label:"登录已失效",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};case"verification_required":return{label:"需要验证",badge:"bg-orange-100 text-orange-700",dot:"bg-orange-500"};case"error":case"stopped":return{label:"运行异常",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};default:return{label:"状态检测中",badge:"bg-gray-100 text-gray-600",dot:"bg-gray-400"}}},Ze=async(o,k)=>{await Xa(o,!k),$e()},Xe=async o=>{confirm("确认删除该账号吗?")&&(await Ha(o),$e())},He=async o=>{F(o.id);try{const k=await il(o.id);k!=null&&k.profile_error&&alert("资料刷新失败:"+k.profile_error),await $e()}catch(k){console.error("刷新账号资料失败:",k),alert((k==null?void 0:k.message)||"刷新账号资料失败,请先重新授权该账号")}finally{F("")}},x=async o=>{var ke,Pe;const k=te.current.next();(ke=Ne.current)==null||ke.abort();const V=new AbortController;Ne.current=V,R(!0),v(!1),H(!1),p("");const[ne,ie]=await Promise.allSettled([Xt({signal:V.signal}),Kl(o,{signal:V.signal})]);(Pe=te.current)!=null&&Pe.isCurrent(k)&&(ne.status==="fulfilled"?ue(ne.value.data||[]):(ue([]),p("通知渠道列表加载失败,请重试")),ie.status==="fulfilled"?(A(ie.value||[]),v(!0)):(A([]),p("通知绑定加载失败;本次保存不会修改现有绑定")),R(!1))},P=async o=>{var V;Le.current+=1,(V=Re.current)==null||V.abort(),Ie(),i({sessionId:"",status:"idle",message:"",qrCodeUrl:""}),N(o),S({remark:o.remark||o.note||"",cookie:o.cookie||o.value||"",auto_confirm:o.auto_confirm||!1,pause_duration:o.pause_duration||0,username:o.username||"",login_password:o.login_password||"",show_browser:o.show_browser||!1,showLoginPassword:!1,clear_password:!1}),le("edit"),T({loading:!0,saving:!1,canOpen:!1,enabled:!1,error:""});const[,k]=await Promise.allSettled([x(o.id),tl(o.id)]);k.status==="fulfilled"?T({loading:!1,saving:!1,canOpen:k.value.can_open_long_login,enabled:k.value.enabled,error:""}):T({loading:!1,saving:!1,canOpen:!1,enabled:!1,error:"无法读取闲鱼保存登录信息状态"})},me=async()=>{if(!D||$.loading||$.saving||!$.canOpen)return;const o=!$.enabled;T(k=>({...k,saving:!0,error:""}));try{const k=await al(D.id,o);T({loading:!1,saving:!1,canOpen:k.can_open_long_login,enabled:k.enabled,error:""})}catch(k){T(V=>({...V,saving:!1,error:k instanceof Error?k.message:"保存登录信息设置失败"}))}},fe=async o=>{var ne,ie,ke,Pe;const k=Z.current.next();(ne=ce.current)==null||ne.abort();const V=new AbortController;ce.current=V,N(o),le("ai-settings"),re(!0);try{const Ce=await Ul(o.id,{signal:V.signal});if(!((ie=Z.current)!=null&&ie.isCurrent(k)))return;se({ai_enabled:Ce.ai_enabled??!1,max_discount_percent:Ce.max_discount_percent??10,max_discount_amount:Ce.max_discount_amount??100,max_bargain_rounds:Ce.max_bargain_rounds??3,custom_prompts:Ce.custom_prompts??""})}catch(Ce){(ke=Z.current)!=null&&ke.isCurrent(k)&&console.error("Failed to load AI settings:",Ce)}finally{(Pe=Z.current)!=null&&Pe.isCurrent(k)&&re(!1)}},ze=async()=>{if(D){re(!0);try{const o={};y.remark!==(D.remark||D.note||"")&&(o.remark=y.remark),y.cookie&&y.cookie!==(D.cookie||D.value||"")&&(o.cookie=y.cookie),y.auto_confirm!==D.auto_confirm&&(o.auto_confirm=y.auto_confirm),tr(y.pause_duration,D)&&(o.pause_duration=y.pause_duration);const k=ar(D,y);k&&Object.assign(o,k),lr(b,K)&&(o.channel_ids=Q),Object.keys(o).length>0&&await sl(D.id,o),le(null),$e()}catch(o){console.error("更新账号失败:",o),alert("更新失败,请重试")}finally{re(!1)}}},r=async()=>{if(!(!D||y.pause_duration<=0)){re(!0);try{const o=await el(D.id,y.pause_duration);N({...D,pause_duration:y.pause_duration,paused:(o==null?void 0:o.paused)===!0,paused_until:Number((o==null?void 0:o.paused_until)||0)}),await $e()}catch(o){alert(o instanceof Error?o.message:"重新暂停失败")}finally{re(!1)}}},a=async()=>{if(D){re(!0);try{await Wl(D.id,U),le(null),$e()}catch(o){console.error("更新AI设置失败:",o),alert("更新失败,请重试")}finally{re(!1)}}},u=async(o,k)=>{var ne;(ne=Re.current)==null||ne.abort();const V=new AbortController;Re.current=V;try{const ie=await rl(o,V.signal);if(k!==Le.current)return;if(ie.status==="success"){Ie(),i({sessionId:o,status:"success",message:ie.message||"账号密码登录成功,授权信息已更新",qrCodeUrl:""}),S(ke=>({...ke,login_password:"",showLoginPassword:!1})),await $e();return}if(ie.status==="processing"||ie.status==="verification_required"){i({sessionId:o,status:ie.status,message:ie.message||(ie.status==="verification_required"?"账号触发风控,需要完成人脸识别":"登录处理中"),qrCodeUrl:ie.qr_code_url||""}),Ie(),Ae.current=window.setTimeout(()=>void u(o,k),1500);return}Ie(),i({sessionId:o,status:"failed",message:ie.error||ie.message||"密码登录失败,请检查账号信息后重试",qrCodeUrl:""})}catch(ie){if(k!==Le.current)return;Ie(),i({sessionId:o,status:"failed",message:ie instanceof Error?ie.message:"查询密码登录状态失败",qrCodeUrl:""})}},w=async()=>{var V;if(!D)return;const o=y.username.trim();if(!o||!y.login_password){alert("请先填写登录账号和本次登录密码");return}Ie(),(V=Re.current)==null||V.abort();const k=++Le.current;i({sessionId:"",status:"processing",message:"正在启动密码登录…",qrCodeUrl:""});try{const ne=await ll({account_id:D.id,account:o,password:y.login_password,show_browser:y.show_browser});if(k!==Le.current)return;if(!ne.success||!ne.session_id)throw new Error(ne.message||"无法启动密码登录");i({sessionId:ne.session_id,status:"processing",message:ne.message||"登录处理中",qrCodeUrl:""}),await u(ne.session_id,k)}catch(ne){if(k!==Le.current)return;i({sessionId:"",status:"failed",message:ne instanceof Error?ne.message:"启动密码登录失败",qrCodeUrl:""})}},W=async()=>{var k;const o=E.sessionId;if(Le.current+=1,(k=Re.current)==null||k.abort(),Ie(),o)try{await nl(o)}catch(V){console.error("取消密码登录失败",V)}i({sessionId:"",status:"idle",message:"",qrCodeUrl:""})},ae=async()=>{var o,k;(o=te.current)==null||o.cancel(),(k=Ne.current)==null||k.abort(),(E.status==="processing"||E.status==="verification_required")&&await W(),le(null)},ve=()=>{var o,k;(o=Z.current)==null||o.cancel(),(k=ce.current)==null||k.abort(),le(null)},he=async(o,k)=>{const V=await Za(o,k==null?void 0:k.id);if(!V.success||!V.account_id)throw new Error(V.message||"保存扫码授权失败");return V.account_id},De=async o=>{var ie,ke,Pe,Ce;Me(),(ie=_e.current)==null||ie.abort();const k=new AbortController;_e.current=k;const V=d.current.next();Be();const ne=o||null;xe(ne),I(!0),X("loading"),G(""),C(""),oe("");try{const Fe=await Ka({signal:k.signal});if(!((ke=d.current)!=null&&ke.isCurrent(V)))return;if(Fe.success&&Fe.qr_code_url&&Fe.session_id){const ts=Fe.session_id;G(Fe.qr_code_url),X("waiting"),(Pe=q.current)==null||Pe.start(ts,Ya,{onSuccess:async()=>{try{if(!await he(ts,ne)){X("error");return}}catch(Oe){console.error("保存扫码授权失败",Oe),X("error");return}X("success"),Ye()},onScanned:()=>{X("waiting")},onTerminalError:()=>{X("error")},onPollError:Oe=>{console.error("轮询扫码状态失败",Oe),X("error")},onVerificationRequired:Oe=>{X("verification"),Oe.face_qr_url&&oe(Oe.face_qr_url),Oe.verification_screenshot&&C(Oe.verification_screenshot)}})}}catch{if(!((Ce=d.current)!=null&&Ce.isCurrent(V)))return;X("error")}};if(l)return e.jsx("div",{className:"p-20 flex justify-center",children:e.jsx(Te,{className:"w-8 h-8 text-[#0094f7] animate-spin"})});const je=s.filter(o=>{const k=h.trim().toLowerCase();return k?[o.id,o.nickname,o.remark,o.note,o.username,o.runtime_message].some(V=>(V||"").toLowerCase().includes(k)):!0});return e.jsxs("div",{className:"space-y-8 animate-fade-in relative",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"账号管理"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理您的闲鱼授权账号及设置。建议给账号填写备注,便于多账号区分。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx("input",{value:h,onChange:o=>f(o.target.value),placeholder:"搜索昵称 / 备注 / 账号ID",className:"ios-input px-4 py-3 rounded-2xl text-sm w-full sm:w-72"}),e.jsxs("button",{onClick:()=>De(),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(Ps,{className:"w-5 h-5"}),"扫码添加新账号"]})]})]}),e.jsxs("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 px-5 py-4 text-sm text-blue-900 flex flex-col md:flex-row md:items-center md:justify-between gap-2",children:[e.jsxs("div",{className:"font-bold",children:["当前显示 ",je.length," / ",s.length," 个账号"]}),e.jsx("div",{className:"text-blue-700",children:"如果某个账号只显示 ID,点该账号右侧“刷新资料”;若刷新失败,先点二维码重新授权。"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6",children:[je.map(o=>{const k=ss(o),V=o.runtime_state==="auth_expired"||o.runtime_state==="verification_required";return e.jsxs("div",{className:"ios-card p-6 rounded-xl flex flex-col lg:flex-row lg:items-center justify-between gap-5 group hover:border-[#0094f7] transition-all duration-300",children:[e.jsxs("div",{className:"flex items-center gap-5 sm:gap-8 min-w-0",children:[e.jsxs("div",{className:"relative",children:[o.avatar_url?e.jsx("img",{src:o.avatar_url,alt:o.nickname||"账号头像",className:"w-20 h-20 rounded-full object-cover shadow-md ring-4 ring-white bg-gray-100"}):e.jsx("div",{className:"w-20 h-20 rounded-full bg-gray-100 text-gray-400 shadow-md ring-4 ring-white flex items-center justify-center",children:e.jsx(ns,{className:"w-9 h-9"})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-6 h-6 rounded-full border-4 border-white flex items-center justify-center ${k.dot}`,children:o.runtime_state==="online"&&e.jsx(Ge,{className:"w-3 h-3 text-white"})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-1",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900 break-words",children:o.nickname||o.remark||`账号 ${o.id.substring(0,6)}...`}),e.jsx("span",{className:`px-2.5 py-0.5 rounded-lg text-xs font-bold ${k.badge}`,children:k.label}),o.ai_enabled&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-purple-100 text-purple-700 text-xs font-bold flex items-center gap-1",children:[e.jsx(ds,{className:"w-3 h-3"})," AI"]}),o.profile_error&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-amber-100 text-amber-700 text-xs font-bold flex items-center gap-1",title:o.profile_error,children:[e.jsx(ms,{className:"w-3 h-3"})," 资料未同步"]})]}),e.jsxs("div",{className:"text-sm text-gray-500 font-medium mb-3 space-y-1",children:[e.jsx("p",{children:o.remark||o.note||"暂无备注"}),e.jsxs("p",{className:"font-mono text-xs text-gray-400",children:["ID: ",o.id]})]}),o.runtime_message&&o.runtime_state!=="online"&&o.runtime_state!=="disabled"&&e.jsxs("div",{className:`mb-3 flex flex-wrap items-center gap-2 text-sm font-medium ${V?"text-red-700":"text-amber-700"}`,children:[e.jsx(ms,{className:"w-4 h-4 flex-shrink-0"}),e.jsx("span",{children:o.runtime_message}),V&&e.jsxs("button",{type:"button",onClick:()=>De(o),className:"inline-flex items-center gap-1.5 rounded-lg bg-red-50 px-2.5 py-1 text-xs font-bold text-red-700 hover:bg-red-100",children:[e.jsx(Ps,{className:"w-3.5 h-3.5"})," 重新授权"]})]}),e.jsxs("div",{className:"flex gap-2",children:[o.auto_confirm&&e.jsxs("span",{className:"text-xs bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg font-bold flex items-center gap-1.5",children:[e.jsx(Ge,{className:"w-3 h-3"})," 自动确认发货"]}),o.paused&&e.jsxs("span",{className:"text-xs bg-blue-50 text-blue-700 px-3 py-1.5 rounded-lg font-bold flex items-center gap-1.5",children:[e.jsx(it,{className:"w-3 h-3"})," 暂停处理中"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 self-end lg:self-auto flex-shrink-0",children:[e.jsx("button",{onClick:()=>He(o),disabled:L===o.id,className:"p-3 rounded-xl transition-colors text-gray-600 hover:bg-gray-100 disabled:opacity-50",title:"刷新昵称和头像",children:e.jsx(qe,{className:`w-5 h-5 ${L===o.id?"animate-spin":""}`})}),e.jsx("button",{onClick:()=>De(o),className:`p-3 rounded-xl transition-colors ${V?"text-red-600 bg-red-50 hover:bg-red-100":"text-blue-600 hover:bg-blue-50"}`,title:"重新扫码授权当前账号",children:e.jsx(Ps,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>P(o),className:"p-3 rounded-xl hover:bg-gray-100 transition-colors text-gray-600",title:"编辑账号",children:e.jsx(Ot,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>fe(o),className:"p-3 rounded-xl hover:bg-purple-100 transition-colors text-purple-600",title:"AI设置",children:e.jsx(ds,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Ze(o.id,o.enabled),className:`p-3 rounded-xl transition-colors ${o.enabled?"text-green-600 hover:bg-green-50":"text-gray-400 hover:bg-gray-100"}`,title:o.enabled?"停用账号":"启用账号",children:e.jsx(ma,{className:"w-5 h-5"})}),e.jsx("button",{onClick:()=>Xe(o.id),className:"p-3 rounded-xl hover:bg-red-100 transition-colors text-red-500",children:e.jsx(Je,{className:"w-5 h-5"})})]})]},o.id)}),s.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("div",{className:"w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4",children:e.jsx(ns,{className:"w-10 h-10 text-gray-400"})}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"暂无账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"请点击右上角扫码添加您的闲鱼账号"})]}),s.length>0&&je.length===0&&e.jsxs("div",{className:"ios-card p-12 text-center",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:"没有匹配的账号"}),e.jsx("p",{className:"text-gray-500 mt-1",children:"换一个关键词搜索昵称、备注或账号ID。"})]})]}),g&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container relative",style:{maxWidth:"26rem"},children:[e.jsx("button",{onClick:We,className:"absolute top-4 right-4 z-10 w-9 h-9 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-full transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900 mb-2",children:ee?"重新授权账号":"扫码添加账号"}),e.jsx("p",{className:"text-gray-500 mb-8 font-medium",children:ee?`请用闲鱼APP扫码,为「${ee.nickname||ee.remark||ee.id}」刷新授权`:"请打开闲鱼APP扫描下方二维码"}),e.jsxs("div",{className:`w-full bg-[#F7F8FA] rounded-xl mx-auto flex items-center justify-center overflow-hidden border-4 border-white shadow-inner mb-6 relative ${Y==="verification"?"max-w-72 min-h-64 h-auto p-2":"max-w-64 aspect-square"}`,children:[Y==="loading"&&e.jsx(Te,{className:"w-10 h-10 text-[#0094f7] animate-spin"}),Y==="waiting"&&e.jsx(_t,{src:j,alt:"闲鱼登录二维码",className:"p-2"}),Y==="success"&&e.jsxs("div",{className:"absolute inset-0 bg-white/95 flex flex-col items-center justify-center text-green-600 animate-fade-in",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4",children:e.jsx(Ge,{className:"w-8 h-8"})}),e.jsx("span",{className:"font-bold text-lg",children:"登录成功"})]}),Y==="error"&&e.jsxs("div",{className:"px-5 text-center",children:[e.jsx("span",{className:"block text-red-600 font-bold",children:"二维码获取失败"}),e.jsx("span",{className:"mt-2 block text-xs leading-5 text-gray-500",children:"请关闭窗口后重新发起扫码登录。"})]}),Y==="verification"&&e.jsx(cr,{faceQrUrl:M,verificationScreenshot:de})]}),Y!=="verification"&&e.jsx("p",{className:"text-xs text-gray-400 font-medium bg-gray-50 py-2 rounded-xl",children:"二维码有效期为5分钟,请尽快扫码。"})]})})]})}),document.body),O==="edit"&&D&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑账号"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:D.nickname||D.remark||D.id})]}),e.jsx("button",{onClick:()=>void ae(),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"账号ID"}),e.jsx("input",{type:"text",value:D.id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注"}),e.jsx("input",{type:"text",value:y.remark,onChange:o=>S({...y,remark:o.target.value}),placeholder:"为账号添加备注",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"Cookie"}),e.jsx("textarea",{value:y.cookie,onChange:o=>S({...y,cookie:o.target.value}),placeholder:"更新账号Cookie",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none font-mono text-xs"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["当前Cookie长度: ",y.cookie.length," 字符"]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(Ge,{className:"w-4 h-4 text-green-500"}),"自动确认发货"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"自动将闲鱼订单标记为已发货"})]}),e.jsx("button",{type:"button",onClick:()=>S({...y,auto_confirm:!y.auto_confirm}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${y.auto_confirm?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${y.auto_confirm?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2 flex items-center gap-2",children:[e.jsx(it,{className:"w-4 h-4 text-blue-500"}),"暂停处理时长(分钟)"]}),e.jsx("input",{type:"number",value:y.pause_duration,onChange:o=>S({...y,pause_duration:parseInt(o.target.value)||0}),placeholder:"0",min:"0",max:"1440",className:"w-full ios-input px-4 py-3 rounded-xl"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"设置后会暂停处理该账号的订单,到时间后自动恢复"}),y.pause_duration>0&&!D.paused&&y.pause_duration===(D.pause_duration||0)&&e.jsx("button",{type:"button",disabled:z,onClick:()=>void r(),className:"mt-3 px-4 py-2 rounded-xl bg-amber-50 text-amber-700 hover:bg-amber-100 text-sm font-bold disabled:opacity-50",children:"立即按当前时长重新暂停"})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-4 flex items-center gap-2",children:[e.jsx(ua,{className:"w-5 h-5 text-blue-500"}),"登录信息"]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-xl bg-blue-50 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"保存登录信息"}),e.jsx("div",{className:"mt-1 text-xs text-gray-500",children:"状态直接读取并修改闲鱼官方长登录设置"}),$.error&&e.jsx("div",{className:"mt-1 text-xs text-red-600",children:$.error})]}),e.jsx("button",{type:"button","aria-label":"保存登录信息",disabled:$.loading||$.saving||!$.canOpen,onClick:()=>void me(),className:`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${$.enabled?"bg-[#0094f7]":"bg-gray-300"} disabled:cursor-not-allowed disabled:opacity-50`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-md transition-transform ${$.enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"用户名"}),e.jsx("input",{type:"text",value:y.username,onChange:o=>S({...y,username:o.target.value}),placeholder:"闲鱼账号/手机号",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"登录密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:y.showLoginPassword?"text":"password",value:y.login_password,onChange:o=>S({...y,login_password:o.target.value,clear_password:!1}),placeholder:"用于自动登录",className:"w-full ios-input px-4 py-3 rounded-xl pr-12"}),e.jsx("button",{type:"button",onClick:()=>S({...y,showLoginPassword:!y.showLoginPassword}),className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600",children:y.showLoginPassword?e.jsx(rs,{className:"w-5 h-5"}):e.jsx(es,{className:"w-5 h-5"})})]}),e.jsxs("label",{className:"mt-3 flex items-center gap-3 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:y.clear_password,onChange:o=>S({...y,clear_password:o.target.checked,login_password:o.target.checked?"":y.login_password}),className:"w-4 h-4 accent-[#0094f7]"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:"清空已保存密码"})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"登录时显示浏览器"}),e.jsx("div",{className:"text-xs text-gray-500",children:"调试时可开启查看登录过程"})]}),e.jsx("button",{type:"button",onClick:()=>S({...y,show_browser:!y.show_browser}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${y.show_browser?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${y.show_browser?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-blue-950",children:"立即执行账号密码登录"}),e.jsx("div",{className:"text-xs text-blue-700 mt-1",children:"需要在上方重新输入本次登录密码;成功后后端会更新 Cookie 和保存的登录信息。"})]}),E.status==="processing"||E.status==="verification_required"?e.jsx("button",{type:"button",onClick:W,className:"px-4 py-2 rounded-xl bg-white text-red-600 font-bold text-sm border border-red-100",children:"取消登录"}):e.jsx("button",{type:"button",onClick:w,className:"px-4 py-2 rounded-xl bg-blue-600 text-white font-bold text-sm whitespace-nowrap",children:"密码登录刷新授权"})]}),E.message&&e.jsx("div",{className:`text-sm font-medium ${E.status==="failed"?"text-red-700":E.status==="success"?"text-green-700":"text-blue-800"}`,children:E.message}),E.status==="verification_required"&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-amber-900",children:[e.jsx("div",{className:"font-extrabold",children:"账号已触发平台风控,需要完成人脸识别"}),e.jsx("div",{className:"text-xs mt-1 leading-5",children:"请在闲鱼 App 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。"}),E.qrCodeUrl&&e.jsx("div",{className:"mt-3 aspect-square w-48 overflow-hidden rounded-xl border bg-white",children:e.jsx(_t,{src:E.qrCodeUrl,alt:"密码登录风控二维码",className:"p-2"})})]})]})]})]}),(J.length>0||B||m)&&e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsxs("h3",{className:"text-lg font-bold text-gray-900 mb-1 flex items-center gap-2",children:[e.jsx(xs,{className:"w-5 h-5 text-blue-500"}),"通知渠道绑定"]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"勾选后,该账号的 token 失效、自动恢复失败、风控验证等事件会推送到这些渠道"}),B&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e.jsx(Te,{className:"w-4 h-4 animate-spin"}),"正在加载通知绑定"]}),m&&!B&&e.jsxs("div",{className:"mb-3 rounded-xl bg-amber-50 p-3 text-sm text-amber-800 flex items-center justify-between gap-3",children:[e.jsx("span",{children:m}),e.jsx("button",{type:"button",className:"font-bold whitespace-nowrap",onClick:()=>x(D.id),children:"重试"})]}),e.jsx("div",{className:"space-y-2",children:J.map(o=>{const k=Q.includes(Number(o.id));return e.jsxs("label",{className:"flex items-center gap-3 p-3 rounded-xl border border-gray-200 hover:bg-gray-50 cursor-pointer transition-colors",children:[e.jsx("button",{type:"button",onClick:()=>{b&&(A(V=>k?V.filter(ne=>ne!==Number(o.id)):[...V,Number(o.id)]),H(!0))},disabled:!b,className:`w-5 h-5 rounded-md border-2 flex items-center justify-center transition-colors flex-shrink-0 ${k?"bg-[#0094f7] border-[#0094f7]":"bg-white border-gray-300"}`,children:k&&e.jsx(Ge,{className:"w-3.5 h-3.5 text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:o.name}),e.jsxs("div",{className:"text-xs text-gray-500",children:[o.type,o.enabled?"":" · 已停用"]})]})]},o.id)})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>void ae(),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:z,children:"取消"}),e.jsxs("button",{onClick:ze,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:z,children:[z?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(Ke,{className:"w-4 h-4"}),z?"保存中...":"保存"]})]})})]})}),document.body),O==="ai-settings"&&D&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-2xl font-extrabold text-gray-900 flex items-center gap-2",children:[e.jsx(ds,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:D.nickname||D.remark||D.id})]}),e.jsx("button",{onClick:ve,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-purple-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex items-center gap-2",children:[e.jsx(ds,{className:"w-4 h-4 text-purple-500"}),"启用AI自动回复"]}),e.jsx("div",{className:"text-xs text-gray-500",children:"AI将自动处理买家的砍价消息"})]}),e.jsx("button",{type:"button",onClick:()=>se({...U,ai_enabled:!U.ai_enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${U.ai_enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 ${U.ai_enabled?"translate-x-6":"translate-x-0"}`})})]}),e.jsxs("div",{className:"border-t border-gray-200 pt-6",children:[e.jsx("h3",{className:"text-lg font-bold text-gray-900 mb-4",children:"砍价策略"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣比例 (%)"}),e.jsx("input",{type:"number",value:U.max_discount_percent,onChange:o=>se({...U,max_discount_percent:parseInt(o.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"100"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:10 表示最多降价 10%;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大折扣金额 (元)"}),e.jsx("input",{type:"number",value:U.max_discount_amount,onChange:o=>se({...U,max_discount_amount:parseInt(o.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"例如:100 表示最多降价 100 元;设为 0 表示不允许降价"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最大砍价轮次"}),e.jsx("input",{type:"number",value:U.max_bargain_rounds,onChange:o=>se({...U,max_bargain_rounds:parseInt(o.target.value)||1}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"10"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"买家最多可以砍价的次数"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"自定义提示词(可选)"}),e.jsx("textarea",{value:U.custom_prompts,onChange:o=>se({...U,custom_prompts:o.target.value}),placeholder:`输入自定义的AI回复规则或风格指引...
+
+例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(Ys,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:ve,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:z,children:"取消"}),e.jsxs("button",{onClick:a,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:z,children:[z?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(Ke,{className:"w-4 h-4"}),z?"保存中...":"保存"]})]})})]})}),document.body)]})},xr=s=>({total:Number((s==null?void 0:s.total)||0),success_count:Number((s==null?void 0:s.success_count)||0),failed_count:Number((s==null?void 0:s.failed_count)||0),results:Array.isArray(s==null?void 0:s.results)?s.results.map(t=>({order_id:String((t==null?void 0:t.order_id)||"unknown"),success:(t==null?void 0:t.success)===!0,message:String((t==null?void 0:t.message)||"")})):[]}),mr=s=>(s==null?void 0:s.results.filter(t=>!t.success))||[],wt=({status:s})=>{const t={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-[#0094f7] text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${t[s]||t.cancelled}`,children:l[s]||s})},ur=()=>{const[s,t]=n.useState([]),[l,c]=n.useState([]),[h,f]=n.useState([]),[L,F]=n.useState({}),[g,I]=n.useState("all"),[j,G]=n.useState(""),[Y,X]=n.useState(""),[de,C]=n.useState(""),M=n.useRef(0),[oe,ee]=n.useState(1),[xe,O]=n.useState(1),[le,D]=n.useState(!1),[N,$]=n.useState(!1),[T,J]=n.useState(!1),[ue,Q]=n.useState(!1),[A,b]=n.useState(null),[v,B]=n.useState(null),[R,K]=n.useState({}),[H,m]=n.useState(!1),[p,y]=n.useState(""),[S,U]=n.useState(!1),[se,z]=n.useState(null),[re,E]=n.useState(null),[i,q]=n.useState(null),[d,_]=n.useState(!1),[te,Z]=n.useState(null),[pe,Ne]=n.useState(null),ce=async()=>{const x=++M.current;D(!0);try{const P=await cl(j||void 0,g,oe,20,de);if(x!==M.current)return;t(P.data),O(P.total_pages)}catch(P){console.error("加载订单失败:",P)}finally{x===M.current&&D(!1)}},_e=(x,P,me)=>{if(me&&me.trim())return me;if(L[`${x}:${P}`])return L[`${x}:${P}`];const fe=l.find(ze=>{if(me&&ze.item_title){const r=me.toLowerCase(),a=ze.item_title.toLowerCase();return a.includes(r)||r.includes(a)}return!1});return fe!=null&&fe.item_title?fe.item_title:"未知商品"},Re=x=>{const P={};x.forEach(me=>{me.item_id&&(P[`${me.cookie_id}:${me.item_id}`]=me.item_title||me.item_id)}),F(P)};n.useEffect(()=>{const x=window.setTimeout(()=>{ee(1),C(Y.trim())},300);return()=>window.clearTimeout(x)},[Y]),n.useEffect(()=>{ce()},[j,g,oe,de]),n.useEffect(()=>{Promise.all([Rs(),ps()]).then(([x,P])=>{f(x),c(P),Re(P)}).catch(x=>{console.error("加载商品列表失败:",x)})},[]);const ye=n.useMemo(()=>new Map(h.map(x=>[x.id,x])),[h]),Ae=x=>{const P=ye.get(x),me=(P==null?void 0:P.remark)||(P==null?void 0:P.nickname);return me?`${me} · ${x.slice(0,6)}`:`账号 ${x.slice(0,8)}`},Le=x=>{const P=ye.get(x);return(P==null?void 0:P.remark)||(P==null?void 0:P.nickname)||"未命名账号"},Be=async()=>{D(!0);try{const x=await ml(j||void 0,g);await ce(),x!=null&&x.message&&alert(x.message)}catch(x){console.error("同步订单失败:",x),alert((x==null?void 0:x.message)||"同步失败,请重试")}finally{D(!1)}},Ie=x=>{y(x),z(null),m(!0)},Me=async x=>{var P;U(!0),z(null);try{const me=await pl([p],x),fe=(P=me==null?void 0:me.results)==null?void 0:P[0];fe!=null&&fe.success?(z({success:!0,message:fe.message}),ce()):z({success:!1,message:(fe==null?void 0:fe.message)||"发货失败"})}catch(me){z({success:!1,message:(me==null?void 0:me.message)||"请求失败"})}finally{U(!1)}},We=x=>{b(x),$(!0)},Ye=x=>{B({...x}),J(!0)},$e=async()=>{if(!(!v||!v.order_id))try{const x={};v.status!==void 0&&(x.order_status=v.status),v.buyer_id!==void 0&&(x.buyer_id=v.buyer_id),v.amount!==void 0&&(x.amount=v.amount),v.receiver_name!==void 0&&(x.receiver_name=v.receiver_name),v.receiver_phone!==void 0&&(x.receiver_phone=v.receiver_phone),v.receiver_address!==void 0&&(x.receiver_address=v.receiver_address),v.item_id!==void 0&&(x.item_id=v.item_id),v.quantity!==void 0&&(x.quantity=v.quantity),v.item_title!==void 0&&(x.item_title=v.item_title),await dl(v.order_id,x),J(!1),B(null),ce()}catch(x){console.error("更新订单失败:",x),alert("更新失败,请重试")}},ss=async()=>{if(re){_(!0);try{const x=new FormData;x.append("file",re);const P=xr(await hl(x));q(P),E(null),await ce(),P.failed_count===0&&(Q(!1),q(null),alert(`订单导入成功,共 ${P.success_count} 条`))}catch(x){alert((x==null?void 0:x.message)||"导入失败,请检查文件格式")}finally{_(!1)}}},Ze=()=>{d||(Q(!1),E(null),q(null))},Xe=async x=>{Z(x);try{const P=await ul(x);P.success?await ce():alert(P.message||"同步失败")}catch(P){console.error("同步订单失败:",P),alert((P==null?void 0:P.message)||"同步失败,请重试")}finally{Z(null)}},He=async x=>{if(confirm("确认删除该订单吗?删除后无法恢复。")){Ne(x);try{await xl(x),s.length===1&&oe>1?ee(P=>P-1):await ce()}catch(P){console.error("删除订单失败:",P),alert((P==null?void 0:P.message)||"删除失败,请重试"),await ce()}finally{Ne(null)}}};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"订单中心"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"查看所有闲鱼交易记录与状态。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:ce,className:"p-3 rounded-2xl bg-white border border-gray-100 text-gray-600 hover:bg-gray-50 hover:text-black transition-colors shadow-sm",children:e.jsx(qe,{className:`w-5 h-5 ${le?"animate-spin":""}`})}),e.jsxs("button",{onClick:()=>{q(null),Q(!0)},className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors text-sm flex items-center gap-2 shadow-lg",children:[e.jsx(Qe,{className:"w-4 h-4"}),"插入订单"]}),e.jsxs("button",{onClick:Be,className:"ios-btn-primary px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 text-sm flex items-center gap-2",children:[e.jsx(ot,{className:"w-5 h-5"}),"一键同步订单"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-[#FAFAFA]",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:[{k:"all",v:"全部"},{k:"processing",v:"处理中"},{k:"shipped",v:"已发货"},{k:"pending_ship",v:"待发货"},{k:"completed",v:"已完成"},{k:"cancelled",v:"已取消"},{k:"refunding",v:"退款中"}].map(x=>e.jsx("button",{onClick:()=>{I(x.k),ee(1),X("")},className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${g===x.k?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:x.v},x.k))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ns,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:j,onChange:x=>{G(x.target.value),ee(1)},className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),h.map(x=>e.jsx("option",{value:x.id,children:Ae(x.id)},x.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(qt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-[#0094f7] transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:Y,onChange:x=>{X(x.target.value),ee(1)},className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]}),e.jsx("div",{className:"overflow-x-auto min-h-[400px]",children:e.jsxs("table",{className:"w-full text-left border-collapse table-fixed",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"px-6 py-5",style:{width:"28%"},children:"订单信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"26%"},children:"买家信息"}),e.jsx("th",{className:"px-6 py-5",style:{width:"11%"},children:"实付金额"}),e.jsx("th",{className:"px-6 py-5",style:{width:"13%"},children:"当前状态"}),e.jsx("th",{className:"px-6 py-5 text-right",style:{width:"22%"},children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:s.map(x=>e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx("div",{className:"w-14 h-14 rounded-xl bg-gray-100 overflow-hidden shadow-sm border border-gray-100 flex-shrink-0",children:x.item_image?e.jsx("img",{src:x.item_image,alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(Ns,{})})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-bold text-gray-900 line-clamp-1 text-sm",children:_e(x.cookie_id,x.item_id,x.item_title)}),e.jsxs("div",{className:"mt-1 flex w-fit min-w-0 max-w-full items-center gap-1 rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700",title:Le(x.cookie_id),children:[e.jsx(ns,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:Le(x.cookie_id)})]}),e.jsxs("div",{className:"text-xs text-gray-500 mt-1 font-medium",children:["订单ID: ",x.order_id]}),e.jsxs("div",{className:"text-xs text-gray-400 mt-0.5",children:["数量: ",x.quantity," • ",Qs(x.created_at)]})]})]})}),e.jsx("td",{className:"px-6 py-5",children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("div",{className:"text-xs text-gray-500",children:"买家ID"}),e.jsx("div",{className:"text-sm font-bold text-gray-800",children:x.buyer_id}),x.receiver_name&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货人"}),e.jsx("div",{className:"text-xs text-gray-600",children:x.receiver_name})]}),x.receiver_phone&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"联系电话"}),e.jsx("div",{className:"text-xs text-gray-600 font-mono",children:x.receiver_phone})]}),x.receiver_address&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-gray-500",children:"收货地址"}),e.jsx("div",{className:"text-xs text-gray-600 line-clamp-1",children:x.receiver_address})]})]})}),e.jsx("td",{className:"px-6 py-5 text-base font-extrabold text-gray-900 font-feature-settings-tnum",children:x.amount?`¥${x.amount}`:e.jsx("span",{className:"text-xs text-amber-600 font-bold",children:"待获取"})}),e.jsx("td",{className:"px-6 py-5",children:e.jsx(wt,{status:x.status})}),e.jsxs("td",{className:"px-6 py-5 text-right",children:[x.status==="pending_ship"&&e.jsx("button",{onClick:()=>Ie(x.order_id),className:"mr-2 text-white bg-black hover:bg-gray-800 shadow-lg shadow-gray-200 text-xs font-bold px-3 py-2 rounded-xl transition-all active:scale-95",children:"立即发货"}),e.jsx("a",{href:`https://www.goofish.com/order-detail?orderId=${x.order_id}&role=seller`,target:"_blank",rel:"noopener noreferrer",className:"mr-2 inline-flex text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看闲鱼详情",children:e.jsx(Mt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>We(x),className:"mr-2 text-gray-400 hover:text-blue-600 p-2 rounded-xl hover:bg-blue-50 transition-colors",title:"查看详情",children:e.jsx(es,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>Ye(x),className:"mr-2 text-gray-400 hover:text-black p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"编辑订单",children:e.jsx(us,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>Xe(x.order_id),disabled:te===x.order_id,className:"mr-2 text-gray-400 hover:text-green-600 p-2 rounded-xl hover:bg-green-50 transition-colors disabled:opacity-50",title:"同步订单",children:e.jsx(qe,{className:`w-4 h-4 ${te===x.order_id?"animate-spin":""}`})}),e.jsx("button",{onClick:()=>He(x.order_id),disabled:pe===x.order_id,className:"text-gray-400 hover:text-red-500 p-2 rounded-xl hover:bg-red-50 transition-colors disabled:opacity-50",title:"删除订单",children:e.jsx(Je,{className:"w-4 h-4"})})]})]},x.id))})]})}),e.jsxs("div",{className:"p-4 border-t border-gray-50 flex items-center justify-between bg-white",children:[e.jsxs("div",{className:"text-sm text-gray-500 font-medium pl-2",children:["第 ",oe," 页 / 共 ",xe," 页"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:oe<=1,onClick:()=>ee(x=>x-1),className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(pa,{className:"w-5 h-5"})}),e.jsx("button",{disabled:oe>=xe,onClick:()=>ee(x=>x+1),className:"p-2.5 rounded-xl bg-gray-50 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed text-gray-600 transition-colors",children:e.jsx(ha,{className:"w-5 h-5"})})]})]})]}),N&&A&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"订单详情"}),e.jsx("button",{onClick:()=>$(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"订单信息"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"订单号"}),e.jsx("div",{className:"font-mono text-sm font-bold text-gray-900",children:A.order_id})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"所属账号"}),e.jsx("div",{className:"truncate whitespace-nowrap text-sm font-bold text-blue-700",title:Le(A.cookie_id),children:Le(A.cookie_id)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"状态"}),e.jsx(wt,{status:A.status})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"实付金额"}),e.jsx("div",{className:"text-lg font-extrabold text-gray-900",children:A.amount?`¥${A.amount}`:"待获取"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"数量"}),e.jsx("div",{className:"font-bold text-gray-900",children:A.quantity})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"创建时间"}),e.jsx("div",{className:"text-sm font-medium text-gray-700",children:Qs(A.created_at)})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"商品信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl flex items-center gap-4",children:[A.item_image&&e.jsx("img",{src:A.item_image,alt:"",className:"w-20 h-20 rounded-xl object-cover border border-gray-200"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-bold text-gray-900 mb-1",children:_e(A.cookie_id,A.item_id,A.item_title)}),e.jsxs("div",{className:"text-sm text-gray-500",children:["商品ID: ",A.item_id]}),A.item_price&&e.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:["标价: ¥",A.item_price]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"text-lg font-bold text-gray-800",children:"买家信息"}),e.jsxs("div",{className:"p-4 bg-gray-50 rounded-xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"买家ID"}),e.jsx("div",{className:"font-bold text-gray-900",children:A.buyer_id})]}),A.receiver_name&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货人"}),e.jsx("div",{className:"font-medium text-gray-700",children:A.receiver_name})]}),A.receiver_phone&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"联系电话"}),e.jsx("div",{className:"font-mono text-sm text-gray-700",children:A.receiver_phone})]}),A.receiver_address&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-gray-500 mb-1",children:"收货地址"}),e.jsx("div",{className:"text-sm text-gray-700",children:A.receiver_address})]})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>$(!1),className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"关闭"}),A.status==="pending_ship"&&e.jsx("button",{onClick:()=>{$(!1),Ie(A.order_id)},className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200",children:"立即发货"})]})})]})}),document.body),ue&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:Ze,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:x=>{var P;return E(((P=x.target.files)==null?void 0:P[0])||null)},className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),re&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:re.name})]})}),i&&i.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",i.success_count," 条,失败 ",i.failed_count," 条"]}),e.jsx("div",{className:"max-h-64 overflow-y-auto rounded-xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"sticky top-0 bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"订单ID"}),e.jsx("th",{className:"px-3 py-2",children:"失败原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-100",children:mr(i).map((x,P)=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-mono",children:x.order_id}),e.jsx("td",{className:"px-3 py-2 text-red-600",children:x.message||"导入失败"})]},`${x.order_id}-${P}`))})]})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:Ze,disabled:d,className:"flex-1 px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:"取消"}),e.jsx("button",{onClick:ss,disabled:!re||d,className:"flex-1 px-6 py-3 rounded-xl ios-btn-primary font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:d?"正在导入…":"导入订单"})]})})]})}),document.body),H&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"480px"},children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"立即发货"}),e.jsx("button",{onClick:()=>{m(!1),z(null)},className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("p",{className:"text-sm text-gray-600",children:"请选择发货方式:"}),e.jsx("button",{onClick:()=>Me("status_only"),disabled:S,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-gray-400 hover:bg-gray-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(ot,{className:"w-5 h-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"仅修改闲鱼发货状态"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:'不实际扣除或发送卡券,仅在闲鱼平台将订单标记为"已发货"。 适用于已经给客户发过货、只是忘记在闲鱼修改状态的情况。'})]})]})}),e.jsx("button",{onClick:()=>Me("full_delivery"),disabled:S,className:"w-full text-left p-4 rounded-xl border-2 border-gray-200 hover:border-[#0094f7] hover:bg-blue-50 transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-100 flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(Ns,{className:"w-5 h-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900 text-sm",children:"完整发货(匹配卡券并发送)"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 leading-relaxed",children:"自动匹配发货规则、获取卡券、发送卡券信息给买家,并修改发货状态。 适用于订单既没有发送卡券给买家、也没有修改发货状态的情况。"})]})]})}),S&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3",children:[e.jsx(qe,{className:"w-4 h-4 animate-spin text-gray-500"}),e.jsx("span",{className:"text-sm text-gray-500",children:"正在处理中..."})]}),se&&e.jsxs("div",{className:`p-3 rounded-xl text-sm ${se.success?"bg-green-50 text-green-800":"bg-red-50 text-red-800"}`,children:[se.success?"✓ ":"✗ ",se.message]})]}),e.jsx("div",{className:"modal-footer",children:e.jsx("button",{onClick:()=>{m(!1),z(null)},className:"w-full px-6 py-3 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold transition-colors",children:se!=null&&se.success?"完成":"取消"})})]})}),document.body),T&&v&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑订单"}),e.jsx("button",{onClick:()=>J(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单号"}),e.jsx("input",{type:"text",value:v.order_id,disabled:!0,className:"w-full ios-input px-4 py-3 rounded-xl bg-gray-50 text-gray-500"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"订单状态"}),e.jsxs("select",{value:v.status,onChange:x=>B({...v,status:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"processing",children:"处理中"}),e.jsx("option",{value:"pending_ship",children:"待发货"}),e.jsx("option",{value:"shipped",children:"已发货"}),e.jsx("option",{value:"completed",children:"已完成"}),e.jsx("option",{value:"cancelled",children:"已取消"}),e.jsx("option",{value:"refunding",children:"退款中"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"买家ID"}),e.jsx("input",{type:"text",value:v.buyer_id,onChange:x=>B({...v,buyer_id:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"实付金额"}),e.jsx("input",{type:"number",value:v.amount,onChange:x=>B({...v,amount:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货人"}),e.jsx("input",{type:"text",value:v.receiver_name||"",onChange:x=>B({...v,receiver_name:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"联系电话"}),e.jsx("input",{type:"text",value:v.receiver_phone||"",onChange:x=>B({...v,receiver_phone:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"收货地址"}),e.jsx("textarea",{value:v.receiver_address||"",onChange:x=>B({...v,receiver_address:x.target.value}),rows:2,className:"w-full ios-input px-4 py-3 rounded-xl resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"商品标题"}),e.jsx("input",{type:"text",value:v.item_title||"",onChange:x=>B({...v,item_title:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>J(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:$e,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ke,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body)]})},pr=(s,t,l)=>{const c=l.trim().toLocaleLowerCase();return s.filter(h=>(!t||h.type===t)&&(!c||h.name.toLocaleLowerCase().includes(c)))},kt=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),hr=()=>{const[s,t]=n.useState([]),[l,c]=n.useState(!1),[h,f]=n.useState(!1),[L,F]=n.useState(null),[g,I]=n.useState({}),[j,G]=n.useState(kt),[Y,X]=n.useState(!1),[de,C]=n.useState("create"),[M,oe]=n.useState(null),[ee,xe]=n.useState(null),[O,le]=n.useState(!1),[D,N]=n.useState(""),[$,T]=n.useState(""),[J,ue]=n.useState(null),[Q,A]=n.useState(""),[b,v]=n.useState("");n.useEffect(()=>{Ve().then(t)},[]);const B=({type:i})=>{switch(i){case"text":return e.jsx(ct,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(dt,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(ja,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(zs,{className:"w-5 h-5 text-gray-500"})}},R=i=>{var q,d,_,te,Z;F(i),I({id:i.id,name:i.name||"",type:i.type||"text",api_url:((q=i.api_config)==null?void 0:q.url)||"",api_method:((d=i.api_config)==null?void 0:d.method)||"GET",api_timeout:((_=i.api_config)==null?void 0:_.timeout)||10,api_headers:((te=i.api_config)==null?void 0:te.headers)||"",api_params:((Z=i.api_config)==null?void 0:Z.params)||"",text_content:i.text_content||"",data_content:i.data_content||"",image_url:i.image_url||"",delay_seconds:i.delay_seconds||0,description:i.description||"",enabled:i.enabled}),c(!0)},K=async()=>{var i,q,d,_,te,Z,pe,Ne;if(L){if(!((i=g.name)!=null&&i.trim())){alert("请输入卡密名称");return}if(!g.type){alert("请选择卡密类型");return}try{const ce={name:g.name.trim(),type:g.type,description:(q=g.description)==null?void 0:q.trim(),delay_seconds:g.delay_seconds||0,enabled:g.enabled??!0};g.type==="api"?ce.api_config={url:((d=g.api_url)==null?void 0:d.trim())||"",method:g.api_method,timeout:g.api_timeout||10,headers:((_=g.api_headers)==null?void 0:_.trim())||void 0,params:((te=g.api_params)==null?void 0:te.trim())||void 0}:g.type==="text"?ce.text_content=((Z=g.text_content)==null?void 0:Z.trim())||"":g.type==="data"?ce.data_content=((pe=g.data_content)==null?void 0:pe.trim())||"":g.type==="image"&&(ce.image_url=((Ne=g.image_url)==null?void 0:Ne.trim())||""),await ft(L.id,ce),c(!1),Ve().then(t)}catch(ce){console.error("更新卡密失败:",ce),alert("更新失败,请重试")}}},H=async i=>{if(confirm("确认删除该卡密吗?"))try{await jl(i),Ve().then(t)}catch(q){console.error("删除卡密失败:",q),alert("删除失败,请重试")}},m=async()=>{if(!j.name.trim()){alert("请输入卡密名称");return}if(!j.content.trim()){alert(j.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const i={name:j.name.trim(),type:j.type,description:j.description.trim(),enabled:j.enabled,delay_seconds:j.delay_seconds};j.type==="text"&&(i.text_content=j.content.trim()),j.type==="data"&&(i.data_content=j.content.trim()),j.type==="image"&&(i.image_url=j.content.trim()),j.type==="api"&&(i.api_config={url:j.content.trim(),method:j.api_method,timeout:j.api_timeout,headers:j.api_headers.trim()||void 0,params:j.api_params.trim()||void 0}),await yl(i),f(!1),G(kt()),Ve().then(t)}catch(i){console.error("添加卡密失败:",i),alert("添加失败,请重试")}},p=async i=>{try{await ft(i.id,{...i,enabled:!i.enabled}),Ve().then(t)}catch(q){console.error("切换状态失败:",q)}},y=async i=>{try{await navigator.clipboard.writeText(String(i)),alert(`已复制卡密组ID:${i}`)}catch{prompt("复制卡密组ID",String(i))}},S=s.filter(i=>i.type==="data"),U=n.useMemo(()=>pr(s,Q,b),[s,b,Q]),se=()=>{const d=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001
+VIP-MONTH-002
+VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(pe=>pe.map(Ne=>`"${String(Ne).replace(/"/g,'""')}"`).join(",")).join(`
+`),_=new Blob(["\uFEFF"+d],{type:"text/csv;charset=utf-8"}),te=URL.createObjectURL(_),Z=document.createElement("a");Z.href=te,Z.download="卡密组批量导入模板.csv",document.body.appendChild(Z),Z.click(),Z.remove(),URL.revokeObjectURL(te)},z=async()=>{if(M){le(!0),xe(null);try{const i=await Nl(M);if(xe(i),i.created>0){const q=await Ve();t(q)}}catch(i){xe({error:(i==null?void 0:i.message)||"上传失败"})}finally{le(!1)}}},re=async()=>{if(!(!D||!$.trim())){le(!0),ue(null);try{const i=await vl(D,$);ue({added:i.added}),T("");const q=await Ve();t(q)}catch(i){alert("追加失败:"+((i==null?void 0:i.message)||"未知错误"))}finally{le(!1)}}},E=()=>{var i;C("create"),oe(null),xe(null),N((i=S[0])!=null&&i.id?String(S[0].id):""),T(""),ue(null),X(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:E,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(js,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>f(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(Qe,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-[#FAFAFA] p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(ga,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:Q,onChange:i=>A(i.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(qt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:b,onChange:i=>v(i.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",U.length," / ",s.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:U.map(i=>{let q="";return i.type==="data"&&i.data_content?q=`库存: ${i.data_content.split(`
+`).filter(_=>_.trim()).length} 条`:i.type==="text"&&i.text_content?q=i.text_content:i.type==="api"&&i.api_config?q=i.api_config.url:i.type==="image"&&i.image_url&&(q="图片链接"),e.jsxs("tr",{className:"hover:bg-[#FFFDE7]/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(B,{type:i.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:i.name,children:i.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>y(i.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:i.id}),e.jsx(ba,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${i.type==="text"?"bg-blue-50 text-blue-600":i.type==="data"?"bg-purple-50 text-purple-600":i.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:i.type==="text"?"文本":i.type==="data"?"批量":i.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:q,children:q})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:i.description||"-",children:i.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>p(i),className:`w-12 h-8 rounded-full relative transition-colors ${i.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${i.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>R(i),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(us,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>H(i.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Je,{className:"h-4 w-4"})})]})})]},i.id)})})]})}),U.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(Dt,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:s.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&L&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>c(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:g.name||"",onChange:i=>I({...g,name:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:g.type||"text",onChange:i=>I({...g,type:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(L==null?void 0:L.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),g.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:g.api_url||"",onChange:i=>I({...g,api_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求方法"}),e.jsxs("select",{value:g.api_method||"GET",onChange:i=>I({...g,api_method:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"超时时间(秒)"}),e.jsx("input",{type:"number",value:g.api_timeout||10,onChange:i=>I({...g,api_timeout:parseInt(i.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"1",max:"60"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求头(JSON 格式)"}),e.jsx("textarea",{value:g.api_headers||"",onChange:i=>I({...g,api_headers:i.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"}'})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"请求参数(JSON 格式)"}),e.jsx("textarea",{value:g.api_params||"",onChange:i=>I({...g,api_params:i.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}'})]})]}),g.type==="text"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"固定文字配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"文字内容"}),e.jsx("textarea",{value:g.text_content||"",onChange:i=>I({...g,text_content:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none",placeholder:"请输入要发送的固定文字内容..."})]})]}),g.type==="data"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"批量数据配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"数据内容(一行一个)"}),e.jsx("textarea",{value:g.data_content||"",onChange:i=>I({...g,data_content:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-80 resize-none font-mono text-sm",placeholder:`请输入数据,每行一个:
+卡号1:密码1
+卡号2:密码2
+或者
+兑换码1
+兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:g.data_content?g.data_content.split(`
+`).filter(i=>i.trim()).length:0})," 条"]})]})]}),g.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:g.image_url||"",onChange:i=>I({...g,image_url:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),g.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:g.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:i=>{i.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:g.delay_seconds||0,onChange:i=>I({...g,delay_seconds:parseInt(i.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:g.description||"",onChange:i=>I({...g,description:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>I({...g,enabled:!g.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${g.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${g.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>c(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:K,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ke,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),h&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>f(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:j.name,onChange:i=>G({...j,name:i.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>G({...j,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="data"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(zs,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>G({...j,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="text"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(ct,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>G({...j,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="image"?"bg-[#0094f7] text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(dt,{className:"w-5 h-5 mx-auto mb-1"}),"图片"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:j.type==="data"?"库存内容(一行一个)":j.type==="text"?"固定回复内容":j.type==="image"?"图片 URL":"API 地址"}),j.type==="api"?e.jsx("input",{type:"url",value:j.content,onChange:i=>G({...j,content:i.target.value}),placeholder:"https://api.example.com/get-code",className:"w-full ios-input px-4 py-3 rounded-xl"}):j.type==="image"?e.jsx("input",{type:"url",value:j.content,onChange:i=>G({...j,content:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://example.com/card.png"}):e.jsx("textarea",{value:j.content,onChange:i=>G({...j,content:i.target.value}),className:`w-full ios-input px-4 py-3 rounded-xl resize-none text-sm ${j.type==="data"?"h-48 font-mono":"h-32"}`,placeholder:j.type==="data"?`CODE-123456
+CODE-789012
+...`:"请输入每次发货时发送的固定文字"}),j.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-[#0094f7]",children:j.content.split(`
+`).filter(i=>i.trim()).length})," 条"]})]}),j.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:j.api_method,onChange:i=>G({...j,api_method:i.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:j.api_timeout,onChange:i=>G({...j,api_timeout:parseInt(i.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:j.api_headers,onChange:i=>G({...j,api_headers:i.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"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:j.api_params,onChange:i=>G({...j,api_params:i.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}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:j.description,onChange:i=>G({...j,description:i.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:j.delay_seconds,onChange:i=>G({...j,delay_seconds:parseInt(i.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>f(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:m,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Qe,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),Y&&Se.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>X(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>C("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${de==="create"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(fa,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>C("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${de==="append"?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(js,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),de==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:se,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm transition-colors",children:[e.jsx(ya,{className:"w-4 h-4"}),"下载模板"]}),e.jsxs("label",{className:"flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm cursor-pointer transition-colors",children:[e.jsx(js,{className:"w-4 h-4"}),M?M.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:i=>{var q;return oe(((q=i.target.files)==null?void 0:q[0])||null)}})]})]}),ee&&!ee.error&&e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-2",children:[e.jsxs("div",{className:"text-sm font-bold text-gray-900",children:["共 ",ee.total," 行 · 成功 ",ee.created," · 失败 ",ee.failed]}),ee.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:ee.rows.filter(i=>!i.success).map(i=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",i.row_no," 行「",i.name,"」:",i.error]},i.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:S.length===0?e.jsx("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800",children:"暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"选择卡密组"}),e.jsx("select",{value:D,onChange:i=>N(i.target.value),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:S.map(i=>e.jsxs("option",{value:String(i.id),children:[i.name,"(ID: ",i.id,")"]},i.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"卡密号(每行一个)"}),e.jsx("textarea",{value:$,onChange:i=>T(i.target.value),placeholder:`VIP-001
+VIP-002
+VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),J&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",J.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>X(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),de==="create"?e.jsxs("button",{onClick:z,disabled:!M||O,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[O?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(js,{className:"w-4 h-4"}),O?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:re,disabled:!D||!$.trim()||O||S.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[O?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(Qe,{className:"w-4 h-4"}),O?"处理中...":"追加卡密"]})]})]})}),document.body)]})},gr=s=>s.find(t=>t.status==="running"||t.status==="canceling"),br=s=>{const t=String(s||"").trim();return t?/^[¥¥]/.test(t)?t:`¥${t}`:"-"},fr=({onConfigureDelivery:s})=>{const[t,l]=n.useState([]),[c,h]=n.useState([]),[f,L]=n.useState([]),[F,g]=n.useState(""),[I,j]=n.useState(""),[G,Y]=n.useState(!1),[X,de]=n.useState(!1),[C,M]=n.useState(!1),[oe,ee]=n.useState(!1),[xe,O]=n.useState(!1),[le,D]=n.useState(!1),[N,$]=n.useState(!1),[T,J]=n.useState("upload"),[ue,Q]=n.useState(null),[A,b]=n.useState(null),[v,B]=n.useState(null),[R,K]=n.useState(null),[H,m]=n.useState(null),p=n.useRef(!1),[y,S]=n.useState(null),[U,se]=n.useState({}),[z,re]=n.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[E,i]=n.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[q,d]=n.useState([]);n.useEffect(()=>{if(!le||E.images.length===0){d([]);return}const r=E.images.map((a,u)=>({key:a.name+u,url:URL.createObjectURL(a)}));return d(r),()=>{r.forEach(a=>URL.revokeObjectURL(a.url))}},[le,E.images]);const _=async()=>{const r=await ps();l(r)},te=async()=>{h(await Is())};n.useEffect(()=>{Promise.all([Rs(),ps(),Is(),yt(20)]).then(([r,a,u,w])=>{L(r),l(a),h(u);const W=w.find(ae=>["running","canceling"].includes(ae.status))||w.find(ae=>ae.status!=="preview");m(W||null)}).catch(r=>console.error("加载商品配置失败:",r))},[]),n.useEffect(()=>{if(!N||!(R!=null&&R.id)||!["running","canceling"].includes(R.status))return;const r=window.setInterval(async()=>{if(!p.current){p.current=!0;try{const a=await os(R.id);K(a),m(a),["running","canceling"].includes(a.status)||(J("done"),await _(),await te())}catch(a){console.error("刷新批量铺货进度失败:",a)}finally{p.current=!1}}},3e3);return()=>{window.clearInterval(r)}},[N,R==null?void 0:R.id,R==null?void 0:R.status]);const Z=async()=>{if(!F)return alert("请先选择账号");Y(!0);try{const r=await _l(F);await _(),alert((r==null?void 0:r.message)||"商品同步完成")}catch(r){console.error("同步商品失败:",r),alert((r==null?void 0:r.message)||"同步失败,请重试")}finally{Y(!1)}},pe=r=>{S(r),se({...r}),ee(!0)},Ne=async()=>{if(y)try{await Rl(y.cookie_id,y.item_id,{item_title:U.item_title||"",item_description:U.item_description||"",item_category:U.item_category||"",item_price:U.item_price||"",item_detail:U.item_detail||y.item_detail||""}),await _(),await te(),ee(!1),S(null)}catch(r){console.error("更新商品失败:",r),alert("更新失败,请重试")}},ce=async r=>{if(confirm(`确认删除商品"${r.item_title}"吗?`))try{await wl(r.cookie_id,r.item_id),l(a=>a.filter(u=>!(u.cookie_id===r.cookie_id&&u.item_id===r.item_id)))}catch(a){console.error("删除商品失败:",a),alert("删除失败,请重试")}},_e=async()=>{try{if(!z.cookie_id||!z.item_id){alert("请选择账号并填写商品ID");return}await kl(z.cookie_id,{item_id:z.item_id,item_title:z.item_title,item_price:z.item_price,item_detail:z.item_image?JSON.stringify({item_image:z.item_image}):""}),await _(),O(!1),re({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""})}catch(r){console.error("添加商品失败:",r),alert("添加失败,请重试")}},Re=async()=>{if(!E.cookie_id)return alert("请选择发布账号");if(!E.title.trim())return alert("请填写商品标题");if(!E.price.trim())return alert("请填写商品价格");if(!E.quantity||Number(E.quantity)<=0)return alert("库存数量必须大于 0");if(E.images.length===0)return alert("至少上传 1 张商品图片");if(E.postage_mode==="fixed"&&!E.postage.trim())return alert("请填写一口价邮费");de(!0);try{const r=await Cl(E);if(await _(),D(!1),i({cookie_id:F||"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),r!=null&&r.item_id){const a={id:r.item_id,cookie_id:E.cookie_id,item_id:r.item_id,item_title:r.item_title||E.title,item_price:r.item_price||E.price,item_image:r.item_image};s(a),alert("商品发布成功,ID: "+r.item_id+",已为你打开发货规则配置")}else alert("商品发布成功")}catch(r){console.error("发布商品失败:",r);const a=r==null?void 0:r.payload;if((a==null?void 0:a.code)==="stock_permission_missing"){alert("发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。");return}alert((r==null?void 0:r.message)||"发布失败,请重试")}finally{de(!1)}},ye=async()=>{J("upload"),B(null),K(null),Q(null),b(null),$(!0),M(!0);try{const r=await yt(20),a=gr(r);if(a!=null&&a.id){const u=await os(a.id);m(u),K(u),J(["running","canceling"].includes(u.status)?"running":"done")}}catch(r){console.error("恢复最近批量铺货任务失败:",r)}finally{M(!1)}},Ae=async()=>{if(H!=null&&H.id){M(!0),$(!0);try{const r=await os(H.id);K(r),J(["running","canceling"].includes(r.status)?"running":"done")}catch(r){console.error("加载最近批量铺货结果失败:",r)}finally{M(!1)}}},Le=async()=>{if(!ue)return alert("请先上传商品表格");if(!F)return alert("请先选择默认发布账号");M(!0);try{const r=await Sl({file:ue,imagesZip:A,defaultCookieId:F});B(r),K(null),J("preview")}catch(r){console.error("批量铺货预检失败:",r),alert((r==null?void 0:r.message)||"预检失败,请检查表格和图片 zip")}finally{M(!1)}},Be=async()=>{if(v!=null&&v.preview_id){if(v.valid<=0)return alert("没有可发布的商品行");M(!0);try{const r=await Ll(v.preview_id),a=await os(r.batch_id||v.preview_id);K(a),m(a),J(a.status==="running"?"running":"done")}catch(r){console.error("启动批量铺货失败:",r),alert((r==null?void 0:r.message)||"启动发布任务失败")}finally{M(!1)}}},Ie=async()=>{if(R!=null&&R.id&&confirm("确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。")){M(!0);try{const r=await Il(R.id),a=await os(R.id);K(a),J((r==null?void 0:r.status)==="canceling"||a.status==="canceling"?"running":"done")}catch(r){alert((r==null?void 0:r.message)||"取消失败")}finally{M(!1)}}},Me=async()=>{const r=v==null?void 0:v.preview_id;if(r&&T==="preview")try{await Al(r)}catch(a){console.error("清理批量铺货预检失败:",a)}B(null),J("upload")},We=async()=>{await Me(),$(!1)},Ye=async()=>{if(R!=null&&R.id){M(!0);try{await $l(R.id),K(await os(R.id)),J("running")}catch(r){alert((r==null?void 0:r.message)||"重试失败")}finally{M(!1)}}},$e=()=>{const u=[["账号ID","标题","描述","价格","原价","库存","邮费模式","邮费","图片","付款发货启用","付款发货内容","评价赠品启用","评价赠品内容","求评价启用","求评价等待小时","求评价文案","求评价最多次数"],...[["","会员组合包自动发货","下单后发送主卡和附赠卡。","19.90","29.90","10","free","","images/bundle-1.jpg;images/bundle-2.jpg","是","101:1;102:1","是","201:1;202:2","是","72","亲,满意的话麻烦给个评价,谢谢~","1"],["","普通商品","仅发布商品,不创建自动化规则。","49.90","","10","fixed","8.00","https://example.com/product.jpg","否","","否","","否","","",""]]].map(ve=>ve.map(he=>`"${String(he).replace(/"/g,'""')}"`).join(",")).join(`
+`),w=new Blob(["\uFEFF"+u],{type:"text/csv;charset=utf-8"}),W=URL.createObjectURL(w),ae=document.createElement("a");ae.href=W,ae.download="批量铺货模板.csv",document.body.appendChild(ae),ae.click(),ae.remove(),URL.revokeObjectURL(W)},ss=()=>{re(r=>({...r,cookie_id:F||r.cookie_id})),O(!0)},Ze=()=>{i(r=>({...r,cookie_id:F||r.cookie_id})),D(!0)},Xe=r=>c.filter(a=>a.cookie_id===r.cookie_id&&a.item_id===r.item_id).length>0?c.filter(a=>a.cookie_id===r.cookie_id&&a.item_id===r.item_id):c.filter(a=>a.cookie_id===r.cookie_id&&!a.item_id),He=r=>{switch(r){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return r||"-"}},x=r=>{switch(r){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},P=n.useMemo(()=>new Map(f.map(r=>[r.id,r])),[f]),me=n.useMemo(()=>I?t.filter(r=>r.cookie_id===I):t,[I,t]),fe=r=>{const a=P.get(r),u=(a==null?void 0:a.remark)||(a==null?void 0:a.nickname);return u?`${u} · ${r.slice(0,6)}`:`账号 ${r.slice(0,8)}`},ze=r=>{const a=P.get(r);return(a==null?void 0:a.remark)||(a==null?void 0:a.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(Na,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:I,onChange:r=>j(r.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),f.map(r=>e.jsx("option",{value:r.id,children:fe(r.id)},r.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(ns,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:F,onChange:r=>g(r.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),f.map(r=>e.jsx("option",{value:r.id,children:fe(r.id)},r.id))]})]})]}),e.jsxs("button",{onClick:Z,disabled:G||!F,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(qe,{className:`w-4 h-4 ${G?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:ss,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(Qe,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:Ze,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-600 text-white hover:bg-emerald-700 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(Ts,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void ye(),className:"px-5 py-3 rounded-2xl font-bold bg-blue-600 text-white hover:bg-blue-700 transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(_s,{className:"w-4 h-4"}),H&&["running","canceling"].includes(H.status)?"继续批量任务":"批量铺货"]}),H&&!["running","canceling"].includes(H.status)&&e.jsx("button",{onClick:()=>void Ae(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[me.map(r=>{const a=Xe(r),u=a.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex-col",children:[e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[e.jsx("button",{onClick:()=>pe(r),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md text-gray-600 hover:bg-[#0094f7] hover:text-white transition-colors",title:"编辑",children:e.jsx(us,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>ce(r),className:"p-1.5 bg-white/90 backdrop-blur rounded-lg shadow-md hover:bg-red-100 text-red-500 transition-colors",title:"删除",children:e.jsx(Je,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"aspect-square bg-gray-100 rounded-xl mb-2.5 overflow-hidden relative",children:[r.item_image?e.jsx("img",{src:r.item_image,alt:"",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-300",children:e.jsx(Et,{className:"w-8 h-8"})}),e.jsx("div",{className:"absolute top-1.5 left-1.5 bg-black/50 backdrop-blur-md text-white text-[10px] font-bold px-1.5 py-0.5 rounded-md",children:br(r.item_price)})]}),e.jsx("h3",{className:"font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4",children:r.item_title}),e.jsxs("div",{className:"mb-2 inline-flex min-w-0 max-w-full items-center gap-1 self-start rounded-md bg-blue-50 px-2 py-1 text-[10px] font-extrabold text-blue-700",title:ze(r.cookie_id),children:[e.jsx(ns,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap",children:ze(r.cookie_id)})]}),e.jsxs("div",{className:"flex justify-between items-center text-[10px] text-gray-500 mb-2",children:[e.jsxs("span",{className:"bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]",children:["ID: ",r.item_id]}),e.jsxs("span",{className:`inline-flex items-center gap-1 font-bold ${u?"text-emerald-600":"text-amber-600"}`,children:[u?e.jsx(Bt,{className:"w-3 h-3"}):e.jsx(va,{className:"w-3 h-3"}),u?`${a.length} 规则`:"未配置"]})]}),e.jsx("div",{className:"space-y-2 mt-auto",children:e.jsxs("button",{onClick:()=>s(r),className:`w-full flex items-center justify-between gap-1 px-2.5 py-2 rounded-lg text-[11px] font-extrabold transition-all ${u?"bg-gray-900 text-white hover:bg-black":"bg-[#0094f7] text-white hover:bg-[#0071e3] shadow-md shadow-blue-100"}`,children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(_a,{className:"w-3.5 h-3.5"}),u?"查看发货规则":"关联发货规则"]}),e.jsx(Ws,{className:"w-3.5 h-3.5"})]})})]},`${r.cookie_id}-${r.item_id}`)}),me.length===0&&e.jsxs("div",{className:"col-span-full py-20 text-center text-gray-400",children:[e.jsx(Tt,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),I?"该账号暂无商品数据":"暂无商品数据,请选择账号进行同步"]})]}),oe&&y&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"560px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"编辑商品"}),e.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["ID: ",y.item_id]})]}),e.jsx("button",{onClick:()=>ee(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-4",children:[e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"商品标题",value:U.item_title||"",onChange:r=>se({...U,item_title:r.target.value})}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"价格",value:U.item_price||"",onChange:r=>se({...U,item_price:r.target.value})}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"分类",value:U.item_category||"",onChange:r=>se({...U,item_category:r.target.value})}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述",value:U.item_description||"",onChange:r=>se({...U,item_description:r.target.value})})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:Ne,className:"w-full ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ke,{className:"w-4 h-4"}),"保存"]})})]})}),document.body),xe&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"720px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"添加商品"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"手动建立商品与自动发货规则的关联"})]}),e.jsx("button",{onClick:()=>O(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"所属账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:z.cookie_id,onChange:r=>re({...z,cookie_id:r.target.value}),children:[e.jsx("option",{value:"",children:"选择账号"}),f.map(r=>e.jsx("option",{value:r.id,children:fe(r.id)},r.id))]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品 ID"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入闲鱼商品 ID",value:z.item_id,onChange:r=>re({...z,item_id:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品价格"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如 99.00",value:z.item_price,onChange:r=>re({...z,item_price:r.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品标题"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"输入商品标题",value:z.item_title,onChange:r=>re({...z,item_title:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"图片 URL"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"https://...",value:z.item_image,onChange:r=>re({...z,item_image:r.target.value})})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{onClick:_e,className:"w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Qe,{className:"w-4 h-4"}),"添加商品"]})})]})}),document.body),le&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"820px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"发布商品到闲鱼"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"普通单规格发布;库存数量会写入闲鱼发布参数,用于判断账号库存能力。"})]}),e.jsx("button",{onClick:()=>D(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx("div",{className:"rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800 leading-6",children:"发布时必须填写库存。若账号没有库存发布能力,后端会返回明确的“库存权限不足”错误,不会误报为普通发布失败。"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"发布账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:E.cookie_id,onChange:r=>i({...E,cookie_id:r.target.value}),children:[e.jsx("option",{value:"",children:"选择账号"}),f.map(r=>e.jsx("option",{value:r.id,children:fe(r.id)},r.id))]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品标题"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:会员月卡自动发货",value:E.title,onChange:r=>i({...E,title:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"库存数量"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",type:"number",min:"1",placeholder:"必须大于 0",value:E.quantity,onChange:r=>i({...E,quantity:r.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品描述"}),e.jsx("textarea",{className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none",placeholder:"描述会用于自动识别类目;留空时使用标题",value:E.description,onChange:r=>i({...E,description:r.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"售价"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"99.00",value:E.price,onChange:r=>i({...E,price:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"原价(可选)"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"129.00",value:E.original_price,onChange:r=>i({...E,original_price:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"运费方式"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:E.postage_mode,onChange:r=>i({...E,postage_mode:r.target.value}),children:[e.jsx("option",{value:"free",children:"包邮"}),e.jsx("option",{value:"distance",children:"按距离计费"}),e.jsx("option",{value:"fixed",children:"一口价邮费"}),e.jsx("option",{value:"none",children:"无需邮寄"})]})]})]}),E.postage_mode==="fixed"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"一口价邮费"}),e.jsx("input",{className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如 8.00",value:E.postage,onChange:r=>i({...E,postage:r.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"商品图片(1-9 张)"}),e.jsxs("label",{className:"flex min-h-[120px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50/50 transition-colors",children:[e.jsx(_s,{className:"w-8 h-8 text-emerald-600 mb-2"}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"选择图片"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:E.images.length?"已选择 "+E.images.length+" 张":"支持 JPG / PNG / GIF"}),e.jsx("input",{className:"hidden",type:"file",accept:"image/*",multiple:!0,onChange:r=>i({...E,images:Array.from(r.target.files||[]).slice(0,9)})})]}),q.length>0&&e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-3",children:q.map(r=>e.jsx("div",{className:"aspect-square rounded-xl bg-gray-100 overflow-hidden border border-gray-100",children:e.jsx("img",{src:r.url,alt:"",className:"w-full h-full object-cover"})},r.key))})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("button",{disabled:X,onClick:Re,className:"w-full bg-emerald-600 hover:bg-emerald-700 disabled:opacity-60 text-white px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ts,{className:"w-4 h-4"}),X?"正在发布...":"发布到闲鱼"]})})]})}),document.body),N&&Se.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"980px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量铺货"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"上传商品表格和图片 zip,先预检,再逐条发布到闲鱼。"})]}),e.jsx("button",{onClick:()=>void We(),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",title:"关闭",children:e.jsx(we,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsx("div",{className:"grid grid-cols-4 gap-2",children:[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]].map(([r,a])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${T===r?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:a},r))}),T==="upload"&&e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"rounded-2xl border border-blue-100 bg-blue-50 p-4 text-sm text-blue-900 leading-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:"先下载模板,再按字段填写。"}),e.jsxs("div",{children:["图片字段写 zip 内相对路径,多个图片用英文分号分隔,例如 ",e.jsx("span",{className:"font-mono font-bold",children:"images/a.jpg;images/b.jpg"}),"。也支持直接填写图片 URL。"]})]}),e.jsx("button",{type:"button",onClick:$e,className:"shrink-0 rounded-xl bg-blue-600 px-4 py-2 text-sm font-extrabold text-white hover:bg-blue-700",children:"下载CSV模板"})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"默认发布账号"}),e.jsxs("select",{className:"w-full ios-input px-4 py-3 rounded-xl",value:F,onChange:r=>g(r.target.value),children:[e.jsx("option",{value:"",children:"选择账号"}),f.map(r=>e.jsx("option",{value:r.id,children:fe(r.id)},r.id))]}),e.jsx("p",{className:"text-xs text-gray-500",children:"表格中“账号ID”为空时,会使用这里选择的账号。"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-blue-300 hover:bg-blue-50 transition-colors",children:[e.jsx(_s,{className:"w-9 h-9 text-blue-600 mb-3"}),e.jsx("span",{className:"text-sm font-extrabold text-gray-900",children:"上传商品表格"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:ue?ue.name:"支持 .xlsx / .csv / .tsv"}),e.jsx("input",{className:"hidden",type:"file",accept:".xlsx,.csv,.tsv",onChange:r=>{var a;return Q(((a=r.target.files)==null?void 0:a[0])||null)}})]}),e.jsxs("label",{className:"flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-emerald-300 hover:bg-emerald-50 transition-colors",children:[e.jsx(_s,{className:"w-9 h-9 text-emerald-600 mb-3"}),e.jsx("span",{className:"text-sm font-extrabold text-gray-900",children:"上传图片 zip(可选)"}),e.jsx("span",{className:"text-xs text-gray-500 mt-1",children:A?A.name:"表格图片字段使用 zip 内相对路径"}),e.jsx("input",{className:"hidden",type:"file",accept:".zip",onChange:r=>{var a;return b(((a=r.target.files)==null?void 0:a[0])||null)}})]})]}),e.jsxs("div",{className:"rounded-2xl bg-gray-50 border border-gray-100 p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"字段说明"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"照着下面的“什么时候填写”处理即可。预检发现问题时,会指出具体哪一行需要修改。"})]}),e.jsxs("div",{className:"rounded-xl border border-blue-100 bg-blue-50 p-4 text-xs text-blue-950",children:[e.jsx("div",{className:"text-sm font-extrabold",children:"“付款后发送的卡密”怎么填"}),e.jsxs("div",{className:"mt-3 grid grid-cols-1 gap-3 lg:grid-cols-3",children:[e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101"}),e.jsx("p",{className:"mt-1 leading-5",children:"从卡密组 101 立即发送 1 份。卡密组 ID 可以在“卡密库存”页面查看。"})]}),e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101:2"}),e.jsx("p",{className:"mt-1 leading-5",children:"每购买 1 件,就从卡密组 101 发送 2 份。买家购买 3 件时会发送 6 份。"})]}),e.jsxs("div",{className:"rounded-lg bg-white/80 p-3",children:[e.jsx("code",{className:"font-bold text-blue-700",children:"101:1:0;102:2:3"}),e.jsx("p",{className:"mt-1 leading-5",children:"先立即发送卡密组 101 的 1 份,再等待 3 秒发送卡密组 102 的 2 份。"})]})]}),e.jsxs("p",{className:"mt-3 leading-5 text-blue-800",children:["每一组依次写“卡密组 ID : 每件发送几份 : 等待几秒”。份数不写时按 1 份处理,等待时间不写时立即发送。需要发送多种卡密时,用英文分号 ",e.jsx("code",{className:"font-bold",children:";"})," 隔开。"]})]}),e.jsx("div",{className:"overflow-x-auto rounded-xl border border-gray-100 bg-white",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{className:"bg-gray-50 text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2",children:"字段"}),e.jsx("th",{className:"px-3 py-2",children:"什么时候填写"}),e.jsx("th",{className:"px-3 py-2",children:"填写方法"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50 text-gray-700",children:[["账号ID","需要覆盖默认账号时填写","上方默认发布账号为必选;本列留空时使用默认账号,填写后仅覆盖当前行"],["标题","每个商品都要填","填写买家能看到的商品标题"],["描述","可以留空","留空时会使用商品标题作为描述"],["价格","每个商品都要填","只填数字,例如 19.90"],["原价","可以留空","需要展示划线原价时填写,例如 29.90"],["库存","可以留空","留空按 1 件处理;填写时必须大于 0"],["邮费模式","可以留空","留空表示包邮;包邮填 free,固定邮费填 fixed"],["邮费","邮费模式填 fixed 时填写","只填数字,例如 8.00"],["图片","每个商品都要填","填写 zip 内图片路径或图片网址;多张图片用英文分号隔开"],["付款发货启用","需要付款后自动发货时填写","填“是”表示开启;不需要时填“否”或留空"],["付款发货内容","“付款发货启用”填“是”时填写","从“卡密库存”页面取得卡密组 ID,按上方示例填写"],["评价赠品启用","需要评价赠品时填写","填“是”表示开启;不需要时填“否”或留空"],["评价赠品内容","“评价赠品启用”填“是”时填写","格式和付款发货内容相同,也可以同时发送多个卡密组"],["求评价启用","需要自动求评价时填写","填“是”表示开启;不需要时填“否”或留空"],["求评价等待小时","“求评价启用”填“是”时填写","填写等待小时数;留空按 72 小时处理"],["求评价文案","“求评价启用”填“是”时填写","填写要发送给买家的求评价消息"],["求评价最多次数","可以留空","留空只提醒 1 次"]].map(([r,a,u])=>e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-bold text-gray-900 whitespace-nowrap",children:r}),e.jsx("td",{className:`px-3 py-2 min-w-[210px] font-bold ${a==="每个商品都要填"?"text-red-600":a==="可以留空"?"text-gray-500":"text-amber-700"}`,children:a}),e.jsx("td",{className:"px-3 py-2 min-w-[260px]",children:u})]},r))})]})})]})]}),T==="preview"&&v&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"rounded-2xl bg-gray-50 p-4 border border-gray-100",children:[e.jsx("div",{className:"text-xs font-bold text-gray-500",children:"总行数"}),e.jsx("div",{className:"text-2xl font-extrabold text-gray-900 mt-1",children:v.total})]}),e.jsxs("div",{className:"rounded-2xl bg-emerald-50 p-4 border border-emerald-100",children:[e.jsx("div",{className:"text-xs font-bold text-emerald-700",children:"可发布"}),e.jsx("div",{className:"text-2xl font-extrabold text-emerald-700 mt-1",children:v.valid})]}),e.jsxs("div",{className:"rounded-2xl bg-red-50 p-4 border border-red-100",children:[e.jsx("div",{className:"text-xs font-bold text-red-700",children:"有问题"}),e.jsx("div",{className:"text-2xl font-extrabold text-red-700 mt-1",children:v.invalid})]})]}),e.jsx("div",{className:"max-h-[380px] overflow-y-auto rounded-2xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"行号"}),e.jsx("th",{className:"px-4 py-3",children:"状态"}),e.jsx("th",{className:"px-4 py-3",children:"标题"}),e.jsx("th",{className:"px-4 py-3",children:"价格/库存"}),e.jsx("th",{className:"px-4 py-3",children:"图片"}),e.jsx("th",{className:"px-4 py-3",children:"问题"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:v.rows.map(r=>{var a,u;return e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:r.row_no}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${r.valid?"bg-emerald-50 text-emerald-700 border-emerald-100":"bg-red-50 text-red-700 border-red-100"}`,children:r.valid?"可发布":"需修正"})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[240px] truncate",children:r.title||"-"}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:["¥",r.price||"-"," / ",r.quantity||1]}),e.jsxs("td",{className:"px-4 py-3 text-gray-600",children:[((a=r.images)==null?void 0:a.length)||0," 张"]}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[280px]",children:((u=r.errors)==null?void 0:u.join(";"))||"-"})]},r.row_no)})})]})})]}),(T==="running"||T==="done")&&R&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("div",{className:`rounded-2xl p-4 border ${x(R.status)}`,children:[e.jsx("div",{className:"text-xs font-bold opacity-70",children:"任务状态"}),e.jsx("div",{className:"text-xl font-extrabold mt-1",children:He(R.status)})]}),e.jsxs("div",{className:"rounded-2xl bg-gray-50 p-4 border border-gray-100",children:[e.jsx("div",{className:"text-xs font-bold text-gray-500",children:"总数"}),e.jsx("div",{className:"text-xl font-extrabold text-gray-900 mt-1",children:R.total})]}),e.jsxs("div",{className:"rounded-2xl bg-emerald-50 p-4 border border-emerald-100",children:[e.jsx("div",{className:"text-xs font-bold text-emerald-700",children:"成功"}),e.jsx("div",{className:"text-xl font-extrabold text-emerald-700 mt-1",children:R.success})]}),e.jsxs("div",{className:"rounded-2xl bg-red-50 p-4 border border-red-100",children:[e.jsx("div",{className:"text-xs font-bold text-red-700",children:"失败"}),e.jsx("div",{className:"text-xl font-extrabold text-red-700 mt-1",children:R.failed})]}),e.jsxs("div",{className:"rounded-2xl bg-blue-50 p-4 border border-blue-100",children:[e.jsx("div",{className:"text-xs font-bold text-blue-700",children:"等待"}),e.jsx("div",{className:"text-xl font-extrabold text-blue-700 mt-1",children:R.pending})]})]}),e.jsx("div",{className:"max-h-[420px] overflow-y-auto rounded-2xl border border-gray-100",children:e.jsxs("table",{className:"w-full text-left text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-white text-xs text-gray-400 border-b border-gray-100",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3",children:"行号"}),e.jsx("th",{className:"px-4 py-3",children:"状态"}),e.jsx("th",{className:"px-4 py-3",children:"标题"}),e.jsx("th",{className:"px-4 py-3",children:"商品ID"}),e.jsx("th",{className:"px-4 py-3",children:"错误原因"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:R.rows.map(r=>e.jsxs("tr",{className:"hover:bg-gray-50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:r.row_no}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:`inline-flex px-2 py-1 rounded-lg border text-xs font-extrabold ${x(r.status)}`,children:He(r.status)})}),e.jsx("td",{className:"px-4 py-3 font-bold text-gray-900 max-w-[260px] truncate",children:r.title}),e.jsx("td",{className:"px-4 py-3 text-xs font-mono",children:r.item_url?e.jsx("a",{href:r.item_url,target:"_blank",rel:"noreferrer",className:"text-blue-600 hover:underline",children:r.item_id}):r.item_id||"-"}),e.jsx("td",{className:"px-4 py-3 text-red-600 text-xs max-w-[340px]",children:r.error_message||"-"})]},r.id))})]})})]})]}),e.jsxs("div",{className:"modal-footer",children:[T==="upload"&&e.jsxs("button",{disabled:C||!ue||!F,onClick:Le,className:"w-full ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(qe,{className:`w-4 h-4 ${C?"animate-spin":""}`}),C?"正在预检...":"开始预检"]}),T==="preview"&&v&&e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{disabled:C,onClick:()=>void Me(),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold",children:"返回修改"}),e.jsxs("button",{disabled:C||v.valid<=0,onClick:Be,className:"flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(Ts,{className:"w-4 h-4"}),C?"启动中...":`确认发布 ${v.valid} 个商品`]})]}),(T==="running"||T==="done")&&R&&e.jsxs("div",{className:"flex gap-3 w-full",children:[R.status==="running"?e.jsx("button",{disabled:C,onClick:Ie,className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"取消任务"}):R.status==="canceling"?e.jsx("button",{disabled:!0,className:"flex-1 px-6 py-3.5 rounded-xl bg-amber-100 text-amber-800 font-bold",children:"正在保存远端结果并安全取消…"}):e.jsx("button",{onClick:()=>window.open(`/items/publish-batches/${R.id}/result.csv`,"_blank"),className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-900 text-white hover:bg-black font-bold",children:"下载结果"}),R.retryable>0&&!["running","canceling"].includes(R.status)&&e.jsxs("button",{disabled:C,onClick:Ye,className:"flex-1 ios-btn-primary px-6 py-3.5 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(qe,{className:`w-4 h-4 ${C?"animate-spin":""}`}),"重试失败项"]}),!["running","canceling"].includes(R.status)&&e.jsx("button",{onClick:()=>{$(!1),_(),te()},className:"flex-1 px-6 py-3.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-800 font-bold",children:"完成"})]})]})]})}),document.body)]})},Ct="https://dashscope.aliyuncs.com/compatible-mode/v1",yr=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],jr=new Set(["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),Nr=()=>{const[s,t]=n.useState(null),[l,c]=n.useState(!1),[h,f]=n.useState(""),[L,F]=n.useState(!1),[g,I]=n.useState([]),[j,G]=n.useState(!1),[Y,X]=n.useState(""),[de,C]=n.useState(!1),M=n.useRef(null),[oe,ee]=n.useState(!1),[xe,O]=n.useState(!1),[le,D]=n.useState(!1),[N,$]=n.useState(!1),[T,J]=n.useState(!1),[ue,Q]=n.useState(null),[A,b]=n.useState({new_username:"",current_password:"",new_password:"",confirm_password:""});n.useEffect(()=>{B(),Gt().then(p=>{p.username&&b(y=>({...y,new_username:p.username||""}))}).catch(()=>{})},[]),n.useEffect(()=>{const p=y=>{var S;(S=M.current)!=null&&S.contains(y.target)||C(!1)};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[]);const v=async(p,y=!1)=>{const S=p||s,U=(S==null?void 0:S.ai_api_url)||(S==null?void 0:S.ai_base_url)||Ct;G(!0),X("");try{const se=await Vl(U,(S==null?void 0:S.ai_api_key)||"");I(se),C(y&&se.length>0),!(S!=null&&S.ai_model)&&se.length>0&&t(z=>z&&{...z,ai_model:se[0]})}catch(se){I([]),C(!1),X(se.message||"读取模型失败")}finally{G(!1)}},B=()=>{c(!0),f(""),Kt().then(p=>{t(p),v(p)}).catch(p=>{t(null),f(p.message||"加载配置失败")}).finally(()=>c(!1))},R=async()=>{if(s){F(!0);try{const p=Object.fromEntries(Object.entries(s).filter(([y,S])=>!jr.has(y)&&S!==void 0&&S!==null));await Yt(p),alert("系统配置已保存")}catch(p){alert("保存失败:"+p.message)}finally{F(!1)}}},K=async p=>{p.preventDefault(),Q(null);const y=A.new_username.trim();if(y.length<3){Q({type:"error",text:"用户名至少需要 3 个字符"});return}if(!A.current_password){Q({type:"error",text:"请输入当前密码确认身份"});return}if(A.new_password&&A.new_password.length<8){Q({type:"error",text:"新密码至少需要 8 个字符"});return}if(A.new_password!==A.confirm_password){Q({type:"error",text:"两次输入的新密码不一致"});return}J(!0);try{const S=await Ga({current_password:A.current_password,new_username:y,new_password:A.new_password||void 0});if(!S.success){Q({type:"error",text:S.message||"登录凭据更新失败"});return}Q({type:"success",text:S.message||"登录凭据已更新"}),window.setTimeout(()=>window.location.reload(),1400)}catch(S){Q({type:"error",text:S.message||"登录凭据更新失败"})}finally{J(!1)}};if(!s)return e.jsx("div",{className:"p-8 text-center text-gray-400",children:h||(l?"加载配置中...":"暂无配置")});const H=s.ai_model||"",m=g;return e.jsxs("div",{className:"max-w-6xl mx-auto space-y-8 animate-fade-in pb-24",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-12 h-12 bg-gray-100 rounded-2xl flex items-center justify-center",children:e.jsx(Ys,{className:"w-6 h-6 text-gray-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900",children:"系统设置"}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm font-medium",children:"配置全局自动化规则与系统参数"})]})]}),e.jsxs("button",{onClick:B,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(qe,{className:"w-4 h-4"}),"刷新"]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-100 text-gray-600",children:e.jsx(wa,{className:"w-4 h-4"})}),"基础设置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出等级"}),e.jsx("select",{value:s.log_level||"info",onChange:p=>t({...s,log_level:p.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:yr.map(p=>e.jsx("option",{value:p.value,children:p.label},p.value))}),e.jsx("p",{className:"text-xs text-gray-500",children:"等级越低输出越详细,Debug 适合排查问题"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"日志输出格式"}),e.jsxs("select",{value:s.log_format||"text",onChange:p=>t({...s,log_format:p.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"json",children:"JSON"})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"JSON 适合接入集中式日志系统,保存后需重启服务生效"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"续期日志保留天数"}),e.jsx("input",{type:"number",value:s.renewal_log_retention_days??10,onChange:p=>t({...s,renewal_log_retention_days:parseInt(p.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"365"}),e.jsx("p",{className:"text-xs text-gray-500",children:"0 表示不自动清理续期日志"})]})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-[#0094f7] text-white",children:e.jsx(Ft,{className:"w-4 h-4"})}),"AI 智能回复配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API 地址"}),e.jsx("input",{type:"text",value:s.ai_api_url||Ct,onChange:p=>t({...s,ai_api_url:p.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://api.openai.com/v1"}),e.jsx("p",{className:"text-xs text-gray-500",children:"无需补全 /chat/completions"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:oe?"text":"password",value:s.ai_api_key||"",onChange:p=>t({...s,ai_api_key:p.target.value}),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",placeholder:"sk-..."}),e.jsx("button",{type:"button",onClick:()=>ee(!oe),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:oe?e.jsx(rs,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"模型"}),e.jsxs("div",{ref:M,className:"relative flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("input",{value:H,onFocus:()=>g.length>0&&C(!0),onChange:p=>{t({...s,ai_model:p.target.value}),g.length>0&&C(!0)},onKeyDown:p=>{p.key==="Escape"&&C(!1),p.key==="ArrowDown"&&g.length>0&&C(!0)},className:"w-full ios-input px-4 py-3 pr-10 rounded-xl",placeholder:"从接口读取或手动输入模型名"}),e.jsx("button",{type:"button",onClick:()=>g.length>0&&C(p=>!p),disabled:g.length===0,className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 disabled:opacity-30","aria-label":"展开模型列表",children:e.jsx(ka,{className:`w-4 h-4 transition-transform ${de?"rotate-180":""}`})}),de&&e.jsx("div",{className:"absolute left-0 right-0 top-[calc(100%+6px)] z-40 max-h-64 overflow-y-auto rounded-xl border border-gray-200 bg-white shadow-xl shadow-gray-200/70 py-1",children:m.length>0?m.map(p=>e.jsxs("button",{type:"button",onClick:()=>{t({...s,ai_model:p}),C(!1)},className:"w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-blue-50 hover:text-[#0094f7] flex items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate",children:p}),p===H&&e.jsx(Ge,{className:"w-4 h-4 shrink-0 text-[#0094f7]"})]},p)):e.jsx("div",{className:"px-4 py-3 text-sm text-gray-400",children:"没有匹配的模型"})})]}),e.jsxs("button",{type:"button",onClick:()=>v(void 0,!0),disabled:j,className:"px-4 py-3 rounded-xl bg-gray-100 text-gray-700 hover:bg-gray-200 disabled:opacity-60 font-bold flex items-center justify-center gap-2 whitespace-nowrap",children:[e.jsx(qe,{className:`w-4 h-4 ${j?"animate-spin":""}`}),"读取模型"]})]}),Y?e.jsx("p",{className:"text-xs text-red-500",children:Y}):e.jsx("p",{className:"text-xs text-gray-500",children:g.length>0?`已从当前 API 地址读取到 ${g.length} 个模型`:"模型列表从当前 API 地址读取,也可以手动输入模型名"})]}),e.jsxs("div",{className:"p-3 bg-blue-50 rounded-xl text-xs text-blue-700",children:[e.jsx("strong",{children:"常见 AI 服务:"}),e.jsxs("ul",{className:"list-disc list-inside mt-1 space-y-0.5",children:[e.jsx("li",{children:"阿里云通义千问: https://dashscope.aliyuncs.com/compatible-mode/v1"}),e.jsx("li",{children:"OpenAI: https://api.openai.com/v1"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-amber-500 text-white",children:e.jsx(Vs,{className:"w-4 h-4"})}),"远程过滑块配置"]}),e.jsxs("div",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务地址"}),e.jsx("input",{type:"url",value:s["captcha.remote_service_url"]||"",onChange:p=>t({...s,"captcha.remote_service_url":p.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"https://example.com/internal/captcha/solve"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"服务秘钥"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:xe?"text":"password",value:s["captcha.remote_secret_key"]||"",onChange:p=>t({...s,"captcha.remote_secret_key":p.target.value}),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl font-mono text-sm",autoComplete:"off"}),e.jsx("button",{type:"button",onClick:()=>O(!xe),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:xe?"隐藏秘钥":"显示秘钥",children:xe?e.jsx(rs,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-xl bg-amber-50 p-4 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:String(s["captcha.remote_pass_cookies"]||"").toLowerCase()==="true",onChange:p=>t({...s,"captcha.remote_pass_cookies":p.target.checked}),className:"mt-0.5 w-4 h-4 rounded border-gray-300"}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-bold text-amber-900",children:"允许向远程服务传递账号 Cookie"}),e.jsx("span",{className:"block mt-1 text-xs text-amber-700",children:"默认关闭。仅在信任远程服务且需要由其自动重取过期验证链接时开启。"})]})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"配置地址和秘钥后优先调用远程服务;只有网络不可用或超时才回退本机引擎,远程明确返回失败时不会重复触发本机验证。"})]})]}),e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h3",{className:"text-lg font-extrabold text-gray-800 flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 rounded-lg bg-gray-900 text-white",children:e.jsx(xt,{className:"w-4 h-4"})}),"登录凭据"]}),e.jsxs("form",{onSubmit:K,className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"登录用户名"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ca,{className:"absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),e.jsx("input",{type:"text",value:A.new_username,onChange:p=>b({...A,new_username:p.target.value}),className:"w-full ios-input pl-11 pr-4 py-3 rounded-xl text-sm",autoComplete:"username"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"当前密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:le?"text":"password",value:A.current_password,onChange:p=>b({...A,current_password:p.target.value}),className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm",placeholder:"用于确认当前身份",autoComplete:"current-password"}),e.jsx("button",{type:"button",onClick:()=>D(!le),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:le?"隐藏密码":"显示密码",children:le?e.jsx(rs,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"新密码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:N?"text":"password",value:A.new_password,onChange:p=>b({...A,new_password:p.target.value}),className:"w-full ios-input px-4 py-3 pr-11 rounded-xl text-sm",placeholder:"不修改则留空",autoComplete:"new-password"}),e.jsx("button",{type:"button",onClick:()=>$(!N),className:"absolute right-2 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",title:N?"隐藏密码":"显示密码",children:N?e.jsx(rs,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"确认新密码"}),e.jsx("input",{type:N?"text":"password",value:A.confirm_password,onChange:p=>b({...A,confirm_password:p.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl text-sm",placeholder:"再次输入新密码",autoComplete:"new-password"})]})]}),ue&&e.jsxs("div",{className:`flex items-start gap-2 rounded-xl px-3 py-2.5 text-sm font-medium ${ue.type==="success"?"bg-green-50 text-green-700":"bg-red-50 text-red-700"}`,children:[e.jsx(Vs,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),e.jsx("span",{children:ue.text})]}),e.jsxs("button",{type:"submit",disabled:T||!A.new_username||!A.current_password,className:"w-full bg-gray-900 hover:bg-black text-white px-5 py-3 rounded-xl font-bold text-sm flex items-center justify-center gap-2 transition-colors disabled:opacity-40",children:[e.jsx(xt,{className:"w-4 h-4"}),T?"正在更新...":"更新登录凭据"]})]})]})]})]}),e.jsx("div",{className:"fixed bottom-10 right-10 z-30",children:e.jsxs("button",{onClick:R,disabled:L,className:"ios-btn-primary px-10 py-5 rounded-xl text-lg shadow-2xl shadow-blue-200 flex items-center gap-3 transform hover:scale-105 active:scale-95 transition-all disabled:opacity-70",children:[e.jsx(Ke,{className:"w-6 h-6"}),L?"保存中...":"保存所有配置"]})})]})},qs=(s,t)=>s.allowed_resolutions.includes(t),vr=(s,t)=>({runs:s.runs.filter(l=>!t||l.cookie_id===t),pending_tasks:s.pending_tasks.filter(l=>!t||l.cookie_id===t)}),_r=s=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[s]||"自动化异常",wr=async s=>{const t=s.loadIssues().then(s.onIssues).catch(s.onIssuesError),l=await s.loadRules();s.onRules(l),await t},kr=(s,t,l,c,h,f)=>s!==t||l!==c?!1:(f(h),!0),ls={order_paid:{label:"付款后自动发货",shortLabel:"自动发货",description:"闲鱼付款系统卡片进入自动化中心后,先发送卡密,成功后再确认发货。",flow:["付款系统卡片","匹配商品/规格","发送卡密","确认发货"],accent:"blue",icon:Ns},buyer_reviewed:{label:"评价后发送赠品",shortLabel:"评价赠品",description:"闲鱼评价系统卡片进入自动化中心后,给买家发送赠品卡密。",flow:["评价系统卡片","匹配商品/规格","发送赠品"],accent:"emerald",icon:Sa},review_missing_timeout:{label:"超时未评价求评价",shortLabel:"求评价",description:"计划任务扫描已发货未评价订单,到期后发送求评价文案。",flow:["计划任务扫描","已发货未评价","达到等待时间","发送提醒"],accent:"amber",icon:zt}},Bs=["order_paid","buyer_reviewed","review_missing_timeout"],Cr="亲,商品使用满意的话,麻烦给个评价,谢谢~",bs=()=>({spec_name:"",spec_value:"",card_id:0,delivery_count:1,enabled:!0,delay_override:!1,delay_seconds:0}),Ht=s=>{if(!s)return{};try{const t=JSON.parse(s);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}},as=(s,t={})=>{const l=Ht(s);return JSON.stringify({after_shipped_hours:Number(l.after_shipped_hours||72),repeat_interval_hours:Number(l.repeat_interval_hours||24),max_attempts:Number(l.max_attempts||1),...t})},fs=(s,t)=>{var c;const l=((c=ls[s])==null?void 0:c.label)||"自动化规则";return t?`${l} - ${t}`:l},St=s=>{const t=(s||"").trim();return t?Object.values(ls).some(l=>t===l.label||t.startsWith(`${l.label} -`)):!0},ys=(s,t=0)=>{if(s==="review_missing_timeout")return[{action_type:"send_text",message_template:Cr,enabled:!0,sort_order:1}];const l={action_type:"send_card",card_id:t,delivery_count:1,enabled:!0,sort_order:1};return s==="order_paid"?[l,{action_type:"confirm_shipment",enabled:!0,sort_order:2}]:[l]},Sr=s=>{var l,c;if(s.trigger_type==="review_missing_timeout")return((c=(l=s.actions)==null?void 0:l.find(h=>h.action_type==="send_text"))==null?void 0:c.message_template)||"发送求评价文案";const t=(s.actions||[]).filter(h=>h.action_type==="send_card");return t.length?t.map(h=>h.card_name||`卡密 ${h.card_id}`).join(" / "):"未配置卡密库存"},Lt=(s,t=!1)=>{const l={blue:t?"border-blue-500 bg-blue-50 text-blue-700":"border-blue-100 bg-blue-50/60 text-blue-700 hover:border-blue-300",emerald:t?"border-emerald-500 bg-emerald-50 text-emerald-700":"border-emerald-100 bg-emerald-50/60 text-emerald-700 hover:border-emerald-300",amber:t?"border-amber-500 bg-amber-50 text-amber-700":"border-amber-100 bg-amber-50/60 text-amber-700 hover:border-amber-300"};return l[s]||l.blue},Lr=s=>s?"bg-emerald-100 text-emerald-700":"bg-gray-200 text-gray-500",Ss=s=>(s==null?void 0:s.nickname)||(s==null?void 0:s.remark)||(s==null?void 0:s.id)||"未知账号",Ar=s=>s===!0||s===1||s==="1",Ir=({initialDeliveryTarget:s,onDeliveryTargetHandled:t})=>{var fe,ze,r;const[l,c]=n.useState("automation"),[h,f]=n.useState([]),[L,F]=n.useState({runs:[],pending_tasks:[]}),[g,I]=n.useState([]),[j,G]=n.useState({}),[Y,X]=n.useState([]),[de,C]=n.useState([]),[M,oe]=n.useState([]),[ee,xe]=n.useState(!1),[O,le]=n.useState(""),D=n.useRef(0),N=n.useRef("");N.current=O;const[$,T]=n.useState(!1),[J,ue]=n.useState(!1),[Q,A]=n.useState(!1),[b,v]=n.useState(null),[B,R]=n.useState(null),[K,H]=n.useState({cookie_id:"",enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""});Y.find(a=>a.id===O);const m=n.useCallback(async()=>{const[a,u,w,W]=await Promise.all([Rs(),Ve(),ps(),vt()]);X(a),C(u),oe(w),G(W),le(ae=>{var ve;return ae||((ve=a[0])==null?void 0:ve.id)||""})},[]),p=n.useCallback(async()=>{await wr({loadRules:Is,loadIssues:El,onRules:f,onIssues:F,onIssuesError:a=>console.warn("加载自动化异常列表失败,不阻断规则展示",a)})},[]),y=n.useCallback(async()=>{const a=O;if(a!==N.current)return;const u=++D.current;if(I([]),!a)return;const w=await ql(a);kr(u,D.current,a,N.current,w,I)},[O]),S=n.useCallback(async()=>{G(await vt())},[]),U=n.useCallback(async()=>{xe(!0);try{l==="automation"?await p():l==="reply"?await y():await S()}finally{xe(!1)}},[l,p,S,y]);n.useEffect(()=>{m().catch(a=>console.error("加载规则参考数据失败",a))},[m]),n.useEffect(()=>{U().catch(a=>console.error("刷新规则页面失败",a))},[U]);const se=n.useMemo(()=>h.filter(a=>!O||a.cookie_id===O),[h,O]),z=n.useMemo(()=>vr(L,O),[L,O]),re=n.useMemo(()=>Y.filter(a=>!O||a.id===O),[Y,O]),E=n.useMemo(()=>{var u;const a={order_paid:[],buyer_reviewed:[],review_missing_timeout:[]};for(const w of se)(u=a[w.trigger_type])==null||u.push(w);return a},[se]),i=n.useMemo(()=>{const a=(b==null?void 0:b.cookie_id)||O;return M.filter(u=>u.cookie_id===a)},[b==null?void 0:b.cookie_id,M,O]),q=n.useMemo(()=>{if(!(!(b!=null&&b.cookie_id)||!(b!=null&&b.item_id)))return M.find(a=>a.cookie_id===b.cookie_id&&a.item_id===b.item_id)},[b==null?void 0:b.cookie_id,b==null?void 0:b.item_id,M]),d=Ar(q==null?void 0:q.is_multi_spec),_=(b==null?void 0:b.trigger_type)||"order_paid",te=ls[_],Z=Ht(b==null?void 0:b.config_json),pe=n.useCallback((a="order_paid",u=O,w="")=>{const W=M.find(ve=>ve.cookie_id===u&&ve.item_id===w),ae=(W==null?void 0:W.item_title)||w;return{name:fs(a,ae),trigger_type:a,cookie_id:u,item_id:w,item_title:(W==null?void 0:W.item_title)||"",item_keyword:ae,card_group_id:0,priority:100,enabled:!0,config_json:a==="review_missing_timeout"?as():"{}",actions:ys(a),variants:a==="review_missing_timeout"?[]:[bs()]}},[M,O]),Ne=n.useCallback(a=>{var w,W;const u=a.trigger_type||"order_paid";v({...a,trigger_type:u,config_json:u==="review_missing_timeout"?as(a.config_json):a.config_json||"{}",actions:(w=a.actions)!=null&&w.length?a.actions.map(ae=>({...ae})):ys(u,a.card_group_id),variants:(W=a.variants)!=null&&W.length?a.variants.map(ae=>({...ae})):u==="review_missing_timeout"?[]:[bs()]}),T(!0)},[]);n.useEffect(()=>{if(!s)return;let a=!1;return(async()=>{c("automation"),le(s.cookieId),xe(!0);try{const[w,W,ae]=await Promise.all([Is(),ps(),Ve().catch(he=>(console.warn("加载卡密库存失败,不阻断打开自动化规则",he),[]))]);if(a)return;f(w),oe(W),C(ae);const ve=w.find(he=>he.cookie_id===s.cookieId&&he.item_id===s.itemId&&he.trigger_type==="order_paid");if(ve)Ne(ve);else{const he=W.find(De=>De.cookie_id===s.cookieId&&De.item_id===s.itemId);v({...pe("order_paid",s.cookieId,s.itemId),item_title:(he==null?void 0:he.item_title)||"",item_keyword:(he==null?void 0:he.item_title)||s.itemId,name:fs("order_paid",(he==null?void 0:he.item_title)||s.itemId)}),T(!0)}}catch(w){console.error("打开商品自动化规则失败",w),alert("无法加载该商品的自动化规则")}finally{a||(xe(!1),t==null||t())}})(),()=>{a=!0}},[pe,s,t,Ne]);const ce=(a="order_paid")=>{if(!O){alert("请先选择账号");return}v(pe(a)),T(!0)},_e=a=>{var W,ae,ve,he,De;if(!b)return;const u=((ae=(W=b.variants)==null?void 0:W.find(je=>je.card_id))==null?void 0:ae.card_id)||((he=(ve=b.actions)==null?void 0:ve.find(je=>je.action_type==="send_card"))==null?void 0:he.card_id)||b.card_group_id||0,w=(q==null?void 0:q.item_title)||b.item_title||b.item_id||"";v({...b,trigger_type:a,name:St(b.name)?fs(a,w):b.name,card_group_id:u,config_json:a==="review_missing_timeout"?as(b.config_json):"{}",actions:ys(a,u),variants:a==="review_missing_timeout"?[]:(De=b.variants)!=null&&De.length?b.variants:[{...bs(),card_id:u}]})},Re=a=>{if(!b)return;const u=M.find(W=>W.cookie_id===(b.cookie_id||O)&&W.item_id===a),w=(u==null?void 0:u.item_title)||a;v({...b,item_id:a,item_title:(u==null?void 0:u.item_title)||"",item_keyword:w,name:St(b.name)?fs(_,w):b.name})},ye=(fe=b==null?void 0:b.variants)!=null&&fe.length?b.variants:[bs()],Ae=(a,u)=>{var W;if(!b)return;const w=ye.map((ae,ve)=>ve===a?{...ae,...u}:ae);v({...b,variants:w,card_group_id:((W=w[0])==null?void 0:W.card_id)||0})},Le=()=>{if(!b)return;const a=ye[ye.length-1];v({...b,variants:[...ye,{...bs(),spec_name:d&&(a==null?void 0:a.spec_name)||"",spec_value:d&&(a==null?void 0:a.spec_value)||""}]})},Be=async()=>{var W,ae,ve,he,De;if(!b)return;const a=b.trigger_type||"order_paid";if(!b.cookie_id){alert("请选择账号");return}const u=(W=b.variants)!=null&&W.length?b.variants:[];if(a!=="review_missing_timeout"){if(!u.length||u.some(je=>!je.card_id)){alert(a==="buyer_reviewed"?"请选择评价赠品卡密库存":"请选择发货卡密库存");return}if(d&&u.some(je=>!je.spec_name.trim()||!je.spec_value.trim())){alert("多规格商品必须填写每一行的规格名称和规格值");return}}if(a==="review_missing_timeout"&&!(((ve=(ae=b.actions)==null?void 0:ae.find(o=>o.action_type==="send_text"))==null?void 0:ve.message_template)||"").trim()){alert("请填写求评价文案");return}const w=a==="review_missing_timeout"?[]:u.map(je=>({...je,spec_name:d?je.spec_name.trim():"",spec_value:d?je.spec_value.trim():"",delivery_count:Math.max(1,Number(je.delivery_count)||1),enabled:je.enabled!==!1}));try{await jt({...b,trigger_type:a,name:(b.name||"").trim()||fs(a,(q==null?void 0:q.item_title)||b.item_id||""),config_json:a==="review_missing_timeout"?as(b.config_json):b.config_json||"{}",actions:(he=b.actions)!=null&&he.length?b.actions:ys(a,((De=w[0])==null?void 0:De.card_id)||b.card_group_id||0),variants:w}),T(!1),await Promise.all([p(),m()]),alert("保存成功")}catch(je){console.error("保存自动化规则失败:",je),alert("保存失败:"+je.message)}},Ie=async a=>{if(confirm("确定删除该自动化规则吗?"))try{await Tl(a),await p(),alert("删除成功")}catch(u){alert("删除失败:"+u.message)}},Me=async a=>{try{await jt({...a,enabled:!a.enabled}),await p()}catch(u){alert("操作失败:"+u.message)}},We=async(a,u)=>{if(confirm(u==="continue"?"确认外部动作已经执行成功,并跳到下一步吗?":u==="retry"?"确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。":"确认终止该自动化运行吗?"))try{await Fl(a,u),await p()}catch(W){alert("处理失败:"+W.message)}},Ye=async(a,u)=>{if(confirm(u==="retry"?"确认重新执行该任务吗?":"确认忽略并删除该异常任务吗?"))try{await Dl(a,u),await p()}catch(w){alert("处理失败:"+w.message)}},$e=()=>{if(!O){alert("请先选择账号");return}R({keyword:"",reply_content:"",image_url:"",item_id:"",type:"text",match_type:"fuzzy",enabled:!0}),ue(!0)},ss=async()=>{var u,w,W;if(!B||!O)return;const a=B.type==="image"?!!((u=B.image_url)!=null&&u.trim()):!!((w=B.reply_content)!=null&&w.trim());if(!((W=B.keyword)!=null&&W.trim())||!a){alert("请填写关键词和回复内容");return}try{await Bl({...B,match_type:"fuzzy",enabled:!0},O),ue(!1),await y(),alert("保存成功")}catch(ae){alert("保存失败:"+ae.message)}},Ze=async a=>{if(!(!O||!confirm("确定删除该回复规则吗?")))try{await zl(a,O),await y(),alert("删除成功")}catch(u){alert("删除失败:"+u.message)}},Xe=async(a=O)=>{if(!a){alert("请先选择账号");return}try{const u=await Zl(a);H({cookie_id:a,enabled:u.enabled,reply_content:u.reply_content,reply_once:u.reply_once,reply_image_url:u.reply_image_url||""})}catch{H({cookie_id:a,enabled:!1,reply_content:"",reply_once:!1,reply_image_url:""})}A(!0)},He=async()=>{if(!K.cookie_id){alert("请先选择账号");return}if(K.enabled&&!K.reply_content.trim()&&!K.reply_image_url.trim()){alert("启用默认回复时,请填写回复内容或图片 URL");return}try{await Xl(K.cookie_id,{enabled:K.enabled,reply_content:K.reply_content,reply_once:K.reply_once,reply_image_url:K.reply_image_url}),A(!1),await S(),alert("保存成功")}catch(a){alert("保存失败:"+a.message)}},x=async a=>{if(confirm("确定删除该账号默认回复吗?"))try{await Hl(a),await S(),alert("删除成功")}catch(u){alert("删除失败:"+u.message)}},P=async a=>{if(confirm("确定清空该账号的默认回复记录吗?清空后可重新对所有会话使用“只回复一次”。"))try{await er(a),alert("清空成功")}catch(u){alert("清空失败:"+u.message)}},me=l==="automation"?"新建自动化":l==="reply"?"新增关键词":"编辑默认回复";return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"系统通知卡片只进入自动化判断;买家消息进入关键词、默认或 AI 回复。"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("select",{value:O,onChange:a=>le(a.target.value),className:"ios-input px-4 py-3 rounded-2xl text-sm min-w-64",children:[e.jsx("option",{value:"",children:"全部账号"}),Y.map(a=>e.jsx("option",{value:a.id,children:Ss(a)},a.id))]}),e.jsxs("button",{onClick:U,className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 hover:bg-gray-200 text-gray-700 flex items-center justify-center gap-2 transition-colors",children:[e.jsx(qe,{className:`w-4 h-4 ${ee?"animate-spin":""}`}),"刷新"]}),e.jsxs("button",{onClick:l==="automation"?()=>ce("order_paid"):l==="reply"?$e:()=>void Xe(),disabled:!O,className:"ios-btn-primary px-5 py-3 rounded-2xl text-sm font-extrabold flex items-center justify-center gap-2 disabled:opacity-50",children:[e.jsx(Qe,{className:"w-4 h-4"}),me]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[{id:"automation",label:"交易自动化",icon:Us},{id:"reply",label:"关键词回复",icon:Ls},{id:"default",label:"账号默认回复",icon:ds}].map(a=>{const u=a.icon;return e.jsxs("button",{onClick:()=>c(a.id),className:`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${l===a.id?"bg-[#0094f7] text-white shadow-md":"bg-white text-gray-600 hover:text-black hover:bg-gray-50"}`,children:[e.jsx(u,{className:"w-4 h-4"}),a.label]},a.id)})}),l==="automation"&&(z.runs.length>0||z.pending_tasks.length>0)&&e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ms,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[z.runs.map(a=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",a.cookie_id," · 订单 ",a.order_id||"-"," · 已记录发送 ",a.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:_r(a.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:a.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[qs(a,"continue")&&e.jsx("button",{onClick:()=>void We(a.id,"continue"),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),qs(a,"retry")&&e.jsx("button",{onClick:()=>void We(a.id,"retry"),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),qs(a,"cancel")&&e.jsx("button",{onClick:()=>void We(a.id,"cancel"),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${a.id}`)),z.pending_tasks.map(a=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",a.cookie_id," · 延迟任务重试已达 ",a.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:a.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:()=>void Ye(a.id,"retry"),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:()=>void Ye(a.id,"dismiss"),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${a.id}`))]})]}),l==="automation"&&e.jsxs("div",{className:"grid grid-cols-1 2xl:grid-cols-[360px_1fr] gap-6",children:[e.jsxs("aside",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsx("h3",{className:"font-black text-gray-900 mb-1",children:"新建规则"}),e.jsx("p",{className:"text-sm text-gray-500 mb-4",children:"先选自动化类型,再配置对应动作。"}),e.jsx("div",{className:"space-y-3",children:Bs.map(a=>{const u=ls[a],w=u.icon;return e.jsx("button",{type:"button",onClick:()=>ce(a),className:`w-full text-left rounded-2xl border p-4 transition-colors ${Lt(u.accent)}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/80 flex items-center justify-center shrink-0",children:e.jsx(w,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-extrabold",children:u.label}),e.jsx("div",{className:"text-xs opacity-75 mt-1 leading-5",children:u.description})]})]})},a)})})]}),e.jsxs("div",{className:"bg-white rounded-xl p-5 border border-gray-100 shadow-sm",children:[e.jsx("h3",{className:"font-black text-gray-900 mb-4",children:"规则概览"}),e.jsx("div",{className:"space-y-3",children:Bs.map(a=>{const u=ls[a],w=u.icon;return e.jsxs("div",{className:"flex items-center justify-between rounded-2xl bg-gray-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(w,{className:"w-4 h-4 text-gray-500"}),e.jsx("span",{className:"text-sm font-bold text-gray-700",children:u.shortLabel})]}),e.jsx("span",{className:"text-sm font-black text-gray-900",children:E[a].length})]},a)})})]})]}),e.jsx("section",{className:"space-y-4",children:se.length===0?e.jsxs("div",{className:"bg-white rounded-xl border border-dashed border-gray-200 p-16 text-center",children:[e.jsx(Us,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-xl font-black text-gray-900",children:"还没有自动化规则"}),e.jsx("p",{className:"text-gray-500 mt-2",children:"从左侧选择一个模板开始配置。"})]}):se.map(a=>{const u=ls[a.trigger_type],w=u.icon;return e.jsx("article",{className:"bg-white rounded-xl border border-gray-100 p-5 shadow-sm hover:shadow-lg transition-all",children:e.jsxs("div",{className:"flex flex-col lg:flex-row lg:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${Lt(u.accent,!0)}`,children:e.jsx(w,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("h3",{className:"text-lg font-black text-gray-900 truncate",children:a.name}),e.jsx("span",{className:`px-2.5 py-1 rounded-full text-xs font-bold ${Lr(a.enabled)}`,children:a.enabled?"已启用":"已禁用"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs font-bold",children:[e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:u.label}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-gray-100 text-gray-600",children:a.item_title||a.item_id||"账号级规则"}),e.jsx("span",{className:"px-2.5 py-1 rounded-lg bg-blue-50 text-blue-700",children:Sr(a)})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:()=>Ne(a),className:"px-4 py-2 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-bold flex items-center gap-2",children:[e.jsx(us,{className:"w-4 h-4"}),"编辑"]}),e.jsx("button",{onClick:()=>Me(a),className:`px-4 py-2 rounded-xl text-sm font-bold ${a.enabled?"bg-amber-50 text-amber-700 hover:bg-amber-100":"bg-emerald-50 text-emerald-700 hover:bg-emerald-100"}`,children:a.enabled?"禁用":"启用"}),e.jsx("button",{onClick:()=>Ie(a.id),className:"p-2.5 rounded-xl text-red-500 hover:bg-red-50",title:"删除",children:e.jsx(Je,{className:"w-4 h-4"})})]})]})},a.id)})})]}),l==="reply"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(ms,{className:"w-4 h-4"}),"这里只处理买家用户消息;系统通知不会进入关键词或 AI 回复。"]}),e.jsxs("div",{className:"space-y-3",children:[g.map(a=>e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border border-gray-100 bg-[#F7F8FA] hover:bg-white hover:shadow-lg transition-all gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("span",{className:"px-3 py-1 bg-black text-white rounded-lg text-xs font-bold",children:"包含匹配"}),e.jsxs("h3",{className:"font-bold text-gray-900",children:["“",a.keyword,"”"]})]}),e.jsx("div",{className:"bg-white p-3 rounded-xl border border-gray-100 text-sm text-gray-600 leading-relaxed",children:a.type==="image"&&a.image_url?a.image_url:a.reply_content})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:()=>{R({...a}),ue(!0)},className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(us,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>Ze(a.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Je,{className:"w-5 h-5"})})]})]},a.id)),g.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无关键词回复规则"})]})]}),l==="default"&&e.jsxs("section",{className:"bg-white rounded-xl border border-gray-100 p-6 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-blue-700 bg-blue-50 px-4 py-2 rounded-xl mb-5 w-fit",children:[e.jsx(ms,{className:"w-4 h-4"}),"默认回复只处理买家用户消息;关键词未命中且 AI 未接管时才会使用。"]}),e.jsxs("div",{className:"space-y-3",children:[re.map(a=>{const u=j[a.id],w=!!(u!=null&&u.enabled);return e.jsxs("div",{className:`flex flex-col md:flex-row md:items-center justify-between p-5 rounded-2xl border transition-all gap-4 ${w?"border-purple-100 bg-purple-50/50 hover:bg-white hover:shadow-lg":"border-gray-100 bg-[#F7F8FA] hover:bg-white hover:shadow-lg"}`,children:[e.jsxs("div",{className:"flex items-center gap-4 min-w-0",children:[e.jsx("div",{className:`w-12 h-12 rounded-2xl flex items-center justify-center ${w?"bg-purple-600 text-white":"bg-gray-200 text-gray-400"}`,children:e.jsx(ds,{className:"w-5 h-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h3",{className:"font-bold text-gray-900 text-lg truncate",children:Ss(a)}),e.jsx("span",{className:`px-2 py-0.5 rounded-lg text-xs font-bold ${w?"bg-green-100 text-green-700":"bg-gray-200 text-gray-500"}`,children:w?"已启用":"未启用"}),(u==null?void 0:u.reply_once)&&e.jsx("span",{className:"px-2 py-0.5 rounded-lg text-xs font-bold bg-purple-100 text-purple-700",children:"只回复一次"})]}),e.jsx("div",{className:"text-sm text-gray-600 line-clamp-2",children:w?u.reply_content||u.reply_image_url||"已配置默认回复":"未配置默认回复"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 border-t md:border-t-0 md:border-l border-gray-200 pt-4 md:pt-0 md:pl-6",children:[e.jsx("button",{onClick:()=>void Xe(a.id),className:"p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors",title:"编辑",children:e.jsx(us,{className:"w-4 h-4"})}),w&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>void P(a.id),className:"px-3 py-2 text-xs font-bold text-blue-600 hover:bg-blue-50 rounded-xl transition-colors",children:"清空记录"}),e.jsx("button",{onClick:()=>void x(a.id),className:"p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors",title:"删除",children:e.jsx(Je,{className:"w-5 h-5"})})]})]})]},a.id)}),re.length===0&&e.jsx("div",{className:"text-center py-20 text-gray-400",children:"暂无账号"})]})]}),$&&b&&Se.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"72rem",maxHeight:"92vh"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-black text-gray-900",children:b.id?"编辑自动化规则":"新建自动化规则"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:te.description})]}),e.jsx("button",{onClick:()=>T(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",title:"关闭",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] min-h-0",children:[e.jsxs("aside",{className:"bg-slate-900 text-white p-5 overflow-y-auto",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"选择自动化类型"}),e.jsx("div",{className:"space-y-3",children:Bs.map(a=>{const u=ls[a],w=u.icon,W=_===a;return e.jsx("button",{type:"button",onClick:()=>_e(a),className:`w-full rounded-2xl p-4 text-left border transition-all ${W?"bg-white text-slate-950 border-white":"bg-white/5 text-white border-white/10 hover:bg-white/10"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(w,{className:`w-5 h-5 mt-0.5 ${W?"text-[#0094f7]":"text-white"}`}),e.jsxs("div",{children:[e.jsx("div",{className:"font-black",children:u.label}),e.jsx("div",{className:`text-xs mt-1 leading-5 ${W?"text-gray-500":"text-gray-400"}`,children:u.description})]})]})},a)})}),e.jsxs("div",{className:"mt-6 rounded-2xl bg-white/5 border border-white/10 p-4",children:[e.jsx("div",{className:"text-xs font-bold text-slate-400 mb-3",children:"执行流程"}),e.jsx("div",{className:"space-y-3",children:te.flow.map((a,u)=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-white text-slate-950 text-xs font-black flex items-center justify-center",children:u+1}),e.jsx("span",{className:"text-sm font-bold text-gray-100",children:a})]},a))})]})]}),e.jsx("div",{className:"p-6 overflow-y-auto bg-[#F7F8FA]",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Bt,{className:"w-5 h-5 text-[#0094f7]"}),e.jsx("h4",{className:"font-black text-gray-900",children:"生效范围"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"规则名称"}),e.jsx("input",{type:"text",value:b.name||"",onChange:a=>v({...b,name:a.target.value}),placeholder:"不填时按类型和商品自动生成",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:b.cookie_id||"",onChange:a=>v({...b,cookie_id:a.target.value,item_id:"",item_title:"",item_keyword:""}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),Y.map(a=>e.jsx("option",{value:a.id,children:Ss(a)},a.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:b.item_id||"",onChange:a=>Re(a.target.value),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级规则(不限定商品)"}),i.map(a=>e.jsx("option",{value:a.item_id,children:a.item_title||a.item_id},`${a.cookie_id}-${a.item_id}`))]})]})]}),q&&_!=="review_missing_timeout"&&e.jsxs("div",{className:"mt-4 rounded-2xl bg-gray-50 border border-gray-100 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsx("span",{className:"px-3 py-1.5 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:q.item_title||q.item_id}),e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${d?"bg-blue-50 text-blue-700":"bg-gray-100 text-gray-500"}`,children:d?"多规格商品":"普通商品"}),e.jsx("span",{className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-emerald-50 text-emerald-700",children:"按订单购买数量自动发货"})]}),e.jsx("p",{className:"text-xs leading-5 text-gray-500",children:"多规格状态来自闲鱼商品本身,发布后不能在这里修改;系统会在买家付款后读取订单详情,按实际购买规格和数量匹配下面的发货规则。"})]})]}),_!=="review_missing_timeout"?e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(La,{className:"w-5 h-5 text-[#0094f7]"}),e.jsx("h4",{className:"font-black text-gray-900",children:_==="buyer_reviewed"?"赠品库存":"发货库存"})]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:d?"每条发货内容绑定一个订单规格;同一规格可添加多条内容并全部发送。":"可添加多条发货内容,买家付款后会按顺序全部发送。"})]}),e.jsxs("button",{type:"button",onClick:Le,className:"px-3 py-2 rounded-xl bg-gray-900 text-white text-xs font-bold hover:bg-black flex items-center gap-1.5",children:[e.jsx(Qe,{className:"w-3.5 h-3.5"}),"添加发货内容"]})]}),e.jsx("div",{className:"space-y-3",children:ye.map((a,u)=>e.jsxs("div",{className:`grid grid-cols-1 gap-3 items-end rounded-2xl border border-gray-200 p-4 ${d?"md:grid-cols-[1fr_1fr_1.4fr_110px_40px]":"md:grid-cols-[1.4fr_110px_40px]"}`,children:[d&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格名称"}),e.jsx("input",{value:a.spec_name,onChange:w=>Ae(u,{spec_name:w.target.value}),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:套餐"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"规格值"}),e.jsx("input",{value:a.spec_value,onChange:w=>Ae(u,{spec_value:w.target.value}),className:"w-full ios-input px-3 py-2.5 rounded-lg",placeholder:"例如:30天"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"卡密库存"}),e.jsxs("select",{value:a.card_id||"",onChange:w=>Ae(u,{card_id:Number(w.target.value)}),className:"w-full ios-input px-3 py-2.5 rounded-lg",children:[e.jsx("option",{value:"",children:"请选择卡密库存"}),de.filter(w=>w.enabled&&w.type!=="api").map(w=>e.jsx("option",{value:w.id,children:w.name},w.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-gray-600 mb-2",children:"每件份数"}),e.jsx("input",{type:"number",min:"1",max:"100",value:a.delivery_count,onChange:w=>Ae(u,{delivery_count:Math.max(1,Number(w.target.value)||1)}),className:"w-full ios-input px-3 py-2.5 rounded-lg"})]}),e.jsxs("div",{className:"md:col-span-full flex flex-wrap items-center gap-3 rounded-xl bg-gray-50 px-3 py-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold text-gray-600 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:a.delay_override===!0,onChange:w=>Ae(u,{delay_override:w.target.checked}),className:"accent-[#0094f7]"}),"覆盖卡密默认延时"]}),a.delay_override&&e.jsx("input",{type:"number",min:"0",max:"3600",value:a.delay_seconds||0,onChange:w=>Ae(u,{delay_seconds:Math.max(0,Number(w.target.value)||0)}),className:"w-28 ios-input px-2 py-1.5 rounded-lg text-xs","aria-label":"动作延时秒数"}),e.jsx("span",{className:"text-xs text-gray-500",children:a.delay_override?`本动作延时 ${a.delay_seconds||0} 秒`:"使用卡密默认延时"})]}),e.jsx("button",{type:"button",disabled:ye.length===1,onClick:()=>v({...b,variants:ye.filter((w,W)=>W!==u)}),className:"w-10 h-10 flex items-center justify-center rounded-lg text-red-500 hover:bg-red-50 disabled:opacity-25",title:"删除发货内容",children:e.jsx(Je,{className:"w-4 h-4"})})]},a.id||u))})]}):e.jsxs("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(zt,{className:"w-5 h-5 text-amber-600"}),e.jsx("h4",{className:"font-black text-gray-900",children:"求评价计划"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"发货后等待小时"}),e.jsx("input",{type:"number",min:"1",value:Number(Z.after_shipped_hours||72),onChange:a=>v({...b,config_json:as(b.config_json,{after_shipped_hours:Math.max(1,Number(a.target.value)||72)})}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"再次求评间隔小时"}),e.jsx("input",{type:"number",min:"1",value:Number(Z.repeat_interval_hours||24),onChange:a=>v({...b,config_json:as(b.config_json,{repeat_interval_hours:Math.max(1,Number(a.target.value)||24)})}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"最多求评次数"}),e.jsx("input",{type:"number",min:"1",value:Number(Z.max_attempts||1),onChange:a=>v({...b,config_json:as(b.config_json,{max_attempts:Math.max(1,Number(a.target.value)||1)})}),className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"md:col-span-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"求评价文案"}),e.jsx("textarea",{value:((r=(ze=b.actions)==null?void 0:ze.find(a=>a.action_type==="send_text"))==null?void 0:r.message_template)||"",onChange:a=>{var u;return v({...b,actions:((u=b.actions)!=null&&u.length?b.actions:ys("review_missing_timeout")).map(w=>w.action_type==="send_text"?{...w,message_template:a.target.value}:w)})},className:"w-full ios-input px-4 py-3 rounded-xl h-28 resize-none"})]})]})]}),e.jsx("section",{className:"bg-white rounded-3xl border border-gray-100 p-5",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-[180px_1fr] gap-4 items-end",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"优先级"}),e.jsx("p",{className:"text-xs text-gray-500 mb-2",children:"数字越小优先级越高;同一账号、商品和触发条件只执行优先级最高的一条规则。"}),e.jsx("input",{type:"number",value:b.priority||100,onChange:a=>v({...b,priority:Number(a.target.value)||100}),min:"1",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"h-[48px] flex items-center gap-3 px-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsx("input",{type:"checkbox",checked:b.enabled!==!1,onChange:a=>v({...b,enabled:a.target.checked}),className:"w-4 h-4 rounded"}),"启用规则"]})]})})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 bg-white flex gap-3",children:[e.jsx("button",{onClick:()=>T(!1),className:"flex-1 px-6 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200",children:"取消"}),e.jsxs("button",{onClick:Be,className:"flex-1 ios-btn-primary px-6 py-3 rounded-2xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ke,{className:"w-4 h-4"}),"保存自动化规则"]})]})]})}),document.body),J&&B&&Se.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:B.id?"编辑回复规则":"新增回复规则"}),e.jsx("button",{onClick:()=>ue(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关联商品"}),e.jsxs("select",{value:B.item_id||"",onChange:a=>R({...B,item_id:a.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"账号级回复"}),M.filter(a=>!O||a.cookie_id===O).map(a=>e.jsx("option",{value:a.item_id,children:a.item_title||a.item_id},`${a.cookie_id}-${a.item_id}`))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复类型"}),e.jsxs("select",{value:B.type||"text",onChange:a=>{const u=a.target.value;R({...B,type:u,reply_content:u==="text"?B.reply_content:"",image_url:u==="image"?B.image_url:""})},className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"text",children:"文字"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"关键词"}),e.jsx("input",{type:"text",value:B.keyword||"",onChange:a=>R({...B,keyword:a.target.value}),placeholder:"买家发送的关键词",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),B.type==="image"?e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{value:B.image_url||"",onChange:a=>R({...B,image_url:a.target.value}),placeholder:"https://...",className:"w-full ios-input px-4 py-3 rounded-xl"})]}):e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:B.reply_content||"",onChange:a=>R({...B,reply_content:a.target.value}),placeholder:"自动回复的内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:()=>ue(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:ss,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Zs,{className:"w-4 h-4"}),"保存规则"]})]})]})]})}),document.body),Q&&Se.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"账号默认回复"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"关键词和 AI 都未处理时,才会使用默认回复。"})]}),e.jsx("button",{onClick:()=>A(!1),className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",title:"关闭",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"闲鱼账号"}),e.jsxs("select",{value:K.cookie_id,onChange:a=>H({...K,cookie_id:a.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"选择账号"}),Y.map(a=>e.jsx("option",{value:a.id,children:Ss(a)},a.id))]})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-gray-900",children:"启用默认回复"}),e.jsx("div",{className:"text-xs text-gray-500 mt-1",children:"启用后,未命中关键词时自动发送"})]}),e.jsx("button",{type:"button",onClick:()=>H({...K,enabled:!K.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${K.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${K.enabled?"translate-x-7":"translate-x-1"}`})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复内容"}),e.jsx("textarea",{value:K.reply_content,onChange:a=>H({...K,reply_content:a.target.value}),placeholder:"输入默认回复内容",className:"w-full ios-input px-4 py-3 rounded-xl h-32 resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"回复图片 URL(可选)"}),e.jsx("input",{type:"text",value:K.reply_image_url,onChange:a=>H({...K,reply_image_url:a.target.value}),placeholder:"https://example.com/image.jpg",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("label",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl text-sm font-bold text-gray-800",children:[e.jsxs("span",{children:["只回复一次",e.jsx("span",{className:"block text-xs text-gray-500 font-medium mt-1",children:"同一会话只发送一次默认回复"})]}),e.jsx("input",{type:"checkbox",checked:K.reply_once,onChange:a=>H({...K,reply_once:a.target.checked}),className:"w-4 h-4 rounded"})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx("button",{onClick:()=>A(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:He,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Ke,{className:"w-4 h-4"}),"保存默认回复"]})]})]})]})}),document.body)]})},$r=s=>{const t=String(s.smtp_from||"").trim(),l=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t);return{...s,smtp_from_name:s.smtp_from_name||(l?"":t),smtp_from_address:s.smtp_from_address||(l?t:s.smtp_user||""),smtp_use_tls:At(s.smtp_use_tls,!0),smtp_use_ssl:At(s.smtp_use_ssl,!1)}},At=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},Hs=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],Ks=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},ea=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),l=Hs.some(c=>String(s[c]??"").trim()!=="");return{...s,use_custom_smtp:t?Ks(s.use_custom_smtp,!1):l}},It=(s,t)=>{const l={...s,use_custom_smtp:!0};for(const c of Hs)String(l[c]??"").trim()===""&&t[c]!==void 0&&(l[c]=t[c]);return l.smtp_port||(l.smtp_port=587),l.smtp_from_address||(l.smtp_from_address=l.smtp_user||""),l.smtp_use_tls=Ks(l.smtp_use_tls,!0),l.smtp_use_ssl=Ks(l.smtp_use_ssl,!1),l},Rr=s=>{const t=ea(s),l={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(l.use_custom_smtp)for(const c of Hs)l[c]=t[c];return l},cs={bark:{label:"Bark",icon:xs,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app//这是测试推送内容","URL 路径里 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:Ls,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:Ls,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:Ls,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:Aa,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:Zs,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的用户 ID",required:!0}],guide:{steps:["在 Telegram 搜索 @BotFather,发送 /newbot,按提示创建机器人,拿到 Bot Token","把你的 Bot 拉进一个群,或私聊它发一条消息","浏览器访问 https://api.telegram.org/bot<你的Token>/getUpdates",'从返回 JSON 里找 "chat":{"id":xxx},xxx 就是 Chat ID(群是负数,私聊是正数)'],urlFormat:"Bot Token: 123456:ABC-DEF... Chat ID: -1001234567890",note:"群聊需先把 Bot 设为管理员才能发消息。"}},email:{label:"邮件",icon:Ut,fields:[{key:"to_email",label:"收件邮箱",placeholder:"receiver@example.com",required:!0}],guide:{steps:["通常先保存页面中的系统 SMTP 配置","邮件渠道只需填写收件邮箱,即可完整继承系统 SMTP","只有确实需要另一套发件服务时,才开启“使用独立 SMTP”并填写整套配置"],note:"继承和独立 SMTP 是互斥模式,不会再混用两套配置中的部分字段。"}}},sa=[{value:"account_offline",label:"掉线通知",description:"账号过期、断线或登录态失效"},{value:"account_recovered",label:"恢复通知",description:"自动恢复成功并重新在线"},{value:"account_disabled",label:"禁用通知",description:"连续失败、账密错误等导致账号停用"},{value:"security_verification",label:"风控验证",description:"滑块、人脸、扫码验证等安全校验"},{value:"delivery_result",label:"交易通知",description:"订单发货、卡密发送等交易结果"},{value:"token_renewal",label:"续期通知",description:"Cookie/token 续期和自动恢复过程"},{value:"system_error",label:"系统错误",description:"后台任务或系统级异常"}],Pr=s=>!s||s.length===0?"全部事件":s.map(l=>{var c;return((c=sa.find(h=>h.value===l))==null?void 0:c.label)||l}).join("、"),Tr=({isAdmin:s=!1})=>{const[t,l]=n.useState([]),[c,h]=n.useState(!0),[f,L]=n.useState(!1),[F,g]=n.useState(null),[I,j]=n.useState(!1),[G,Y]=n.useState(""),[X,de]=n.useState(null),[C,M]=n.useState({}),[oe,ee]=n.useState(!1),[xe,O]=n.useState(!1),[le,D]=n.useState(!1),[N,$]=n.useState({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),T=async()=>{h(!0);try{const m=await Xt();l(m.data||[])}catch(m){console.error("加载通知渠道失败",m)}finally{h(!1)}},J=async()=>{try{const m=await Kt();M($r(m||{}))}catch(m){console.error("加载 SMTP 配置失败",m)}},ue=async()=>{ee(!0);try{await Yt({smtp_server:C.smtp_server||"",smtp_port:C.smtp_port||587,smtp_user:C.smtp_user||"",smtp_password:C.smtp_password||"",smtp_from_name:C.smtp_from_name||"",smtp_from_address:C.smtp_from_address||C.smtp_user||"",smtp_use_tls:C.smtp_use_tls!==!1,smtp_use_ssl:C.smtp_use_ssl===!0}),Q("success","SMTP 配置已保存")}catch(m){Q("error",(m==null?void 0:m.message)||"保存失败")}finally{ee(!1)}};n.useEffect(()=>{T(),s?J():M({})},[s]);const Q=(m,p)=>{de({type:m,text:p}),window.setTimeout(()=>de(null),3e3)},A=()=>{g(null),$({name:"",type:"bark",enabled:!0,config:{},event_types:[]}),D(!1),L(!0)},b=m=>{g(m);const p=m.type==="email"?ea({...m.config||{}}):null,y=p?p.use_custom_smtp===!0?It(p,C):p:{...m.config||{}};$({name:m.name,type:m.type,enabled:m.enabled,config:y,event_types:m.event_types||[]}),D(!1),L(!0)},v=async()=>{const m=cs[N.type];for(const y of m.fields)if(y.required&&!String(N.config[y.key]||"").trim()){Q("error",`请填写 ${y.label}`);return}if(!N.name.trim()){Q("error","请填写渠道名称");return}let p=N.config;if(N.type==="email"&&(p=Rr(N.config),p.use_custom_smtp)){const S=[["smtp_server","独立 SMTP 服务器"],["smtp_port","独立 SMTP 端口"],["smtp_user","独立 SMTP 登录邮箱"],["smtp_password","独立 SMTP 密码 / 授权码"],["smtp_from_address","独立 SMTP 发件地址"]].find(([U])=>!String(p[U]||"").trim());if(S){Q("error",`请填写 ${S[1]}`);return}}j(!0);try{const y={name:N.name.trim(),type:N.type,config:p,event_types:N.event_types,enabled:N.enabled};F?await Nt(F.id,y):await Jl(y),L(!1),await T(),Q("success",F?"已更新":"已创建")}catch(y){console.error("保存失败",y),Q("error",(y==null?void 0:y.message)||"保存失败")}finally{j(!1)}},B=async m=>{if(confirm(`确认删除渠道「${m.name}」吗?已绑定该渠道的账号会自动解绑。`))try{await Ql(m.id),await T(),Q("success","已删除")}catch(p){Q("error",(p==null?void 0:p.message)||"删除失败")}},R=async m=>{try{await Nt(m.id,{enabled:!m.enabled}),l(p=>p.map(y=>y.id===m.id?{...y,enabled:!y.enabled}:y))}catch(p){Q("error",(p==null?void 0:p.message)||"切换失败")}},K=async m=>{Y(m.id);try{await Yl(m.id),Q("success","测试通知已发送,请检查对应渠道")}catch(p){Q("error",(p==null?void 0:p.message)||"发送失败")}finally{Y("")}},H=cs[N.type];return e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"通知设置"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"配置通知渠道,账号异常时主动推送告警"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:T,className:"px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(qe,{className:"w-4 h-4"}),"刷新"]}),e.jsxs("button",{onClick:A,className:"ios-btn-primary px-5 py-2.5 rounded-xl font-bold flex items-center gap-2",children:[e.jsx(Qe,{className:"w-4 h-4"}),"新建渠道"]})]})]}),e.jsx("div",{className:"ios-card rounded-xl p-5 bg-blue-50/50 border border-blue-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(xs,{className:"w-5 h-5 text-[#0094f7] mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"text-sm text-gray-700 leading-6",children:["配置通知渠道并在「账号管理 → 编辑」里绑定后,以下事件会主动推送到该账号绑定的渠道:",e.jsxs("ul",{className:"mt-2 space-y-1 text-gray-600",children:[e.jsxs("li",{children:["• ",e.jsx("strong",{children:"账号 session 失效"}),":系统正在尝试自动恢复(警告)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"自动恢复失败"}),":账号已停止,需人工处理(严重)"]}),e.jsxs("li",{children:["• ",e.jsx("strong",{children:"触发风控验证"}),":可能需要扫码完成验证(警告)"]})]})]})]})}),c?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(Te,{className:"w-8 h-8 text-[#0094f7] animate-spin"})}):t.length===0?e.jsxs("div",{className:"ios-card rounded-xl p-12 bg-white text-center",children:[e.jsx(xs,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"还没有配置任何通知渠道"}),e.jsx("p",{className:"text-gray-400 text-sm mt-1",children:"点击右上角「新建渠道」开始配置"})]}):e.jsx("div",{className:"space-y-3",children:t.map(m=>{const p=cs[m.type]||cs.webhook,y=p.icon;return e.jsxs("div",{className:"ios-card rounded-xl p-5 bg-white flex items-center gap-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-gray-100 flex items-center justify-center flex-shrink-0",children:e.jsx(y,{className:"w-5 h-5 text-gray-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-bold text-gray-900 truncate",children:m.name}),e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-600 font-medium",children:p.label}),!m.enabled&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-400 font-medium",children:"已停用"})]}),e.jsx("div",{className:"text-xs text-gray-500 mt-1 truncate",children:p.fields.map(S=>{var U;return(U=m.config)==null?void 0:U[S.key]}).filter(Boolean).map((S,U)=>e.jsx("span",{className:"mr-3",children:String(S).length>40?String(S).slice(0,40)+"…":String(S)},U))}),e.jsxs("div",{className:"text-xs text-gray-400 mt-1 truncate",children:["订阅:",Pr(m.event_types)]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:()=>R(m),className:`px-3 py-1.5 rounded-lg text-xs font-bold transition-colors ${m.enabled?"bg-green-50 text-green-700 hover:bg-green-100":"bg-gray-100 text-gray-500 hover:bg-gray-200"}`,children:m.enabled?"启用中":"已停用"}),e.jsxs("button",{onClick:()=>K(m),disabled:G===m.id,className:"px-3 py-1.5 rounded-lg text-xs font-bold bg-blue-50 text-[#0094f7] hover:bg-blue-100 transition-colors flex items-center gap-1 disabled:opacity-50",children:[G===m.id?e.jsx(Te,{className:"w-3 h-3 animate-spin"}):e.jsx(Zs,{className:"w-3 h-3"}),"测试"]}),e.jsx("button",{onClick:()=>b(m),className:"w-8 h-8 rounded-lg bg-gray-100 hover:bg-gray-200 flex items-center justify-center text-gray-600 transition-colors",title:"编辑",children:e.jsx(Ot,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>B(m),className:"w-8 h-8 rounded-lg bg-red-50 hover:bg-red-100 flex items-center justify-center text-red-500 transition-colors",title:"删除",children:e.jsx(Je,{className:"w-4 h-4"})})]})]},m.id)})}),s&&e.jsxs("section",{className:"ios-card rounded-xl p-6 bg-white space-y-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-extrabold text-gray-800",children:"SMTP 邮件配置"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"系统级邮件发送服务,供邮件通知渠道复用"})]}),e.jsx("div",{className:"p-2 rounded-xl bg-blue-50 text-blue-600",children:e.jsx(Ut,{className:"w-5 h-5"})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 服务器"}),e.jsx("input",{type:"text",value:C.smtp_server||"",onChange:m=>M({...C,smtp_server:m.target.value}),placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"SMTP 端口"}),e.jsx("input",{type:"number",value:C.smtp_port||587,onChange:m=>M({...C,smtp_port:parseInt(m.target.value)||587}),placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱"}),e.jsx("input",{type:"email",value:C.smtp_user||"",onChange:m=>M({...C,smtp_user:m.target.value}),placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"邮箱密码 / 授权码"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:xe?"text":"password",value:C.smtp_password||"",onChange:m=>M({...C,smtp_password:m.target.value}),placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:()=>O(!xe),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors",children:xe?e.jsx(rs,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-xs text-gray-500",children:"QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件人显示名(可选)"}),e.jsx("input",{type:"text",value:C.smtp_from_name||"",onChange:m=>M({...C,smtp_from_name:m.target.value}),placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件邮箱地址"}),e.jsx("input",{type:"email",value:C.smtp_from_address||C.smtp_user||"",onChange:m=>M({...C,smtp_from_address:m.target.value}),placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:C.smtp_use_tls!==!1,onChange:m=>M({...C,smtp_use_tls:m.target.checked,smtp_use_ssl:m.target.checked?!1:C.smtp_use_ssl})}),"STARTTLS(常用于 587 端口)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:C.smtp_use_ssl===!0,onChange:m=>M({...C,smtp_use_ssl:m.target.checked,smtp_use_tls:m.target.checked?!1:C.smtp_use_tls})}),"SSL/TLS 直连(常用于 465 端口)"]})]}),e.jsxs("button",{onClick:ue,disabled:oe,className:"ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[oe?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(Ke,{className:"w-4 h-4"}),oe?"保存中...":"保存 SMTP 配置"]})]}),f&&Se.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"36rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:F?"编辑通知渠道":"新建通知渠道"}),e.jsx("button",{onClick:()=>L(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(we,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5 overflow-y-auto flex-1 min-h-0",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道名称"}),e.jsx("input",{type:"text",value:N.name,onChange:m=>$({...N,name:m.target.value}),placeholder:"例如:我的 Bark",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"渠道类型"}),e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2",children:Object.keys(cs).map(m=>{const p=cs[m],y=p.icon,S=N.type===m;return e.jsxs("button",{type:"button",onClick:()=>$({...N,type:m,config:{}}),className:`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${S?"border-[#0094f7] bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsx(y,{className:`w-5 h-5 ${S?"text-[#0094f7]":"text-gray-500"}`}),e.jsx("span",{className:`text-xs font-bold ${S?"text-[#0094f7]":"text-gray-600"}`,children:p.label})]},m)})})]}),e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xs,{className:"w-4 h-4 text-amber-600"}),e.jsxs("span",{className:"text-sm font-bold text-amber-800",children:["如何获取 ",H.label," 配置?"]})]}),e.jsx("ol",{className:"space-y-1.5 text-xs text-amber-900/90 leading-5 list-decimal pl-5",children:H.guide.steps.map((m,p)=>e.jsx("li",{children:m},p))}),H.guide.urlFormat&&e.jsxs("div",{className:"text-xs text-amber-900/90",children:[e.jsx("span",{className:"font-bold",children:"格式示例:"}),e.jsx("code",{className:"mt-1 block bg-amber-100/70 px-2.5 py-1.5 rounded-lg break-all font-mono text-[11px]",children:H.guide.urlFormat})]}),H.guide.note&&e.jsxs("p",{className:"text-xs text-amber-800/80 leading-5 pt-1",children:["💡 ",H.guide.note]})]}),e.jsx("div",{className:"space-y-3",children:H.fields.map(m=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:[m.label,m.required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),e.jsx("input",{type:m.type==="password"?"password":m.type==="number"?"number":"text",value:String(N.config[m.key]||""),onChange:p=>$({...N,config:{...N.config,[m.key]:p.target.value}}),placeholder:m.placeholder,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),m.help&&e.jsx("p",{className:"text-xs text-gray-500",children:m.help})]},m.key))}),N.type==="email"&&e.jsxs("div",{className:"overflow-hidden rounded-2xl border border-blue-100 bg-blue-50/40",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-extrabold text-gray-900",children:"SMTP 来源"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-gray-500",children:N.config.use_custom_smtp===!0?"当前渠道使用一套完整、独立的发件配置。":"当前渠道完整继承系统 SMTP,只单独设置收件邮箱。"})]}),e.jsx("button",{type:"button",onClick:()=>{const m=N.config.use_custom_smtp===!0;$({...N,config:m?{...N.config,use_custom_smtp:!1}:It(N.config,C)})},className:`relative h-7 w-12 shrink-0 rounded-full transition-colors ${N.config.use_custom_smtp===!0?"bg-[#0094f7]":"bg-gray-300"}`,"aria-label":"使用独立 SMTP",children:e.jsx("span",{className:`absolute left-1 top-1 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${N.config.use_custom_smtp===!0?"translate-x-5":""}`})})]}),N.config.use_custom_smtp===!0&&e.jsxs("div",{className:"space-y-4 border-t border-blue-100 bg-white/80 p-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["SMTP 服务器 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:String(N.config.smtp_server||""),onChange:m=>$({...N,config:{...N.config,smtp_server:m.target.value}}),placeholder:"smtp.qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["SMTP 端口 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"number",value:String(N.config.smtp_port||587),onChange:m=>$({...N,config:{...N.config,smtp_port:m.target.value}}),placeholder:"587",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["登录邮箱 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"email",value:String(N.config.smtp_user||""),onChange:m=>$({...N,config:{...N.config,smtp_user:m.target.value}}),placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["密码 / 授权码 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:le?"text":"password",value:String(N.config.smtp_password||""),onChange:m=>$({...N,config:{...N.config,smtp_password:m.target.value}}),placeholder:"输入密码或授权码",className:"w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm"}),e.jsx("button",{type:"button",onClick:()=>D(m=>!m),className:"absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600",children:le?e.jsx(rs,{className:"w-4 h-4"}):e.jsx(es,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"发件人显示名(可选)"}),e.jsx("input",{type:"text",value:String(N.config.smtp_from_name||""),onChange:m=>$({...N,config:{...N.config,smtp_from_name:m.target.value}}),placeholder:"闲鱼自动回复系统",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-800",children:["发件邮箱地址 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"email",value:String(N.config.smtp_from_address||""),onChange:m=>$({...N,config:{...N.config,smtp_from_address:m.target.value}}),placeholder:"your-email@qq.com",className:"w-full ios-input px-4 py-3 rounded-xl text-sm"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:N.config.smtp_use_tls!==!1,onChange:m=>$({...N,config:{...N.config,smtp_use_tls:m.target.checked,smtp_use_ssl:m.target.checked?!1:N.config.smtp_use_ssl}})}),"STARTTLS(常用于 587)"]}),e.jsxs("label",{className:"flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:N.config.smtp_use_ssl===!0,onChange:m=>$({...N,config:{...N.config,smtp_use_ssl:m.target.checked,smtp_use_tls:m.target.checked?!1:N.config.smtp_use_tls}})}),"SSL/TLS 直连(常用于 465)"]})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"通知内容"}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"不选择表示接收全部通知;选择后仅接收勾选类型。"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:sa.map(m=>{const p=N.event_types.includes(m.value);return e.jsxs("button",{type:"button",onClick:()=>{const y=p?N.event_types.filter(S=>S!==m.value):[...N.event_types,m.value];$({...N,event_types:y})},className:`text-left rounded-xl border px-3 py-2.5 transition-colors ${p?"border-[#0094f7] bg-blue-50":"border-gray-100 hover:border-gray-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-4 h-4 rounded border flex items-center justify-center ${p?"bg-[#0094f7] border-[#0094f7]":"border-gray-300"}`,children:p&&e.jsx(Ge,{className:"w-3 h-3 text-white"})}),e.jsx("span",{className:`text-sm font-bold ${p?"text-[#0094f7]":"text-gray-800"}`,children:m.label})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1 pl-6 leading-5",children:m.description})]},m.value)})})]}),e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("button",{type:"button",onClick:()=>$({...N,enabled:!N.enabled}),className:`relative w-11 h-6 rounded-full transition-colors ${N.enabled?"bg-[#0094f7]":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform ${N.enabled?"translate-x-5":""}`})}),e.jsx("span",{className:"text-sm font-bold text-gray-800",children:"启用此渠道"})]})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>L(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"取消"}),e.jsxs("button",{onClick:v,disabled:I,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[I?e.jsx(Te,{className:"w-4 h-4 animate-spin"}):e.jsx(Ge,{className:"w-4 h-4"}),I?"保存中...":"保存"]})]})]})}),document.body),X&&e.jsxs("div",{className:"fixed bottom-8 left-1/2 -translate-x-1/2 z-[10000] px-5 py-3 rounded-xl shadow-lg font-bold text-sm flex items-center gap-2 animate-fade-in",style:{background:X.type==="success"?"#10b981":"#ef4444",color:"white"},children:[X.type==="success"?e.jsx(Ge,{className:"w-4 h-4"}):e.jsx(we,{className:"w-4 h-4"}),X.text]})]})},ta={"/app/dashboard":"dashboard","/app/accounts":"accounts","/app/orders":"orders","/app/cards":"cards","/app/items":"items","/app/rules":"rules","/app/notifications":"notifications","/app/settings":"settings"},$t=Object.fromEntries(Object.entries(ta).map(([s,t])=>[t,s])),Rt=()=>ta[window.location.pathname]||"dashboard",Er=/Win/i.test(navigator.platform||navigator.userAgent),Fr=()=>{const[s,t]=n.useState(!1),[l,c]=n.useState(!1),[h,f]=n.useState(Rt),[L,F]=n.useState(!0),[g,I]=n.useState(!1),[j,G]=n.useState(""),[Y,X]=n.useState(""),[de,C]=n.useState(!1),[M,oe]=n.useState(""),[ee,xe]=n.useState(),O=$=>{const T=$==="settings"&&!l?"dashboard":$,J=$t[T];J&&J!==window.location.pathname&&window.history.pushState({},"",J),f(T)};n.useEffect(()=>{const $=()=>f(Rt());return window.addEventListener("popstate",$),()=>window.removeEventListener("popstate",$)},[]),n.useEffect(()=>{Gt().then(T=>{if((T==null?void 0:T.initialized)===!1){I(!0),t(!1),c(!1);return}I(!1),T!=null&&T.authenticated?(t(!0),c(T.is_admin===!0)):c(!1)}).catch(()=>{t(!1),c(!1)}).finally(()=>F(!1));const $=()=>{t(!1),c(!1)};return window.addEventListener("auth:logout",$),()=>window.removeEventListener("auth:logout",$)},[]),n.useEffect(()=>{!L&&s&&!l&&h==="settings"&&(window.history.replaceState({},"",$t.dashboard),f("dashboard"))},[L,s,l,h]);const le=async $=>{$.preventDefault(),C(!0),oe("");try{const T=await Wa({username:j,password:Y});T.success?(t(!0),c(T.is_admin===!0)):oe(T.message||"登录失败")}catch(T){const J=T instanceof Error?T.message:String(T);oe(J||"登录失败")}finally{C(!1)}},D=async()=>{try{await Va()}catch($){console.error("退出登录失败",$)}finally{t(!1),c(!1)}};if(L)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#f5f5f7]",children:e.jsx(Te,{className:"w-8 h-8 text-[#0094f7] animate-spin"})});if(g)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-[#F4F5F7] p-4 relative overflow-hidden font-sans",children:[e.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),e.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-xl border border-white relative z-10 animate-fade-in",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"mx-auto mb-6 flex justify-center",children:e.jsx(Gs,{sizeClass:"w-24 h-24"})}),e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"系统尚未初始化"}),e.jsx("p",{className:"text-gray-600 font-medium",children:"为避免默认口令风险,管理员必须通过服务器本机 CLI 初始化。"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"p-4 rounded-2xl bg-gray-50 border border-gray-100",children:[e.jsx("div",{className:"text-sm font-bold text-gray-900 mb-2",children:"请在服务器上执行:"}),e.jsx("pre",{className:"text-xs bg-black text-white p-4 rounded-2xl overflow-x-auto",children:Er?'.\\xianyu-server.exe -init-admin -db data\\xianyu_data.db -admin-password "请设置密码"':"./xianyu-server -init-admin -db data/xianyu_data.db -admin-password '请设置密码'"}),e.jsx("div",{className:"text-xs text-gray-500 mt-2",children:"完成后刷新页面即可进入登录。"})]}),e.jsxs("button",{type:"button",onClick:()=>window.location.reload(),className:"w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group",children:["我已初始化,刷新 ",e.jsx(Ws,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})]}),e.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100 text-center",children:e.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Secure Bootstrap"})})]})]});if(!s)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-[#F4F5F7] p-4 relative overflow-hidden font-sans",children:[e.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[60%] h-[60%] bg-blue-200/40 rounded-full blur-[120px] animate-pulse"}),e.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-blue-200/30 rounded-full blur-[120px] animate-pulse",style:{animationDelay:"2s"}}),e.jsxs("div",{className:"bg-white/80 backdrop-blur-3xl p-8 md:p-12 rounded-xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.05)] w-full max-w-lg border border-white relative z-10 animate-fade-in",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("div",{className:"group mx-auto mb-6 flex cursor-pointer justify-center",children:e.jsx(Gs,{sizeClass:"w-24 h-24",logoClassName:"w-full h-full text-white group-hover:scale-110 transition-transform"})}),e.jsx("h2",{className:"text-3xl font-extrabold text-gray-900 mb-2 tracking-tight",children:"欢迎回来"}),e.jsx("p",{className:"text-gray-500 font-medium",children:"Ydisks闲鱼助手 · 自动发货与管家系统"})]}),e.jsxs("form",{onSubmit:le,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative group",children:[e.jsx(ns,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),e.jsx("input",{type:"text",placeholder:"管理员账号",value:j,onChange:$=>G($.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(Ia,{className:"absolute left-5 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400 group-focus-within:text-black transition-colors"}),e.jsx("input",{type:"password",placeholder:"密码",value:Y,onChange:$=>X($.target.value),className:"w-full ios-input pl-14 pr-6 py-4.5 rounded-2xl text-base h-14"})]})]}),M&&e.jsxs("div",{className:"p-3 rounded-xl bg-red-50 text-red-500 text-sm text-center font-bold flex items-center justify-center gap-2",children:[e.jsx(Vs,{className:"w-4 h-4"})," ",M]}),e.jsx("button",{type:"submit",disabled:de,className:"w-full ios-btn-primary h-14 rounded-2xl text-lg shadow-xl shadow-blue-200 mt-2 flex items-center justify-center gap-2 group disabled:opacity-70",children:de?e.jsx(Te,{className:"w-5 h-5 animate-spin"}):e.jsxs(e.Fragment,{children:["立即登录 ",e.jsx(Ws,{className:"w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]}),e.jsx("div",{className:"mt-8 pt-6 border-t border-gray-100",children:e.jsx("div",{className:"mt-6 text-center",children:e.jsx("span",{className:"text-xs text-gray-400 font-medium tracking-widest uppercase",children:"Ydisks闲鱼助手 v1.0"})})})]})]});const N=()=>{switch(h){case"dashboard":return e.jsx(Os,{});case"accounts":return e.jsx(dr,{});case"orders":return e.jsx(ur,{});case"cards":return e.jsx(hr,{});case"items":return e.jsx(fr,{onConfigureDelivery:$=>{xe({cookieId:$.cookie_id,itemId:$.item_id,requestId:Date.now()}),O("rules")}});case"rules":return e.jsx(Ir,{initialDeliveryTarget:ee,onDeliveryTargetHandled:()=>xe(void 0)});case"notifications":return e.jsx(Tr,{isAdmin:l});case"settings":return l?e.jsx(Nr,{}):e.jsx(Os,{});default:return e.jsx(Os,{})}};return e.jsxs("div",{className:"flex min-h-screen bg-[#F4F5F7] text-[#111]",children:[e.jsx(Ma,{activeTab:h,isAdmin:l,onNavigate:O,onLogout:D}),e.jsxs("main",{className:"flex-1 ml-64 p-8 md:p-12 overflow-y-auto h-screen relative scroll-smooth",children:[e.jsx("div",{className:"fixed top-0 right-0 w-[800px] h-[800px] bg-gradient-to-bl from-blue-50 to-transparent rounded-full blur-[120px] pointer-events-none -z-10 opacity-60"}),e.jsx("div",{className:"max-w-[1400px] mx-auto pb-10",children:N()})]})]})},aa=document.getElementById("root");if(!aa)throw new Error("Could not find root element to mount to");const Dr=ra.createRoot(aa);Dr.render(e.jsx(na.StrictMode,{children:e.jsx(Fr,{})}));
diff --git a/internal/webui/static/assets/index-hVsGsb1z.css b/internal/webui/static/assets/index-hVsGsb1z.css
new file mode 100644
index 0000000..7d5a49b
--- /dev/null
+++ b/internal/webui/static/assets/index-hVsGsb1z.css
@@ -0,0 +1 @@
+*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.-inset-1{top:-.25rem;right:-.25rem;bottom:-.25rem;left:-.25rem}.inset-0{top:0;right:0;bottom:0;left:0}.-bottom-1{bottom:-.25rem}.-right-1{right:-.25rem}.-right-6{right:-1.5rem}.-top-6{top:-1.5rem}.bottom-10{bottom:2.5rem}.bottom-8{bottom:2rem}.bottom-\[-10\%\]{bottom:-10%}.left-0{left:0}.left-0\.5{left:.125rem}.left-1{left:.25rem}.left-1\.5{left:.375rem}.left-1\/2{left:50%}.left-4{left:1rem}.left-5{left:1.25rem}.left-\[-10\%\]{left:-10%}.right-0{right:0}.right-10{right:2.5rem}.right-2{right:.5rem}.right-3{right:.75rem}.right-4{right:1rem}.right-\[-10\%\]{right:-10%}.top-0{top:0}.top-0\.5{top:.125rem}.top-1{top:.25rem}.top-1\.5{top:.375rem}.top-1\/2{top:50%}.top-2{top:.5rem}.top-4{top:1rem}.top-\[-10\%\]{top:-10%}.top-\[calc\(100\%\+6px\)\]{top:calc(100% + 6px)}.-z-10{z-index:-10}.z-10{z-index:10}.z-20{z-index:20}.z-30{z-index:30}.z-40{z-index:40}.z-\[10000\]{z-index:10000}.col-span-2{grid-column:span 2 / span 2}.col-span-full{grid-column:1 / -1}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-1\.5{margin-bottom:.375rem}.mb-10{margin-bottom:2.5rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-2\.5{margin-bottom:.625rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.ml-64{margin-left:16rem}.mr-2{margin-right:.5rem}.mr-3{margin-right:.75rem}.mt-0\.5{margin-top:.125rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.mt-auto{margin-top:auto}.line-clamp-1{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.line-clamp-2{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2}.line-clamp-3{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:3}.block{display:block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.contents{display:contents}.hidden{display:none}.aspect-square{aspect-ratio:1 / 1}.h-10{height:2.5rem}.h-11{height:2.75rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-2\.5{height:.625rem}.h-20{height:5rem}.h-24{height:6rem}.h-28{height:7rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-32{height:8rem}.h-4{height:1rem}.h-40{height:10rem}.h-48{height:12rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-80{height:20rem}.h-9{height:2.25rem}.h-\[280px\]{height:280px}.h-\[300px\]{height:300px}.h-\[350px\]{height:350px}.h-\[48px\]{height:48px}.h-\[60\%\]{height:60%}.h-\[800px\]{height:800px}.h-auto{height:auto}.h-full{height:100%}.h-screen{height:100vh}.max-h-44{max-height:11rem}.max-h-48{max-height:12rem}.max-h-64{max-height:16rem}.max-h-\[380px\]{max-height:380px}.max-h-\[400px\]{max-height:400px}.max-h-\[420px\]{max-height:420px}.max-h-\[min\(64vh\,28rem\)\]{max-height:min(64vh,28rem)}.min-h-0{min-height:0px}.min-h-36{min-height:9rem}.min-h-64{min-height:16rem}.min-h-\[120px\]{min-height:120px}.min-h-\[150px\]{min-height:150px}.min-h-\[400px\]{min-height:400px}.min-h-screen{min-height:100vh}.w-10{width:2.5rem}.w-11{width:2.75rem}.w-12{width:3rem}.w-14{width:3.5rem}.w-16{width:4rem}.w-2\.5{width:.625rem}.w-20{width:5rem}.w-24{width:6rem}.w-28{width:7rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-32{width:8rem}.w-4{width:1rem}.w-48{width:12rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-64{width:16rem}.w-7{width:1.75rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-\[19\%\]{width:19%}.w-\[23\%\]{width:23%}.w-\[27\%\]{width:27%}.w-\[60\%\]{width:60%}.w-\[7\%\]{width:7%}.w-\[8\%\]{width:8%}.w-\[800px\]{width:800px}.w-\[9\%\]{width:9%}.w-fit{width:-moz-fit-content;width:fit-content}.w-full{width:100%}.min-w-0{min-width:0px}.min-w-64{min-width:16rem}.min-w-\[200px\]{min-width:200px}.min-w-\[210px\]{min-width:210px}.min-w-\[260px\]{min-width:260px}.max-w-64{max-width:16rem}.max-w-6xl{max-width:72rem}.max-w-72{max-width:18rem}.max-w-\[12rem\]{max-width:12rem}.max-w-\[1400px\]{max-width:1400px}.max-w-\[15rem\]{max-width:15rem}.max-w-\[240px\]{max-width:240px}.max-w-\[260px\]{max-width:260px}.max-w-\[280px\]{max-width:280px}.max-w-\[340px\]{max-width:340px}.max-w-\[80px\]{max-width:80px}.max-w-full{max-width:100%}.max-w-lg{max-width:32rem}.max-w-md{max-width:28rem}.max-w-xl{max-width:36rem}.flex-1{flex:1 1 0%}.flex-shrink-0,.shrink-0{flex-shrink:0}.table-fixed{table-layout:fixed}.border-collapse{border-collapse:collapse}.-translate-x-1\/2{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-1{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-5{--tw-translate-x: 1.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-6{--tw-translate-x: 1.5rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-x-7{--tw-translate-x: 1.75rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.scale-\[1\.02\]{--tw-scale-x: 1.02;--tw-scale-y: 1.02;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}@keyframes spin{to{transform:rotate(360deg)}}.cursor-pointer{cursor:pointer}.resize-none{resize:none}.resize-y{resize:vertical}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-0\.5{gap:.125rem}.gap-1{gap:.25rem}.gap-1\.5{gap:.375rem}.gap-2{gap:.5rem}.gap-2\.5{gap:.625rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-5{gap:1.25rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.25rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(2rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-gray-100>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(243 244 246 / var(--tw-divide-opacity, 1))}.divide-gray-50>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(249 250 251 / var(--tw-divide-opacity, 1))}.self-start{align-self:flex-start}.self-end{align-self:flex-end}.self-center{align-self:center}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.overscroll-contain{overscroll-behavior:contain}.scroll-smooth{scroll-behavior:smooth}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-nowrap{white-space:nowrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:6px}.rounded-2xl,.rounded-3xl{border-radius:10px}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:7px}.rounded-md{border-radius:6px}.rounded-xl{border-radius:8px}.border{border-width:1px}.border-0{border-width:0px}.border-2{border-width:2px}.border-4{border-width:4px}.border-b{border-bottom-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-none{border-style:none}.border-\[\#0094f7\]{--tw-border-opacity: 1;border-color:rgb(0 148 247 / var(--tw-border-opacity, 1))}.border-amber-100{--tw-border-opacity: 1;border-color:rgb(254 243 199 / var(--tw-border-opacity, 1))}.border-amber-200{--tw-border-opacity: 1;border-color:rgb(253 230 138 / var(--tw-border-opacity, 1))}.border-amber-500{--tw-border-opacity: 1;border-color:rgb(245 158 11 / var(--tw-border-opacity, 1))}.border-blue-100{--tw-border-opacity: 1;border-color:rgb(219 234 254 / var(--tw-border-opacity, 1))}.border-blue-200{--tw-border-opacity: 1;border-color:rgb(191 219 254 / var(--tw-border-opacity, 1))}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-blue-600{--tw-border-opacity: 1;border-color:rgb(37 99 235 / var(--tw-border-opacity, 1))}.border-emerald-100{--tw-border-opacity: 1;border-color:rgb(209 250 229 / var(--tw-border-opacity, 1))}.border-emerald-500{--tw-border-opacity: 1;border-color:rgb(16 185 129 / var(--tw-border-opacity, 1))}.border-gray-100{--tw-border-opacity: 1;border-color:rgb(243 244 246 / var(--tw-border-opacity, 1))}.border-gray-200{--tw-border-opacity: 1;border-color:rgb(229 231 235 / var(--tw-border-opacity, 1))}.border-gray-300{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.border-gray-50{--tw-border-opacity: 1;border-color:rgb(249 250 251 / var(--tw-border-opacity, 1))}.border-green-200{--tw-border-opacity: 1;border-color:rgb(187 247 208 / var(--tw-border-opacity, 1))}.border-purple-100{--tw-border-opacity: 1;border-color:rgb(243 232 255 / var(--tw-border-opacity, 1))}.border-red-100{--tw-border-opacity: 1;border-color:rgb(254 226 226 / var(--tw-border-opacity, 1))}.border-red-200{--tw-border-opacity: 1;border-color:rgb(254 202 202 / var(--tw-border-opacity, 1))}.border-white{--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.border-white\/10{border-color:#ffffff1a}.bg-\[\#0094f7\]{--tw-bg-opacity: 1;background-color:rgb(0 148 247 / var(--tw-bg-opacity, 1))}.bg-\[\#F4F5F7\]{--tw-bg-opacity: 1;background-color:rgb(244 245 247 / var(--tw-bg-opacity, 1))}.bg-\[\#F7F8FA\]{--tw-bg-opacity: 1;background-color:rgb(247 248 250 / var(--tw-bg-opacity, 1))}.bg-\[\#FAFAFA\]{--tw-bg-opacity: 1;background-color:rgb(250 250 250 / var(--tw-bg-opacity, 1))}.bg-\[\#f5f5f7\]{--tw-bg-opacity: 1;background-color:rgb(245 245 247 / var(--tw-bg-opacity, 1))}.bg-amber-100{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.bg-amber-100\/70{background-color:#fef3c7b3}.bg-amber-50{--tw-bg-opacity: 1;background-color:rgb(255 251 235 / var(--tw-bg-opacity, 1))}.bg-amber-50\/60{background-color:#fffbeb99}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-black{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.bg-black\/50{background-color:#00000080}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-100\/70{background-color:#dbeafeb3}.bg-blue-200\/30{background-color:#bfdbfe4d}.bg-blue-200\/40{background-color:#bfdbfe66}.bg-blue-400{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.bg-blue-50{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.bg-blue-50\/40{background-color:#eff6ff66}.bg-blue-50\/50{background-color:#eff6ff80}.bg-blue-50\/60{background-color:#eff6ff99}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-500\/20{background-color:#3b82f633}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-emerald-100{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.bg-emerald-50{--tw-bg-opacity: 1;background-color:rgb(236 253 245 / var(--tw-bg-opacity, 1))}.bg-emerald-50\/60{background-color:#ecfdf599}.bg-emerald-600{--tw-bg-opacity: 1;background-color:rgb(5 150 105 / var(--tw-bg-opacity, 1))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-100\/50{background-color:#f3f4f680}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.bg-gray-200\/50{background-color:#e5e7eb80}.bg-gray-300{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity, 1))}.bg-gray-400{--tw-bg-opacity: 1;background-color:rgb(156 163 175 / var(--tw-bg-opacity, 1))}.bg-gray-50{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity, 1))}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-50{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-orange-100{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.bg-orange-500{--tw-bg-opacity: 1;background-color:rgb(249 115 22 / var(--tw-bg-opacity, 1))}.bg-pink-50{--tw-bg-opacity: 1;background-color:rgb(253 242 248 / var(--tw-bg-opacity, 1))}.bg-purple-100{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.bg-purple-50{--tw-bg-opacity: 1;background-color:rgb(250 245 255 / var(--tw-bg-opacity, 1))}.bg-purple-50\/50{background-color:#faf5ff80}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.bg-purple-600{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.bg-red-100{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.bg-red-50{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-slate-900{--tw-bg-opacity: 1;background-color:rgb(15 23 42 / var(--tw-bg-opacity, 1))}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-white\/5{background-color:#ffffff0d}.bg-white\/80{background-color:#fffc}.bg-white\/90{background-color:#ffffffe6}.bg-white\/95{background-color:#fffffff2}.bg-opacity-10{--tw-bg-opacity: .1}.bg-gradient-to-bl{background-image:linear-gradient(to bottom left,var(--tw-gradient-stops))}.from-blue-50{--tw-gradient-from: #eff6ff var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 246 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.to-transparent{--tw-gradient-to: transparent var(--tw-gradient-to-position)}.object-contain{-o-object-fit:contain;object-fit:contain}.object-cover{-o-object-fit:cover;object-fit:cover}.p-0{padding:0}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-12{padding:3rem}.p-16{padding:4rem}.p-2{padding:.5rem}.p-2\.5{padding:.625rem}.p-20{padding:5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-10{padding-left:2.5rem;padding-right:2.5rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-16{padding-top:4rem;padding-bottom:4rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-20{padding-top:5rem;padding-bottom:5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-3\.5{padding-top:.875rem;padding-bottom:.875rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-5{padding-top:1.25rem;padding-bottom:1.25rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.pb-10{padding-bottom:2.5rem}.pb-24{padding-bottom:6rem}.pl-10{padding-left:2.5rem}.pl-11{padding-left:2.75rem}.pl-14{padding-left:3.5rem}.pl-2{padding-left:.5rem}.pl-4{padding-left:1rem}.pl-5{padding-left:1.25rem}.pl-6{padding-left:1.5rem}.pr-10{padding-right:2.5rem}.pr-11{padding-right:2.75rem}.pr-12{padding-right:3rem}.pr-2{padding-right:.5rem}.pr-4{padding-right:1rem}.pr-6{padding-right:1.5rem}.pr-9{padding-right:2.25rem}.pt-1{padding-top:.25rem}.pt-4{padding-top:1rem}.pt-5{padding-top:1.25rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-\[13px\]{font-size:13px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-black{font-weight:900}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.leading-4{line-height:1rem}.leading-5{line-height:1.25rem}.leading-6{line-height:1.5rem}.leading-relaxed{line-height:1.625}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.tracking-widest{letter-spacing:.1em}.text-\[\#0094f7\]{--tw-text-opacity: 1;color:rgb(0 148 247 / var(--tw-text-opacity, 1))}.text-\[\#111\]{--tw-text-opacity: 1;color:rgb(17 17 17 / var(--tw-text-opacity, 1))}.text-amber-600{--tw-text-opacity: 1;color:rgb(217 119 6 / var(--tw-text-opacity, 1))}.text-amber-700{--tw-text-opacity: 1;color:rgb(180 83 9 / var(--tw-text-opacity, 1))}.text-amber-800{--tw-text-opacity: 1;color:rgb(146 64 14 / var(--tw-text-opacity, 1))}.text-amber-800\/80{color:#92400ecc}.text-amber-900{--tw-text-opacity: 1;color:rgb(120 53 15 / var(--tw-text-opacity, 1))}.text-amber-900\/90{color:#78350fe6}.text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-blue-700{--tw-text-opacity: 1;color:rgb(29 78 216 / var(--tw-text-opacity, 1))}.text-blue-800{--tw-text-opacity: 1;color:rgb(30 64 175 / var(--tw-text-opacity, 1))}.text-blue-900{--tw-text-opacity: 1;color:rgb(30 58 138 / var(--tw-text-opacity, 1))}.text-blue-950{--tw-text-opacity: 1;color:rgb(23 37 84 / var(--tw-text-opacity, 1))}.text-emerald-600{--tw-text-opacity: 1;color:rgb(5 150 105 / var(--tw-text-opacity, 1))}.text-emerald-700{--tw-text-opacity: 1;color:rgb(4 120 87 / var(--tw-text-opacity, 1))}.text-emerald-800{--tw-text-opacity: 1;color:rgb(6 95 70 / var(--tw-text-opacity, 1))}.text-gray-100{--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity, 1))}.text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity, 1))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-gray-700{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity, 1))}.text-gray-900{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-green-700{--tw-text-opacity: 1;color:rgb(21 128 61 / var(--tw-text-opacity, 1))}.text-green-800{--tw-text-opacity: 1;color:rgb(22 101 52 / var(--tw-text-opacity, 1))}.text-orange-700{--tw-text-opacity: 1;color:rgb(194 65 12 / var(--tw-text-opacity, 1))}.text-pink-600{--tw-text-opacity: 1;color:rgb(219 39 119 / var(--tw-text-opacity, 1))}.text-purple-500{--tw-text-opacity: 1;color:rgb(168 85 247 / var(--tw-text-opacity, 1))}.text-purple-600{--tw-text-opacity: 1;color:rgb(147 51 234 / var(--tw-text-opacity, 1))}.text-purple-700{--tw-text-opacity: 1;color:rgb(126 34 206 / var(--tw-text-opacity, 1))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-red-700{--tw-text-opacity: 1;color:rgb(185 28 28 / var(--tw-text-opacity, 1))}.text-red-800{--tw-text-opacity: 1;color:rgb(153 27 27 / var(--tw-text-opacity, 1))}.text-red-900{--tw-text-opacity: 1;color:rgb(127 29 29 / var(--tw-text-opacity, 1))}.text-slate-400{--tw-text-opacity: 1;color:rgb(148 163 184 / var(--tw-text-opacity, 1))}.text-slate-950{--tw-text-opacity: 1;color:rgb(2 6 23 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-white\/30{color:#ffffff4d}.accent-\[\#0094f7\]{accent-color:#0094f7}.opacity-0{opacity:0}.opacity-10{opacity:.1}.opacity-20{opacity:.2}.opacity-25{opacity:.25}.opacity-30{opacity:.3}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-75{opacity:.75}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_20px_60px_-15px_rgba\(0\,0\,0\,0\.05\)\]{--tw-shadow: 0 20px 60px -15px rgba(0,0,0,.05);--tw-shadow-colored: 0 20px 60px -15px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[4px_0_24px_rgba\(0\,0\,0\,0\.02\)\]{--tw-shadow: 4px 0 24px rgba(0,0,0,.02);--tw-shadow-colored: 4px 0 24px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-inner{--tw-shadow: inset 0 2px 4px 0 rgb(0 0 0 / .05);--tw-shadow-colored: inset 0 2px 4px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-blue-100{--tw-shadow-color: #dbeafe;--tw-shadow: var(--tw-shadow-colored)}.shadow-blue-200{--tw-shadow-color: #bfdbfe;--tw-shadow: var(--tw-shadow-colored)}.shadow-emerald-100{--tw-shadow-color: #d1fae5;--tw-shadow: var(--tw-shadow-colored)}.shadow-gray-200{--tw-shadow-color: #e5e7eb;--tw-shadow: var(--tw-shadow-colored)}.shadow-gray-200\/70{--tw-shadow-color: rgb(229 231 235 / .7);--tw-shadow: var(--tw-shadow-colored)}.outline-none{outline:2px solid transparent;outline-offset:2px}.ring-4{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-white{--tw-ring-opacity: 1;--tw-ring-color: rgb(255 255 255 / var(--tw-ring-opacity, 1))}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.blur-2xl{--tw-blur: blur(40px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.blur-\[120px\]{--tw-blur: blur(120px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur{--tw-backdrop-blur: blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-3xl{--tw-backdrop-blur: blur(64px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.squircle{-webkit-mask-image:url(/static/assets/squircle-rb6SKa34.svg);mask-image:url(/static/assets/squircle-rb6SKa34.svg);-webkit-mask-size:contain;mask-size:contain;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-position:center;mask-position:center;border-radius:0}*{box-sizing:border-box;margin:0;padding:0}html,body,#root{height:100%;width:100%}body{font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;background-color:#f4f5f7;color:#fff;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.ios-card{background:#fff;border-radius:8px;border:1px solid rgba(0,0,0,.02);box-shadow:0 8px 24px #0000000a;transition:transform .2s ease,box-shadow .2s ease}.ios-card:hover{box-shadow:0 12px 32px #0000000f}.ios-input{background:#f7f8fa;border:1px solid transparent;transition:all .3s cubic-bezier(.25,.8,.25,1);color:#111;font-weight:500}.ios-input:focus{background:#fff;border-color:#0094f7;box-shadow:0 0 0 4px #0094f74d;outline:none}.ios-input::-moz-placeholder{color:#9ca3af;font-weight:400}.ios-input::placeholder{color:#9ca3af;font-weight:400}.ios-btn-primary{background:#0094f7;color:#fff;font-weight:700;border:none;transition:all .2s cubic-bezier(.25,.8,.25,1);cursor:pointer}.ios-btn-primary:hover:not(:disabled){background:#0071e3;transform:translateY(-1px);box-shadow:0 8px 20px #0094f74d}.ios-btn-primary:active:not(:disabled){transform:translateY(1px);box-shadow:0 2px 8px #0094f733}.ios-btn-primary:disabled{background:#f0f0f0;color:#aaa;box-shadow:none;transform:none;cursor:not-allowed}.ios-btn-secondary{background:#f7f8fa;color:#fff;font-weight:600;border:1px solid transparent;transition:all .2s ease;cursor:pointer}.ios-btn-secondary:hover{background:#e5e7eb;border-color:#d1d5db}.ios-btn-danger{background:#fee2e2;color:#dc2626;font-weight:600;border:1px solid transparent;transition:all .2s ease;cursor:pointer}.ios-btn-danger:hover{background:#fecaca;border-color:#fca5a5}::-webkit-scrollbar{width:6px;height:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:#0000001a;border-radius:10px}::-webkit-scrollbar-thumb:hover{background:#0003}@keyframes fadeIn{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in{animation:fadeIn .5s cubic-bezier(.16,1,.3,1) forwards}@keyframes slideUp{0%{opacity:0;transform:translateY(30px) scale(.95)}to{opacity:1;transform:translateY(0) scale(1)}}.animate-slide-up{animation:slideUp .3s cubic-bezier(.16,1,.3,1) forwards}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}@keyframes pulse{0%,to{opacity:1}50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}::-moz-selection{background:#0094f7;color:#fff}::selection{background:#0094f7;color:#fff}.text-brand{color:#0094f7}.bg-brand{background-color:#0094f7}.border-brand{border-color:#0094f7}.status-badge{display:inline-flex;align-items:center;padding:4px 12px;border-radius:9999px;font-size:12px;font-weight:600}.status-badge-success{background-color:#d1fae5;color:#065f46}.status-badge-warning{background-color:#fef3c7;color:#92400e}.status-badge-error{background-color:#fee2e2;color:#991b1b}.status-badge-info{background-color:#dbeafe;color:#1e40af}.loading-skeleton{background:linear-gradient(90deg,#f3f4f6,#e5e7eb,#f3f4f6);background-size:200% 100%;animation:loading 1.5s ease-in-out infinite}@keyframes loading{0%{background-position:200% 0}to{background-position:-200% 0}}.modal-overlay{position:fixed;top:0;right:0;bottom:0;left:0;z-index:9999;display:flex;align-items:center;justify-content:center;background-color:#0006;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);padding:1rem;overflow-y:auto}.modal-container{position:relative;width:100%;max-width:42rem;max-height:85vh;margin:auto;display:flex;flex-direction:column;background-color:#fff;border-radius:10px;box-shadow:0 25px 50px -12px #00000040;overflow:hidden}.modal-header{flex-shrink:0;padding:2rem 2rem 1.5rem;border-bottom:1px solid #F3F4F6;background-color:#fff;z-index:10}.modal-body{flex:1 1 auto;overflow-y:auto;overflow-x:hidden;padding:2rem}.modal-footer{flex-shrink:0;padding:1.5rem 2rem 2rem;border-top:1px solid #F3F4F6;background-color:#fff;z-index:10}.modal-container-lg{max-width:64rem}.modal-overlay-centered{position:fixed;top:0;right:0;bottom:0;left:0;z-index:9999;display:flex;justify-content:center;background-color:#0006;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);padding:1rem;overflow-y:auto}.modal-overlay-centered .modal-container{position:relative;width:100%;max-width:42rem;max-height:85vh;margin:auto 0;display:flex;flex-direction:column;background-color:#fff;border-radius:10px;box-shadow:0 25px 50px -12px #00000040;overflow:hidden}@media(max-width:768px){.ios-card{border-radius:6px}.ios-input{font-size:16px}.modal-container{max-width:calc(100% - 2rem);max-height:90vh;border-radius:8px}.modal-header,.modal-body,.modal-footer{padding-left:1.5rem;padding-right:1.5rem}}.hover\:translate-y-\[-4px\]:hover{--tw-translate-y: -4px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:scale-105:hover{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:border-\[\#0094f7\]:hover{--tw-border-opacity: 1;border-color:rgb(0 148 247 / var(--tw-border-opacity, 1))}.hover\:border-amber-300:hover{--tw-border-opacity: 1;border-color:rgb(252 211 77 / var(--tw-border-opacity, 1))}.hover\:border-blue-300:hover{--tw-border-opacity: 1;border-color:rgb(147 197 253 / var(--tw-border-opacity, 1))}.hover\:border-emerald-300:hover{--tw-border-opacity: 1;border-color:rgb(110 231 183 / var(--tw-border-opacity, 1))}.hover\:border-gray-300:hover{--tw-border-opacity: 1;border-color:rgb(209 213 219 / var(--tw-border-opacity, 1))}.hover\:border-gray-400:hover{--tw-border-opacity: 1;border-color:rgb(156 163 175 / var(--tw-border-opacity, 1))}.hover\:bg-\[\#0071e3\]:hover{--tw-bg-opacity: 1;background-color:rgb(0 113 227 / var(--tw-bg-opacity, 1))}.hover\:bg-\[\#0094f7\]:hover{--tw-bg-opacity: 1;background-color:rgb(0 148 247 / var(--tw-bg-opacity, 1))}.hover\:bg-\[\#FFFDE7\]\/50:hover{background-color:#fffde780}.hover\:bg-amber-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 243 199 / var(--tw-bg-opacity, 1))}.hover\:bg-black:hover{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-100:hover{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-50:hover{--tw-bg-opacity: 1;background-color:rgb(239 246 255 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-100:hover{--tw-bg-opacity: 1;background-color:rgb(209 250 229 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-50:hover{--tw-bg-opacity: 1;background-color:rgb(236 253 245 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-50\/50:hover{background-color:#ecfdf580}.hover\:bg-emerald-700:hover{--tw-bg-opacity: 1;background-color:rgb(4 120 87 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-200:hover{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-50:hover{--tw-bg-opacity: 1;background-color:rgb(249 250 251 / var(--tw-bg-opacity, 1))}.hover\:bg-gray-800:hover{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity, 1))}.hover\:bg-green-100:hover{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.hover\:bg-green-50:hover{--tw-bg-opacity: 1;background-color:rgb(240 253 244 / var(--tw-bg-opacity, 1))}.hover\:bg-purple-100:hover{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.hover\:bg-red-100:hover{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.hover\:bg-red-50:hover{--tw-bg-opacity: 1;background-color:rgb(254 242 242 / var(--tw-bg-opacity, 1))}.hover\:bg-white:hover{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.hover\:bg-white\/10:hover{background-color:#ffffff1a}.hover\:text-\[\#0094f7\]:hover{--tw-text-opacity: 1;color:rgb(0 148 247 / var(--tw-text-opacity, 1))}.hover\:text-black:hover{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.hover\:text-blue-600:hover{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.hover\:text-gray-600:hover{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.hover\:text-gray-700:hover{--tw-text-opacity: 1;color:rgb(55 65 81 / var(--tw-text-opacity, 1))}.hover\:text-gray-900:hover{--tw-text-opacity: 1;color:rgb(17 24 39 / var(--tw-text-opacity, 1))}.hover\:text-green-600:hover{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.hover\:text-red-500:hover{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.focus\:border-blue-400:focus{--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-0:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-\[\#0094f7\]:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(0 148 247 / var(--tw-ring-opacity, 1))}.active\:scale-95:active{--tw-scale-x: .95;--tw-scale-y: .95;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-25:disabled{opacity:.25}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}.disabled\:opacity-70:disabled{opacity:.7}.group:focus-within .group-focus-within\:text-\[\#0094f7\]{--tw-text-opacity: 1;color:rgb(0 148 247 / var(--tw-text-opacity, 1))}.group:focus-within .group-focus-within\:text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:translate-x-1{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-105{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-110{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:scale-125{--tw-scale-x: 1.25;--tw-scale-y: 1.25;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.group:hover .group-hover\:text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:opacity-100{opacity:1}@media(min-width:640px){.sm\:w-48{width:12rem}.sm\:w-56{width:14rem}.sm\:w-72{width:18rem}.sm\:max-w-sm{max-width:24rem}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.sm\:grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.sm\:grid-cols-\[1fr_180px\]{grid-template-columns:1fr 180px}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-8{gap:2rem}}@media(min-width:768px){.md\:col-span-2{grid-column:span 2 / span 2}.md\:col-span-3{grid-column:span 3 / span 3}.md\:col-span-full{grid-column:1 / -1}.md\:w-auto{width:auto}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.md\:grid-cols-\[1\.4fr_110px_40px\]{grid-template-columns:1.4fr 110px 40px}.md\:grid-cols-\[180px_1fr\]{grid-template-columns:180px 1fr}.md\:grid-cols-\[1fr_1fr_1\.4fr_110px_40px\]{grid-template-columns:1fr 1fr 1.4fr 110px 40px}.md\:flex-row{flex-direction:row}.md\:items-end{align-items:flex-end}.md\:items-center{align-items:center}.md\:justify-between{justify-content:space-between}.md\:border-l{border-left-width:1px}.md\:border-t-0{border-top-width:0px}.md\:p-12{padding:3rem}.md\:pl-6{padding-left:1.5rem}.md\:pt-0{padding-top:0}}@media(min-width:1024px){.lg\:col-span-2{grid-column:span 2 / span 2}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:grid-cols-\[320px_1fr\]{grid-template-columns:320px 1fr}.lg\:flex-row{flex-direction:row}.lg\:items-center{align-items:center}.lg\:self-auto{align-self:auto}}@media(min-width:1280px){.xl\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.xl\:flex-row{flex-direction:row}.xl\:items-end{align-items:flex-end}.xl\:items-center{align-items:center}.xl\:justify-between{justify-content:space-between}}@media(min-width:1536px){.\32xl\:grid-cols-\[360px_1fr\]{grid-template-columns:360px 1fr}}
diff --git a/internal/webui/static/index.html b/internal/webui/static/index.html
index 3af871e..924f906 100644
--- a/internal/webui/static/index.html
+++ b/internal/webui/static/index.html
@@ -6,12 +6,12 @@
Ydisks闲鱼助手 - 自动发货与管家系统
-
+
-
+
-
+
diff --git a/internal/xianyu/cookierefresh/cookies.go b/internal/xianyu/cookierefresh/cookies.go
index 8739635..f1ed8bf 100644
--- a/internal/xianyu/cookierefresh/cookies.go
+++ b/internal/xianyu/cookierefresh/cookies.go
@@ -2,8 +2,12 @@ package cookierefresh
import (
"encoding/json"
+ "net/http"
+ "net/url"
+ "path"
"sort"
"strings"
+ "time"
)
const (
@@ -13,14 +17,15 @@ const (
// BrowserCookie 保存浏览器返回的完整 Cookie 属性。
type BrowserCookie struct {
- Name string `json:"name"`
- Value string `json:"value"`
- Domain string `json:"domain,omitempty"`
- Path string `json:"path,omitempty"`
- Expires float64 `json:"expires,omitempty"`
- HTTPOnly bool `json:"httpOnly,omitempty"`
- Secure bool `json:"secure,omitempty"`
- SameSite string `json:"sameSite,omitempty"`
+ Name string `json:"name"`
+ Value string `json:"value"`
+ Domain string `json:"domain,omitempty"`
+ Path string `json:"path,omitempty"`
+ Expires float64 `json:"expires,omitempty"`
+ HTTPOnly bool `json:"httpOnly,omitempty"`
+ Secure bool `json:"secure,omitempty"`
+ SameSite string `json:"sameSite,omitempty"`
+ PartitionKey string `json:"partitionKey,omitempty"`
}
// ParseCookieString 把 Cookie 头解析为 name -> value。
@@ -77,6 +82,288 @@ func MergeSetCookies(original string, setCookies []string) string {
return MarshalCookieString(m)
}
+// SnapshotFromCookieString 为只有扁平 Cookie 的历史账号建立兼容快照。浏览器刷新后
+// 应使用真实快照覆盖它,避免长期依赖推断出的 Domain/Path。
+func SnapshotFromCookieString(cookieString, domain string) []BrowserCookie {
+ domain = strings.TrimSpace(domain)
+ if domain == "" {
+ domain = ".goofish.com"
+ }
+ values := ParseCookieString(cookieString)
+ names := make([]string, 0, len(values))
+ for name := range values {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+ out := make([]BrowserCookie, 0, len(names))
+ for _, name := range names {
+ value := values[name]
+ out = append(out, BrowserCookie{Name: name, Value: value, Domain: domain, Path: "/", Secure: true})
+ }
+ return NormalizeSnapshot(out)
+}
+
+// ReconcileSnapshotWithCookieString 在调用方暂时只能获得扁平 Cookie 结果时保留
+// 已知属性,并同步值与删除项。新增字段使用 .goofish.com 根路径作为兼容作用域。
+func ReconcileSnapshotWithCookieString(snapshot []BrowserCookie, cookieString string) []BrowserCookie {
+ values := ParseCookieString(cookieString)
+ counts := make(map[string]int, len(snapshot))
+ for _, cookie := range NormalizeSnapshot(snapshot) {
+ counts[cookie.Name]++
+ }
+ seen := make(map[string]struct{})
+ out := make([]BrowserCookie, 0, len(snapshot)+len(values))
+ for _, cookie := range NormalizeSnapshot(snapshot) {
+ value, exists := values[cookie.Name]
+ if !exists {
+ continue
+ }
+ // 扁平 Cookie 字符串无法表达同名 Cookie 的 Domain/Path/PartitionKey。
+ // 只有名称唯一时才可确定其新值;否则保留各作用域原值,避免把一个值
+ // 错误覆盖到完整 Jar 的所有同名项。
+ if counts[cookie.Name] == 1 {
+ cookie.Value = value
+ }
+ out = append(out, cookie)
+ seen[cookie.Name] = struct{}{}
+ }
+ names := make([]string, 0, len(values))
+ for name := range values {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+ for _, name := range names {
+ if _, exists := seen[name]; exists {
+ continue
+ }
+ value := values[name]
+ out = append(out, BrowserCookie{Name: name, Value: value, Domain: ".goofish.com", Path: "/", Secure: true})
+ }
+ return NormalizeSnapshot(out)
+}
+
+// CookieHeaderForURL 按浏览器 Domain/Path/Secure/Expires 规则生成指定 URL 的
+// Cookie header,并保留不同路径下的同名 Cookie。
+func CookieHeaderForURL(snapshot []BrowserCookie, rawURL string, now time.Time) string {
+ header, _ := ScopedCookieHeaderForURL(snapshot, rawURL, now)
+ return header
+}
+
+// ScopedCookieHeaderForURL 按浏览器匹配规则生成 Cookie header。第二个返回值
+// 表示调用方提供了权威快照且 URL 有效;即使没有任何 Cookie 匹配,也会返回
+// ("", true),让调用方能区分“明确为空”和“没有快照,需要兼容回退”。
+//
+// 此简化入口不具备顶级站点上下文,因此不会发送分区 Cookie。需要处理 CHIPS
+// 时应使用 ScopedCookieHeaderForRequest 并传入浏览器提供的 PartitionKey。
+func ScopedCookieHeaderForURL(snapshot []BrowserCookie, rawURL string, now time.Time) (string, bool) {
+ return ScopedCookieHeaderForRequest(snapshot, rawURL, "", now)
+}
+
+// ScopedCookieHeaderForRequest 为带顶级站点 PartitionKey 的请求生成 Cookie header。
+func ScopedCookieHeaderForRequest(snapshot []BrowserCookie, rawURL, partitionKey string, now time.Time) (string, bool) {
+ if snapshot == nil {
+ return "", false
+ }
+ target, err := url.Parse(rawURL)
+ if err != nil || target.Hostname() == "" {
+ return "", false
+ }
+ type matchedCookie struct {
+ cookie BrowserCookie
+ index int
+ }
+ matched := make([]matchedCookie, 0, len(snapshot))
+ for index, cookie := range NormalizeSnapshot(snapshot) {
+ // Unpartitioned cookies are always eligible. Partitioned cookies are
+ // additionally sent when their key matches the current top-level site.
+ if cookie.PartitionKey != "" && cookie.PartitionKey != partitionKey {
+ continue
+ }
+ if cookie.Expires > 0 && cookie.Expires <= float64(now.Unix()) {
+ continue
+ }
+ if cookie.Secure && target.Scheme != "https" && target.Scheme != "wss" {
+ continue
+ }
+ if !cookieDomainMatches(target.Hostname(), cookie.Domain) || !cookiePathMatches(target.EscapedPath(), cookie.Path) {
+ continue
+ }
+ matched = append(matched, matchedCookie{cookie: cookie, index: index})
+ }
+ sort.SliceStable(matched, func(i, j int) bool {
+ if len(matched[i].cookie.Path) != len(matched[j].cookie.Path) {
+ return len(matched[i].cookie.Path) > len(matched[j].cookie.Path)
+ }
+ return matched[i].index < matched[j].index
+ })
+ parts := make([]string, 0, len(matched))
+ for _, item := range matched {
+ parts = append(parts, item.cookie.Name+"="+item.cookie.Value)
+ }
+ return strings.Join(parts, "; "), true
+}
+
+// ApplySetCookies 把某次请求响应的 Set-Cookie 应用到完整快照。删除操作只删除
+// 相同 name/domain/path 的 Cookie,不会误删其他作用域下的同名项。
+func ApplySetCookies(snapshot []BrowserCookie, requestURL string, setCookies []string, now time.Time, partitionKeys ...string) []BrowserCookie {
+ target, err := url.Parse(requestURL)
+ if err != nil || target.Hostname() == "" {
+ return NormalizeSnapshot(snapshot)
+ }
+ // Cookie identity is name/domain/path/partition key, while header ordering for
+ // equal paths follows creation time. Keep the input position when replacing an
+ // existing cookie; if it is deleted and later recreated, append it as a new
+ // creation, just like Chromium's cookie store.
+ state := make([]BrowserCookie, 0, len(snapshot)+len(setCookies))
+ positions := make(map[string]int, len(snapshot)+len(setCookies))
+ for _, cookie := range NormalizeSnapshot(snapshot) {
+ key := snapshotKey(cookie)
+ if index, exists := positions[key]; exists {
+ state[index] = cookie
+ continue
+ }
+ positions[key] = len(state)
+ state = append(state, cookie)
+ }
+ for _, raw := range setCookies {
+ parsed, err := http.ParseSetCookie(raw)
+ if err != nil || strings.TrimSpace(parsed.Name) == "" {
+ continue
+ }
+ rawDomain := strings.TrimSpace(parsed.Domain)
+ domain := strings.ToLower(rawDomain)
+ if domain == "" {
+ domain = strings.ToLower(target.Hostname())
+ } else {
+ // Domain 属性无论是否带前导点都表示域 Cookie;前导点按
+ // RFC 6265 应被忽略。不能复用已存 Cookie 的 host-only
+ // 匹配规则,否则 Domain=goofish.com 会被错误拒绝。
+ if !cookieDomainAttributeMatches(strings.ToLower(target.Hostname()), domain) {
+ // Chromium rejects a Domain attribute unrelated to the response host.
+ continue
+ }
+ if !strings.HasPrefix(domain, ".") {
+ domain = "." + domain
+ }
+ }
+ cookiePath := parsed.Path
+ if cookiePath == "" {
+ cookiePath = defaultCookiePath(target.Path)
+ }
+ if parsed.SameSite == http.SameSiteNoneMode && !parsed.Secure {
+ // Chromium rejects SameSite=None cookies unless they are also Secure.
+ continue
+ }
+ if strings.HasPrefix(parsed.Name, "__Secure-") && !parsed.Secure {
+ continue
+ }
+ if strings.HasPrefix(parsed.Name, "__Host-") && (!parsed.Secure || rawDomain != "" || parsed.Path != "/") {
+ // __Host- requires Secure, an explicit Path=/, and no Domain attribute.
+ continue
+ }
+ partitionKey := ""
+ if parsed.Partitioned {
+ if !parsed.Secure || len(partitionKeys) == 0 || strings.TrimSpace(partitionKeys[0]) == "" {
+ // Without the top-level site key this cookie cannot be represented
+ // faithfully; never turn it into an unpartitioned cookie.
+ continue
+ }
+ partitionKey = strings.TrimSpace(partitionKeys[0])
+ }
+ cookie := BrowserCookie{
+ Name: parsed.Name, Value: parsed.Value, Domain: domain, Path: cookiePath,
+ HTTPOnly: parsed.HttpOnly, Secure: parsed.Secure, SameSite: sameSiteLabel(parsed.SameSite), PartitionKey: partitionKey,
+ }
+ if parsed.MaxAge > 0 {
+ // RFC 6265: Max-Age 优先于 Expires,并从收到响应的时刻计算。
+ cookie.Expires = float64(now.Add(time.Duration(parsed.MaxAge) * time.Second).Unix())
+ } else if !parsed.Expires.IsZero() {
+ cookie.Expires = float64(parsed.Expires.Unix())
+ }
+ key := snapshotKey(cookie)
+ if parsed.MaxAge < 0 || (parsed.MaxAge == 0 && !parsed.Expires.IsZero() && !parsed.Expires.After(now)) {
+ if index, exists := positions[key]; exists {
+ state = append(state[:index], state[index+1:]...)
+ delete(positions, key)
+ for i := index; i < len(state); i++ {
+ positions[snapshotKey(state[i])] = i
+ }
+ }
+ continue
+ }
+ if index, exists := positions[key]; exists {
+ state[index] = cookie
+ continue
+ }
+ positions[key] = len(state)
+ state = append(state, cookie)
+ }
+ return NormalizeSnapshot(state)
+}
+
+func snapshotKey(cookie BrowserCookie) string {
+ return cookie.Name + "\x00" + strings.ToLower(cookie.Domain) + "\x00" + cookie.Path + "\x00" + cookie.PartitionKey
+}
+
+func cookieDomainAttributeMatches(host, domain string) bool {
+ host = strings.ToLower(strings.TrimSpace(host))
+ base := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(domain)), ".")
+ return base != "" && (host == base || strings.HasSuffix(host, "."+base))
+}
+
+func cookieDomainMatches(host, domain string) bool {
+ host = strings.ToLower(strings.TrimSpace(host))
+ domain = strings.ToLower(strings.TrimSpace(domain))
+ if domain == "" {
+ return false
+ }
+ if strings.HasPrefix(domain, ".") {
+ base := strings.TrimPrefix(domain, ".")
+ return host == base || strings.HasSuffix(host, "."+base)
+ }
+ return host == domain
+}
+
+func cookiePathMatches(requestPath, cookiePath string) bool {
+ if requestPath == "" {
+ requestPath = "/"
+ }
+ if cookiePath == "" {
+ cookiePath = "/"
+ }
+ if requestPath == cookiePath {
+ return true
+ }
+ if !strings.HasPrefix(requestPath, cookiePath) {
+ return false
+ }
+ return strings.HasSuffix(cookiePath, "/") || (len(requestPath) > len(cookiePath) && requestPath[len(cookiePath)] == '/')
+}
+
+func defaultCookiePath(requestPath string) string {
+ if requestPath == "" || requestPath[0] != '/' || requestPath == "/" {
+ return "/"
+ }
+ dir := path.Dir(requestPath)
+ if dir == "." || dir == "/" {
+ return "/"
+ }
+ return dir
+}
+
+func sameSiteLabel(value http.SameSite) string {
+ switch value {
+ case http.SameSiteStrictMode:
+ return "Strict"
+ case http.SameSiteLaxMode:
+ return "Lax"
+ case http.SameSiteNoneMode:
+ return "None"
+ default:
+ return ""
+ }
+}
+
// ChangedCookieNames 返回两个 Cookie 字符串之间发生变化的字段名。
func ChangedCookieNames(before, after string) []string {
a := ParseCookieString(before)
@@ -105,7 +392,7 @@ func ChangedSnapshotLabels(before, after []BrowserCookie) []string {
if path == "" {
path = "/"
}
- return c.Name + "|" + c.Domain + "|" + path
+ return c.Name + "|" + c.Domain + "|" + path + "|" + c.PartitionKey
}
label := func(c BrowserCookie) string {
path := c.Path
@@ -113,7 +400,11 @@ func ChangedSnapshotLabels(before, after []BrowserCookie) []string {
path = "/"
}
if c.Domain != "" {
- return c.Name + "@" + c.Domain + path
+ out := c.Name + "@" + c.Domain + path
+ if c.PartitionKey != "" {
+ out += "#" + c.PartitionKey
+ }
+ return out
}
return c.Name
}
@@ -151,14 +442,14 @@ func ChangedSnapshotLabels(before, after []BrowserCookie) []string {
// CookieStringFromSnapshot 将浏览器 Cookie 快照压成请求 Cookie 字符串。
func CookieStringFromSnapshot(cookies []BrowserCookie) string {
- m := make(map[string]string, len(cookies))
- for _, c := range cookies {
+ parts := make([]string, 0, len(cookies))
+ for _, c := range NormalizeSnapshot(cookies) {
if c.Name == "" {
continue
}
- m[c.Name] = c.Value
+ parts = append(parts, c.Name+"="+c.Value)
}
- return MarshalCookieString(m)
+ return strings.Join(parts, "; ")
}
// MergeOriginalFields 补回浏览器未返回但原 Cookie 中存在的字段。
@@ -170,8 +461,12 @@ func MergeOriginalFields(original, browserCookieString string) string {
return MarshalCookieString(m)
}
-// NormalizeSnapshot 排序并补齐默认 path,保证 metadata 稳定。
+// NormalizeSnapshot 补齐默认 path 并保留浏览器返回的创建顺序。Cookie
+// header 在 Path 长度相同时必须沿用该顺序,因此不能在这里按名称重排。
func NormalizeSnapshot(cookies []BrowserCookie) []BrowserCookie {
+ if cookies == nil {
+ return nil
+ }
out := make([]BrowserCookie, 0, len(cookies))
for _, c := range cookies {
if c.Name == "" {
@@ -182,31 +477,39 @@ func NormalizeSnapshot(cookies []BrowserCookie) []BrowserCookie {
}
out = append(out, c)
}
- sort.Slice(out, func(i, j int) bool {
- if out[i].Domain != out[j].Domain {
- return out[i].Domain < out[j].Domain
- }
- if out[i].Path != out[j].Path {
- return out[i].Path < out[j].Path
- }
- return out[i].Name < out[j].Name
- })
return out
}
// SnapshotFromMetadata 从 cookies.metadata_json 中读取浏览器 Cookie 快照。
func SnapshotFromMetadata(metadata string) []BrowserCookie {
+ out, _ := SnapshotFromMetadataOK(metadata)
+ return out
+}
+
+// SnapshotFromMetadataOK 读取完整 Cookie 快照,并报告 metadata 中是否真的
+// 存在快照键。存在空数组时返回非 nil 空切片和 true,避免被误当成历史账号
+// 而回退到扁平 Cookie。
+func SnapshotFromMetadataOK(metadata string) ([]BrowserCookie, bool) {
var m map[string]json.RawMessage
if err := json.Unmarshal([]byte(strings.TrimSpace(metadata)), &m); err != nil {
- return nil
+ return nil, false
}
var out []BrowserCookie
if raw := m[metadataSnapshotKey]; len(raw) > 0 {
- _ = json.Unmarshal(raw, &out)
+ if err := json.Unmarshal(raw, &out); err != nil {
+ return nil, false
+ }
} else if raw := m[legacyMetadataSnapshot]; len(raw) > 0 {
- _ = json.Unmarshal(raw, &out)
+ if err := json.Unmarshal(raw, &out); err != nil {
+ return nil, false
+ }
+ } else {
+ return nil, false
}
- return NormalizeSnapshot(out)
+ if out == nil {
+ out = []BrowserCookie{}
+ }
+ return NormalizeSnapshot(out), true
}
// MetadataWithSnapshot 写入浏览器 Cookie 快照,保留 metadata 中的其他键。
diff --git a/internal/xianyu/cookierefresh/cookies_test.go b/internal/xianyu/cookierefresh/cookies_test.go
index 10e4889..a829325 100644
--- a/internal/xianyu/cookierefresh/cookies_test.go
+++ b/internal/xianyu/cookierefresh/cookies_test.go
@@ -1,6 +1,10 @@
package cookierefresh
-import "testing"
+import (
+ "strings"
+ "testing"
+ "time"
+)
func TestMetadataSnapshotKeyCompatibility(t *testing.T) {
oldMeta := `{"cookie_refresh_snapshot":[{"name":"a","value":"1","domain":".goofish.com","path":"/"}]}`
@@ -17,6 +21,242 @@ func TestMetadataSnapshotKeyCompatibility(t *testing.T) {
}
}
+func TestCookieHeaderForURLScopesDomainPathAndSecure(t *testing.T) {
+ now := time.Unix(1_800_000_000, 0)
+ snapshot := []BrowserCookie{
+ {Name: "root", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "passport", Value: "2", Domain: "passport.goofish.com", Path: "/newlogin", Secure: true},
+ {Name: "other", Value: "3", Domain: "h5api.m.goofish.com", Path: "/", Secure: true},
+ {Name: "expired", Value: "4", Domain: ".goofish.com", Path: "/", Expires: float64(now.Add(-time.Hour).Unix())},
+ }
+ got := CookieHeaderForURL(snapshot, "https://passport.goofish.com/newlogin/silentHasLogin.do", now)
+ if got != "passport=2; root=1" {
+ t.Fatalf("CookieHeaderForURL=%q", got)
+ }
+}
+
+func TestCookieHeaderForURLOrdersLongerPathFirst(t *testing.T) {
+ now := time.Now()
+ snapshot := []BrowserCookie{
+ {Name: "_m_h5_tk", Value: "root_1", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "_m_h5_tk", Value: "im_2", Domain: "www.goofish.com", Path: "/im", Secure: true},
+ }
+ got := CookieHeaderForURL(snapshot, "https://www.goofish.com/im", now)
+ if !strings.HasPrefix(got, "_m_h5_tk=im_2; _m_h5_tk=root_1") {
+ t.Fatalf("longer-path cookie must be first, got %q", got)
+ }
+}
+
+func TestCookieHeaderForURLKeepsCreationOrderForEqualPaths(t *testing.T) {
+ now := time.Now()
+ snapshot := []BrowserCookie{
+ {Name: "third", Value: "3", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "first", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "second", Value: "2", Domain: ".goofish.com", Path: "/", Secure: true},
+ }
+ if got := CookieHeaderForURL(snapshot, "https://www.goofish.com/im", now); got != "third=3; first=1; second=2" {
+ t.Fatalf("equal-path creation order lost: %q", got)
+ }
+}
+
+func TestScopedCookieHeaderDistinguishesEmptySnapshotFromUnavailable(t *testing.T) {
+ now := time.Unix(1_800_000_000, 0)
+ if got, ok := ScopedCookieHeaderForURL(nil, "https://www.goofish.com/im", now); ok || got != "" {
+ t.Fatalf("nil snapshot=(%q,%v), want unavailable", got, ok)
+ }
+ if got, ok := ScopedCookieHeaderForURL([]BrowserCookie{}, "https://www.goofish.com/im", now); !ok || got != "" {
+ t.Fatalf("empty snapshot=(%q,%v), want authoritative empty", got, ok)
+ }
+ snapshot := []BrowserCookie{{
+ Name: "partitioned", Value: "1", Domain: ".goofish.com", Path: "/",
+ Secure: true, PartitionKey: "https://example.com",
+ }}
+ if got, ok := ScopedCookieHeaderForURL(snapshot, "https://www.goofish.com/im", now); !ok || got != "" {
+ t.Fatalf("partitionless request=(%q,%v)", got, ok)
+ }
+ if got, ok := ScopedCookieHeaderForRequest(snapshot, "https://www.goofish.com/im", "https://example.com", now); !ok || got != "partitioned=1" {
+ t.Fatalf("partitioned request=(%q,%v)", got, ok)
+ }
+}
+
+func TestApplySetCookiesPreservesAttributesAndDeletesExactScope(t *testing.T) {
+ now := time.Unix(1_800_000_000, 0)
+ snapshot := []BrowserCookie{
+ {Name: "sid", Value: "root", Domain: ".goofish.com", Path: "/"},
+ {Name: "sid", Value: "login", Domain: ".goofish.com", Path: "/newlogin"},
+ }
+ updated := ApplySetCookies(snapshot, "https://passport.goofish.com/newlogin/silentHasLogin.do", []string{
+ "sid=; Domain=.goofish.com; Path=/newlogin; Max-Age=0",
+ "fresh=ok; Domain=.goofish.com; Path=/; Secure; HttpOnly; SameSite=None",
+ }, now)
+ if got := CookieHeaderForURL(updated, "https://www.goofish.com/", now); !strings.Contains(got, "sid=root") || !strings.Contains(got, "fresh=ok") {
+ t.Fatalf("updated header=%q snapshot=%+v", got, updated)
+ }
+ for _, cookie := range updated {
+ if cookie.Name == "sid" && cookie.Path == "/newlogin" {
+ t.Fatalf("精确作用域删除失败: %+v", updated)
+ }
+ if cookie.Name == "fresh" && (!cookie.Secure || !cookie.HTTPOnly || cookie.SameSite != "None") {
+ t.Fatalf("Cookie 属性未保留: %+v", cookie)
+ }
+ }
+}
+
+func TestApplySetCookiesAcceptsDomainAttributeWithoutLeadingDot(t *testing.T) {
+ updated := ApplySetCookies(nil, "https://passport.goofish.com/ivCheckLogin.htm", []string{
+ "unb=777; Domain=goofish.com; Path=/; Secure; HttpOnly",
+ }, time.Now(), "https://goofish.com")
+ if len(updated) != 1 || updated[0].Domain != ".goofish.com" || !updated[0].Secure || !updated[0].HTTPOnly {
+ t.Fatalf("Domain 属性未按域 Cookie 处理: %+v", updated)
+ }
+ if got := CookieHeaderForURL(updated, "https://www.goofish.com/im", time.Now()); got != "unb=777" {
+ t.Fatalf("跨子域 Cookie header=%q", got)
+ }
+}
+
+func TestApplySetCookiesMaxAgeOverridesExpires(t *testing.T) {
+ now := time.Unix(1_800_000_000, 0)
+ updated := ApplySetCookies(nil, "https://www.goofish.com/im", []string{
+ "sid=fresh; Domain=.goofish.com; Path=/; Max-Age=3600; Expires=Thu, 01 Jan 1970 00:00:00 GMT",
+ }, now)
+ if len(updated) != 1 {
+ t.Fatalf("snapshot=%+v", updated)
+ }
+ if got, want := int64(updated[0].Expires), now.Add(time.Hour).Unix(); got != want {
+ t.Fatalf("expires=%d want %d", got, want)
+ }
+
+ deleted := ApplySetCookies(updated, "https://www.goofish.com/im", []string{
+ "sid=stale; Domain=.goofish.com; Path=/; Max-Age=0; Expires=Thu, 01 Jan 2099 00:00:00 GMT",
+ }, now)
+ if len(deleted) != 0 {
+ t.Fatalf("Max-Age=0 must delete cookie: %+v", deleted)
+ }
+}
+
+func TestApplySetCookiesReplacementAndRecreationOrder(t *testing.T) {
+ now := time.Unix(1_800_000_000, 0)
+ initial := []BrowserCookie{
+ {Name: "a", Value: "1", Domain: ".goofish.com", Path: "/"},
+ {Name: "b", Value: "2", Domain: ".goofish.com", Path: "/"},
+ {Name: "c", Value: "3", Domain: ".goofish.com", Path: "/"},
+ }
+ replaced := ApplySetCookies(initial, "https://www.goofish.com/im", []string{
+ "b=fresh; Domain=.goofish.com; Path=/",
+ }, now)
+ if got := CookieHeaderForURL(replaced, "https://www.goofish.com/im", now); got != "a=1; b=fresh; c=3" {
+ t.Fatalf("replacement moved cookie: %q", got)
+ }
+
+ recreated := ApplySetCookies(replaced, "https://www.goofish.com/im", []string{
+ "b=; Domain=.goofish.com; Path=/; Max-Age=0",
+ "b=recreated; Domain=.goofish.com; Path=/",
+ }, now)
+ if got := CookieHeaderForURL(recreated, "https://www.goofish.com/im", now); got != "a=1; c=3; b=recreated" {
+ t.Fatalf("recreated cookie was not appended: %q", got)
+ }
+}
+
+func TestApplySetCookiesRejectsUnrepresentablePartitionedCookie(t *testing.T) {
+ now := time.Unix(1_800_000_000, 0)
+ raw := []string{"chip=value; Domain=.goofish.com; Path=/; Secure; SameSite=None; Partitioned"}
+ if got := ApplySetCookies(nil, "https://www.goofish.com/im", raw, now); len(got) != 0 {
+ t.Fatalf("partitioned cookie without key must be rejected: %+v", got)
+ }
+ if got := ApplySetCookies(nil, "https://www.goofish.com/im", raw, now, " "); len(got) != 0 {
+ t.Fatalf("partitioned cookie with empty key must be rejected: %+v", got)
+ }
+ got := ApplySetCookies(nil, "https://www.goofish.com/im", raw, now, "https://goofish.com")
+ if len(got) != 1 || got[0].PartitionKey != "https://goofish.com" {
+ t.Fatalf("valid partitioned cookie missing: %+v", got)
+ }
+}
+
+func TestApplySetCookiesEnforcesSameSiteAndCookiePrefixes(t *testing.T) {
+ now := time.Unix(1_800_000_000, 0)
+ updated := ApplySetCookies(nil, "https://www.goofish.com/im", []string{
+ "none_insecure=1; Domain=.goofish.com; Path=/; SameSite=None",
+ "none_secure=1; Domain=.goofish.com; Path=/; SameSite=None; Secure",
+ "__Secure-bad=1; Domain=.goofish.com; Path=/",
+ "__Secure-good=1; Domain=.goofish.com; Path=/; Secure",
+ "__Host-domain=1; Domain=www.goofish.com; Path=/; Secure",
+ "__Host-default-path=1; Secure",
+ "__Host-good=1; Path=/; Secure",
+ }, now)
+ values := make(map[string]BrowserCookie, len(updated))
+ for _, cookie := range updated {
+ values[cookie.Name] = cookie
+ }
+ for _, rejected := range []string{"none_insecure", "__Secure-bad", "__Host-domain", "__Host-default-path"} {
+ if _, exists := values[rejected]; exists {
+ t.Fatalf("invalid cookie %s was accepted: %+v", rejected, updated)
+ }
+ }
+ for _, accepted := range []string{"none_secure", "__Secure-good", "__Host-good"} {
+ if _, exists := values[accepted]; !exists {
+ t.Fatalf("valid cookie %s was rejected: %+v", accepted, updated)
+ }
+ }
+}
+
+func TestSameNameCookiesKeepScopeAndPartitionIdentity(t *testing.T) {
+ snapshot := []BrowserCookie{
+ {Name: "sid", Value: "root", Domain: ".goofish.com", Path: "/"},
+ {Name: "sid", Value: "im", Domain: ".goofish.com", Path: "/im"},
+ {Name: "sid", Value: "partitioned", Domain: ".goofish.com", Path: "/", PartitionKey: "https://example.com"},
+ }
+ if got := CookieStringFromSnapshot(snapshot); got != "sid=root; sid=im; sid=partitioned" {
+ t.Fatalf("flat snapshot lost scoped duplicate: %q", got)
+ }
+ reconciled := ReconcileSnapshotWithCookieString(snapshot, "sid=new-flat")
+ if len(reconciled) != 3 {
+ t.Fatalf("reconciled=%+v", reconciled)
+ }
+ for _, cookie := range reconciled {
+ if cookie.Value == "new-flat" {
+ t.Fatalf("ambiguous flat value overwrote scoped cookie: %+v", reconciled)
+ }
+ }
+
+ updated := ApplySetCookies(snapshot, "https://www.goofish.com/", []string{
+ "sid=new-root; Domain=.goofish.com; Path=/",
+ }, time.Unix(1_800_000_000, 0))
+ if len(updated) != 3 {
+ t.Fatalf("partition identity collapsed: %+v", updated)
+ }
+}
+
+func TestSynthesizedSnapshotsRemainDeterministic(t *testing.T) {
+ fromFlat := SnapshotFromCookieString("z=3; a=1; m=2", ".goofish.com")
+ if got := CookieStringFromSnapshot(fromFlat); got != "a=1; m=2; z=3" {
+ t.Fatalf("flat snapshot order=%q", got)
+ }
+ reconciled := ReconcileSnapshotWithCookieString(
+ []BrowserCookie{{Name: "keep", Value: "old", Domain: ".goofish.com", Path: "/"}},
+ "z=3; keep=new; a=1",
+ )
+ if got := CookieStringFromSnapshot(reconciled); got != "keep=new; a=1; z=3" {
+ t.Fatalf("reconciled snapshot order=%q", got)
+ }
+}
+
+func TestSnapshotMetadataReportsAuthoritativeEmptyAndPreservesPartitionKey(t *testing.T) {
+ if got, ok := SnapshotFromMetadataOK(`{"other":true}`); ok || got != nil {
+ t.Fatalf("missing snapshot=(%+v,%v)", got, ok)
+ }
+ metadata := MetadataWithSnapshot(`{"other":true}`, []BrowserCookie{})
+ if got, ok := SnapshotFromMetadataOK(metadata); !ok || got == nil || len(got) != 0 {
+ t.Fatalf("empty snapshot=(%+v,%v) metadata=%s", got, ok, metadata)
+ }
+ metadata = MetadataWithSnapshot("", []BrowserCookie{{
+ Name: "chip", Value: "secret", Domain: ".goofish.com", Path: "/", PartitionKey: "https://example.com",
+ }})
+ got, ok := SnapshotFromMetadataOK(metadata)
+ if !ok || len(got) != 1 || got[0].PartitionKey != "https://example.com" {
+ t.Fatalf("partition snapshot=(%+v,%v) metadata=%s", got, ok, metadata)
+ }
+}
+
func TestChangedSnapshotLabels(t *testing.T) {
before := []BrowserCookie{{Name: "a", Value: "1", Domain: ".goofish.com", Path: "/"}}
after := []BrowserCookie{{Name: "a", Value: "2", Domain: ".goofish.com", Path: "/"}}
diff --git a/internal/xianyu/mtop/client.go b/internal/xianyu/mtop/client.go
index 8e04e68..97729dd 100644
--- a/internal/xianyu/mtop/client.go
+++ b/internal/xianyu/mtop/client.go
@@ -11,10 +11,10 @@ import (
"net/http"
"strconv"
"strings"
- "sync"
"time"
"xianyu-go/internal/xianyu"
+ "xianyu-go/internal/xianyu/cookierefresh"
)
// RegAppKey 是 WS 注册用的 appKey(与签名用的 protocol.SignAppKey 不同)。
@@ -35,6 +35,12 @@ const UserPageNavAPI = "https://h5api.m.goofish.com/h5/mtop.idle.web.user.page.n
// ItemListAPI 是卖家商品列表端点。
const ItemListAPI = "https://h5api.m.goofish.com/h5/mtop.idle.web.xyh.item.list/1.0/"
+// SoldOrdersAPI 是闲鱼卖家工作台的已售订单列表端点。
+const SoldOrdersAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.trade.merchant.sold.get/1.0/"
+
+// ItemDetailAPI 是闲鱼 PC 商品详情端点。
+const ItemDetailAPI = "https://h5api.m.goofish.com/h5/mtop.taobao.idle.pc.detail/1.0/"
+
const (
MTopRetryGap = time.Second
ItemPageGap = time.Second
@@ -59,43 +65,15 @@ type ClientImpl struct {
TokenURL string
ConsignURL string
OrderDetailURL string
+ SoldOrdersURL string
+ ItemDetailURL string
LoginUserURL string
- TokenExecutor TokenRequestExecutor
}
-type TokenBrowserRequest struct {
- URL string
- Body string
- Cookies string
-}
-
-type TokenBrowserResponse struct {
- Status int
- Body []byte
- UpdatedCookies string
-}
-
-type TokenRequestExecutor interface {
- ExecuteTokenRequest(context.Context, TokenBrowserRequest) (*TokenBrowserResponse, error)
-}
-
-var defaultTokenExecutor struct {
- sync.RWMutex
- value TokenRequestExecutor
-}
-
-func SetDefaultTokenRequestExecutor(executor TokenRequestExecutor) {
- defaultTokenExecutor.Lock()
- defaultTokenExecutor.value = executor
- defaultTokenExecutor.Unlock()
-}
-
-// NewClient 构造默认 HTTP 实现的非零 ClientImpl(调用方多为持有 Client 接口字段)。
+// NewClient 构造纯 Go HTTP 的 MTOP 客户端。Chromium 只用于读取本机指纹
+// 和处理滑块,不能成为登录、续期、token 或 WebSocket 的传输层。
func NewClient() *ClientImpl {
- defaultTokenExecutor.RLock()
- executor := defaultTokenExecutor.value
- defaultTokenExecutor.RUnlock()
- return &ClientImpl{TokenExecutor: executor}
+ return &ClientImpl{}
}
// 编译期保证 *ClientImpl 实现 Client 接口。
@@ -103,17 +81,22 @@ var _ Client = (*ClientImpl)(nil)
// RefreshResult 是刷新 token 的结果。
type RefreshResult struct {
- AccessToken string // 用于 WS /reg 注册
- UpdatedCookies string // 合并 Set-Cookie 后的新 cookie 字符串(无变化则与入参相同)
+ AccessToken string // 用于 WS /reg 注册
+ AccessTokenExpireAt int64 // 服务端 accessTokenExpiredTime 归一化后的 Unix 秒
+ UpdatedCookies string // 合并 Set-Cookie 后的新 cookie 字符串(无变化则与入参相同)
+ CookieSnapshot []cookierefresh.BrowserCookie // token 请求后的完整 Cookie Jar
+ CookieSnapshotComplete bool // true 表示快照权威完整;空切片代表 Cookie Jar 已被清空
+ CookieStateChanged bool // true 表示本次响应明确更新或删除了 Cookie(包括更新后为空)
}
// FreshCaptchaResult 是重取 token 风控验证链接的结果。
type FreshCaptchaResult struct {
- TokenOK bool
- AccessToken string
- UpdatedCookies string
- VerificationURL string
- Ret []string
+ TokenOK bool
+ AccessToken string
+ AccessTokenExpireAt int64
+ UpdatedCookies string
+ VerificationURL string
+ Ret []string
}
// UserProfileResult 是 mtop.idle.web.user.page.nav 返回的当前账号资料。
@@ -149,6 +132,7 @@ type ItemListItem struct {
ItemDetail string
AuctionType string
ItemStatus int
+ IsMultiSpec bool
}
func hasMTopSuccess(ret []string) bool {
@@ -299,19 +283,16 @@ func mergeSetCookie(orig string, current map[string]string, resp *http.Response)
}
changed := false
for _, sc := range setCookies {
- // Set-Cookie: name=value; Path=/; ...
- pair := sc
- if i := strings.Index(pair, ";"); i >= 0 {
- pair = pair[:i]
+ parsed, err := http.ParseSetCookie(sc)
+ if err != nil || strings.TrimSpace(parsed.Name) == "" {
+ continue
}
- if eq := strings.Index(pair, "="); eq >= 0 {
- name := strings.TrimSpace(pair[:eq])
- val := strings.TrimSpace(pair[eq+1:])
- if name != "" {
- current[name] = val
- changed = true
- }
+ if parsed.MaxAge < 0 || (parsed.MaxAge == 0 && !parsed.Expires.IsZero() && !parsed.Expires.After(time.Now())) {
+ delete(current, parsed.Name)
+ } else {
+ current[parsed.Name] = parsed.Value
}
+ changed = true
}
if !changed {
return orig
diff --git a/internal/xianyu/mtop/client_test.go b/internal/xianyu/mtop/client_test.go
index 1ef3d55..04d5580 100644
--- a/internal/xianyu/mtop/client_test.go
+++ b/internal/xianyu/mtop/client_test.go
@@ -13,6 +13,12 @@ import (
"time"
)
+func TestNewClientUsesGoHTTPByDefault(t *testing.T) {
+ if client := NewClient(); client == nil {
+ t.Fatal("默认 MTOP 客户端为空")
+ }
+}
+
func TestRefreshTokenRetriesOnceWithUpdatedCookie(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -52,7 +58,7 @@ func TestReadMTopBodyRejectsOversizedResponse(t *testing.T) {
}
}
-func TestRefreshTokenRetriesOnceWithoutUpdatedCookie(t *testing.T) {
+func TestRefreshTokenUsesOfficialAttemptLimitWithoutUpdatedCookie(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
@@ -65,8 +71,8 @@ func TestRefreshTokenRetriesOnceWithoutUpdatedCookie(t *testing.T) {
if err == nil || !strings.Contains(err.Error(), "登录凭证已失效") {
t.Fatalf("err=%v", err)
}
- if requests.Load() != 2 {
- t.Fatalf("请求次数=%d want 2", requests.Load())
+ if requests.Load() != officialMTopMaxAttempts {
+ t.Fatalf("请求次数=%d want %d", requests.Load(), officialMTopMaxAttempts)
}
}
@@ -310,6 +316,17 @@ func TestMergeSetCookieMalformedIgnored(t *testing.T) {
}
}
+func TestMergeSetCookieMaxAgeOverridesPastExpires(t *testing.T) {
+ orig := "session=old"
+ current := map[string]string{"session": "old"}
+ resp := &http.Response{Header: http.Header{
+ "Set-Cookie": {"session=fresh; Max-Age=3600; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/"},
+ }}
+ if got := mergeSetCookie(orig, current, resp); !strings.Contains(got, "session=fresh") {
+ t.Fatalf("positive Max-Age must override past Expires: %q", got)
+ }
+}
+
func TestSleepCtx(t *testing.T) {
// d <= 0 直接返回
if err := sleepCtx(context.Background(), 0); err != nil {
diff --git a/internal/xianyu/mtop/consign.go b/internal/xianyu/mtop/consign.go
index e9af0b8..10faf82 100644
--- a/internal/xianyu/mtop/consign.go
+++ b/internal/xianyu/mtop/consign.go
@@ -25,6 +25,9 @@ func (c *ClientImpl) Consign(cookiesStr, orderID string) (ok bool, ret []string,
// ConsignContext 确认发货;签名 token 过期时使用响应下发的新 Cookie 重签并重试。
func (c *ClientImpl) ConsignContext(ctx context.Context, cookiesStr, orderID string) (ok bool, ret []string, updatedCookies string, err error) {
currentCookies := cookiesStr
+ if session := cookieSessionFromContext(ctx); session != nil {
+ currentCookies, _, _ = session.State()
+ }
var lastRet []string
for attempt := 0; attempt < 4; attempt++ {
previousCookies := currentCookies
@@ -69,35 +72,35 @@ func (c *ClientImpl) consignOnce(ctx context.Context, cookiesStr, orderID string
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
- cookies := protocol.TransCookies(cookiesStr)
- token := protocol.SignToken(cookiesStr)
+ consignURL := c.ConsignURL
+ if consignURL == "" {
+ consignURL = ConsignAPI
+ }
+ signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", consignURL)
+ token := protocol.SignToken(signingCookies)
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
dataVal := `{"orderId":"` + orderID + `", "tradeText":"","picList":[],"newUnconsign":true}`
sign := protocol.GenerateSign(t, token, dataVal)
query := buildConsignQuery(t, sign)
body := "data=" + url.QueryEscape(dataVal)
- consignURL := c.ConsignURL
- if consignURL == "" {
- consignURL = ConsignAPI
- }
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
consignURL+"?"+query,
strings.NewReader(body))
if err != nil {
return false, nil, cookiesStr, err
}
- setCommonHeaders(req, cookiesStr)
+ setCommonHeaders(req, requestCookies)
resp, err := hc.Do(req)
if err != nil {
return false, nil, cookiesStr, fmt.Errorf("consign 请求失败: %w", err)
}
defer resp.Body.Close()
+ updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
raw, err := readMTopBody(resp)
if err != nil {
- return false, nil, cookiesStr, err
+ return false, nil, updated, err
}
- updated := mergeSetCookie(cookiesStr, cookies, resp)
var res struct {
Ret []string `json:"ret"`
}
diff --git a/internal/xianyu/mtop/cookie_session.go b/internal/xianyu/mtop/cookie_session.go
new file mode 100644
index 0000000..a1df55c
--- /dev/null
+++ b/internal/xianyu/mtop/cookie_session.go
@@ -0,0 +1,240 @@
+package mtop
+
+import (
+ "context"
+ "net/http"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+
+ "xianyu-go/internal/xianyu/cookierefresh"
+ "xianyu-go/internal/xianyu/protocol"
+)
+
+const (
+ mtopDocumentURL = "https://www.goofish.com/im"
+ goofishTopSite = "https://goofish.com"
+)
+
+type cookieSessionContextKey struct{}
+
+// CookieSession carries an authoritative Cookie Jar through one MTOP workflow.
+// It lets direct Go HTTP calls reproduce the browser split between
+// document cookies used for signing and cookies scoped to the request URL.
+// The same session absorbs every Set-Cookie before response-body processing,
+// so callers can persist rotations and deletions even when parsing later fails.
+type CookieSession struct {
+ mu sync.Mutex
+ snapshot []cookierefresh.BrowserCookie
+ flat string
+ authoritative bool
+ changed bool
+}
+
+// WithCookieSnapshot installs an authoritative Cookie Jar on ctx. A nil input
+// is normalized to an explicitly empty Jar; callers should invoke this only
+// when metadata confirms that a complete snapshot exists.
+func WithCookieSnapshot(ctx context.Context, snapshot []cookierefresh.BrowserCookie) (context.Context, *CookieSession) {
+ normalized := cookierefresh.NormalizeSnapshot(snapshot)
+ if normalized == nil {
+ normalized = []cookierefresh.BrowserCookie{}
+ }
+ session := &CookieSession{snapshot: normalized, authoritative: true}
+ return context.WithValue(ctx, cookieSessionContextKey{}, session), session
+}
+
+// WithFlatCookieSession carries a legacy flat Cookie header without claiming
+// that it is a complete Cookie Jar. Response Set-Cookie values are still
+// observable and persistable, but callers must keep metadata snapshot-free
+// until a protocol flow supplies an authoritative Jar.
+func WithFlatCookieSession(ctx context.Context, cookies string) (context.Context, *CookieSession) {
+ session := &CookieSession{flat: cookies}
+ return context.WithValue(ctx, cookieSessionContextKey{}, session), session
+}
+
+// State returns the /im canonical Cookie header, a copy of the complete Jar,
+// and whether the workflow observed an authoritative update.
+func (s *CookieSession) State() (string, []cookierefresh.BrowserCookie, bool) {
+ if s == nil {
+ return "", nil, false
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if !s.authoritative {
+ return s.flat, nil, s.changed
+ }
+ snapshot := normalizedCompleteSnapshot(s.snapshot)
+ value, _ := cookierefresh.ScopedCookieHeaderForRequest(snapshot, mtopDocumentURL, goofishTopSite, time.Now())
+ return value, snapshot, s.changed
+}
+
+func cookieSessionFromContext(ctx context.Context) *CookieSession {
+ if ctx == nil {
+ return nil
+ }
+ session, _ := ctx.Value(cookieSessionContextKey{}).(*CookieSession)
+ return session
+}
+
+// CookieSessionFromContext exposes the operation-scoped session to legacy
+// helpers that may replace it with a final authoritative Jar.
+func CookieSessionFromContext(ctx context.Context) *CookieSession {
+ return cookieSessionFromContext(ctx)
+}
+
+// Snapshot returns a copy of the current complete Jar.
+func (s *CookieSession) Snapshot() []cookierefresh.BrowserCookie {
+ snapshot, authoritative, _ := s.requestState()
+ if !authoritative {
+ return nil
+ }
+ return snapshot
+}
+
+// ReplaceSnapshot records a final complete Jar, including an explicitly empty one.
+func (s *CookieSession) ReplaceSnapshot(snapshot []cookierefresh.BrowserCookie) {
+ if snapshot == nil {
+ snapshot = []cookierefresh.BrowserCookie{}
+ }
+ s.replace(snapshot)
+}
+
+func (s *CookieSession) requestState() ([]cookierefresh.BrowserCookie, bool, string) {
+ if s == nil {
+ return nil, false, ""
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if !s.authoritative {
+ return nil, false, s.flat
+ }
+ return normalizedCompleteSnapshot(s.snapshot), true, ""
+}
+
+func (s *CookieSession) replace(snapshot []cookierefresh.BrowserCookie) {
+ if s == nil || snapshot == nil {
+ return
+ }
+ normalized := cookierefresh.NormalizeSnapshot(snapshot)
+ if normalized == nil {
+ normalized = []cookierefresh.BrowserCookie{}
+ }
+ s.mu.Lock()
+ s.snapshot = normalized
+ s.flat = ""
+ s.authoritative = true
+ s.changed = true
+ s.mu.Unlock()
+}
+
+func (s *CookieSession) replaceFlat(flat string) {
+ if s == nil {
+ return
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.authoritative {
+ return
+ }
+ if s.flat != flat {
+ s.flat = flat
+ s.changed = true
+ }
+}
+
+func (s *CookieSession) absorb(requestURL string, setCookies []string) string {
+ if s == nil {
+ return ""
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if len(setCookies) > 0 && s.authoritative {
+ updated := normalizedCompleteSnapshot(cookierefresh.ApplySetCookies(s.snapshot, requestURL, setCookies, time.Now(), goofishTopSite))
+ if !slices.Equal(s.snapshot, updated) {
+ s.snapshot = updated
+ s.changed = true
+ }
+ value, _ := cookierefresh.ScopedCookieHeaderForRequest(s.snapshot, mtopDocumentURL, goofishTopSite, time.Now())
+ return value
+ }
+ if len(setCookies) > 0 {
+ updated, changed := applyFlatSetCookies(s.flat, setCookies, time.Now())
+ if changed {
+ s.flat = updated
+ s.changed = true
+ }
+ }
+ return s.flat
+}
+
+// mtopRequestCookies returns the document-visible cookies used by lib-mtop for
+// token/sign generation and the URL-scoped Cookie header sent on the request.
+func mtopRequestCookies(ctx context.Context, fallback, documentURL, requestURL string) (string, string) {
+ session := cookieSessionFromContext(ctx)
+ if session == nil {
+ return fallback, fallback
+ }
+ snapshot, authoritative, flat := session.requestState()
+ if !authoritative {
+ return flat, flat
+ }
+ documentCookies := make([]cookierefresh.BrowserCookie, 0, len(snapshot))
+ for _, cookie := range snapshot {
+ if !cookie.HTTPOnly {
+ documentCookies = append(documentCookies, cookie)
+ }
+ }
+ signing, _ := cookierefresh.ScopedCookieHeaderForRequest(documentCookies, documentURL, goofishTopSite, time.Now())
+ requestCookies, _ := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, goofishTopSite, time.Now())
+ return signing, requestCookies
+}
+
+func normalizedCompleteSnapshot(snapshot []cookierefresh.BrowserCookie) []cookierefresh.BrowserCookie {
+ normalized := cookierefresh.NormalizeSnapshot(snapshot)
+ if normalized == nil {
+ return []cookierefresh.BrowserCookie{}
+ }
+ return normalized
+}
+
+func applyFlatSetCookies(original string, setCookies []string, now time.Time) (string, bool) {
+ values := protocol.TransCookies(original)
+ changed := false
+ for _, raw := range setCookies {
+ parsed, err := http.ParseSetCookie(raw)
+ if err != nil || strings.TrimSpace(parsed.Name) == "" {
+ continue
+ }
+ changed = true
+ if parsed.MaxAge < 0 || (parsed.MaxAge == 0 && !parsed.Expires.IsZero() && !parsed.Expires.After(now)) {
+ delete(values, parsed.Name)
+ continue
+ }
+ values[parsed.Name] = parsed.Value
+ }
+ if !changed {
+ return original, false
+ }
+ return cookierefresh.MarshalCookieString(values), true
+}
+
+// absorbMTopResponseCookies applies response cookies before body reads. Without
+// an authoritative session it preserves the historical flat-cookie fallback.
+func absorbMTopResponseCookies(ctx context.Context, fallback string, resp *http.Response) string {
+ if resp == nil {
+ return fallback
+ }
+ if session := cookieSessionFromContext(ctx); session != nil {
+ setCookies := resp.Header.Values("Set-Cookie")
+ if len(setCookies) == 0 {
+ return fallback
+ }
+ requestURL := ""
+ if resp.Request != nil && resp.Request.URL != nil {
+ requestURL = resp.Request.URL.String()
+ }
+ return session.absorb(requestURL, setCookies)
+ }
+ return mergeSetCookie(fallback, protocol.TransCookies(fallback), resp)
+}
diff --git a/internal/xianyu/mtop/cookie_session_test.go b/internal/xianyu/mtop/cookie_session_test.go
new file mode 100644
index 0000000..3c6a936
--- /dev/null
+++ b/internal/xianyu/mtop/cookie_session_test.go
@@ -0,0 +1,312 @@
+package mtop
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "xianyu-go/internal/xianyu/cookierefresh"
+ "xianyu-go/internal/xianyu/protocol"
+)
+
+type cookieSessionRoundTripFunc func(*http.Request) (*http.Response, error)
+
+func (fn cookieSessionRoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
+ return fn(req)
+}
+
+func TestMTopRequestCookiesSeparatesDocumentAndRequestScopes(t *testing.T) {
+ snapshot := []cookierefresh.BrowserCookie{
+ {Name: "_m_h5_tk", Value: "token_1", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "doc_only", Value: "doc", Domain: "www.goofish.com", Path: "/im", Secure: true},
+ {Name: "api_only", Value: "api", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
+ {Name: "partitioned", Value: "part", Domain: ".goofish.com", Path: "/", Secure: true, PartitionKey: goofishTopSite},
+ {Name: "foreign_partition", Value: "no", Domain: ".goofish.com", Path: "/", Secure: true, PartitionKey: "https://example.com"},
+ }
+ ctx, _ := WithCookieSnapshot(context.Background(), snapshot)
+ signing, request := mtopRequestCookies(ctx, "fallback=1", mtopDocumentURL, TokenAPI)
+ for _, want := range []string{"_m_h5_tk=token_1", "doc_only=doc", "partitioned=part"} {
+ if !strings.Contains(signing, want) {
+ t.Fatalf("document cookies %q missing %q", signing, want)
+ }
+ }
+ for _, unwanted := range []string{"api_only=", "foreign_partition="} {
+ if strings.Contains(signing, unwanted) {
+ t.Fatalf("document cookies %q unexpectedly contain %q", signing, unwanted)
+ }
+ }
+ for _, want := range []string{"_m_h5_tk=token_1", "api_only=api", "partitioned=part"} {
+ if !strings.Contains(request, want) {
+ t.Fatalf("request cookies %q missing %q", request, want)
+ }
+ }
+ for _, unwanted := range []string{"doc_only=", "foreign_partition="} {
+ if strings.Contains(request, unwanted) {
+ t.Fatalf("request cookies %q unexpectedly contain %q", request, unwanted)
+ }
+ }
+}
+
+func TestCookieSessionAbsorbsScopedSetCookieAndDeletion(t *testing.T) {
+ snapshot := []cookierefresh.BrowserCookie{
+ {Name: "same", Value: "root", Domain: ".goofish.com", Path: "/"},
+ {Name: "same", Value: "api-old", Domain: "h5api.m.goofish.com", Path: "/h5"},
+ }
+ _, session := WithCookieSnapshot(context.Background(), snapshot)
+ requestURL, err := url.Parse(TokenAPI)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp := &http.Response{
+ Request: &http.Request{URL: requestURL},
+ Header: http.Header{"Set-Cookie": {
+ "same=api-new; Path=/h5; Secure",
+ "partitioned=value; Path=/; Secure; SameSite=None; Partitioned",
+ }},
+ }
+ session.absorb(requestURL.String(), resp.Header.Values("Set-Cookie"))
+ _, got, changed := session.State()
+ if !changed {
+ t.Fatal("Set-Cookie must mark session changed")
+ }
+ values := make(map[string]string)
+ for _, cookie := range got {
+ values[cookie.Name+"|"+cookie.Domain+"|"+cookie.Path+"|"+cookie.PartitionKey] = cookie.Value
+ }
+ if values["same|.goofish.com|/|"] != "root" {
+ t.Fatalf("root same-name cookie changed: %+v", got)
+ }
+ if values["same|h5api.m.goofish.com|/h5|"] != "api-new" {
+ t.Fatalf("host/path cookie not updated precisely: %+v", got)
+ }
+ if values["partitioned|h5api.m.goofish.com|/|"+goofishTopSite] != "value" {
+ t.Fatalf("partitioned cookie missing top-level key: %+v", got)
+ }
+
+ session.absorb(requestURL.String(), []string{"same=; Max-Age=-1; Path=/h5"})
+ _, got, _ = session.State()
+ for _, cookie := range got {
+ if cookie.Name == "same" && cookie.Domain == "h5api.m.goofish.com" && cookie.Path == "/h5" {
+ t.Fatalf("scoped deletion was not applied: %+v", got)
+ }
+ }
+}
+
+func TestCookieSessionAuthoritativeEmptyJar(t *testing.T) {
+ ctx, session := WithCookieSnapshot(context.Background(), nil)
+ signing, request := mtopRequestCookies(ctx, "fallback=must-not-leak", mtopDocumentURL, TokenAPI)
+ if signing != "" || request != "" {
+ t.Fatalf("authoritative empty jar leaked fallback: signing=%q request=%q", signing, request)
+ }
+ canonical, snapshot, changed := session.State()
+ if canonical != "" || snapshot == nil || len(snapshot) != 0 || changed {
+ t.Fatalf("empty state canonical=%q snapshot=%#v changed=%v", canonical, snapshot, changed)
+ }
+}
+
+func TestFlatCookieSessionCapturesUpdatesWithoutInventingSnapshot(t *testing.T) {
+ ctx, session := WithFlatCookieSession(context.Background(), "sid=old; keep=1")
+ signing, request := mtopRequestCookies(ctx, "fallback=must-not-leak", mtopDocumentURL, TokenAPI)
+ if signing != "sid=old; keep=1" || request != signing {
+ t.Fatalf("legacy flat session signing=%q request=%q", signing, request)
+ }
+ session.absorb(TokenAPI, []string{
+ "sid=new; Domain=.goofish.com; Path=/; Secure",
+ "keep=; Max-Age=0; Domain=.goofish.com; Path=/; Secure",
+ })
+ value, snapshot, changed := session.State()
+ if !changed || snapshot != nil || value != "sid=new" {
+ t.Fatalf("flat update value=%q snapshot=%#v changed=%v", value, snapshot, changed)
+ }
+}
+
+func TestScopedCookieHeaderForRequestIncludesMatchingPartitionAndUnpartitioned(t *testing.T) {
+ snapshot := []cookierefresh.BrowserCookie{
+ {Name: "plain", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "part", Value: "2", Domain: ".goofish.com", Path: "/", Secure: true, PartitionKey: goofishTopSite},
+ {Name: "other", Value: "3", Domain: ".goofish.com", Path: "/", Secure: true, PartitionKey: "https://example.com"},
+ }
+ header, ok := cookierefresh.ScopedCookieHeaderForRequest(snapshot, TokenAPI, goofishTopSite, time.Now())
+ if !ok || !strings.Contains(header, "plain=1") || !strings.Contains(header, "part=2") || strings.Contains(header, "other=3") {
+ t.Fatalf("partition-scoped header=%q ok=%v", header, ok)
+ }
+}
+
+func TestLoginStatusUsesDocumentSigningAndURLScopedRequestCookies(t *testing.T) {
+ snapshot := []cookierefresh.BrowserCookie{
+ {Name: "_m_h5_tk", Value: "im-token_1", Domain: "www.goofish.com", Path: "/im", Secure: true},
+ {Name: "_m_h5_tk", Value: "root-token_1", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "document_only", Value: "visible", Domain: "www.goofish.com", Path: "/im", Secure: true},
+ {Name: "api_http_only", Value: "secret", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
+ }
+ ctx, session := WithCookieSnapshot(context.Background(), snapshot)
+ client := &ClientImpl{HTTPClient: &http.Client{Transport: cookieSessionRoundTripFunc(func(req *http.Request) (*http.Response, error) {
+ requestCookies := req.Header.Get("Cookie")
+ for _, want := range []string{"_m_h5_tk=root-token_1", "unb=123", "api_http_only=secret"} {
+ if !strings.Contains(requestCookies, want) {
+ t.Errorf("URL scoped Cookie %q missing %q", requestCookies, want)
+ }
+ }
+ for _, unwanted := range []string{"document_only=", "fallback_only="} {
+ if strings.Contains(requestCookies, unwanted) {
+ t.Errorf("URL scoped Cookie %q unexpectedly contains %q", requestCookies, unwanted)
+ }
+ }
+ if got := req.Header.Get("Referer"); got != mtopDocumentURL {
+ t.Errorf("Referer=%q want %q", got, mtopDocumentURL)
+ }
+ timestamp := req.URL.Query().Get("t")
+ wantSign := protocol.GenerateSign(timestamp, "im-token", `{}`)
+ if got := req.URL.Query().Get("sign"); got != wantSign {
+ t.Errorf("sign=%q want %q", got, wantSign)
+ }
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Set-Cookie": {
+ "_m_h5_tk=rotated-token_9; Domain=.goofish.com; Path=/; Secure",
+ }},
+ Body: io.NopCloser(strings.NewReader("not-json")),
+ Request: req,
+ }, nil
+ })}}
+
+ _, err := client.CheckLoginStatusContext(ctx, "_m_h5_tk=fallback_1; fallback_only=leak")
+ if err == nil || !strings.Contains(err.Error(), "解析 loginuser.get 响应失败") {
+ t.Fatalf("err=%v", err)
+ }
+ canonical, gotSnapshot, changed := session.State()
+ if !changed || !strings.Contains(canonical, "_m_h5_tk=rotated-token_9") {
+ t.Fatalf("response Cookie was not absorbed before body parse: canonical=%q changed=%v snapshot=%+v", canonical, changed, gotSnapshot)
+ }
+}
+
+func TestOrderDetailUsesOrderDocumentForSigningAndReferer(t *testing.T) {
+ snapshot := []cookierefresh.BrowserCookie{
+ {Name: "_m_h5_tk", Value: "order-token_1", Domain: "www.goofish.com", Path: "/order-detail", Secure: true},
+ {Name: "_m_h5_tk", Value: "root-token_1", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
+ }
+ ctx, _ := WithCookieSnapshot(context.Background(), snapshot)
+ client := &ClientImpl{HTTPClient: &http.Client{Transport: cookieSessionRoundTripFunc(func(req *http.Request) (*http.Response, error) {
+ if got := req.Header.Get("Referer"); got != "https://www.goofish.com/order-detail?orderId=order-1&role=seller" {
+ t.Errorf("Referer=%q", got)
+ }
+ if got := req.Header.Get("Cookie"); !strings.Contains(got, "_m_h5_tk=root-token_1") || strings.Contains(got, "order-token_1") {
+ t.Errorf("request Cookie=%q", got)
+ }
+ timestamp := req.URL.Query().Get("t")
+ wantSign := protocol.GenerateSign(timestamp, "order-token", `{"tid":"order-1"}`)
+ if got := req.URL.Query().Get("sign"); got != wantSign {
+ t.Errorf("sign=%q want %q", got, wantSign)
+ }
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: make(http.Header),
+ Body: io.NopCloser(strings.NewReader(`{"ret":["SUCCESS::调用成功"],"data":{"components":[]}}`)),
+ Request: req,
+ }, nil
+ })}}
+ if _, err := client.FetchOrderDetail(ctx, "fallback=must-not-leak", "order-1"); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestPublishWorkflowUsesCookieSessionForEveryRequest(t *testing.T) {
+ snapshot := []cookierefresh.BrowserCookie{
+ {Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "_m_h5_tk", Value: "token0_1", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "document_only", Value: "visible", Domain: "www.goofish.com", Path: "/im", Secure: true},
+ {Name: "api_http_only", Value: "api", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
+ {Name: "upload_http_only", Value: "upload", Domain: "stream-upload.goofish.com", Path: "/api", Secure: true, HTTPOnly: true},
+ }
+ ctx, session := WithCookieSnapshot(context.Background(), snapshot)
+ requestCount := 0
+ assertCookies := func(req *http.Request, token, scoped string) {
+ t.Helper()
+ requestCount++
+ cookieHeader := req.Header.Get("Cookie")
+ for _, want := range []string{"unb=123", "_m_h5_tk=" + token + "_1", scoped} {
+ if !strings.Contains(cookieHeader, want) {
+ t.Errorf("%s Cookie %q missing %q", req.URL.Host, cookieHeader, want)
+ }
+ }
+ for _, unwanted := range []string{"document_only=", "fallback_only="} {
+ if strings.Contains(cookieHeader, unwanted) {
+ t.Errorf("%s Cookie %q unexpectedly contains %q", req.URL.Host, cookieHeader, unwanted)
+ }
+ }
+ }
+ assertSign := func(req *http.Request, token string) {
+ t.Helper()
+ body, err := io.ReadAll(req.Body)
+ if err != nil {
+ t.Errorf("read request body: %v", err)
+ return
+ }
+ form, err := url.ParseQuery(string(body))
+ if err != nil {
+ t.Errorf("parse request body: %v", err)
+ return
+ }
+ timestamp := req.URL.Query().Get("t")
+ want := protocol.GenerateSign(timestamp, token, form.Get("data"))
+ if got := req.URL.Query().Get("sign"); got != want {
+ t.Errorf("%s sign=%q want %q", req.URL.Query().Get("api"), got, want)
+ }
+ }
+ rotate := func(w http.ResponseWriter, value string) {
+ w.Header().Add("Set-Cookie", "_m_h5_tk="+value+"_1; Domain=.goofish.com; Path=/; Secure")
+ }
+
+ dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
+ "_upload": func(w http.ResponseWriter, req *http.Request) {
+ assertCookies(req, "token0", "upload_http_only=upload")
+ if strings.Contains(req.Header.Get("Cookie"), "api_http_only=") {
+ t.Errorf("upload request leaked h5api cookie: %q", req.Header.Get("Cookie"))
+ }
+ rotate(w, "token1")
+ fmt.Fprint(w, `{"object":{"url":"https://cdn/a.jpg","pix":"1x1"}}`)
+ },
+ "mtop.taobao.idle.kgraph.property.recommend": func(w http.ResponseWriter, req *http.Request) {
+ assertCookies(req, "token1", "api_http_only=api")
+ assertSign(req, "token1")
+ rotate(w, "token2")
+ fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"c1","catName":"类目"}}}`)
+ },
+ "mtop.taobao.idle.local.poi.get": func(w http.ResponseWriter, req *http.Request) {
+ assertCookies(req, "token2", "api_http_only=api")
+ assertSign(req, "token2")
+ rotate(w, "token3")
+ fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"area":"X","city":"Y","divisionId":"1","longitude":118.7,"latitude":31.9,"poiId":"p1","poi":"P","prov":"Z"}]}}`)
+ },
+ "mtop.idle.pc.idleitem.publish": func(w http.ResponseWriter, req *http.Request) {
+ assertCookies(req, "token3", "api_http_only=api")
+ assertSign(req, "token3")
+ rotate(w, "token4")
+ fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"new-item"}}`)
+ },
+ }}
+ client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
+ result, err := client.PublishItem(ctx, "_m_h5_tk=fallback_1; fallback_only=leak", PublishItemRequest{
+ Title: "T",
+ PriceCents: 100,
+ Quantity: 1,
+ Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: tinyPNG(t)}},
+ })
+ if err != nil {
+ t.Fatalf("PublishItem: %v", err)
+ }
+ if requestCount != 4 || result.ItemID != "new-item" || !strings.Contains(result.UpdatedCookies, "_m_h5_tk=token4_1") {
+ t.Fatalf("requests=%d result=%+v", requestCount, result)
+ }
+ canonical, _, changed := session.State()
+ if !changed || !strings.Contains(canonical, "_m_h5_tk=token4_1") {
+ t.Fatalf("final session canonical=%q changed=%v", canonical, changed)
+ }
+}
diff --git a/internal/xianyu/mtop/item_detail.go b/internal/xianyu/mtop/item_detail.go
new file mode 100644
index 0000000..4c9d30d
--- /dev/null
+++ b/internal/xianyu/mtop/item_detail.go
@@ -0,0 +1,142 @@
+// Package mtop: 商品详情域 — 补充商品列表未返回的多规格信息。
+package mtop
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "xianyu-go/internal/xianyu/protocol"
+)
+
+// ItemDetailFetcher 是商品同步使用的可选详情能力。
+type ItemDetailFetcher interface {
+ DetectItemMultiSpec(ctx context.Context, cookies, itemID string) (bool, error)
+}
+
+var _ ItemDetailFetcher = (*ClientImpl)(nil)
+
+// DetectItemMultiSpec 查询商品详情并识别多规格结构。该调用不主动刷新 token;
+// 当 ctx 携带 CookieSession 时会像浏览器一样吸收响应 Cookie。
+func (c *ClientImpl) DetectItemMultiSpec(ctx context.Context, cookies, itemID string) (bool, error) {
+ itemID = strings.TrimSpace(itemID)
+ if itemID == "" {
+ return false, fmt.Errorf("item_id 不能为空")
+ }
+ endpoint := c.ItemDetailURL
+ if endpoint == "" {
+ endpoint = ItemDetailAPI
+ }
+ documentURL := "https://www.goofish.com/item?id=" + url.QueryEscape(itemID)
+ signingCookies, requestCookies := mtopRequestCookies(ctx, cookies, documentURL, endpoint)
+ token := protocol.SignToken(signingCookies)
+ if token == "" {
+ return false, fmt.Errorf("cookie 缺少 _m_h5_tk,无法获取商品详情")
+ }
+ dataVal := `{"itemId":` + strconv.Quote(itemID) + `}`
+ timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10)
+ sign := protocol.GenerateSign(timestamp, token, dataVal)
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+buildItemDetailQuery(timestamp, sign), strings.NewReader("data="+url.QueryEscape(dataVal)))
+ if err != nil {
+ return false, err
+ }
+ setCommonHeaders(req, requestCookies)
+ req.Header.Set("Origin", "https://www.goofish.com")
+ req.Header.Set("Referer", documentURL)
+
+ hc := c.HTTPClient
+ if hc == nil {
+ hc = &http.Client{Timeout: 30 * time.Second}
+ }
+ resp, err := hc.Do(req)
+ if err != nil {
+ return false, fmt.Errorf("商品详情请求失败: %w", err)
+ }
+ defer resp.Body.Close()
+ absorbMTopResponseCookies(ctx, cookies, resp)
+ raw, err := readMTopBody(resp)
+ if err != nil {
+ return false, err
+ }
+ var decoded struct {
+ Ret []string `json:"ret"`
+ Data map[string]any `json:"data"`
+ }
+ if err := json.Unmarshal(raw, &decoded); err != nil {
+ return false, fmt.Errorf("解析商品详情响应失败: %w (body=%s)", err, truncate(string(raw), 300))
+ }
+ if !hasMTopSuccess(decoded.Ret) {
+ return false, fmt.Errorf("商品详情接口返回非成功: ret=%v", decoded.Ret)
+ }
+ return detectItemMultiSpec(decoded.Data), nil
+}
+
+func buildItemDetailQuery(timestamp, sign string) string {
+ values := url.Values{
+ "jsv": {"2.7.2"},
+ "appKey": {protocol.SignAppKey},
+ "t": {timestamp},
+ "sign": {sign},
+ "v": {"1.0"},
+ "type": {"originaljson"},
+ "accountSite": {"xianyu"},
+ "dataType": {"json"},
+ "timeout": {"20000"},
+ "api": {"mtop.taobao.idle.pc.detail"},
+ "sessionOption": {"AutoLoginOnly"},
+ "spm_cnt": {"a21ybx.item.0.0"},
+ }
+ return values.Encode()
+}
+
+func detectItemMultiSpec(value any) bool {
+ return detectMultiSpecValue(value, false, 0)
+}
+
+func detectMultiSpecValue(value any, skuContext bool, depth int) bool {
+ if depth > 16 {
+ return false
+ }
+ switch typed := value.(type) {
+ case map[string]any:
+ for key, child := range typed {
+ normalized := strings.ToLower(strings.NewReplacer("_", "", "-", "").Replace(key))
+ switch normalized {
+ case "multisku", "ismultisku", "ismultispec", "multiplesku":
+ if mtopBool(child) {
+ return true
+ }
+ case "skulist", "skus":
+ if list, ok := child.([]any); ok && len(list) > 1 {
+ return true
+ }
+ case "skuprops", "skuproperties", "specprops", "specifications":
+ if list, ok := child.([]any); ok && len(list) > 0 {
+ return true
+ }
+ case "props", "properties":
+ if skuContext {
+ if list, ok := child.([]any); ok && len(list) > 0 {
+ return true
+ }
+ }
+ }
+ nextSKUContext := skuContext || normalized == "skudo" || normalized == "skubase" || normalized == "skumodel"
+ if detectMultiSpecValue(child, nextSKUContext, depth+1) {
+ return true
+ }
+ }
+ case []any:
+ for _, child := range typed {
+ if detectMultiSpecValue(child, skuContext, depth+1) {
+ return true
+ }
+ }
+ }
+ return false
+}
diff --git a/internal/xianyu/mtop/item_detail_test.go b/internal/xianyu/mtop/item_detail_test.go
new file mode 100644
index 0000000..8989566
--- /dev/null
+++ b/internal/xianyu/mtop/item_detail_test.go
@@ -0,0 +1,58 @@
+package mtop
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+)
+
+func TestDetectItemMultiSpec(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Query().Get("api") != "mtop.taobao.idle.pc.detail" {
+ t.Errorf("query=%s", r.URL.RawQuery)
+ }
+ rawBody, _ := io.ReadAll(r.Body)
+ form, _ := url.ParseQuery(string(rawBody))
+ if form.Get("data") != `{"itemId":"item-1"}` {
+ t.Errorf("data=%q", form.Get("data"))
+ }
+ _, _ = io.WriteString(w, `{"ret":["SUCCESS::调用成功"],"data":{"skuDO":{"skuProperties":[{"name":"颜色"}],"skuList":[{"id":"1"},{"id":"2"}]}}}`)
+ }))
+ defer server.Close()
+ client := &ClientImpl{HTTPClient: server.Client(), ItemDetailURL: server.URL}
+ got, err := client.DetectItemMultiSpec(context.Background(), "_m_h5_tk=token_1", "item-1")
+ if err != nil || !got {
+ t.Fatalf("got=%v err=%v", got, err)
+ }
+}
+
+func TestDetectItemMultiSpecSignals(t *testing.T) {
+ cases := []struct {
+ name string
+ data any
+ want bool
+ }{
+ {name: "explicit", data: map[string]any{"multiSKU": true}, want: true},
+ {name: "two skus", data: map[string]any{"skuList": []any{1, 2}}, want: true},
+ {name: "sku props", data: map[string]any{"skuDO": map[string]any{"props": []any{"颜色"}}}, want: true},
+ {name: "single", data: map[string]any{"multiSKU": false, "skuList": []any{1}}, want: false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := detectItemMultiSpec(tc.data); got != tc.want {
+ t.Fatalf("got=%v want=%v", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestDetectItemMultiSpecRejectsMissingToken(t *testing.T) {
+ client := &ClientImpl{}
+ if _, err := client.DetectItemMultiSpec(context.Background(), "unb=1", "item-1"); err == nil || !strings.Contains(err.Error(), "_m_h5_tk") {
+ t.Fatalf("err=%v", err)
+ }
+}
diff --git a/internal/xianyu/mtop/items.go b/internal/xianyu/mtop/items.go
index e587dd5..5acae54 100644
--- a/internal/xianyu/mtop/items.go
+++ b/internal/xianyu/mtop/items.go
@@ -23,6 +23,9 @@ func (c *ClientImpl) FetchItemsPage(ctx context.Context, cookiesStr string, page
pageSize = 20
}
currentCookies := cookiesStr
+ if session := cookieSessionFromContext(ctx); session != nil {
+ currentCookies, _, _ = session.State()
+ }
var lastRet []string
for attempt := 0; attempt < 4; attempt++ {
res, ret, updatedCookies, err := c.fetchItemsPageOnce(ctx, currentCookies, pageNumber, pageSize)
@@ -46,7 +49,7 @@ func (c *ClientImpl) FetchItemsPage(ctx context.Context, cookiesStr string, page
if err := sleepCtx(ctx, MTopRetryGap); err != nil {
return nil, err
}
- refreshed, err := c.RefreshToken(currentCookies)
+ refreshed, err := c.RefreshTokenContext(ctx, currentCookies)
if err != nil {
return nil, fmt.Errorf("刷新 mtop token 失败: %w", err)
}
@@ -60,7 +63,8 @@ func (c *ClientImpl) fetchItemsPageOnce(ctx context.Context, cookiesStr string,
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
- cookies := protocol.TransCookies(cookiesStr)
+ signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", ItemListAPI)
+ cookies := protocol.TransCookies(signingCookies)
userID := cookies["unb"]
if userID == "" {
return nil, nil, cookiesStr, fmt.Errorf("cookie 缺少 unb 字段,无法获取商品列表")
@@ -78,7 +82,7 @@ func (c *ClientImpl) fetchItemsPageOnce(ctx context.Context, cookiesStr string,
rawData, _ := json.Marshal(data)
dataVal := string(rawData)
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
- sign := protocol.GenerateSign(t, protocol.SignToken(cookiesStr), dataVal)
+ sign := protocol.GenerateSign(t, protocol.SignToken(signingCookies), dataVal)
query := buildItemListQuery(t, sign)
body := "data=" + url.QueryEscape(dataVal)
@@ -86,17 +90,17 @@ func (c *ClientImpl) fetchItemsPageOnce(ctx context.Context, cookiesStr string,
if err != nil {
return nil, nil, cookiesStr, err
}
- setCommonHeaders(req, cookiesStr)
+ setCommonHeaders(req, requestCookies)
resp, err := hc.Do(req)
if err != nil {
return nil, nil, cookiesStr, fmt.Errorf("商品列表请求失败: %w", err)
}
defer resp.Body.Close()
+ updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
raw, err := readMTopBody(resp)
if err != nil {
- return nil, nil, cookiesStr, err
+ return nil, nil, updated, err
}
- updated := mergeSetCookie(cookiesStr, cookies, resp)
var decoded struct {
Ret []string `json:"ret"`
@@ -126,6 +130,9 @@ func (c *ClientImpl) FetchAllItems(ctx context.Context, cookiesStr string, pageS
pageSize = 20
}
currentCookies := cookiesStr
+ if session := cookieSessionFromContext(ctx); session != nil {
+ currentCookies, _, _ = session.State()
+ }
page := 1
var all []ItemListItem
for maxPages <= 0 || page <= maxPages {
@@ -237,6 +244,7 @@ func parseItemList(data map[string]any) []ItemListItem {
ItemDetail: string(detailJSON),
AuctionType: mtopString(cardData["auctionType"]),
ItemStatus: mtopInt(cardData["itemStatus"]),
+ IsMultiSpec: detectItemMultiSpec(cardData),
})
}
return items
diff --git a/internal/xianyu/mtop/login_status.go b/internal/xianyu/mtop/login_status.go
index 7d480d0..ea4a67e 100644
--- a/internal/xianyu/mtop/login_status.go
+++ b/internal/xianyu/mtop/login_status.go
@@ -35,34 +35,39 @@ type LoginStatusResult struct {
// CheckLoginStatusContext 调用 loginuser.get 做低成本登录态检查。
// 它不会做浏览器动作;只负责分类响应和合并 Set-Cookie。
func (c *ClientImpl) CheckLoginStatusContext(ctx context.Context, cookiesStr string) (*LoginStatusResult, error) {
+ if session := cookieSessionFromContext(ctx); session != nil {
+ cookiesStr, _, _ = session.State()
+ }
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 20 * time.Second}
}
- t := strconv.FormatInt(time.Now().UnixMilli(), 10)
- dataVal := `{}`
- query := buildLoginStatusQuery(t, protocol.GenerateSign(t, protocol.SignToken(cookiesStr), dataVal))
-
loginURL := c.LoginUserURL
if loginURL == "" {
loginURL = LoginUserAPI
}
+ signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, mtopDocumentURL, loginURL)
+ t := strconv.FormatInt(time.Now().UnixMilli(), 10)
+ dataVal := `{}`
+ query := buildLoginStatusQuery(t, protocol.GenerateSign(t, protocol.SignToken(signingCookies), dataVal))
+
req, err := http.NewRequestWithContext(ctx, http.MethodPost, loginURL+"?"+query, strings.NewReader("data=%7B%7D"))
if err != nil {
return nil, err
}
- setCommonHeaders(req, cookiesStr)
+ setCommonHeaders(req, requestCookies)
+ req.Header.Set("Referer", mtopDocumentURL)
resp, err := hc.Do(req)
if err != nil {
return nil, fmt.Errorf("loginuser.get 请求失败: %w", err)
}
defer resp.Body.Close()
+ updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
raw, err := readMTopBody(resp)
if err != nil {
return nil, err
}
- updated := mergeSetCookie(cookiesStr, protocol.TransCookies(cookiesStr), resp)
var payload struct {
Ret []string `json:"ret"`
diff --git a/internal/xianyu/mtop/order_detail.go b/internal/xianyu/mtop/order_detail.go
index 7d8c847..fe955af 100644
--- a/internal/xianyu/mtop/order_detail.go
+++ b/internal/xianyu/mtop/order_detail.go
@@ -27,6 +27,9 @@ type OrderDetailResult struct {
// FetchOrderDetail 获取订单真实成交价、数量、状态和规格;token 过期时自动重签重试。
func (c *ClientImpl) FetchOrderDetail(ctx context.Context, cookiesStr, orderID string) (*OrderDetailResult, error) {
currentCookies := cookiesStr
+ if session := cookieSessionFromContext(ctx); session != nil {
+ currentCookies, _, _ = session.State()
+ }
var lastRet []string
for attempt := 0; attempt < 4; attempt++ {
previousCookies := currentCookies
@@ -67,29 +70,31 @@ func (c *ClientImpl) fetchOrderDetailOnce(ctx context.Context, cookiesStr, order
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
- cookies := protocol.TransCookies(cookiesStr)
- t := strconv.FormatInt(time.Now().UnixMilli(), 10)
- dataVal := `{"tid":"` + orderID + `"}`
- sign := protocol.GenerateSign(t, protocol.SignToken(cookiesStr), dataVal)
endpoint := c.OrderDetailURL
if endpoint == "" {
endpoint = OrderDetailAPI
}
+ documentURL := "https://www.goofish.com/order-detail?orderId=" + url.QueryEscape(orderID) + "&role=seller"
+ signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, documentURL, endpoint)
+ t := strconv.FormatInt(time.Now().UnixMilli(), 10)
+ dataVal := `{"tid":"` + orderID + `"}`
+ sign := protocol.GenerateSign(t, protocol.SignToken(signingCookies), dataVal)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+buildOrderDetailQuery(t, sign), strings.NewReader("data="+url.QueryEscape(dataVal)))
if err != nil {
return nil, nil, cookiesStr, err
}
- setCommonHeaders(req, cookiesStr)
+ setCommonHeaders(req, requestCookies)
+ req.Header.Set("Referer", documentURL)
resp, err := hc.Do(req)
if err != nil {
return nil, nil, cookiesStr, fmt.Errorf("订单详情请求失败: %w", err)
}
defer resp.Body.Close()
+ updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
raw, err := readMTopBody(resp)
if err != nil {
- return nil, nil, cookiesStr, err
+ return nil, nil, updated, err
}
- updated := mergeSetCookie(cookiesStr, cookies, resp)
var decoded struct {
Ret []string `json:"ret"`
Data map[string]any `json:"data"`
diff --git a/internal/xianyu/mtop/publish.go b/internal/xianyu/mtop/publish.go
index 82e4101..64693b3 100644
--- a/internal/xianyu/mtop/publish.go
+++ b/internal/xianyu/mtop/publish.go
@@ -110,6 +110,9 @@ func (c *ClientImpl) PublishItem(ctx context.Context, cookiesStr string, req Pub
return nil, errors.New("商品图片最多 9 张")
}
currentCookies := cookiesStr
+ if session := cookieSessionFromContext(ctx); session != nil {
+ currentCookies, _, _ = session.State()
+ }
uploaded := make([]uploadedImage, 0, len(req.Images))
for _, img := range req.Images {
res, updated, err := c.uploadPublishImage(ctx, currentCookies, img)
@@ -174,19 +177,20 @@ func (c *ClientImpl) uploadPublishImage(ctx context.Context, cookiesStr string,
if err != nil {
return uploadedImage{}, cookiesStr, err
}
+ _, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", u.String())
req.Header.Set("content-type", mw.FormDataContentType())
- setBrowserHeaders(req, cookiesStr)
+ setBrowserHeaders(req, requestCookies)
req.Header.Set("accept", "*/*")
resp, err := hc.Do(req)
if err != nil {
return uploadedImage{}, cookiesStr, fmt.Errorf("上传商品图片失败: %w", err)
}
defer resp.Body.Close()
+ updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
raw, err := readMTopBody(resp)
if err != nil {
- return uploadedImage{}, cookiesStr, err
+ return uploadedImage{}, updated, err
}
- updated := mergeSetCookie(cookiesStr, protocol.TransCookies(cookiesStr), resp)
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return uploadedImage{}, updated, fmt.Errorf("上传商品图片失败: http=%d body=%s", resp.StatusCode, truncate(string(raw), 240))
}
@@ -349,28 +353,28 @@ func (c *ClientImpl) callMTop(ctx context.Context, cookiesStr, endpoint, api, ve
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
- cookies := protocol.TransCookies(cookiesStr)
rawData, _ := json.Marshal(data)
dataVal := string(rawData)
+ signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", endpoint)
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
- sign := protocol.GenerateSign(t, protocol.SignToken(cookiesStr), dataVal)
+ sign := protocol.GenerateSign(t, protocol.SignToken(signingCookies), dataVal)
query := buildMTopQuery(api, version, t, sign, spmCnt, spmPre, logID)
body := "data=" + url.QueryEscape(dataVal)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+query, strings.NewReader(body))
if err != nil {
return nil, cookiesStr, err
}
- setCommonHeaders(req, cookiesStr)
+ setCommonHeaders(req, requestCookies)
resp, err := hc.Do(req)
if err != nil {
return nil, cookiesStr, fmt.Errorf("%s 请求失败: %w", api, err)
}
defer resp.Body.Close()
+ updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
raw, err := readMTopBody(resp)
if err != nil {
- return nil, cookiesStr, err
+ return nil, updated, err
}
- updated := mergeSetCookie(cookiesStr, cookies, resp)
var decoded map[string]any
if err := json.Unmarshal(raw, &decoded); err != nil {
return nil, updated, fmt.Errorf("解析 %s 响应失败: %w (body=%s)", api, err, truncate(string(raw), 300))
diff --git a/internal/xianyu/mtop/sold_orders.go b/internal/xianyu/mtop/sold_orders.go
new file mode 100644
index 0000000..a21e91f
--- /dev/null
+++ b/internal/xianyu/mtop/sold_orders.go
@@ -0,0 +1,242 @@
+// Package mtop: 卖家订单列表域 — 从卖家工作台发现并解析订单。
+package mtop
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "xianyu-go/internal/xianyu/protocol"
+)
+
+const soldOrdersReferer = "https://seller.goofish.com/?site=COMMONPRO#/seller-trade/order-manage"
+
+// SoldOrderFetcher 是订单同步使用的可选能力,不扩展基础 Client 接口,避免影响其他调用方的 mock。
+type SoldOrderFetcher interface {
+ FetchSoldOrdersPage(ctx context.Context, cookies string, pageNumber, pageSize int) (*SoldOrdersPage, error)
+}
+
+// SoldOrdersPage 是一页卖家订单列表。
+type SoldOrdersPage struct {
+ Items []SoldOrder
+ NextPage bool
+ TotalCount int
+}
+
+// SoldOrder 是订单列表可直接落库的字段。
+type SoldOrder struct {
+ OrderID string
+ ItemID string
+ BuyerID string
+ OrderStatus string
+ Quantity string
+ Amount string
+ ReceiverName string
+ ReceiverPhone string
+ ReceiverAddr string
+ ReceiverCity string
+ IsBargain bool
+ PlatformStatus string
+}
+
+var _ SoldOrderFetcher = (*ClientImpl)(nil)
+
+// FetchSoldOrdersPage 获取卖家已售订单。该调用不主动刷新 token;当 ctx
+// 携带 CookieSession 时会像浏览器一样吸收响应 Cookie。
+func (c *ClientImpl) FetchSoldOrdersPage(ctx context.Context, cookies string, pageNumber, pageSize int) (*SoldOrdersPage, error) {
+ if pageNumber < 1 {
+ pageNumber = 1
+ }
+ if pageSize < 1 || pageSize > 100 {
+ pageSize = 30
+ }
+ endpoint := c.SoldOrdersURL
+ if endpoint == "" {
+ endpoint = SoldOrdersAPI
+ }
+ signingCookies, requestCookies := mtopRequestCookies(ctx, cookies, soldOrdersReferer, endpoint)
+ token := protocol.SignToken(signingCookies)
+ if token == "" {
+ return nil, fmt.Errorf("cookie 缺少 _m_h5_tk,无法获取订单列表")
+ }
+ payload := map[string]any{
+ "pageNumber": pageNumber,
+ "rowsPerPage": pageSize,
+ "orderIds": "",
+ "queryCode": "ALL",
+ "orderSearchParam": "{}",
+ }
+ rawPayload, err := json.Marshal(payload)
+ if err != nil {
+ return nil, err
+ }
+ dataVal := string(rawPayload)
+ timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10)
+ sign := protocol.GenerateSign(timestamp, token, dataVal)
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+buildSoldOrdersQuery(timestamp, sign), strings.NewReader("data="+url.QueryEscape(dataVal)))
+ if err != nil {
+ return nil, err
+ }
+ setCommonHeaders(req, requestCookies)
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("Origin", "https://seller.goofish.com")
+ req.Header.Set("Referer", soldOrdersReferer)
+ req.Header.Set("idle_site_biz_code", "COMMONPRO")
+
+ hc := c.HTTPClient
+ if hc == nil {
+ hc = &http.Client{Timeout: 30 * time.Second}
+ }
+ resp, err := hc.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("订单列表请求失败: %w", err)
+ }
+ defer resp.Body.Close()
+ absorbMTopResponseCookies(ctx, cookies, resp)
+ raw, err := readMTopBody(resp)
+ if err != nil {
+ return nil, err
+ }
+ var decoded struct {
+ Ret []string `json:"ret"`
+ Data struct {
+ Module map[string]any `json:"module"`
+ } `json:"data"`
+ }
+ if err := json.Unmarshal(raw, &decoded); err != nil {
+ return nil, fmt.Errorf("解析订单列表响应失败: %w (body=%s)", err, truncate(string(raw), 300))
+ }
+ if !hasMTopSuccess(decoded.Ret) {
+ return nil, fmt.Errorf("订单列表接口返回非成功: ret=%v", decoded.Ret)
+ }
+ module := decoded.Data.Module
+ rawItems, _ := module["items"].([]any)
+ items := make([]SoldOrder, 0, len(rawItems))
+ for _, rawItem := range rawItems {
+ item, ok := parseSoldOrder(rawItem)
+ if ok {
+ items = append(items, item)
+ }
+ }
+ return &SoldOrdersPage{
+ Items: items,
+ NextPage: mtopBool(module["nextPage"]),
+ TotalCount: mtopInt(module["totalCount"]),
+ }, nil
+}
+
+func buildSoldOrdersQuery(timestamp, sign string) string {
+ values := url.Values{
+ "jsv": {"2.7.2"},
+ "appKey": {protocol.SignAppKey},
+ "t": {timestamp},
+ "sign": {sign},
+ "v": {"1.0"},
+ "type": {"json"},
+ "accountSite": {"xianyu"},
+ "dataType": {"json"},
+ "timeout": {"20000"},
+ "api": {"mtop.taobao.idle.trade.merchant.sold.get"},
+ "valueType": {"string"},
+ "sessionOption": {"AutoLoginOnly"},
+ "spm_cnt": {"a21107h.42831410.0.0"},
+ }
+ return values.Encode()
+}
+
+func parseSoldOrder(raw any) (SoldOrder, bool) {
+ item, ok := raw.(map[string]any)
+ if !ok {
+ return SoldOrder{}, false
+ }
+ common, _ := item["commonData"].(map[string]any)
+ buyer, _ := item["buyerInfoVO"].(map[string]any)
+ price, _ := item["priceVO"].(map[string]any)
+ rights, _ := item["rightVO"].(map[string]any)
+ orderID := strings.TrimSpace(mtopString(common["orderId"]))
+ if orderID == "" {
+ return SoldOrder{}, false
+ }
+ rawStatus := strings.TrimSpace(mtopString(common["orderStatus"]))
+ status := normalizeSoldOrderStatus(rawStatus, mtopBool(common["inRefund"]))
+ amount := firstMTopString(price, "totalPrice", "confirmFee", "auctionPrice")
+ quantity := firstMTopString(price, "buyNum", "quantity")
+ if quantity == "" || quantity == "0" {
+ quantity = "1"
+ }
+ isBargain := false
+ buttons, _ := rights["btnList"].([]any)
+ for _, rawButton := range buttons {
+ button, _ := rawButton.(map[string]any)
+ if strings.EqualFold(mtopString(button["tradeAction"]), "SKIP_PIN") {
+ isBargain = true
+ break
+ }
+ }
+ return SoldOrder{
+ OrderID: orderID,
+ ItemID: strings.TrimSpace(mtopString(common["itemId"])),
+ BuyerID: strings.TrimSpace(mtopString(buyer["buyerId"])),
+ OrderStatus: status,
+ Quantity: quantity,
+ Amount: amount,
+ ReceiverName: firstMTopString(buyer, "name", "receiverName"),
+ ReceiverPhone: firstMTopString(buyer, "phone", "receiverPhone"),
+ ReceiverAddr: firstMTopString(buyer, "address", "receiverAddress"),
+ ReceiverCity: firstMTopString(buyer, "city", "receiverCity"),
+ IsBargain: isBargain,
+ PlatformStatus: rawStatus,
+ }, true
+}
+
+func normalizeSoldOrderStatus(raw string, inRefund bool) string {
+ if inRefund {
+ return "refunding"
+ }
+ switch strings.TrimSpace(raw) {
+ case "待付款", "处理中":
+ return "processing"
+ case "待发货", "已付款":
+ return "pending_ship"
+ case "已发货":
+ return "shipped"
+ case "交易成功", "已完成":
+ return "completed"
+ case "交易关闭", "已关闭", "退款关闭", "退款成功", "已退款":
+ return "cancelled"
+ case "退款中":
+ return "refunding"
+ default:
+ return "unknown"
+ }
+}
+
+func firstMTopString(values map[string]any, keys ...string) string {
+ for _, key := range keys {
+ if value := strings.TrimSpace(mtopString(values[key])); value != "" {
+ return value
+ }
+ }
+ return ""
+}
+
+func mtopBool(value any) bool {
+ switch typed := value.(type) {
+ case bool:
+ return typed
+ case float64:
+ return typed != 0
+ case int:
+ return typed != 0
+ case string:
+ normalized := strings.ToLower(strings.TrimSpace(typed))
+ return normalized == "true" || normalized == "1" || normalized == "yes"
+ default:
+ return false
+ }
+}
diff --git a/internal/xianyu/mtop/sold_orders_test.go b/internal/xianyu/mtop/sold_orders_test.go
new file mode 100644
index 0000000..46672b8
--- /dev/null
+++ b/internal/xianyu/mtop/sold_orders_test.go
@@ -0,0 +1,81 @@
+package mtop
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+)
+
+func TestFetchSoldOrdersPageRequestAndParse(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Query().Get("api") != "mtop.taobao.idle.trade.merchant.sold.get" || r.URL.Query().Get("sign") == "" {
+ t.Errorf("query=%s", r.URL.RawQuery)
+ }
+ if r.Header.Get("Origin") != "https://seller.goofish.com" || r.Header.Get("idle_site_biz_code") != "COMMONPRO" {
+ t.Errorf("headers=%v", r.Header)
+ }
+ rawBody, _ := io.ReadAll(r.Body)
+ form, _ := url.ParseQuery(string(rawBody))
+ var payload map[string]any
+ if err := json.Unmarshal([]byte(form.Get("data")), &payload); err != nil {
+ t.Fatal(err)
+ }
+ if payload["pageNumber"] != float64(2) || payload["rowsPerPage"] != float64(30) || payload["queryCode"] != "ALL" {
+ t.Errorf("payload=%+v", payload)
+ }
+ _, _ = io.WriteString(w, `{"ret":["SUCCESS::调用成功"],"data":{"module":{"nextPage":"true","totalCount":"31","items":[{`+
+ `"commonData":{"orderId":"order-1","itemId":"item-1","orderStatus":"待发货","inRefund":"false"},`+
+ `"buyerInfoVO":{"buyerId":"buyer-1","name":"李四","phone":"13900000000","address":"杭州市"},`+
+ `"priceVO":{"totalPrice":"29.90","buyNum":"3"},"rightVO":{"btnList":[{"tradeAction":"SKIP_PIN"}]}}]}}}`)
+ }))
+ defer server.Close()
+
+ client := &ClientImpl{HTTPClient: server.Client(), SoldOrdersURL: server.URL}
+ page, err := client.FetchSoldOrdersPage(context.Background(), "unb=1; _m_h5_tk=token_1;", 2, 30)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !page.NextPage || page.TotalCount != 31 || len(page.Items) != 1 {
+ t.Fatalf("page=%+v", page)
+ }
+ item := page.Items[0]
+ if item.OrderID != "order-1" || item.ItemID != "item-1" || item.OrderStatus != "pending_ship" ||
+ item.Quantity != "3" || item.Amount != "29.90" || !item.IsBargain || item.ReceiverName != "李四" {
+ t.Fatalf("item=%+v", item)
+ }
+}
+
+func TestFetchSoldOrdersPageRejectsMissingTokenAndFailure(t *testing.T) {
+ client := &ClientImpl{}
+ if _, err := client.FetchSoldOrdersPage(context.Background(), "unb=1", 1, 30); err == nil || !strings.Contains(err.Error(), "_m_h5_tk") {
+ t.Fatalf("err=%v", err)
+ }
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = io.WriteString(w, `{"ret":["FAIL_BIZ_ERROR::失败"]}`)
+ }))
+ defer server.Close()
+ client = &ClientImpl{HTTPClient: server.Client(), SoldOrdersURL: server.URL}
+ if _, err := client.FetchSoldOrdersPage(context.Background(), "_m_h5_tk=token_1", 1, 30); err == nil || !strings.Contains(err.Error(), "非成功") {
+ t.Fatalf("err=%v", err)
+ }
+}
+
+func TestNormalizeSoldOrderStatus(t *testing.T) {
+ cases := map[string]string{
+ "待付款": "processing", "待发货": "pending_ship", "已发货": "shipped",
+ "交易成功": "completed", "退款成功": "cancelled", "退款中": "refunding",
+ }
+ for input, want := range cases {
+ if got := normalizeSoldOrderStatus(input, false); got != want {
+ t.Fatalf("input=%s got=%s want=%s", input, got, want)
+ }
+ }
+ if got := normalizeSoldOrderStatus("待发货", true); got != "refunding" {
+ t.Fatalf("inRefund got=%s", got)
+ }
+}
diff --git a/internal/xianyu/mtop/token.go b/internal/xianyu/mtop/token.go
index a68baa0..995fe88 100644
--- a/internal/xianyu/mtop/token.go
+++ b/internal/xianyu/mtop/token.go
@@ -7,17 +7,21 @@ import (
"fmt"
"net/http"
"net/url"
+ "slices"
+ "sort"
"strconv"
"strings"
"time"
+ "xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/protocol"
)
-const tokenRetryGap = 500 * time.Millisecond
+const officialMTopMaxAttempts = 5
// RefreshToken 调用 mtop.taobao.idlemessage.pc.login.token 获取 accessToken。
-// 遇到 mtop 签名 token 过期时,仅在响应下发了新 Cookie 后低频重试一次。
+// 遇到 mtop 签名 token 过期时,按官网 lib-mtop 2.7.3 的 H5 流程最多执行
+// 5 次请求(含首次),每次先吸收 Go Cookie Jar 再重新签名。
func (c *ClientImpl) RefreshToken(cookiesStr string) (*RefreshResult, error) {
return c.RefreshTokenContext(context.Background(), cookiesStr)
}
@@ -32,49 +36,114 @@ func (c *ClientImpl) RefreshTokenContext(ctx context.Context, cookiesStr string)
// 必须与 /reg.headers.did 完全一致,否则 /reg 会返回
// "device id or appkey is not equal"。
func (c *ClientImpl) RefreshTokenWithDeviceIDContext(ctx context.Context, cookiesStr, deviceID string) (*RefreshResult, error) {
+ return c.RefreshTokenWithCredentialContext(ctx, cookiesStr, deviceID, nil)
+}
+
+// RefreshTokenWithCredentialContext 使用完整 Cookie 快照执行纯 Go HTTP 请求,
+// 避免把不同 Domain/Path 的同名 Cookie 压成一个值。
+func (c *ClientImpl) RefreshTokenWithCredentialContext(ctx context.Context, cookiesStr, deviceID string, cookieSnapshot []cookierefresh.BrowserCookie) (*RefreshResult, error) {
currentCookies := cookiesStr
- for attempt := 0; attempt < 2; attempt++ {
- accessToken, ret, updatedCookies, verificationURL, status, err := c.refreshTokenOnce(ctx, currentCookies, deviceID)
- if err != nil {
- return &RefreshResult{UpdatedCookies: currentCookies}, err
- }
- if accessToken != "" {
- return &RefreshResult{AccessToken: accessToken, UpdatedCookies: updatedCookies}, nil
- }
- if isRiskVerificationRet(ret) {
- return &RefreshResult{UpdatedCookies: updatedCookies}, &RiskVerificationError{Ret: ret, VerificationURL: verificationURL}
- }
- if !isTokenExpiredRet(ret) {
- return &RefreshResult{UpdatedCookies: updatedCookies}, fmt.Errorf("token API 返回非成功: ret=%v (status=%d)", ret, status)
- }
- // 参考实现对 FAIL_SYS_TOKEN_EXOIRED/EXPIRED 固定等待 0.5 秒重试
- // 一次;是否收到 Set-Cookie 不改变重试次数。
- if attempt == 1 {
- return &RefreshResult{UpdatedCookies: updatedCookies}, fmt.Errorf("token API 登录凭证已失效: ret=%v (status=%d)", ret, status)
- }
- if updatedCookies != "" {
+ currentSnapshot := cookierefresh.NormalizeSnapshot(cookieSnapshot)
+ currentSnapshotComplete := cookieSnapshot != nil
+ cookieStateChanged := false
+ if session := cookieSessionFromContext(ctx); session != nil {
+ currentCookies, currentSnapshot, cookieStateChanged = session.State()
+ currentSnapshotComplete = currentSnapshot != nil
+ }
+ for attempt := 0; attempt < officialMTopMaxAttempts; attempt++ {
+ accessToken, expireAt, ret, updatedCookies, snapshot, verificationURL, status, snapshotComplete, attemptChanged, err := c.refreshTokenOnce(ctx, currentCookies, deviceID, currentSnapshot)
+ if updatedCookies != "" || snapshot != nil || attemptChanged {
currentCookies = updatedCookies
}
- if err := sleepCtx(ctx, tokenRetryGap); err != nil {
- return &RefreshResult{UpdatedCookies: currentCookies}, err
+ if snapshotComplete {
+ currentSnapshot = snapshot
+ currentSnapshotComplete = true
+ } else if attemptChanged {
+ // 只有扁平更新时无法把变化安全映射回既有 Domain/Path Jar;
+ // 必须降级为非权威状态。
+ currentSnapshot = nil
+ currentSnapshotComplete = false
+ }
+ cookieStateChanged = cookieStateChanged || attemptChanged
+ if err != nil {
+ return refreshResultFromContext(ctx, currentCookies, currentSnapshot, currentSnapshotComplete, cookieStateChanged), err
+ }
+ if accessToken != "" {
+ result := refreshResultFromContext(ctx, currentCookies, currentSnapshot, currentSnapshotComplete, cookieStateChanged)
+ result.AccessToken = accessToken
+ result.AccessTokenExpireAt = expireAt
+ return result, nil
+ }
+ if isRiskVerificationRet(ret) {
+ return refreshResultFromContext(ctx, currentCookies, currentSnapshot, currentSnapshotComplete, cookieStateChanged), &RiskVerificationError{Ret: ret, VerificationURL: verificationURL}
+ }
+ if !isOfficialTokenRetryRet(ret) {
+ return refreshResultFromContext(ctx, currentCookies, currentSnapshot, currentSnapshotComplete, cookieStateChanged), fmt.Errorf("token API 返回非成功: ret=%v (status=%d)", ret, status)
+ }
+ if attempt == officialMTopMaxAttempts-1 {
+ var snapshotForClear []cookierefresh.BrowserCookie
+ if currentSnapshotComplete {
+ snapshotForClear = currentSnapshot
+ }
+ cleanedCookies, cleanedSnapshot := clearOfficialMTopTokenCookies(currentCookies, snapshotForClear)
+ cookieStateChanged = cookieStateChanged || cleanedCookies != currentCookies || !slices.Equal(cleanedSnapshot, currentSnapshot)
+ currentCookies, currentSnapshot = cleanedCookies, cleanedSnapshot
+ if session := cookieSessionFromContext(ctx); session != nil {
+ if currentSnapshot != nil {
+ session.replace(currentSnapshot)
+ } else {
+ session.replaceFlat(currentCookies)
+ }
+ }
+ return refreshResultFromContext(ctx, currentCookies, currentSnapshot, currentSnapshotComplete, cookieStateChanged), fmt.Errorf("token API 登录凭证已失效: ret=%v (status=%d)", ret, status)
}
}
- return &RefreshResult{UpdatedCookies: currentCookies}, fmt.Errorf("token API 登录凭证已失效")
+ return refreshResultFromContext(ctx, currentCookies, currentSnapshot, currentSnapshotComplete, cookieStateChanged), fmt.Errorf("token API 登录凭证已失效")
+}
+
+func refreshResult(updatedCookies string, snapshot []cookierefresh.BrowserCookie, complete, changed bool) *RefreshResult {
+ if !complete {
+ snapshot = nil
+ }
+ return &RefreshResult{
+ UpdatedCookies: updatedCookies,
+ CookieSnapshot: snapshot,
+ CookieSnapshotComplete: complete,
+ CookieStateChanged: changed,
+ }
+}
+
+func refreshResultFromContext(ctx context.Context, updatedCookies string, snapshot []cookierefresh.BrowserCookie, complete, changed bool) *RefreshResult {
+ if session := cookieSessionFromContext(ctx); session != nil {
+ var sessionChanged bool
+ updatedCookies, snapshot, sessionChanged = session.State()
+ complete = snapshot != nil
+ changed = changed || sessionChanged
+ }
+ return refreshResult(updatedCookies, snapshot, complete, changed)
}
// RequestFreshCaptchaURLContext 重新请求 token API,用于浏览器风控验证前获取新鲜验证链接。
// 如果风控已解除并直接返回 accessToken,则 TokenOK=true。
func (c *ClientImpl) RequestFreshCaptchaURLContext(ctx context.Context, cookiesStr, deviceID string) (*FreshCaptchaResult, error) {
- accessToken, ret, updatedCookies, verificationURL, _, err := c.refreshTokenOnce(ctx, cookiesStr, deviceID)
+ var snapshot []cookierefresh.BrowserCookie
+ if session := cookieSessionFromContext(ctx); session != nil {
+ cookiesStr, snapshot, _ = session.State()
+ }
+ accessToken, expireAt, ret, updatedCookies, _, verificationURL, _, _, _, err := c.refreshTokenOnce(ctx, cookiesStr, deviceID, snapshot)
+ if session := cookieSessionFromContext(ctx); session != nil {
+ updatedCookies, _, _ = session.State()
+ }
if err != nil {
return &FreshCaptchaResult{UpdatedCookies: updatedCookies}, err
}
if accessToken != "" {
return &FreshCaptchaResult{
- TokenOK: true,
- AccessToken: accessToken,
- UpdatedCookies: updatedCookies,
- Ret: ret,
+ TokenOK: true,
+ AccessToken: accessToken,
+ AccessTokenExpireAt: expireAt,
+ UpdatedCookies: updatedCookies,
+ Ret: ret,
}, nil
}
return &FreshCaptchaResult{
@@ -84,21 +153,28 @@ func (c *ClientImpl) RequestFreshCaptchaURLContext(ctx context.Context, cookiesS
}, nil
}
-func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID string) (string, []string, string, string, int, error) {
+func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID string, cookieSnapshot []cookierefresh.BrowserCookie) (string, int64, []string, string, []cookierefresh.BrowserCookie, string, int, bool, bool, error) {
hc := c.HTTPClient
if hc == nil {
- hc = &http.Client{Timeout: 30 * time.Second}
+ hc = &http.Client{Timeout: 20 * time.Second}
}
- cookies := protocol.TransCookies(cookiesStr)
- myid := cookies["unb"]
+ tokenURL := c.TokenURL
+ if tokenURL == "" {
+ tokenURL = TokenAPI
+ }
+ signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, mtopDocumentURL, tokenURL)
+ if cookieSessionFromContext(ctx) == nil && cookieSnapshot != nil {
+ signingCookies, requestCookies = snapshotRequestCookies(cookieSnapshot, cookiesStr, tokenURL)
+ }
+ myid := protocol.TransCookies(signingCookies)["unb"]
if myid == "" {
- return "", nil, cookiesStr, "", 0, fmt.Errorf("cookie 缺少 unb 字段,无法生成 deviceId")
+ return "", 0, nil, cookiesStr, nil, "", 0, false, false, fmt.Errorf("cookie 缺少 unb 字段,无法生成 deviceId")
}
if strings.TrimSpace(deviceID) == "" {
deviceID = protocol.GenerateDeviceID(myid)
}
- token := protocol.SignToken(cookiesStr)
+ token := protocol.SignToken(signingCookies)
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
dataVal := `{"appKey":"` + RegAppKey + `","deviceId":"` + deviceID + `"}`
@@ -108,73 +184,167 @@ func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID
body := "data=" + url.QueryEscape(dataVal)
- tokenURL := c.TokenURL
- if tokenURL == "" {
- tokenURL = TokenAPI
- }
requestURL := tokenURL + "?" + query
var raw []byte
var status int
- updated := cookiesStr
- if c.TokenExecutor != nil {
- browserResp, execErr := c.TokenExecutor.ExecuteTokenRequest(ctx, TokenBrowserRequest{
- URL: requestURL, Body: body, Cookies: cookiesStr,
- })
- if execErr != nil {
- return "", nil, cookiesStr, "", 0, fmt.Errorf("浏览器 token API 请求失败: %w", execErr)
- }
- if browserResp == nil {
- return "", nil, cookiesStr, "", 0, fmt.Errorf("浏览器 token API 返回空响应")
- }
- raw, status = browserResp.Body, browserResp.Status
- if strings.TrimSpace(browserResp.UpdatedCookies) != "" {
- updated = browserResp.UpdatedCookies
- }
- } else {
- req, reqErr := http.NewRequestWithContext(ctx, http.MethodPost, requestURL, strings.NewReader(body))
- if reqErr != nil {
- return "", nil, cookiesStr, "", 0, reqErr
- }
- setCommonHeaders(req, cookiesStr)
- resp, reqErr := hc.Do(req)
- if reqErr != nil {
- return "", nil, cookiesStr, "", 0, fmt.Errorf("token API 请求失败: %w", reqErr)
- }
- defer resp.Body.Close()
- raw, reqErr = readMTopBody(resp)
- if reqErr != nil {
- return "", nil, cookiesStr, "", resp.StatusCode, reqErr
- }
- status = resp.StatusCode
- // 即使业务返回 token 过期,也要保留响应下发的新签名 Cookie。
- updated = mergeSetCookie(cookiesStr, cookies, resp)
+ var updated string
+ var snapshot []cookierefresh.BrowserCookie
+ snapshotComplete := false
+ stateChanged := false
+ req, reqErr := http.NewRequestWithContext(ctx, http.MethodPost, requestURL, strings.NewReader(body))
+ if reqErr != nil {
+ return "", 0, nil, cookiesStr, nil, "", 0, false, false, reqErr
}
+ setCommonHeaders(req, requestCookies)
+ req.Header.Set("Referer", "https://www.goofish.com/im")
+ resp, reqErr := hc.Do(req)
+ if reqErr != nil {
+ return "", 0, nil, cookiesStr, nil, "", 0, false, false, fmt.Errorf("token API 请求失败: %w", reqErr)
+ }
+ defer resp.Body.Close()
+ // Go CookieSession 在读取响应体前应用 Set-Cookie,避免解析失败时丢掉
+ // 服务端已经下发的凭证轮换或删除。
+ if session := cookieSessionFromContext(ctx); session != nil {
+ updated = absorbMTopResponseCookies(ctx, cookiesStr, resp)
+ var sessionChanged bool
+ _, snapshot, sessionChanged = session.State()
+ stateChanged = sessionChanged
+ snapshotComplete = snapshot != nil
+ } else if cookieSnapshot != nil {
+ snapshot = cookierefresh.ApplySetCookies(cookieSnapshot, requestURL, resp.Header.Values("Set-Cookie"), time.Now(), goofishTopSite)
+ updated, _ = cookierefresh.ScopedCookieHeaderForRequest(snapshot, mtopDocumentURL, goofishTopSite, time.Now())
+ stateChanged = !slices.Equal(snapshot, cookierefresh.NormalizeSnapshot(cookieSnapshot))
+ snapshotComplete = true
+ } else {
+ updated = absorbMTopResponseCookies(ctx, cookiesStr, resp)
+ stateChanged = updated != cookiesStr
+ }
+ raw, reqErr = readMTopBody(resp)
+ if reqErr != nil {
+ return "", 0, nil, updated, snapshot, "", resp.StatusCode, snapshotComplete, stateChanged, reqErr
+ }
+ status = resp.StatusCode
var res struct {
Ret []string `json:"ret"`
Data struct {
- AccessToken string `json:"accessToken"`
- URL string `json:"url"`
+ AccessToken string `json:"accessToken"`
+ AccessTokenExpiredTime json.RawMessage `json:"accessTokenExpiredTime"`
+ URL string `json:"url"`
} `json:"data"`
}
if err := json.Unmarshal(raw, &res); err != nil {
- return "", nil, updated, "", status, fmt.Errorf("解析 token 响应失败: %w (body=%s)", err, truncate(string(raw), 300))
+ return "", 0, nil, updated, snapshot, "", status, snapshotComplete, stateChanged, fmt.Errorf("解析 token 响应失败: %w (body=%s)", err, truncate(string(raw), 300))
}
ok := false
for _, r := range res.Ret {
- if strings.Contains(r, "SUCCESS::调用成功") {
+ if strings.Contains(r, "SUCCESS") {
ok = true
break
}
}
if !ok {
- return "", res.Ret, updated, res.Data.URL, status, nil
+ return "", 0, res.Ret, updated, snapshot, res.Data.URL, status, snapshotComplete, stateChanged, nil
}
if res.Data.AccessToken == "" {
- return "", res.Ret, updated, "", status, fmt.Errorf("token API 成功但 accessToken 为空 (body=%s)", truncate(string(raw), 300))
+ return "", 0, res.Ret, updated, snapshot, "", status, snapshotComplete, stateChanged, fmt.Errorf("token API 成功但 accessToken 为空 (body=%s)", truncate(string(raw), 300))
+ }
+ return res.Data.AccessToken, parseAccessTokenExpireAt(res.Data.AccessTokenExpiredTime, time.Now()), res.Ret, updated, snapshot, "", status, snapshotComplete, stateChanged, nil
+}
+
+func snapshotRequestCookies(snapshot []cookierefresh.BrowserCookie, fallback, requestURL string) (string, string) {
+ if snapshot == nil {
+ return fallback, fallback
+ }
+ documentCookies := make([]cookierefresh.BrowserCookie, 0, len(snapshot))
+ for _, cookie := range snapshot {
+ if !cookie.HTTPOnly {
+ documentCookies = append(documentCookies, cookie)
+ }
+ }
+ signing, _ := cookierefresh.ScopedCookieHeaderForRequest(documentCookies, mtopDocumentURL, goofishTopSite, time.Now())
+ requestCookies, _ := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, goofishTopSite, time.Now())
+ return signing, requestCookies
+}
+
+func isOfficialTokenRetryRet(ret []string) bool {
+ for _, value := range ret {
+ if strings.Contains(value, "TOKEN_EMPTY") || strings.Contains(value, "TOKEN_EXOIRED") {
+ return true
+ }
+ }
+ return false
+}
+
+func clearOfficialMTopTokenCookies(cookieStr string, snapshot []cookierefresh.BrowserCookie) (string, []cookierefresh.BrowserCookie) {
+ values := protocol.TransCookies(cookieStr)
+ for _, name := range []string{"_m_h5_c", "_m_h5_tk", "_m_h5_tk_enc"} {
+ delete(values, name)
+ }
+ var cleaned []cookierefresh.BrowserCookie
+ if snapshot != nil {
+ cleaned = make([]cookierefresh.BrowserCookie, 0, len(snapshot))
+ }
+ for _, cookie := range snapshot {
+ domain := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(cookie.Domain), "."))
+ cookiePath := cookie.Path
+ if cookiePath == "" {
+ cookiePath = "/"
+ }
+ remove := cookiePath == "/" && domain == "goofish.com" &&
+ (cookie.Name == "_m_h5_c" || cookie.Name == "_m_h5_tk" || cookie.Name == "_m_h5_tk_enc")
+ remove = remove || (cookiePath == "/" && domain == "m.goofish.com" &&
+ (cookie.Name == "_m_h5_tk" || cookie.Name == "_m_h5_tk_enc"))
+ if !remove {
+ cleaned = append(cleaned, cookie)
+ }
+ }
+ cleaned = cookierefresh.NormalizeSnapshot(cleaned)
+ if snapshot != nil {
+ // 完整 Jar 存在时,扁平兼容值也必须重新按 /im scope 生成;不能用
+ // name map 把仍有效的 Path=/im 同名凭证一并抹掉。
+ canonical, _ := cookierefresh.ScopedCookieHeaderForRequest(cleaned, mtopDocumentURL, goofishTopSite, time.Now())
+ return canonical, cleaned
+ }
+ return marshalTokenCookies(values), cleaned
+}
+
+func marshalTokenCookies(cookies map[string]string) string {
+ keys := make([]string, 0, len(cookies))
+ for key := range cookies {
+ keys = append(keys, key)
+ }
+ sort.Strings(keys)
+ parts := make([]string, 0, len(keys))
+ for _, key := range keys {
+ parts = append(parts, key+"="+cookies[key])
+ }
+ return strings.Join(parts, "; ")
+}
+
+func parseAccessTokenExpireAt(raw json.RawMessage, now time.Time) int64 {
+ value := strings.Trim(strings.TrimSpace(string(raw)), `"`)
+ if value == "" || value == "null" {
+ return 0
+ }
+ if parsed, err := time.Parse(time.RFC3339, value); err == nil {
+ return parsed.Unix()
+ }
+ n, err := strconv.ParseFloat(value, 64)
+ if err != nil || n <= 0 {
+ return 0
+ }
+ switch {
+ case n >= float64(now.UnixMilli()/2):
+ return int64(n / 1000)
+ case n >= float64(now.Unix()/2):
+ return int64(n)
+ case n >= 1_000_000:
+ return now.Add(time.Duration(n) * time.Millisecond).Unix()
+ default:
+ return now.Add(time.Duration(n) * time.Second).Unix()
}
- return res.Data.AccessToken, res.Ret, updated, "", status, nil
}
// buildTokenQuery 构造 token API 的 query string。
@@ -190,15 +360,16 @@ func buildTokenQuery(t, sign string) string {
{"accountSite", "xianyu"},
{"dataType", "json"},
{"timeout", "20000"},
+ {"needLoginPC", "false"},
+ {"showErrorToast", "false"},
{"api", "mtop.taobao.idlemessage.pc.login.token"},
+ {"needLogin", "false"},
{"sessionOption", "AutoLoginOnly"},
+ {"ecode", "0"},
{"dangerouslySetWindvaneParams", "%5Bobject%20Object%5D"},
- {"smToken", "token"},
- {"queryToken", "sm"},
- {"sm", "sm"},
{"spm_cnt", "a21ybx.im.0.0"},
- {"spm_pre", "a21ybx.home.sidebar.1.4c053da6vYwnmf"},
- {"log_id", "4c053da6vYwnmf"},
+ {"spm_pre", ""},
+ {"log_id", ""},
}
var b strings.Builder
for i, p := range parts {
diff --git a/internal/xianyu/mtop/token_test.go b/internal/xianyu/mtop/token_test.go
index 0d20ef5..85705a9 100644
--- a/internal/xianyu/mtop/token_test.go
+++ b/internal/xianyu/mtop/token_test.go
@@ -2,54 +2,66 @@ package mtop
import (
"context"
+ "encoding/json"
"fmt"
+ "io"
"net/http"
"net/http/httptest"
+ "net/url"
"strings"
"sync/atomic"
"testing"
"time"
"xianyu-go/internal/xianyu"
+ "xianyu-go/internal/xianyu/cookierefresh"
+ "xianyu-go/internal/xianyu/protocol"
)
const testCookiesWithUnb = "unb=123; _m_h5_tk=oldtoken_1;"
-type recordingTokenExecutor struct {
- requests []TokenBrowserRequest
- responses []*TokenBrowserResponse
-}
-
-func (e *recordingTokenExecutor) ExecuteTokenRequest(_ context.Context, req TokenBrowserRequest) (*TokenBrowserResponse, error) {
- e.requests = append(e.requests, req)
- if len(e.responses) == 0 {
- return nil, fmt.Errorf("unexpected token request")
+func TestRefreshTokenHTTPUsesCookieSessionScopes(t *testing.T) {
+ initial := []cookierefresh.BrowserCookie{
+ {Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "_m_h5_tk", Value: "document-old_1", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "document_only", Value: "visible", Domain: "www.goofish.com", Path: "/im", Secure: true},
+ {Name: "api_http_only", Value: "secret", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
}
- response := e.responses[0]
- e.responses = e.responses[1:]
- return response, nil
-}
-
-func TestRefreshTokenUsesBrowserExecutor(t *testing.T) {
- executor := &recordingTokenExecutor{responses: []*TokenBrowserResponse{{
- Status: http.StatusOK,
- Body: []byte(`{"ret":["SUCCESS::调用成功"],"data":{"accessToken":"browser-token"}}`),
- UpdatedCookies: testCookiesWithUnb + " x5sec=fresh;",
- }}}
- client := &ClientImpl{TokenExecutor: executor}
- result, err := client.RefreshTokenWithDeviceIDContext(context.Background(), testCookiesWithUnb, "permanent-device")
- if err != nil {
- t.Fatal(err)
+ ctx, session := WithCookieSnapshot(context.Background(), initial)
+ client := &ClientImpl{HTTPClient: &http.Client{Transport: cookieSessionRoundTripFunc(func(req *http.Request) (*http.Response, error) {
+ cookieHeader := req.Header.Get("Cookie")
+ for _, want := range []string{"unb=123", "_m_h5_tk=document-old_1", "api_http_only=secret"} {
+ if !strings.Contains(cookieHeader, want) {
+ t.Errorf("request Cookie %q missing %q", cookieHeader, want)
+ }
+ }
+ for _, unwanted := range []string{"document_only=", "fallback_only="} {
+ if strings.Contains(cookieHeader, unwanted) {
+ t.Errorf("request Cookie %q unexpectedly contains %q", cookieHeader, unwanted)
+ }
+ }
+ timestamp := req.URL.Query().Get("t")
+ dataVal := `{"appKey":"` + RegAppKey + `","deviceId":"did"}`
+ wantSign := protocol.GenerateSign(timestamp, "document-old", dataVal)
+ if got := req.URL.Query().Get("sign"); got != wantSign {
+ t.Errorf("sign=%q want %q", got, wantSign)
+ }
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Set-Cookie": {
+ "_m_h5_tk=document-new_9; Domain=.goofish.com; Path=/; Secure",
+ }},
+ Body: io.NopCloser(strings.NewReader(`{"ret":["SUCCESS::调用成功"],"data":{"accessToken":"direct-context"}}`)),
+ Request: req,
+ }, nil
+ })}}
+ result, err := client.RefreshTokenWithDeviceIDContext(ctx, "unb=fallback; _m_h5_tk=fallback_1; fallback_only=leak", "did")
+ if err != nil || result.AccessToken != "direct-context" {
+ t.Fatalf("result=%+v err=%v", result, err)
}
- if result.AccessToken != "browser-token" || !strings.Contains(result.UpdatedCookies, "x5sec=fresh") {
- t.Fatalf("result=%+v", result)
- }
- if len(executor.requests) != 1 {
- t.Fatalf("browser requests=%d", len(executor.requests))
- }
- req := executor.requests[0]
- if !strings.HasPrefix(req.URL, TokenAPI+"?") || !strings.Contains(req.Body, "permanent-device") || req.Cookies != testCookiesWithUnb {
- t.Fatalf("browser request=%+v", req)
+ canonical, _, changed := session.State()
+ if !changed || !strings.Contains(canonical, "_m_h5_tk=document-new_9") || !strings.Contains(result.UpdatedCookies, "_m_h5_tk=document-new_9") {
+ t.Fatalf("canonical=%q result=%+v changed=%v", canonical, result, changed)
}
}
@@ -177,9 +189,9 @@ func TestRefreshTokenRequestError(t *testing.T) {
}
}
-// TestRefreshTokenExpiredRetNoCookieRetriesOnce: 参考实现即使响应未下发新 Cookie,
-// 也固定等待 0.5 秒重试一次。
-func TestRefreshTokenExpiredRetNoCookieRetriesOnce(t *testing.T) {
+// TestRefreshTokenExpiredRetNoCookieUsesOfficialAttemptLimit: 官网 lib-mtop 即使
+// 响应未下发新 Cookie,也会最多执行五次请求(含首次)。
+func TestRefreshTokenExpiredRetNoCookieUsesOfficialAttemptLimit(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
@@ -193,8 +205,164 @@ func TestRefreshTokenExpiredRetNoCookieRetriesOnce(t *testing.T) {
if err == nil || !strings.Contains(err.Error(), "登录凭证已失效") {
t.Fatalf("err=%v", err)
}
- if requests.Load() != 2 {
- t.Fatalf("requests=%d want 2", requests.Load())
+ if requests.Load() != officialMTopMaxAttempts {
+ t.Fatalf("requests=%d want %d", requests.Load(), officialMTopMaxAttempts)
+ }
+}
+
+func TestRefreshTokenExhaustionClearsOfficialMTopCookies(t *testing.T) {
+ snapshot := []cookierefresh.BrowserCookie{
+ {Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/"},
+ {Name: "keep", Value: "yes", Domain: ".goofish.com", Path: "/"},
+ {Name: "_m_h5_c", Value: "c", Domain: ".goofish.com", Path: "/"},
+ {Name: "_m_h5_tk", Value: "tk", Domain: ".goofish.com", Path: "/"},
+ {Name: "_m_h5_tk_enc", Value: "enc", Domain: ".m.goofish.com", Path: "/"},
+ {Name: "_m_h5_tk", Value: "scoped", Domain: ".goofish.com", Path: "/im"},
+ }
+ var requests atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ requests.Add(1)
+ fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"]}`)
+ }))
+ defer server.Close()
+ ctx, _ := WithCookieSnapshot(context.Background(), snapshot)
+ result, err := (&ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}).RefreshTokenWithCredentialContext(
+ ctx, testCookiesWithUnb, "did", snapshot,
+ )
+ if err == nil || !strings.Contains(err.Error(), "登录凭证已失效") {
+ t.Fatalf("result=%+v err=%v", result, err)
+ }
+ if requests.Load() != officialMTopMaxAttempts {
+ t.Fatalf("requests=%d want %d", requests.Load(), officialMTopMaxAttempts)
+ }
+ for _, name := range []string{"_m_h5_c=", "_m_h5_tk_enc="} {
+ if strings.Contains(result.UpdatedCookies, name) {
+ t.Fatalf("官网清理后仍包含 %s: %q", name, result.UpdatedCookies)
+ }
+ }
+ if !strings.Contains(result.UpdatedCookies, "_m_h5_tk=scoped") {
+ t.Fatalf("Path=/im 的同名 token 不应被根路径清理误删: %q", result.UpdatedCookies)
+ }
+ if !strings.Contains(result.UpdatedCookies, "keep=yes") {
+ t.Fatalf("无关 Cookie 被误删: %q", result.UpdatedCookies)
+ }
+ var keptScoped bool
+ for _, cookie := range result.CookieSnapshot {
+ if cookie.Name == "_m_h5_tk" && cookie.Path == "/im" {
+ keptScoped = true
+ }
+ if cookie.Path == "/" && (cookie.Name == "_m_h5_c" || cookie.Name == "_m_h5_tk" || cookie.Name == "_m_h5_tk_enc") {
+ t.Fatalf("官网根路径凭证 Cookie 未清理: %+v", cookie)
+ }
+ }
+ if !keptScoped {
+ t.Fatal("不属于官网清理目标的同名作用域 Cookie 被误删")
+ }
+}
+
+func TestRefreshTokenFlatSessionExhaustionPersistsOfficialCookieClear(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"],"data":{}}`)
+ }))
+ defer server.Close()
+ initial := "unb=123; _m_h5_c=c; _m_h5_tk=oldtoken_1; _m_h5_tk_enc=enc; keep=yes"
+ ctx, session := WithFlatCookieSession(context.Background(), initial)
+ result, err := (&ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}).RefreshTokenContext(ctx, initial)
+ if err == nil || !strings.Contains(err.Error(), "登录凭证已失效") {
+ t.Fatalf("result=%+v err=%v", result, err)
+ }
+ for _, removed := range []string{"_m_h5_c=", "_m_h5_tk=", "_m_h5_tk_enc="} {
+ if strings.Contains(result.UpdatedCookies, removed) {
+ t.Fatalf("legacy flat 清理结果仍包含 %s: %q", removed, result.UpdatedCookies)
+ }
+ }
+ if !strings.Contains(result.UpdatedCookies, "unb=123") || !strings.Contains(result.UpdatedCookies, "keep=yes") || !result.CookieStateChanged {
+ t.Fatalf("result=%+v", result)
+ }
+ value, snapshot, changed := session.State()
+ if !changed || snapshot != nil || value != result.UpdatedCookies {
+ t.Fatalf("session value=%q snapshot=%+v changed=%v result=%+v", value, snapshot, changed, result)
+ }
+}
+
+func TestRefreshTokenKeepsAccumulatedSnapshotWhenLaterAttemptFails(t *testing.T) {
+ var calls atomic.Int32
+ client := &ClientImpl{HTTPClient: &http.Client{Transport: cookieSessionRoundTripFunc(func(req *http.Request) (*http.Response, error) {
+ if calls.Add(1) == 1 {
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Set-Cookie": {
+ "off_im=rotated; Domain=.goofish.com; Path=/account; Secure; HttpOnly",
+ }},
+ Body: io.NopCloser(strings.NewReader(`{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"],"data":{}}`)),
+ Request: req,
+ }, nil
+ }
+ return nil, fmt.Errorf("second attempt network failure")
+ })}}
+ snapshot := []cookierefresh.BrowserCookie{
+ {Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "_m_h5_tk", Value: "oldtoken_1", Domain: ".goofish.com", Path: "/", Secure: true},
+ }
+ result, err := client.RefreshTokenWithCredentialContext(context.Background(), testCookiesWithUnb, "did", snapshot)
+ if err == nil || !strings.Contains(err.Error(), "network failure") {
+ t.Fatalf("result=%+v err=%v", result, err)
+ }
+ if !result.CookieSnapshotComplete || !result.CookieStateChanged {
+ t.Fatalf("累计 Jar 状态丢失: %+v", result)
+ }
+ var found bool
+ for _, cookie := range result.CookieSnapshot {
+ if cookie.Name == "off_im" && cookie.Value == "rotated" && cookie.Path == "/account" {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("首轮 off-/im Set-Cookie 在后续网络失败后丢失: %+v", result.CookieSnapshot)
+ }
+}
+
+func TestRefreshTokenPreservesExplicitFlatDeletionOnParseError(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Add("Set-Cookie", "unb=; Path=/; Max-Age=0")
+ w.Header().Add("Set-Cookie", "_m_h5_tk=; Path=/; Max-Age=0")
+ _, _ = w.Write([]byte(`not-json`))
+ }))
+ defer server.Close()
+ result, err := (&ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}).RefreshTokenContext(context.Background(), testCookiesWithUnb)
+ if err == nil || !strings.Contains(err.Error(), "解析 token 响应失败") {
+ t.Fatalf("result=%+v err=%v", result, err)
+ }
+ if result.UpdatedCookies != "" || !result.CookieStateChanged || result.CookieSnapshotComplete {
+ t.Fatalf("明确删除到空的 flat Cookie 被恢复: %+v", result)
+ }
+}
+
+func TestRefreshTokenSessionExpiredDoesNotUseTokenRetry(t *testing.T) {
+ var requests atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ requests.Add(1)
+ fmt.Fprint(w, `{"ret":["FAIL_SYS_SESSION_EXPIRED::会话过期"]}`)
+ }))
+ defer server.Close()
+ _, err := (&ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}).RefreshTokenContext(context.Background(), testCookiesWithUnb)
+ if err == nil || requests.Load() != 1 {
+ t.Fatalf("err=%v requests=%d want 1", err, requests.Load())
+ }
+}
+
+func TestBuildTokenQueryMatchesCurrentMessagePageContext(t *testing.T) {
+ query, err := url.ParseQuery(buildTokenQuery("123", "sig"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if query.Get("spm_cnt") != "a21ybx.im.0.0" || query.Get("spm_pre") != "" || query.Get("log_id") != "" {
+ t.Fatalf("spm query=%v", query)
+ }
+ for _, stale := range []string{"smToken", "queryToken", "sm"} {
+ if _, ok := query[stale]; ok {
+ t.Fatalf("官网当前 token 请求不应包含 %s: %v", stale, query)
+ }
}
}
@@ -217,7 +385,7 @@ func TestRefreshTokenUsesReferenceFingerprint(t *testing.T) {
}
}
-// TestRefreshTokenContextCanceled: ctx 取消时 sleepCtx 返回 ctx.Err。
+// TestRefreshTokenContextCanceled: 连续重试期间仍遵守调用方 ctx。
func TestRefreshTokenContextCanceled(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -227,16 +395,18 @@ func TestRefreshTokenContextCanceled(t *testing.T) {
fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"],"data":{}}`)
return
}
- fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"accessToken":"x"}}`)
+ select {
+ case <-r.Context().Done():
+ case <-time.After(time.Second):
+ }
}))
defer server.Close()
client := &ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}
ctx, cancel := context.WithCancel(context.Background())
- // 在第一次请求返回后、sleep 触发前取消
+ // 在第二次请求开始后取消,避免依赖固定重试延迟。
go func() {
- // 等待第一次请求完成
- for requests.Load() < 1 {
+ for requests.Load() < 2 {
time.Sleep(5 * time.Millisecond)
}
cancel()
@@ -267,3 +437,30 @@ func TestRefreshTokenRefreshWrapper(t *testing.T) {
t.Fatalf("AccessToken=%q", result.AccessToken)
}
}
+
+func TestParseAccessTokenExpireAtSupportsOfficialTimestampForms(t *testing.T) {
+ now := time.Unix(1_700_000_000, 0)
+ tests := []struct {
+ name string
+ raw string
+ want int64
+ }{
+ {name: "unix milliseconds", raw: `1700007200000`, want: now.Add(2 * time.Hour).Unix()},
+ {name: "unix seconds string", raw: `"1700007200"`, want: now.Add(2 * time.Hour).Unix()},
+ {name: "relative seconds", raw: `7200`, want: now.Add(2 * time.Hour).Unix()},
+ {name: "relative milliseconds", raw: `7200000`, want: now.Add(2 * time.Hour).Unix()},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := parseAccessTokenExpireAt(json.RawMessage(tt.raw), now); got != tt.want {
+ t.Fatalf("expireAt=%d want=%d", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestParseAccessTokenExpireAtRejectsMissingValue(t *testing.T) {
+ if got := parseAccessTokenExpireAt(nil, time.Now()); got != 0 {
+ t.Fatalf("expireAt=%d want=0", got)
+ }
+}
diff --git a/internal/xianyu/mtop/user_profile.go b/internal/xianyu/mtop/user_profile.go
index 7817bb3..d5dae7c 100644
--- a/internal/xianyu/mtop/user_profile.go
+++ b/internal/xianyu/mtop/user_profile.go
@@ -17,6 +17,9 @@ import (
// FetchUserProfile 获取当前 cookie 对应账号的实时昵称和头像。
func (c *ClientImpl) FetchUserProfile(ctx context.Context, cookiesStr string) (*UserProfileResult, error) {
currentCookies := cookiesStr
+ if session := cookieSessionFromContext(ctx); session != nil {
+ currentCookies, _, _ = session.State()
+ }
var lastRet []string
for attempt := 0; attempt < 4; attempt++ {
res, ret, updatedCookies, err := c.fetchUserProfileOnce(ctx, currentCookies)
@@ -40,7 +43,7 @@ func (c *ClientImpl) FetchUserProfile(ctx context.Context, cookiesStr string) (*
if err := sleepCtx(ctx, MTopRetryGap); err != nil {
return nil, err
}
- refreshed, err := c.RefreshToken(currentCookies)
+ refreshed, err := c.RefreshTokenContext(ctx, currentCookies)
if err != nil {
return nil, fmt.Errorf("刷新 mtop token 失败: %w", err)
}
@@ -55,10 +58,10 @@ func (c *ClientImpl) fetchUserProfileOnce(ctx context.Context, cookiesStr string
hc = &http.Client{Timeout: 30 * time.Second}
}
- cookies := protocol.TransCookies(cookiesStr)
dataVal := "{}"
+ signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", UserPageNavAPI)
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
- sign := protocol.GenerateSign(t, protocol.SignToken(cookiesStr), dataVal)
+ sign := protocol.GenerateSign(t, protocol.SignToken(signingCookies), dataVal)
query := buildUserPageNavQuery(t, sign)
body := "data=" + url.QueryEscape(dataVal)
@@ -66,18 +69,18 @@ func (c *ClientImpl) fetchUserProfileOnce(ctx context.Context, cookiesStr string
if err != nil {
return nil, nil, cookiesStr, err
}
- setCommonHeaders(req, cookiesStr)
+ setCommonHeaders(req, requestCookies)
resp, err := hc.Do(req)
if err != nil {
return nil, nil, cookiesStr, fmt.Errorf("账号资料请求失败: %w", err)
}
defer resp.Body.Close()
+ updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
raw, err := readMTopBody(resp)
if err != nil {
- return nil, nil, cookiesStr, err
+ return nil, nil, updated, err
}
- updated := mergeSetCookie(cookiesStr, cookies, resp)
var decoded struct {
Ret []string `json:"ret"`
diff --git a/internal/xianyu/protocol/cookies.go b/internal/xianyu/protocol/cookies.go
index 4cebed4..dc4e1c9 100644
--- a/internal/xianyu/protocol/cookies.go
+++ b/internal/xianyu/protocol/cookies.go
@@ -9,12 +9,14 @@ func TransCookies(cookiesStr string) map[string]string {
if cookiesStr == "" {
return cookies
}
- for _, part := range strings.Split(cookiesStr, "; ") {
- if eq := strings.Index(part, "="); eq >= 0 {
- k := part[:eq]
- v := part[eq+1:]
- cookies[k] = v
+ for _, part := range strings.Split(cookiesStr, ";") {
+ part = strings.TrimSpace(part)
+ key, value, ok := strings.Cut(part, "=")
+ key = strings.TrimSpace(key)
+ if !ok || key == "" {
+ continue
}
+ cookies[key] = strings.TrimSpace(value)
}
return cookies
}
@@ -22,7 +24,17 @@ func TransCookies(cookiesStr string) map[string]string {
// SignToken 从 cookie 字符串中提取 _m_h5_tk 的前半段,作为 mtop API 签名用的 token。
// _m_h5_tk 形如 "_",取 "_" 前的部分。
func SignToken(cookiesStr string) string {
- v := TransCookies(cookiesStr)["_m_h5_tk"]
+ // 浏览器 Cookie header / document.cookie 会把更长 Path 的同名 Cookie
+ // 排在前面,官网 cookie getter 读取首个匹配项。不能先压成 map 再取值,
+ // 否则同名 token 会被最后一个(通常是更宽作用域)错误覆盖。
+ v := ""
+ for _, part := range strings.Split(cookiesStr, ";") {
+ key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
+ if ok && strings.TrimSpace(key) == "_m_h5_tk" {
+ v = strings.TrimSpace(value)
+ break
+ }
+ }
if v == "" {
return ""
}
diff --git a/internal/xianyu/protocol/cookies_test.go b/internal/xianyu/protocol/cookies_test.go
index e904f79..c41bede 100644
--- a/internal/xianyu/protocol/cookies_test.go
+++ b/internal/xianyu/protocol/cookies_test.go
@@ -22,9 +22,10 @@ func TestTransCookies_Table(t *testing.T) {
{"empty value", "k=", map[string]string{"k": ""}},
{"value with equals sign", "k=a=b=c", map[string]string{"k": "a=b=c"}},
{"url encoded value", "k=" + url.QueryEscape("a b&c=d"), map[string]string{"k": "a+b%26c%3Dd"}},
- {"leading/trailing spaces in value", "k= v ", map[string]string{"k": " v "}},
- {"only separator", "=", map[string]string{"": ""}},
- {"single fragment no space separator", "a=1;b=2", map[string]string{"a": "1;b=2"}},
+ {"leading/trailing spaces in value", "k= v ", map[string]string{"k": "v"}},
+ {"only separator", "=", map[string]string{}},
+ {"single fragment no space separator", "a=1;b=2", map[string]string{"a": "1", "b": "2"}},
+ {"trailing separator", "a=1; b=2;", map[string]string{"a": "1", "b": "2"}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
@@ -68,6 +69,13 @@ func TestSignToken(t *testing.T) {
}
}
+func TestSignTokenUsesFirstScopedDuplicate(t *testing.T) {
+ got := SignToken("_m_h5_tk=narrow_1; other=x; _m_h5_tk=wide_2")
+ if got != "narrow" {
+ t.Fatalf("SignToken duplicate=%q want narrow", got)
+ }
+}
+
// TestSignToken_ConsistentWithTransCookies SignToken 必须基于 TransCookies 的解析结果。
func TestSignToken_ConsistentWithTransCookies(t *testing.T) {
cookies := "x=1; _m_h5_tk=mytoken_999; y=2"
diff --git a/internal/xianyu/qrlogin/client.go b/internal/xianyu/qrlogin/client.go
index 70ae040..ec73fd7 100644
--- a/internal/xianyu/qrlogin/client.go
+++ b/internal/xianyu/qrlogin/client.go
@@ -1,4 +1,4 @@
-// Package qrlogin 实现闲鱼扫码登录;风控验证场景可通过浏览器提取真实 cookie。
+// Package qrlogin 使用纯 Go HTTP 复刻闲鱼扫码登录与人脸验证流程。
package qrlogin
import (
@@ -23,9 +23,15 @@ import (
"xianyu-go/internal/logsafe"
"xianyu-go/internal/xianyu"
+ "xianyu-go/internal/xianyu/cookierefresh"
)
-const maxQRResponseBytes = 2 << 20
+const (
+ maxQRResponseBytes = 2 << 20
+ qrPollInterval = 2 * time.Second
+ maxQRServerErrors = 5
+ qrTopSite = "https://goofish.com"
+)
const (
host = "https://passport.goofish.com"
@@ -54,16 +60,17 @@ var qrHeaders = map[string]string{
type Session struct {
mu sync.RWMutex
SessionID string `json:"session_id"`
- Status string `json:"status"` // waiting/scanned/success/expired/cancelled/verification_required
+ Status string `json:"status"` // waiting/scanned/success/expired/cancelled/error/verification_required
QRCodeURL string `json:"qr_code_url"`
qrContent string
cookies map[string]string
+ cookieSnapshot []cookierefresh.BrowserCookie
unb string
createdTime time.Time
expireTime time.Duration
params map[string]string
verificationURL string
- verificationScreenshot string // 最新截图 data URL,前端轮询时显示
+ verificationScreenshot string // 历史兼容字段;纯 Go 人脸流程直接返回二维码
faceQRURL string // 人脸验证二维码 data URL,优先展示给前端
faceQRContent string // 人脸验证二维码原始内容,便于排查协议变化
}
@@ -77,6 +84,7 @@ func (s *Session) isExpired() bool {
type sessionSnapshot struct {
status string
cookies map[string]string
+ cookieSnapshot []cookierefresh.BrowserCookie
unb string
params map[string]string
verificationURL string
@@ -91,37 +99,19 @@ func (s *Session) snapshot() sessionSnapshot {
defer s.mu.RUnlock()
return sessionSnapshot{
status: s.Status, cookies: cloneCookieMap(s.cookies), unb: s.unb,
- params: cloneCookieMap(s.params), verificationURL: s.verificationURL,
+ cookieSnapshot: cloneCookieSnapshot(s.cookieSnapshot),
+ params: cloneCookieMap(s.params), verificationURL: s.verificationURL,
verificationScreenshot: s.verificationScreenshot, faceQRURL: s.faceQRURL,
expireTime: s.expireTime, createdTime: s.createdTime,
}
}
-// BrowserRefresher 由外部注入的浏览器刷新函数。
-// tmpCookies: 扫码临时 cookie;verificationURL: Chromium 打开后持有 session 等待验证。
-// onScreenshot: 每次截图时回调(data:image/png;base64,...),前端实时显示验证页画面。
-type BrowserRefresher func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (realCookies string, unb string, err error)
-
// Manager 扫码登录管理器。
type Manager struct {
mu sync.Mutex
sessions map[string]*Session
httpc *http.Client
logger *slog.Logger
- browser BrowserRefresher // 可选:风控验证后用浏览器提取真实 cookie
-}
-
-// SetBrowserRefresher 注入浏览器刷新函数(风控验证场景必需)。
-func (m *Manager) SetBrowserRefresher(f BrowserRefresher) {
- m.mu.Lock()
- defer m.mu.Unlock()
- m.browser = f
-}
-
-func (m *Manager) browserRefresher() BrowserRefresher {
- m.mu.Lock()
- defer m.mu.Unlock()
- return m.browser
}
// NewManager 构造。
@@ -143,12 +133,13 @@ func (m *Manager) GenerateQRCode(ctx context.Context) (sessionID string, qrCodeU
return "", "", fmt.Errorf("生成扫码会话 ID: %w", err)
}
sess := &Session{
- SessionID: sessionID,
- Status: "waiting",
- cookies: make(map[string]string),
- createdTime: time.Now(),
- expireTime: 5 * time.Minute,
- params: make(map[string]string),
+ SessionID: sessionID,
+ Status: "waiting",
+ cookies: make(map[string]string),
+ cookieSnapshot: []cookierefresh.BrowserCookie{},
+ createdTime: time.Now(),
+ expireTime: 5 * time.Minute,
+ params: make(map[string]string),
}
// 1. 获取 m_h5_tk。
@@ -170,13 +161,16 @@ func (m *Manager) GenerateQRCode(ctx context.Context) (sessionID string, qrCodeU
}
req.URL.RawQuery = q.Encode()
m.setHeaders(req)
+ if cookieStr := sessionCookieHeader(sess, req.URL.String()); cookieStr != "" {
+ req.Header.Set("Cookie", cookieStr)
+ }
resp, err := m.httpc.Do(req)
if err != nil {
return "", "", fmt.Errorf("请求二维码接口失败: %w", err)
}
defer resp.Body.Close()
- mergeSessionResponseCookies(sess, resp.Cookies())
+ absorbSessionResponse(sess, apiGenerateQR, resp)
body, err := readQRBody(resp.Body)
if err != nil {
return "", "", err
@@ -255,6 +249,7 @@ func (m *Manager) GetSessionStatus(sessionID string) map[string]any {
}
snapshot := sessionSnapshot{
status: sess.Status, cookies: cloneCookieMap(sess.cookies), unb: sess.unb,
+ cookieSnapshot: cloneCookieSnapshot(sess.cookieSnapshot),
verificationURL: sess.verificationURL, verificationScreenshot: sess.verificationScreenshot,
faceQRURL: sess.faceQRURL,
}
@@ -275,8 +270,14 @@ func (m *Manager) GetSessionStatus(sessionID string) map[string]any {
}
}
if snapshot.status == "success" && snapshot.cookies != nil && snapshot.unb != "" {
- result["cookies"] = cookieMarshal(snapshot.cookies)
+ result["cookies"] = snapshotCookieHeader(snapshot, qrVerifyTargetURL)
result["unb"] = snapshot.unb
+ if snapshot.cookieSnapshot != nil {
+ result["cookie_snapshot"] = cloneCookieSnapshot(snapshot.cookieSnapshot)
+ }
+ }
+ if snapshot.status == "error" {
+ result["message"] = "扫码登录接口连续返回异常,请刷新二维码重试"
}
return result
}
@@ -299,6 +300,7 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
maxWait := 5 * time.Minute
start := time.Now()
+ serverErrors := 0
for time.Since(start) < maxWait {
select {
@@ -317,24 +319,25 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
resp, err := m.pollQRCodeStatus(ctx, sess)
if err != nil {
m.logger.Error("轮询扫码状态异常", "err", err)
- if !waitQRRetry(ctx, 2*time.Second) {
+ if !waitQRRetry(ctx, qrPollInterval) {
return
}
continue
}
+ absorbSessionResponse(sess, apiScanStatus, resp)
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
- mergeSessionResponseCookies(sess, resp.Cookies())
closeErr := resp.Body.Close()
if readErr != nil || closeErr != nil {
m.logger.Warn("读取扫码状态响应失败", "read_err", readErr, "close_err", closeErr)
- if !waitQRRetry(ctx, 800*time.Millisecond) {
+ if !waitQRRetry(ctx, qrPollInterval) {
return
}
continue
}
var qrResult struct {
- Content struct {
+ HasError bool `json:"hasError"`
+ Content struct {
Data struct {
QRCodeStatus string `json:"qrCodeStatus"`
IframeRedirect bool `json:"iframeRedirect"`
@@ -344,11 +347,24 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
}
if err := json.Unmarshal(body, &qrResult); err != nil {
m.logger.Warn("解析扫码状态响应失败", "err", err)
- if !waitQRRetry(ctx, 800*time.Millisecond) {
+ if !waitQRRetry(ctx, qrPollInterval) {
return
}
continue
}
+ if qrResult.HasError {
+ serverErrors++
+ if serverErrors >= maxQRServerErrors {
+ sess.mu.Lock()
+ sess.Status = "error"
+ sess.mu.Unlock()
+ m.logger.Warn("扫码登录接口连续返回异常", "session_id", sessionID, "failures", serverErrors)
+ return
+ }
+ // 官网脚本对业务层 hasError 立即重试,最多五次。
+ continue
+ }
+ serverErrors = 0
status := qrResult.Content.Data.QRCodeStatus
switch status {
@@ -364,9 +380,8 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
if sess.Status != "verification_required" {
sess.Status = "verification_required"
sess.verificationURL = qrResult.Content.Data.IframeRedirectURL
- for _, c := range resp.Cookies() {
- sess.cookies[c.Name] = c.Value
- }
+ // 已有权威快照交给可导出的 Go Cookie Jar;它会继续吸收
+ // 人脸跳转链每个重定向响应的 Set-Cookie。
// 人脸验证会额外占用用户手机端操作时间。这里重置窗口,避免普通
// 扫码 5 分钟窗口在用户扫人脸二维码时把会话误标为 expired。
sess.createdTime = time.Now()
@@ -375,12 +390,12 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
expireTime := sess.expireTime
cookieCount := len(sess.cookies)
sess.mu.Unlock()
- m.logger.Warn("扫码登录需要风控验证,交给浏览器保持原登录会话", "session_id", sessionID, "verification_url", logsafe.URL(verURL), "tmp_cookie_count", cookieCount)
+ m.logger.Warn("扫码登录需要风控验证,使用 Go HTTP 保持原登录会话", "session_id", sessionID, "verification_url", logsafe.URL(verURL), "tmp_cookie_count", cookieCount)
// #nosec G118 -- 验证必须跨越轮询请求,且由独立五分钟上下文保证退出。
go func() {
verifyCtx, cancel := context.WithTimeout(context.Background(), expireTime)
defer cancel()
- m.runBrowserVerification(verifyCtx, sessionID, verURL)
+ m.runGoVerification(verifyCtx, sessionID, verURL)
}()
} else {
sess.mu.Unlock()
@@ -389,12 +404,7 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
}
sess.mu.Lock()
sess.Status = "success"
- for _, c := range resp.Cookies() {
- sess.cookies[c.Name] = c.Value
- if c.Name == "unb" {
- sess.unb = c.Value
- }
- }
+ finalizeSessionCredentialsLocked(sess)
unb := sess.unb
sess.mu.Unlock()
m.logger.Info("扫码登录成功", "session_id", sessionID, "account_hash", logsafe.ID(unb))
@@ -414,14 +424,23 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
m.logger.Info("二维码已扫描,等待确认", "session_id", sessionID)
}
sess.mu.Unlock()
- default:
+ case "CANCELED":
sess.mu.Lock()
sess.Status = "cancelled"
sess.mu.Unlock()
m.logger.Info("用户取消登录", "session_id", sessionID)
return
+ case "ERROR":
+ sess.mu.Lock()
+ sess.Status = "error"
+ sess.mu.Unlock()
+ m.logger.Warn("扫码登录接口返回错误状态", "session_id", sessionID)
+ return
+ default:
+ // 官网脚本对未识别状态按普通未扫码状态处理,等待下一轮,
+ // 不能擅自推断成用户取消。
}
- if !waitQRRetry(ctx, 800*time.Millisecond) {
+ if !waitQRRetry(ctx, qrPollInterval) {
return
}
}
@@ -434,74 +453,14 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
sess.mu.Unlock()
}
-func (m *Manager) markSessionExpired(sessionID string) {
- m.mu.Lock()
- sess := m.sessions[sessionID]
- m.mu.Unlock()
- if sess == nil {
+func (m *Manager) runGoVerification(ctx context.Context, sessionID, verificationURL string) {
+ if !strings.Contains(verificationURL, "/iv/") && !strings.Contains(verificationURL, "identity_verify") {
+ m.logger.Warn("扫码验证地址不属于已支持的人脸流程,保持人工验证状态", "session_id", sessionID, "verification_url", logsafe.URL(verificationURL))
return
}
- sess.mu.Lock()
- sess.Status = "expired"
- sess.mu.Unlock()
-}
-
-func (m *Manager) runBrowserVerification(ctx context.Context, sessionID, verificationURL string) {
- if strings.Contains(verificationURL, "/iv/") || strings.Contains(verificationURL, "identity_verify") {
- if err := m.runFaceVerification(ctx, sessionID, verificationURL); err == nil {
- return
- } else {
- m.logger.Warn("扫码人脸验证 HTTP 流程未完成,回退浏览器", "session_id", sessionID, "err", err)
- }
+ if err := m.runFaceVerification(ctx, sessionID, verificationURL); err != nil {
+ m.logger.Warn("扫码人脸验证 Go HTTP 流程未完成,保持人工验证状态", "session_id", sessionID, "err", err)
}
- browser := m.browserRefresher()
- if browser == nil {
- m.logger.Warn("扫码验证需要浏览器支持,保持人工验证状态", "session_id", sessionID)
- return
- }
- m.mu.Lock()
- sess := m.sessions[sessionID]
- m.mu.Unlock()
- if sess == nil {
- return
- }
- state := sess.snapshot()
- realCookies, browserUNB, err := browser(ctx, cookieMarshal(state.cookies), verificationURL, func(dataURL string) {
- m.mu.Lock()
- current := m.sessions[sessionID]
- m.mu.Unlock()
- if current == nil {
- return
- }
- current.mu.Lock()
- current.verificationScreenshot = dataURL
- current.mu.Unlock()
- })
- if err != nil {
- m.logger.Warn("浏览器扫码验证未完成", "session_id", sessionID, "err", err)
- return
- }
- parsed := parseCookieStr(realCookies)
- if browserUNB == "" {
- browserUNB = parsed["unb"]
- }
- if len(parsed) == 0 || browserUNB == "" {
- m.logger.Warn("浏览器扫码验证未返回完整登录凭证", "session_id", sessionID)
- return
- }
- m.mu.Lock()
- sess = m.sessions[sessionID]
- m.mu.Unlock()
- if sess == nil {
- return
- }
- sess.mu.Lock()
- sess.cookies = parsed
- sess.unb = browserUNB
- sess.Status = "success"
- sess.verificationScreenshot = ""
- sess.mu.Unlock()
- m.logger.Info("浏览器扫码验证成功", "session_id", sessionID, "account_hash", logsafe.ID(browserUNB), "cookie_count", len(parsed))
}
func waitQRRetry(ctx context.Context, delay time.Duration) bool {
@@ -515,8 +474,8 @@ func waitQRRetry(ctx context.Context, delay time.Duration) bool {
}
}
-// CompleteVerification 用户完成风控验证后调用:先用扫码临时 cookie 访问 goofish.com/im,
-// 必要时再使用浏览器提取真实 cookie(含 unb)。
+// CompleteVerification 用户完成风控验证后调用。整个凭证换取过程只使用
+// Go Cookie Jar;不得导航浏览器页面或通过 DOM 判断登录状态。
func (m *Manager) CompleteVerification(ctx context.Context, sessionID string) (cookies string, unb string, err error) {
m.mu.Lock()
sess, ok := m.sessions[sessionID]
@@ -529,96 +488,59 @@ func (m *Manager) CompleteVerification(ctx context.Context, sessionID string) (c
return "", "", fmt.Errorf("无扫码临时 cookie")
}
if state.status == "success" && state.unb != "" {
- return cookieMarshal(state.cookies), state.unb, nil
+ return snapshotCookieHeader(state, qrVerifyTargetURL), state.unb, nil
}
- browser := m.browserRefresher()
-
m.logger.Info("开始用临时 cookie 换取真实 cookie", "session_id", sessionID, "tmp_cookie_count", len(state.cookies))
- // 用带 cookie jar 的 client,访问 goofish.com/im 触发真实 cookie 下发。
- jarClient := &http.Client{Timeout: 30 * time.Second}
targetURL := qrVerifyTargetURL
- req, _ := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
- m.setHeaders(req)
- req.Header.Set("Cookie", cookieMarshal(state.cookies))
- // im 页面 referer
- req.Header.Set("Referer", "https://www.goofish.com/")
-
+ seedURL := state.verificationURL
+ if strings.TrimSpace(seedURL) == "" {
+ seedURL = targetURL
+ }
+ jarClient, jar, err := m.faceHTTPClient(state.cookies, state.cookieSnapshot, seedURL, targetURL)
+ if err != nil {
+ return "", "", fmt.Errorf("创建登录 Cookie Jar: %w", err)
+ }
+ jarClient.Timeout = 30 * time.Second
+ target, err := url.Parse(targetURL)
+ if err != nil {
+ return "", "", fmt.Errorf("解析登录凭证换取地址: %w", err)
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, target.String(), nil)
+ if err != nil {
+ return "", "", err
+ }
+ m.setDocumentHeaders(req)
resp, err := jarClient.Do(req)
if err != nil {
- if browser == nil {
- return "", "", fmt.Errorf("访问 goofish.com/im 失败: %w", err)
- }
- m.logger.Warn("纯 HTTP 访问 goofish.com/im 失败,改用浏览器提取", "session_id", sessionID, "err", err)
- } else {
- defer resp.Body.Close()
- if _, err := io.Copy(io.Discard, resp.Body); err != nil {
- return "", "", fmt.Errorf("读取验证响应失败: %w", err)
- }
-
- // 收集 Set-Cookie。
- sess.mu.Lock()
- for _, c := range resp.Cookies() {
- sess.cookies[c.Name] = c.Value
- if c.Name == "unb" {
- sess.unb = c.Value
- }
- }
- sess.mu.Unlock()
+ return "", "", fmt.Errorf("访问 goofish.com/im 换取登录凭证失败: %w", err)
}
-
- // 如果还没 unb 且没有浏览器刷新器,再访问 mtop token API 触发(有时需要额外请求)。
- // 有浏览器刷新器时直接走浏览器路径,避免在风控场景中重复纯 HTTP 请求。
- state = sess.snapshot()
- if state.unb == "" && browser == nil {
- m.logger.Info("首次访问未拿到 unb,尝试 mtop token API", "session_id", sessionID)
- if err := m.getMH5TK(ctx, sess); err != nil {
- m.logger.Warn("mtop token API 失败", "err", err)
- }
+ defer resp.Body.Close()
+ if _, err := io.Copy(io.Discard, resp.Body); err != nil {
+ return "", "", fmt.Errorf("读取登录凭证换取响应失败: %w", err)
}
-
- state = sess.snapshot()
- m.logger.Info("验证完成,提取 cookie", "session_id", sessionID, "cookie_count", len(state.cookies), "has_unb", state.unb != "")
- if state.unb != "" {
- sess.mu.Lock()
- sess.Status = "success"
- sess.mu.Unlock()
- m.logger.Info("纯 HTTP 提取 cookie 成功", "session_id", sessionID, "account_hash", logsafe.ID(state.unb))
- return cookieMarshal(state.cookies), state.unb, nil
+ var responseURL *url.URL
+ if resp.Request != nil {
+ responseURL = resp.Request.URL
}
-
- // 纯 HTTP 拿不到 unb(闲鱼真实 cookie 由页面 JS 异步下发),
- // 风控验证后的 cookie 提取必须依赖浏览器。
- if browser == nil {
- return "", "", fmt.Errorf("风控验证后的 cookie 提取需要浏览器支持(请勿使用 -no-browser 启动)")
- }
-
- m.logger.Info("纯 HTTP 未拿到 unb,调用浏览器提取", "session_id", sessionID)
- realCookies, browserUNB, err := browser(ctx, cookieMarshal(state.cookies), state.verificationURL, nil)
- if err != nil {
- m.logger.Error("浏览器提取失败", "err", err)
- return "", "", fmt.Errorf("浏览器提取 cookie 失败: %w", err)
- }
- parsedCookies := parseCookieStr(realCookies)
- if len(parsedCookies) == 0 {
- return "", "", fmt.Errorf("浏览器提取 cookie 失败: 未返回有效 cookie")
+ finalCookies := collectJarCookies(jar, target, responseURL)
+ finalUNB := finalCookies["unb"]
+ if finalUNB == "" {
+ return "", "", fmt.Errorf("纯 Go 登录凭证换取未获取到 unb,验证可能尚未完成或临时 Cookie 已失效")
}
sess.mu.Lock()
- sess.cookies = parsedCookies
- sess.unb = browserUNB
- if sess.unb == "" {
- sess.unb = sess.cookies["unb"]
- }
- if sess.unb == "" {
- sess.mu.Unlock()
- return "", "", fmt.Errorf("验证后仍未获取到 unb,可能验证未完成或临时 cookie 已失效")
+ sess.cookies = finalCookies
+ if finalSnapshot, complete := jar.Snapshot(); complete {
+ sess.cookieSnapshot = finalSnapshot
+ } else {
+ sess.cookieSnapshot = nil
}
+ sess.unb = finalUNB
sess.Status = "success"
- finalCookies := cloneCookieMap(sess.cookies)
- finalUNB := sess.unb
+ sess.verificationScreenshot = ""
sess.mu.Unlock()
- m.logger.Info("浏览器提取成功", "session_id", sessionID, "account_hash", logsafe.ID(finalUNB), "cookie_count", len(finalCookies))
- return cookieMarshal(finalCookies), finalUNB, nil
+ m.logger.Info("纯 Go 提取登录凭证成功", "session_id", sessionID, "account_hash", logsafe.ID(finalUNB), "cookie_count", len(finalCookies))
+ return snapshotCookieHeader(sess.snapshot(), qrVerifyTargetURL), finalUNB, nil
}
// parseCookieStr 把 "k=v; k2=v2" 解析回 map。
@@ -642,18 +564,11 @@ func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error {
return err
}
defer resp.Body.Close()
+ absorbSessionResponse(sess, apiH5TK, resp)
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
return err
}
-
- // 合并 Set-Cookie。
- sess.mu.Lock()
- for _, c := range resp.Cookies() {
- sess.cookies[c.Name] = c.Value
- }
-
- mH5TK := sess.cookies["_m_h5_tk"]
- sess.mu.Unlock()
+ mH5TK := protocolCookieValue(sessionCookieHeader(sess, apiH5TK), "_m_h5_tk")
token := ""
if parts := strings.SplitN(mH5TK, "_", 2); len(parts) > 0 {
token = parts[0]
@@ -679,9 +594,7 @@ func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error {
req2, _ := http.NewRequestWithContext(ctx, http.MethodPost, apiH5TK+"?"+params.Encode(), nil)
m.setHeaders(req2)
req2.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- sess.mu.RLock()
- cookieStr := cookieMarshal(sess.cookies)
- sess.mu.RUnlock()
+ cookieStr := sessionCookieHeader(sess, req2.URL.String())
if cookieStr != "" {
req2.Header.Set("Cookie", cookieStr)
}
@@ -691,7 +604,7 @@ func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error {
return err
}
defer resp2.Body.Close()
- mergeSessionResponseCookies(sess, resp2.Cookies())
+ absorbSessionResponse(sess, req2.URL.String(), resp2)
if _, err := io.Copy(io.Discard, resp2.Body); err != nil {
return err
}
@@ -718,9 +631,7 @@ func (m *Manager) getLoginParams(ctx context.Context, sess *Session) (map[string
m.setHeaders(req)
// 带上已有 cookie。
- sess.mu.RLock()
- cookieStr := cookieMarshal(sess.cookies)
- sess.mu.RUnlock()
+ cookieStr := sessionCookieHeader(sess, req.URL.String())
if cookieStr != "" {
req.Header.Set("Cookie", cookieStr)
}
@@ -730,7 +641,7 @@ func (m *Manager) getLoginParams(ctx context.Context, sess *Session) (map[string
return nil, err
}
defer resp.Body.Close()
- mergeSessionResponseCookies(sess, resp.Cookies())
+ absorbSessionResponse(sess, req.URL.String(), resp)
body, err := readQRBody(resp.Body)
if err != nil {
return nil, err
@@ -773,11 +684,22 @@ func (m *Manager) pollQRCodeStatus(ctx context.Context, sess *Session) (*http.Re
for k, v := range state.params {
form.Set(k, v)
}
+ fingerprint := xianyu.CurrentBrowserFingerprint()
+ // 对齐 havana-nlogin 二维码组件 query.do 的浏览器环境字段。
+ // ua 是 AWSC/UAB 的可选结果;纯 Go 客户端在该值尚未生成时与官网
+ // 脚本一样发送空值,不借助 Chromium 执行业务页面脚本。
+ form.Set("ua", "")
+ form.Set("navlanguage", "zh-CN")
+ form.Set("navUserAgent", fingerprint.UserAgent)
+ form.Set("navPlatform", navigatorPlatform(fingerprint.Platform))
+ form.Set("isIframe", "true")
+ form.Set("documentReferer", qrVerifyTargetURL)
+ form.Set("defaultView", "qrcode")
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, apiScanStatus, strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
m.setHeaders(req)
- cookieStr := cookieMarshal(state.cookies)
+ cookieStr := sessionCookieHeader(sess, req.URL.String())
if cookieStr != "" {
req.Header.Set("Cookie", cookieStr)
}
@@ -785,6 +707,23 @@ func (m *Manager) pollQRCodeStatus(ctx context.Context, sess *Session) (*http.Re
return m.httpc.Do(req)
}
+func navigatorPlatform(secCHPlatform string) string {
+ switch strings.ToLower(strings.TrimSpace(secCHPlatform)) {
+ case "windows":
+ return "Win32"
+ case "macos":
+ return "MacIntel"
+ case "linux":
+ return "Linux x86_64"
+ case "android":
+ return "Linux armv8l"
+ case "ios":
+ return "iPhone"
+ default:
+ return strings.TrimSpace(secCHPlatform)
+ }
+}
+
func (m *Manager) setHeaders(req *http.Request) {
xianyu.ApplyBrowserFingerprint(req.Header)
for k, v := range qrHeaders {
@@ -792,16 +731,62 @@ func (m *Manager) setHeaders(req *http.Request) {
}
}
-func mergeSessionResponseCookies(sess *Session, cookies []*http.Cookie) {
- if sess == nil || len(cookies) == 0 {
+// setDocumentHeaders 复刻浏览器从闲鱼首页进入 /im 的文档请求头。这里只
+// 发送 HTTP 请求并接收 Set-Cookie,不加载或校验任何页面 DOM。
+func (m *Manager) setDocumentHeaders(req *http.Request) {
+ xianyu.ApplyBrowserFingerprint(req.Header)
+ req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
+ req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
+ req.Header.Set("Referer", "https://www.goofish.com/")
+ req.Header.Set("Sec-Fetch-Dest", "document")
+ req.Header.Set("Sec-Fetch-Mode", "navigate")
+ req.Header.Set("Sec-Fetch-Site", "same-origin")
+ req.Header.Set("Upgrade-Insecure-Requests", "1")
+}
+
+func sessionCookieHeader(sess *Session, requestURL string) string {
+ if sess == nil {
+ return ""
+ }
+ return snapshotCookieHeader(sess.snapshot(), requestURL)
+}
+
+func snapshotCookieHeader(state sessionSnapshot, requestURL string) string {
+ if state.cookieSnapshot != nil {
+ if value, authoritative := cookierefresh.ScopedCookieHeaderForRequest(
+ state.cookieSnapshot, requestURL, qrTopSite, time.Now(),
+ ); authoritative {
+ return value
+ }
+ }
+ return cookieMarshal(state.cookies)
+}
+
+func absorbSessionResponse(sess *Session, requestURL string, resp *http.Response) {
+ if sess == nil || resp == nil {
return
}
sess.mu.Lock()
defer sess.mu.Unlock()
- for _, cookie := range cookies {
+ if sess.cookieSnapshot != nil {
+ sess.cookieSnapshot = cookierefresh.ApplySetCookies(
+ sess.cookieSnapshot, requestURL, resp.Header.Values("Set-Cookie"), time.Now(), qrTopSite,
+ )
+ if sess.cookieSnapshot == nil {
+ sess.cookieSnapshot = []cookierefresh.BrowserCookie{}
+ }
+ }
+ for _, cookie := range resp.Cookies() {
if cookie == nil || cookie.Name == "" {
continue
}
+ if cookie.MaxAge < 0 || (!cookie.Expires.IsZero() && !cookie.Expires.After(time.Now())) {
+ delete(sess.cookies, cookie.Name)
+ if cookie.Name == "unb" {
+ sess.unb = ""
+ }
+ continue
+ }
sess.cookies[cookie.Name] = cookie.Value
if cookie.Name == "unb" && cookie.Value != "" {
sess.unb = cookie.Value
@@ -809,6 +794,42 @@ func mergeSessionResponseCookies(sess *Session, cookies []*http.Cookie) {
}
}
+func finalizeSessionCredentialsLocked(sess *Session) {
+ if sess == nil {
+ return
+ }
+ if sess.cookieSnapshot != nil {
+ value, _ := cookierefresh.ScopedCookieHeaderForRequest(
+ sess.cookieSnapshot, qrVerifyTargetURL, qrTopSite, time.Now(),
+ )
+ sess.cookies = parseCookieStr(value)
+ }
+ if unb := sess.cookies["unb"]; unb != "" {
+ sess.unb = unb
+ }
+}
+
+func cloneCookieSnapshot(in []cookierefresh.BrowserCookie) []cookierefresh.BrowserCookie {
+ if in == nil {
+ return nil
+ }
+ out := cookierefresh.NormalizeSnapshot(in)
+ if out == nil {
+ return []cookierefresh.BrowserCookie{}
+ }
+ return out
+}
+
+func protocolCookieValue(cookieHeader, name string) string {
+ for _, part := range strings.Split(cookieHeader, ";") {
+ key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
+ if ok && key == name {
+ return value
+ }
+ }
+ return ""
+}
+
// ---- 工具函数 ----
func md5hex(s string) string {
diff --git a/internal/xianyu/qrlogin/client_test.go b/internal/xianyu/qrlogin/client_test.go
index 042b05f..b7dc415 100644
--- a/internal/xianyu/qrlogin/client_test.go
+++ b/internal/xianyu/qrlogin/client_test.go
@@ -13,6 +13,8 @@ import (
"sync"
"testing"
"time"
+
+ "xianyu-go/internal/xianyu/cookierefresh"
)
type failingReader struct{}
@@ -54,7 +56,7 @@ func TestSessionStatusConcurrentSnapshot(t *testing.T) {
wg.Wait()
}
-func TestCompleteVerificationRequiresBrowserWhenHTTPMissingUNB(t *testing.T) {
+func TestCompleteVerificationRequiresPureGoCredentialResult(t *testing.T) {
m := NewManager(nil)
m.sessions["s1"] = testVerificationSession()
oldTarget := qrVerifyTargetURL
@@ -62,7 +64,7 @@ func TestCompleteVerificationRequiresBrowserWhenHTTPMissingUNB(t *testing.T) {
defer func() { qrVerifyTargetURL = oldTarget }()
_, _, err := m.CompleteVerification(context.Background(), "s1")
- if err == nil || !strings.Contains(err.Error(), "需要浏览器支持") {
+ if err == nil || !strings.Contains(err.Error(), "纯 Go 登录凭证换取未获取到 unb") {
t.Fatalf("错误异常: %v", err)
}
}
@@ -81,50 +83,6 @@ func TestCompleteVerificationReturnsCompletedSessionWithoutAnotherRequest(t *tes
}
}
-func TestCompleteVerificationBrowserSuccess(t *testing.T) {
- m := NewManager(nil)
- m.sessions["s1"] = testVerificationSession()
- m.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
- if !strings.Contains(tmpCookies, "tmp=1") {
- t.Fatalf("浏览器刷新器收到临时 cookie 异常: %q", tmpCookies)
- }
- return "unb=999; cookie2=abc", "999", nil
- })
- oldTarget := qrVerifyTargetURL
- qrVerifyTargetURL = newEmptyCookieServer(t)
- defer func() { qrVerifyTargetURL = oldTarget }()
-
- cookies, unb, err := m.CompleteVerification(context.Background(), "s1")
- if err != nil {
- t.Fatalf("CompleteVerification: %v", err)
- }
- if unb != "999" || !strings.Contains(cookies, "unb=999") {
- t.Fatalf("返回异常: cookies=%q unb=%q", cookies, unb)
- }
- if m.sessions["s1"].Status != "success" {
- t.Fatalf("状态异常: %s", m.sessions["s1"].Status)
- }
-}
-
-func TestCompleteVerificationBrowserUNBFromCookieMap(t *testing.T) {
- m := NewManager(nil)
- m.sessions["s1"] = testVerificationSession()
- m.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
- return "unb=888; cookie2=abc", "", nil
- })
- oldTarget := qrVerifyTargetURL
- qrVerifyTargetURL = newEmptyCookieServer(t)
- defer func() { qrVerifyTargetURL = oldTarget }()
-
- _, unb, err := m.CompleteVerification(context.Background(), "s1")
- if err != nil {
- t.Fatalf("CompleteVerification: %v", err)
- }
- if unb != "888" {
- t.Fatalf("应从 cookie map 提取 unb,got %q", unb)
- }
-}
-
func TestCompleteVerificationMissingSession(t *testing.T) {
m := NewManager(nil)
_, _, err := m.CompleteVerification(context.Background(), "missing")
@@ -203,6 +161,25 @@ func TestCollectJarCookies(t *testing.T) {
}
}
+func TestFaceCookieJarExportsCrossDomainAttributes(t *testing.T) {
+ jar := newFaceCookieJar(map[string]string{"tmp": "1"}, []cookierefresh.BrowserCookie{})
+ passport, _ := url.Parse("https://passport.goofish.com/ivCheckLogin.htm")
+ input := &http.Cookie{
+ Name: "unb", Value: "777", Domain: ".goofish.com", Path: "/", Secure: true, HttpOnly: true,
+ }
+ jar.SetCookies(passport, []*http.Cookie{input})
+ www, _ := url.Parse("https://www.goofish.com/im")
+ got := collectJarCookies(jar, www)
+ if got["unb"] != "777" {
+ snapshot, _ := jar.Snapshot()
+ t.Fatalf("跨域 Cookie 未进入 /im: cookies=%v snapshot=%+v raw=%q", got, snapshot, input.String())
+ }
+ snapshot, complete := jar.Snapshot()
+ if !complete || len(snapshot) != 1 || snapshot[0].Domain != ".goofish.com" || !snapshot[0].HTTPOnly || !snapshot[0].Secure {
+ t.Fatalf("完整 Cookie 属性未保留: complete=%v snapshot=%+v", complete, snapshot)
+ }
+}
+
func testVerificationSession() *Session {
return &Session{
SessionID: "s1",
diff --git a/internal/xianyu/qrlogin/coverage_test.go b/internal/xianyu/qrlogin/coverage_test.go
index a8d4405..4b7efa3 100644
--- a/internal/xianyu/qrlogin/coverage_test.go
+++ b/internal/xianyu/qrlogin/coverage_test.go
@@ -9,6 +9,7 @@ import (
"fmt"
"net/http"
"net/http/httptest"
+ "net/url"
"strings"
"sync"
"sync/atomic"
@@ -16,6 +17,7 @@ import (
"time"
"xianyu-go/internal/xianyu"
+ "xianyu-go/internal/xianyu/cookierefresh"
)
// stubTransport 把所有请求转发到 httptest.Server,保留路径与查询,
@@ -50,6 +52,35 @@ func newStubbedManager(t *testing.T, handler http.Handler) (*Manager, *httptest.
return m, srv, tr
}
+func TestAbsorbSessionResponsePreservesCookieScope(t *testing.T) {
+ sess := &Session{cookies: map[string]string{}, cookieSnapshot: []cookierefresh.BrowserCookie{}}
+ resp := &http.Response{Header: http.Header{
+ "Set-Cookie": {"_m_h5_tk=tok_1; Domain=.goofish.com; Path=/; Secure; HttpOnly"},
+ }}
+ absorbSessionResponse(sess, apiH5TK, resp)
+ if got := sessionCookieHeader(sess, apiGenerateQR); !strings.Contains(got, "_m_h5_tk=tok_1") {
+ t.Fatalf("跨子域 Cookie 作用域丢失: header=%q snapshot=%+v", got, sess.cookieSnapshot)
+ }
+}
+
+func TestAbsorbSessionResponseDeletesExpiredFlatCookie(t *testing.T) {
+ sess := &Session{
+ cookies: map[string]string{"unb": "stale", "keep": "yes"},
+ cookieSnapshot: []cookierefresh.BrowserCookie{},
+ unb: "stale",
+ }
+ resp := &http.Response{Header: http.Header{
+ "Set-Cookie": {"unb=; Domain=.goofish.com; Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT"},
+ }}
+ absorbSessionResponse(sess, apiScanStatus, resp)
+ if _, exists := sess.cookies["unb"]; exists || sess.unb != "" {
+ t.Fatalf("服务端删除 Cookie 后扁平兼容状态仍残留 unb: cookies=%v unb=%q", sess.cookies, sess.unb)
+ }
+ if sess.cookies["keep"] != "yes" {
+ t.Fatalf("删除 unb 时不得丢失无关 Cookie: %v", sess.cookies)
+ }
+}
+
// gzipBody 用 gzip 压缩输入字符串。
func gzipBody(t *testing.T, raw string) []byte {
t.Helper()
@@ -254,9 +285,10 @@ func TestGetLoginParamsEmptyLoginFormData(t *testing.T) {
func TestGenerateQRCodeSuccess(t *testing.T) {
hc := &handlerChain{}
+ var generateCookie string
// getMH5TK 路径
hc.handle("/h5/mtop.gaia.nodejs.gaia.idle.data.gw.v2.index.get/1.0/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "tok_1717"})
+ w.Header().Add("Set-Cookie", "_m_h5_tk=tok_1717; Domain=.goofish.com; Path=/; Secure; HttpOnly")
w.WriteHeader(http.StatusOK)
}))
// getLoginParams 路径
@@ -265,6 +297,7 @@ func TestGenerateQRCodeSuccess(t *testing.T) {
}))
// generate.do 二维码接口
hc.handle("/newlogin/qrcode/generate.do", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ generateCookie = r.Header.Get("Cookie")
resp := map[string]any{
"content": map[string]any{
"success": true,
@@ -304,6 +337,9 @@ func TestGenerateQRCodeSuccess(t *testing.T) {
if sess.qrContent != "https://login/qr?token=xyz" {
t.Fatalf("qrContent 异常: %q", sess.qrContent)
}
+ if !strings.Contains(generateCookie, "_m_h5_tk=tok_1717") {
+ t.Fatalf("生成二维码请求未继承当前 Cookie: %q snapshot=%+v cookies=%v", generateCookie, sess.cookieSnapshot, sess.cookies)
+ }
}
func TestGenerateQRCodeFailureResponse(t *testing.T) {
@@ -406,9 +442,13 @@ func TestGetSessionStatusExpired(t *testing.T) {
func TestGetSessionStatusSuccessWithCookies(t *testing.T) {
m := NewManager(nil)
m.sessions["s"] = &Session{
- SessionID: "s",
- Status: "success",
- cookies: map[string]string{"unb": "u1", "c": "v"},
+ SessionID: "s",
+ Status: "success",
+ cookies: map[string]string{"unb": "u1", "c": "v"},
+ cookieSnapshot: []cookierefresh.BrowserCookie{
+ {Name: "unb", Value: "u1", Domain: ".goofish.com", Path: "/", Secure: true, HTTPOnly: true},
+ {Name: "scoped", Value: "v2", Domain: "www.goofish.com", Path: "/im", Secure: true},
+ },
unb: "u1",
createdTime: time.Now(),
expireTime: 5 * time.Minute,
@@ -424,6 +464,28 @@ func TestGetSessionStatusSuccessWithCookies(t *testing.T) {
if !strings.Contains(cookies, "unb=u1") {
t.Fatalf("cookie 字符串异常: %q", cookies)
}
+ snapshot, ok := got["cookie_snapshot"].([]cookierefresh.BrowserCookie)
+ if !ok || len(snapshot) != 2 {
+ t.Fatalf("成功状态必须返回内部权威 Cookie Jar: ok=%v snapshot=%+v", ok, snapshot)
+ }
+}
+
+func TestGetSessionStatusUsesAuthoritativeScopedCookieHeader(t *testing.T) {
+ m := NewManager(nil)
+ m.sessions["s"] = &Session{
+ SessionID: "s", Status: "success", cookies: map[string]string{"unb": "u1", "same": "flat"}, unb: "u1",
+ cookieSnapshot: []cookierefresh.BrowserCookie{
+ {Name: "unb", Value: "u1", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "same", Value: "im", Domain: "www.goofish.com", Path: "/im", Secure: true},
+ {Name: "same", Value: "root", Domain: ".goofish.com", Path: "/", Secure: true},
+ },
+ createdTime: time.Now(), expireTime: 5 * time.Minute,
+ }
+ got := m.GetSessionStatus("s")
+ cookies, _ := got["cookies"].(string)
+ if strings.Count(cookies, "same=") != 2 || strings.Index(cookies, "same=im") > strings.Index(cookies, "same=root") {
+ t.Fatalf("同名不同 Path Cookie 被扁平化: %q", cookies)
+ }
}
func TestGetSessionStatusVerificationRequired(t *testing.T) {
@@ -627,7 +689,7 @@ func TestMonitorQRStatusExpiredDoesNotKeepPolling(t *testing.T) {
func TestMonitorQRStatusCancelled(t *testing.T) {
hc := &handlerChain{}
- hc.handle("/newlogin/qrcode/query.do", statusHandler("REFUSED"))
+ hc.handle("/newlogin/qrcode/query.do", statusHandler("CANCELED"))
m, _, _ := newStubbedManager(t, hc)
sess := newMonitorSession("waiting")
m.sessions["s"] = sess
@@ -641,6 +703,44 @@ func TestMonitorQRStatusCancelled(t *testing.T) {
}
}
+func TestMonitorQRStatusServerHasErrorStopsAfterFiveImmediateRetries(t *testing.T) {
+ hc := &handlerChain{}
+ var calls atomic.Int64
+ hc.handle("/newlogin/qrcode/query.do", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ _, _ = w.Write([]byte(`{"hasError":true}`))
+ }))
+ m, _, _ := newStubbedManager(t, hc)
+ sess := newMonitorSession("waiting")
+ m.sessions["s"] = sess
+
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ m.monitorQRStatus(ctx, "s")
+
+ if sess.Status != "error" {
+ t.Fatalf("连续业务错误应进入 error 状态: %s", sess.Status)
+ }
+ if got := calls.Load(); got != maxQRServerErrors {
+ t.Fatalf("业务错误重试次数=%d, want %d", got, maxQRServerErrors)
+ }
+}
+
+func TestMonitorQRStatusUnknownStatusKeepsPolling(t *testing.T) {
+ hc := &handlerChain{}
+ hc.handle("/newlogin/qrcode/query.do", statusHandler("FUTURE_STATUS"))
+ m, _, _ := newStubbedManager(t, hc)
+ sess := newMonitorSession("waiting")
+ m.sessions["s"] = sess
+
+ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
+ defer cancel()
+ m.monitorQRStatus(ctx, "s")
+ if sess.Status != "waiting" {
+ t.Fatalf("未知状态不应被推断成取消: %s", sess.Status)
+ }
+}
+
func TestMonitorQRStatusVerificationRequiredStopsPollingAndRunsFaceFlow(t *testing.T) {
hc := &handlerChain{}
var queryCalls atomic.Int64
@@ -669,13 +769,14 @@ func TestMonitorQRStatusVerificationRequiredStopsPollingAndRunsFaceFlow(t *testi
_, _ = w.Write([]byte(`{"content":{"code":3,"url":"https://passport.goofish.com/ivCheckLogin.htm?ok=1"}}`))
}))
hc.handle("/ivCheckLogin.htm", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- http.SetCookie(w, &http.Cookie{Name: "unb", Value: "777", Path: "/"})
- http.SetCookie(w, &http.Cookie{Name: "cookie2", Value: "z", Path: "/"})
+ http.SetCookie(w, &http.Cookie{Name: "unb", Value: "777", Domain: ".goofish.com", Path: "/", Secure: true, HttpOnly: true})
+ http.SetCookie(w, &http.Cookie{Name: "cookie2", Value: "z", Domain: ".goofish.com", Path: "/", Secure: true})
_, _ = w.Write([]byte(`ok`))
}))
m, _, _ := newStubbedManager(t, hc)
sess := newMonitorSession("waiting")
+ sess.cookieSnapshot = []cookierefresh.BrowserCookie{}
m.sessions["s"] = sess
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
@@ -704,6 +805,18 @@ func TestMonitorQRStatusVerificationRequiredStopsPollingAndRunsFaceFlow(t *testi
if state.faceQRURL == "" {
t.Fatal("人脸验证二维码未生成")
}
+ if state.cookieSnapshot == nil {
+ t.Fatal("人脸验证跳转链必须保留权威 Cookie Jar")
+ }
+ var foundUNB bool
+ for _, cookie := range state.cookieSnapshot {
+ if cookie.Name == "unb" && cookie.Value == "777" && cookie.Domain == ".goofish.com" && cookie.HTTPOnly && cookie.Secure {
+ foundUNB = true
+ }
+ }
+ if !foundUNB {
+ t.Fatalf("人脸验证 Cookie 属性丢失: %+v", state.cookieSnapshot)
+ }
}
func TestMonitorQRStatusMissingSession(t *testing.T) {
@@ -784,13 +897,20 @@ func TestMonitorQRStatusSessionDeletedMidLoop(t *testing.T) {
// ---- pollQRCodeStatus ----
func TestPollQRCodeStatusSetsHeadersAndCookie(t *testing.T) {
- xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "playwright-native-ua"})
+ oldFingerprint := xianyu.CurrentBrowserFingerprint()
+ xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "playwright-native-ua", Platform: "macOS"})
+ t.Cleanup(func() { xianyu.SetBrowserFingerprint(oldFingerprint) })
hc := &handlerChain{}
var gotUA, gotCookie, gotCT string
+ var gotForm url.Values
hc.handle("/newlogin/qrcode/query.do", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotUA = r.Header.Get("User-Agent")
gotCookie = r.Header.Get("Cookie")
gotCT = r.Header.Get("Content-Type")
+ if err := r.ParseForm(); err != nil {
+ t.Errorf("ParseForm: %v", err)
+ }
+ gotForm = r.PostForm
_, _ = w.Write([]byte(`{}`))
}))
m, _, _ := newStubbedManager(t, hc)
@@ -811,6 +931,20 @@ func TestPollQRCodeStatusSetsHeadersAndCookie(t *testing.T) {
if gotCT != "application/x-www-form-urlencoded" {
t.Fatalf("Content-Type 异常: %q", gotCT)
}
+ wantForm := map[string]string{
+ "ua": "",
+ "navlanguage": "zh-CN",
+ "navUserAgent": "playwright-native-ua",
+ "navPlatform": "MacIntel",
+ "isIframe": "true",
+ "documentReferer": qrVerifyTargetURL,
+ "defaultView": "qrcode",
+ }
+ for key, want := range wantForm {
+ if got := gotForm.Get(key); got != want {
+ t.Errorf("轮询字段 %s=%q, want %q", key, got, want)
+ }
+ }
}
// ---- gzip 解压(历史坑点)----
@@ -888,74 +1022,47 @@ func TestCompleteVerificationHTTPSuccessWithUNB(t *testing.T) {
}
}
-func TestCompleteVerificationHTTPFailsWithBrowser(t *testing.T) {
- // 用一个会立即失败的 target URL(端口不存在)。
+func TestCompleteVerificationHTTPFailureDoesNotUseBrowser(t *testing.T) {
m := NewManager(nil)
m.sessions["s"] = testVerificationSession()
- m.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
- return "unb=200; c=1", "200", nil
- })
old := qrVerifyTargetURL
qrVerifyTargetURL = "http://127.0.0.1:0/im"
defer func() { qrVerifyTargetURL = old }()
+ _, _, err := m.CompleteVerification(context.Background(), "s")
+ if err == nil || !strings.Contains(err.Error(), "换取登录凭证失败") {
+ t.Fatalf("错误异常: %v", err)
+ }
+}
+
+func TestCompleteVerificationCarriesCookiesAcrossRedirects(t *testing.T) {
+ var srv *httptest.Server
+ srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/start":
+ http.SetCookie(w, &http.Cookie{Name: "redirect_anchor", Value: "1", Path: "/"})
+ http.Redirect(w, r, srv.URL+"/done", http.StatusFound)
+ case "/done":
+ cookie, err := r.Cookie("redirect_anchor")
+ if err != nil || cookie.Value != "1" {
+ t.Fatalf("重定向未携带中间 Cookie: cookie=%v err=%v", cookie, err)
+ }
+ http.SetCookie(w, &http.Cookie{Name: "unb", Value: "redirect-account", Path: "/"})
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ t.Cleanup(srv.Close)
+
+ m := NewManager(nil)
+ m.sessions["s"] = testVerificationSession()
+ old := qrVerifyTargetURL
+ qrVerifyTargetURL = srv.URL + "/start"
+ defer func() { qrVerifyTargetURL = old }()
+
cookies, unb, err := m.CompleteVerification(context.Background(), "s")
- if err != nil {
- t.Fatalf("CompleteVerification: %v", err)
- }
- if unb != "200" {
- t.Fatalf("unb 异常: %q", unb)
- }
- if !strings.Contains(cookies, "unb=200") {
- t.Fatalf("cookies 异常: %q", cookies)
- }
-}
-
-func TestCompleteVerificationBrowserReturnsEmptyCookies(t *testing.T) {
- m := NewManager(nil)
- m.sessions["s"] = testVerificationSession()
- m.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
- return "noequalsign", "", nil // parseCookieStr 解析后为空 map
- })
- old := qrVerifyTargetURL
- qrVerifyTargetURL = newEmptyCookieServer(t)
- defer func() { qrVerifyTargetURL = old }()
-
- _, _, err := m.CompleteVerification(context.Background(), "s")
- if err == nil || !strings.Contains(err.Error(), "未返回有效 cookie") {
- t.Fatalf("错误异常: %v", err)
- }
-}
-
-func TestCompleteVerificationBrowserFails(t *testing.T) {
- m := NewManager(nil)
- m.sessions["s"] = testVerificationSession()
- m.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
- return "", "", errors.New("browser boom")
- })
- old := qrVerifyTargetURL
- qrVerifyTargetURL = newEmptyCookieServer(t)
- defer func() { qrVerifyTargetURL = old }()
-
- _, _, err := m.CompleteVerification(context.Background(), "s")
- if err == nil || !strings.Contains(err.Error(), "浏览器提取 cookie 失败") {
- t.Fatalf("错误异常: %v", err)
- }
-}
-
-func TestCompleteVerificationBrowserNoUNBAnywhere(t *testing.T) {
- m := NewManager(nil)
- m.sessions["s"] = testVerificationSession()
- m.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
- return "cookie2=abc; cookie3=def", "", nil
- })
- old := qrVerifyTargetURL
- qrVerifyTargetURL = newEmptyCookieServer(t)
- defer func() { qrVerifyTargetURL = old }()
-
- _, _, err := m.CompleteVerification(context.Background(), "s")
- if err == nil || !strings.Contains(err.Error(), "仍未获取到 unb") {
- t.Fatalf("错误异常: %v", err)
+ if err != nil || unb != "redirect-account" || !strings.Contains(cookies, "redirect_anchor=1") {
+ t.Fatalf("纯 Go 重定向 Cookie Jar 异常: cookies=%q unb=%q err=%v", cookies, unb, err)
}
}
@@ -1000,25 +1107,6 @@ func TestMd5hex(t *testing.T) {
}
}
-func TestSetBrowserRefresher(t *testing.T) {
- m := NewManager(nil)
- if m.browser != nil {
- t.Fatal("初始 browser 应为 nil")
- }
- called := false
- m.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
- called = true
- return "", "", nil
- })
- if m.browser == nil {
- t.Fatal("browser 未注入")
- }
- _, _, _ = m.browser(context.Background(), "", "", nil)
- if !called {
- t.Fatal("browser 未调用")
- }
-}
-
func TestNewManagerDefaultsLogger(t *testing.T) {
m := NewManager(nil)
if m.logger == nil {
diff --git a/internal/xianyu/qrlogin/face_verification.go b/internal/xianyu/qrlogin/face_verification.go
index e8825a1..d747798 100644
--- a/internal/xianyu/qrlogin/face_verification.go
+++ b/internal/xianyu/qrlogin/face_verification.go
@@ -7,16 +7,17 @@ import (
"fmt"
"html"
"net/http"
- "net/http/cookiejar"
"net/url"
"regexp"
"strconv"
"strings"
+ "sync"
"time"
qrcode "github.com/skip2/go-qrcode"
"xianyu-go/internal/logsafe"
+ "xianyu-go/internal/xianyu/cookierefresh"
)
// runFaceVerification 参照闲鱼浏览器端风控跳转链,纯 HTTP 复现人脸验证流程。
@@ -32,12 +33,13 @@ func (m *Manager) runFaceVerification(ctx context.Context, sessionID, iframeURL
return fmt.Errorf("会话不存在")
}
m.mu.Unlock()
- initialCookies := sess.snapshot().cookies
+ state := sess.snapshot()
+ initialCookies := state.cookies
if len(initialCookies) == 0 {
return fmt.Errorf("无扫码临时 cookie")
}
- client, jar, err := m.faceHTTPClient(initialCookies, iframeURL)
+ client, jar, err := m.faceHTTPClient(initialCookies, state.cookieSnapshot, iframeURL)
if err != nil {
return err
}
@@ -88,15 +90,11 @@ func (m *Manager) runFaceVerification(ctx context.Context, sessionID, iframeURL
return fmt.Errorf("请求 ivCheckLogin: %w", err)
}
- finalCookies := collectJarCookies(jar,
- mustParseURL(host),
- mustParseURL("https://www.goofish.com/"),
- mustParseURL(iframeURL),
- mustParseURL(ivCheckURL),
- )
+ finalCookies := collectJarCookies(jar, mustParseURL(qrVerifyTargetURL))
if finalCookies["unb"] == "" {
return fmt.Errorf("人脸验证完成但未获取到 unb")
}
+ finalSnapshot, snapshotComplete := jar.Snapshot()
m.mu.Lock()
s = m.sessions[sessionID]
@@ -104,6 +102,11 @@ func (m *Manager) runFaceVerification(ctx context.Context, sessionID, iframeURL
if s != nil {
s.mu.Lock()
s.cookies = finalCookies
+ if snapshotComplete {
+ s.cookieSnapshot = finalSnapshot
+ } else {
+ s.cookieSnapshot = nil
+ }
s.unb = finalCookies["unb"]
s.Status = "success"
s.mu.Unlock()
@@ -112,20 +115,112 @@ func (m *Manager) runFaceVerification(ctx context.Context, sessionID, iframeURL
return nil
}
-func (m *Manager) faceHTTPClient(cookies map[string]string, iframeURL string) (*http.Client, http.CookieJar, error) {
- jar, err := cookiejar.New(nil)
- if err != nil {
- return nil, nil, err
- }
- setJarCookies(jar, mustParseURL(host), cookies)
- if u, err := url.Parse(iframeURL); err == nil {
- setJarCookies(jar, u, cookies)
+func (m *Manager) faceHTTPClient(cookies map[string]string, snapshot []cookierefresh.BrowserCookie, seedURLs ...string) (*http.Client, *faceCookieJar, error) {
+ jar := newFaceCookieJar(cookies, snapshot)
+ if snapshot == nil {
+ setJarCookies(jar, mustParseURL(host), cookies)
+ for _, rawURL := range seedURLs {
+ if u, err := url.Parse(rawURL); err == nil {
+ setJarCookies(jar, u, cookies)
+ }
+ }
}
hc := *m.httpc
hc.Jar = jar
return &hc, jar, nil
}
+// faceCookieJar 是人脸验证与登录凭证换取专用的 Go Cookie Jar。标准库
+// cookiejar 能正确发送 Cookie,但没有导出完整 Jar 的接口;这个实现直接以
+// BrowserCookie 为权威状态,使自动重定向中的每个 Set-Cookie 都能原样进入
+// 最终持久化快照。
+type faceCookieJar struct {
+ mu sync.Mutex
+ snapshot []cookierefresh.BrowserCookie
+ authoritative bool
+}
+
+func newFaceCookieJar(cookies map[string]string, snapshot []cookierefresh.BrowserCookie) *faceCookieJar {
+ jar := &faceCookieJar{authoritative: snapshot != nil}
+ if snapshot != nil {
+ jar.snapshot = cookierefresh.NormalizeSnapshot(snapshot)
+ if jar.snapshot == nil {
+ jar.snapshot = []cookierefresh.BrowserCookie{}
+ }
+ return jar
+ }
+ // 只有历史/异常会话才会走这里。推断快照仅用于维持 HTTP 会话,
+ // authoritative=false 保证调用方不会把推断属性持久化成完整 Jar。
+ jar.snapshot = cookierefresh.SnapshotFromCookieString(cookieMarshal(cookies), ".goofish.com")
+ return jar
+}
+
+func (j *faceCookieJar) Cookies(u *url.URL) []*http.Cookie {
+ if j == nil || u == nil {
+ return nil
+ }
+ j.mu.Lock()
+ header, _ := cookierefresh.ScopedCookieHeaderForRequest(j.snapshot, u.String(), qrTopSite, time.Now())
+ j.mu.Unlock()
+ if header == "" {
+ return nil
+ }
+ parts := strings.Split(header, ";")
+ out := make([]*http.Cookie, 0, len(parts))
+ for _, part := range parts {
+ name, value, ok := strings.Cut(strings.TrimSpace(part), "=")
+ if !ok || name == "" {
+ continue
+ }
+ out = append(out, &http.Cookie{Name: name, Value: value})
+ }
+ return out
+}
+
+func (j *faceCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) {
+ if j == nil || u == nil || len(cookies) == 0 {
+ return
+ }
+ raw := make([]string, 0, len(cookies))
+ for _, cookie := range cookies {
+ if cookie == nil || strings.TrimSpace(cookie.Name) == "" {
+ continue
+ }
+ line := strings.TrimSpace(cookie.Raw)
+ if line == "" {
+ line = cookie.String()
+ }
+ if line != "" {
+ raw = append(raw, line)
+ }
+ }
+ if len(raw) == 0 {
+ return
+ }
+ j.mu.Lock()
+ j.snapshot = cookierefresh.ApplySetCookies(j.snapshot, u.String(), raw, time.Now(), qrTopSite)
+ if j.snapshot == nil {
+ j.snapshot = []cookierefresh.BrowserCookie{}
+ }
+ j.mu.Unlock()
+}
+
+func (j *faceCookieJar) Snapshot() ([]cookierefresh.BrowserCookie, bool) {
+ if j == nil {
+ return nil, false
+ }
+ j.mu.Lock()
+ defer j.mu.Unlock()
+ if !j.authoritative {
+ return nil, false
+ }
+ out := cookierefresh.NormalizeSnapshot(j.snapshot)
+ if out == nil {
+ out = []cookierefresh.BrowserCookie{}
+ }
+ return out, true
+}
+
func (m *Manager) faceGetHTML(ctx context.Context, client *http.Client, targetURL, referer string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
if err != nil {
diff --git a/internal/xianyu/renew/service.go b/internal/xianyu/renew/service.go
index 926f015..d83f912 100644
--- a/internal/xianyu/renew/service.go
+++ b/internal/xianyu/renew/service.go
@@ -1,17 +1,13 @@
-// Package renew 实现闲鱼登录 Cookie 续期链路。
-//
-// 这层只负责低成本 HTTP 续期:hasLogin.do -> silentHasLogin.do ->
-// setLoginSettings.do。浏览器续期和密码登录属于更重的恢复手段,应该由上层在
-// 本包返回失败后再决定是否执行。
+// Package renew 实现闲鱼登录 Cookie 续期与“保存登录信息”接口。
+// 主动续期严格复用 auto-login plugin 的单次 silentHasLogin 流程;长登录开关
+// 独立执行 setLoginSettings -> queryLoginSettings,不混入主动续期链。
package renew
import (
"context"
- cryptorand "crypto/rand"
"encoding/json"
"fmt"
"io"
- "math/big"
"net/http"
"net/url"
"sort"
@@ -20,39 +16,311 @@ import (
"time"
"xianyu-go/internal/xianyu"
+ "xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/protocol"
)
const (
- HasLoginURL = "https://passport.goofish.com/newlogin/hasLogin.do"
- SilentHasLoginURL = "https://passport.goofish.com/newlogin/silentHasLogin.do"
- SetLoginSettingsURL = "https://passport.goofish.com/ac/account/setLoginSettings.do"
- defaultRequestTimout = 20 * time.Second
- maxRenewBodyBytes = 2 << 20
+ HasLoginURL = "https://passport.goofish.com/newlogin/hasLogin.do"
+ SilentHasLoginURL = "https://passport.goofish.com/newlogin/silentHasLogin.do"
+ SetLoginSettingsURL = "https://passport.goofish.com/ac/account/setLoginSettings.do"
+ QueryLoginSettingsURL = "https://passport.goofish.com/ac/account/queryLoginSettings.do"
+ defaultRequestTimout = 2 * time.Second
+ backgroundFetchTimeout = 30 * time.Second
+ longLoginRequestTimout = 30 * time.Second
+ maxRenewBodyBytes = 2 << 20
+ goofishTopSite = "https://goofish.com"
+ goofishIMDocumentURL = "https://www.goofish.com/im"
)
// Service 是 Cookie 接口续期服务。零值可用;测试可覆盖 URL 和 HTTPClient。
type Service struct {
- HTTPClient *http.Client
- HasLoginURL string
- SilentHasLoginURL string
- SetLoginSettingsURL string
- RetryDelay time.Duration
+ HTTPClient *http.Client
+ HasLoginURL string
+ SilentHasLoginURL string
+ QueryLoginSettingsURL string
+ SetLoginSettingsURL string
+ DocumentReferer string
+ RetryDelay time.Duration
+ // PromiseTimeout 仅供测试缩短官网固定的 2 秒 Promise.race 窗口;
+ // 生产零值始终使用 defaultRequestTimout。
+ PromiseTimeout time.Duration
+}
+
+type LongLoginSettings struct {
+ CanOpenLongLogin bool `json:"can_open_long_login"`
+ Enabled bool `json:"enabled"`
+ NewCookies string `json:"-"`
+ SetCookies []string `json:"-"`
+ CookieSnapshot []cookierefresh.BrowserCookie `json:"-"`
+ CookieSnapshotComplete bool `json:"-"`
+}
+
+type longLoginCookieState struct {
+ flat string
+ snapshot []cookierefresh.BrowserCookie
+ authoritative bool
+}
+
+func newLongLoginCookieState(cookiesStr string, snapshots [][]cookierefresh.BrowserCookie) *longLoginCookieState {
+ state := &longLoginCookieState{flat: cookiesStr, authoritative: len(snapshots) > 0}
+ if state.authoritative {
+ state.snapshot = cookierefresh.NormalizeSnapshot(snapshots[0])
+ if state.snapshot == nil {
+ state.snapshot = []cookierefresh.BrowserCookie{}
+ }
+ state.refreshCanonical()
+ }
+ return state
+}
+
+func (state *longLoginCookieState) requestCookies(requestURL string) string {
+ if state == nil || !state.authoritative {
+ if state == nil {
+ return ""
+ }
+ return state.flat
+ }
+ value, _ := cookierefresh.ScopedCookieHeaderForRequest(state.snapshot, requestURL, goofishTopSite, time.Now())
+ return value
+}
+
+func (state *longLoginCookieState) apply(requestURL string, setCookies []string) {
+ if state == nil {
+ return
+ }
+ if state.authoritative {
+ state.snapshot = cookierefresh.ApplySetCookies(state.snapshot, requestURL, setCookies, time.Now(), goofishTopSite)
+ if state.snapshot == nil {
+ state.snapshot = []cookierefresh.BrowserCookie{}
+ }
+ state.refreshCanonical()
+ return
+ }
+ state.flat = MergeSetCookies(state.flat, setCookies)
+}
+
+func (state *longLoginCookieState) refreshCanonical() {
+ state.flat, _ = cookierefresh.ScopedCookieHeaderForRequest(state.snapshot, goofishIMDocumentURL, goofishTopSite, time.Now())
+}
+
+func (state *longLoginCookieState) populate(result *LongLoginSettings) {
+ if state == nil || result == nil {
+ return
+ }
+ result.NewCookies = state.flat
+ result.CookieSnapshotComplete = state.authoritative
+ if state.authoritative {
+ result.CookieSnapshot = cookierefresh.NormalizeSnapshot(state.snapshot)
+ if result.CookieSnapshot == nil {
+ result.CookieSnapshot = []cookierefresh.BrowserCookie{}
+ }
+ }
+}
+
+// QueryLongLoginSettings 对齐官网个人信息弹窗的“保存登录信息”查询。
+func (s Service) QueryLongLoginSettings(ctx context.Context, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*LongLoginSettings, error) {
+ return s.longLoginRequest(ctx, newLongLoginCookieState(cookiesStr, snapshots), nil)
+}
+
+// SetLongLoginSettings 中 status=0 表示开启,status=1 表示关闭。
+func (s Service) SetLongLoginSettings(ctx context.Context, cookiesStr string, enabled bool, snapshots ...[]cookierefresh.BrowserCookie) (*LongLoginSettings, error) {
+ status := "1"
+ if enabled {
+ status = "0"
+ }
+ state := newLongLoginCookieState(cookiesStr, snapshots)
+ setResult, err := s.longLoginRequest(ctx, state, &status)
+ if err != nil {
+ return setResult, err
+ }
+ // 官网 SET 成功后触发 LONG_LOGIN_SWITCH,再通过 QUERY 获取最终状态;SET
+ // 本身只要求 data.success,不要求携带 returnValue。
+ queried, err := s.longLoginRequest(ctx, state, nil)
+ if queried == nil {
+ queried = &LongLoginSettings{
+ Enabled: enabled,
+ }
+ state.populate(queried)
+ }
+ queried.SetCookies = append(append([]string(nil), setResult.SetCookies...), queried.SetCookies...)
+ if err != nil {
+ // QUERY 失败时仍返回 SET 请求及 QUERY 响应头已经刷新的 Cookie;最终
+ // 开关状态尚未确认,只能保留调用方本次请求的目标值。
+ queried.Enabled = enabled
+ return queried, err
+ }
+ return queried, nil
+}
+
+func (s Service) longLoginRequest(ctx context.Context, cookieState *longLoginCookieState, status *string) (*LongLoginSettings, error) {
+ partial := &LongLoginSettings{}
+ cookieState.populate(partial)
+ if status != nil {
+ partial.Enabled = *status == "0"
+ }
+ cookieURL := QueryLoginSettingsURL
+ target := s.urlOrDefault(s.QueryLoginSettingsURL, QueryLoginSettingsURL)
+ var body io.Reader
+ if status != nil {
+ cookieURL = SetLoginSettingsURL
+ target = s.urlOrDefault(s.SetLoginSettingsURL, SetLoginSettingsURL)
+ body = strings.NewReader("status=" + url.QueryEscape(*status))
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, target, body)
+ if err != nil {
+ return partial, err
+ }
+ appendOrderedQuery(req.URL, [][2]string{{"fromSite", "77"}, {"appName", "xianyu"}, {"bizEntrance", "web"}})
+ setSilentHasLoginHeaders(req, cookieState.requestCookies(cookieURL), s.documentReferer())
+ if status != nil {
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ }
+ hc := s.HTTPClient
+ if hc == nil {
+ hc = &http.Client{Timeout: longLoginRequestTimout}
+ }
+ requestCtx, cancel := context.WithTimeout(req.Context(), longLoginRequestTimout)
+ defer cancel()
+ resp, err := hc.Do(req.Clone(requestCtx))
+ if err != nil {
+ return partial, fmt.Errorf("保存登录信息请求失败: %w", err)
+ }
+ defer resp.Body.Close()
+ // 浏览器在响应头到达时就会更新 Cookie Jar;因此必须先捕获 Set-Cookie,
+ // 即使随后读取响应体、校验 HTTP 状态或解析业务 JSON 失败也要返回给调用方。
+ partial.SetCookies = filterValidSetCookies(resp.Header.Values("Set-Cookie"))
+ cookieState.apply(cookieURL, partial.SetCookies)
+ cookieState.populate(partial)
+ raw, err := readRenewBody(resp.Body)
+ if err != nil {
+ return partial, fmt.Errorf("保存登录信息响应读取失败: %w", err)
+ }
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return partial, fmt.Errorf("保存登录信息 HTTP 状态异常: %d", resp.StatusCode)
+ }
+ if status != nil {
+ if !longLoginSetBusinessOK(raw) {
+ return partial, fmt.Errorf("保存登录信息业务结果未确认成功")
+ }
+ return partial, nil
+ }
+ value, ok := findReturnValue(raw)
+ if !ok {
+ return partial, fmt.Errorf("保存登录信息响应缺少 returnValue")
+ }
+ partial.CanOpenLongLogin, _ = value["canOpenLongLogin"].(bool)
+ partial.Enabled, _ = value["hasLongTokenLogin"].(bool)
+ return partial, nil
+}
+
+func longLoginSetBusinessOK(raw []byte) bool {
+ var payload map[string]any
+ if json.Unmarshal(raw, &payload) != nil {
+ return false
+ }
+ if success, _ := payload["success"].(bool); success {
+ return true
+ }
+ if data, _ := payload["data"].(map[string]any); data != nil {
+ success, _ := data["success"].(bool)
+ return success
+ }
+ return false
+}
+
+func findReturnValue(raw []byte) (map[string]any, bool) {
+ var payload map[string]any
+ if json.Unmarshal(raw, &payload) != nil {
+ return nil, false
+ }
+ return findMapChild(payload, "returnValue", 0)
+}
+
+func findMapChild(parent map[string]any, key string, depth int) (map[string]any, bool) {
+ if parent == nil || depth > 6 {
+ return nil, false
+ }
+ if value, ok := parent[key].(map[string]any); ok {
+ return value, true
+ }
+ for _, child := range parent {
+ if nested, ok := child.(map[string]any); ok {
+ if value, found := findMapChild(nested, key, depth+1); found {
+ return value, true
+ }
+ }
+ }
+ return nil, false
}
// Result 描述一次接口续期的完整结果。
type Result struct {
- Success bool
- Skipped bool
- SkipReason string
- RenewMethod string
- NewCookies string
- UpdatedCookieNames []string
- StepDetails []StepResult
- Message string
- ResponseText string
- NeedPasswordLogin bool
- RequestCount int
+ Success bool
+ Skipped bool
+ SkipReason string
+ RenewMethod string
+ NewCookies string
+ UpdatedCookieNames []string
+ SetCookies []string
+ CookieSnapshot []cookierefresh.BrowserCookie
+ CookieSnapshotComplete bool
+ StepDetails []StepResult
+ Message string
+ ResponseText string
+ NeedPasswordLogin bool
+ RequestCount int
+ pending <-chan pendingRenewResult
+ responseCookieURL string
+}
+
+type pendingRenewResult struct {
+ result *Result
+ err error
+}
+
+// HasPending 表示官网 2 秒 Promise 已结束,但底层 fetch 仍在接收响应。
+func (r *Result) HasPending() bool { return r != nil && r.pending != nil }
+
+// AwaitPending 等待底层 fetch 的最终响应。只能由一个持久化调用方消费一次。
+func (r *Result) AwaitPending(ctx context.Context) (*Result, error) {
+ if r == nil || r.pending == nil {
+ return nil, nil
+ }
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case outcome, ok := <-r.pending:
+ if !ok {
+ return nil, nil
+ }
+ return outcome.result, outcome.err
+ }
+}
+
+// RebaseResponseCookies 把续期响应的 Set-Cookie 应用到“当前最新”凭证状态。
+// 后台 fetch 可能晚于其他 MTOP 请求返回,必须重放响应头而不是覆盖成请求发起
+// 时计算出的旧快照。
+func RebaseResponseCookies(currentCookies, currentMetadata string, result *Result) (string, string, bool) {
+ if result == nil || len(result.SetCookies) == 0 {
+ return currentCookies, currentMetadata, false
+ }
+ requestURL := strings.TrimSpace(result.responseCookieURL)
+ if requestURL == "" {
+ requestURL = SilentHasLoginURL
+ }
+ if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(currentMetadata); complete {
+ updated := cookierefresh.ApplySetCookies(snapshot, requestURL, result.SetCookies, time.Now(), goofishTopSite)
+ if updated == nil {
+ updated = []cookierefresh.BrowserCookie{}
+ }
+ value, _ := cookierefresh.ScopedCookieHeaderForRequest(updated, goofishIMDocumentURL, goofishTopSite, time.Now())
+ metadata := cookierefresh.MetadataWithSnapshot(currentMetadata, updated)
+ return value, metadata, value != currentCookies || metadata != currentMetadata
+ }
+ value := MergeSetCookies(currentCookies, result.SetCookies)
+ metadata := cookierefresh.MetadataWithoutSnapshot(currentMetadata)
+ return value, metadata, value != currentCookies || metadata != currentMetadata
}
// StepResult 是单个续期接口的执行结果,便于上层记录日志和定位失败点。
@@ -74,20 +342,63 @@ const (
// branch, waits briefly, and sends exactly one silentHasLogin request.
// It never chains hasLogin/setLoginSettings or escalates to an interactive
// login from this proactive renewal path.
-func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string) (*Result, error) {
+func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*Result, error) {
cookiesStr = strings.TrimSpace(cookiesStr)
- if cookiesStr == "" {
- return &Result{RenewMethod: "none", Message: "Cookie为空,无法续期", NeedPasswordLogin: true}, nil
+ authoritativeSnapshot := len(snapshots) > 0 && snapshots[0] != nil
+ documentURL := s.documentReferer()
+ requestURL := s.urlOrDefault(s.SilentHasLoginURL, SilentHasLoginURL)
+ now := time.Now()
+ decisionCookies := cookiesStr
+ requestCookies := cookiesStr
+ newCookies := cookiesStr
+ var snapshot []cookierefresh.BrowserCookie
+ if authoritativeSnapshot {
+ snapshot = cookierefresh.NormalizeSnapshot(snapshots[0])
+ documentCookies := make([]cookierefresh.BrowserCookie, 0, len(snapshot))
+ for _, cookie := range snapshot {
+ if !cookie.HTTPOnly {
+ documentCookies = append(documentCookies, cookie)
+ }
+ }
+ if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(documentCookies, documentURL, goofishTopSite, now); authoritative {
+ decisionCookies = scoped
+ }
+ if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, goofishTopSite, now); authoritative {
+ requestCookies = scoped
+ }
+ if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, goofishIMDocumentURL, goofishTopSite, now); authoritative {
+ newCookies = scoped
+ }
}
- mode, skipReason := autoLoginMode(protocol.TransCookies(cookiesStr), time.Now())
+ result := &Result{
+ RenewMethod: "auto_login_plugin",
+ NewCookies: newCookies,
+ responseCookieURL: requestURL,
+ }
+ if authoritativeSnapshot {
+ result.CookieSnapshot = make([]cookierefresh.BrowserCookie, len(snapshot))
+ copy(result.CookieSnapshot, snapshot)
+ result.CookieSnapshotComplete = true
+ }
+ if cookiesStr == "" && !authoritativeSnapshot {
+ result.RenewMethod = "none"
+ result.Message = "Cookie为空,无法续期"
+ result.NeedPasswordLogin = true
+ return result, nil
+ }
+ if ua := strings.ToLower(xianyu.CurrentBrowserFingerprint().UserAgent); ua != "" &&
+ !strings.Contains(ua, "windows") && !strings.Contains(ua, "macintosh") {
+ result.Skipped = true
+ result.SkipReason = "unsupported_desktop_ua"
+ result.Message = autoLoginSkipMessage(result.SkipReason)
+ return result, nil
+ }
+ mode, skipReason := autoLoginMode(firstCookieValues(decisionCookies), now)
if skipReason != "" {
- return &Result{
- Skipped: true,
- SkipReason: skipReason,
- RenewMethod: "auto_login_plugin",
- NewCookies: cookiesStr,
- Message: autoLoginSkipMessage(skipReason),
- }, nil
+ result.Skipped = true
+ result.SkipReason = skipReason
+ result.Message = autoLoginSkipMessage(skipReason)
+ return result, nil
}
delay := 2 * time.Second
if s.RetryDelay < 0 {
@@ -100,37 +411,88 @@ func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string) (*Result,
select {
case <-ctx.Done():
timer.Stop()
- return nil, ctx.Err()
+ result.Message = ctx.Err().Error()
+ result.NeedPasswordLogin = true
+ return result, ctx.Err()
case <-timer.C:
}
}
- call, err := s.callAutoLogin(ctx, cookiesStr, mode)
- if err != nil {
- return nil, err
+ call, err := s.callAutoLogin(ctx, requestCookies, mode)
+ populate := func(target *Result, finished callResult, callErr error, promiseTimedOut bool) (*Result, error) {
+ target.RequestCount = 1
+ target.SetCookies = append([]string(nil), finished.SetCookies...)
+ target.ResponseText = string(finished.Body)
+ if strings.TrimSpace(finished.Step.Name) != "" {
+ target.StepDetails = []StepResult{finished.Step}
+ }
+ if authoritativeSnapshot {
+ updatedSnapshot := cookierefresh.ApplySetCookies(snapshot, requestURL, finished.SetCookies, time.Now(), goofishTopSite)
+ target.CookieSnapshot = updatedSnapshot
+ target.CookieSnapshotComplete = true
+ if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(updatedSnapshot, goofishIMDocumentURL, goofishTopSite, time.Now()); authoritative {
+ target.NewCookies = scoped
+ }
+ target.UpdatedCookieNames = cookierefresh.ChangedSnapshotLabels(snapshot, updatedSnapshot)
+ } else {
+ target.NewCookies = MergeSetCookies(cookiesStr, finished.SetCookies)
+ target.UpdatedCookieNames = ChangedCookieNames(cookiesStr, target.NewCookies)
+ }
+ if promiseTimedOut {
+ target.Success = false
+ target.NeedPasswordLogin = false
+ target.Message = "官网静默续期 Promise 已超时"
+ if len(finished.SetCookies) > 0 {
+ target.Message += ";底层响应 Cookie 已接收"
+ }
+ return target, callErr
+ }
+ if callErr != nil {
+ target.Message = callErr.Error()
+ target.NeedPasswordLogin = true
+ return target, callErr
+ }
+ message := "静默续期成功"
+ if !finished.Step.BusinessOK {
+ message = firstNonEmpty(finished.Step.Message, "静默续期未通过")
+ }
+ target.Success = finished.Step.BusinessOK
+ target.Message = message
+ target.NeedPasswordLogin = !finished.Step.BusinessOK
+ return target, nil
}
- newCookies := cookiesStr
- if len(call.SetCookies) > 0 {
- newCookies = MergeSetCookies(cookiesStr, call.SetCookies)
+ if call.pending != nil {
+ result.RequestCount = 1
+ result.StepDetails = []StepResult{call.Step}
+ result.Message = call.Step.Message
+ result.NeedPasswordLogin = false
+ pending := make(chan pendingRenewResult, 1)
+ result.pending = pending
+ go func() {
+ outcome, ok := <-call.pending
+ if !ok {
+ close(pending)
+ return
+ }
+ late := &Result{
+ RenewMethod: "auto_login_plugin",
+ NewCookies: newCookies,
+ responseCookieURL: requestURL,
+ }
+ if authoritativeSnapshot {
+ late.CookieSnapshot = append([]cookierefresh.BrowserCookie(nil), snapshot...)
+ late.CookieSnapshotComplete = true
+ }
+ late, lateErr := populate(late, outcome.call, outcome.err, true)
+ pending <- pendingRenewResult{result: late, err: lateErr}
+ close(pending)
+ }()
+ return result, nil
}
- message := "静默续期成功"
- if !call.Step.BusinessOK {
- message = firstNonEmpty(call.Step.Message, "静默续期未通过")
- }
- return &Result{
- Success: call.Step.BusinessOK,
- RenewMethod: "auto_login_plugin",
- NewCookies: newCookies,
- UpdatedCookieNames: ChangedCookieNames(cookiesStr, newCookies),
- StepDetails: []StepResult{call.Step},
- Message: message,
- ResponseText: string(call.Body),
- NeedPasswordLogin: !call.Step.BusinessOK,
- RequestCount: 1,
- }, nil
+ return populate(result, call, err, false)
}
func autoLoginMode(cookies map[string]string, now time.Time) (mode, skipReason string) {
- if cookieTimeAfter(cookies["sdkSilent"], now) {
+ if strictCookieTimeAfter(cookies["sdkSilent"], now) {
return "", "fatigue"
}
if cookieTimeAfter(cookies["havana_lgc_exp"], now) {
@@ -142,217 +504,166 @@ func autoLoginMode(cookies map[string]string, now time.Time) (mode, skipReason s
return "", "long_login_expired"
}
-func cookieTimeAfter(raw string, now time.Time) bool {
- millis, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64)
+// firstCookieValues 对齐浏览器 document.cookie getter:同名 Cookie 按浏览器
+// header 顺序读取首个值。ScopedCookieHeaderForRequest 已把更长 Path 排在前面。
+func firstCookieValues(cookieHeader string) map[string]string {
+ values := make(map[string]string)
+ for _, part := range strings.Split(cookieHeader, ";") {
+ name, value, ok := strings.Cut(strings.TrimSpace(part), "=")
+ name = strings.TrimSpace(name)
+ if !ok || name == "" {
+ continue
+ }
+ if _, exists := values[name]; exists {
+ continue
+ }
+ values[name] = strings.TrimSpace(value)
+ }
+ return values
+}
+
+func strictCookieTimeAfter(raw string, now time.Time) bool {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return false
+ }
+ millis, err := strconv.ParseInt(raw, 10, 64)
return err == nil && millis > now.UnixMilli()
}
+func cookieTimeAfter(raw string, now time.Time) bool {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return false
+ }
+ millis, err := strconv.ParseInt(raw, 10, 64)
+ if err != nil {
+ // plugin.js 使用 Invalid Date <= now;结果为 false,因此非空异常值
+ // 会继续进入对应续期分支。
+ return true
+ }
+ return millis > now.UnixMilli()
+}
+
func autoLoginSkipMessage(reason string) string {
switch reason {
case "fatigue":
return "sdkSilent 疲劳窗口内,跳过静默续期"
case "long_login_expired":
return "长登录凭证已过期,静默续期不应发起请求"
+ case "unsupported_desktop_ua":
+ return "官网静默续期仅支持 Windows 或 macOS 桌面浏览器"
default:
return "无需静默续期"
}
}
-func (s Service) renewOnce(ctx context.Context, original string) (*Result, error) {
- current := original
- steps := make([]StepResult, 0, 3)
- allSetCookies := make([]string, 0, 8)
-
- hasLogin, err := s.callHasLogin(ctx, current)
- if err != nil {
- return nil, err
- }
- steps = append(steps, hasLogin.Step)
- if len(hasLogin.SetCookies) > 0 {
- allSetCookies = append(allSetCookies, hasLogin.SetCookies...)
- current = MergeSetCookies(current, hasLogin.SetCookies)
- }
-
- silent, err := s.callSilentHasLogin(ctx, current)
- if err != nil {
- return nil, err
- }
- steps = append(steps, silent.Step)
- if len(silent.SetCookies) > 0 {
- allSetCookies = append(allSetCookies, silent.SetCookies...)
- current = MergeSetCookies(current, silent.SetCookies)
- }
-
- settings, err := s.callSetLoginSettings(ctx, current)
- if err != nil {
- return nil, err
- }
- steps = append(steps, settings.Step)
- if len(settings.SetCookies) > 0 {
- allSetCookies = append(allSetCookies, settings.SetCookies...)
- }
-
- newCookies := original
- if len(allSetCookies) > 0 {
- newCookies = MergeSetCookies(original, allSetCookies)
- }
- updated := ChangedCookieNames(original, newCookies)
- success := len(settings.SetCookies) > 0
- method := "none"
- msg := "setLoginSettings 未返回 Set-Cookie,需要浏览器续期或密码登录"
- if success {
- method = "api"
- msg = "接口续期成功"
- }
- return &Result{
- Success: success,
- RenewMethod: method,
- NewCookies: newCookies,
- UpdatedCookieNames: updated,
- StepDetails: steps,
- Message: msg,
- ResponseText: string(silent.Body),
- NeedPasswordLogin: !success,
- }, nil
-}
-
type callResult struct {
Step StepResult
SetCookies []string
Body []byte
+ pending <-chan callOutcome
}
-func (s Service) callHasLogin(ctx context.Context, cookiesStr string) (callResult, error) {
- cookies := protocol.TransCookies(cookiesStr)
- unb := cookies["unb"]
- if unb == "" {
- return callResult{Step: StepResult{Name: "hasLogin", Message: "Cookie缺少unb,跳过"}}, nil
- }
- form := url.Values{}
- form.Set("hid", unb)
- form.Set("ltl", "true")
- form.Set("appName", "xianyu")
- form.Set("appEntrance", "web")
- form.Set("_csrf_token", cookies["_tb_token_"])
- form.Set("umidToken", firstNonEmpty(cookies["_uab_collina"], cookies["cna"]))
- form.Set("hsiz", cookies["cookie2"])
- form.Set("bizParams", "taobaoBizLoginFrom=web&renderRefer=https%3A%2F%2Fwww.goofish.com%2F")
- form.Set("mainPage", "false")
- form.Set("isMobile", "false")
- form.Set("lang", "zh_CN")
- form.Set("fromSite", "77")
- form.Set("isIframe", "true")
- form.Set("documentReferer", "https://www.goofish.com/")
- form.Set("defaultView", "hasLogin")
- form.Set("umidTag", "SERVER")
- form.Set("returnUrl", "")
- form.Set("deviceId", "")
- form.Set("pageTraceId", "21504"+strconv.FormatInt(time.Now().UnixMilli(), 10)+randomDigits(6))
-
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.urlOrDefault(s.HasLoginURL, HasLoginURL), strings.NewReader(form.Encode()))
- if err != nil {
- return callResult{}, err
- }
- setHasLoginHeaders(req, cookiesStr, miniLoginReferer())
- if xsrf := cookies["XSRF-TOKEN"]; xsrf != "" {
- req.Header.Set("x-xsrf-token", xsrf)
- }
- q := req.URL.Query()
- q.Set("appName", "xianyu")
- q.Set("fromSite", "77")
- req.URL.RawQuery = q.Encode()
- return s.doRenewRequest(req, "hasLogin")
-}
-
-func (s Service) callSilentHasLogin(ctx context.Context, cookiesStr string) (callResult, error) {
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.urlOrDefault(s.SilentHasLoginURL, SilentHasLoginURL), nil)
- if err != nil {
- return callResult{}, err
- }
- q := req.URL.Query()
- q.Set("documentReferer", "https://www.goofish.com/")
- q.Set("appName", "xianyu")
- q.Set("appEntrance", "xianyu_sdkSilent")
- q.Set("fromSite", "0")
- q.Set("ltl", "true")
- req.URL.RawQuery = q.Encode()
- setSilentHasLoginHeaders(req, cookiesStr)
- return s.doRenewRequest(req, "silentHasLogin")
+type callOutcome struct {
+ call callResult
+ err error
}
func (s Service) callAutoLogin(ctx context.Context, cookiesStr, mode string) (callResult, error) {
+ partial := callResult{Step: StepResult{Name: "silentHasLogin"}}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.urlOrDefault(s.SilentHasLoginURL, SilentHasLoginURL), nil)
if err != nil {
- return callResult{}, err
+ return partial, err
+ }
+ query := [][2]string{
+ {"documentReferer", s.documentReferer()},
+ {"appName", "xianyu"},
+ {"appEntrance", "xianyu_sdkSilent"},
+ {"fromSite", "0"},
}
- q := req.URL.Query()
- q.Set("documentReferer", "https://www.goofish.com/")
- q.Set("appName", "xianyu")
- q.Set("appEntrance", "xianyu_sdkSilent")
- q.Set("fromSite", "0")
switch mode {
case autoLoginModeHavana:
- q.Set("ltl", "true")
+ query = append(query, [2]string{"ltl", "true"})
case autoLoginModeCookie3:
- q.Set("skipSessionFilter", "true")
- q.Set("c2r", "true")
+ query = append(query, [2]string{"skipSessionFilter", "true"}, [2]string{"c2r", "true"})
default:
- return callResult{}, fmt.Errorf("未知静默续期模式: %s", mode)
+ return partial, fmt.Errorf("未知静默续期模式: %s", mode)
}
- req.URL.RawQuery = q.Encode()
- setSilentHasLoginHeaders(req, cookiesStr)
+ appendOrderedQuery(req.URL, query)
+ setSilentHasLoginHeaders(req, cookiesStr, s.documentReferer())
return s.doRenewRequest(req, "silentHasLogin")
}
-func (s Service) callSetLoginSettings(ctx context.Context, cookiesStr string) (callResult, error) {
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.urlOrDefault(s.SetLoginSettingsURL, SetLoginSettingsURL), strings.NewReader("status=0"))
- if err != nil {
- return callResult{}, err
- }
- q := req.URL.Query()
- q.Set("fromSite", "77")
- q.Set("appName", "xianyu")
- q.Set("bizEntrance", "web")
- req.URL.RawQuery = q.Encode()
- setLoginSettingsHeaders(req, cookiesStr)
- return s.doRenewRequest(req, "setLoginSettings")
-}
-
func (s Service) doRenewRequest(req *http.Request, name string) (callResult, error) {
hc := s.HTTPClient
if hc == nil {
- hc = &http.Client{Timeout: defaultRequestTimout}
+ hc = &http.Client{Timeout: backgroundFetchTimeout}
}
- client := *hc
- client.CheckRedirect = func(*http.Request, []*http.Request) error {
- return http.ErrUseLastResponse
+ // Promise.race 的计时器不能取消底层 fetch。使用 WithoutCancel 让 2 秒
+ // 窗口结束后请求继续,但仍以 30 秒硬上限防止后台泄漏。
+ requestCtx, cancel := context.WithTimeout(context.WithoutCancel(req.Context()), backgroundFetchTimeout)
+ backgroundReq := req.Clone(requestCtx)
+ done := make(chan callOutcome, 1)
+ go func() {
+ defer cancel()
+ call, err := executeRenewRequest(hc, backgroundReq, name)
+ done <- callOutcome{call: call, err: err}
+ }()
+ timer := time.NewTimer(s.promiseTimeout())
+ defer timer.Stop()
+ select {
+ case <-req.Context().Done():
+ cancel()
+ result := callResult{Step: StepResult{Name: name, Message: req.Context().Err().Error()}}
+ return result, req.Context().Err()
+ case outcome := <-done:
+ return outcome.call, outcome.err
+ case <-timer.C:
+ return callResult{
+ Step: StepResult{Name: name, Message: "官网静默续期 Promise 已超时;底层 fetch 继续接收 Cookie"},
+ pending: done,
+ }, nil
}
- resp, err := client.Do(req)
+}
+
+func (s Service) promiseTimeout() time.Duration {
+ if s.PromiseTimeout > 0 {
+ return s.PromiseTimeout
+ }
+ return defaultRequestTimout
+}
+
+func executeRenewRequest(hc *http.Client, req *http.Request, name string) (callResult, error) {
+ result := callResult{Step: StepResult{Name: name}}
+ resp, err := hc.Do(req)
if err != nil {
- return callResult{}, fmt.Errorf("%s 请求失败: %w", name, err)
+ result.Step.Message = fmt.Sprintf("请求失败: %v", err)
+ return result, fmt.Errorf("%s 请求失败: %w", name, err)
}
defer resp.Body.Close()
+ // 与浏览器 Cookie Jar 一样,在响应头到达后立即接收 Set-Cookie。后续响应体
+ // 读取失败也不能丢弃服务端已经完成的凭证轮换。
+ result.SetCookies = filterValidSetCookies(resp.Header.Values("Set-Cookie"))
+ result.Step.HTTPStatus = resp.StatusCode
+ result.Step.SetCookieCount = len(result.SetCookies)
body, err := readRenewBody(resp.Body)
if err != nil {
- return callResult{}, fmt.Errorf("%s 响应读取失败: %w", name, err)
+ result.Step.Message = fmt.Sprintf("响应读取失败: %v", err)
+ return result, fmt.Errorf("%s 响应读取失败: %w", name, err)
}
- setCookies := filterValidSetCookies(resp.Header.Values("Set-Cookie"))
- step := StepResult{
- Name: name,
- HTTPStatus: resp.StatusCode,
- SetCookieCount: len(setCookies),
+ result.Body = body
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ result.Step.Message = fmt.Sprintf("HTTP状态异常: %d", resp.StatusCode)
+ return result, nil
}
- if resp.StatusCode < 200 || resp.StatusCode >= 400 {
- step.Message = fmt.Sprintf("HTTP状态异常: %d", resp.StatusCode)
- return callResult{Step: step, SetCookies: setCookies, Body: body}, nil
- }
- step.BusinessOK = renewBusinessOK(body)
- if step.BusinessOK {
- step.Message = "业务成功"
+ result.Step.BusinessOK = renewBusinessOK(body)
+ if result.Step.BusinessOK {
+ result.Step.Message = "业务成功"
} else {
- step.Message = "业务结果未确认成功"
+ result.Step.Message = "业务结果未确认成功"
}
- return callResult{Step: step, SetCookies: setCookies, Body: body}, nil
+ return result, nil
}
func renewBusinessOK(body []byte) bool {
@@ -375,63 +686,48 @@ func renewBusinessOK(body []byte) bool {
data, _ := content["data"].(map[string]any)
if data != nil {
finished, _ := data["processFinished"].(bool)
- if finished && mtopInt(data["resultCode"]) == 100 {
+ if finished && numericResultCode(data["resultCode"]) == 100 {
return true
}
}
- ok, _ := content["success"].(bool)
- return ok
+ return false
}
-func mtopInt(v any) int {
+func numericResultCode(v any) int {
switch value := v.(type) {
case float64:
return int(value)
case json.Number:
n, _ := strconv.Atoi(value.String())
return n
- case string:
- n, _ := strconv.Atoi(value)
- return n
+ case int:
+ return value
default:
return 0
}
}
-func setHasLoginHeaders(req *http.Request, cookiesStr, referer string) {
- xianyu.ApplyBrowserFingerprint(req.Header)
- req.Header.Set("Accept", "application/json, text/plain, */*")
- req.Header.Set("Accept-Language", "zh-CN")
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- req.Header.Set("Referer", referer)
- req.Header.Set("bx-v", "2.5.31")
- req.Header.Set("Cookie", strings.ReplaceAll(strings.ReplaceAll(cookiesStr, "\n", ""), "\r", ""))
-}
-
-func setSilentHasLoginHeaders(req *http.Request, cookiesStr string) {
+func setSilentHasLoginHeaders(req *http.Request, cookiesStr, documentReferer string) {
xianyu.ApplyBrowserFingerprint(req.Header)
req.Header.Set("Accept", "*/*")
- req.Header.Set("Accept-Language", "en,zh-CN;q=0.9,zh;q=0.8,ru;q=0.7")
- req.Header.Set("Cache-Control", "no-cache")
- req.Header.Set("Pragma", "no-cache")
- req.Header.Set("Priority", "u=1, i")
- req.Header.Set("Referer", "https://www.goofish.com/")
+ req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
+ req.Header.Set("Origin", "https://www.goofish.com")
+ req.Header.Set("Referer", documentReferer)
req.Header.Set("sec-fetch-dest", "empty")
req.Header.Set("sec-fetch-mode", "cors")
req.Header.Set("sec-fetch-site", "same-site")
req.Header.Set("Cookie", strings.ReplaceAll(strings.ReplaceAll(cookiesStr, "\n", ""), "\r", ""))
}
-func setLoginSettingsHeaders(req *http.Request, cookiesStr string) {
- xianyu.ApplyBrowserFingerprint(req.Header)
- req.Header.Set("Accept", "application/json, text/plain, */*")
- req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- req.Header.Set("Referer", "https://www.goofish.com/")
- req.Header.Set("sec-fetch-dest", "empty")
- req.Header.Set("sec-fetch-mode", "cors")
- req.Header.Set("sec-fetch-site", "same-site")
- req.Header.Set("Cookie", strings.ReplaceAll(strings.ReplaceAll(cookiesStr, "\n", ""), "\r", ""))
+func appendOrderedQuery(target *url.URL, values [][2]string) {
+ parts := make([]string, 0, len(values)+1)
+ if strings.TrimSpace(target.RawQuery) != "" {
+ parts = append(parts, target.RawQuery)
+ }
+ for _, item := range values {
+ parts = append(parts, url.QueryEscape(item[0])+"="+url.QueryEscape(item[1]))
+ }
+ target.RawQuery = strings.Join(parts, "&")
}
func (s Service) urlOrDefault(v, fallback string) string {
@@ -441,6 +737,13 @@ func (s Service) urlOrDefault(v, fallback string) string {
return fallback
}
+func (s Service) documentReferer() string {
+ if strings.TrimSpace(s.DocumentReferer) != "" {
+ return strings.TrimSpace(s.DocumentReferer)
+ }
+ return "https://www.goofish.com/im"
+}
+
func readRenewBody(r io.Reader) ([]byte, error) {
body, err := io.ReadAll(io.LimitReader(r, maxRenewBodyBytes+1))
if err != nil {
@@ -461,41 +764,13 @@ func firstNonEmpty(values ...string) string {
return ""
}
-func miniLoginReferer() string {
- return "https://passport.goofish.com/mini_login.htm?lang=zh_cn&appName=xianyu&appEntrance=web&styleType=vertical&bizParams=¬LoadSsoView=false¬KeepLogin=false&isMobile=false&qrCodeFirst=false&stie=77&rnd=" + randomFraction()
-}
-
-func randomDigits(n int) string {
- if n <= 0 {
- return ""
- }
- min := 1
- for i := 1; i < n; i++ {
- min *= 10
- }
- max := min * 9
- v, err := cryptorand.Int(cryptorand.Reader, big.NewInt(int64(max)))
- if err != nil {
- return strings.Repeat("0", n)
- }
- return strconv.Itoa(min + int(v.Int64()))
-}
-
-func randomFraction() string {
- v, err := cryptorand.Int(cryptorand.Reader, big.NewInt(1_000_000_000))
- if err != nil {
- return "0.0"
- }
- return "0." + fmt.Sprintf("%09d", v.Int64())
-}
-
func filterValidSetCookies(setCookies []string) []string {
if len(setCookies) == 0 {
return nil
}
out := make([]string, 0, len(setCookies))
for _, sc := range setCookies {
- if strings.Contains(sc, "Max-Age=0") || strings.Contains(sc, "1970") {
+ if strings.TrimSpace(sc) == "" {
continue
}
out = append(out, sc)
@@ -508,19 +783,15 @@ func filterValidSetCookies(setCookies []string) []string {
func MergeSetCookies(original string, setCookies []string) string {
cookies := protocol.TransCookies(original)
for _, sc := range setCookies {
- pair := sc
- if i := strings.Index(pair, ";"); i >= 0 {
- pair = pair[:i]
- }
- name, val, ok := strings.Cut(pair, "=")
- if !ok {
+ parsed, err := http.ParseSetCookie(sc)
+ if err != nil || strings.TrimSpace(parsed.Name) == "" {
continue
}
- name = strings.TrimSpace(name)
- if name == "" {
- continue
+ if parsed.MaxAge < 0 || (parsed.MaxAge == 0 && !parsed.Expires.IsZero() && !parsed.Expires.After(time.Now())) {
+ delete(cookies, parsed.Name)
+ } else {
+ cookies[parsed.Name] = parsed.Value
}
- cookies[name] = strings.TrimSpace(val)
}
return marshalCookies(cookies)
}
@@ -530,8 +801,15 @@ func ChangedCookieNames(original, newCookies string) []string {
oldMap := protocol.TransCookies(original)
newMap := protocol.TransCookies(newCookies)
changed := make([]string, 0)
- for k, v := range newMap {
- if oldMap[k] != v {
+ seen := make(map[string]struct{}, len(oldMap)+len(newMap))
+ for k := range oldMap {
+ seen[k] = struct{}{}
+ }
+ for k := range newMap {
+ seen[k] = struct{}{}
+ }
+ for k := range seen {
+ if oldMap[k] != newMap[k] {
changed = append(changed, k)
}
}
diff --git a/internal/xianyu/renew/service_test.go b/internal/xianyu/renew/service_test.go
index ad5de7e..2c7929a 100644
--- a/internal/xianyu/renew/service_test.go
+++ b/internal/xianyu/renew/service_test.go
@@ -2,7 +2,9 @@ package renew
import (
"context"
+ "errors"
"fmt"
+ "io"
"net/http"
"net/http/httptest"
"strconv"
@@ -12,12 +14,40 @@ import (
"time"
"xianyu-go/internal/xianyu"
+ "xianyu-go/internal/xianyu/cookierefresh"
)
+type roundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
+ return f(req)
+}
+
+type failingReadCloser struct {
+ err error
+}
+
+func (r failingReadCloser) Read([]byte) (int, error) { return 0, r.err }
+func (failingReadCloser) Close() error { return nil }
+
func futureMillis(d time.Duration) string {
return strconv.FormatInt(time.Now().Add(d).UnixMilli(), 10)
}
+func useTestDesktopFingerprint(t *testing.T) xianyu.BrowserFingerprint {
+ t.Helper()
+ old := xianyu.CurrentBrowserFingerprint()
+ fingerprint := xianyu.BrowserFingerprint{
+ UserAgent: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/999.0.0.0 Safari/537.36`,
+ SecChUA: `"Chromium";v="999", "Google Chrome";v="999", "Not_A Brand";v="24"`,
+ Platform: "macOS",
+ Mobile: "?0",
+ }
+ xianyu.SetBrowserFingerprint(fingerprint)
+ t.Cleanup(func() { xianyu.SetBrowserFingerprint(old) })
+ return fingerprint
+}
+
func TestAutoLoginModeMatchesBrowserPlugin(t *testing.T) {
now := time.Now()
tests := []struct {
@@ -27,9 +57,10 @@ func TestAutoLoginModeMatchesBrowserPlugin(t *testing.T) {
wantReason string
}{
{name: "fatigue", cookies: map[string]string{"sdkSilent": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10), "havana_lgc_exp": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)}, wantReason: "fatigue"},
+ {name: "malformed sdkSilent does not cause fatigue", cookies: map[string]string{"sdkSilent": "invalid", "havana_lgc_exp": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)}, wantMode: autoLoginModeHavana},
{name: "havana", cookies: map[string]string{"havana_lgc_exp": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)}, wantMode: autoLoginModeHavana},
{name: "cookie3 backup", cookies: map[string]string{"havana_lgc_exp": strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10), "cookie3_bak_exp": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)}, wantMode: autoLoginModeCookie3},
- {name: "expired", cookies: map[string]string{"havana_lgc_exp": "bad", "cookie3_bak_exp": strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10)}, wantReason: "long_login_expired"},
+ {name: "malformed long-login expiry follows browser Invalid Date branch", cookies: map[string]string{"havana_lgc_exp": "bad", "cookie3_bak_exp": strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10)}, wantMode: autoLoginModeHavana},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -41,8 +72,187 @@ func TestAutoLoginModeMatchesBrowserPlugin(t *testing.T) {
}
}
+func TestAutoLoginDecisionUsesFirstCookieForDuplicatePaths(t *testing.T) {
+ now := time.Now()
+ cookies := strings.Join([]string{
+ "sdkSilent=" + strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10),
+ "sdkSilent=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10),
+ "havana_lgc_exp=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10),
+ "havana_lgc_exp=" + strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10),
+ }, "; ")
+ mode, reason := autoLoginMode(firstCookieValues(cookies), now)
+ if mode != autoLoginModeHavana || reason != "" {
+ t.Fatalf("mode=%q reason=%q;应采用浏览器排序后的首个同名 Cookie", mode, reason)
+ }
+}
+
+func TestLongLoginSettingsMatchOfficialRequest(t *testing.T) {
+ var calls atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ if r.Method != http.MethodPost {
+ t.Fatalf("method=%s", r.Method)
+ }
+ if r.URL.Query().Get("fromSite") != "77" || r.URL.Query().Get("appName") != "xianyu" || r.URL.Query().Get("bizEntrance") != "web" {
+ t.Fatalf("query=%s", r.URL.RawQuery)
+ }
+ if r.Header.Get("Origin") != "https://www.goofish.com" || r.Header.Get("Referer") != "https://www.goofish.com/im" {
+ t.Fatalf("origin/referer=%q/%q", r.Header.Get("Origin"), r.Header.Get("Referer"))
+ }
+ if !strings.Contains(r.Header.Get("Cookie"), "unb=1") {
+ t.Fatalf("Cookie=%q", r.Header.Get("Cookie"))
+ }
+ if strings.Contains(r.URL.Path, "set") {
+ if err := r.ParseForm(); err != nil || r.Form.Get("status") != "0" {
+ t.Fatalf("set form=%v err=%v", r.Form, err)
+ }
+ }
+ http.SetCookie(w, &http.Cookie{Name: "havana_lgc_exp", Value: futureMillis(24 * time.Hour), Path: "/", HttpOnly: true})
+ if strings.Contains(r.URL.Path, "set") {
+ _, _ = w.Write([]byte(`{"data":{"success":true}}`))
+ return
+ }
+ _, _ = w.Write([]byte(`{"content":{"data":{"returnValue":{"canOpenLongLogin":true,"hasLongTokenLogin":true}}}}`))
+ }))
+ defer srv.Close()
+
+ service := Service{
+ HTTPClient: srv.Client(),
+ QueryLoginSettingsURL: srv.URL + "/queryLoginSettings.do",
+ SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
+ DocumentReferer: "https://www.goofish.com/im",
+ }
+ queried, err := service.QueryLongLoginSettings(context.Background(), "unb=1")
+ if err != nil || !queried.CanOpenLongLogin || !queried.Enabled {
+ t.Fatalf("query result=%+v err=%v", queried, err)
+ }
+ set, err := service.SetLongLoginSettings(context.Background(), queried.NewCookies, true)
+ if err != nil || !set.Enabled || len(set.SetCookies) != 2 || !strings.Contains(set.NewCookies, "havana_lgc_exp=") {
+ t.Fatalf("set result=%+v err=%v", set, err)
+ }
+ if calls.Load() != 3 {
+ t.Fatalf("calls=%d", calls.Load())
+ }
+}
+
+func TestLongLoginRequestKeepsResponseCookiesOnFailures(t *testing.T) {
+ tests := []struct {
+ name string
+ statusCode int
+ body io.ReadCloser
+ }{
+ {
+ name: "body read",
+ statusCode: http.StatusOK,
+ body: failingReadCloser{err: errors.New("broken body")},
+ },
+ {
+ name: "business parse",
+ statusCode: http.StatusOK,
+ body: io.NopCloser(strings.NewReader(`not-json`)),
+ },
+ {
+ name: "http status",
+ statusCode: http.StatusServiceUnavailable,
+ body: io.NopCloser(strings.NewReader(`{"error":"busy"}`)),
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
+ return &http.Response{
+ StatusCode: tt.statusCode,
+ Header: http.Header{
+ "Set-Cookie": {"rotated=fresh; Domain=.goofish.com; Path=/; Secure; HttpOnly"},
+ },
+ Body: tt.body,
+ }, nil
+ })}
+ settings, err := (Service{HTTPClient: client}).QueryLongLoginSettings(context.Background(), "unb=1")
+ if err == nil || settings == nil {
+ t.Fatalf("settings=%+v err=%v", settings, err)
+ }
+ if len(settings.SetCookies) != 1 || !strings.Contains(settings.NewCookies, "rotated=fresh") {
+ t.Fatalf("response Cookie was lost: %+v", settings)
+ }
+ })
+ }
+}
+
+func TestSetLongLoginSettingsMergesSetAndFailedQueryCookies(t *testing.T) {
+ var calls atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ if strings.Contains(r.URL.Path, "set") {
+ http.SetCookie(w, &http.Cookie{Name: "set_cookie", Value: "one", Path: "/"})
+ _, _ = w.Write([]byte(`{"data":{"success":true}}`))
+ return
+ }
+ if !strings.Contains(r.Header.Get("Cookie"), "set_cookie=one") {
+ t.Fatalf("QUERY did not receive SET Cookie: %q", r.Header.Get("Cookie"))
+ }
+ http.SetCookie(w, &http.Cookie{Name: "query_cookie", Value: "two", Path: "/"})
+ w.WriteHeader(http.StatusBadGateway)
+ _, _ = w.Write([]byte(`{"error":"upstream"}`))
+ }))
+ defer srv.Close()
+
+ svc := Service{
+ HTTPClient: srv.Client(),
+ SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
+ QueryLoginSettingsURL: srv.URL + "/queryLoginSettings.do",
+ }
+ settings, err := svc.SetLongLoginSettings(context.Background(), "unb=1", true)
+ if err == nil || settings == nil {
+ t.Fatalf("settings=%+v err=%v", settings, err)
+ }
+ if calls.Load() != 2 || len(settings.SetCookies) != 2 || !settings.Enabled {
+ t.Fatalf("settings=%+v calls=%d", settings, calls.Load())
+ }
+ if !strings.Contains(settings.NewCookies, "set_cookie=one") || !strings.Contains(settings.NewCookies, "query_cookie=two") {
+ t.Fatalf("SET/QUERY Cookie was lost: %q", settings.NewCookies)
+ }
+}
+
+func TestSetLongLoginSettingsScopesCompleteJarBetweenSetAndQuery(t *testing.T) {
+ var queryCookie string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.Contains(r.URL.Path, "set") {
+ w.Header().Add("Set-Cookie", "set_only=hidden; Path=/ac/account/setLoginSettings.do; Secure")
+ w.Header().Add("Set-Cookie", "shared=next; Path=/ac/account; Secure")
+ _, _ = w.Write([]byte(`{"data":{"success":true}}`))
+ return
+ }
+ queryCookie = r.Header.Get("Cookie")
+ _, _ = w.Write([]byte(`{"content":{"data":{"returnValue":{"canOpenLongLogin":true,"hasLongTokenLogin":true}}}}`))
+ }))
+ defer srv.Close()
+ snapshot := []cookierefresh.BrowserCookie{
+ {Name: "shared", Value: "old", Domain: "passport.goofish.com", Path: "/ac/account", Secure: true},
+ {Name: "im_only", Value: "visible", Domain: "www.goofish.com", Path: "/im", Secure: true},
+ }
+ svc := Service{
+ HTTPClient: srv.Client(),
+ SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
+ QueryLoginSettingsURL: srv.URL + "/queryLoginSettings.do",
+ }
+ settings, err := svc.SetLongLoginSettings(context.Background(), "fallback=must-not-leak", true, snapshot)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(queryCookie, "set_only=hidden") || !strings.Contains(queryCookie, "shared=next") {
+ t.Fatalf("QUERY Cookie 未按更新后 Jar 重新做 Path scope: %q", queryCookie)
+ }
+ if !settings.CookieSnapshotComplete || len(settings.CookieSnapshot) != 3 {
+ t.Fatalf("最终完整 Jar 未返回: %+v", settings)
+ }
+ if settings.NewCookies != "im_only=visible" {
+ t.Fatalf("/im canonical Cookie=%q", settings.NewCookies)
+ }
+}
+
func TestRenewAPIFirstHavanaSendsOneSilentRequest(t *testing.T) {
- xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "native-browser-ua", SecChUA: `"Chromium";v="999"`, Platform: "macOS", Mobile: "?0"})
+ fingerprint := useTestDesktopFingerprint(t)
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
@@ -52,7 +262,10 @@ func TestRenewAPIFirstHavanaSendsOneSilentRequest(t *testing.T) {
if r.URL.Query().Get("skipSessionFilter") != "" || r.URL.Query().Get("c2r") != "" {
t.Fatalf("havana mode included cookie3 flags: %s", r.URL.RawQuery)
}
- if got := r.Header.Get("User-Agent"); got != "native-browser-ua" {
+ if got := r.URL.Query().Get("documentReferer"); got != "https://www.goofish.com/im" {
+ t.Fatalf("documentReferer=%q", got)
+ }
+ if got := r.Header.Get("User-Agent"); got != fingerprint.UserAgent {
t.Fatalf("User-Agent=%q", got)
}
if got := r.Header.Get("Cookie"); !strings.Contains(got, "unb=1") {
@@ -63,7 +276,7 @@ func TestRenewAPIFirstHavanaSendsOneSilentRequest(t *testing.T) {
}))
defer srv.Close()
- svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
+ svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, DocumentReferer: "https://www.goofish.com/im", RetryDelay: -1}
input := "unb=1; havana_lgc_exp=" + futureMillis(time.Hour)
res, err := svc.RenewAPIFirst(context.Background(), input)
if err != nil {
@@ -77,12 +290,117 @@ func TestRenewAPIFirstHavanaSendsOneSilentRequest(t *testing.T) {
}
}
+func TestRenewAPIFirstUsesBrowserCookieScopes(t *testing.T) {
+ useTestDesktopFingerprint(t)
+ var receivedCookie string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ receivedCookie = r.Header.Get("Cookie")
+ _, _ = w.Write([]byte(`{"data":{"content":{"data":{"processFinished":true,"resultCode":100}}}}`))
+ }))
+ defer srv.Close()
+ host := strings.TrimPrefix(srv.URL, "http://")
+ host = strings.Split(host, ":")[0]
+ snapshot := []cookierefresh.BrowserCookie{
+ {Name: "havana_lgc_exp", Value: futureMillis(time.Hour), Domain: ".goofish.com", Path: "/"},
+ {Name: "request_only", Value: "passport", Domain: host, Path: "/"},
+ {Name: "www_only", Value: "private", Domain: "www.goofish.com", Path: "/im"},
+ {Name: "http_only_document", Value: "hidden", Domain: ".goofish.com", Path: "/", HTTPOnly: true},
+ }
+ svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, DocumentReferer: "https://www.goofish.com/im", RetryDelay: -1}
+ res, err := svc.RenewAPIFirst(context.Background(), "havana_lgc_exp="+futureMillis(time.Hour)+"; request_only=passport; www_only=private", snapshot)
+ if err != nil || !res.Success {
+ t.Fatalf("result=%+v err=%v", res, err)
+ }
+ if !strings.Contains(receivedCookie, "request_only=passport") || strings.Contains(receivedCookie, "www_only=private") {
+ t.Fatalf("passport 请求未遵守 Cookie Domain/Path: %q", receivedCookie)
+ }
+ if !res.CookieSnapshotComplete || res.CookieSnapshot == nil {
+ t.Fatalf("authoritative snapshot was not returned: %+v", res)
+ }
+}
+
+func TestRenewAPIFirstUsesTopSiteAndAppliesPartitionedSetCookie(t *testing.T) {
+ useTestDesktopFingerprint(t)
+ snapshot := []cookierefresh.BrowserCookie{
+ {Name: "havana_lgc_exp", Value: futureMillis(time.Hour), Domain: ".goofish.com", Path: "/", Secure: true, PartitionKey: goofishTopSite},
+ {Name: "passport_partitioned", Value: "right", Domain: "passport.goofish.com", Path: "/", Secure: true, PartitionKey: goofishTopSite},
+ {Name: "wrong_partition", Value: "hidden", Domain: "passport.goofish.com", Path: "/", Secure: true, PartitionKey: "https://example.com"},
+ }
+ client := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ cookies := req.Header.Get("Cookie")
+ if !strings.Contains(cookies, "passport_partitioned=right") || strings.Contains(cookies, "wrong_partition=hidden") {
+ t.Fatalf("partitioned request Cookie=%q", cookies)
+ }
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{
+ "Set-Cookie": {"rotated=fresh; Domain=.goofish.com; Path=/; Secure; Partitioned"},
+ },
+ Body: io.NopCloser(strings.NewReader(`{"data":{"content":{"data":{"processFinished":true,"resultCode":100}}}}`)),
+ }, nil
+ })}
+ svc := Service{HTTPClient: client, RetryDelay: -1}
+ res, err := svc.RenewAPIFirst(context.Background(), "", snapshot)
+ if err != nil || !res.Success {
+ t.Fatalf("result=%+v err=%v", res, err)
+ }
+ if !res.CookieSnapshotComplete || !strings.Contains(res.NewCookies, "rotated=fresh") {
+ t.Fatalf("authoritative renewal result=%+v", res)
+ }
+ found := false
+ for _, cookie := range res.CookieSnapshot {
+ if cookie.Name == "rotated" && cookie.Value == "fresh" && cookie.PartitionKey == goofishTopSite {
+ found = true
+ }
+ }
+ if !found || len(res.UpdatedCookieNames) == 0 {
+ t.Fatalf("partitioned Set-Cookie was not applied exactly: %+v", res)
+ }
+}
+
+func TestRenewAPIFirstKeepsSetCookieWhenBodyReadFails(t *testing.T) {
+ useTestDesktopFingerprint(t)
+ snapshot := []cookierefresh.BrowserCookie{
+ {Name: "havana_lgc_exp", Value: futureMillis(time.Hour), Domain: ".goofish.com", Path: "/", Secure: true},
+ }
+ client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{
+ "Set-Cookie": {"rotated=fresh; Domain=.goofish.com; Path=/; Secure; HttpOnly"},
+ },
+ Body: failingReadCloser{err: errors.New("broken response body")},
+ }, nil
+ })}
+ svc := Service{HTTPClient: client, RetryDelay: -1}
+ res, err := svc.RenewAPIFirst(context.Background(), "", snapshot)
+ if err == nil || res == nil {
+ t.Fatalf("result=%+v err=%v", res, err)
+ }
+ if !res.CookieSnapshotComplete || res.RequestCount != 1 || len(res.SetCookies) != 1 || !strings.Contains(res.NewCookies, "rotated=fresh") {
+ t.Fatalf("response Cookie was lost after body error: %+v", res)
+ }
+}
+
+func TestRenewAPIFirstTreatsNonNilEmptySnapshotAsAuthoritative(t *testing.T) {
+ useTestDesktopFingerprint(t)
+ emptySnapshot := make([]cookierefresh.BrowserCookie, 0)
+ res, err := (Service{RetryDelay: -1}).RenewAPIFirst(context.Background(), "", emptySnapshot)
+ if err != nil || !res.Skipped || res.SkipReason != "long_login_expired" {
+ t.Fatalf("result=%+v err=%v", res, err)
+ }
+ if !res.CookieSnapshotComplete || res.CookieSnapshot == nil || len(res.CookieSnapshot) != 0 || res.RenewMethod != "auto_login_plugin" {
+ t.Fatalf("empty authoritative snapshot was downgraded: %+v", res)
+ }
+}
+
func TestRenewAPIFirstCookie3UsesBackupFlags(t *testing.T) {
+ useTestDesktopFingerprint(t)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("skipSessionFilter") != "true" || r.URL.Query().Get("c2r") != "true" || r.URL.Query().Get("ltl") != "" {
t.Fatalf("cookie3 query=%s", r.URL.RawQuery)
}
- _, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":"100"}}}`))
+ _, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
}))
defer srv.Close()
svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
@@ -113,6 +431,7 @@ func TestRenewAPIFirstSkipsFatigueAndExpiredCookies(t *testing.T) {
}
func TestRenewAPIFirstDoesNotRetryOrEscalateFailure(t *testing.T) {
+ useTestDesktopFingerprint(t)
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
calls.Add(1)
@@ -140,6 +459,102 @@ func TestMergeSetCookies(t *testing.T) {
}
}
+func TestMergeSetCookiesAppliesServerDeletion(t *testing.T) {
+ got := MergeSetCookies("unb=1; stale=a; expired=b", []string{
+ "stale=; Max-Age=0; Path=/",
+ "expired=; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/",
+ })
+ if strings.Contains(got, "stale=") || strings.Contains(got, "expired=") {
+ t.Fatalf("deleted cookies survived: %q", got)
+ }
+ if changed := strings.Join(ChangedCookieNames("unb=1; stale=a; expired=b", got), ","); changed != "expired,stale" {
+ t.Fatalf("ChangedCookieNames=%s", changed)
+ }
+}
+
+func TestMergeSetCookiesMaxAgeOverridesPastExpires(t *testing.T) {
+ got := MergeSetCookies("session=old", []string{
+ "session=fresh; Max-Age=3600; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/",
+ })
+ if !strings.Contains(got, "session=fresh") {
+ t.Fatalf("positive Max-Age must override past Expires: %q", got)
+ }
+}
+
+func TestRenewBusinessOKMatchesOfficialPlugin(t *testing.T) {
+ if renewBusinessOK([]byte(`{"content":{"success":true}}`)) {
+ t.Fatal("official plugin requires processFinished=true and resultCode=100")
+ }
+ if !renewBusinessOK([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`)) {
+ t.Fatal("official success payload was rejected")
+ }
+}
+
+func TestRenewAPIFirstReturnsAtPromiseTimeoutAndKeepsLateCookies(t *testing.T) {
+ useTestDesktopFingerprint(t)
+ var completed atomic.Bool
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ time.Sleep(80 * time.Millisecond)
+ http.SetCookie(w, &http.Cookie{Name: "sdkSilent", Value: futureMillis(time.Hour), Path: "/"})
+ _, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
+ completed.Store(true)
+ }))
+ defer srv.Close()
+ svc := Service{
+ HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1,
+ PromiseTimeout: 20 * time.Millisecond,
+ }
+ started := time.Now()
+ res, err := svc.RenewAPIFirst(context.Background(), "havana_lgc_exp="+futureMillis(time.Hour))
+ if err != nil || res == nil || !res.HasPending() {
+ t.Fatalf("result=%+v err=%v", res, err)
+ }
+ if elapsed := time.Since(started); elapsed >= 70*time.Millisecond {
+ t.Fatalf("外层 Promise 没有按时返回: %s", elapsed)
+ }
+ if completed.Load() || len(res.SetCookies) != 0 || res.Success || res.NeedPasswordLogin {
+ t.Fatalf("超时瞬间不应伪造底层结果或要求重新登录: %+v completed=%v", res, completed.Load())
+ }
+ waitCtx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ late, lateErr := res.AwaitPending(waitCtx)
+ if lateErr != nil || late == nil || len(late.SetCookies) != 1 || !strings.Contains(late.NewCookies, "sdkSilent=") {
+ t.Fatalf("迟到响应 Cookie 丢失: result=%+v err=%v", late, lateErr)
+ }
+ if !completed.Load() || late.Success || late.NeedPasswordLogin {
+ t.Fatalf("底层请求应完成,但不得在 Promise 超时后触发成功 reload/重新登录: %+v completed=%v", late, completed.Load())
+ }
+}
+
+func TestRebaseResponseCookiesUsesLatestAuthoritativeJar(t *testing.T) {
+ current := []cookierefresh.BrowserCookie{
+ {Name: "unb", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true},
+ {Name: "concurrent", Value: "kept", Domain: ".goofish.com", Path: "/", Secure: true},
+ }
+ metadata := cookierefresh.MetadataWithSnapshot(`{"note":"keep"}`, current)
+ late := &Result{
+ SetCookies: []string{"sdkSilent=9999999999999; Domain=goofish.com; Path=/; Secure; HttpOnly"},
+ responseCookieURL: SilentHasLoginURL,
+ }
+ value, updatedMetadata, changed := RebaseResponseCookies("unb=1; concurrent=kept", metadata, late)
+ if !changed || !strings.Contains(value, "concurrent=kept") || !strings.Contains(value, "sdkSilent=9999999999999") {
+ t.Fatalf("迟到响应覆盖了并发 Cookie: value=%q changed=%v", value, changed)
+ }
+ snapshot, complete := cookierefresh.SnapshotFromMetadataOK(updatedMetadata)
+ if !complete {
+ t.Fatalf("权威快照被降级: %s", updatedMetadata)
+ }
+ var found bool
+ for _, cookie := range snapshot {
+ if cookie.Name == "sdkSilent" && cookie.HTTPOnly && cookie.Domain == ".goofish.com" {
+ found = true
+ }
+ }
+ if !found || !strings.Contains(updatedMetadata, `"note":"keep"`) {
+ t.Fatalf("迟到 Cookie 属性或其他 metadata 丢失: %+v metadata=%s", snapshot, updatedMetadata)
+ }
+}
+
func TestRenewBodyLimit(t *testing.T) {
_, err := readRenewBody(strings.NewReader(strings.Repeat("x", maxRenewBodyBytes+1)))
if err == nil || !strings.Contains(err.Error(), fmt.Sprint(maxRenewBodyBytes>>20)) {
diff --git a/internal/xianyu/ws/auth_error.go b/internal/xianyu/ws/auth_error.go
new file mode 100644
index 0000000..d674269
--- /dev/null
+++ b/internal/xianyu/ws/auth_error.go
@@ -0,0 +1,94 @@
+package ws
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+)
+
+type RegErrorKind string
+
+const (
+ RegErrorInvalidToken RegErrorKind = "invalid_token"
+ RegErrorConnectLimit RegErrorKind = "connect_limit"
+ RegErrorAuthentication RegErrorKind = "authentication"
+)
+
+// RegError describes a server-side /reg rejection after the WebSocket itself
+// has opened successfully.
+type RegError struct {
+ Kind RegErrorKind
+ Code int
+ Reason string
+}
+
+func (e *RegError) Error() string {
+ if e == nil {
+ return ""
+ }
+ return fmt.Sprintf("WS /reg 被拒绝: kind=%s code=%d reason=%s", e.Kind, e.Code, e.Reason)
+}
+
+func IsInvalidTokenError(err error) bool {
+ var regErr *RegError
+ return errors.As(err, ®Err) && regErr.Kind == RegErrorInvalidToken
+}
+
+func IsConnectLimitError(err error) bool {
+ var regErr *RegError
+ return errors.As(err, ®Err) && regErr.Kind == RegErrorConnectLimit
+}
+
+func IsAuthenticationError(err error) bool {
+ var regErr *RegError
+ return errors.As(err, ®Err) && regErr.Kind == RegErrorAuthentication
+}
+
+func newRegError(code int, frame map[string]any) error {
+ reason := regErrorReason(frame)
+ lower := strings.ToLower(reason)
+ kind := RegErrorAuthentication
+ switch {
+ case code == 401,
+ strings.Contains(lower, "invalid token"),
+ strings.Contains(lower, "not auth"),
+ strings.Contains(lower, "token invalid"),
+ strings.Contains(lower, "device id or appkey is not equal"):
+ kind = RegErrorInvalidToken
+ case strings.Contains(lower, "connect limit"),
+ strings.Contains(lower, "session remove"),
+ strings.Contains(lower, "too many"):
+ kind = RegErrorConnectLimit
+ }
+ return &RegError{Kind: kind, Code: code, Reason: reason}
+}
+
+func regErrorReason(frame map[string]any) string {
+ values := make([]string, 0, 8)
+ appendValue := func(value any) {
+ if value == nil {
+ return
+ }
+ text := strings.TrimSpace(fmt.Sprint(value))
+ if text != "" && text != "" {
+ values = append(values, text)
+ }
+ }
+ for _, key := range []string{"message", "msg", "reason", "ret"} {
+ appendValue(frame[key])
+ }
+ if body, ok := frame["body"].(map[string]any); ok {
+ for _, key := range []string{"message", "msg", "reason", "moreInfo"} {
+ appendValue(body[key])
+ }
+ }
+ if headers, ok := frame["headers"].(map[string]any); ok {
+ for _, key := range []string{"message", "msg", "reason", "error", "error-message"} {
+ appendValue(headers[key])
+ }
+ }
+ if len(values) == 0 {
+ return "unknown authentication error"
+ }
+ return strings.Join(values, " | ")
+}
diff --git a/internal/xianyu/ws/client.go b/internal/xianyu/ws/client.go
index d586edf..db3d00e 100644
--- a/internal/xianyu/ws/client.go
+++ b/internal/xianyu/ws/client.go
@@ -8,9 +8,12 @@ import (
"fmt"
"log/slog"
"net/http"
+ "net/url"
+ "regexp"
"strings"
"sync"
"time"
+ "unicode/utf8"
"github.com/coder/websocket"
@@ -19,16 +22,17 @@ import (
)
// WSURL 闲鱼 IM WebSocket 地址。
-const WSURL = "wss://wss-goofish.dingtalk.com/"
+const WSURL = "wss://wss-goofish.dingtalk.com:443"
const (
- wsOpenTimeout = 30 * time.Second
- protocolPingInterval = 20 * time.Second
- protocolPingTimeout = 15 * time.Second
+ wsOpenTimeout = 30 * time.Second
+ regResponseTimeout = 30 * time.Second
)
-// 变量仅用于让单元测试无需真实等待 10 秒;生产值严格对齐参考实现。
-var heartbeatRetryInterval = 5 * time.Second
+var (
+ heartbeatResponseTimeout = 30 * time.Second
+ batchConnectDelays = []time.Duration{0, 200 * time.Millisecond, 900 * time.Millisecond, 1500 * time.Millisecond, 4 * time.Second}
+)
// RegAppKey WS /reg 用的 app-key。
const RegAppKey = "444e9908a51d1cb236a27862abc769c9"
@@ -43,250 +47,560 @@ type Config struct {
// Conn 包装一条已注册的 WebSocket 连接。
type Conn struct {
- ws *websocket.Conn
- cfg Config
- logger *slog.Logger
- sendMu sync.Mutex
- recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string)
+ ws *websocket.Conn
+ cfg Config
+ logger *slog.Logger
+ sendGate chan struct{}
+ recorderMu sync.RWMutex
+ recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string)
+
+ readCtx context.Context
+ readCancel context.CancelFunc
+ readDone chan struct{}
+ initOnce sync.Once
+ readErrMu sync.Mutex
+ readErr error
+
+ pendingMu sync.Mutex
+ pending map[string]chan map[string]any
+ pushes chan incomingFrame
+}
+
+type incomingFrame struct {
+ messageType websocket.MessageType
+ data []byte
+ parsed map[string]any
}
// SetRecorder 设置帧记录器。
func (c *Conn) SetRecorder(rec func(direction, rawText, parsedJSON, parseStatus, errMsg string)) {
+ c.recorderMu.Lock()
c.recorder = rec
+ c.recorderMu.Unlock()
}
-// Dial 建立并注册 WS 连接:握手 → /reg → /r/SyncStatus/ackDiff。
+func (c *Conn) recorderSnapshot() func(direction, rawText, parsedJSON, parseStatus, errMsg string) {
+ c.recorderMu.RLock()
+ recorder := c.recorder
+ c.recorderMu.RUnlock()
+ return recorder
+}
+
+// Dial 保留旧的一步式入口;新账号主循环使用 Open → 获取 token → Register,
+// 从而与官网 authConnect 的顺序一致。
func Dial(ctx context.Context, cfg Config, logger *slog.Logger) (*Conn, error) {
- if logger == nil {
- logger = slog.Default()
- }
- // 参考实现的 WEBSOCKET_HEADERS 为空,只在拨号前加入 Cookie。额外伪造
- // Origin/User-Agent 等头会改变服务端看到的连接指纹。
- hdr := websocketHeaders(cfg.CookieStr)
-
- logger.Info("正在连接闲鱼 WebSocket", "url", WSURL)
- dialCtx, cancel := context.WithTimeout(ctx, wsOpenTimeout)
- defer cancel()
- c, _, err := websocket.Dial(dialCtx, WSURL, &websocket.DialOptions{HTTPHeader: hdr})
+ conn, err := Open(ctx, cfg, logger)
if err != nil {
- return nil, fmt.Errorf("WS dial: %w", err)
+ return nil, err
}
- // 闲鱼消息多为文本 JSON。
- c.SetReadLimit(8 << 20) // 8 MiB,宽松上限
-
- conn := &Conn{ws: c, cfg: cfg, logger: logger, recorder: cfg.Recorder}
- if err := conn.register(ctx); err != nil {
- _ = c.CloseNow()
+ if err := conn.Register(ctx, cfg.DeviceID, cfg.AccessToken); err != nil {
+ _ = conn.Close()
return nil, err
}
return conn, nil
}
-func websocketHeaders(cookieStr string) http.Header {
+// Open 按官网 batchConnectWs 策略并行打开最多五条原生 WebSocket,由最先
+// settle 的成功或失败决定本轮结果,并关闭迟到连接。此阶段不请求 token,
+// 也不发送 /reg。
+func Open(ctx context.Context, cfg Config, logger *slog.Logger) (*Conn, error) {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ logger.Info("正在连接闲鱼 WebSocket", "url", WSURL)
+ return openBatch(ctx, WSURL, cfg, logger)
+}
+
+func websocketHeaders() http.Header {
hdr := http.Header{}
- hdr.Set("Cookie", strings.NewReplacer("\n", "", "\r", "").Replace(cookieStr))
+ hdr.Set("Origin", "https://www.goofish.com")
+ if ua := xianyu.CurrentBrowserFingerprint().UserAgent; ua != "" {
+ hdr.Set("User-Agent", ua)
+ }
return hdr
}
-// register 发送 /reg 与 ackDiff。
-func (c *Conn) register(ctx context.Context) error {
- reg := map[string]any{
- "lwp": "/reg",
- "headers": map[string]any{
- "cache-header": "app-key token ua wv",
- "app-key": RegAppKey,
- "token": c.cfg.AccessToken,
- "ua": xianyu.CurrentBrowserFingerprint().UserAgent,
- "dt": "j",
- "wv": "im:3,au:3,sy:6",
- "sync": "0,0;0;0;",
- "did": c.cfg.DeviceID,
- "mid": protocol.GenerateMid(),
- },
- }
- if err := c.sendJSON(ctx, reg); err != nil {
- return fmt.Errorf("发送 /reg 失败: %w", err)
- }
+var (
+ chromeVersionPattern = regexp.MustCompile(`(?:Chrome|CriOS)/([\d.]+)`)
+ headlessChromePattern = regexp.MustCompile(`HeadlessChrome/([\d.]+)`)
+ edgeVersionPattern = regexp.MustCompile(`Edg(?:e|A|iOS)?/([\d.]+)`)
+ firefoxVersionPattern = regexp.MustCompile(`Firefox/([\d.]+)`)
+ safariVersionPattern = regexp.MustCompile(`Version/([\d.]+).*Safari`)
+ macVersionPattern = regexp.MustCompile(`Mac OS X[ /]([\d_\.]+)`)
+ windowsVersionPattern = regexp.MustCompile(`Windows NT ([\d.]+)`)
+ androidVersionPattern = regexp.MustCompile(`Android[ /]([\d.]+)`)
+)
- // /reg 后等待 1 秒再发送 ackDiff。
- select {
- case <-time.After(time.Second):
- case <-ctx.Done():
- return ctx.Err()
+// OfficialRegistrationUA mirrors IMPaaS 2.2.0's ua-parser-js composition.
+// The raw UA (and therefore its browser version) comes from local Chromium;
+// all wrapper fields and ordering are fixed to the official web implementation.
+func OfficialRegistrationUA(rawUA string) string {
+ rawUA = strings.TrimSpace(rawUA)
+ if rawUA == "" {
+ return ""
}
-
- now := time.Now().UnixMilli()
- ackDiff := map[string]any{
- "lwp": "/r/SyncStatus/ackDiff",
- "headers": map[string]any{"mid": protocol.GenerateMid()},
- "body": []any{
- map[string]any{
- "pipeline": "sync",
- "tooLong2Tag": "PNM,1",
- "channel": "sync",
- "topic": "sync",
- "highPts": 0,
- "pts": now * 1000,
- "seq": 0,
- "timestamp": now,
- },
- },
- }
- if err := c.sendJSON(ctx, ackDiff); err != nil {
- return fmt.Errorf("发送 ackDiff 失败: %w", err)
- }
- c.logger.Info("WS 注册完成")
- return nil
+ osName, osVersion := parseOfficialOS(rawUA)
+ browserName, browserVersion := parseOfficialBrowser(rawUA)
+ return strings.Join([]string{
+ rawUA,
+ "DingTalk(2.2.0)",
+ fmt.Sprintf("OS(%s/%s)", osName, osVersion),
+ fmt.Sprintf("Browser(%s/%s)", browserName, browserVersion),
+ "DingWeb/2.2.0",
+ "IMPaaS",
+ "DingWeb/2.2.0",
+ }, " ")
}
-// HeartbeatLoop 周期性发送应用层心跳 {"lwp":"/!"},直到 ctx 取消或连续失败 maxFailures 次。
-func (c *Conn) HeartbeatLoop(ctx context.Context, interval time.Duration) error {
- const maxFailures = 3
- consecutive := 0
- pingCtx, cancelPing := context.WithCancel(ctx)
- defer cancelPing()
- pingErr := make(chan error, 1)
- go func() { pingErr <- c.protocolPingLoop(pingCtx) }()
-
- for {
- // 参考实现连接建立后立即发送应用层心跳,成功后才等待 15 秒。
- hb := map[string]any{
- "lwp": "/!",
- "headers": map[string]any{"mid": protocol.GenerateMid()},
+func parseOfficialOS(ua string) (string, string) {
+ if match := macVersionPattern.FindStringSubmatch(ua); len(match) == 2 {
+ return "Mac OS", strings.ReplaceAll(match[1], "_", ".")
+ }
+ if match := windowsVersionPattern.FindStringSubmatch(ua); len(match) == 2 {
+ versions := map[string]string{"10.0": "10", "6.3": "8.1", "6.2": "8", "6.1": "7", "6.0": "Vista", "5.1": "XP"}
+ if version := versions[match[1]]; version != "" {
+ return "Windows", version
}
- // 2s 超时保护。
- sendCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
- err := c.sendJSON(sendCtx, hb)
- cancel()
- if err != nil {
- consecutive++
- c.logger.Error("心跳发送失败", "err", err, "consecutive", consecutive)
- if consecutive >= maxFailures {
- return fmt.Errorf("心跳连续失败 %d 次", maxFailures)
+ return "Windows", match[1]
+ }
+ if match := androidVersionPattern.FindStringSubmatch(ua); len(match) == 2 {
+ return "Android", match[1]
+ }
+ if strings.Contains(ua, "Linux") {
+ return "Linux", "other"
+ }
+ return "other", "other"
+}
+
+func parseOfficialBrowser(ua string) (string, string) {
+ for _, candidate := range []struct {
+ name string
+ pattern *regexp.Regexp
+ }{{"Edge", edgeVersionPattern}, {"Chrome Headless", headlessChromePattern}, {"Chrome", chromeVersionPattern}, {"Firefox", firefoxVersionPattern}, {"Safari", safariVersionPattern}} {
+ if match := candidate.pattern.FindStringSubmatch(ua); len(match) == 2 {
+ return candidate.name, match[1]
+ }
+ }
+ return "other", "other"
+}
+
+type dialResult struct {
+ conn *websocket.Conn
+ err error
+}
+
+func openBatch(ctx context.Context, target string, cfg Config, logger *slog.Logger) (*Conn, error) {
+ delays := append([]time.Duration(nil), batchConnectDelays...)
+ if len(delays) == 0 {
+ return nil, fmt.Errorf("WS dial: batchConnect 未配置竞速连接")
+ }
+ batchCtx, cancel := context.WithCancel(ctx)
+ results := make(chan dialResult, len(delays))
+ for _, delay := range delays {
+ delay := delay
+ go func() {
+ if delay > 0 {
+ timer := time.NewTimer(delay)
+ defer timer.Stop()
+ select {
+ case <-batchCtx.Done():
+ results <- dialResult{err: batchCtx.Err()}
+ return
+ case <-timer.C:
+ }
}
- if err := waitHeartbeat(ctx, pingErr, heartbeatRetryInterval); err != nil {
- return err
+ dialCtx, dialCancel := context.WithTimeout(batchCtx, wsOpenTimeout)
+ defer dialCancel()
+ conn, _, err := websocket.Dial(dialCtx, target, &websocket.DialOptions{HTTPHeader: websocketHeaders()})
+ results <- dialResult{conn: conn, err: err}
+ }()
+ }
+
+ // 官网使用 Promise.race:第一条完成的连接无论成功或失败都会决定本轮
+ // batchConnect 的结果;不会在先收到失败后继续等待其他竞速连接。
+ result := <-results
+ go func() {
+ defer cancel()
+ for i := 1; i < len(delays); i++ {
+ late := <-results
+ if late.conn != nil {
+ _ = late.conn.CloseNow()
+ }
+ }
+ }()
+ if result.err != nil {
+ if result.conn != nil {
+ _ = result.conn.CloseNow()
+ }
+ return nil, fmt.Errorf("WS dial: %w", result.err)
+ }
+ result.conn.SetReadLimit(8 << 20)
+ return newConn(result.conn, cfg, logger), nil
+}
+
+func newConn(raw *websocket.Conn, cfg Config, logger *slog.Logger) *Conn {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ c := &Conn{
+ ws: raw,
+ cfg: cfg,
+ logger: logger,
+ sendGate: make(chan struct{}, 1),
+ recorder: cfg.Recorder,
+ }
+ c.ensureReadPump()
+ return c
+}
+
+func (c *Conn) ensureReadPump() {
+ c.initOnce.Do(func() {
+ if c.logger == nil {
+ c.logger = slog.Default()
+ }
+ c.readCtx, c.readCancel = context.WithCancel(context.Background())
+ c.readDone = make(chan struct{})
+ c.pending = make(map[string]chan map[string]any)
+ c.pushes = make(chan incomingFrame, 128)
+ go c.readPump()
+ })
+}
+
+// Register 发送官网最终态 /reg headers。注册后不主动构造 ackDiff。
+func (c *Conn) Register(ctx context.Context, deviceID, accessToken string) error {
+ c.ensureReadPump()
+ c.cfg.DeviceID = deviceID
+ // 官网 authConnect 在 _auth 前对 MTOP accessToken 执行
+ // decodeURIComponent。保留原始值供重试,再把解码值写入 /reg。
+ c.cfg.AccessToken = accessToken
+ decodedAccessToken, err := url.PathUnescape(accessToken)
+ if err != nil {
+ return fmt.Errorf("解码 WebSocket accessToken 失败: %w", err)
+ }
+ if !utf8.ValidString(decodedAccessToken) {
+ return fmt.Errorf("解码 WebSocket accessToken 失败: 非法 UTF-8")
+ }
+ response, err := c.request(ctx, "/reg", map[string]any{
+ "cache-header": "app-key token ua wv",
+ "app-key": RegAppKey,
+ "token": decodedAccessToken,
+ "ua": OfficialRegistrationUA(xianyu.CurrentBrowserFingerprint().UserAgent),
+ "dt": "j",
+ "wv": "im:3,au:3,sy:6",
+ "sync": "0,0;0;0;",
+ "did": deviceID,
+ }, nil, regResponseTimeout)
+ if err != nil {
+ return fmt.Errorf("等待 /reg 响应失败: %w", err)
+ }
+ code, ok := responseCode(response["code"])
+ if ok && code == 200 {
+ c.logger.Info("WS 注册完成")
+ return nil
+ }
+ return newRegError(code, response)
+}
+
+// register 兼容包内旧测试。
+func (c *Conn) register(ctx context.Context) error {
+ return c.Register(ctx, c.cfg.DeviceID, c.cfg.AccessToken)
+}
+
+func midKey(mid string) string {
+ fields := strings.Fields(mid)
+ if len(fields) == 0 {
+ return ""
+ }
+ return fields[0]
+}
+
+func responseCode(value any) (int, bool) {
+ switch code := value.(type) {
+ case float64:
+ return int(code), true
+ case int:
+ return code, true
+ case json.Number:
+ parsed, err := code.Int64()
+ return int(parsed), err == nil
+ case string:
+ var parsed int
+ if _, err := fmt.Sscanf(strings.TrimSpace(code), "%d", &parsed); err == nil {
+ return parsed, true
+ }
+ }
+ return 0, false
+}
+
+func (c *Conn) request(ctx context.Context, path string, headers map[string]any, body any, timeout time.Duration) (map[string]any, error) {
+ c.ensureReadPump()
+ requestCtx := ctx
+ cancel := func() {}
+ if timeout > 0 {
+ requestCtx, cancel = context.WithTimeout(ctx, timeout)
+ }
+ defer cancel()
+
+ if headers == nil {
+ headers = make(map[string]any)
+ }
+ mid := strings.TrimSpace(fmt.Sprint(headers["mid"]))
+ if mid == "" || mid == "" {
+ mid = protocol.GenerateMid()
+ headers["mid"] = mid
+ }
+ key := midKey(mid)
+ responseCh := make(chan map[string]any, 1)
+ c.pendingMu.Lock()
+ c.pending[key] = responseCh
+ c.pendingMu.Unlock()
+ defer func() {
+ c.pendingMu.Lock()
+ delete(c.pending, key)
+ c.pendingMu.Unlock()
+ }()
+
+ frame := map[string]any{"lwp": path, "headers": headers}
+ if body != nil {
+ frame["body"] = body
+ }
+ if err := c.sendJSON(requestCtx, frame); err != nil {
+ return nil, err
+ }
+ select {
+ case response := <-responseCh:
+ return response, nil
+ case <-c.readDone:
+ // readPump always dispatches a decoded response before it can observe the
+ // following close. Prefer that already-resolved response over readDone,
+ // matching browser event ordering (message before close).
+ select {
+ case response := <-responseCh:
+ return response, nil
+ default:
+ }
+ return nil, c.connectionReadError()
+ case <-requestCtx.Done():
+ return nil, requestCtx.Err()
+ }
+}
+
+func (c *Conn) readPump() {
+ defer close(c.readDone)
+ for {
+ messageType, data, err := c.ws.Read(c.readCtx)
+ if err != nil {
+ c.readErrMu.Lock()
+ c.readErr = err
+ c.readErrMu.Unlock()
+ return
+ }
+ var parsed map[string]any
+ if err := json.Unmarshal(data, &parsed); err != nil {
+ if recorder := c.recorderSnapshot(); recorder != nil {
+ recorder("in", string(data), "", "non_json", err.Error())
}
continue
}
- consecutive = 0
- if err := waitHeartbeat(ctx, pingErr, interval); err != nil {
- return err
+ c.recordParsedIncoming(data, parsed)
+ if _, hasCode := parsed["code"]; hasCode {
+ if _, hasHeaders := parsed["headers"].(map[string]any); hasHeaders {
+ c.dispatchResponse(parsed)
+ continue
+ }
+ }
+ lwp, hasLWP := parsed["lwp"].(string)
+ _, hasHeaders := parsed["headers"].(map[string]any)
+ if !hasLWP || strings.TrimSpace(lwp) == "" || !hasHeaders {
+ if recorder := c.recorderSnapshot(); recorder != nil {
+ recorder("in", string(data), string(data), "skip_invalid_lwp", "")
+ }
+ continue
+ }
+ incoming := incomingFrame{messageType: messageType, data: append([]byte(nil), data...), parsed: parsed}
+ select {
+ case c.pushes <- incoming:
+ case <-c.readCtx.Done():
+ return
}
}
}
-func waitHeartbeat(ctx context.Context, pingErr <-chan error, delay time.Duration) error {
- timer := time.NewTimer(delay)
- defer timer.Stop()
+func (c *Conn) dispatchResponse(frame map[string]any) bool {
+ headers, _ := frame["headers"].(map[string]any)
+ key := midKey(strings.TrimSpace(fmt.Sprint(headers["mid"])))
+ c.pendingMu.Lock()
+ ch := c.pending[key]
+ c.pendingMu.Unlock()
+ if ch == nil {
+ return false
+ }
select {
- case <-ctx.Done():
- return ctx.Err()
- case err := <-pingErr:
- if err == nil {
- return fmt.Errorf("WebSocket PING 循环意外退出")
+ case ch <- frame:
+ default:
+ }
+ return true
+}
+
+func (c *Conn) connectionReadError() error {
+ c.readErrMu.Lock()
+ defer c.readErrMu.Unlock()
+ if c.readErr != nil {
+ return c.readErr
+ }
+ return fmt.Errorf("WebSocket 读取循环已结束")
+}
+
+func (c *Conn) recordParsedIncoming(data []byte, parsed map[string]any) {
+ recorder := c.recorderSnapshot()
+ if recorder == nil {
+ return
+ }
+ parsedJSON := string(data)
+ if normalized, err := json.Marshal(parsed); err == nil {
+ parsedJSON = string(normalized)
+ }
+ recorder("in", string(data), parsedJSON, "json", "")
+}
+
+// HeartbeatLoop 对齐官网:注册后以固定 15 秒节拍发送 /!,即使上一请求仍在
+// 等待也不推迟下一次;任一请求失败或 30 秒无响应即结束连接。官网只以
+// Promise 是否 reject 判断心跳,不因已收到的非 200 响应主动断线。
+func (c *Conn) HeartbeatLoop(ctx context.Context, interval time.Duration) error {
+ c.ensureReadPump()
+ heartbeatCtx, cancel := context.WithCancel(ctx)
+ defer cancel()
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+ heartbeatErr := make(chan error, 1)
+ for {
+ select {
+ case <-heartbeatCtx.Done():
+ return heartbeatCtx.Err()
+ case <-c.readDone:
+ return c.connectionReadError()
+ case err := <-heartbeatErr:
+ _ = c.Close()
+ return fmt.Errorf("心跳响应失败: %w", err)
+ case <-ticker.C:
+ go func() {
+ _, err := c.request(heartbeatCtx, "/!", map[string]any{}, nil, heartbeatResponseTimeout)
+ if err == nil || heartbeatCtx.Err() != nil {
+ return
+ }
+ select {
+ case heartbeatErr <- err:
+ default:
+ }
+ }()
}
- return err
- case <-timer.C:
- return nil
}
}
-// protocolPingLoop 对齐参考库的 ping_interval=20、ping_timeout=15。
-func (c *Conn) protocolPingLoop(ctx context.Context) error {
- ticker := time.NewTicker(protocolPingInterval)
- defer ticker.Stop()
+// ReceiveLoop 消费 readPump 分发的 Push。响应帧永远不会进入这里,因此不会被
+// 错误 ACK;Push ACK 原样复用服务端完整 headers。
+func (c *Conn) ReceiveLoop(ctx context.Context, onMessage func(decrypted map[string]any)) error {
+ c.ensureReadPump()
for {
+ var frame incomingFrame
select {
case <-ctx.Done():
return ctx.Err()
- case <-ticker.C:
- }
- pingCtx, cancel := context.WithTimeout(ctx, protocolPingTimeout)
- err := c.ws.Ping(pingCtx)
- cancel()
- if err != nil {
- return fmt.Errorf("WebSocket PING 失败: %w", err)
- }
- }
-}
-
-// ReceiveLoop 阻塞读取消息:回 ACK,对同步包解密并回调 handler。
-// 非 JSON / 非同步包消息仅记录后跳过。返回 ctx 错误或致命读取错误。
-func (c *Conn) ReceiveLoop(ctx context.Context, onMessage func(decrypted map[string]any)) error {
- for {
- msgType, data, err := c.ws.Read(ctx)
- if err != nil {
- return fmt.Errorf("WS read: %w", err)
- }
- _ = msgType
- rawText := string(data)
- var raw map[string]any
- if err := json.Unmarshal(data, &raw); err != nil {
- if c.recorder != nil {
- c.recorder("in", rawText, "", "non_json", err.Error())
+ case <-c.readDone:
+ // onmessage is delivered before the subsequent onclose in browsers.
+ // If readPump already queued a final push/control frame, consume it
+ // before surfacing the close.
+ select {
+ case frame = <-c.pushes:
+ default:
+ return fmt.Errorf("WS read: %w", c.connectionReadError())
}
- c.logger.Debug("非 JSON 消息,跳过", "err", err)
- continue
+ case frame = <-c.pushes:
}
- if c.recorder != nil {
- if b, e := json.Marshal(raw); e == nil {
- c.recorder("in", rawText, string(b), "json", "")
- } else {
- c.recorder("in", rawText, "", "json", e.Error())
+ raw := frame.parsed
+ rawText := string(frame.data)
+ switch strings.TrimSpace(fmt.Sprint(raw["lwp"])) {
+ case "/push/kickout":
+ c.readCancel()
+ _ = c.ws.CloseNow()
+ return &RegError{Kind: RegErrorAuthentication, Code: http.StatusUnauthorized, Reason: "server kickout"}
+ case "/s/session/remove":
+ c.readCancel()
+ _ = c.ws.CloseNow()
+ return &RegError{Kind: RegErrorConnectLimit, Code: http.StatusOK, Reason: "session remove"}
+ }
+ // 官网异步启动 sync state 恢复,并立即完成当前 Push handler;不能
+ // 为 getState/ackDiff 最多阻塞 Push ACK 60 秒。
+ go func(message map[string]any) {
+ if err := c.handleSyncExtra(c.readCtx, message); err != nil && c.readCtx.Err() == nil {
+ c.logger.Error("同步状态恢复失败", "err", err)
}
- }
-
- // 心跳响应等直接跳过。
- if code, ok := raw["code"]; ok && code != nil {
- c.logger.Debug("收到响应", "code", code)
- }
-
- // 收到消息后先回复 ACK。
- c.sendACK(ctx, raw)
+ }(raw)
// 仅处理同步包:body.syncPushPackage.data[0].data
syncData, ok := extractSyncPayload(raw)
if !ok {
- if c.recorder != nil {
- c.recorder("in", rawText, "", "skip_non_sync", "")
+ c.sendACK(ctx, raw)
+ if recorder := c.recorderSnapshot(); recorder != nil {
+ recorder("in", rawText, "", "skip_non_sync", "")
}
continue
}
decoded, err := decodeSyncData(syncData)
if err != nil {
- if c.recorder != nil {
- c.recorder("in", rawText, "", "decrypt_failed", err.Error())
+ c.sendACK(ctx, raw)
+ if recorder := c.recorderSnapshot(); recorder != nil {
+ recorder("in", rawText, "", "decrypt_failed", err.Error())
}
c.logger.Error("消息解密失败", "err", err)
continue
}
- if c.recorder != nil {
+ if recorder := c.recorderSnapshot(); recorder != nil {
if b, e := json.Marshal(decoded); e == nil {
- c.recorder("in", rawText, string(b), "decrypted", "")
+ recorder("in", rawText, string(b), "decrypted", "")
}
}
+ c.sendACK(ctx, raw)
if onMessage != nil {
onMessage(decoded)
}
}
}
-// sendACK 回复 {"code":200, headers:{mid,sid,...}},失败时仅记录日志。
+func (c *Conn) handleSyncExtra(ctx context.Context, msg map[string]any) error {
+ body, _ := msg["body"].(map[string]any)
+ extra, _ := body["syncExtraType"].(map[string]any)
+ typeCode, ok := responseCode(extra["type"])
+ if !ok || (typeCode != 1 && typeCode != 2) {
+ return nil
+ }
+ state, err := c.request(ctx, "/r/SyncStatus/getState", map[string]any{}, []any{map[string]any{"topic": "sync"}}, regResponseTimeout)
+ if err != nil {
+ return fmt.Errorf("getState: %w", err)
+ }
+ if code, ok := responseCode(state["code"]); !ok || code != http.StatusOK || state["body"] == nil {
+ return fmt.Errorf("getState 返回异常: code=%v", state["code"])
+ }
+ response, err := c.request(ctx, "/r/SyncStatus/ackDiff", map[string]any{}, []any{state["body"]}, regResponseTimeout)
+ if err != nil {
+ return fmt.Errorf("ackDiff: %w", err)
+ }
+ if code, ok := responseCode(response["code"]); ok && code != http.StatusOK {
+ return fmt.Errorf("ackDiff 返回异常: code=%d", code)
+ }
+ return nil
+}
+
+// sendACK 回复 {"code":200, headers:<服务端完整 headers>}。
func (c *Conn) sendACK(ctx context.Context, msg map[string]any) {
headers, _ := msg["headers"].(map[string]any)
- ack := map[string]any{
- "code": 200,
- "headers": map[string]any{
- "mid": ackVal(headers, "mid", protocol.GenerateMid()),
- "sid": ackVal(headers, "sid", ""),
- },
+ ackHeaders := make(map[string]any, len(headers))
+ for key, value := range headers {
+ ackHeaders[key] = value
}
- ackHeaders := ack["headers"].(map[string]any)
- for _, k := range []string{"app-key", "ua", "dt"} {
- if v, ok := headers[k]; ok && v != nil {
- ackHeaders[k] = v
- }
+ ack := map[string]any{
+ "code": 200,
+ "headers": ackHeaders,
}
// ACK 失败不阻塞主循环。
ackCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
@@ -294,14 +608,6 @@ func (c *Conn) sendACK(ctx context.Context, msg map[string]any) {
cancel()
}
-// ackVal 取 header 中的 key,缺失或为 nil 时返回 fallback。
-func ackVal(headers map[string]any, key string, fallback any) any {
- if v, ok := headers[key]; ok && v != nil {
- return v
- }
- return fallback
-}
-
// extractSyncPayload 取出 body.syncPushPackage.data[0].data(字符串)。
func extractSyncPayload(msg map[string]any) (string, bool) {
body, _ := msg["body"].(map[string]any)
@@ -351,21 +657,18 @@ func (c *Conn) sendJSON(ctx context.Context, v any) error {
if err != nil {
return err
}
- if c.recorder != nil {
- c.recorder("out", string(b), string(b), "json", "")
+ if recorder := c.recorderSnapshot(); recorder != nil {
+ recorder("out", string(b), string(b), "json", "")
+ }
+ select {
+ case c.sendGate <- struct{}{}:
+ defer func() { <-c.sendGate }()
+ case <-ctx.Done():
+ return ctx.Err()
}
- c.sendMu.Lock()
- defer c.sendMu.Unlock()
return c.ws.Write(ctx, websocket.MessageText, b)
}
-// SetAccessToken 在线更新 token(仅在连接保持期间用于定时刷新)。
-func (c *Conn) SetAccessToken(token string) {
- c.sendMu.Lock()
- defer c.sendMu.Unlock()
- c.cfg.AccessToken = token
-}
-
// SendText 发送一条闲鱼聊天文本消息。
func (c *Conn) SendText(ctx context.Context, myID, cid, toID, text string) error {
content := map[string]any{
@@ -457,5 +760,7 @@ func stripGoofish(s string) string {
// Close 关闭连接。
func (c *Conn) Close() error {
+ c.ensureReadPump()
+ c.readCancel()
return c.ws.Close(websocket.StatusNormalClosure, "bye")
}
diff --git a/internal/xianyu/ws/client_test.go b/internal/xianyu/ws/client_test.go
index 935a214..4a34c55 100644
--- a/internal/xianyu/ws/client_test.go
+++ b/internal/xianyu/ws/client_test.go
@@ -2,15 +2,35 @@ package ws
import (
"encoding/base64"
- "reflect"
"testing"
+
+ "xianyu-go/internal/xianyu"
)
-func TestWebsocketHeadersOnlyContainSanitizedCookie(t *testing.T) {
- got := websocketHeaders("a=1;\r\nb=2")
- want := map[string][]string{"Cookie": {"a=1;b=2"}}
- if !reflect.DeepEqual(map[string][]string(got), want) {
- t.Fatalf("websocket headers = %#v, want %#v", got, want)
+func TestWebsocketHeadersMatchBrowserHandshake(t *testing.T) {
+ xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "runtime-browser-ua"})
+ got := websocketHeaders()
+ if got.Get("Origin") != "https://www.goofish.com" || got.Get("User-Agent") != "runtime-browser-ua" {
+ t.Fatalf("websocket headers = %#v", got)
+ }
+ if got.Get("Cookie") != "" {
+ t.Fatalf("dingtalk WebSocket 不应收到 goofish Cookie: %#v", got)
+ }
+}
+
+func TestOfficialRegistrationUAUsesRuntimeBrowserVersion(t *testing.T) {
+ raw := "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/138.0.7204.92 Safari/537.36"
+ want := raw + " DingTalk(2.2.0) OS(Mac OS/10.15.7) Browser(Chrome/138.0.7204.92) DingWeb/2.2.0 IMPaaS DingWeb/2.2.0"
+ if got := OfficialRegistrationUA(raw); got != want {
+ t.Fatalf("OfficialRegistrationUA() = %q, want %q", got, want)
+ }
+}
+
+func TestOfficialRegistrationUARecognizesHeadlessChrome(t *testing.T) {
+ raw := "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 HeadlessChrome/138.0.7204.92 Safari/537.36"
+ want := raw + " DingTalk(2.2.0) OS(Linux/other) Browser(Chrome Headless/138.0.7204.92) DingWeb/2.2.0 IMPaaS DingWeb/2.2.0"
+ if got := OfficialRegistrationUA(raw); got != want {
+ t.Fatalf("OfficialRegistrationUA() = %q, want %q", got, want)
}
}
@@ -40,13 +60,6 @@ func TestDecodeSyncDataJSONAndInvalid(t *testing.T) {
}
func TestWSHelpers(t *testing.T) {
- headers := map[string]any{"mid": "m1", "nil": nil}
- if got := ackVal(headers, "mid", "fallback"); got != "m1" {
- t.Fatalf("ackVal existing = %v", got)
- }
- if got := ackVal(headers, "nil", "fallback"); got != "fallback" {
- t.Fatalf("ackVal nil = %v", got)
- }
if got := stripGoofish(" 123@goofish "); got != "123" {
t.Fatalf("stripGoofish = %q", got)
}
diff --git a/internal/xianyu/ws/dial_test.go b/internal/xianyu/ws/dial_test.go
index 2a17fb4..c8ceacb 100644
--- a/internal/xianyu/ws/dial_test.go
+++ b/internal/xianyu/ws/dial_test.go
@@ -9,6 +9,7 @@ import (
"net/http/httptest"
"strings"
"sync"
+ "sync/atomic"
"testing"
"time"
@@ -17,8 +18,7 @@ import (
"xianyu-go/internal/xianyu"
)
-// startRegServer 启动一个本地 WS 服务,模拟 /reg 握手:读取客户端发来的 /reg 与
-// ackDiff 两条消息,验证它们的结构,然后保持连接打开(由调用方决定何时关闭)。
+// startRegServer 启动一个本地 WS 服务,模拟 /reg 握手并保持连接打开。
// 返回服务实例与一个收集到所有客户端消息的 channel。
func startRegServer(t *testing.T) (*httptest.Server, chan map[string]any) {
t.Helper()
@@ -42,6 +42,20 @@ func startRegServer(t *testing.T) (*httptest.Server, chan map[string]any) {
case got <- m:
default:
}
+ if m["lwp"] == "/reg" {
+ headers, _ := m["headers"].(map[string]any)
+ response := map[string]any{
+ "code": 200,
+ "headers": map[string]any{
+ "mid": headers["mid"],
+ "reg-uid": "123@goofish",
+ },
+ }
+ raw, _ := json.Marshal(response)
+ if err := c.Write(ctx, websocket.MessageText, raw); err != nil {
+ return
+ }
+ }
}
}
}))
@@ -61,18 +75,100 @@ func dialLocal(t *testing.T, srv *httptest.Server, cfg Config) *Conn {
}
dialed.SetReadLimit(8 << 20)
t.Cleanup(func() { _ = dialed.CloseNow() })
- return &Conn{ws: dialed, cfg: cfg, logger: nilLogger(), recorder: cfg.Recorder}
+ return newConn(dialed, cfg, nilLogger())
}
-// TestRegister_SendsRegAndAckDiff 直接调用 register 覆盖 /reg 握手 + ackDiff 两条消息。
-// 验证:1) /reg 消息含正确 lwp/app-key/token/ua/did;2) ackDiff 消息 lwp 正确且 body 非空。
-func TestRegister_SendsRegAndAckDiff(t *testing.T) {
- xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "playwright-native-ua"})
+// TestOpenBatchRacesDelayedConnections 验证官网 batchConnectWs 会在首条握手
+// 迟滞时启动后续连接,并采用最先成功者。
+func TestOpenBatchRacesDelayedConnections(t *testing.T) {
+ originalDelays := batchConnectDelays
+ batchConnectDelays = []time.Duration{0, 20 * time.Millisecond, 60 * time.Millisecond}
+ t.Cleanup(func() { batchConnectDelays = originalDelays })
+
+ var attempts atomic.Int32
+ firstAttempt := make(chan struct{})
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ attempt := attempts.Add(1)
+ if attempt == 1 {
+ close(firstAttempt)
+ <-r.Context().Done()
+ return
+ }
+ c, err := websocket.Accept(w, r, &websocket.AcceptOptions{InsecureSkipVerify: true})
+ if err != nil {
+ return
+ }
+ defer c.CloseNow()
+ <-r.Context().Done()
+ }))
+ t.Cleanup(srv.Close)
+
+ type openResult struct {
+ conn *Conn
+ err error
+ }
+ resultCh := make(chan openResult, 1)
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ go func() {
+ conn, err := openBatch(ctx, wsURL(srv), Config{}, nilLogger())
+ resultCh <- openResult{conn: conn, err: err}
+ }()
+
+ select {
+ case <-firstAttempt:
+ case <-time.After(time.Second):
+ t.Fatal("WebSocket 首次握手未开始")
+ }
+ select {
+ case result := <-resultCh:
+ if result.err != nil {
+ t.Fatalf("openBatch: %v", result.err)
+ }
+ t.Cleanup(func() { _ = result.conn.ws.CloseNow() })
+ case <-time.After(time.Second):
+ t.Fatal("后续竞速连接未在首条握手阻塞时成功")
+ }
+ if got := attempts.Load(); got < 2 {
+ t.Fatalf("WebSocket 握手次数=%d,期望至少启动 2 条竞速连接", got)
+ }
+}
+
+// TestOpenBatchFirstFailureWins mirrors Promise.race: a fast failed handshake
+// rejects the whole batch even when a later candidate could have connected.
+func TestOpenBatchFirstFailureWins(t *testing.T) {
+ originalDelays := batchConnectDelays
+ batchConnectDelays = []time.Duration{0, 100 * time.Millisecond}
+ t.Cleanup(func() { batchConnectDelays = originalDelays })
+
+ var attempts atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ attempts.Add(1)
+ http.Error(w, "handshake rejected", http.StatusServiceUnavailable)
+ }))
+ t.Cleanup(srv.Close)
+
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ conn, err := openBatch(ctx, wsURL(srv), Config{}, nilLogger())
+ if err == nil || conn != nil {
+ t.Fatalf("openBatch conn=%v err=%v,期望首个握手失败直接结束", conn, err)
+ }
+ time.Sleep(150 * time.Millisecond)
+ if got := attempts.Load(); got != 2 {
+ t.Fatalf("官网延迟任务应继续启动,实际握手 %d 次,期望 2", got)
+ }
+}
+
+// TestRegisterSendsOnlyOfficialReg 验证注册只发送 /reg,不再伪造 ackDiff。
+func TestRegisterSendsOnlyOfficialReg(t *testing.T) {
+ rawUA := "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/138.0.7204.92 Safari/537.36"
+ xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: rawUA})
srv, got := startRegServer(t)
conn := dialLocal(t, srv, Config{
CookieStr: "cookie=1",
DeviceID: "device-xyz",
- AccessToken: "token-abc",
+ AccessToken: "token%2Fabc%2Braw",
})
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
@@ -89,15 +185,15 @@ collect:
select {
case m := <-got:
msgs = append(msgs, m)
- if len(msgs) >= 2 {
+ if len(msgs) >= 1 {
break collect
}
case <-timer.C:
break collect
}
}
- if len(msgs) < 2 {
- t.Fatalf("期望收到 2 条消息,实际 %d: %#v", len(msgs), msgs)
+ if len(msgs) != 1 {
+ t.Fatalf("期望只收到 /reg,实际 %d: %#v", len(msgs), msgs)
}
reg := msgs[0]
@@ -108,11 +204,11 @@ collect:
if headers["app-key"] != RegAppKey {
t.Errorf("/reg app-key = %v, 期望 %s", headers["app-key"], RegAppKey)
}
- if headers["token"] != "token-abc" {
- t.Errorf("/reg token = %v, 期望 token-abc", headers["token"])
+ if headers["token"] != "token/abc+raw" {
+ t.Errorf("/reg token = %v, 期望 decodeURIComponent 后的 token/abc+raw", headers["token"])
}
- if headers["ua"] != "playwright-native-ua" {
- t.Errorf("/reg ua = %v, 期望 Playwright 原生 UA", headers["ua"])
+ if headers["ua"] != OfficialRegistrationUA(rawUA) {
+ t.Errorf("/reg ua = %v, 期望官方复合 UA", headers["ua"])
}
if headers["did"] != "device-xyz" {
t.Errorf("/reg did = %v, 期望 device-xyz", headers["did"])
@@ -121,27 +217,32 @@ collect:
t.Errorf("/reg mid 应为非空字符串, 实际 %v", headers["mid"])
}
- ackDiff := msgs[1]
- if ackDiff["lwp"] != "/r/SyncStatus/ackDiff" {
- t.Fatalf("第二条消息 lwp 应为 ackDiff, 实际 %v", ackDiff["lwp"])
- }
- body, _ := ackDiff["body"].([]any)
- if len(body) == 0 {
- t.Fatalf("ackDiff body 为空")
- }
- first, _ := body[0].(map[string]any)
- if first["pipeline"] != "sync" || first["channel"] != "sync" {
- t.Errorf("ackDiff body[0] 结构异常: %#v", first)
+}
+
+func TestRegisterRejectsDecodeURIComponentInvalidUTF8(t *testing.T) {
+ srv, _ := startRegServer(t)
+ conn := dialLocal(t, srv, Config{DeviceID: "did", AccessToken: "%FF"})
+ err := conn.register(context.Background())
+ if err == nil || !strings.Contains(err.Error(), "非法 UTF-8") {
+ t.Fatalf("register error=%v", err)
}
}
-// TestRegister_ContextCancelledDuringWait register 在 1 秒等待期间 ctx 取消应返回 ctx.Err。
+// TestRegister_ContextCancelledDuringWait register 等不到响应时应服从 ctx 取消。
func TestRegister_ContextCancelledDuringWait(t *testing.T) {
- srv, _ := startRegServer(t)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ c, err := websocket.Accept(w, r, nil)
+ if err != nil {
+ return
+ }
+ defer c.CloseNow()
+ _, _, _ = c.Read(r.Context())
+ <-r.Context().Done()
+ }))
+ t.Cleanup(srv.Close)
conn := dialLocal(t, srv, Config{})
ctx, cancel := context.WithCancel(context.Background())
- // 等到 /reg 发出、进入 1 秒等待后再取消。
go func() {
time.Sleep(100 * time.Millisecond)
cancel()
@@ -152,6 +253,143 @@ func TestRegister_ContextCancelledDuringWait(t *testing.T) {
}
}
+func TestRegisterResponseWinsImmediateClose(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ c, err := websocket.Accept(w, r, nil)
+ if err != nil {
+ return
+ }
+ defer c.CloseNow()
+ _, raw, err := c.Read(r.Context())
+ if err != nil {
+ return
+ }
+ var request map[string]any
+ if json.Unmarshal(raw, &request) != nil {
+ return
+ }
+ headers, _ := request["headers"].(map[string]any)
+ response, _ := json.Marshal(map[string]any{
+ "code": 200, "headers": map[string]any{"mid": headers["mid"], "reg-uid": "123@goofish"},
+ })
+ _ = c.Write(r.Context(), websocket.MessageText, response)
+ }))
+ t.Cleanup(srv.Close)
+ conn := dialLocal(t, srv, Config{DeviceID: "did", AccessToken: "token"})
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ if err := conn.register(ctx); err != nil {
+ t.Fatalf("服务端响应后立即断链不应覆盖成功响应: %v", err)
+ }
+}
+
+// TestRequestTimeoutIncludesSendPhase 验证请求超时从等待发送权开始计算,
+// 不会因另一条半开连接写入占用发送权而永久阻塞。
+func TestRequestTimeoutIncludesSendPhase(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ c, err := websocket.Accept(w, r, nil)
+ if err != nil {
+ return
+ }
+ defer c.CloseNow()
+ <-r.Context().Done()
+ }))
+ t.Cleanup(srv.Close)
+ conn := dialLocal(t, srv, Config{})
+
+ conn.sendGate <- struct{}{}
+ started := time.Now()
+ _, err := conn.request(context.Background(), "/!", map[string]any{}, nil, 60*time.Millisecond)
+ elapsed := time.Since(started)
+ <-conn.sendGate
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("request error=%v,期望 context.DeadlineExceeded", err)
+ }
+ if elapsed > 500*time.Millisecond {
+ t.Fatalf("发送阶段未及时超时,耗时 %v", elapsed)
+ }
+ conn.pendingMu.Lock()
+ pending := len(conn.pending)
+ conn.pendingMu.Unlock()
+ if pending != 0 {
+ t.Fatalf("请求超时后仍残留 %d 个 pending", pending)
+ }
+}
+
+func TestRegisterRejectsInvalidToken(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ c, err := websocket.Accept(w, r, nil)
+ if err != nil {
+ return
+ }
+ defer c.CloseNow()
+ _, data, err := c.Read(r.Context())
+ if err != nil {
+ return
+ }
+ var reg map[string]any
+ _ = json.Unmarshal(data, ®)
+ headers, _ := reg["headers"].(map[string]any)
+ response, _ := json.Marshal(map[string]any{
+ "code": 401,
+ "headers": map[string]any{"mid": headers["mid"]},
+ "body": map[string]any{"reason": "invalid token"},
+ })
+ _ = c.Write(r.Context(), websocket.MessageText, response)
+ }))
+ t.Cleanup(srv.Close)
+
+ conn := dialLocal(t, srv, Config{AccessToken: "rejected"})
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ err := conn.register(ctx)
+ if !IsInvalidTokenError(err) {
+ t.Fatalf("register error=%v, want invalid token", err)
+ }
+}
+
+func TestRegisterBuffersFrameBeforeResponse(t *testing.T) {
+ push := map[string]any{"lwp": "/push/test", "headers": map[string]any{"mid": "push-1"}}
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ c, err := websocket.Accept(w, r, nil)
+ if err != nil {
+ return
+ }
+ defer c.CloseNow()
+ ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
+ defer cancel()
+ _, data, err := c.Read(ctx)
+ if err != nil {
+ return
+ }
+ var reg map[string]any
+ _ = json.Unmarshal(data, ®)
+ headers, _ := reg["headers"].(map[string]any)
+ pushRaw, _ := json.Marshal(push)
+ _ = c.Write(ctx, websocket.MessageText, pushRaw)
+ response, _ := json.Marshal(map[string]any{"code": 200, "headers": map[string]any{"mid": headers["mid"]}})
+ _ = c.Write(ctx, websocket.MessageText, response)
+ }))
+ t.Cleanup(srv.Close)
+
+ conn := dialLocal(t, srv, Config{})
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ if err := conn.register(ctx); err != nil {
+ t.Fatalf("register: %v", err)
+ }
+ var got map[string]any
+ select {
+ case frame := <-conn.pushes:
+ got = frame.parsed
+ case <-ctx.Done():
+ t.Fatalf("read buffered frame: %v", ctx.Err())
+ }
+ if got["lwp"] != push["lwp"] {
+ t.Fatalf("buffered frame=%v want=%v", got, push)
+ }
+}
+
// TestDial_RegisterFailure register 的 ackDiff 发送失败时应返回错误。
// 服务端 accept 后等待 1.5s(超过 register 内 1s 等待)再 CloseNow,
// 使 ackDiff 的 sendJSON 写入已关闭连接而失败。
@@ -178,7 +416,7 @@ func TestDial_RegisterFailure(t *testing.T) {
}
defer dialed.CloseNow()
dialed.SetReadLimit(8 << 20)
- conn := &Conn{ws: dialed, cfg: Config{}, logger: nilLogger()}
+ conn := newConn(dialed, Config{}, nilLogger())
err = conn.register(dialCtx)
if err == nil {
t.Fatal("register 应在连接关闭时返回错误")
@@ -196,6 +434,7 @@ func TestSendACK_RepliesWithMidSid(t *testing.T) {
defer c.Close(websocket.StatusNormalClosure, "")
// 发一条带 mid/sid 的非同步消息(无 syncPushPackage),客户端应回 ACK 但不调 onMessage。
frame := map[string]any{
+ "lwp": "/push/test",
"headers": map[string]any{
"mid": "server-mid-1",
"sid": "server-sid-1",
@@ -223,6 +462,7 @@ func TestSendACK_RepliesWithMidSid(t *testing.T) {
ackBytes, _ := json.Marshal(map[string]any{"ack": ack})
b64 := base64.StdEncoding.EncodeToString(ackBytes)
echo, _ := json.Marshal(map[string]any{
+ "lwp": "/s/sync",
"headers": map[string]any{"mid": "echo"},
"body": map[string]any{"syncPushPackage": map[string]any{"data": []any{map[string]any{"data": b64}}}},
})
@@ -240,7 +480,7 @@ func TestSendACK_RepliesWithMidSid(t *testing.T) {
defer dialed.CloseNow()
dialed.SetReadLimit(8 << 20)
- conn := &Conn{ws: dialed, logger: nilLogger()}
+ conn := newConn(dialed, Config{}, nilLogger())
var ackSeen map[string]any
var onMessageCount int
loopDone := make(chan error, 1)
@@ -278,8 +518,8 @@ func TestSendACK_RepliesWithMidSid(t *testing.T) {
}
}
-// TestSendACK_NoHeaders 消息无 headers 时 ACK 用 fallback mid(GenerateMid 非空)且 sid 为空。
-func TestSendACK_NoHeaders(t *testing.T) {
+// TestReceiveLoop_NoHeadersIsIgnored 官网只把同时包含 lwp/headers 的帧当 Push。
+func TestReceiveLoop_NoHeadersIsIgnored(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c, err := websocket.Accept(w, r, nil)
if err != nil {
@@ -291,22 +531,6 @@ func TestSendACK_NoHeaders(t *testing.T) {
_ = c.Write(r.Context(), websocket.MessageText, raw)
ctx, cancel := context.WithTimeout(r.Context(), time.Second)
defer cancel()
- _, data, err := c.Read(ctx)
- if err != nil {
- return
- }
- var ack map[string]any
- if json.Unmarshal(data, &ack) != nil {
- return
- }
- // 回写 echo 带 ack(包成同步推送帧)。
- ackBytes, _ := json.Marshal(map[string]any{"ack": ack})
- b64 := base64.StdEncoding.EncodeToString(ackBytes)
- echo, _ := json.Marshal(map[string]any{
- "headers": map[string]any{"mid": "echo"},
- "body": map[string]any{"syncPushPackage": map[string]any{"data": []any{map[string]any{"data": b64}}}},
- })
- _ = c.Write(r.Context(), websocket.MessageText, echo)
_, _, _ = c.Read(ctx)
}))
t.Cleanup(srv.Close)
@@ -320,39 +544,64 @@ func TestSendACK_NoHeaders(t *testing.T) {
defer dialed.CloseNow()
dialed.SetReadLimit(8 << 20)
- conn := &Conn{ws: dialed, logger: nilLogger()}
- var ackSeen map[string]any
+ conn := newConn(dialed, Config{}, nilLogger())
+ var called bool
loopDone := make(chan error, 1)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
go func() {
- loopDone <- conn.ReceiveLoop(ctx, func(d map[string]any) {
- if ack, ok := d["ack"].(map[string]any); ok {
- ackSeen = ack
- }
- })
+ loopDone <- conn.ReceiveLoop(ctx, func(map[string]any) { called = true })
}()
<-loopDone
- if ackSeen == nil {
- t.Fatal("未收到 ack")
- }
- ackHeaders, _ := ackSeen["headers"].(map[string]any)
- mid, _ := ackHeaders["mid"].(string)
- if mid == "" {
- t.Errorf("无 headers 时 ACK mid 应用 fallback (GenerateMid), 实际空")
- }
- if ackHeaders["sid"] != "" {
- t.Errorf("无 headers 时 ACK sid 应为空, 实际 %v", ackHeaders["sid"])
+ if called {
+ t.Fatal("无 headers 的帧不应进入 Push 回调")
}
}
-// TestHeartbeatLoop_SendFailure 服务端立刻关闭连接,HeartbeatLoop 的 sendJSON 应失败;
-// 连续失败达 maxFailures(3) 次后应返回错误。
-func TestHeartbeatLoop_SendFailure(t *testing.T) {
- oldRetry := heartbeatRetryInterval
- heartbeatRetryInterval = 20 * time.Millisecond
- t.Cleanup(func() { heartbeatRetryInterval = oldRetry })
+func TestReceiveLoop_OfficialControlPushesCloseSession(t *testing.T) {
+ tests := []struct {
+ name string
+ lwp string
+ matchesErr func(error) bool
+ }{
+ {name: "kickout", lwp: "/push/kickout", matchesErr: IsAuthenticationError},
+ {name: "session remove", lwp: "/s/session/remove", matchesErr: IsConnectLimitError},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ c, err := websocket.Accept(w, r, nil)
+ if err != nil {
+ return
+ }
+ defer c.CloseNow()
+ frame, _ := json.Marshal(map[string]any{
+ "lwp": tt.lwp, "headers": map[string]any{"mid": "control-1", "sid": "s1"},
+ })
+ _ = c.Write(r.Context(), websocket.MessageText, frame)
+ // 官网控制 handler 先发起 close,随后 LWP 的 ACK 尝试通常因
+ // readyState=CLOSING 失败;紧接着断链也不能吞掉控制事件。
+ }))
+ defer srv.Close()
+ dialCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ dialed, _, err := websocket.Dial(dialCtx, wsURL(srv), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer dialed.CloseNow()
+ conn := newConn(dialed, Config{}, nilLogger())
+ err = conn.ReceiveLoop(dialCtx, nil)
+ if !tt.matchesErr(err) {
+ t.Fatalf("ReceiveLoop err=%v", err)
+ }
+ })
+ }
+}
+
+// TestHeartbeatLoop_SendFailure 服务端关闭后心跳立即结束,不做三次写失败重试。
+func TestHeartbeatLoop_SendFailure(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c, err := websocket.Accept(w, r, nil)
if err != nil {
@@ -372,7 +621,7 @@ func TestHeartbeatLoop_SendFailure(t *testing.T) {
defer dialed.CloseNow()
dialed.SetReadLimit(8 << 20)
- conn := &Conn{ws: dialed, logger: nilLogger()}
+ conn := newConn(dialed, Config{}, nilLogger())
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
loopDone := make(chan error, 1)
@@ -384,9 +633,6 @@ func TestHeartbeatLoop_SendFailure(t *testing.T) {
if err == nil {
t.Fatal("HeartbeatLoop 应在连续失败后返回错误")
}
- if !strings.Contains(err.Error(), "心跳连续失败") {
- t.Fatalf("期望心跳连续失败错误, 实际 %v", err)
- }
case <-time.After(8 * time.Second):
t.Fatal("HeartbeatLoop 未在超时内退出")
}
@@ -646,35 +892,6 @@ func TestSendChatContent_MissingParams(t *testing.T) {
}
}
-// TestSetAccessToken_AppliedToSubsequentSend SetAccessToken 后 register/SendText 发送的消息
-// 应携带新 token(通过 register 验证,因为 SendText 不直接带 token;这里用 register 覆盖)。
-func TestSetAccessToken_AppliedToSubsequentSend(t *testing.T) {
- srv, got := startRegServer(t)
- conn := dialLocal(t, srv, Config{AccessToken: "old-token"})
-
- // 在线更新 token。
- conn.SetAccessToken("new-token-999")
-
- ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
- defer cancel()
- if err := conn.register(ctx); err != nil {
- t.Fatalf("register: %v", err)
- }
-
- select {
- case m := <-got:
- if m["lwp"] != "/reg" {
- t.Fatalf("期望首条为 /reg, 实际 %v", m["lwp"])
- }
- headers, _ := m["headers"].(map[string]any)
- if headers["token"] != "new-token-999" {
- t.Errorf("/reg token = %v, 期望 new-token-999 (在线更新后)", headers["token"])
- }
- case <-time.After(2 * time.Second):
- t.Fatal("服务端未收到 /reg")
- }
-}
-
// TestSetRecorder_RecordsOutgoingAndIncoming SetRecorder 后 outgoing/incoming 都应触发回调。
func TestSetRecorder_RecordsOutgoingAndIncoming(t *testing.T) {
payload := `{"event":"paid"}`
@@ -700,7 +917,7 @@ func TestSetRecorder_RecordsOutgoingAndIncoming(t *testing.T) {
dir, parsed, status string
}{direction, parsedJSON, parseStatus})
}
- conn := &Conn{ws: dialed, logger: nilLogger()}
+ conn := newConn(dialed, Config{}, nilLogger())
// 通过 SetRecorder 方法设置(覆盖该方法),而非直接赋值字段。
conn.SetRecorder(rec)
if conn.recorder == nil {
@@ -766,7 +983,7 @@ func TestClose_TerminatesConnection(t *testing.T) {
t.Fatalf("dial: %v", err)
}
dialed.SetReadLimit(8 << 20)
- conn := &Conn{ws: dialed, logger: nilLogger()}
+ conn := newConn(dialed, Config{}, nilLogger())
if err := conn.Close(); err != nil {
t.Fatalf("Close: %v", err)
diff --git a/internal/xianyu/ws/receive_loop_test.go b/internal/xianyu/ws/receive_loop_test.go
index cdceed8..94d7d37 100644
--- a/internal/xianyu/ws/receive_loop_test.go
+++ b/internal/xianyu/ws/receive_loop_test.go
@@ -28,6 +28,7 @@ func startWSEchoServer(t *testing.T, payload string) *httptest.Server {
// 构造同步推送帧:body.syncPushPackage.data[0].data = base64(payload)。
b64 := base64.StdEncoding.EncodeToString([]byte(payload))
frame := map[string]any{
+ "lwp": "/s/sync",
"headers": map[string]any{"mid": "m1", "sid": "s1"},
"body": map[string]any{"syncPushPackage": map[string]any{
"data": []any{map[string]any{"data": b64}},
@@ -66,7 +67,7 @@ func TestReceiveLoop_DecodesSyncPayload(t *testing.T) {
defer dialed.CloseNow()
dialed.SetReadLimit(8 << 20)
- conn := &Conn{ws: dialed, logger: nilLogger()}
+ conn := newConn(dialed, Config{}, nilLogger())
var got map[string]any
loopDone := make(chan error, 1)
@@ -100,6 +101,7 @@ func TestReceiveLoop_NonJSONSkipped(t *testing.T) {
c.Write(r.Context(), websocket.MessageText, []byte("not-json"))
b64 := base64.StdEncoding.EncodeToString([]byte(`{"ok":true}`))
frame := map[string]any{
+ "lwp": "/s/sync",
"headers": map[string]any{"mid": "m2"},
"body": map[string]any{"syncPushPackage": map[string]any{"data": []any{map[string]any{"data": b64}}}},
}
@@ -120,7 +122,7 @@ func TestReceiveLoop_NonJSONSkipped(t *testing.T) {
defer dialed.CloseNow()
dialed.SetReadLimit(8 << 20)
- conn := &Conn{ws: dialed, logger: nilLogger()}
+ conn := newConn(dialed, Config{}, nilLogger())
var got map[string]any
loopDone := make(chan error, 1)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
@@ -162,7 +164,7 @@ func TestHeartbeatLoop_ContextCancel(t *testing.T) {
defer dialed.CloseNow()
dialed.SetReadLimit(8 << 20)
- conn := &Conn{ws: dialed, logger: nilLogger()}
+ conn := newConn(dialed, Config{}, nilLogger())
ctx, cancel := context.WithCancel(context.Background())
loopDone := make(chan error, 1)
go func() {
|