feat: 重构更新流程 — 无更新不抛异常、用户决定下载、更新详情展示(md文件中的)
【核心重构】
- getLatestVersion() 不再 throw Error,无更新时返回 { version: APP_VERSION }
- checkForUpdates() 先自行预检 → 无更新直发 IPC,有更新才交 electron-updater
- 移除 NO_UPDATE_MESSAGE 常量及所有字符串匹配拦截代码
- HeiXiuProvider 增加 500ms TTL 缓存,避免预检+electron-updater 重复请求 API
【用户体验】
- 检查到新版本后不再自动下载,展示更新内容供用户决定
- 新增"下载更新"按钮(与"安装更新"分离为两步操作)
- 设置页新增"查看详情"弹窗,Markdown 格式化渲染更新日志
- available / downloading / downloaded 三个状态 UI 独立展示
【Bug 修复】
- 测试服务器版本排序:字符串序 → 语义版本序(_version_key),0.0.10 正确 > 0.0.9
- 版本比较:!= → <(_version_key),防止高版本误判为有更新
- get_best_release fallback 同样改为语义版本排序
- Windows cmd set 命令尾部空格 → Invalid URL(.trim() 修复)
- electron-updater 'error' 事件中拦截 NO_UPDATE_MESSAGE → UPDATE_NOT_AVAILABLE
【文档更新】
- CHANGELOG.md、PROJECT.md、UpdateA.md 同步更新架构图和流程说明
This commit is contained in:
@@ -11,7 +11,7 @@ import { safeIpcOn, safeIpcOff } from '@/utils/ipc';
|
||||
import { AppContext } from '@/contexts/app-context';
|
||||
import type { AppContextValue } from '@/contexts/app-context';
|
||||
import type { LoginResponseBody } from '@/services/modules';
|
||||
import { setToken, clearToken } from '@/services/request';
|
||||
import { setToken, clearToken, initTokenStore } from '@/services/request';
|
||||
import { emit, EVENTS } from '@/utils/event-bus';
|
||||
import { logger } from '@/utils/logger';
|
||||
import { AuthAPI } from '@/services/modules';
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
getStoredRefreshToken,
|
||||
setStoredRefreshToken,
|
||||
clearStoredRefreshToken,
|
||||
initRefreshTokenStore,
|
||||
} from '@/services/auth-token';
|
||||
|
||||
interface AppProviderProps {
|
||||
@@ -37,9 +38,9 @@ export function AppProvider({ children }: AppProviderProps) {
|
||||
|
||||
// ---------- 登录 / 退出 ----------
|
||||
|
||||
const login = useCallback((auth: LoginResponseBody) => {
|
||||
setToken(auth.access_token);
|
||||
setStoredRefreshToken(auth.refresh_token);
|
||||
const login = useCallback(async (auth: LoginResponseBody) => {
|
||||
await setToken(auth.access_token);
|
||||
await setStoredRefreshToken(auth.refresh_token);
|
||||
setUser(auth);
|
||||
setIsLoggedIn(true);
|
||||
logger.info('auth', 'User logged in', {
|
||||
@@ -58,57 +59,58 @@ export function AppProvider({ children }: AppProviderProps) {
|
||||
emit(EVENTS.LOGOUT);
|
||||
}, []);
|
||||
|
||||
// ---------- 初始化 token 刷新回调(给 request.ts 401 拦截器用) ----------
|
||||
// ---------- 启动时初始化 token 存储 + 自动登录 ----------
|
||||
|
||||
useEffect(() => {
|
||||
initAuthRefresh();
|
||||
}, []);
|
||||
// 从加密存储恢复 token 到内存缓存
|
||||
Promise.all([initTokenStore(), initRefreshTokenStore()]).then(() => {
|
||||
// 初始化 401 刷新回调(token 缓存就绪后才注册)
|
||||
initAuthRefresh();
|
||||
|
||||
// ---------- 启动时自动登录(refresh_token 续期) ----------
|
||||
// 自动登录(refresh_token 续期)
|
||||
if (!getAutoLoginFlag()) return;
|
||||
|
||||
useEffect(() => {
|
||||
if (!getAutoLoginFlag()) return;
|
||||
const refreshToken = getStoredRefreshToken();
|
||||
if (!refreshToken) return;
|
||||
|
||||
const refreshToken = getStoredRefreshToken();
|
||||
if (!refreshToken) return;
|
||||
|
||||
AuthAPI.refreshToken({ refresh_token: refreshToken })
|
||||
.then((res) => {
|
||||
setToken(res.access_token);
|
||||
setStoredRefreshToken(res.refresh_token);
|
||||
setIsLoggedIn(true);
|
||||
logger.info('auth', 'Auto-login succeeded');
|
||||
// 补全用户信息
|
||||
AuthAPI.getUserInfo().then((info) => {
|
||||
const u: LoginResponseBody = {
|
||||
access_token: res.access_token,
|
||||
refresh_token: res.refresh_token,
|
||||
token_type: res.token_type,
|
||||
expires_in: res.expires_in,
|
||||
refresh_expires_in: res.refresh_expires_in,
|
||||
user_id: info.id,
|
||||
username: info.username,
|
||||
role: info.role,
|
||||
email: info.email,
|
||||
balance_cent: info.balance_cent,
|
||||
account_type: info.account_type,
|
||||
display_name: info.display_name,
|
||||
company_id: info.company_id,
|
||||
real_name: info.real_name,
|
||||
phone: info.phone,
|
||||
license_code: '',
|
||||
admin_permissions: info.admin_permissions,
|
||||
};
|
||||
setUser(u);
|
||||
emit(EVENTS.LOGIN_SUCCESS, u);
|
||||
AuthAPI.refreshToken({ refresh_token: refreshToken })
|
||||
.then(async (res) => {
|
||||
await setToken(res.access_token);
|
||||
await setStoredRefreshToken(res.refresh_token);
|
||||
setIsLoggedIn(true);
|
||||
logger.info('auth', 'Auto-login succeeded');
|
||||
// 补全用户信息
|
||||
AuthAPI.getUserInfo().then((info) => {
|
||||
const u: LoginResponseBody = {
|
||||
access_token: res.access_token,
|
||||
refresh_token: res.refresh_token,
|
||||
token_type: res.token_type,
|
||||
expires_in: res.expires_in,
|
||||
refresh_expires_in: res.refresh_expires_in,
|
||||
user_id: info.id,
|
||||
username: info.username,
|
||||
role: info.role,
|
||||
email: info.email,
|
||||
balance_cent: info.balance_cent,
|
||||
account_type: info.account_type,
|
||||
display_name: info.display_name,
|
||||
company_id: info.company_id,
|
||||
real_name: info.real_name,
|
||||
phone: info.phone,
|
||||
license_code: '',
|
||||
admin_permissions: info.admin_permissions,
|
||||
};
|
||||
setUser(u);
|
||||
emit(EVENTS.LOGIN_SUCCESS, u);
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
logger.warn('auth', 'Auto-login failed, refresh_token expired');
|
||||
clearStoredRefreshToken();
|
||||
// 仅清除自动登录标记,保留用户名供下次表单回填
|
||||
clearAutoLoginFlag();
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
logger.warn('auth', 'Auto-login failed, refresh_token expired');
|
||||
clearStoredRefreshToken();
|
||||
// 仅清除自动登录标记,保留用户名+密码供下次表单回填
|
||||
clearAutoLoginFlag();
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
|
||||
// ---------- 监听主进程推送的平台/版本信息 ----------
|
||||
|
||||
@@ -17,8 +17,8 @@ export interface AppContextValue {
|
||||
isLoggedIn: boolean;
|
||||
/** 当前登录用户信息(未登录时为 null,结构与 LoginResponseBody 一致) */
|
||||
user: LoginResponseBody | null;
|
||||
/** 登录:保存 Token 并更新登录态(auth 为登录接口返回值) */
|
||||
login: (auth: LoginResponseBody) => void;
|
||||
/** 登录:保存 Token 并更新登录态(auth 为登录接口返回值,异步加密存储) */
|
||||
login: (auth: LoginResponseBody) => Promise<void>;
|
||||
/** 退出登录:清除 Token 和用户状态 */
|
||||
logout: () => void;
|
||||
/** 是否为开发环境 */
|
||||
|
||||
@@ -92,6 +92,7 @@ const CH = {
|
||||
UPDATE_NOT_AVAILABLE: 'update-not-available',
|
||||
INSTALL_UPDATE: 'install-update',
|
||||
CHECK_FOR_UPDATE: 'check-for-update',
|
||||
DOWNLOAD_UPDATE: 'download-update',
|
||||
} as const;
|
||||
|
||||
// ---------- 注册 IPC 监听器(模块级,仅一次)----------
|
||||
@@ -153,6 +154,7 @@ export function useUpdater() {
|
||||
|
||||
/** 手动检查更新 */
|
||||
const checkForUpdates = useCallback(async () => {
|
||||
console.log("process.env.UPDATE_API_URL:", process.env.UPDATE_API_URL);
|
||||
setSharedState({ status: 'checking', error: null });
|
||||
try {
|
||||
await safeIpcInvoke(CH.CHECK_FOR_UPDATE);
|
||||
@@ -164,6 +166,19 @@ export function useUpdater() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
/** 用户确认后开始下载更新 */
|
||||
const downloadUpdate = useCallback(async () => {
|
||||
setSharedState({ status: 'downloading', error: null });
|
||||
try {
|
||||
await safeIpcInvoke(CH.DOWNLOAD_UPDATE);
|
||||
} catch (err) {
|
||||
setSharedState({
|
||||
status: 'error',
|
||||
error: { message: (err as Error).message || '下载更新失败' },
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
/** 确认安装更新(退出 → 安装 → 重启) */
|
||||
const installUpdate = useCallback(() => {
|
||||
safeIpcSend(CH.INSTALL_UPDATE);
|
||||
@@ -185,6 +200,7 @@ export function useUpdater() {
|
||||
progress: state.progress,
|
||||
error: state.error,
|
||||
checkForUpdates,
|
||||
downloadUpdate,
|
||||
installUpdate,
|
||||
reset,
|
||||
} as const;
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
// ============================================================
|
||||
// useAuthState — 记住账号 / 记住密码 / 自动登录 状态管理
|
||||
// useAuthState — 记住账号 / 自动登录 状态管理
|
||||
//
|
||||
// "记住密码":下次打开页面自动回填用户名 + 密码(Base64 编码)
|
||||
// "记住密码":下次打开页面自动回填用户名(不再存储密码)
|
||||
// "自动登录":登录成功时标记,AppProvider 启动时用 refresh_token 静默续期
|
||||
//
|
||||
// 注意:密码 Base64 仅作基本混淆,非安全加密。
|
||||
// 安全性由 refresh_token + access_token 的 JWT 双重机制保障。
|
||||
// 安全:
|
||||
// - 密码从不持久化存储(access_token / refresh_token 由 safeStorage 加密保护)
|
||||
// - 安全性由 refresh_token + access_token 的 JWT 双重机制 + OS 密钥链保障
|
||||
// ============================================================
|
||||
|
||||
import { useState, useCallback } from 'react';
|
||||
@@ -15,9 +16,7 @@ const STORAGE_KEY = 'ele-heixiu-auth';
|
||||
interface StoredAuth {
|
||||
/** 上次登录的用户名(表单回填用) */
|
||||
username: string;
|
||||
/** 密码的 Base64 编码(仅"记住密码"勾选时存储) */
|
||||
passwordBase64?: string;
|
||||
/** 是否记住密码(勾选后表单自动回填用户名+密码) */
|
||||
/** 是否记住用户名(勾选后表单自动回填用户名) */
|
||||
remember: boolean;
|
||||
/** 是否勾选了自动登录(AppProvider 据此决定启动时是否刷新 token) */
|
||||
autoLogin: boolean;
|
||||
@@ -48,18 +47,7 @@ export function getAutoLoginFlag(): boolean {
|
||||
return readAuth()?.autoLogin || false;
|
||||
}
|
||||
|
||||
/** 读取存储的密码(Base64 解码后返回明文,表单回填用) */
|
||||
export function getStoredPassword(): string {
|
||||
const auth = readAuth();
|
||||
if (!auth?.passwordBase64) return '';
|
||||
try {
|
||||
return atob(auth.passwordBase64);
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/** 仅清除自动登录标记(保留用户名和密码,下次还能回填表单) */
|
||||
/** 仅清除自动登录标记(保留用户名,下次还能回填表单) */
|
||||
export function clearAutoLoginFlag(): void {
|
||||
const auth = readAuth();
|
||||
if (!auth) return;
|
||||
@@ -81,7 +69,6 @@ export function useAuthState() {
|
||||
const saved = readAuth();
|
||||
|
||||
const [username, setUsername] = useState(saved?.username || '');
|
||||
// 密码不存 state,直接从 localStorage 读取,避免 stale closure 问题
|
||||
const [remember, setRemember] = useState(saved?.remember || false);
|
||||
const [autoLogin, setAutoLogin] = useState(saved?.autoLogin || false);
|
||||
|
||||
@@ -101,13 +88,13 @@ export function useAuthState() {
|
||||
* 登录成功后调用。
|
||||
* 参数由调用方(LoginPage)直接从表单值传入,避免 useCallback 的 stale closure。
|
||||
*
|
||||
* @param user - 用户名
|
||||
* @param password - 明文密码(仅在"记住密码"勾选时存储,Base64 编码)
|
||||
* @param doRemember - 是否勾选"记住密码"
|
||||
* @param user - 用户名
|
||||
* @param _password - 明文密码(不再持久化存储,保留参数以兼容调用方)
|
||||
* @param doRemember - 是否勾选"记住用户名"
|
||||
* @param doAutoLogin - 是否勾选"自动登录"
|
||||
*/
|
||||
const saveAuth = useCallback(
|
||||
(user: string, password: string, doRemember: boolean, doAutoLogin: boolean) => {
|
||||
(user: string, _password: string, doRemember: boolean, doAutoLogin: boolean) => {
|
||||
setUsername(user);
|
||||
if (doRemember || doAutoLogin) {
|
||||
const payload: StoredAuth = {
|
||||
@@ -115,14 +102,6 @@ export function useAuthState() {
|
||||
remember: doRemember,
|
||||
autoLogin: doAutoLogin,
|
||||
};
|
||||
// 仅在勾选"记住密码"时存储密码
|
||||
if (doRemember && password) {
|
||||
try {
|
||||
payload.passwordBase64 = btoa(password);
|
||||
} catch {
|
||||
/* Base64 编码失败则放弃存储密码 */
|
||||
}
|
||||
}
|
||||
writeAuth(payload);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -14,7 +14,7 @@ import { useAppContext } from '@/contexts/app-context.ts';
|
||||
import { useTheme } from '@/hooks/use-theme.ts';
|
||||
import { LoginForm } from './components/LoginForm';
|
||||
import { RegisterForm } from './components/RegisterForm';
|
||||
import { useAuthState, getStoredPassword } from './hooks/use-auth-state';
|
||||
import { useAuthState } from './hooks/use-auth-state';
|
||||
import {AuthAPI, LoginResponseBody} from '@/services/modules';
|
||||
import { getDeviceId } from '@/utils/device';
|
||||
import type { LoginFormValues, RegisterFormValues } from './types';
|
||||
@@ -50,11 +50,11 @@ export function LoginPage({ open, onClose }: LoginPageProps) {
|
||||
user_ip: '',
|
||||
});
|
||||
|
||||
// 记住偏好(密码 Base64 编码,自动登录靠 refresh_token)
|
||||
// 记住偏好(用户名、自动登录标记,密码不再持久化)
|
||||
authState.saveAuth(values.username, values.password, values.remember, values.autoLogin);
|
||||
|
||||
// 更新全局登录态(内部完成 setToken + emit LOGIN_SUCCESS)
|
||||
login(auth);
|
||||
await login(auth);
|
||||
|
||||
message.success(`登录成功,欢迎 ${auth.display_name || auth.username}`);
|
||||
onClose();
|
||||
@@ -111,7 +111,7 @@ export function LoginPage({ open, onClose }: LoginPageProps) {
|
||||
const loginTab = (
|
||||
<LoginForm
|
||||
initialUsername={authState.username}
|
||||
initialPassword={getStoredPassword()}
|
||||
|
||||
initialRemember={authState.remember}
|
||||
initialAutoLogin={authState.autoLogin}
|
||||
submitting={submitting}
|
||||
|
||||
@@ -2,18 +2,67 @@
|
||||
// UpdateSetting — 版本更新区块
|
||||
// ============================================================
|
||||
|
||||
import { Card, Button, Typography, Progress, Tag } from 'antd';
|
||||
import { useState } from 'react';
|
||||
import { Card, Button, Typography, Progress, Tag, Modal, Divider } from 'antd';
|
||||
import {
|
||||
SyncOutlined,
|
||||
CheckCircleOutlined,
|
||||
ExclamationCircleOutlined,
|
||||
RocketOutlined,
|
||||
DownloadOutlined,
|
||||
FileTextOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { useUpdater } from '@/hooks/use-updater';
|
||||
import { isDev } from '@/utils/platform';
|
||||
|
||||
const { Text } = Typography;
|
||||
const { Text, Title } = Typography;
|
||||
|
||||
/** 简单渲染 changelog(Markdown → JSX),支持 ## / - / --- */
|
||||
function renderChangelog(markdown: string) {
|
||||
const lines = markdown.split('\n');
|
||||
const elements: React.ReactNode[] = [];
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
const key = `cl-${i}`;
|
||||
|
||||
if (line.startsWith('## ')) {
|
||||
elements.push(
|
||||
<Title key={key} level={5} className="!mt-3! !mb-1!">
|
||||
{line.slice(3)}
|
||||
</Title>,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (/^-{3,}$/.test(line.trim())) {
|
||||
elements.push(<Divider key={key} className="!my-2!" />);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (line.trim().startsWith('- ')) {
|
||||
elements.push(
|
||||
<Text key={key} className="block pl-3 text-sm leading-relaxed">
|
||||
• {line.trim().slice(2)}
|
||||
</Text>,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (line.trim() === '') {
|
||||
elements.push(<div key={key} className="h-2" />);
|
||||
continue;
|
||||
}
|
||||
|
||||
elements.push(
|
||||
<Text key={key} className="block text-sm leading-relaxed">
|
||||
{line}
|
||||
</Text>,
|
||||
);
|
||||
}
|
||||
|
||||
return elements.length > 0 ? elements : <Text type="secondary">暂无更新详情</Text>;
|
||||
}
|
||||
|
||||
export function UpdateSetting() {
|
||||
const {
|
||||
@@ -22,19 +71,23 @@ export function UpdateSetting() {
|
||||
progress,
|
||||
error,
|
||||
checkForUpdates,
|
||||
downloadUpdate,
|
||||
installUpdate,
|
||||
} = useUpdater();
|
||||
|
||||
const [detailOpen, setDetailOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<Card size="small" title="版本更新" className="rounded-md!">
|
||||
<div className="flex flex-col gap-3">
|
||||
{/* ---- 状态展示 ---- */}
|
||||
{/* ---- idle ---- */}
|
||||
{status === 'idle' && (
|
||||
<Text type="secondary" className="text-sm">
|
||||
点击下方按钮检查是否有新版本
|
||||
</Text>
|
||||
)}
|
||||
|
||||
{/* ---- checking ---- */}
|
||||
{status === 'checking' && (
|
||||
<div className="flex items-center gap-2">
|
||||
<SyncOutlined spin style={{ color: 'var(--color-primary, #4F46E5)' }} />
|
||||
@@ -42,6 +95,7 @@ export function UpdateSetting() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ---- no-update ---- */}
|
||||
{status === 'no-update' && (
|
||||
<div className="flex items-center gap-2">
|
||||
<CheckCircleOutlined style={{ color: 'var(--color-success, #52c41a)' }} />
|
||||
@@ -49,6 +103,7 @@ export function UpdateSetting() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ---- error ---- */}
|
||||
{status === 'error' && (
|
||||
<div className="flex items-center gap-2">
|
||||
<ExclamationCircleOutlined style={{ color: 'var(--color-error, #ff4d4f)' }} />
|
||||
@@ -56,8 +111,8 @@ export function UpdateSetting() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ---- 发现新版本 / 下载中 ---- */}
|
||||
{(status === 'available' || status === 'downloading') && (
|
||||
{/* ---- 发现新版本(等待用户决定)---- */}
|
||||
{status === 'available' && (
|
||||
<>
|
||||
<div className="flex items-center gap-2">
|
||||
<RocketOutlined style={{ color: 'var(--color-primary, #4F46E5)' }} />
|
||||
@@ -65,20 +120,52 @@ export function UpdateSetting() {
|
||||
{info?.forceUpdate && <Tag color="red">强制更新</Tag>}
|
||||
</div>
|
||||
{info?.releaseNotes && (
|
||||
<Text type="secondary" className="text-xs whitespace-pre-line">
|
||||
{info.releaseNotes}
|
||||
</Text>
|
||||
<div className="flex items-start gap-2">
|
||||
<Text
|
||||
type="secondary"
|
||||
className="text-xs whitespace-pre-line line-clamp-2 flex-1"
|
||||
>
|
||||
{info.releaseNotes
|
||||
.replace(/^## .+?\n\n?/, '')
|
||||
.replace(/\n---\n?[\s\S]*$/, '')
|
||||
.trim()}
|
||||
</Text>
|
||||
<Button
|
||||
type="link"
|
||||
size="small"
|
||||
icon={<FileTextOutlined />}
|
||||
onClick={() => setDetailOpen(true)}
|
||||
className="!px-1! flex-shrink-0"
|
||||
>
|
||||
查看详情
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
type="primary"
|
||||
size="small"
|
||||
icon={<DownloadOutlined />}
|
||||
onClick={downloadUpdate}
|
||||
className="self-start"
|
||||
>
|
||||
下载更新
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* ---- 下载进度 ---- */}
|
||||
{/* ---- 下载中 ---- */}
|
||||
{status === 'downloading' && (
|
||||
<Progress
|
||||
percent={progress.percent}
|
||||
strokeColor={{ '0%': '#4F46E5', '100%': '#7C3AED' }}
|
||||
size="small"
|
||||
/>
|
||||
<>
|
||||
<div className="flex items-center gap-2">
|
||||
<DownloadOutlined style={{ color: 'var(--color-primary, #4F46E5)' }} />
|
||||
<Text>正在下载 v{info?.version}...</Text>
|
||||
</div>
|
||||
<Progress
|
||||
percent={progress.percent}
|
||||
strokeColor={{ '0%': '#4F46E5', '100%': '#7C3AED' }}
|
||||
size="small"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* ---- 下载完成 ---- */}
|
||||
@@ -106,17 +193,34 @@ export function UpdateSetting() {
|
||||
size="small"
|
||||
icon={<SyncOutlined spin={status === 'checking'} />}
|
||||
onClick={checkForUpdates}
|
||||
disabled={status === 'checking'}
|
||||
disabled={status === 'checking' || status === 'downloading'}
|
||||
>
|
||||
检查更新
|
||||
</Button>
|
||||
{isDev() && (
|
||||
<Text type="secondary" className="text-xs">
|
||||
生产环境启动 5 秒后自动检查
|
||||
生产环境启动 5 秒后自动检查
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ---- 更新详情弹窗 ---- */}
|
||||
<Modal
|
||||
title={`更新详情 — v${info?.version || ''}`}
|
||||
open={detailOpen}
|
||||
onCancel={() => setDetailOpen(false)}
|
||||
footer={
|
||||
<Button onClick={() => setDetailOpen(false)}>关闭</Button>
|
||||
}
|
||||
width={520}
|
||||
>
|
||||
<div className="max-h-96 overflow-y-auto py-2">
|
||||
{info?.releaseNotes
|
||||
? renderChangelog(info.releaseNotes)
|
||||
: <Text type="secondary">暂无更新详情</Text>}
|
||||
</div>
|
||||
</Modal>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,41 +2,52 @@
|
||||
// auth-token — Token 生命周期管理(存取 refresh_token + 注册刷新回调)
|
||||
//
|
||||
// 职责:
|
||||
// - 持久化 / 清除 refresh_token
|
||||
// - 持久化 / 清除 refresh_token(通过 safeStorage 加密)
|
||||
// - 向 request.ts 注册 handle401 触发的 token 刷新回调
|
||||
// - request.ts 不依赖此模块(通过 setTokenRefreshHandler 解耦)
|
||||
//
|
||||
// 安全:
|
||||
// - refresh_token 由 Electron safeStorage 加密后存入 localStorage
|
||||
// - 内存缓存供同步读取(setTokenRefreshHandler 回调内使用)
|
||||
// ============================================================
|
||||
|
||||
import { setToken, setTokenRefreshHandler } from './request';
|
||||
import { AuthAPI } from './modules';
|
||||
import type { RefreshTokenResponseBody } from './modules';
|
||||
import {
|
||||
getSafeStore,
|
||||
setSafeStore,
|
||||
clearSafeStore,
|
||||
initSafeStore,
|
||||
} from '../utils/safe-storage';
|
||||
|
||||
const REFRESH_KEY = 'ele-heixiu-refresh-token';
|
||||
|
||||
// ---------- 初始化 ----------
|
||||
|
||||
/**
|
||||
* 启动时初始化 refresh_token:从加密存储解密到内存缓存。
|
||||
* 应在 AppProvider 挂载时调用。
|
||||
*/
|
||||
export async function initRefreshTokenStore(): Promise<void> {
|
||||
await initSafeStore(REFRESH_KEY);
|
||||
}
|
||||
|
||||
// ---------- 存取 ----------
|
||||
|
||||
/** 获取当前内存缓存中的 refresh_token(同步,需先调用 initRefreshTokenStore) */
|
||||
export function getStoredRefreshToken(): string | null {
|
||||
try {
|
||||
return localStorage.getItem(REFRESH_KEY);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return getSafeStore(REFRESH_KEY);
|
||||
}
|
||||
|
||||
export function setStoredRefreshToken(token: string): void {
|
||||
try {
|
||||
localStorage.setItem(REFRESH_KEY, token);
|
||||
} catch {
|
||||
/* 静默 */
|
||||
}
|
||||
/** 设置 refresh_token(异步加密存储 + 更新内存缓存) */
|
||||
export async function setStoredRefreshToken(token: string): Promise<void> {
|
||||
await setSafeStore(REFRESH_KEY, token);
|
||||
}
|
||||
|
||||
/** 清除 refresh_token(同步清除内存缓存 + localStorage) */
|
||||
export function clearStoredRefreshToken(): void {
|
||||
try {
|
||||
localStorage.removeItem(REFRESH_KEY);
|
||||
} catch {
|
||||
/* 静默 */
|
||||
}
|
||||
clearSafeStore(REFRESH_KEY);
|
||||
}
|
||||
|
||||
// ---------- 初始化(App 启动时调用一次) ----------
|
||||
@@ -56,9 +67,9 @@ export function initAuthRefresh(): void {
|
||||
try {
|
||||
const res: RefreshTokenResponseBody = await AuthAPI.refreshToken({ refresh_token: refreshToken });
|
||||
|
||||
// 更新持久化 token
|
||||
setToken(res.access_token);
|
||||
setStoredRefreshToken(res.refresh_token);
|
||||
// 更新持久化 token(加密存储)
|
||||
await setToken(res.access_token);
|
||||
await setStoredRefreshToken(res.refresh_token);
|
||||
|
||||
return res.access_token;
|
||||
} catch {
|
||||
|
||||
@@ -19,6 +19,7 @@ import type { ApiResponse } from './types';
|
||||
import { RequestError, RequestErrorType, RefreshError, isRefreshError } from './types';
|
||||
import { emit, EVENTS } from '../utils/event-bus';
|
||||
import { logger } from '../utils/logger';
|
||||
import { getSafeStore, setSafeStore, clearSafeStore, initSafeStore } from '../utils/safe-storage';
|
||||
|
||||
// ---------- 配置 ----------
|
||||
|
||||
@@ -27,7 +28,7 @@ const BASE_URL = import.meta.env.VITE_API_BASE_URL;
|
||||
/** 请求超时时间(毫秒) */
|
||||
const TIMEOUT = 30_000;
|
||||
|
||||
/** localStorage 中 Token 的键名 */
|
||||
/** localStorage 中 Token 的键名(密文由 safeStorage 保护) */
|
||||
const TOKEN_KEY = 'ele-heixiu-token';
|
||||
|
||||
/** refresh token 接口路径(该接口 401 时不应触发 handle401,否则死循环) */
|
||||
@@ -40,31 +41,27 @@ function isRefreshRequest(config: InternalAxiosRequestConfig): boolean {
|
||||
|
||||
// ---------- Token 管理 ----------
|
||||
|
||||
/** 获取存储的 Token */
|
||||
/**
|
||||
* 启动时初始化 Token:从加密存储解密到内存缓存。
|
||||
* 应在 AppProvider 挂载时调用(login/logout 之前)。
|
||||
*/
|
||||
export async function initTokenStore(): Promise<void> {
|
||||
await initSafeStore(TOKEN_KEY);
|
||||
}
|
||||
|
||||
/** 获取当前内存缓存中的 Token(同步,高频安全) */
|
||||
export function getToken(): string | null {
|
||||
try {
|
||||
return localStorage.getItem(TOKEN_KEY);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return getSafeStore(TOKEN_KEY);
|
||||
}
|
||||
|
||||
/** 设置 Token */
|
||||
export function setToken(token: string): void {
|
||||
try {
|
||||
localStorage.setItem(TOKEN_KEY, token);
|
||||
} catch {
|
||||
/* 静默忽略 */
|
||||
}
|
||||
/** 设置 Token(异步加密存储 + 更新内存缓存) */
|
||||
export async function setToken(token: string): Promise<void> {
|
||||
await setSafeStore(TOKEN_KEY, token);
|
||||
}
|
||||
|
||||
/** 清除 Token */
|
||||
/** 清除 Token(同步清除内存缓存 + localStorage) */
|
||||
export function clearToken(): void {
|
||||
try {
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
} catch {
|
||||
/* 静默忽略 */
|
||||
}
|
||||
clearSafeStore(TOKEN_KEY);
|
||||
}
|
||||
|
||||
// ---------- Token 刷新(由外部注册,request.ts 不依赖任何 auth 模块) ----------
|
||||
|
||||
147
src/utils/safe-storage.ts
Normal file
147
src/utils/safe-storage.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
// ============================================================
|
||||
// safe-storage — 渲染进程安全存储工具
|
||||
//
|
||||
// 架构:
|
||||
// - 内存缓存:get() 同步返回,避免每次 API 请求都触发 IPC 往返
|
||||
// - 持久化:set() 异步加密后写入 localStorage
|
||||
// - 启动恢复:init() 从 localStorage 读取密文,异步解密到内存缓存
|
||||
// - 降级:非 Electron 环境回退到 localStorage 明文(仅开发用)
|
||||
//
|
||||
// 使用模式:
|
||||
// // App 启动时
|
||||
// await safeStore.init('my-key');
|
||||
//
|
||||
// // 任意位置读取(同步,高频安全)
|
||||
// const value = safeStore.get('my-key');
|
||||
//
|
||||
// // 写入(异步加密)
|
||||
// await safeStore.set('my-key', 'plaintext');
|
||||
//
|
||||
// // 清除
|
||||
// safeStore.clear('my-key');
|
||||
// ============================================================
|
||||
|
||||
import { hasIpc } from './ipc';
|
||||
|
||||
// ---------- 内部状态 ----------
|
||||
|
||||
/** 内存缓存(key → 明文) */
|
||||
const cache = new Map<string, string>();
|
||||
|
||||
// ---------- IPC 桥接 ----------
|
||||
|
||||
interface SafeStorageBridge {
|
||||
encrypt(plaintext: string): Promise<string | null>;
|
||||
decrypt(encryptedBase64: string): Promise<string | null>;
|
||||
}
|
||||
|
||||
/** 获取 safeStorage 桥接(由 preload 注入) */
|
||||
function getBridge(): SafeStorageBridge | null {
|
||||
if (!hasIpc() || !window.safeStorage) return null;
|
||||
return window.safeStorage;
|
||||
}
|
||||
|
||||
// ---------- 公开 API ----------
|
||||
|
||||
/**
|
||||
* 初始化指定的键:从持久化存储读取密文 → 解密 → 加载到内存缓存。
|
||||
* 应在 App 启动时(如 AppProvider 挂载)对需要用到的 key 逐一调用。
|
||||
*
|
||||
* @param key - 存储键名(与 localStorage key 对应)
|
||||
* @returns 解密后的明文,失败或无数据返回 null
|
||||
*/
|
||||
export async function initSafeStore(key: string): Promise<string | null> {
|
||||
// 先从 localStorage 读取密文
|
||||
let encrypted: string | null = null;
|
||||
try {
|
||||
encrypted = localStorage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!encrypted) return null;
|
||||
|
||||
const bridge = getBridge();
|
||||
|
||||
if (bridge) {
|
||||
// Electron 环境:IPC 解密
|
||||
const plaintext = await bridge.decrypt(encrypted);
|
||||
if (plaintext !== null) {
|
||||
cache.set(key, plaintext);
|
||||
return plaintext;
|
||||
}
|
||||
// 解密失败(可能 OS 密钥变更)→ 清除残留
|
||||
try {
|
||||
localStorage.removeItem(key);
|
||||
} catch {
|
||||
/* 静默 */
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// 非 Electron 环境(浏览器开发):localStorage 明文
|
||||
cache.set(key, encrypted);
|
||||
return encrypted;
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步读取已缓存的明文(高频安全,不触发 IPC)。
|
||||
* 如果缓存未命中,返回 null(调用方应先 await initSafeStore)。
|
||||
*/
|
||||
export function getSafeStore(key: string): string | null {
|
||||
return cache.get(key) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密并持久化存储。
|
||||
* 同时更新内存缓存(后续 get() 可直接同步读取)。
|
||||
*
|
||||
* @returns 是否存储成功
|
||||
*/
|
||||
export async function setSafeStore(key: string, plaintext: string): Promise<boolean> {
|
||||
// 先更新内存缓存(即使持久化失败,当前 session 仍可用)
|
||||
cache.set(key, plaintext);
|
||||
|
||||
const bridge = getBridge();
|
||||
|
||||
if (bridge) {
|
||||
// Electron 环境:加密后写入 localStorage
|
||||
const encrypted = await bridge.encrypt(plaintext);
|
||||
if (encrypted !== null) {
|
||||
try {
|
||||
localStorage.setItem(key, encrypted);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 非 Electron 环境:直接写入 localStorage 明文
|
||||
try {
|
||||
localStorage.setItem(key, plaintext);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除指定键的缓存和持久化数据。
|
||||
* 同步执行(不阻塞),持久化清除为 best-effort。
|
||||
*/
|
||||
export function clearSafeStore(key: string): void {
|
||||
cache.delete(key);
|
||||
try {
|
||||
localStorage.removeItem(key);
|
||||
} catch {
|
||||
/* 静默 */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查指定键是否已有缓存(用于判断 init 是否已被调用)。
|
||||
*/
|
||||
export function hasSafeStoreCache(key: string): boolean {
|
||||
return cache.has(key);
|
||||
}
|
||||
5
src/vite-env.d.ts
vendored
5
src/vite-env.d.ts
vendored
@@ -8,6 +8,11 @@ declare global {
|
||||
send(channel: string, ...args: unknown[]): void;
|
||||
invoke(channel: string, ...args: unknown[]): Promise<unknown>;
|
||||
};
|
||||
/** Electron safeStorage 安全加密 API(由 preload 注入,基于 OS 原生密钥链) */
|
||||
safeStorage: {
|
||||
encrypt(plaintext: string): Promise<string | null>;
|
||||
decrypt(encryptedBase64: string): Promise<string | null>;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user