一分钟搭建影视站,支持Docker等部署方式
feat: implement proxy request authentication mechanism using PASSWORD
developere323adae11bc
diff --git a/api/proxy/[...path].mjs b/api/proxy/[...path].mjsindex 047a125..70f3b48 100644--- a/api/proxy/[...path].mjs+++ b/api/proxy/[...path].mjs@@ -2,6 +2,7 @@import fetch from 'node-fetch';import { URL } from 'url'; // 使用 Node.js 内置 URL 处理+import crypto from 'crypto'; // 导入 crypto 模块用于密码哈希// --- 配置 (从环境变量读取) ---const DEBUG_ENABLED = process.env.DEBUG === 'true';@@ -299,6 +300,40 @@ async function processMasterPlaylist(url, content, recursionDepth) {return await processM3u8Content(bestVariantUrl, variantContent, recursionDepth + 1);}+/**+ * 验证代理请求的鉴权+ */+async function validateAuth(req) {+ const authHash = req.query.auth;+ const timestamp = req.query.t;++ // 获取服务器端密码哈希+ const serverPassword = process.env.PASSWORD;+ if (!serverPassword) {+ console.error('服务器未设置 PASSWORD 环境变量,代理访问被拒绝');+ return false;+ }++ // 使用 crypto 模块计算 SHA-256 哈希+ const serverPasswordHash = crypto.createHash('sha256').update(serverPassword).digest('hex');++ if (!authHash || authHash !== serverPasswordHash) {+ console.warn('代理请求鉴权失败:密码哈希不匹配');+ return false;+ }++ // 验证时间戳(10分钟有效期)+ if (timestamp) {+ const now = Date.now();+ const maxAge = 10 * 60 * 1000; // 10分钟+ if (now - parseInt(timestamp) > maxAge) {+ console.warn('代理请求鉴权失败:时间戳过期');+ return false;+ }+ }++ return true;+}// --- Vercel Handler 函数 ---export default async function handler(req, res) {@@ -325,6 +360,17 @@ export default async function handler(req, res) {try { // ---- 开始主处理逻辑的 try 块 ----+ // --- 验证鉴权 ---+ const isAuthorized = await validateAuth(req);+ if (!isAuthorized) {+ console.warn('代理请求鉴权失败');+ res.status(401).json({+ success: false,+ error: '代理访问未授权:请检查密码配置或鉴权参数'+ });+ return;+ }+// --- 提取目标 URL (主要依赖 req.query["...path"]) ---// Vercel 将 :path* 捕获的内容(可能包含斜杠)放入 req.query["...path"] 数组const pathData = req.query["...path"]; // 使用正确的键名diff --git a/functions/proxy/[[path]].js b/functions/proxy/[[path]].jsindex bc4e886..977b74b 100644--- a/functions/proxy/[[path]].js+++ b/functions/proxy/[[path]].js@@ -7,6 +7,7 @@// FILTER_DISCONTINUITY (不再需要,设为 false 或移除)// USER_AGENTS_JSON (例如 ["UA1", "UA2"]) - JSON 字符串数组// DEBUG (例如 false 或 true)+// PASSWORD (例如 "your_password") - 鉴权密码// --- 配置结束 ---// --- 常量 (之前在 config.js 中,现在移到这里,因为它们与代理逻辑相关) ---@@ -27,6 +28,23 @@ export async function onRequest(context) {const { request, env, next, waitUntil } = context; // next 和 waitUntil 可能需要const url = new URL(request.url);+ // 验证鉴权(主函数调用)+ const isValidAuth = await validateAuth(request, env);+ if (!isValidAuth) {+ return new Response(JSON.stringify({+ success: false,+ error: '代理访问未授权:请检查密码配置或鉴权参数'+ }), {+ status: 401,+ headers: {+ 'Access-Control-Allow-Origin': '*',+ 'Access-Control-Allow-Methods': 'GET, HEAD, POST, OPTIONS',+ 'Access-Control-Allow-Headers': '*',+ 'Content-Type': 'application/json'+ }+ });+ }+// --- 从环境变量读取配置 ---const DEBUG_ENABLED = (env.DEBUG === 'true');const CACHE_TTL = parseInt(env.CACHE_TTL || '86400'); // 默认 24 小时@@ -54,6 +72,62 @@ export async function onRequest(context) {// --- 辅助函数 ---+ // 验证代理请求的鉴权+ async function validateAuth(request, env) {+ const url = new URL(request.url);+ const authHash = url.searchParams.get('auth');+ const timestamp = url.searchParams.get('t');++ // 获取服务器端密码+ const serverPassword = env.PASSWORD;+ if (!serverPassword) {+ console.error('服务器未设置 PASSWORD 环境变量,代理访问被拒绝');+ return false;+ }++ // 使用 SHA-256 哈希算法(与其他平台保持一致)+ // 在 Cloudflare Workers 中使用 crypto.subtle+ try {+ const encoder = new TextEncoder();+ const data = encoder.encode(serverPassword);+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);+ const hashArray = Array.from(new Uint8Array(hashBuffer));+ const serverPasswordHash = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');++ if (!authHash || authHash !== serverPasswordHash) {+ console.warn('代理请求鉴权失败:密码哈希不匹配');+ return false;+ }+ } catch (error) {+ console.error('计算密码哈希失败:', error);+ return false;+ }++ // 验证时间戳(10分钟有效期)+ if (timestamp) {+ const now = Date.now();+ const maxAge = 10 * 60 * 1000; // 10分钟+ if (now - parseInt(timestamp) > maxAge) {+ console.warn('代理请求鉴权失败:时间戳过期');+ return false;+ }+ }++ return true;+ }++ // 验证鉴权(主函数调用)+ if (!validateAuth(request, env)) {+ return new Response('Unauthorized', {+ status: 401,+ headers: {+ 'Access-Control-Allow-Origin': '*',+ 'Access-Control-Allow-Methods': 'GET, HEAD, POST, OPTIONS',+ 'Access-Control-Allow-Headers': '*'+ }+ });+ }+// 输出调试日志 (需要设置 DEBUG: true 环境变量)function logDebug(message) {if (DEBUG_ENABLED) {diff --git a/index.html b/index.htmlindex 5d63128..5a491f1 100644--- a/index.html+++ b/index.html@@ -414,6 +414,7 @@window._jsSha256 = window.sha256;</script><script src="js/config.js"></script>+ <script src="js/proxy-auth.js"></script><script src="js/customer_site.js"></script><script src="js/ui.js"></script><script src="js/api.js"></script>diff --git a/js/api.js b/js/api.jsindex dc02eae..34332a3 100644--- a/js/api.js+++ b/js/api.js@@ -29,7 +29,12 @@ async function handleApiRequest(url) {const timeoutId = setTimeout(() => controller.abort(), 10000);try {- const response = await fetch(PROXY_URL + encodeURIComponent(apiUrl), {+ // 添加鉴权参数到代理URL+ const proxiedUrl = await window.ProxyAuth?.addAuthToProxyUrl ?+ await window.ProxyAuth.addAuthToProxyUrl(PROXY_URL + encodeURIComponent(apiUrl)) :+ PROXY_URL + encodeURIComponent(apiUrl);++ const response = await fetch(proxiedUrl, {headers: API_CONFIG.search.headers,signal: controller.signal});@@ -113,7 +118,12 @@ async function handleApiRequest(url) {const timeoutId = setTimeout(() => controller.abort(), 10000);try {- const response = await fetch(PROXY_URL + encodeURIComponent(detailUrl), {+ // 添加鉴权参数到代理URL+ const proxiedUrl = await window.ProxyAuth?.addAuthToProxyUrl ?+ await window.ProxyAuth.addAuthToProxyUrl(PROXY_URL + encodeURIComponent(detailUrl)) :+ PROXY_URL + encodeURIComponent(detailUrl);++ const response = await fetch(proxiedUrl, {headers: API_CONFIG.detail.headers,signal: controller.signal});@@ -209,8 +219,13 @@ async function handleCustomApiSpecialDetail(id, customApi) {const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), 10000);+ // 添加鉴权参数到代理URL+ const proxiedUrl = await window.ProxyAuth?.addAuthToProxyUrl ?+ await window.ProxyAuth.addAuthToProxyUrl(PROXY_URL + encodeURIComponent(detailUrl)) :+ PROXY_URL + encodeURIComponent(detailUrl);+// 获取详情页HTML- const response = await fetch(PROXY_URL + encodeURIComponent(detailUrl), {+ const response = await fetch(proxiedUrl, {headers: {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',},@@ -271,8 +286,13 @@ async function handleSpecialSourceDetail(id, sourceCode) {const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), 10000);+ // 添加鉴权参数到代理URL+ const proxiedUrl = await window.ProxyAuth?.addAuthToProxyUrl ?+ await window.ProxyAuth.addAuthToProxyUrl(PROXY_URL + encodeURIComponent(detailUrl)) :+ PROXY_URL + encodeURIComponent(detailUrl);+// 获取详情页HTML- const response = await fetch(PROXY_URL + encodeURIComponent(detailUrl), {+ const response = await fetch(proxiedUrl, {headers: {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',},@@ -356,7 +376,12 @@ async function handleAggregatedSearch(searchQuery) {setTimeout(() => reject(new Error(`${source}源搜索超时`)), 8000));- const fetchPromise = fetch(PROXY_URL + encodeURIComponent(apiUrl), {+ // 添加鉴权参数到代理URL+ const proxiedUrl = await window.ProxyAuth?.addAuthToProxyUrl ?+ await window.ProxyAuth.addAuthToProxyUrl(PROXY_URL + encodeURIComponent(apiUrl)) :+ PROXY_URL + encodeURIComponent(apiUrl);++ const fetchPromise = fetch(proxiedUrl, {headers: API_CONFIG.search.headers});@@ -465,7 +490,12 @@ async function handleMultipleCustomSearch(searchQuery, customApiUrls) {setTimeout(() => reject(new Error(`自定义API ${index+1} 搜索超时`)), 8000));- const fetchPromise = fetch(PROXY_URL + encodeURIComponent(fullUrl), {+ // 添加鉴权参数到代理URL+ const proxiedUrl = await window.ProxyAuth?.addAuthToProxyUrl ?+ await window.ProxyAuth.addAuthToProxyUrl(PROXY_URL + encodeURIComponent(fullUrl)) :+ PROXY_URL + encodeURIComponent(fullUrl);++ const fetchPromise = fetch(proxiedUrl, {headers: API_CONFIG.search.headers});diff --git a/js/douban.js b/js/douban.jsindex 9b4c26d..6de0f57 100644--- a/js/douban.js+++ b/js/douban.js@@ -457,8 +457,13 @@ async function fetchDoubanData(url) {};try {+ // 添加鉴权参数到代理URL+ const proxiedUrl = await window.ProxyAuth?.addAuthToProxyUrl ?+ await window.ProxyAuth.addAuthToProxyUrl(PROXY_URL + encodeURIComponent(url)) :+ PROXY_URL + encodeURIComponent(url);+// 尝试直接访问(豆瓣API可能允许部分CORS请求)- const response = await fetch(PROXY_URL + encodeURIComponent(url), fetchOptions);+ const response = await fetch(proxiedUrl, fetchOptions);clearTimeout(timeoutId);if (!response.ok) {diff --git a/js/proxy-auth.js b/js/proxy-auth.jsnew file mode 100644index 0000000..9030d9d--- /dev/null+++ b/js/proxy-auth.js@@ -0,0 +1,127 @@+/**+ * 代理请求鉴权模块+ * 为代理请求添加基于 PASSWORD 的鉴权机制+ */++// 从全局配置获取密码哈希(如果存在)+let cachedPasswordHash = null;++/**+ * 获取当前会话的密码哈希+ */+async function getPasswordHash() {+ if (cachedPasswordHash) {+ return cachedPasswordHash;+ }++ // 1. 优先从已存储的代理鉴权哈希获取+ const storedHash = localStorage.getItem('proxyAuthHash');+ if (storedHash) {+ cachedPasswordHash = storedHash;+ return storedHash;+ }++ // 2. 尝试从密码验证状态获取(password.js 验证后存储的哈希)+ const passwordVerified = localStorage.getItem('passwordVerified');+ const storedPasswordHash = localStorage.getItem('passwordHash');+ if (passwordVerified === 'true' && storedPasswordHash) {+ localStorage.setItem('proxyAuthHash', storedPasswordHash);+ cachedPasswordHash = storedPasswordHash;+ return storedPasswordHash;+ }++ // 3. 尝试从用户输入的密码生成哈希+ const userPassword = localStorage.getItem('userPassword');+ if (userPassword) {+ try {+ // 动态导入 sha256 函数+ const { sha256 } = await import('./sha256.js');+ const hash = await sha256(userPassword);+ localStorage.setItem('proxyAuthHash', hash);+ cachedPasswordHash = hash;+ return hash;+ } catch (error) {+ console.error('生成密码哈希失败:', error);+ }+ }++ // 4. 如果用户没有设置密码,尝试使用环境变量中的密码哈希+ if (window.__ENV__ && window.__ENV__.PASSWORD) {+ cachedPasswordHash = window.__ENV__.PASSWORD;+ return window.__ENV__.PASSWORD;+ }++ return null;+}++/**+ * 为代理请求URL添加鉴权参数+ */+async function addAuthToProxyUrl(url) {+ try {+ const hash = await getPasswordHash();+ if (!hash) {+ console.warn('无法获取密码哈希,代理请求可能失败');+ return url;+ }++ // 添加时间戳防止重放攻击+ const timestamp = Date.now();++ // 检查URL是否已包含查询参数+ 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;+ }++ // 验证时间戳(10分钟有效期)+ const now = Date.now();+ const maxAge = 10 * 60 * 1000; // 10分钟++ 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+};diff --git a/js/search.js b/js/search.jsindex d2aa386..8f9b6a4 100644--- a/js/search.js+++ b/js/search.js@@ -23,7 +23,12 @@ async function searchByAPIAndKeyWord(apiId, query) {const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), 8000);- const response = await fetch(PROXY_URL + encodeURIComponent(apiUrl), {+ // 添加鉴权参数到代理URL+ const proxiedUrl = await window.ProxyAuth?.addAuthToProxyUrl ?+ await window.ProxyAuth.addAuthToProxyUrl(PROXY_URL + encodeURIComponent(apiUrl)) :+ PROXY_URL + encodeURIComponent(apiUrl);++ const response = await fetch(proxiedUrl, {headers: API_CONFIG.search.headers,signal: controller.signal});@@ -69,7 +74,12 @@ async function searchByAPIAndKeyWord(apiId, query) {const pageController = new AbortController();const pageTimeoutId = setTimeout(() => pageController.abort(), 8000);- const pageResponse = await fetch(PROXY_URL + encodeURIComponent(pageUrl), {+ // 添加鉴权参数到代理URL+ const proxiedPageUrl = await window.ProxyAuth?.addAuthToProxyUrl ?+ await window.ProxyAuth.addAuthToProxyUrl(PROXY_URL + encodeURIComponent(pageUrl)) :+ PROXY_URL + encodeURIComponent(pageUrl);++ const pageResponse = await fetch(proxiedPageUrl, {headers: API_CONFIG.search.headers,signal: pageController.signal});diff --git a/netlify/functions/proxy.mjs b/netlify/functions/proxy.mjsindex 6d1e146..412754b 100644--- a/netlify/functions/proxy.mjs+++ b/netlify/functions/proxy.mjs@@ -2,6 +2,7 @@import fetch from 'node-fetch';import { URL } from 'url'; // Use Node.js built-in URL+import crypto from 'crypto'; // 导入 crypto 模块用于密码哈希// --- Configuration (Read from Environment Variables) ---const DEBUG_ENABLED = process.env.DEBUG === 'true';@@ -86,6 +87,42 @@ function rewriteUrlToProxy(targetUrl) {function getRandomUserAgent() { return USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)]; }+/**+ * 验证代理请求的鉴权+ */+function validateAuth(event) {+ const params = new URLSearchParams(event.queryStringParameters || {});+ const authHash = params.get('auth');+ const timestamp = params.get('t');++ // 获取服务器端密码哈希+ const serverPassword = process.env.PASSWORD;+ if (!serverPassword) {+ console.error('服务器未设置 PASSWORD 环境变量,代理访问被拒绝');+ return false;+ }++ // 使用 crypto 模块计算 SHA-256 哈希+ const serverPasswordHash = crypto.createHash('sha256').update(serverPassword).digest('hex');++ if (!authHash || authHash !== serverPasswordHash) {+ console.warn('代理请求鉴权失败:密码哈希不匹配');+ return false;+ }++ // 验证时间戳(10分钟有效期)+ if (timestamp) {+ const now = Date.now();+ const maxAge = 10 * 60 * 1000; // 10分钟+ if (now - parseInt(timestamp) > maxAge) {+ console.warn('代理请求鉴权失败:时间戳过期');+ return false;+ }+ }++ return true;+}+async function fetchContentWithType(targetUrl, requestHeaders) {const headers = {'User-Agent': getRandomUserAgent(),@@ -178,6 +215,19 @@ export const handler = async (event, context) => {};}+ // --- 验证鉴权 ---+ if (!validateAuth(event)) {+ console.warn('Netlify 代理请求鉴权失败');+ return {+ statusCode: 401,+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },+ body: JSON.stringify({+ success: false,+ error: '代理访问未授权:请检查密码配置或鉴权参数'+ }),+ };+ }+// --- Extract Target URL ---// Based on netlify.toml rewrite: from = "/proxy/*" to = "/.netlify/functions/proxy/:splat"// The :splat part should be available in event.path after the base path@@ -210,6 +260,16 @@ export const handler = async (event, context) => {logDebug(`Processing proxy request for target: ${targetUrl}`);try {+ // 验证鉴权+ const isValidAuth = validateAuth(event);+ if (!isValidAuth) {+ return {+ statusCode: 403,+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },+ body: JSON.stringify({ success: false, error: "Forbidden: Invalid auth credentials." }),+ };+ }+// Fetch Original Content (Pass Netlify event headers)const { content, contentType, responseHeaders } = await fetchContentWithType(targetUrl, event.headers);diff --git a/player.html b/player.htmlindex d822e1b..100c526 100644--- a/player.html+++ b/player.html@@ -227,6 +227,7 @@<script src="libs/artplayer.min.js" crossorigin="anonymous"></script><script src="js/config.js"></script>+ <script src="js/proxy-auth.js"></script><script src="js/customer_site.js"></script><script src="js/password.js"></script><script src="js/ui.js"></script>diff --git a/server.mjs b/server.mjsindex 19bf67e..53b9791 100644--- a/server.mjs+++ b/server.mjs@@ -128,8 +128,49 @@ app.use('/proxy', (req, res, next) => {});// 代理路由+// 验证代理请求的鉴权+function validateProxyAuth(req) {+ const authHash = req.query.auth;+ const timestamp = req.query.t;++ // 获取服务器端密码哈希+ const serverPassword = config.password;+ if (!serverPassword) {+ console.error('服务器未设置 PASSWORD 环境变量,代理访问被拒绝');+ return false;+ }++ // 使用 crypto 模块计算 SHA-256 哈希+ const serverPasswordHash = crypto.createHash('sha256').update(serverPassword).digest('hex');++ if (!authHash || authHash !== serverPasswordHash) {+ console.warn('代理请求鉴权失败:密码哈希不匹配');+ return false;+ }++ // 验证时间戳(10分钟有效期)+ if (timestamp) {+ const now = Date.now();+ const maxAge = 10 * 60 * 1000; // 10分钟+ if (now - parseInt(timestamp) > maxAge) {+ console.warn('代理请求鉴权失败:时间戳过期');+ return false;+ }+ }++ return true;+}+app.get('/proxy/:encodedUrl', async (req, res) => {try {+ // 验证鉴权+ if (!validateProxyAuth(req)) {+ return res.status(401).json({+ success: false,+ error: '代理访问未授权:请检查密码配置或鉴权参数'+ });+ }+const encodedUrl = req.params.encodedUrl;const targetUrl = decodeURIComponent(encodedUrl);