Skip to content

一分钟搭建影视站,支持Docker等部署方式

fix(server): 取消支持cloudflare、vercel

bestZweic80071fd4886
diff --git a/api/proxy/[...path].mjs b/api/proxy/[...path].mjs
deleted file mode 100644
index 37664c9..0000000
--- a/api/proxy/[...path].mjs
+++ /dev/null
@@ -1,546 +0,0 @@
-// /api/proxy/[...path].mjs - Vercel Serverless Function (ES Module)
-
-import fetch from 'node-fetch';
-import { URL } from 'url'; // 使用 Node.js 内置 URL 处理
-import crypto from 'crypto'; // 导入 crypto 模块用于密码哈希
-import dns from 'node:dns';
-
-// --- 配置 (从环境变量读取) ---
-const DEBUG_ENABLED = process.env.DEBUG === 'true';
-const CACHE_TTL = parseInt(process.env.CACHE_TTL || '86400', 10); // 默认 24 小时
-const MAX_RECURSION = parseInt(process.env.MAX_RECURSION || '5', 10); // 默认 5 层
-
-// --- User Agent 处理 ---
-// 默认 User Agent 列表
-let USER_AGENTS = [
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15'
-];
-// 尝试从环境变量读取并解析 USER_AGENTS_JSON
-try {
- const agentsJsonString = process.env.USER_AGENTS_JSON;
- if (agentsJsonString) {
- const parsedAgents = JSON.parse(agentsJsonString);
- // 检查解析结果是否为非空数组
- if (Array.isArray(parsedAgents) && parsedAgents.length > 0) {
- USER_AGENTS = parsedAgents; // 使用环境变量中的数组
- console.log(`[代理日志] 已从环境变量加载 ${USER_AGENTS.length} 个 User Agent。`);
- } else {
- console.warn("[代理日志] 环境变量 USER_AGENTS_JSON 不是有效的非空数组,使用默认值。");
- }
- } else {
- console.log("[代理日志] 未设置环境变量 USER_AGENTS_JSON,使用默认 User Agent。");
- }
-} catch (e) {
- // 如果 JSON 解析失败,记录错误并使用默认值
- console.error(`[代理日志] 解析环境变量 USER_AGENTS_JSON 出错: ${e.message}。使用默认 User Agent。`);
-}
-
-// 广告过滤在代理中禁用,由播放器处理
-const FILTER_DISCONTINUITY = false;
-
-
-// --- 辅助函数 ---
-
-function logDebug(message) {
- if (DEBUG_ENABLED) {
- console.log(`[代理日志] ${message}`);
- }
-}
-
-/**
- * 从代理请求路径中提取编码后的目标 URL。
- * @param {string} encodedPath - URL 编码后的路径部分 (例如 "https%3A%2F%2F...")
- * @returns {string|null} 解码后的目标 URL,如果无效则返回 null。
- */
-function getTargetUrlFromPath(encodedPath) {
- if (!encodedPath) {
- logDebug("getTargetUrlFromPath 收到空路径。");
- return null;
- }
- try {
- const decodedUrl = decodeURIComponent(encodedPath);
- // 基础检查,看是否像一个 HTTP/HTTPS URL
- if (decodedUrl.match(/^https?:\/\/.+/i)) {
- return decodedUrl;
- } else {
- logDebug(`无效的解码 URL 格式: ${decodedUrl}`);
- // 备选检查:原始路径是否未编码但看起来像 URL?
- if (encodedPath.match(/^https?:\/\/.+/i)) {
- logDebug(`警告: 路径未编码但看起来像 URL: ${encodedPath}`);
- return encodedPath;
- }
- return null;
- }
- } catch (e) {
- // 捕获解码错误 (例如格式错误的 URI)
- logDebug(`解码目标 URL 出错: ${encodedPath} - ${e.message}`);
- return null;
- }
-}
-
-function getBaseUrl(urlStr) {
- if (!urlStr) return '';
- try {
- const parsedUrl = new URL(urlStr);
- // 处理根目录或只有文件名的情况
- const pathSegments = parsedUrl.pathname.split('/').filter(Boolean); // 移除空字符串
- if (pathSegments.length <= 1) {
- return `${parsedUrl.origin}/`;
- }
- pathSegments.pop(); // 移除最后一段
- return `${parsedUrl.origin}/${pathSegments.join('/')}/`;
- } catch (e) {
- logDebug(`获取 BaseUrl 失败: "${urlStr}": ${e.message}`);
- // 备用方法:查找最后一个斜杠
- const lastSlashIndex = urlStr.lastIndexOf('/');
- if (lastSlashIndex > urlStr.indexOf('://') + 2) { // 确保不是协议部分的斜杠
- return urlStr.substring(0, lastSlashIndex + 1);
- }
- return urlStr + '/'; // 如果没有路径,添加斜杠
- }
-}
-
-function resolveUrl(baseUrl, relativeUrl) {
- if (!relativeUrl) return ''; // 处理空的 relativeUrl
- if (relativeUrl.match(/^https?:\/\/.+/i)) {
- return relativeUrl; // 已经是绝对 URL
- }
- if (!baseUrl) return relativeUrl; // 没有基础 URL 无法解析
-
- try {
- // 使用 Node.js 的 URL 构造函数处理相对路径
- return new URL(relativeUrl, baseUrl).toString();
- } catch (e) {
- logDebug(`URL 解析失败: base="${baseUrl}", relative="${relativeUrl}". 错误: ${e.message}`);
- // 简单的备用逻辑
- if (relativeUrl.startsWith('/')) {
- try {
- const baseOrigin = new URL(baseUrl).origin;
- return `${baseOrigin}${relativeUrl}`;
- } catch { return relativeUrl; } // 如果 baseUrl 也无效,返回原始相对路径
- } else {
- // 假设相对于包含基础 URL 资源的目录
- return `${baseUrl.substring(0, baseUrl.lastIndexOf('/') + 1)}${relativeUrl}`;
- }
- }
-}
-
-// --- SSRF 防护 ---
-function isPrivateIP(ip) {
- if (/^(127\.|0\.0\.0\.0$|::1$|fe80:|fc|fd)/i.test(ip)) return true;
- if (ip.startsWith('10.')) return true;
- if (ip.startsWith('192.168.')) return true;
- if (/^172\.(1[6-9]|2\d|3[01])\./.test(ip)) return true;
- if (ip.startsWith('169.254.')) return true; // 链路本地(含云元数据 169.254.169.254)
- if (ip.startsWith('100.64.')) return true; // CGNAT
- if (ip.startsWith('192.0.0.')) return true; // 协议分配块
- return false;
-}
-
-function isBlockedHostname(host) {
- if (host === 'localhost' || host.endsWith('.internal') || host.startsWith('metadata') || host === '169.254.169.254') return true;
- return false;
-}
-
-async function isBlockedByDNS(urlString) {
- try {
- const { hostname } = new URL(urlString);
- if (/^\d{1,3}(\.\d{1,3}){3}$/.test(hostname) || hostname.includes(':')) {
- return isPrivateIP(hostname);
- }
- if (isBlockedHostname(hostname)) return true;
- const result = await dns.lookup(hostname, { all: true });
- return result.some(r => isPrivateIP(r.address));
- } catch {
- return false;
- }
-}
-
-// ** 已修正:确保生成 /proxy/ 前缀的链接 **
-function rewriteUrlToProxy(targetUrl) {
- if (!targetUrl || typeof targetUrl !== 'string') return '';
- // 返回与 vercel.json 的 "source" 和前端 PROXY_URL 一致的路径
- return `/proxy/${encodeURIComponent(targetUrl)}`;
-}
-
-function getRandomUserAgent() {
- return USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)];
-}
-
-async function fetchContentWithType(targetUrl, requestHeaders) {
- // 准备请求头
- // 针对豆瓣图片:强制豆瓣 Referer 以绕过 418 防盗链(对齐 LunaTV 的图片代理做法)
- let referer = requestHeaders['referer'] || new URL(targetUrl).origin;
- try {
- if (/doubanio\.com$/i.test(new URL(targetUrl).hostname)) {
- referer = 'https://movie.douban.com/';
- }
- } catch (e) { /* 忽略非法 URL */ }
- const headers = {
- 'User-Agent': getRandomUserAgent(),
- 'Accept': requestHeaders['accept'] || '*/*', // 传递原始 Accept 头(如果有)
- 'Accept-Language': requestHeaders['accept-language'] || 'zh-CN,zh;q=0.9,en;q=0.8',
- 'Referer': referer,
- };
- // 清理空值的头
- Object.keys(headers).forEach(key => headers[key] === undefined || headers[key] === null || headers[key] === '' ? delete headers[key] : {});
-
- logDebug(`准备请求目标: ${targetUrl},请求头: ${JSON.stringify(headers)}`);
-
- try {
- // 发起 fetch 请求
- const response = await fetch(targetUrl, { headers, redirect: 'follow' });
-
- // 检查响应是否成功
- if (!response.ok) {
- const errorBody = await response.text().catch(() => ''); // 尝试获取错误响应体
- logDebug(`请求失败: ${response.status} ${response.statusText} - ${targetUrl}`);
- // 创建一个包含状态码的错误对象
- const err = new Error(`HTTP 错误 ${response.status}: ${response.statusText}. URL: ${targetUrl}. Body: ${errorBody.substring(0, 200)}`);
- err.status = response.status; // 将状态码附加到错误对象
- throw err; // 抛出错误
- }
-
- // 读取响应内容
- const content = await response.text();
- const contentType = response.headers.get('content-type') || '';
- logDebug(`请求成功: ${targetUrl}, Content-Type: ${contentType}, 内容长度: ${content.length}`);
- // 返回结果
- return { content, contentType, responseHeaders: response.headers };
-
- } catch (error) {
- // 捕获 fetch 本身的错误(网络、超时等)或上面抛出的 HTTP 错误
- logDebug(`请求异常 ${targetUrl}: ${error.message}`);
- // 重新抛出,确保包含原始错误信息
- throw new Error(`请求目标 URL 失败 ${targetUrl}: ${error.message}`);
- }
-}
-
-function isM3u8Content(content, contentType) {
- if (contentType && (contentType.includes('application/vnd.apple.mpegurl') || contentType.includes('application/x-mpegurl') || contentType.includes('audio/mpegurl'))) {
- return true;
- }
- return content && typeof content === 'string' && content.trim().startsWith('#EXTM3U');
-}
-
-function processKeyLine(line, baseUrl) {
- return line.replace(/URI="([^"]+)"/, (match, uri) => {
- const absoluteUri = resolveUrl(baseUrl, uri);
- logDebug(`处理 KEY URI: 原始='${uri}', 绝对='${absoluteUri}'`);
- return `URI="${rewriteUrlToProxy(absoluteUri)}"`;
- });
-}
-
-function processMapLine(line, baseUrl) {
- return line.replace(/URI="([^"]+)"/, (match, uri) => {
- const absoluteUri = resolveUrl(baseUrl, uri);
- logDebug(`处理 MAP URI: 原始='${uri}', 绝对='${absoluteUri}'`);
- return `URI="${rewriteUrlToProxy(absoluteUri)}"`;
- });
- }
-
-function processMediaPlaylist(url, content) {
- const baseUrl = getBaseUrl(url);
- if (!baseUrl) {
- logDebug(`无法确定媒体列表的 Base URL: ${url},相对路径可能无法处理。`);
- }
- const lines = content.split('\n');
- const output = [];
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i].trim();
- // 保留最后一个空行
- if (!line && i === lines.length - 1) { output.push(line); continue; }
- if (!line) continue; // 跳过中间空行
- // 广告过滤已禁用
- if (line.startsWith('#EXT-X-KEY')) { output.push(processKeyLine(line, baseUrl)); continue; }
- if (line.startsWith('#EXT-X-MAP')) { output.push(processMapLine(line, baseUrl)); continue; }
- if (line.startsWith('#EXTINF')) { output.push(line); continue; }
- // 处理 URL 行
- if (!line.startsWith('#')) {
- const absoluteUrl = resolveUrl(baseUrl, line);
- logDebug(`重写媒体片段: 原始='${line}', 解析后='${absoluteUrl}'`);
- output.push(rewriteUrlToProxy(absoluteUrl)); continue;
- }
- // 保留其他 M3U8 标签
- output.push(line);
- }
- return output.join('\n');
-}
-
-async function processM3u8Content(targetUrl, content, recursionDepth = 0) {
- // 判断是主列表还是媒体列表
- if (content.includes('#EXT-X-STREAM-INF') || content.includes('#EXT-X-MEDIA:')) {
- logDebug(`检测到主播放列表: ${targetUrl} (深度: ${recursionDepth})`);
- return await processMasterPlaylist(targetUrl, content, recursionDepth);
- }
- logDebug(`检测到媒体播放列表: ${targetUrl} (深度: ${recursionDepth})`);
- return processMediaPlaylist(targetUrl, content);
-}
-
-async function processMasterPlaylist(url, content, recursionDepth) {
- // 检查递归深度
- if (recursionDepth > MAX_RECURSION) {
- throw new Error(`处理主播放列表时,递归深度超过最大限制 (${MAX_RECURSION}): ${url}`);
- }
- const baseUrl = getBaseUrl(url);
- const lines = content.split('\n');
- let highestBandwidth = -1;
- let bestVariantUrl = '';
-
- // 查找最高带宽的流
- for (let i = 0; i < lines.length; i++) {
- if (lines[i].startsWith('#EXT-X-STREAM-INF')) {
- const bandwidthMatch = lines[i].match(/BANDWIDTH=(\d+)/);
- const currentBandwidth = bandwidthMatch ? parseInt(bandwidthMatch[1], 10) : 0;
- let variantUriLine = '';
- // 找到下一行的 URI
- for (let j = i + 1; j < lines.length; j++) {
- const line = lines[j].trim();
- if (line && !line.startsWith('#')) { variantUriLine = line; i = j; break; }
- }
- if (variantUriLine && currentBandwidth >= highestBandwidth) {
- highestBandwidth = currentBandwidth;
- bestVariantUrl = resolveUrl(baseUrl, variantUriLine);
- }
- }
- }
- // 如果没有找到带宽信息,尝试查找第一个 .m3u8 链接
- if (!bestVariantUrl) {
- logDebug(`主播放列表中未找到 BANDWIDTH 信息,尝试查找第一个 URI: ${url}`);
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i].trim();
- // 更可靠地匹配 .m3u8 链接
- if (line && !line.startsWith('#') && line.match(/\.m3u8($|\?.*)/i)) {
- bestVariantUrl = resolveUrl(baseUrl, line);
- logDebug(`备选方案: 找到第一个子播放列表 URI: ${bestVariantUrl}`);
- break;
- }
- }
- }
- // 如果仍然没有找到子列表 URL
- if (!bestVariantUrl) {
- logDebug(`在主播放列表 ${url} 中未找到有效的子列表 URI,将其作为媒体列表处理。`);
- return processMediaPlaylist(url, content);
- }
-
- logDebug(`选择的子播放列表 (带宽: ${highestBandwidth}): ${bestVariantUrl}`);
- // 请求选定的子播放列表内容 (注意:这里传递 {} 作为请求头,不传递客户端的原始请求头)
- const { content: variantContent, contentType: variantContentType } = await fetchContentWithType(bestVariantUrl, {});
-
- // 检查获取的内容是否是 M3U8
- if (!isM3u8Content(variantContent, variantContentType)) {
- logDebug(`获取的子播放列表 ${bestVariantUrl} 不是 M3U8 (类型: ${variantContentType}),将其作为媒体列表处理。`);
- return processMediaPlaylist(bestVariantUrl, variantContent);
- }
-
- // 递归处理获取到的子 M3U8 内容
- return await processM3u8Content(bestVariantUrl, variantContent, recursionDepth + 1);
-}
-
-/**
- * 验证代理请求的鉴权(优先 token,兼容旧静态哈希)
- */
-async function validateAuth(req) {
- const authHash = req.query.auth;
- const token = req.query.token;
- const t = req.query.t;
-
- const serverPassword = process.env.PASSWORD;
- if (!serverPassword) {
- console.error('服务器未设置 PASSWORD 环境变量,代理访问被拒绝');
- return false;
- }
-
- // 服务端签名密钥:优先 PROXY_SECRET,否则由密码派生(客户端仅持有 sha256(password),无法反推)
- const secret = process.env.PROXY_SECRET ||
- crypto.createHash('sha256').update(serverPassword + ':libretv::proxy-salt').digest('hex');
-
- // 优先校验服务端签发的短时效 token
- if (token && t) {
- const expected = crypto.createHash('sha256').update(secret + ':' + t).digest('hex');
- const now = Date.now();
- if (token === expected && Math.abs(now - parseInt(t, 10)) <= 10 * 60 * 1000) {
- return true;
- }
- }
-
- // 兼容旧模式:使用页面中的静态哈希(安全性较弱,建议配置 PROXY_SECRET)
- const serverPasswordHash = crypto.createHash('sha256').update(serverPassword).digest('hex');
- if (authHash && authHash === serverPasswordHash) {
- if (t) {
- const now = Date.now();
- if (now - parseInt(t, 10) > 10 * 60 * 1000) return false;
- }
- return true;
- }
-
- return false;
-}
-
-// --- Vercel Handler 函数 ---
-export default async function handler(req, res) {
- // --- 记录请求开始 ---
- console.info('--- Vercel 代理请求开始 ---');
- console.info('时间:', new Date().toISOString());
- console.info('方法:', req.method);
- console.info('URL:', req.url); // 原始请求 URL (例如 /proxy/...)
- console.info('查询参数:', JSON.stringify(req.query)); // Vercel 解析的查询参数
-
- // --- 提前设置 CORS 头 ---
- res.setHeader('Access-Control-Allow-Origin', '*');
- res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
- res.setHeader('Access-Control-Allow-Headers', '*'); // 允许所有请求头
-
- // --- 处理 OPTIONS 预检请求 ---
- if (req.method === 'OPTIONS') {
- console.info("处理 OPTIONS 预检请求");
- res.status(204).setHeader('Access-Control-Max-Age', '86400').end(); // 缓存预检结果 24 小时
- return;
- }
-
- let targetUrl = null; // 初始化目标 URL
-
- 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"]; // 使用正确的键名
- let encodedUrlPath = '';
-
- if (pathData) {
- if (Array.isArray(pathData)) {
- encodedUrlPath = pathData.join('/'); // 重新组合
- console.info(`从 req.query["...path"] (数组) 组合的编码路径: ${encodedUrlPath}`);
- } else if (typeof pathData === 'string') {
- encodedUrlPath = pathData; // 也处理 Vercel 可能只返回字符串的情况
- console.info(`从 req.query["...path"] (字符串) 获取的编码路径: ${encodedUrlPath}`);
- } else {
- console.warn(`[代理警告] req.query["...path"] 类型未知: ${typeof pathData}`);
- }
- } else {
- console.warn(`[代理警告] req.query["...path"] 为空或未定义。`);
- // 备选:尝试从 req.url 提取(如果需要)
- if (req.url && req.url.startsWith('/proxy/')) {
- encodedUrlPath = req.url.substring('/proxy/'.length);
- console.info(`使用备选方法从 req.url 提取的编码路径: ${encodedUrlPath}`);
- }
- }
-
- // 如果仍然为空,则无法继续
- if (!encodedUrlPath) {
- throw new Error("无法从请求中确定编码后的目标路径。");
- }
-
- // 解析目标 URL
- targetUrl = getTargetUrlFromPath(encodedUrlPath);
- console.info(`解析出的目标 URL: ${targetUrl || 'null'}`); // 记录解析结果
-
- // 检查目标 URL 是否有效
- if (!targetUrl) {
- // 抛出包含更多上下文的错误
- throw new Error(`无效的代理请求路径。无法从组合路径 "${encodedUrlPath}" 中提取有效的目标 URL。`);
- }
-
- console.info(`开始处理目标 URL 的代理请求: ${targetUrl}`);
-
- // SSRF 深度防护:拒绝内网/保留地址
- if (await isBlockedByDNS(targetUrl)) {
- res.status(403).json({ success: false, error: '不允许访问私有/保留网络地址' });
- return;
- }
-
- // --- 获取并处理目标内容 ---
- const { content, contentType, responseHeaders } = await fetchContentWithType(targetUrl, req.headers);
-
- // --- 如果是 M3U8,处理并返回 ---
- if (isM3u8Content(content, contentType)) {
- console.info(`正在处理 M3U8 内容: ${targetUrl}`);
- const processedM3u8 = await processM3u8Content(targetUrl, content);
-
- console.info(`成功处理 M3U8: ${targetUrl}`);
- // 发送处理后的 M3U8 响应
- res.status(200)
- .setHeader('Content-Type', 'application/vnd.apple.mpegurl;charset=utf-8')
- .setHeader('Cache-Control', `public, max-age=${CACHE_TTL}`)
- // 移除可能导致问题的原始响应头
- .removeHeader('content-encoding') // 很重要!node-fetch 已解压
- .removeHeader('content-length') // 长度已改变
- .send(processedM3u8); // 发送 M3U8 文本
-
- } else {
- // --- 如果不是 M3U8,直接返回原始内容 ---
- console.info(`直接返回非 M3U8 内容: ${targetUrl}, 类型: ${contentType}`);
-
- // 设置原始响应头,但排除有问题的头和 CORS 头(已设置)
- responseHeaders.forEach((value, key) => {
- const lowerKey = key.toLowerCase();
- if (!lowerKey.startsWith('access-control-') &&
- lowerKey !== 'content-encoding' && // 很重要!
- lowerKey !== 'content-length') { // 很重要!
- res.setHeader(key, value); // 设置其他原始头
- }
- });
- // 设置我们自己的缓存策略
- res.setHeader('Cache-Control', `public, max-age=${CACHE_TTL}`);
-
- // 发送原始(已解压)内容
- res.status(200).send(content);
- }
-
- // ---- 结束主处理逻辑的 try 块 ----
- } catch (error) { // ---- 捕获处理过程中的任何错误 ----
- // **检查这个错误是否是 "Assignment to constant variable"**
- console.error(`[代理错误处理 V3] 捕获错误!目标: ${targetUrl || '解析失败'} | 错误类型: ${error.constructor.name} | 错误消息: ${error.message}`);
- console.error(`[代理错误堆栈 V3] ${error.stack}`); // 记录完整的错误堆栈信息
-
- // 特别标记 "Assignment to constant variable" 错误
- if (error instanceof TypeError && error.message.includes("Assignment to constant variable")) {
- console.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
- console.error("捕获到 'Assignment to constant variable' 错误!");
- console.error("请再次检查函数代码及所有辅助函数中,是否有 const 声明的变量被重新赋值。");
- console.error("错误堆栈指向:", error.stack);
- console.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
- }
-
- // 尝试从错误对象获取状态码,否则默认为 500
- const statusCode = error.status || 500;
-
- // 确保在发送错误响应前没有发送过响应头
- if (!res.headersSent) {
- res.setHeader('Content-Type', 'application/json');
- // CORS 头应该已经在前面设置好了
- res.status(statusCode).json({
- success: false,
- error: `代理处理错误: ${error.message}`, // 返回错误消息给前端
- targetUrl: targetUrl // 包含目标 URL 以便调试
- });
- } else {
- // 如果响应头已发送,无法再发送 JSON 错误
- console.error("[代理错误处理 V3] 响应头已发送,无法发送 JSON 错误响应。");
- // 尝试结束响应
- if (!res.writableEnded) {
- res.end();
- }
- }
- } finally {
- // 记录请求处理结束
- console.info('--- Vercel 代理请求结束 ---');
- }
-}
-
-// --- [确保所有辅助函数定义都在这里] ---
-// getTargetUrlFromPath, getBaseUrl, resolveUrl, rewriteUrlToProxy, getRandomUserAgent,
-// fetchContentWithType, isM3u8Content, processKeyLine, processMapLine,
-// processMediaPlaylist, processM3u8Content, processMasterPlaylist
diff --git a/functions/_middleware.js b/functions/_middleware.js
deleted file mode 100644
index 4e213e9..0000000
--- a/functions/_middleware.js
+++ /dev/null
@@ -1,34 +0,0 @@
-import { sha256 } from '../js/sha256.js';
-
-export async function onRequest(context) {
- const { request, env, next } = context;
- const response = await next();
- const contentType = response.headers.get("content-type") || "";
-
- if (contentType.includes("text/html")) {
- let html = await response.text();
-
- // 注入访问密码哈希(sha256),与 server.mjs 行为一致
- const password = env.PASSWORD || "";
- const passwordHash = password ? await sha256(password) : "";
- html = html.replace('window.__ENV__.PASSWORD = "{{PASSWORD}}";',
- `window.__ENV__.PASSWORD = "${passwordHash}";`);
-
- // 注入代理鉴权模式:Cloudflare Pages 函数不提供 /api/proxy-token 签发端点,
- // 固定为兼容(静态哈希)模式;前端据此回退到 auth=sha256(password)
- html = html.replace('window.__ENV__.PROXY_TOKEN_MODE = "{{PROXY_TOKEN_MODE}}";',
- `window.__ENV__.PROXY_TOKEN_MODE = "";`);
-
- // 复制响应头,并移除会因内容变化而过期的 content-length
- const headers = new Headers(response.headers);
- headers.delete("content-length");
-
- return new Response(html, {
- headers,
- status: response.status,
- statusText: response.statusText,
- });
- }
-
- return response;
-}
\ No newline at end of file
diff --git a/functions/proxy/[[path]].js b/functions/proxy/[[path]].js
deleted file mode 100644
index 405eb2e..0000000
--- a/functions/proxy/[[path]].js
+++ /dev/null
@@ -1,609 +0,0 @@
-// functions/proxy/[[path]].js
-
-// --- 配置 (现在从 Cloudflare 环境变量读取) ---
-// 在 Cloudflare Pages 设置 -> 函数 -> 环境变量绑定 中设置以下变量:
-// CACHE_TTL (例如 86400)
-// MAX_RECURSION (例如 5)
-// FILTER_DISCONTINUITY (不再需要,设为 false 或移除)
-// USER_AGENTS_JSON (例如 ["UA1", "UA2"]) - JSON 字符串数组
-// DEBUG (例如 false 或 true)
-// PASSWORD (例如 "your_password") - 鉴权密码
-// --- 配置结束 ---
-
-// --- 常量 (之前在 config.js 中,现在移到这里,因为它们与代理逻辑相关) ---
-const MEDIA_FILE_EXTENSIONS = [
- '.mp4', '.webm', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.f4v', '.m4v', '.3gp', '.3g2', '.ts', '.mts', '.m2ts',
- '.mp3', '.wav', '.ogg', '.aac', '.m4a', '.flac', '.wma', '.alac', '.aiff', '.opus',
- '.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.tiff', '.svg', '.avif', '.heic'
-];
-const MEDIA_CONTENT_TYPES = ['video/', 'audio/', 'image/'];
-// --- 常量结束 ---
-
-// --- SSRF 防护 ---
-function isPrivateIP(ip) {
- if (/^(127\.|0\.0\.0\.0$|::1$|fe80:|fc|fd)/i.test(ip)) return true;
- if (ip.startsWith('10.')) return true;
- if (ip.startsWith('192.168.')) return true;
- if (/^172\.(1[6-9]|2\d|3[01])\./.test(ip)) return true;
- if (ip.startsWith('169.254.')) return true; // 链路本地(含云元数据 169.254.169.254)
- if (ip.startsWith('100.64.')) return true; // CGNAT
- if (ip.startsWith('192.0.0.')) return true; // 协议分配块
- return false;
-}
-
-function isBlockedTarget(targetUrl) {
- try {
- const { hostname } = new URL(targetUrl);
- if (/^\d{1,3}(\.\d{1,3}){3}$/.test(hostname) || hostname.includes(':')) {
- return isPrivateIP(hostname);
- }
- if (hostname === 'localhost' || hostname.endsWith('.internal') || hostname.startsWith('metadata') || hostname === '169.254.169.254') return true;
- } catch { return false; }
- return false;
-}
-
-async function sha256Hex(message) {
- const data = new TextEncoder().encode(message);
- const buf = await crypto.subtle.digest('SHA-256', data);
- return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, '0')).join('');
-}
-
-
-/**
- * 主要的 Pages Function 处理函数
- * 拦截发往 /proxy/* 的请求
- */
-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 小时
- const MAX_RECURSION = parseInt(env.MAX_RECURSION || '5'); // 默认 5 层
- // 广告过滤已移至播放器处理,代理不再执行
- let USER_AGENTS = [ // 提供一个基础的默认值
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
- ];
- try {
- // 尝试从环境变量解析 USER_AGENTS_JSON
- const agentsJson = env.USER_AGENTS_JSON;
- if (agentsJson) {
- const parsedAgents = JSON.parse(agentsJson);
- if (Array.isArray(parsedAgents) && parsedAgents.length > 0) {
- USER_AGENTS = parsedAgents;
- } else {
- logDebug("环境变量 USER_AGENTS_JSON 格式无效或为空,使用默认值");
- }
- }
- } catch (e) {
- logDebug(`解析环境变量 USER_AGENTS_JSON 失败: ${e.message},使用默认值`);
- }
- // --- 配置读取结束 ---
-
-
- // --- 辅助函数 ---
-
- // 验证代理请求的鉴权(优先 token,兼容旧静态哈希)
- async function validateAuth(request, env) {
- const url = new URL(request.url);
- const authHash = url.searchParams.get('auth');
- const token = url.searchParams.get('token');
- const t = url.searchParams.get('t');
-
- const serverPassword = env.PASSWORD;
- if (!serverPassword) {
- console.error('服务器未设置 PASSWORD 环境变量,代理访问被拒绝');
- return false;
- }
-
- // 服务端签名密钥:优先 PROXY_SECRET,否则由密码派生
- const secret = env.PROXY_SECRET || await sha256Hex(serverPassword + ':libretv::proxy-salt');
-
- // 优先校验服务端签发的短时效 token
- if (token && t) {
- const expected = await sha256Hex(secret + ':' + t);
- const now = Date.now();
- if (token === expected && Math.abs(now - parseInt(t, 10)) <= 10 * 60 * 1000) {
- return true;
- }
- }
-
- // 兼容旧模式:静态哈希
- const serverPasswordHash = await sha256Hex(serverPassword);
- if (authHash && authHash === serverPasswordHash) {
- if (t) {
- const now = Date.now();
- if (now - parseInt(t, 10) > 10 * 60 * 1000) return false;
- }
- return true;
- }
-
- return false;
- }
-
- // 输出调试日志 (需要设置 DEBUG: true 环境变量)
- function logDebug(message) {
- if (DEBUG_ENABLED) {
- console.log(`[Proxy Func] ${message}`);
- }
- }
-
- // 从请求路径中提取目标 URL
- function getTargetUrlFromPath(pathname) {
- // 路径格式: /proxy/经过编码的URL
- // 例如: /proxy/https%3A%2F%2Fexample.com%2Fplaylist.m3u8
- const encodedUrl = pathname.replace(/^\/proxy\//, '');
- if (!encodedUrl) return null;
- try {
- // 解码
- let decodedUrl = decodeURIComponent(encodedUrl);
-
- // 简单检查解码后是否是有效的 http/https URL
- if (!decodedUrl.match(/^https?:\/\//i)) {
- // 也许原始路径就没有编码?如果看起来像URL就直接用
- if (encodedUrl.match(/^https?:\/\//i)) {
- decodedUrl = encodedUrl;
- logDebug(`Warning: Path was not encoded but looks like URL: ${decodedUrl}`);
- } else {
- logDebug(`无效的目标URL格式 (解码后): ${decodedUrl}`);
- return null;
- }
- }
- return decodedUrl;
-
- } catch (e) {
- logDebug(`解码目标URL时出错: ${encodedUrl} - ${e.message}`);
- return null;
- }
- }
-
- // 创建标准化的响应
- function createResponse(body, status = 200, headers = {}) {
- const responseHeaders = new Headers(headers);
- // 关键:添加 CORS 跨域头,允许前端 JS 访问代理后的响应
- responseHeaders.set("Access-Control-Allow-Origin", "*"); // 允许任何来源访问
- responseHeaders.set("Access-Control-Allow-Methods", "GET, HEAD, POST, OPTIONS"); // 允许的方法
- responseHeaders.set("Access-Control-Allow-Headers", "*"); // 允许所有请求头
-
- // 处理 CORS 预检请求 (OPTIONS) - 放在这里确保所有响应都处理
- if (request.method === "OPTIONS") {
- // 使用下面的 onOptions 函数可以更规范,但在这里处理也可以
- return new Response(null, {
- status: 204, // No Content
- headers: responseHeaders // 包含上面设置的 CORS 头
- });
- }
-
- return new Response(body, { status, headers: responseHeaders });
- }
-
- // 创建 M3U8 类型的响应
- function createM3u8Response(content) {
- return createResponse(content, 200, {
- "Content-Type": "application/vnd.apple.mpegurl", // M3U8 的标准 MIME 类型
- "Cache-Control": `public, max-age=${CACHE_TTL}` // 允许浏览器和CDN缓存
- });
- }
-
- // 获取随机 User-Agent
- function getRandomUserAgent() {
- return USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)];
- }
-
- // 获取 URL 的基础路径 (用于解析相对路径)
- function getBaseUrl(urlStr) {
- try {
- const parsedUrl = new URL(urlStr);
- // 如果路径是根目录,或者没有斜杠,直接返回 origin + /
- if (!parsedUrl.pathname || parsedUrl.pathname === '/') {
- return `${parsedUrl.origin}/`;
- }
- const pathParts = parsedUrl.pathname.split('/');
- pathParts.pop(); // 移除文件名或最后一个路径段
- return `${parsedUrl.origin}${pathParts.join('/')}/`;
- } catch (e) {
- logDebug(`获取 BaseUrl 时出错: ${urlStr} - ${e.message}`);
- // 备用方法:找到最后一个斜杠
- const lastSlashIndex = urlStr.lastIndexOf('/');
- // 确保不是协议部分的斜杠 (http://)
- return lastSlashIndex > urlStr.indexOf('://') + 2 ? urlStr.substring(0, lastSlashIndex + 1) : urlStr + '/';
- }
- }
-
-
- // 将相对 URL 转换为绝对 URL
- function resolveUrl(baseUrl, relativeUrl) {
- // 如果已经是绝对 URL,直接返回
- if (relativeUrl.match(/^https?:\/\//i)) {
- return relativeUrl;
- }
- try {
- // 使用 URL 对象来处理相对路径
- return new URL(relativeUrl, baseUrl).toString();
- } catch (e) {
- logDebug(`解析 URL 失败: baseUrl=${baseUrl}, relativeUrl=${relativeUrl}, error=${e.message}`);
- // 简单的备用方法
- if (relativeUrl.startsWith('/')) {
- // 处理根路径相对 URL
- const urlObj = new URL(baseUrl);
- return `${urlObj.origin}${relativeUrl}`;
- }
- // 处理同级目录相对 URL
- return `${baseUrl.replace(/\/[^/]*$/, '/')}${relativeUrl}`; // 确保baseUrl以 / 结尾
- }
- }
-
- // 将目标 URL 重写为内部代理路径 (/proxy/...)
- function rewriteUrlToProxy(targetUrl) {
- // 确保目标URL被正确编码,以便作为路径的一部分
- return `/proxy/${encodeURIComponent(targetUrl)}`;
- }
-
- // 获取远程内容及其类型
- async function fetchContentWithType(targetUrl) {
- const headers = new Headers({
- 'User-Agent': getRandomUserAgent(),
- 'Accept': '*/*',
- // 尝试传递一些原始请求的头信息
- 'Accept-Language': request.headers.get('Accept-Language') || 'zh-CN,zh;q=0.9,en;q=0.8',
- // 尝试设置 Referer 为目标网站的域名,或者传递原始 Referer
- 'Referer': request.headers.get('Referer') || new URL(targetUrl).origin
- });
-
- try {
- // 直接请求目标 URL
- logDebug(`开始直接请求: ${targetUrl}`);
- // Cloudflare Functions 的 fetch 默认支持重定向
- const response = await fetch(targetUrl, { headers, redirect: 'follow' });
-
- if (!response.ok) {
- const errorBody = await response.text().catch(() => '');
- logDebug(`请求失败: ${response.status} ${response.statusText} - ${targetUrl}`);
- throw new Error(`HTTP error ${response.status}: ${response.statusText}. URL: ${targetUrl}. Body: ${errorBody.substring(0, 150)}`);
- }
-
- // 读取响应内容为文本
- const content = await response.text();
- const contentType = response.headers.get('Content-Type') || '';
- logDebug(`请求成功: ${targetUrl}, Content-Type: ${contentType}, 内容长度: ${content.length}`);
- return { content, contentType, responseHeaders: response.headers }; // 同时返回原始响应头
-
- } catch (error) {
- logDebug(`请求彻底失败: ${targetUrl}: ${error.message}`);
- // 抛出更详细的错误
- throw new Error(`请求目标URL失败 ${targetUrl}: ${error.message}`);
- }
- }
-
- // 判断是否是 M3U8 内容
- function isM3u8Content(content, contentType) {
- // 检查 Content-Type
- if (contentType && (contentType.includes('application/vnd.apple.mpegurl') || contentType.includes('application/x-mpegurl') || contentType.includes('audio/mpegurl'))) {
- return true;
- }
- // 检查内容本身是否以 #EXTM3U 开头
- return content && typeof content === 'string' && content.trim().startsWith('#EXTM3U');
- }
-
- // 判断是否是媒体文件 (根据扩展名和 Content-Type) - 这部分在此代理中似乎未使用,但保留
- function isMediaFile(url, contentType) {
- if (contentType) {
- for (const mediaType of MEDIA_CONTENT_TYPES) {
- if (contentType.toLowerCase().startsWith(mediaType)) {
- return true;
- }
- }
- }
- const urlLower = url.toLowerCase();
- for (const ext of MEDIA_FILE_EXTENSIONS) {
- if (urlLower.endsWith(ext) || urlLower.includes(`${ext}?`)) {
- return true;
- }
- }
- return false;
- }
-
- // 处理 M3U8 中的 #EXT-X-KEY 行 (加密密钥)
- function processKeyLine(line, baseUrl) {
- return line.replace(/URI="([^"]+)"/, (match, uri) => {
- const absoluteUri = resolveUrl(baseUrl, uri);
- logDebug(`处理 KEY URI: 原始='${uri}', 绝对='${absoluteUri}'`);
- return `URI="${rewriteUrlToProxy(absoluteUri)}"`; // 重写为代理路径
- });
- }
-
- // 处理 M3U8 中的 #EXT-X-MAP 行 (初始化片段)
- function processMapLine(line, baseUrl) {
- return line.replace(/URI="([^"]+)"/, (match, uri) => {
- const absoluteUri = resolveUrl(baseUrl, uri);
- logDebug(`处理 MAP URI: 原始='${uri}', 绝对='${absoluteUri}'`);
- return `URI="${rewriteUrlToProxy(absoluteUri)}"`; // 重写为代理路径
- });
- }
-
- // 处理媒体 M3U8 播放列表 (包含视频/音频片段)
- function processMediaPlaylist(url, content) {
- const baseUrl = getBaseUrl(url);
- const lines = content.split('\n');
- const output = [];
-
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i].trim();
- // 保留最后的空行
- if (!line && i === lines.length - 1) {
- output.push(line);
- continue;
- }
- if (!line) continue; // 跳过中间的空行
-
- if (line.startsWith('#EXT-X-KEY')) {
- output.push(processKeyLine(line, baseUrl));
- continue;
- }
- if (line.startsWith('#EXT-X-MAP')) {
- output.push(processMapLine(line, baseUrl));
- continue;
- }
- if (line.startsWith('#EXTINF')) {
- output.push(line);
- continue;
- }
- if (!line.startsWith('#')) {
- const absoluteUrl = resolveUrl(baseUrl, line);
- logDebug(`重写媒体片段: 原始='${line}', 绝对='${absoluteUrl}'`);
- output.push(rewriteUrlToProxy(absoluteUrl));
- continue;
- }
- // 其他 M3U8 标签直接添加
- output.push(line);
- }
- return output.join('\n');
- }
-
- // 递归处理 M3U8 内容
- async function processM3u8Content(targetUrl, content, recursionDepth = 0, env) {
- if (content.includes('#EXT-X-STREAM-INF') || content.includes('#EXT-X-MEDIA:')) {
- logDebug(`检测到主播放列表: ${targetUrl}`);
- return await processMasterPlaylist(targetUrl, content, recursionDepth, env);
- }
- logDebug(`检测到媒体播放列表: ${targetUrl}`);
- return processMediaPlaylist(targetUrl, content);
- }
-
- // 处理主 M3U8 播放列表
- async function processMasterPlaylist(url, content, recursionDepth, env) {
- if (recursionDepth > MAX_RECURSION) {
- throw new Error(`处理主列表时递归层数过多 (${MAX_RECURSION}): ${url}`);
- }
-
- const baseUrl = getBaseUrl(url);
- const lines = content.split('\n');
- let highestBandwidth = -1;
- let bestVariantUrl = '';
-
- for (let i = 0; i < lines.length; i++) {
- if (lines[i].startsWith('#EXT-X-STREAM-INF')) {
- const bandwidthMatch = lines[i].match(/BANDWIDTH=(\d+)/);
- const currentBandwidth = bandwidthMatch ? parseInt(bandwidthMatch[1], 10) : 0;
-
- let variantUriLine = '';
- for (let j = i + 1; j < lines.length; j++) {
- const line = lines[j].trim();
- if (line && !line.startsWith('#')) {
- variantUriLine = line;
- i = j;
- break;
- }
- }
-
- if (variantUriLine && currentBandwidth >= highestBandwidth) {
- highestBandwidth = currentBandwidth;
- bestVariantUrl = resolveUrl(baseUrl, variantUriLine);
- }
- }
- }
-
- if (!bestVariantUrl) {
- logDebug(`主列表中未找到 BANDWIDTH 或 STREAM-INF,尝试查找第一个子列表引用: ${url}`);
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i].trim();
- if (line && !line.startsWith('#') && (line.endsWith('.m3u8') || line.includes('.m3u8?'))) { // 修复:检查是否包含 .m3u8?
- bestVariantUrl = resolveUrl(baseUrl, line);
- logDebug(`备选方案:找到第一个子列表引用: ${bestVariantUrl}`);
- break;
- }
- }
- }
-
- if (!bestVariantUrl) {
- logDebug(`在主列表 ${url} 中未找到任何有效的子播放列表 URL。可能格式有问题或仅包含音频/字幕。将尝试按媒体列表处理原始内容。`);
- return processMediaPlaylist(url, content);
- }
-
- // --- 获取并处理选中的子 M3U8 ---
-
- const cacheKey = `m3u8_processed:${bestVariantUrl}`; // 使用处理后的缓存键
-
- let kvNamespace = null;
- try {
- kvNamespace = env.LIBRETV_PROXY_KV; // 从环境获取 KV 命名空间 (变量名在 Cloudflare 设置)
- if (!kvNamespace) throw new Error("KV 命名空间未绑定");
- } catch (e) {
- logDebug(`KV 命名空间 'LIBRETV_PROXY_KV' 访问出错或未绑定: ${e.message}`);
- kvNamespace = null; // 确保设为 null
- }
-
- if (kvNamespace) {
- try {
- const cachedContent = await kvNamespace.get(cacheKey);
- if (cachedContent) {
- logDebug(`[缓存命中] 主列表的子列表: ${bestVariantUrl}`);
- return cachedContent;
- } else {
- logDebug(`[缓存未命中] 主列表的子列表: ${bestVariantUrl}`);
- }
- } catch (kvError) {
- logDebug(`从 KV 读取缓存失败 (${cacheKey}): ${kvError.message}`);
- // 出错则继续执行,不影响功能
- }
- }
-
- logDebug(`选择的子列表 (带宽: ${highestBandwidth}): ${bestVariantUrl}`);
- const { content: variantContent, contentType: variantContentType } = await fetchContentWithType(bestVariantUrl);
-
- if (!isM3u8Content(variantContent, variantContentType)) {
- logDebug(`获取到的子列表 ${bestVariantUrl} 不是 M3U8 内容 (类型: ${variantContentType})。可能直接是媒体文件,返回原始内容。`);
- // 如果不是M3U8,但看起来像媒体内容,直接返回代理后的内容
- // 注意:这里可能需要决定是否直接代理这个非 M3U8 的 URL
- // 为了简化,我们假设如果不是 M3U8,则流程中断或按原样处理
- // 或者,尝试将其作为媒体列表处理?(当前行为)
- // return createResponse(variantContent, 200, { 'Content-Type': variantContentType || 'application/octet-stream' });
- // 尝试按媒体列表处理,以防万一
- return processMediaPlaylist(bestVariantUrl, variantContent);
-
- }
-
- const processedVariant = await processM3u8Content(bestVariantUrl, variantContent, recursionDepth + 1, env);
-
- if (kvNamespace) {
- try {
- // 使用 waitUntil 异步写入缓存,不阻塞响应返回
- // 注意 KV 的写入限制 (免费版每天 1000 次)
- waitUntil(kvNamespace.put(cacheKey, processedVariant, { expirationTtl: CACHE_TTL }));
- logDebug(`已将处理后的子列表写入缓存: ${bestVariantUrl}`);
- } catch (kvError) {
- logDebug(`向 KV 写入缓存失败 (${cacheKey}): ${kvError.message}`);
- // 写入失败不影响返回结果
- }
- }
-
- return processedVariant;
- }
-
- // --- 主要请求处理逻辑 ---
-
- try {
- const targetUrl = getTargetUrlFromPath(url.pathname);
-
- if (!targetUrl) {
- logDebug(`无效的代理请求路径: ${url.pathname}`);
- return createResponse("无效的代理请求。路径应为 /proxy/<经过编码的URL>", 400);
- }
-
- logDebug(`收到代理请求: ${targetUrl}`);
-
- // SSRF 防护:拒绝内网/保留地址(Cloudflare Workers 无 dns 模块,采用启发式拦截)
- if (isBlockedTarget(targetUrl)) {
- return createResponse("不允许访问私有/保留网络地址", 403);
- }
-
- // --- 缓存检查 (KV) ---
- const cacheKey = `proxy_raw:${targetUrl}`; // 使用原始内容的缓存键
- let kvNamespace = null;
- try {
- kvNamespace = env.LIBRETV_PROXY_KV;
- if (!kvNamespace) throw new Error("KV 命名空间未绑定");
- } catch (e) {
- logDebug(`KV 命名空间 'LIBRETV_PROXY_KV' 访问出错或未绑定: ${e.message}`);
- kvNamespace = null;
- }
-
- if (kvNamespace) {
- try {
- const cachedDataJson = await kvNamespace.get(cacheKey); // 直接获取字符串
- if (cachedDataJson) {
- logDebug(`[缓存命中] 原始内容: ${targetUrl}`);
- const cachedData = JSON.parse(cachedDataJson); // 解析 JSON
- const content = cachedData.body;
- let headers = {};
- try { headers = JSON.parse(cachedData.headers); } catch(e){} // 解析头部
- const contentType = headers['content-type'] || headers['Content-Type'] || '';
-
- if (isM3u8Content(content, contentType)) {
- logDebug(`缓存内容是 M3U8,重新处理: ${targetUrl}`);
- const processedM3u8 = await processM3u8Content(targetUrl, content, 0, env);
- return createM3u8Response(processedM3u8);
- } else {
- logDebug(`从缓存返回非 M3U8 内容: ${targetUrl}`);
- return createResponse(content, 200, new Headers(headers));
- }
- } else {
- logDebug(`[缓存未命中] 原始内容: ${targetUrl}`);
- }
- } catch (kvError) {
- logDebug(`从 KV 读取或解析缓存失败 (${cacheKey}): ${kvError.message}`);
- // 出错则继续执行,不影响功能
- }
- }
-
- // --- 实际请求 ---
- const { content, contentType, responseHeaders } = await fetchContentWithType(targetUrl);
-
- // --- 写入缓存 (KV) ---
- if (kvNamespace) {
- try {
- const headersToCache = {};
- responseHeaders.forEach((value, key) => { headersToCache[key.toLowerCase()] = value; });
- const cacheValue = { body: content, headers: JSON.stringify(headersToCache) };
- // 注意 KV 写入限制
- waitUntil(kvNamespace.put(cacheKey, JSON.stringify(cacheValue), { expirationTtl: CACHE_TTL }));
- logDebug(`已将原始内容写入缓存: ${targetUrl}`);
- } catch (kvError) {
- logDebug(`向 KV 写入缓存失败 (${cacheKey}): ${kvError.message}`);
- // 写入失败不影响返回结果
- }
- }
-
- // --- 处理响应 ---
- if (isM3u8Content(content, contentType)) {
- logDebug(`内容是 M3U8,开始处理: ${targetUrl}`);
- const processedM3u8 = await processM3u8Content(targetUrl, content, 0, env);
- return createM3u8Response(processedM3u8);
- } else {
- logDebug(`内容不是 M3U8 (类型: ${contentType}),直接返回: ${targetUrl}`);
- const finalHeaders = new Headers(responseHeaders);
- finalHeaders.set('Cache-Control', `public, max-age=${CACHE_TTL}`);
- // 添加 CORS 头,确保非 M3U8 内容也能跨域访问(例如图片、字幕文件等)
- finalHeaders.set("Access-Control-Allow-Origin", "*");
- finalHeaders.set("Access-Control-Allow-Methods", "GET, HEAD, POST, OPTIONS");
- finalHeaders.set("Access-Control-Allow-Headers", "*");
- return createResponse(content, 200, finalHeaders);
- }
-
- } catch (error) {
- logDebug(`处理代理请求时发生严重错误: ${error.message} \n ${error.stack}`);
- return createResponse(`代理处理错误: ${error.message}`, 500);
- }
-}
-
-// 处理 OPTIONS 预检请求的函数
-export async function onOptions(context) {
- // 直接返回允许跨域的头信息
- return new Response(null, {
- status: 204, // No Content
- headers: {
- "Access-Control-Allow-Origin": "*",
- "Access-Control-Allow-Methods": "GET, HEAD, POST, OPTIONS",
- "Access-Control-Allow-Headers": "*", // 允许所有请求头
- "Access-Control-Max-Age": "86400", // 预检请求结果缓存一天
- },
- });
-}
diff --git a/js/config.js b/js/config.js
index 3dc5f81..b8aff8f 100644
--- a/js/config.js
+++ b/js/config.js
@@ -1,5 +1,5 @@
// 全局常量配置
-const PROXY_URL = '/proxy/'; // 适用于 Cloudflare, Netlify (带重写), Vercel (带重写)
+const PROXY_URL = '/proxy/'; // 自托管 Node 后端(server.mjs)提供的代理路径
// const HOPLAYER_URL = 'https://hoplayer.com/index.html';
const SEARCH_HISTORY_KEY = 'videoSearchHistory';
const MAX_HISTORY_ITEMS = 5;
diff --git a/middleware.js b/middleware.js
deleted file mode 100644
index dcccd84..0000000
--- a/middleware.js
+++ /dev/null
@@ -1,50 +0,0 @@
-import { sha256 } from './js/sha256.js'; // 需新建或引入SHA-256实现
-
-// Vercel Middleware to inject environment variables
-export default async function middleware(request) {
- // Get the URL from the request
- const url = new URL(request.url);
-
- // Only process HTML pages
- const isHtmlPage = url.pathname.endsWith('.html') || url.pathname.endsWith('/');
- if (!isHtmlPage) {
- return; // Let the request pass through unchanged
- }
-
- // Fetch the original response
- const response = await fetch(request);
-
- // Check if it's an HTML response
- const contentType = response.headers.get('content-type') || '';
- if (!contentType.includes('text/html')) {
- return response; // Return the original response if not HTML
- }
-
- // Get the HTML content
- const originalHtml = await response.text();
-
- // Replace the placeholder with actual environment variable
- // If PASSWORD is not set, replace with empty string
- const password = process.env.PASSWORD || '';
- let passwordHash = '';
- if (password) {
- passwordHash = await sha256(password);
- }
-
- // 替换密码占位符
- let modifiedHtml = originalHtml.replace(
- 'window.__ENV__.PASSWORD = "{{PASSWORD}}";',
- `window.__ENV__.PASSWORD = "${passwordHash}"; // SHA-256 hash`
- );
-
- // 修复Response构造
- return new Response(modifiedHtml, {
- status: response.status,
- statusText: response.statusText,
- headers: response.headers
- });
-}
-
-export const config = {
- matcher: ['/', '/((?!api|_next/static|_vercel|favicon.ico).*)'],
-};
\ No newline at end of file
diff --git a/netlify.toml b/netlify.toml
deleted file mode 100644
index 6b12e17..0000000
--- a/netlify.toml
+++ /dev/null
@@ -1,30 +0,0 @@
-# netlify.toml
-
-[build]
- # 如果你的项目不需要构建步骤 (纯静态 + functions),可以省略 publish
- # publish = "." # 假设你的 HTML/CSS/JS 文件在根目录
- functions = "netlify/functions" # 指定 Netlify 函数目录
-
-# 配置 Edge Functions
-[[edge_functions]]
- function = "inject-env"
- path = "/*"
-
-# 配置重写规则,将 /proxy/* 的请求路由到 proxy 函数
-# 这样前端的 PROXY_URL 仍然可以是 '/proxy/'
-[[redirects]]
- from = "/proxy/*"
- to = "/.netlify/functions/proxy/:splat" # 将路径参数传递给函数
- status = 200 # 重要:这是代理,不是重定向
-
-# 处理搜索路径格式 /s=*
-[[redirects]]
- from = "/s=*"
- to = "/index.html"
- status = 200
-
-# (可选)为其他静态文件设置缓存头等
-# [[headers]]
-# for = "/*"
-# [headers.values]
-# # Add any global headers here
diff --git a/netlify/edge-functions/inject-env.js b/netlify/edge-functions/inject-env.js
deleted file mode 100644
index 15e67cf..0000000
--- a/netlify/edge-functions/inject-env.js
+++ /dev/null
@@ -1,53 +0,0 @@
-// Netlify Edge Function to inject environment variables into HTML
-export default async (request, context) => {
- const url = new URL(request.url);
-
- // Only process HTML pages
- const isHtmlPage = url.pathname.endsWith('.html') || url.pathname === '/';
- if (!isHtmlPage) {
- return; // Let the request pass through unchanged
- }
-
- // Get the original response
- const response = await context.next();
-
- // Check if it's an HTML response
- const contentType = response.headers.get('content-type') || '';
- if (!contentType.includes('text/html')) {
- return response; // Return the original response if not HTML
- }
-
- // Get the HTML content
- const originalHtml = await response.text();
-
- // Simple SHA-256 implementation for Netlify Edge Functions
- async function sha256(message) {
- const msgUint8 = new TextEncoder().encode(message);
- const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);
- const hashArray = Array.from(new Uint8Array(hashBuffer));
- return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
- }
-
- // Replace the placeholder with actual environment variable
- const password = Netlify.env.get('PASSWORD') || '';
- let passwordHash = '';
- if (password) {
- passwordHash = await sha256(password);
- }
-
- const modifiedHtml = originalHtml.replace(
- 'window.__ENV__.PASSWORD = "{{PASSWORD}}";',
- `window.__ENV__.PASSWORD = "${passwordHash}"; // SHA-256 hash`
- );
-
- // Create a new response with the modified HTML
- return new Response(modifiedHtml, {
- status: response.status,
- statusText: response.statusText,
- headers: response.headers
- });
-};
-
-export const config = {
- path: ["/*"]
-};
diff --git a/netlify/functions/proxy.mjs b/netlify/functions/proxy.mjs
deleted file mode 100644
index eaa7d06..0000000
--- a/netlify/functions/proxy.mjs
+++ /dev/null
@@ -1,341 +0,0 @@
-// /netlify/functions/proxy.mjs - Netlify Function (ES Module)
-
-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';
-const CACHE_TTL = parseInt(process.env.CACHE_TTL || '86400', 10); // Default 24 hours
-const MAX_RECURSION = parseInt(process.env.MAX_RECURSION || '5', 10); // Default 5 levels
-
-// --- User Agent Handling ---
-let USER_AGENTS = [
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
- 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15'
-];
-try {
- const agentsJsonString = process.env.USER_AGENTS_JSON;
- if (agentsJsonString) {
- const parsedAgents = JSON.parse(agentsJsonString);
- if (Array.isArray(parsedAgents) && parsedAgents.length > 0) {
- USER_AGENTS = parsedAgents;
- console.log(`[Proxy Log Netlify] Loaded ${USER_AGENTS.length} user agents from environment variable.`);
- } else {
- console.warn("[Proxy Log Netlify] USER_AGENTS_JSON environment variable is not a valid non-empty array, using default.");
- }
- } else {
- console.log("[Proxy Log Netlify] USER_AGENTS_JSON environment variable not set, using default user agents.");
- }
-} catch (e) {
- console.error(`[Proxy Log Netlify] Error parsing USER_AGENTS_JSON environment variable: ${e.message}. Using default user agents.`);
-}
-const FILTER_DISCONTINUITY = false; // Ad filtering disabled
-
-// --- Helper Functions (Same as Vercel version, except rewriteUrlToProxy) ---
-
-function logDebug(message) {
- if (DEBUG_ENABLED) {
- console.log(`[Proxy Log Netlify] ${message}`);
- }
-}
-
-function getTargetUrlFromPath(encodedPath) {
- if (!encodedPath) { logDebug("getTargetUrlFromPath received empty path."); return null; }
- try {
- const decodedUrl = decodeURIComponent(encodedPath);
- if (decodedUrl.match(/^https?:\/\/.+/i)) { return decodedUrl; }
- else {
- logDebug(`Invalid decoded URL format: ${decodedUrl}`);
- if (encodedPath.match(/^https?:\/\/.+/i)) { logDebug(`Warning: Path was not encoded but looks like URL: ${encodedPath}`); return encodedPath; }
- return null;
- }
- } catch (e) { logDebug(`Error decoding target URL: ${encodedPath} - ${e.message}`); return null; }
-}
-
-function getBaseUrl(urlStr) {
- if (!urlStr) return '';
- try {
- const parsedUrl = new URL(urlStr);
- const pathSegments = parsedUrl.pathname.split('/').filter(Boolean);
- if (pathSegments.length <= 1) { return `${parsedUrl.origin}/`; }
- pathSegments.pop(); return `${parsedUrl.origin}/${pathSegments.join('/')}/`;
- } catch (e) {
- logDebug(`Getting BaseUrl failed for "${urlStr}": ${e.message}`);
- const lastSlashIndex = urlStr.lastIndexOf('/');
- if (lastSlashIndex > urlStr.indexOf('://') + 2) { return urlStr.substring(0, lastSlashIndex + 1); }
- return urlStr + '/';
- }
-}
-
-function resolveUrl(baseUrl, relativeUrl) {
- if (!relativeUrl) return ''; if (relativeUrl.match(/^https?:\/\/.+/i)) { return relativeUrl; } if (!baseUrl) return relativeUrl;
- try { return new URL(relativeUrl, baseUrl).toString(); }
- catch (e) {
- logDebug(`URL resolution failed: base="${baseUrl}", relative="${relativeUrl}". Error: ${e.message}`);
- if (relativeUrl.startsWith('/')) { try { const baseOrigin = new URL(baseUrl).origin; return `${baseOrigin}${relativeUrl}`; } catch { return relativeUrl; } }
- else { return `${baseUrl.substring(0, baseUrl.lastIndexOf('/') + 1)}${relativeUrl}`; }
- }
-}
-
-// ** MODIFIED for Netlify redirect **
-function rewriteUrlToProxy(targetUrl) {
- if (!targetUrl || typeof targetUrl !== 'string') return '';
- // Use the path defined in netlify.toml 'from' field
- return `/proxy/${encodeURIComponent(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) {
- // 针对豆瓣图片:强制豆瓣 Referer 以绕过 418 防盗链(对齐 LunaTV 的图片代理做法)
- let referer = requestHeaders['referer'] || new URL(targetUrl).origin;
- try {
- if (/doubanio\.com$/i.test(new URL(targetUrl).hostname)) {
- referer = 'https://movie.douban.com/';
- }
- } catch (e) { /* 忽略非法 URL */ }
- const headers = {
- 'User-Agent': getRandomUserAgent(),
- 'Accept': requestHeaders['accept'] || '*/*',
- 'Accept-Language': requestHeaders['accept-language'] || 'zh-CN,zh;q=0.9,en;q=0.8',
- 'Referer': referer,
- };
- Object.keys(headers).forEach(key => headers[key] === undefined || headers[key] === null || headers[key] === '' ? delete headers[key] : {});
- logDebug(`Fetching target: ${targetUrl} with headers: ${JSON.stringify(headers)}`);
- try {
- const response = await fetch(targetUrl, { headers, redirect: 'follow' });
- if (!response.ok) {
- const errorBody = await response.text().catch(() => '');
- logDebug(`Fetch failed: ${response.status} ${response.statusText} - ${targetUrl}`);
- const err = new Error(`HTTP error ${response.status}: ${response.statusText}. URL: ${targetUrl}. Body: ${errorBody.substring(0, 200)}`);
- err.status = response.status; throw err;
- }
- const content = await response.text();
- const contentType = response.headers.get('content-type') || '';
- logDebug(`Fetch success: ${targetUrl}, Content-Type: ${contentType}, Length: ${content.length}`);
- return { content, contentType, responseHeaders: response.headers };
- } catch (error) {
- logDebug(`Fetch exception for ${targetUrl}: ${error.message}`);
- throw new Error(`Failed to fetch target URL ${targetUrl}: ${error.message}`);
- }
-}
-
-function isM3u8Content(content, contentType) {
- if (contentType && (contentType.includes('application/vnd.apple.mpegurl') || contentType.includes('application/x-mpegurl') || contentType.includes('audio/mpegurl'))) { return true; }
- return content && typeof content === 'string' && content.trim().startsWith('#EXTM3U');
-}
-
-function processKeyLine(line, baseUrl) { return line.replace(/URI="([^"]+)"/, (match, uri) => { const absoluteUri = resolveUrl(baseUrl, uri); logDebug(`Processing KEY URI: Original='${uri}', Absolute='${absoluteUri}'`); return `URI="${rewriteUrlToProxy(absoluteUri)}"`; }); }
-function processMapLine(line, baseUrl) { return line.replace(/URI="([^"]+)"/, (match, uri) => { const absoluteUri = resolveUrl(baseUrl, uri); logDebug(`Processing MAP URI: Original='${uri}', Absolute='${absoluteUri}'`); return `URI="${rewriteUrlToProxy(absoluteUri)}"`; }); }
-function processMediaPlaylist(url, content) {
- const baseUrl = getBaseUrl(url); if (!baseUrl) { logDebug(`Could not determine base URL for media playlist: ${url}. Cannot process relative paths.`); }
- const lines = content.split('\n'); const output = [];
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i].trim(); if (!line && i === lines.length - 1) { output.push(line); continue; } if (!line) continue;
- if (line.startsWith('#EXT-X-KEY')) { output.push(processKeyLine(line, baseUrl)); continue; }
- if (line.startsWith('#EXT-X-MAP')) { output.push(processMapLine(line, baseUrl)); continue; }
- if (line.startsWith('#EXTINF')) { output.push(line); continue; }
- if (!line.startsWith('#')) { const absoluteUrl = resolveUrl(baseUrl, line); logDebug(`Rewriting media segment: Original='${line}', Resolved='${absoluteUrl}'`); output.push(rewriteUrlToProxy(absoluteUrl)); continue; }
- output.push(line);
- } return output.join('\n');
-}
-async function processM3u8Content(targetUrl, content, recursionDepth = 0) {
- if (content.includes('#EXT-X-STREAM-INF') || content.includes('#EXT-X-MEDIA:')) { logDebug(`Detected master playlist: ${targetUrl} (Depth: ${recursionDepth})`); return await processMasterPlaylist(targetUrl, content, recursionDepth); }
- logDebug(`Detected media playlist: ${targetUrl} (Depth: ${recursionDepth})`); return processMediaPlaylist(targetUrl, content);
-}
-async function processMasterPlaylist(url, content, recursionDepth) {
- if (recursionDepth > MAX_RECURSION) { throw new Error(`Max recursion depth (${MAX_RECURSION}) exceeded for master playlist: ${url}`); }
- const baseUrl = getBaseUrl(url); const lines = content.split('\n'); let highestBandwidth = -1; let bestVariantUrl = '';
- for (let i = 0; i < lines.length; i++) { if (lines[i].startsWith('#EXT-X-STREAM-INF')) { const bandwidthMatch = lines[i].match(/BANDWIDTH=(\d+)/); const currentBandwidth = bandwidthMatch ? parseInt(bandwidthMatch[1], 10) : 0; let variantUriLine = ''; for (let j = i + 1; j < lines.length; j++) { const line = lines[j].trim(); if (line && !line.startsWith('#')) { variantUriLine = line; i = j; break; } } if (variantUriLine && currentBandwidth >= highestBandwidth) { highestBandwidth = currentBandwidth; bestVariantUrl = resolveUrl(baseUrl, variantUriLine); } } }
- if (!bestVariantUrl) { logDebug(`No BANDWIDTH found, trying first URI in: ${url}`); for (let i = 0; i < lines.length; i++) { const line = lines[i].trim(); if (line && !line.startsWith('#') && line.match(/\.m3u8($|\?.*)/i)) { bestVariantUrl = resolveUrl(baseUrl, line); logDebug(`Fallback: Found first sub-playlist URI: ${bestVariantUrl}`); break; } } }
- if (!bestVariantUrl) { logDebug(`No valid sub-playlist URI found in master: ${url}. Processing as media playlist.`); return processMediaPlaylist(url, content); }
- logDebug(`Selected sub-playlist (Bandwidth: ${highestBandwidth}): ${bestVariantUrl}`);
- const { content: variantContent, contentType: variantContentType } = await fetchContentWithType(bestVariantUrl, {});
- if (!isM3u8Content(variantContent, variantContentType)) { logDebug(`Fetched sub-playlist ${bestVariantUrl} is not M3U8 (Type: ${variantContentType}). Treating as media playlist.`); return processMediaPlaylist(bestVariantUrl, variantContent); }
- return await processM3u8Content(bestVariantUrl, variantContent, recursionDepth + 1);
-}
-
-
-// --- Netlify Handler ---
-export const handler = async (event, context) => {
- console.log('--- Netlify Proxy Request ---');
- console.log('Time:', new Date().toISOString());
- console.log('Method:', event.httpMethod);
- console.log('Path:', event.path);
- // Note: event.queryStringParameters contains query params if any
- // Note: event.headers contains incoming headers
-
- // --- CORS Headers (for all responses) ---
- const corsHeaders = {
- 'Access-Control-Allow-Origin': '*',
- 'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS',
- 'Access-Control-Allow-Headers': '*', // Allow all headers client might send
- };
-
- // --- Handle OPTIONS Preflight Request ---
- if (event.httpMethod === 'OPTIONS') {
- logDebug("Handling OPTIONS request");
- return {
- statusCode: 204,
- headers: {
- ...corsHeaders,
- 'Access-Control-Max-Age': '86400', // Cache preflight for 24 hours
- },
- body: '',
- };
- }
-
- // --- 验证鉴权 ---
- 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
- let encodedUrlPath = '';
- const proxyPrefix = '/proxy/'; // Match the 'from' path in netlify.toml
- if (event.path && event.path.startsWith(proxyPrefix)) {
- encodedUrlPath = event.path.substring(proxyPrefix.length);
- logDebug(`Extracted encoded path from event.path: ${encodedUrlPath}`);
- } else {
- logDebug(`Could not extract encoded path from event.path: ${event.path}`);
- // Potentially handle direct calls too? Less likely needed.
- // const functionPath = '/.netlify/functions/proxy/';
- // if (event.path && event.path.startsWith(functionPath)) {
- // encodedUrlPath = event.path.substring(functionPath.length);
- // }
- }
-
- const targetUrl = getTargetUrlFromPath(encodedUrlPath);
- logDebug(`Resolved target URL: ${targetUrl || 'null'}`);
-
- if (!targetUrl) {
- logDebug('Error: Invalid proxy request path.');
- return {
- statusCode: 400,
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
- body: JSON.stringify({ success: false, error: "Invalid proxy request path. Could not extract target URL." }),
- };
- }
-
- 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);
-
- // --- Process if M3U8 ---
- if (isM3u8Content(content, contentType)) {
- logDebug(`Processing M3U8 content: ${targetUrl}`);
- const processedM3u8 = await processM3u8Content(targetUrl, content);
-
- logDebug(`Successfully processed M3U8 for ${targetUrl}`);
- return {
- statusCode: 200,
- headers: {
- ...corsHeaders, // Include CORS headers
- 'Content-Type': 'application/vnd.apple.mpegurl;charset=utf-8',
- 'Cache-Control': `public, max-age=${CACHE_TTL}`,
- // Note: Do NOT include content-encoding or content-length from original response
- // as node-fetch likely decompressed it and length changed.
- },
- body: processedM3u8, // Netlify expects body as string
- };
- } else {
- // --- Return Original Content (Non-M3U8) ---
- logDebug(`Returning non-M3U8 content directly: ${targetUrl}, Type: ${contentType}`);
-
- // Prepare headers for Netlify response object
- const netlifyHeaders = { ...corsHeaders };
- responseHeaders.forEach((value, key) => {
- const lowerKey = key.toLowerCase();
- // Exclude problematic headers and CORS headers (already added)
- if (!lowerKey.startsWith('access-control-') &&
- lowerKey !== 'content-encoding' &&
- lowerKey !== 'content-length') {
- netlifyHeaders[key] = value; // Add other original headers
- }
- });
- netlifyHeaders['Cache-Control'] = `public, max-age=${CACHE_TTL}`; // Set our cache policy
-
- return {
- statusCode: 200,
- headers: netlifyHeaders,
- body: content, // Body as string
- // isBase64Encoded: false, // Set true only if returning binary data as base64
- };
- }
-
- } catch (error) {
- logDebug(`ERROR in proxy processing for ${targetUrl}: ${error.message}`);
- console.error(`[Proxy Error Stack Netlify] ${error.stack}`); // Log full stack
-
- const statusCode = error.status || 500; // Get status from error if available
-
- return {
- statusCode: statusCode,
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
- body: JSON.stringify({
- success: false,
- error: `Proxy processing error: ${error.message}`,
- targetUrl: targetUrl
- }),
- };
- }
-};
diff --git a/render.yaml b/render.yaml
deleted file mode 100644
index cafeee5..0000000
--- a/render.yaml
+++ /dev/null
@@ -1,8 +0,0 @@
-services:
- - type: web
- name: libretv
- runtime: node
- plan: free
- buildCommand: 'npm install'
- startCommand: 'node server.mjs'
- autoDeploy: true
\ No newline at end of file
diff --git a/server.mjs b/server.mjs
index 3ac7532..087188d 100644
--- a/server.mjs
+++ b/server.mjs
@@ -299,10 +299,15 @@ app.get('/proxy/:encodedUrl', async (req, res) => {
'content-security-policy,cookie,set-cookie,x-frame-options,access-control-allow-origin'
).split(',');
sensitiveHeaders.forEach(header => delete headers[header]);
+ // axios 已自动解压响应体(decompress:true),必须移除内容编码/长度相关头,
+ // 否则浏览器会按 Content-Encoding 二次解压,导致 JSON/文本乱码(如 "Unterminated string in JSON")
+ delete headers['content-encoding'];
+ delete headers['content-length'];
+ delete headers['transfer-encoding'];
res.set(headers);
res.set('Access-Control-Allow-Origin', '*');
- // m3u8 文本:重写内部绝对地址为 /proxy/...,使自托管与 Vercel/CF 行为一致(修复分片直连导致 CORS 失败)
+ // m3u8 文本:重写内部绝对地址为 /proxy/...,使自托管后端行为一致(修复分片直连导致 CORS 失败)
if (isM3u8) {
const chunks = [];
for await (const chunk of response.data) chunks.push(chunk);
@@ -349,7 +354,7 @@ app.get('/api/proxy-token', (req, res) => {
// 防止将服务端源码(server.mjs / 配置 / 函数目录等)当作静态文件暴露
app.use((req, res, next) => {
const p = req.path.split('?')[0];
- if (/\/(server\.mjs|package\.json|package-lock\.json|Dockerfile|docker-compose\.yml|README\.md|LICENSE|api|functions|netlify|node_modules|\.env|VERSION\.txt)/i.test(p)) {
+ if (/\/(server\.mjs|package\.json|package-lock\.json|Dockerfile|docker-compose\.yml|README\.md|LICENSE|node_modules|\.env|VERSION\.txt)/i.test(p)) {
return res.status(404).send('Not Found');
}
next();
diff --git a/vercel.json b/vercel.json
deleted file mode 100644
index ea48df8..0000000
--- a/vercel.json
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "rewrites": [
- {
- "source": "/proxy/:path*",
- "destination": "/api/proxy/:path*"
- },
- {
- "source": "/s=:query",
- "destination": "/index.html"
- },
- {
- "source": "/player.html",
- "destination": "/player.html"
- },
- {
- "source": "/player.html/:path*",
- "destination": "/player.html"
- },
- {
- "source": "/:path*",
- "destination": "/:path*"
- }
- ]
-}