11import { ApiResponse } from '../types' ;
2- import { showToast } from '../components/Toast'
2+ import { showToast } from '../components/Toast' ;
3+ import { hashPassword } from './passwordHash' ;
4+ import { getCookie , setCookie } from './cookie' ;
35
46const TOKEN_KEY = 'webui_token' ;
7+ const TOKEN_EXPIRY_DAYS = 30 ; // Cookie 过期天数
8+
59let passwordPromptHandler : ( ( tip : string ) => Promise < string > ) | null = null ;
610
711export function setPasswordPromptHandler ( handler : ( tip : string ) => Promise < string > ) {
812 passwordPromptHandler = handler ;
913}
1014
1115export function getToken ( ) : string | null {
12- return localStorage . getItem ( TOKEN_KEY ) ;
16+ return getCookie ( TOKEN_KEY ) ;
1317}
1418
1519export function setTokenStorage ( token : string ) {
16- localStorage . setItem ( TOKEN_KEY , token ) ;
20+ setCookie ( TOKEN_KEY , token , TOKEN_EXPIRY_DAYS ) ;
1721}
1822
1923export async function apiFetch < T = any > (
@@ -49,7 +53,7 @@ export async function apiFetch<T = any>(
4953 throw new Error ( '密码不能为空' ) ;
5054 }
5155
52- // 调用设置密码接口
56+ // 调用设置密码接口(传送明文)
5357 const setTokenResponse = await fetch ( '/api/set-token' , {
5458 method : 'POST' ,
5559 headers : { 'Content-Type' : 'application/json' } ,
@@ -60,10 +64,12 @@ export async function apiFetch<T = any>(
6064 throw new Error ( '设置密码失败' ) ;
6165 }
6266
63- setTokenStorage ( newPassword . trim ( ) ) ;
67+ // 存储 hash 后的密码
68+ const hashedPassword = await hashPassword ( newPassword . trim ( ) ) ;
69+ setTokenStorage ( hashedPassword ) ;
6470
65- // 重新请求原接口
66- response = await makeRequest ( newPassword . trim ( ) ) ;
71+ // 重新请求原接口(使用 hash)
72+ response = await makeRequest ( hashedPassword ) ;
6773 }
6874
6975 // 403: 密码错误或账户锁定,需要重新输入
@@ -96,10 +102,12 @@ export async function apiFetch<T = any>(
96102 throw new Error ( '密码不能为空' ) ;
97103 }
98104
99- setTokenStorage ( newPassword . trim ( ) ) ;
105+ // 存储 hash 后的密码
106+ const hashedPassword = await hashPassword ( newPassword . trim ( ) ) ;
107+ setTokenStorage ( hashedPassword ) ;
100108
101- // 重新请求
102- response = await makeRequest ( newPassword . trim ( ) ) ;
109+ // 重新请求(使用 hash)
110+ response = await makeRequest ( hashedPassword ) ;
103111
104112 if ( response . status === 200 ) {
105113 console . log ( 'Authentication successful!' ) ;
0 commit comments