合并登录续期与 x86 Docker 部署改进

This commit is contained in:
Christ committed 2026-07-23 16:03:27 +08:00
commit 6a9a684e5e
124 files changed
+10742 -4417

No files matched your search

+2
View File
@@ -1,5 +1,7 @@
.git
.gitignore
.env
.env.*
data
browser_data
frontend/node_modules
+24
View File
@@ -0,0 +1,24 @@
# 复制为 .env 后再填写。不要提交包含真实密钥的 .env。
COMPOSE_PROJECT_NAME=xianyu
# PostgreSQL 17
POSTGRES_IMAGE=postgres:17-trixie
POSTGRES_DB=xianyu
POSTGRES_USER=xianyu
POSTGRES_PASSWORD=请替换为高强度数据库密码
# 密码含有特殊字符时,必须先进行 URL 编码。
DATABASE_URL=postgres://xianyu:请替换为URL编码后的数据库密码@postgres:5432/xianyu?sslmode=disable
# 应用
XIANYU_IMAGE=xianyu-go:debian13-amd64
XIANYU_DATA_KEY=请替换为稳定且足够长的随机密钥
XIANYU_BIND_ADDRESS=0.0.0.0
XIANYU_HTTP_PORT=8080
XIANYU_UPLOAD_DIR=/app/data/uploads
TZ=Asia/Shanghai
LOG_LEVEL=info
LOG_FORMAT=json
BROWSER_HEADLESS=true
# 仅在执行 init-admin profile 时使用。
XIANYU_ADMIN_PASSWORD=请替换为管理员密码
+5
View File
@@ -8,6 +8,11 @@
!/Dockerfile.test
*.out
# Local deployment environment (keep secrets out of Git)
/.env
/.env.*
!/.env.example
# Runtime data
/data/
/browser_data/
+10 -6
View File
@@ -1,11 +1,13 @@
FROM node:22-trixie AS frontend
# syntax=docker/dockerfile:1.7
FROM --platform=$BUILDPLATFORM node:22-trixie AS frontend
WORKDIR /src/frontend
COPY frontend/package*.json ./
RUN npm ci
COPY frontend/ ./
RUN npm run build
FROM node:22-trixie AS playwright-driver
FROM --platform=$BUILDPLATFORM node:22-trixie AS playwright-driver
RUN npm install -g playwright@1.57.0 \
&& mkdir -p /ms-playwright-go/package \
&& cp -a /usr/local/lib/node_modules/playwright/. /ms-playwright-go/package/ \
@@ -14,15 +16,17 @@ RUN npm install -g playwright@1.57.0 \
&& cp -a /usr/local/lib/node_modules/playwright-core /ms-playwright-go/package/node_modules/playwright-core; \
fi
FROM golang:1.26-trixie AS backend
FROM --platform=$BUILDPLATFORM golang:1.26-trixie AS backend
ARG TARGETOS
ARG TARGETARCH
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
COPY --from=frontend /src/internal/webui/static ./internal/webui/static
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/xianyu-server ./cmd/server \
&& CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbseed ./cmd/dbseed \
&& CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbverify ./cmd/dbverify
RUN CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldflags="-s -w" -o /out/xianyu-server ./cmd/server \
&& CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbseed ./cmd/dbseed \
&& CGO_ENABLED=0 GOOS="$TARGETOS" GOARCH="$TARGETARCH" go build -trimpath -ldflags="-s -w" -o /out/xianyu-dbverify ./cmd/dbverify
FROM debian:13-slim AS runtime
ENV TZ=Asia/Shanghai
+23 -8
View File
@@ -158,25 +158,40 @@ go run ./cmd/dbverify "postgres://user:pass@host:5432/db"
## Docker 部署注意
批量铺货会用到上传目录。容器部署时建议挂载持久化数据:
仓库提供 `docker-compose.debian13-postgres17.yml`,用于在 x86_64 Linux 上运行
Debian 13 应用镜像和 PostgreSQL 17。Compose 明确锁定 `linux/amd64`,即使在 ARM
开发机上也会构建并验证 x86_64 镜像。
```bash
-v ./data:/app/data
cp .env.example .env
# 编辑 .env,至少替换 PostgreSQL 密码、DATABASE_URL 和 XIANYU_DATA_KEY
docker compose -f docker-compose.debian13-postgres17.yml build app
docker compose -f docker-compose.debian13-postgres17.yml up -d postgres app
```
并设置:
数据库只在 Compose 内部网络开放,不映射宿主机端口;应用端口由
`XIANYU_BIND_ADDRESS` 和 `XIANYU_HTTP_PORT` 控制。PostgreSQL 数据、应用数据和
Chromium 持久化配置分别保存在命名卷 `postgres_data`、`app_data` 和
`browser_data` 中。
首次部署后初始化管理员:
```bash
XIANYU_UPLOAD_DIR=/app/data/uploads
docker compose -f docker-compose.debian13-postgres17.yml --profile init run --rm init-admin
```
数据库建议放在:
检查服务和日志:
```text
/app/data/xianyu_data.db
```bash
docker compose -f docker-compose.debian13-postgres17.yml ps
curl -fsS http://127.0.0.1:8080/health
docker compose -f docker-compose.debian13-postgres17.yml logs -f app
```
外置 MySQL/Postgres 时改用 `DATABASE_URL` 环境变量。
`.env` 已被 Git 和 Docker 构建上下文忽略。`DATABASE_URL` 必须使用 Compose 服务名
`postgres` 作为主机;如果密码包含 `@`、`:`、`/` 等字符,需要在连接串中进行 URL
编码。部署到服务器前可用 `openssl rand -base64 48` 生成稳定的
`XIANYU_DATA_KEY`,并与数据库卷一同安全备份。
生产环境建议同时设置稳定且仅由服务进程可读的 `XIANYU_DATA_KEY`。启用后,Cookie、
账号登录密码、设备/访问令牌、AI/SMTP 密钥和通知渠道配置会使用 AES-256-GCM 加密
+7 -8
View File
@@ -8,8 +8,8 @@
//
// 首次使用可直接用本二进制初始化管理员,不再需要单独 init-admin。
//
// 浏览器自动化(扫码风控验证、密码登录、订单抓取)内置 playwright-go,
// 首次使用时自动下载 Chromium。加 -no-browser 可禁用。
// Chromium 仅用于读取本机浏览器指纹和处理 token 滑块,首次使用时由
// playwright-go 准备运行环境。加 -no-browser 可禁用这两项能力。
package main
import (
@@ -32,7 +32,6 @@ import (
"xianyu-go/internal/notify"
"xianyu-go/internal/renewal"
"xianyu-go/internal/server"
"xianyu-go/internal/xianyu/mtop"
)
func main() {
@@ -41,7 +40,7 @@ func main() {
addr := flag.String("addr", ":8080", "HTTP 监听地址")
webDir := flag.String("web", "", "前端静态资源目录(含 index.html)")
secure := flag.Bool("secure", false, "HTTPS 模式(Cookie 加 Secure)")
noBrowser := flag.Bool("no-browser", false, "禁用内置浏览器自动化(扫码风控验证/密码登录/订单抓取将不可用)")
noBrowser := flag.Bool("no-browser", false, "禁用 Chromium(本机浏览器指纹读取和 token 滑块自动处理将不可用)")
verbose := flag.Bool("v", false, "调试日志")
logLevel := flag.String("log-level", "", "日志等级:debug/info/warn/error;默认读取 LOG_LEVEL 或系统设置")
logFormat := flag.String("log-format", "", "日志格式:text/json;默认读取 LOG_FORMAT")
@@ -126,7 +125,8 @@ func main() {
logger.Warn("系统尚未初始化,请先运行本二进制的 -init-admin 初始化管理员")
}
// 2) 内置浏览器管理器(playwright-go,首运行自动下载 Chromium)。
// 2) Chromium 只负责读取本机浏览器指纹和处理 token 滑块。
// 扫码、人脸、续期、MTOP、Cookie 与 WebSocket 全部走 Go 协议实现。
var bm *browser.Manager
if !*noBrowser {
bm = browser.NewManager(logger)
@@ -134,7 +134,6 @@ func main() {
logger.Error("初始化 Playwright Chromium 指纹失败", "err", err)
os.Exit(1)
}
mtop.SetDefaultTokenRequestExecutor(bm)
}
var mgr *account.Manager
ap := adapter.New(store, bm, logger)
@@ -150,10 +149,10 @@ func main() {
logger.Error("启动账号引擎失败", "err", err)
}
go automation.NewScheduler(autoCenter).Run(ctx)
go renewal.NewScheduler(store, mgr, bm, ap, logger).Run(ctx)
go renewal.NewScheduler(store, mgr, ap, logger).Run(ctx)
// 3) HTTP 服务。
srv := server.New(store, mgr, bm, *secure, *webDir, *addr, logger, autoCenter, notifier)
srv := server.New(store, mgr, *secure, *webDir, *addr, logger, autoCenter, notifier)
go srv.RunPublishBatchRecovery(ctx)
if err := srv.Run(ctx); err != nil {
logger.Error("HTTP 服务退出", "err", err)
+21 -12
View File
@@ -1,12 +1,15 @@
x-app-env: &app-env
DATABASE_URL: postgres://${POSTGRES_USER:-xianyu}:${POSTGRES_PASSWORD:-xianyu_password}@postgres:5432/${POSTGRES_DB:-xianyu}?sslmode=disable
DATABASE_URL: ${DATABASE_URL:?请在 .env 中配置 DATABASE_URL}
XIANYU_DATA_KEY: ${XIANYU_DATA_KEY:?请在 .env 中配置 XIANYU_DATA_KEY}
XIANYU_UPLOAD_DIR: ${XIANYU_UPLOAD_DIR:-/app/data/uploads}
TZ: ${TZ:-Asia/Shanghai}
LOG_LEVEL: ${LOG_LEVEL:-info}
LOG_FORMAT: ${LOG_FORMAT:-json}
BROWSER_HEADLESS: ${BROWSER_HEADLESS:-true}
PLAYWRIGHT_DRIVER_PATH: ${PLAYWRIGHT_DRIVER_PATH:-/ms-playwright-go}
PLAYWRIGHT_NODEJS_PATH: ${PLAYWRIGHT_NODEJS_PATH:-/usr/bin/node}
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: ${PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD:-1}
PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH: ${PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH:-/usr/bin/chromium}
XIANYU_ADMIN_PASSWORD: ${XIANYU_ADMIN_PASSWORD:-}
x-app-volumes: &app-volumes
- app_data:/app/data
@@ -14,25 +17,28 @@ x-app-volumes: &app-volumes
services:
postgres:
image: postgres:17-trixie
platform: linux/amd64
image: ${POSTGRES_IMAGE:-postgres:17-trixie}
restart: unless-stopped
environment:
POSTGRES_DB: ${POSTGRES_DB:-xianyu}
POSTGRES_USER: ${POSTGRES_USER:-xianyu}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-xianyu_password}
POSTGRES_DB: ${POSTGRES_DB:?请在 .env 中配置 POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER:?请在 .env 中配置 POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?请在 .env 中配置 POSTGRES_PASSWORD}
TZ: ${TZ:-Asia/Shanghai}
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "${POSTGRES_PORT:-5432}:5432"
expose:
- "5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""]
interval: 10s
timeout: 5s
retries: 10
start_period: 10s
app:
image: ${XIANYU_IMAGE:-xianyu-go:debian13}
platform: linux/amd64
image: ${XIANYU_IMAGE:-xianyu-go:debian13-amd64}
build:
context: .
dockerfile: Dockerfile.debian13
@@ -43,7 +49,7 @@ services:
environment: *app-env
command: ["/app/xianyu-server", "-addr", ":8080"]
ports:
- "${XIANYU_HTTP_PORT:-8080}:8080"
- "${XIANYU_BIND_ADDRESS:-0.0.0.0}:${XIANYU_HTTP_PORT:-8080}:8080"
volumes: *app-volumes
healthcheck:
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null || exit 1"]
@@ -53,7 +59,8 @@ services:
start_period: 30s
init-admin:
image: ${XIANYU_IMAGE:-xianyu-go:debian13}
platform: linux/amd64
image: ${XIANYU_IMAGE:-xianyu-go:debian13-amd64}
build:
context: .
dockerfile: Dockerfile.debian13
@@ -62,7 +69,9 @@ services:
depends_on:
postgres:
condition: service_healthy
environment: *app-env
environment:
<<: *app-env
XIANYU_ADMIN_PASSWORD: ${XIANYU_ADMIN_PASSWORD:-}
command:
- /bin/sh
- -c
+5 -4
View File
@@ -8,6 +8,7 @@ import ItemList from './components/ItemList';
import Settings from './components/Settings';
import Rules from './components/Rules';
import Notifications from './components/Notifications';
import { YdisksBrandIcon } from './components/YdisksLogo';
import { login, logout, verifySession } from './services/api';
import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react';
@@ -157,8 +158,8 @@ const App: React.FC = () => {
<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">
<div className="text-center mb-8">
<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))' }}>
<img src="/static/ydisks-logo.svg" alt="Ydisks" className="w-full h-full" />
<div className="mx-auto mb-6 flex justify-center">
<YdisksBrandIcon sizeClass="w-24 h-24" />
</div>
<h2 className="text-3xl font-extrabold text-gray-900 mb-2 tracking-tight">系统尚未初始化</h2>
<p className="text-gray-600 font-medium">为避免默认口令风险,管理员必须通过服务器本机 CLI 初始化。</p>
@@ -202,8 +203,8 @@ const App: React.FC = () => {
{/* Header with Logo */}
<div className="text-center mb-10">
<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))' }}>
<img src="/static/ydisks-logo.svg" alt="Ydisks" className="w-full h-full group-hover:scale-110 transition-transform" />
<div className="group mx-auto mb-6 flex cursor-pointer justify-center">
<YdisksBrandIcon sizeClass="w-24 h-24" logoClassName="w-full h-full text-white group-hover:scale-110 transition-transform" />
</div>
<h2 className="text-3xl font-extrabold text-gray-900 mb-2 tracking-tight">欢迎回来</h2>
<p className="text-gray-500 font-medium">Ydisks闲鱼助手 · 自动发货与管家系统</p>
+41 -1
View File
@@ -20,6 +20,8 @@ import {
getAccountAISettings,
getNotificationChannels,
getAccountBindings,
getLongLoginSettings,
setLongLoginSettings,
} from '../services/api';
import { shouldUpdateAccountPause } from './accountPause';
import {
@@ -49,6 +51,7 @@ const AccountList: React.FC = () => {
const [qrReauthTarget, setQrReauthTarget] = useState<AccountDetail | null>(null);
const [activeModal, setActiveModal] = useState<ModalType>(null);
const [editingAccount, setEditingAccount] = useState<AccountDetail | null>(null);
const [longLogin, setLongLogin] = useState({ loading: false, saving: false, canOpen: false, enabled: false, error: '' });
// 通知渠道绑定(编辑弹窗用)
const [notifChannels, setNotifChannels] = useState<NotificationChannel[]>([]);
@@ -328,7 +331,28 @@ const AccountList: React.FC = () => {
clear_password: false,
});
setActiveModal('edit');
await loadNotificationBindings(account.id);
setLongLogin({ loading: true, saving: false, canOpen: false, enabled: false, error: '' });
const [, longLoginResult] = await Promise.allSettled([
loadNotificationBindings(account.id),
getLongLoginSettings(account.id),
]);
if (longLoginResult.status === 'fulfilled') {
setLongLogin({ loading: false, saving: false, canOpen: longLoginResult.value.can_open_long_login, enabled: longLoginResult.value.enabled, error: '' });
} else {
setLongLogin({ loading: false, saving: false, canOpen: false, enabled: false, error: '无法读取闲鱼保存登录信息状态' });
}
};
const handleLongLoginToggle = async () => {
if (!editingAccount || longLogin.loading || longLogin.saving || !longLogin.canOpen) return;
const enabled = !longLogin.enabled;
setLongLogin(current => ({ ...current, saving: true, error: '' }));
try {
const result = await setLongLoginSettings(editingAccount.id, enabled);
setLongLogin({ loading: false, saving: false, canOpen: result.can_open_long_login, enabled: result.enabled, error: '' });
} catch (error) {
setLongLogin(current => ({ ...current, saving: false, error: error instanceof Error ? error.message : '保存登录信息设置失败' }));
}
};
const openAIModal = async (account: AccountDetail) => {
@@ -966,6 +990,22 @@ const AccountList: React.FC = () => {
登录信息
</h3>
<div className="space-y-4">
<div className="flex items-center justify-between gap-4 rounded-xl bg-blue-50 p-4">
<div>
<div className="font-bold text-gray-900">保存登录信息</div>
<div className="mt-1 text-xs text-gray-500">状态直接读取并修改闲鱼官方长登录设置</div>
{longLogin.error && <div className="mt-1 text-xs text-red-600">{longLogin.error}</div>}
</div>
<button
type="button"
aria-label="保存登录信息"
disabled={longLogin.loading || longLogin.saving || !longLogin.canOpen}
onClick={() => void handleLongLoginToggle()}
className={`relative h-8 w-14 flex-shrink-0 rounded-full transition-colors ${longLogin.enabled ? 'bg-[#0094f7]' : 'bg-gray-300'} disabled:cursor-not-allowed disabled:opacity-50`}
>
<span className={`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-md transition-transform ${longLogin.enabled ? 'translate-x-6' : 'translate-x-0'}`} />
</button>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-2">用户名</label>
<input
+74 -34
View File
@@ -1,8 +1,9 @@
import React, { useEffect, useState } from 'react';
import React, { useEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { Card } from '../types';
import { getCards, createCard, updateCard, deleteCard, batchCreateCards, appendCardData } from '../services/api';
import { Plus, CreditCard, Clock, FileText, Image as ImageIcon, Code, Edit, Trash2, Save, X, Eye, EyeOff, Package, Copy, Upload, Loader2, FileDown, ListPlus } from 'lucide-react';
import { Plus, CreditCard, Clock, FileText, Image as ImageIcon, Code, Edit, Trash2, Save, X, Eye, EyeOff, Package, Copy, Upload, Loader2, FileDown, ListPlus, Search, SlidersHorizontal } from 'lucide-react';
import { filterCards } from './cardListState';
type AddCardForm = {
name: string;
@@ -55,6 +56,8 @@ const CardList: React.FC = () => {
const [appendTargetId, setAppendTargetId] = useState<string>('');
const [appendContent, setAppendContent] = useState('');
const [appendResult, setAppendResult] = useState<{ added: number } | null>(null);
const [typeFilter, setTypeFilter] = useState<Card['type'] | ''>('');
const [nameSearch, setNameSearch] = useState('');
useEffect(() => {
getCards().then(setCards);
@@ -213,6 +216,10 @@ const CardList: React.FC = () => {
};
const dataCards = cards.filter(c => c.type === 'data');
const filteredCards = useMemo(
() => filterCards(cards, typeFilter, nameSearch),
[cards, nameSearch, typeFilter],
);
const downloadCardTemplate = () => {
const headers = ['名称', '类型', '内容', '描述', '启用', '延迟秒', '多规格', '规格名', '规格值'];
@@ -306,28 +313,61 @@ const CardList: React.FC = () => {
</div>
<div className="ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white">
<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">
<div className="flex flex-1 flex-col gap-3 sm:flex-row">
<div className="relative sm:w-48">
<SlidersHorizontal className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
<select
aria-label="按卡密类型筛选"
value={typeFilter}
onChange={event => setTypeFilter(event.target.value as Card['type'] | '')}
className="ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm"
>
<option value="">全部类型</option>
<option value="data">批量卡密</option>
<option value="text">文本</option>
<option value="api">API</option>
<option value="image">图片</option>
</select>
</div>
<div className="relative w-full sm:max-w-sm">
<Search className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
<input
type="search"
aria-label="按卡密名称搜索"
placeholder="搜索卡密名称..."
value={nameSearch}
onChange={event => setNameSearch(event.target.value)}
className="ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"
/>
</div>
</div>
<div className="whitespace-nowrap px-1 text-xs font-bold text-gray-400">
显示 {filteredCards.length} / {cards.length} 组
</div>
</div>
<div className="overflow-x-auto">
<table className="w-full text-left border-collapse">
<table className="w-full table-fixed text-left border-collapse">
<thead>
<tr className="bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50">
<th className="px-8 py-5 w-[18%]">卡密名称</th>
<th className="px-6 py-5 w-[12%]">卡密组ID</th>
<th className="px-6 py-5 w-[10%]">类型</th>
<th className="px-6 py-5 w-[22%]">内容/库存</th>
<th className="px-6 py-5 w-[18%]">描述</th>
<th className="px-6 py-5 w-[10%]">状态</th>
<th className="px-6 py-5 w-[10%] text-right">操作</th>
<th className="w-[23%] px-5 py-5">卡密名称</th>
<th className="w-[8%] px-3 py-5">卡密组ID</th>
<th className="w-[7%] px-2 py-5">类型</th>
<th className="w-[27%] px-5 py-5">内容/库存</th>
<th className="w-[19%] px-5 py-5">描述</th>
<th className="w-[7%] px-2 py-5">状态</th>
<th className="w-[9%] px-3 py-5 text-right">操作</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-50">
{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 (
<tr key={card.id} className="hover:bg-[#FFFDE7]/50 transition-colors group">
<td className="px-8 py-5">
<div className="flex items-center gap-3">
<div className="p-2 bg-gray-50 rounded-xl group-hover:bg-white transition-colors">
<td className="px-5 py-5 align-middle">
<div className="flex items-center gap-2.5">
<div className="shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white">
<CardIcon type={card.type} />
</div>
<span className="font-bold text-gray-900">{card.name}</span>
<span className="line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900" title={card.name}>{card.name}</span>
</div>
</td>
<td className="px-6 py-5">
<td className="px-3 py-5">
<button
onClick={() => copyCardID(card.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"
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,用于批量铺货表格"
>
{card.id}
<Copy className="w-3.5 h-3.5" />
<span className="truncate">{card.id}</span>
<Copy className="h-3 w-3 shrink-0" />
</button>
</td>
<td className="px-6 py-5">
<span className={`px-3 py-1.5 rounded-lg text-xs font-bold ${
<td className="px-2 py-5">
<span className={`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${
card.type === 'text' ? 'bg-blue-50 text-blue-600' :
card.type === 'data' ? 'bg-purple-50 text-purple-600' :
card.type === 'api' ? 'bg-blue-50 text-blue-600' :
@@ -366,20 +406,20 @@ const CardList: React.FC = () => {
card.type === 'api' ? 'API' : '图片'}
</span>
</td>
<td className="px-6 py-5">
<span className="text-sm text-gray-600 font-mono block truncate" title={stockInfo}>
<td className="px-5 py-5">
<span className="line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600" title={stockInfo}>
{stockInfo}
</span>
</td>
<td className="px-6 py-5">
<td className="px-5 py-5">
<span
className="text-sm text-gray-500 block max-w-[200px] truncate"
className="block truncate text-sm text-gray-500"
title={card.description || '-'}
>
{card.description || '-'}
</span>
</td>
<td className="px-6 py-5">
<td className="px-2 py-5">
<button
onClick={() => toggleCardStatus(card)}
className={`w-12 h-8 rounded-full relative transition-colors ${
@@ -391,20 +431,20 @@ const CardList: React.FC = () => {
}`}></div>
</button>
</td>
<td className="px-6 py-5">
<div className="flex items-center justify-end gap-2">
<td className="px-3 py-5">
<div className="flex items-center justify-end gap-0.5">
<button
onClick={() => handleEdit(card)}
className="p-2 text-gray-400 hover:text-black hover:bg-gray-100 rounded-xl transition-colors"
className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black"
title="编辑"
>
<Edit className="w-4 h-4" />
</button>
<button
onClick={() => handleDelete(card.id)}
className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors"
className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500"
>
<Trash2 className="w-5 h-5" />
<Trash2 className="h-4 w-4" />
</button>
</div>
</td>
@@ -415,10 +455,10 @@ const CardList: React.FC = () => {
</table>
</div>
{cards.length === 0 && (
{filteredCards.length === 0 && (
<div className="py-20 text-center text-gray-400">
<Package className="w-12 h-12 mx-auto mb-4 opacity-30" />
<p>暂无卡密配置,请点击右上角添加。</p>
<p>{cards.length === 0 ? '暂无卡密配置,请点击右上角添加。' : '没有符合当前筛选条件的卡密组。'}</p>
</div>
)}
</div>
+2 -1
View File
@@ -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 = () => {
<td className="px-6 py-4">
<div className="text-sm font-bold text-gray-800">{order.buyer_id}</div>
{order.created_at && (
<div className="text-xs text-gray-400 mt-1">{order.created_at}</div>
<div className="text-xs text-gray-400 mt-1">{formatLocalDateTime(order.created_at)}</div>
)}
</td>
<td className="px-6 py-4 text-base font-extrabold text-gray-900 font-feature-settings-tnum">
+74 -21
View File
@@ -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<ItemListProps> = ({ onConfigureDelivery }) => {
const [shippingRules, setShippingRules] = useState<ShippingRule[]>([]);
const [accounts, setAccounts] = useState<AccountDetail[]>([]);
const [selectedAccount, setSelectedAccount] = useState<string>('');
const [accountFilter, setAccountFilter] = useState<string>('');
const [loading, setLoading] = useState(false);
const [publishing, setPublishing] = useState(false);
const [batchLoading, setBatchLoading] = useState(false);
@@ -510,24 +511,72 @@ const ItemList: React.FC<ItemListProps> = ({ 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 (
<div className="space-y-6 animate-fade-in">
<div className="flex justify-between items-center">
<div className="flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4">
<div>
<h2 className="text-3xl font-bold text-gray-900">商品管理</h2>
<p className="text-gray-500 mt-2 text-sm">监控并管理所有账号下的闲鱼商品。</p>
</div>
<div className="flex gap-3">
<select
className="ios-input px-4 py-3 rounded-xl text-sm"
value={selectedAccount}
onChange={e => setSelectedAccount(e.target.value)}
>
<option value="">选择账号以同步</option>
{accounts.map(acc => (
<option key={acc.id} value={acc.id}>{acc.nickname}</option>
))}
</select>
<div className="flex flex-wrap items-end gap-3">
<div className="flex min-w-[200px] flex-col gap-1.5">
<label htmlFor="item-account-filter" className="px-1 text-[11px] font-extrabold tracking-wide text-gray-500">
商品列表筛选
</label>
<div className="relative">
<Filter className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
<select
id="item-account-filter"
aria-label="按账号筛选商品列表"
className="ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm"
value={accountFilter}
onChange={event => setAccountFilter(event.target.value)}
>
<option value="">全部账号</option>
{accounts.map(account => (
<option key={account.id} value={account.id}>{accountName(account.id)}</option>
))}
</select>
</div>
</div>
<div className="flex min-w-[200px] flex-col gap-1.5">
<label htmlFor="item-sync-account" className="px-1 text-[11px] font-extrabold tracking-wide text-gray-500">
同步商品账号
</label>
<div className="relative">
<User className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
<select
id="item-sync-account"
aria-label="选择要同步商品的账号"
className="ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm"
value={selectedAccount}
onChange={e => setSelectedAccount(e.target.value)}
>
<option value="">请选择账号</option>
{accounts.map(acc => (
<option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>
))}
</select>
</div>
</div>
<button
onClick={handleSync}
disabled={loading || !selectedAccount}
@@ -569,7 +618,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
</div>
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
{items.map(item => {
{visibleItems.map(item => {
const linkedRules = rulesForItem(item);
const hasRule = linkedRules.length > 0;
return (
@@ -603,6 +652,10 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
</div>
</div>
<h3 className="font-bold text-gray-900 line-clamp-2 text-xs mb-1.5 h-8 leading-4">{item.item_title}</h3>
<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={accountNickname(item.cookie_id)}>
<User className="h-3 w-3 shrink-0" />
<span className="min-w-0 truncate whitespace-nowrap">{accountNickname(item.cookie_id)}</span>
</div>
<div className="flex justify-between items-center text-[10px] text-gray-500 mb-2">
<span className="bg-gray-100 px-1.5 py-0.5 rounded truncate max-w-[80px]">ID: {item.item_id}</span>
<span className={`inline-flex items-center gap-1 font-bold ${hasRule ? 'text-emerald-600' : 'text-amber-600'}`}>
@@ -622,10 +675,10 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
</div>
);
})}
{items.length === 0 && (
{visibleItems.length === 0 && (
<div className="col-span-full py-20 text-center text-gray-400">
<ShoppingBag className="w-12 h-12 mx-auto mb-4 opacity-30" />
暂无商品数据,请选择账号进行同步
{accountFilter ? '该账号暂无商品数据' : '暂无商品数据,请选择账号进行同步'}
</div>
)}
</div>
@@ -675,7 +728,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
<label className="block text-sm font-bold text-gray-700">所属账号</label>
<select className="w-full ios-input px-4 py-3 rounded-xl" value={addForm.cookie_id} onChange={e => setAddForm({...addForm, cookie_id: e.target.value})}>
<option value="">选择账号</option>
{accounts.map(acc => <option key={acc.id} value={acc.id}>{acc.nickname || acc.remark || acc.id}</option>)}
{accounts.map(acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
</select>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
@@ -727,7 +780,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
<label className="block text-sm font-bold text-gray-700">发布账号</label>
<select className="w-full ios-input px-4 py-3 rounded-xl" value={publishForm.cookie_id} onChange={e => setPublishForm({...publishForm, cookie_id: e.target.value})}>
<option value="">选择账号</option>
{accounts.map(acc => <option key={acc.id} value={acc.id}>{acc.nickname || acc.remark || acc.id}</option>)}
{accounts.map(acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
</select>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
@@ -857,7 +910,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
onChange={e => setSelectedAccount(e.target.value)}
>
<option value="">选择账号</option>
{accounts.map(acc => <option key={acc.id} value={acc.id}>{acc.nickname || acc.remark || acc.id}</option>)}
{accounts.map(acc => <option key={acc.id} value={acc.id}>{accountName(acc.id)}</option>)}
</select>
<p className="text-xs text-gray-500">表格中“账号ID”为空时,会使用这里选择的账号。</p>
</div>
@@ -924,7 +977,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
</thead>
<tbody className="divide-y divide-gray-50 text-gray-700">
{[
['账号ID', '没有在上方选择默认账号时填写', '填写账号 ID;已经选择默认账号时可以留空'],
['账号ID', '需要覆盖默认账号时填写', '上方默认发布账号为必选;本列留空时使用默认账号,填写后仅覆盖当前行'],
['标题', '每个商品都要填', '填写买家能看到的商品标题'],
['描述', '可以留空', '留空时会使用商品标题作为描述'],
['价格', '每个商品都要填', '只填数字,例如 19.90'],
+167 -10
View File
@@ -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<NotificationChannelType, ChannelTypeMeta> = {
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<NotificationsProps> = ({ isAdmin = false }) => {
const [smtp, setSmtp] = useState<SystemSettings>({});
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<NotificationsProps> = ({ 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<NotificationsProps> = ({ 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<NotificationsProps> = ({ isAdmin = false }) => {
))}
</div>
{form.type === 'email' && (
<div className="overflow-hidden rounded-2xl border border-blue-100 bg-blue-50/40">
<div className="flex items-center justify-between gap-4 p-4">
<div>
<div className="text-sm font-extrabold text-gray-900">SMTP 来源</div>
<p className="mt-1 text-xs leading-5 text-gray-500">
{form.config.use_custom_smtp === true
? '当前渠道使用一套完整、独立的发件配置。'
: '当前渠道完整继承系统 SMTP,只单独设置收件邮箱。'}
</p>
</div>
<button
type="button"
onClick={() => {
const useCustom = form.config.use_custom_smtp === true;
setForm({
...form,
config: useCustom
? { ...form.config, use_custom_smtp: false }
: enableCustomSMTP(form.config, smtp),
});
}}
className={`relative h-7 w-12 shrink-0 rounded-full transition-colors ${form.config.use_custom_smtp === true ? 'bg-[#0094f7]' : 'bg-gray-300'}`}
aria-label="使用独立 SMTP"
>
<span className={`absolute left-1 top-1 h-5 w-5 rounded-full bg-white shadow-sm transition-transform ${form.config.use_custom_smtp === true ? 'translate-x-5' : ''}`} />
</button>
</div>
{form.config.use_custom_smtp === true && (
<div className="space-y-4 border-t border-blue-100 bg-white/80 p-4">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">SMTP 服务器 <span className="text-red-500">*</span></label>
<input
type="text"
value={String(form.config.smtp_server || '')}
onChange={e => setForm({ ...form, config: { ...form.config, smtp_server: e.target.value } })}
placeholder="smtp.qq.com"
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">SMTP 端口 <span className="text-red-500">*</span></label>
<input
type="number"
value={String(form.config.smtp_port || 587)}
onChange={e => setForm({ ...form, config: { ...form.config, smtp_port: e.target.value } })}
placeholder="587"
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
</div>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">登录邮箱 <span className="text-red-500">*</span></label>
<input
type="email"
value={String(form.config.smtp_user || '')}
onChange={e => 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"
/>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">密码 / 授权码 <span className="text-red-500">*</span></label>
<div className="relative">
<input
type={showChannelSmtpPassword ? 'text' : 'password'}
value={String(form.config.smtp_password || '')}
onChange={e => 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"
/>
<button
type="button"
onClick={() => setShowChannelSmtpPassword(value => !value)}
className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600"
>
{showChannelSmtpPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">发件人显示名(可选)</label>
<input
type="text"
value={String(form.config.smtp_from_name || '')}
onChange={e => setForm({ ...form, config: { ...form.config, smtp_from_name: e.target.value } })}
placeholder="闲鱼自动回复系统"
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
</div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">发件邮箱地址 <span className="text-red-500">*</span></label>
<input
type="email"
value={String(form.config.smtp_from_address || '')}
onChange={e => setForm({ ...form, config: { ...form.config, smtp_from_address: e.target.value } })}
placeholder="your-email@qq.com"
className="w-full ios-input px-4 py-3 rounded-xl text-sm"
/>
</div>
</div>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<label className="flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700">
<input
type="checkbox"
checked={form.config.smtp_use_tls !== false}
onChange={e => setForm({ ...form, config: { ...form.config, smtp_use_tls: e.target.checked, smtp_use_ssl: e.target.checked ? false : form.config.smtp_use_ssl } })}
/>
STARTTLS(常用于 587)
</label>
<label className="flex items-center gap-3 rounded-xl border border-gray-200 p-3 text-xs font-bold text-gray-700">
<input
type="checkbox"
checked={form.config.smtp_use_ssl === true}
onChange={e => setForm({ ...form, config: { ...form.config, smtp_use_ssl: e.target.checked, smtp_use_tls: e.target.checked ? false : form.config.smtp_use_tls } })}
/>
SSL/TLS 直连(常用于 465)
</label>
</div>
</div>
)}
</div>
)}
<div className="space-y-3">
<div>
<label className="block text-sm font-bold text-gray-800">通知内容</label>
+60 -17
View File
@@ -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<Order[]>([]);
const [items, setItems] = useState<Item[]>([]);
const [accounts, setAccounts] = useState<AccountDetail[]>([]);
const [itemNames, setItemNames] = useState<Record<string, string>>({});
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<string, string> = {};
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 = () => {
</button>
))}
</div>
<div className="relative w-full md:w-auto group">
<div className="flex w-full md:w-auto flex-col sm:flex-row gap-3">
<div className="relative">
<UserIcon className="w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
<select
aria-label="按账号筛选订单"
value={accountFilter}
onChange={(event) => { setAccountFilter(event.target.value); setPage(1); }}
className="ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm"
>
<option value="">全部账号</option>
{accounts.map(account => (
<option key={account.id} value={account.id}>{accountName(account.id)}</option>
))}
</select>
</div>
<div className="relative group">
<Search 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" />
<input
type="text"
@@ -366,6 +400,7 @@ 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"
/>
</div>
</div>
</div>
@@ -395,10 +430,14 @@ const OrderList: React.FC = () => {
</div>
<div className="min-w-0">
<div className="font-bold text-gray-900 line-clamp-1 text-sm">
{getItemNameById(order.item_id, order.item_title)}
{getItemNameById(order.cookie_id, order.item_id, order.item_title)}
</div>
<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={accountNickname(order.cookie_id)}>
<UserIcon className="h-3 w-3 shrink-0" />
<span className="min-w-0 truncate whitespace-nowrap">{accountNickname(order.cookie_id)}</span>
</div>
<div className="text-xs text-gray-500 mt-1 font-medium">订单ID: {order.order_id}</div>
<div className="text-xs text-gray-400 mt-0.5">数量: {order.quantity} • {order.created_at}</div>
<div className="text-xs text-gray-400 mt-0.5">数量: {order.quantity} • {formatLocalDateTime(order.created_at)}</div>
</div>
</div>
</td>
@@ -536,6 +575,10 @@ const OrderList: React.FC = () => {
<div className="text-xs text-gray-500 mb-1">订单号</div>
<div className="font-mono text-sm font-bold text-gray-900">{selectedOrder.order_id}</div>
</div>
<div>
<div className="text-xs text-gray-500 mb-1">所属账号</div>
<div className="truncate whitespace-nowrap text-sm font-bold text-blue-700" title={accountNickname(selectedOrder.cookie_id)}>{accountNickname(selectedOrder.cookie_id)}</div>
</div>
<div>
<div className="text-xs text-gray-500 mb-1">状态</div>
<StatusBadge status={selectedOrder.status} />
@@ -550,7 +593,7 @@ const OrderList: React.FC = () => {
</div>
<div className="col-span-2">
<div className="text-xs text-gray-500 mb-1">创建时间</div>
<div className="text-sm font-medium text-gray-700">{selectedOrder.created_at}</div>
<div className="text-sm font-medium text-gray-700">{formatLocalDateTime(selectedOrder.created_at)}</div>
</div>
</div>
</div>
@@ -564,7 +607,7 @@ const OrderList: React.FC = () => {
)}
<div className="flex-1">
<div className="font-bold text-gray-900 mb-1">
{getItemNameById(selectedOrder.item_id, selectedOrder.item_title)}
{getItemNameById(selectedOrder.cookie_id, selectedOrder.item_id, selectedOrder.item_title)}
</div>
<div className="text-sm text-gray-500">商品ID: {selectedOrder.item_id}</div>
{selectedOrder.item_price && (
+1 -1
View File
@@ -1280,7 +1280,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
<input
type="number"
min="0"
max="86400"
max="3600"
value={variant.delay_seconds || 0}
onChange={event => 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"
+3 -2
View File
@@ -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<SidebarProps> = ({ activeTab, isAdmin = false, onNavigat
<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)]">
<div className="p-6">
<div className="flex items-center gap-3 mb-12 px-2">
<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))' }}>
<img src="/static/ydisks-logo.svg" alt="Ydisks" className="w-full h-full" />
<div className="shrink-0">
<YdisksBrandIcon sizeClass="w-10 h-10" />
</div>
<h1 className="text-xl font-extrabold tracking-tight text-gray-900">Ydisks闲鱼助手 <span className="text-xs bg-[#0094f7] text-white px-1.5 py-0.5 rounded ml-1">PRO</span></h1>
</div>
+21
View File
@@ -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(<YdisksLogo />);
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(<YdisksBrandIcon />);
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');
});
});
+43
View File
@@ -0,0 +1,43 @@
import React from 'react';
interface YdisksLogoProps {
className?: string;
}
interface YdisksBrandIconProps {
sizeClass?: string;
logoClassName?: string;
}
const YdisksLogo: React.FC<YdisksLogoProps> = ({ className = 'w-full h-full text-white' }) => (
<svg className={className} viewBox="0 0 256 256" aria-hidden="true">
<g stroke="none" fill="none" fillRule="evenodd">
<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" />
</g>
</svg>
);
export const YdisksBrandIcon: React.FC<YdisksBrandIconProps> = ({
sizeClass = 'w-12 h-12',
logoClassName = 'w-full h-full text-white',
}) => (
<div className="relative z-10 flex items-center justify-center">
<div className="absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25" />
<div className={`relative ${sizeClass} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`}>
<svg className="absolute inset-0 w-full h-full" viewBox="0 0 120 120" aria-hidden="true">
<defs>
<linearGradient id="login-squircle-gradient" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stopColor="#0094f7" />
<stop offset="100%" stopColor="#287efe" />
</linearGradient>
</defs>
<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)" />
</svg>
<div className="relative z-10 flex items-center justify-center w-full h-full">
<YdisksLogo className={logoClassName} />
</div>
</div>
</div>
);
export default YdisksLogo;
+19
View File
@@ -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]]);
});
});
+13
View File
@@ -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))
));
};
+13
View File
@@ -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('-');
});
});
+19
View File
@@ -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(':');
};
+36
View File
@@ -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,
});
});
});
+59
View File
@@ -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<string, unknown>): Record<string, unknown> => {
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<string, unknown>,
systemSettings: Record<string, unknown>,
): Record<string, unknown> => {
const next: Record<string, unknown> = { ...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<string, unknown>): Record<string, unknown> => {
const normalized = normalizeEmailChannelConfig(config);
const result: Record<string, unknown> = {
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;
};
+3 -2
View File
@@ -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('注册验证码');
});
+12
View File
@@ -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',
+15 -2
View File
@@ -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<LongLoginSettings> => {
return get(`/cookies/${id}/long-login`);
};
export const setLongLoginSettings = async (id: string, enabled: boolean): Promise<LongLoginSettings> => {
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<Item[]> => {
const res = await get<any>('/items');
export const getItems = async (cookieId?: string): Promise<Item[]> => {
const res = await get<any>('/items', cookieId ? { cookie_id: cookieId } : undefined);
const items = Array.isArray(res) ? res : (res.items || []);
return items.map((item: any) => ({
...item,
+28
View File
@@ -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{
+202 -233
View File
@@ -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。
+138 -56
View File
@@ -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)
}
}
+64 -14
View File
@@ -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 {
@@ -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)
}
}
+163 -5
View File
@@ -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()
+210 -75
View File
@@ -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()
+89
View File
@@ -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")
}
}
+6
View File
@@ -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)
+104
View File
@@ -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
}
+57 -13
View File
@@ -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)
}
+38
View File
@@ -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"})
+34 -7
View File
@@ -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)
-78
View File
@@ -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
}
+32
View File
@@ -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")
}
}
+25 -26
View File
@@ -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
}
+11 -11
View File
@@ -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)
}
}
+106 -23
View File
@@ -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
}
+6 -2
View File
@@ -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)
@@ -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;
@@ -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;
@@ -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;
+5 -1
View File
@@ -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)
+4
View File
@@ -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
}
+48 -5
View File
@@ -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
}
+125
View File
@@ -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)
}
}
+13 -6
View File
@@ -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
}
}
+50 -22
View File
@@ -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
}
+671 -445
View File
File diff suppressed because it is too large. Load diff
+298 -14
View File
@@ -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)
}
}
+5
View File
@@ -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)
+19 -5
View File
@@ -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)
+53 -207
View File
@@ -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)
}
}
+300 -62
View File
@@ -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)
}
}
+48 -30
View File
@@ -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[:])
}
+44 -23
View File
@@ -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 必须与没有快照的历史状态区分")
}
}
+30 -9
View File
@@ -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)
+27
View File
@@ -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)
+189 -204
View File
@@ -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
+114 -242
View File
@@ -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)
}
}
+2 -2
View File
@@ -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 = "{}"
+2 -2
View File
@@ -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
}
+2 -2
View File
@@ -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":
+288 -26
View File
@@ -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)
+273
View File
@@ -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)
+1 -1
View File
@@ -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}`,
+198 -24
View File
@@ -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 {
+60
View File
@@ -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)
+73 -20
View File
@@ -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 之间")
}
}
}
+65
View File
@@ -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
}
+137
View File
@@ -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)
}
}
+309 -85
View File
@@ -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 {
+46 -7
View File
@@ -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())
}
}
+9 -432
View File
@@ -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"
}
+21 -446
View File
@@ -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)
}
}
}
+21
View File
@@ -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)
+76 -28
View File
@@ -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
}
+17
View File
@@ -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)
}
+30 -50
View File
@@ -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 {
+1 -1
View File
@@ -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{
@@ -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};
@@ -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,lLine truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,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", Line truncated
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_mLine truncated
卡号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-Line truncated
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 Line truncated
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:"" Line truncated
`),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-emerLine truncated
@@ -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{Line truncated
@@ -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 88Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,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 Line truncated
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("Line truncated
卡号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-Line truncated
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- Line truncated
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:" Line truncated
`),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- Line truncated
@@ -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:-.25remLine truncated
+3 -3
View File
@@ -6,12 +6,12 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
<script type="module" crossorigin src="/static/assets/index-2Xnmtmdh.js"></script>
<script type="module" crossorigin src="/static/assets/index-DWScSBc3.js"></script>
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-DZnRGM0-.js">
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-BhUPp6x7.js">
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-RenKjhri.js">
<link rel="modulepreload" crossorigin href="/static/assets/vendor-w5t2K9ux.js">
<link rel="modulepreload" crossorigin href="/static/assets/charts-vendor-B_BfwiL0.js">
<link rel="stylesheet" crossorigin href="/static/assets/index-D0gOrWMZ.css">
<link rel="stylesheet" crossorigin href="/static/assets/index-hVsGsb1z.css">
</head>
<body>
<div id="root"></div>
+331 -28
View File
@@ -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 中的其他键。
+241 -1
View File
@@ -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: "/"}}
+33 -52
View File
@@ -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
+20 -3
View File
@@ -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 {
+12 -9
View File
@@ -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"`
}
+240
View File
@@ -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)
}
+312
View File
@@ -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)
}
}
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more