修复登录续期与数据库验证回归
- 修复密码登录、续期和账号编辑链路的边界问题 - 补齐 dbverify、后端与前端单测 - 同步 Docker 与前端构建产物
This commit is contained in:
1 parent
3436acecdc
commit
25419c027f
87 files changed
+7485
-900
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { AccountDetail, AIReplySettings, NotificationChannel } from '../types';
|
||||
import {
|
||||
@@ -28,6 +28,8 @@ import {
|
||||
RefreshCw, Save, User, Clock, MessageCircle,
|
||||
Upload, Key, Eye, EyeOff, Bot, Settings, AlertCircle, ExternalLink, Bell
|
||||
} from 'lucide-react';
|
||||
import { buildAccountLoginInfoUpdate } from './accountEdit';
|
||||
import { createQRLoginPoller } from './qrPolling';
|
||||
|
||||
type ModalType = 'edit' | 'ai-settings' | null;
|
||||
|
||||
@@ -72,6 +74,37 @@ const AccountList: React.FC = () => {
|
||||
custom_prompts: '',
|
||||
});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const qrPollerRef = useRef<ReturnType<typeof createQRLoginPoller> | null>(null);
|
||||
const qrCloseTimerRef = useRef<ReturnType<typeof window.setTimeout> | null>(null);
|
||||
if (qrPollerRef.current === null) {
|
||||
qrPollerRef.current = createQRLoginPoller();
|
||||
}
|
||||
|
||||
const clearQRCloseTimer = () => {
|
||||
if (qrCloseTimerRef.current !== null) {
|
||||
window.clearTimeout(qrCloseTimerRef.current);
|
||||
qrCloseTimerRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
const stopQRPolling = () => {
|
||||
qrPollerRef.current?.stop();
|
||||
};
|
||||
|
||||
const closeQRModal = () => {
|
||||
stopQRPolling();
|
||||
clearQRCloseTimer();
|
||||
setShowQRModal(false);
|
||||
};
|
||||
|
||||
const scheduleQRModalClose = () => {
|
||||
clearQRCloseTimer();
|
||||
qrCloseTimerRef.current = window.setTimeout(() => {
|
||||
qrCloseTimerRef.current = null;
|
||||
setShowQRModal(false);
|
||||
loadAccounts();
|
||||
}, 1000);
|
||||
};
|
||||
|
||||
const refreshRuntimeStatuses = async () => {
|
||||
try {
|
||||
@@ -130,6 +163,13 @@ const AccountList: React.FC = () => {
|
||||
return () => window.clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
stopQRPolling();
|
||||
clearQRCloseTimer();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const runtimePresentation = (account: AccountDetail) => {
|
||||
if (!account.enabled || account.runtime_state === 'disabled') {
|
||||
return { label: '已停用', badge: 'bg-gray-100 text-gray-500', dot: 'bg-gray-300' };
|
||||
@@ -258,16 +298,9 @@ const AccountList: React.FC = () => {
|
||||
}
|
||||
|
||||
// 更新登录信息
|
||||
if (
|
||||
editForm.username !== (editingAccount.username || '') ||
|
||||
editForm.login_password !== (editingAccount.login_password || '') ||
|
||||
editForm.show_browser !== (editingAccount.show_browser || false)
|
||||
) {
|
||||
promises.push(updateAccountLoginInfo(editingAccount.id, {
|
||||
username: editForm.username,
|
||||
login_password: editForm.login_password,
|
||||
show_browser: editForm.show_browser,
|
||||
}));
|
||||
const loginInfo = buildAccountLoginInfoUpdate(editingAccount, editForm);
|
||||
if (loginInfo) {
|
||||
promises.push(updateAccountLoginInfo(editingAccount.id, loginInfo));
|
||||
}
|
||||
|
||||
// 更新通知渠道绑定(覆盖式,总是提交以支持解绑)
|
||||
@@ -308,17 +341,19 @@ const AccountList: React.FC = () => {
|
||||
throw new Error('已取消覆盖当前账号授权');
|
||||
}
|
||||
}
|
||||
await updateAccountCookie(target.id, cookies);
|
||||
await updateAccountCookie(target.id, cookies, 'qr_scan');
|
||||
return target.id;
|
||||
}
|
||||
if (!unb) {
|
||||
throw new Error('扫码结果缺少账号ID,无法添加账号');
|
||||
}
|
||||
await addAccount(unb, cookies);
|
||||
await addAccount(unb, cookies, 'qr_scan');
|
||||
return unb;
|
||||
};
|
||||
|
||||
const startQRLogin = async (target?: AccountDetail) => {
|
||||
stopQRPolling();
|
||||
clearQRCloseTimer();
|
||||
const targetAccount = target || null;
|
||||
setQrReauthTarget(targetAccount);
|
||||
setShowQRModal(true);
|
||||
@@ -335,10 +370,8 @@ const AccountList: React.FC = () => {
|
||||
setQrSessionId(res.session_id);
|
||||
setQrStatus('waiting');
|
||||
|
||||
const interval = setInterval(async () => {
|
||||
const statusRes = await checkQRLoginStatus(res.session_id!);
|
||||
if (statusRes.status === 'success') {
|
||||
clearInterval(interval);
|
||||
qrPollerRef.current?.start(res.session_id, checkQRLoginStatus, {
|
||||
onSuccess: async (statusRes) => {
|
||||
setQrStatus('success');
|
||||
if (statusRes.cookies && statusRes.unb) {
|
||||
try {
|
||||
@@ -346,18 +379,22 @@ const AccountList: React.FC = () => {
|
||||
} catch (e) {
|
||||
console.error('保存扫码授权失败', e);
|
||||
setQrStatus('error');
|
||||
return;
|
||||
}
|
||||
}
|
||||
setTimeout(() => {
|
||||
setShowQRModal(false);
|
||||
loadAccounts();
|
||||
}, 1000);
|
||||
} else if (statusRes.status === 'scanned') {
|
||||
scheduleQRModalClose();
|
||||
},
|
||||
onScanned: () => {
|
||||
setQrStatus('waiting'); // 已扫描,继续等待确认
|
||||
} else if (statusRes.status === 'expired' || statusRes.status === 'cancelled' || statusRes.status === 'error' || statusRes.status === 'not_found') {
|
||||
clearInterval(interval);
|
||||
},
|
||||
onTerminalError: () => {
|
||||
setQrStatus('error');
|
||||
} else if (statusRes.status === 'verification_required') {
|
||||
},
|
||||
onPollError: (error) => {
|
||||
console.error('轮询扫码状态失败', error);
|
||||
setQrStatus('error');
|
||||
},
|
||||
onVerificationRequired: (statusRes) => {
|
||||
setQrStatus('verification');
|
||||
setVerificationUrl(statusRes.verification_url || '');
|
||||
if (statusRes.face_qr_url) {
|
||||
@@ -366,8 +403,8 @@ const AccountList: React.FC = () => {
|
||||
if (statusRes.verification_screenshot) {
|
||||
setVerificationScreenshot(statusRes.verification_screenshot);
|
||||
}
|
||||
}
|
||||
}, 2000);
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
setQrStatus('error');
|
||||
@@ -381,12 +418,10 @@ const AccountList: React.FC = () => {
|
||||
try {
|
||||
const res = await completeQRVerification(qrSessionId);
|
||||
if (res.success && res.cookies && res.unb) {
|
||||
stopQRPolling();
|
||||
await persistQRLoginResult(res.cookies, res.unb, qrReauthTarget);
|
||||
setQrStatus('success');
|
||||
setTimeout(() => {
|
||||
setShowQRModal(false);
|
||||
loadAccounts();
|
||||
}, 1000);
|
||||
scheduleQRModalClose();
|
||||
} else {
|
||||
setQrStatus('verification');
|
||||
alert('验证未完成:' + (res.message || '可能验证尚未通过,请先在验证页面完成验证'));
|
||||
@@ -577,7 +612,7 @@ const AccountList: React.FC = () => {
|
||||
<div className="modal-overlay-centered">
|
||||
<div className="modal-container relative" style={{maxWidth: '24rem'}}>
|
||||
<button
|
||||
onClick={() => setShowQRModal(false)}
|
||||
onClick={closeQRModal}
|
||||
className="absolute top-4 right-4 z-10 w-9 h-9 flex items-center justify-center bg-gray-100 hover:bg-gray-200 rounded-full transition-colors"
|
||||
>
|
||||
<X className="w-5 h-5 text-gray-600" />
|
||||
|
||||
@@ -401,6 +401,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
case 'success': return '成功';
|
||||
case 'failed': return '失败';
|
||||
case 'completed': return '已完成';
|
||||
case 'partially_failed': return '部分失败';
|
||||
case 'canceled': return '已取消';
|
||||
default: return status || '-';
|
||||
}
|
||||
@@ -411,6 +412,7 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
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':
|
||||
|
||||
@@ -221,25 +221,6 @@ const Settings: React.FC = () => {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
|
||||
<div>
|
||||
<div className="font-bold text-gray-900">登录滑动验证码</div>
|
||||
<div className="text-xs text-gray-500 mt-1">开启后账号密码登录需要完成滑动验证</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setSettings({...settings, login_captcha_enabled: !settings.login_captcha_enabled})}
|
||||
className={`w-14 h-8 rounded-full transition-all relative ${
|
||||
settings.login_captcha_enabled ? 'bg-[#0094f7]' : 'bg-gray-300'
|
||||
}`}
|
||||
>
|
||||
<div
|
||||
className={`w-6 h-6 bg-white rounded-full absolute top-1 transition-all shadow-md ${
|
||||
settings.login_captcha_enabled ? 'left-7' : 'left-1'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between p-4 bg-gray-50 rounded-xl">
|
||||
<div>
|
||||
<div className="font-bold text-gray-900">启用商品自动同步</div>
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import { buildAccountLoginInfoUpdate } from './accountEdit';
|
||||
|
||||
test('buildAccountLoginInfoUpdate omits blank password while updating other login fields', () => {
|
||||
const payload = buildAccountLoginInfoUpdate(
|
||||
{ id: 'acc1', enabled: true, auto_confirm: true, username: 'old-user', show_browser: true },
|
||||
{ username: 'new-user', login_password: '', show_browser: false },
|
||||
);
|
||||
|
||||
expect(payload).toEqual({
|
||||
username: 'new-user',
|
||||
show_browser: false,
|
||||
});
|
||||
});
|
||||
|
||||
test('buildAccountLoginInfoUpdate includes password only when user entered one', () => {
|
||||
const payload = buildAccountLoginInfoUpdate(
|
||||
{ id: 'acc1', enabled: true, auto_confirm: true, username: 'old-user', show_browser: false },
|
||||
{ username: 'old-user', login_password: 'new-secret', show_browser: false },
|
||||
);
|
||||
|
||||
expect(payload).toEqual({
|
||||
username: 'old-user',
|
||||
login_password: 'new-secret',
|
||||
show_browser: false,
|
||||
});
|
||||
});
|
||||
|
||||
test('buildAccountLoginInfoUpdate skips unchanged login info', () => {
|
||||
const payload = buildAccountLoginInfoUpdate(
|
||||
{ id: 'acc1', enabled: true, auto_confirm: true, username: 'old-user', show_browser: false },
|
||||
{ username: 'old-user', login_password: '', show_browser: false },
|
||||
);
|
||||
|
||||
expect(payload).toBeNull();
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { AccountDetail } from '../types';
|
||||
|
||||
export interface AccountLoginEditForm {
|
||||
username: string;
|
||||
login_password: string;
|
||||
show_browser: boolean;
|
||||
}
|
||||
|
||||
export interface AccountLoginInfoPayload {
|
||||
username: string;
|
||||
login_password?: string;
|
||||
show_browser: boolean;
|
||||
}
|
||||
|
||||
export const buildAccountLoginInfoUpdate = (
|
||||
account: AccountDetail,
|
||||
form: AccountLoginEditForm,
|
||||
): AccountLoginInfoPayload | null => {
|
||||
const usernameChanged = form.username !== (account.username || '');
|
||||
const showBrowserChanged = form.show_browser !== (account.show_browser || false);
|
||||
const passwordChanged = form.login_password !== '';
|
||||
if (!usernameChanged && !showBrowserChanged && !passwordChanged) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const payload: AccountLoginInfoPayload = {
|
||||
username: form.username,
|
||||
show_browser: form.show_browser,
|
||||
};
|
||||
if (passwordChanged) {
|
||||
payload.login_password = form.login_password;
|
||||
}
|
||||
return payload;
|
||||
};
|
||||
@@ -0,0 +1,98 @@
|
||||
import { afterEach, expect, test, vi } from 'vitest';
|
||||
import { createQRLoginPoller } from './qrPolling';
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
const flushMicrotasks = async () => {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
};
|
||||
|
||||
test('QR poller clears the previous interval before starting another session', () => {
|
||||
vi.useFakeTimers();
|
||||
const checkStatus = vi.fn().mockResolvedValue({ status: 'waiting' });
|
||||
const handlers = {
|
||||
onSuccess: vi.fn(),
|
||||
onTerminalError: vi.fn(),
|
||||
onPollError: vi.fn(),
|
||||
};
|
||||
const poller = createQRLoginPoller();
|
||||
|
||||
poller.start('sid-1', checkStatus, handlers);
|
||||
poller.start('sid-2', checkStatus, handlers);
|
||||
vi.advanceTimersByTime(2000);
|
||||
|
||||
expect(checkStatus).toHaveBeenCalledTimes(1);
|
||||
expect(checkStatus).toHaveBeenCalledWith('sid-2');
|
||||
});
|
||||
|
||||
test('QR poller stops on success and terminal errors', async () => {
|
||||
vi.useFakeTimers();
|
||||
const checkStatus = vi.fn()
|
||||
.mockResolvedValueOnce({ status: 'success', cookies: 'a=b', unb: 'acc1' })
|
||||
.mockResolvedValueOnce({ status: 'expired' });
|
||||
const onSuccess = vi.fn();
|
||||
const onTerminalError = vi.fn();
|
||||
const poller = createQRLoginPoller();
|
||||
|
||||
poller.start('sid-1', checkStatus, {
|
||||
onSuccess,
|
||||
onTerminalError,
|
||||
onPollError: vi.fn(),
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(onSuccess).toHaveBeenCalledWith({ status: 'success', cookies: 'a=b', unb: 'acc1' });
|
||||
expect(poller.isActive()).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(4000);
|
||||
expect(checkStatus).toHaveBeenCalledTimes(1);
|
||||
|
||||
poller.start('sid-2', checkStatus, {
|
||||
onSuccess,
|
||||
onTerminalError,
|
||||
onPollError: vi.fn(),
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(onTerminalError).toHaveBeenCalledWith({ status: 'expired' });
|
||||
expect(poller.isActive()).toBe(false);
|
||||
});
|
||||
|
||||
test('QR poller keeps polling during verification and stops on thrown errors', async () => {
|
||||
vi.useFakeTimers();
|
||||
const checkStatus = vi.fn()
|
||||
.mockResolvedValueOnce({
|
||||
status: 'verification_required',
|
||||
verification_url: 'https://verify.example',
|
||||
face_qr_url: 'https://face.example',
|
||||
})
|
||||
.mockRejectedValueOnce(new Error('network down'));
|
||||
const onVerificationRequired = vi.fn();
|
||||
const onPollError = vi.fn();
|
||||
const poller = createQRLoginPoller();
|
||||
|
||||
poller.start('sid-1', checkStatus, {
|
||||
onSuccess: vi.fn(),
|
||||
onTerminalError: vi.fn(),
|
||||
onPollError,
|
||||
onVerificationRequired,
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(onVerificationRequired).toHaveBeenCalledWith(expect.objectContaining({
|
||||
status: 'verification_required',
|
||||
face_qr_url: 'https://face.example',
|
||||
}));
|
||||
expect(poller.isActive()).toBe(true);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(onPollError).toHaveBeenCalledWith(expect.any(Error));
|
||||
expect(poller.isActive()).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
export interface QRLoginStatusResult {
|
||||
status?: string;
|
||||
cookies?: string;
|
||||
unb?: string;
|
||||
verification_url?: string;
|
||||
verification_screenshot?: string;
|
||||
face_qr_url?: string;
|
||||
}
|
||||
|
||||
interface QRLoginPollerTimers {
|
||||
setInterval: (handler: () => void, timeout: number) => ReturnType<typeof setInterval>;
|
||||
clearInterval: (id: ReturnType<typeof setInterval>) => void;
|
||||
}
|
||||
|
||||
export interface QRLoginPollHandlers {
|
||||
onSuccess: (status: QRLoginStatusResult) => void | Promise<void>;
|
||||
onScanned?: (status: QRLoginStatusResult) => void;
|
||||
onVerificationRequired?: (status: QRLoginStatusResult) => void;
|
||||
onTerminalError: (status: QRLoginStatusResult) => void;
|
||||
onPollError: (error: unknown) => void;
|
||||
}
|
||||
|
||||
const terminalQRStatuses = new Set(['expired', 'cancelled', 'error', 'not_found']);
|
||||
|
||||
export const createQRLoginPoller = (
|
||||
timers: QRLoginPollerTimers = {
|
||||
setInterval: globalThis.setInterval.bind(globalThis),
|
||||
clearInterval: globalThis.clearInterval.bind(globalThis),
|
||||
},
|
||||
) => {
|
||||
let interval: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const stop = () => {
|
||||
if (interval !== null) {
|
||||
timers.clearInterval(interval);
|
||||
interval = null;
|
||||
}
|
||||
};
|
||||
|
||||
const start = (
|
||||
sessionId: string,
|
||||
checkStatus: (sessionId: string) => Promise<QRLoginStatusResult>,
|
||||
handlers: QRLoginPollHandlers,
|
||||
intervalMs = 2000,
|
||||
) => {
|
||||
stop();
|
||||
interval = timers.setInterval(() => {
|
||||
void (async () => {
|
||||
try {
|
||||
const statusRes = await checkStatus(sessionId);
|
||||
if (statusRes.status === 'success') {
|
||||
stop();
|
||||
await handlers.onSuccess(statusRes);
|
||||
return;
|
||||
}
|
||||
if (statusRes.status === 'scanned') {
|
||||
handlers.onScanned?.(statusRes);
|
||||
return;
|
||||
}
|
||||
if (statusRes.status === 'verification_required') {
|
||||
handlers.onVerificationRequired?.(statusRes);
|
||||
return;
|
||||
}
|
||||
if (statusRes.status && terminalQRStatuses.has(statusRes.status)) {
|
||||
stop();
|
||||
handlers.onTerminalError(statusRes);
|
||||
}
|
||||
} catch (error) {
|
||||
stop();
|
||||
handlers.onPollError(error);
|
||||
}
|
||||
})();
|
||||
}, intervalMs);
|
||||
};
|
||||
|
||||
return {
|
||||
start,
|
||||
stop,
|
||||
isActive: () => interval !== null,
|
||||
};
|
||||
};
|
||||
Reference in new issue
Block a user