|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
let cachedPasswordHash = null; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async function getPasswordHash() { |
|
|
if (cachedPasswordHash) { |
|
|
return cachedPasswordHash; |
|
|
} |
|
|
|
|
|
|
|
|
const storedHash = localStorage.getItem('proxyAuthHash'); |
|
|
if (storedHash) { |
|
|
cachedPasswordHash = storedHash; |
|
|
return storedHash; |
|
|
} |
|
|
|
|
|
|
|
|
const passwordVerified = localStorage.getItem('passwordVerified'); |
|
|
const storedPasswordHash = localStorage.getItem('passwordHash'); |
|
|
if (passwordVerified === 'true' && storedPasswordHash) { |
|
|
localStorage.setItem('proxyAuthHash', storedPasswordHash); |
|
|
cachedPasswordHash = storedPasswordHash; |
|
|
return storedPasswordHash; |
|
|
} |
|
|
|
|
|
|
|
|
const userPassword = localStorage.getItem('userPassword'); |
|
|
if (userPassword) { |
|
|
try { |
|
|
|
|
|
const { sha256 } = await import('./sha256.js'); |
|
|
const hash = await sha256(userPassword); |
|
|
localStorage.setItem('proxyAuthHash', hash); |
|
|
cachedPasswordHash = hash; |
|
|
return hash; |
|
|
} catch (error) { |
|
|
console.error('生成密码哈希失败:', error); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
if (window.__ENV__ && window.__ENV__.PASSWORD) { |
|
|
cachedPasswordHash = window.__ENV__.PASSWORD; |
|
|
return window.__ENV__.PASSWORD; |
|
|
} |
|
|
|
|
|
return null; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async function addAuthToProxyUrl(url) { |
|
|
try { |
|
|
const hash = await getPasswordHash(); |
|
|
if (!hash) { |
|
|
console.warn('无法获取密码哈希,代理请求可能失败'); |
|
|
return url; |
|
|
} |
|
|
|
|
|
|
|
|
const timestamp = Date.now(); |
|
|
|
|
|
|
|
|
const separator = url.includes('?') ? '&' : '?'; |
|
|
|
|
|
return `${url}${separator}auth=${encodeURIComponent(hash)}&t=${timestamp}`; |
|
|
} catch (error) { |
|
|
console.error('添加代理鉴权失败:', error); |
|
|
return url; |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function validateProxyAuth(authHash, serverPasswordHash, timestamp) { |
|
|
if (!authHash || !serverPasswordHash) { |
|
|
return false; |
|
|
} |
|
|
|
|
|
|
|
|
if (authHash !== serverPasswordHash) { |
|
|
return false; |
|
|
} |
|
|
|
|
|
|
|
|
const now = Date.now(); |
|
|
const maxAge = 10 * 60 * 1000; |
|
|
|
|
|
if (timestamp && (now - parseInt(timestamp)) > maxAge) { |
|
|
console.warn('代理请求时间戳过期'); |
|
|
return false; |
|
|
} |
|
|
|
|
|
return true; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function clearAuthCache() { |
|
|
cachedPasswordHash = null; |
|
|
localStorage.removeItem('proxyAuthHash'); |
|
|
} |
|
|
|
|
|
|
|
|
window.addEventListener('storage', (e) => { |
|
|
if (e.key === 'userPassword' || (window.PASSWORD_CONFIG && e.key === window.PASSWORD_CONFIG.localStorageKey)) { |
|
|
clearAuthCache(); |
|
|
} |
|
|
}); |
|
|
|
|
|
|
|
|
window.ProxyAuth = { |
|
|
addAuthToProxyUrl, |
|
|
validateProxyAuth, |
|
|
clearAuthCache, |
|
|
getPasswordHash |
|
|
}; |
|
|
|