一分钟搭建影视站,支持Docker等部署方式
refactor: 代理切换为查询串形式并抽取公共处理逻辑
bestZwei4866e27681b2
diff --git a/src/app/api/live/stream/[url]/route.ts b/src/app/api/live/stream/[url]/route.tsindex cb90acd..308a507 100644--- a/src/app/api/live/stream/[url]/route.ts+++ b/src/app/api/live/stream/[url]/route.ts@@ -1,110 +1,10 @@-import { NextResponse } from 'next/server';-import { guardRequest, jsonError } from '@/lib/api-guard';-import { checkLiveUrlAllowed } from '@/lib/ssrf';-import { fetchWithSafeRedirects } from '@/lib/fetch-utils';-import { rewriteM3u8 } from '@/lib/m3u8';+import { decodePathTarget, handleLiveStreamRequest } from '@/lib/proxy-handlers';export const runtime = 'nodejs';export const dynamic = 'force-dynamic';-/**- * 直播流专用长连接代理(不复用 /api/proxy):- *- * /api/proxy 的 AbortSignal.timeout(TIMEOUT_MS) 作用于整个响应流,- * 8 秒后即切断长连接——对 HTTP-FLV(单一无限长连接)是致命的。- * 本路由改为「仅对响应头等待设超时」(fetchWithSafeRedirects 的- * headerTimeoutMs):fetch 拿到响应头后立即清除计时器,- * 之后 body 无限时长流式透传,直到客户端断开。- *- * - 不重试(重试对直播无意义);- * - m3u8 manifest 仍需重写(变体/分片地址改指本路由),FLV 等纯透传;- * - 每一跳都强制 SSRF 校验(不信任解析阶段的校验结果);- * - 部署者可设 LIVE_ALLOW_PRIVATE=1 显式放行内网自建源(默认拒绝)。- */--const HEADER_TIMEOUT_MS = 15_000;-const LIVE_PREFIX = '/api/live/stream/';-const UA =- process.env.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';-+/** 旧路径形式的直播流代理:/api/live/stream/<encodeURIComponent(target)>,保持兼容 */export async function GET(req: Request, ctx: { params: Promise<{ url: string }> }) {const { url: encodedUrl } = await ctx.params;- const targetUrl = (() => {- try { return decodeURIComponent(encodedUrl); } catch { return encodedUrl; }- })();-- const guarded = guardRequest(req);- if (guarded) return guarded;-- const verdict = await checkLiveUrlAllowed(targetUrl);- if (!verdict.ok) return jsonError(verdict.reason, 403);-- const controller = new AbortController();- // 客户端断开(切台/关页)时终止上游连接,防止连接泄漏- const onClientAbort = () => controller.abort();- req.signal.addEventListener('abort', onClientAbort, { once: true });-- const headers: Record<string, string> = { 'User-Agent': UA, Accept: '*/*' };-- let response: Response;- let finalUrl: string;- try {- // 客户端断开(切台/关页)时经 controller.signal 终止上游连接,防止连接泄漏- const result = await fetchWithSafeRedirects(- targetUrl,- { headers, signal: controller.signal },- { allowPrivate: true, headerTimeoutMs: HEADER_TIMEOUT_MS }- );- response = result.res;- finalUrl = result.finalUrl;- } catch (err) {- return jsonError(- `直播流连接失败: ${err instanceof Error ? err.message : '未知错误'}`,- 502- );- }-- if (!response.ok && response.body) {- // 非直播正常响应(403/404 等):透传原始状态码便于前端与开发者工具定位- // (一律包成 502 会掩盖「token 过期 403」与「源瞬断」的区别)- try { await response.body.cancel(); } catch { /* 忽略 */ }- return NextResponse.json(- { error: `直播流上游返回 ${response.status}` },- {- status: response.status,- headers: { 'Cache-Control': 'no-store', 'X-Live-Upstream-Status': String(response.status) },- }- );- }-- const contentType = response.headers.get('content-type') || '';- const isM3u8 =- contentType.includes('mpegurl') || contentType.includes('x-mpegurl') ||- targetUrl.toLowerCase().split('?')[0].endsWith('.m3u8');-- // HLS manifest:重写变体/分片地址指向本路由,保证后续请求同源同鉴权。- // 关键:以重定向后的最终 URL 为 base 解析相对地址(gslb 调度源 302 后路径会变)- if (isM3u8) {- const text = await response.text();- return new NextResponse(rewriteM3u8(text, finalUrl, 0, LIVE_PREFIX), {- status: response.status,- headers: {- 'Content-Type': 'application/vnd.apple.mpegurl',- 'Cache-Control': 'no-store',- },- });- }-- // FLV / TS 等流媒体:纯流式透传(禁止缓冲与缓存)- const outHeaders = new Headers();- const ct = contentType || 'video/mp2t';- outHeaders.set('Content-Type', ct);- outHeaders.set('Cache-Control', 'no-store, no-transform');- outHeaders.set('X-Accel-Buffering', 'no');-- return new NextResponse(response.body, {- status: response.status,- headers: outHeaders,- });+ return handleLiveStreamRequest(req, decodePathTarget(encodedUrl));}diff --git a/src/app/api/live/stream/route.ts b/src/app/api/live/stream/route.tsnew file mode 100644index 0000000..f84cf60--- /dev/null+++ b/src/app/api/live/stream/route.ts@@ -0,0 +1,19 @@+import { handleLiveStreamRequest } from '@/lib/proxy-handlers';++export const runtime = 'nodejs';+export const dynamic = 'force-dynamic';++/**+ * 查询串形式的直播流代理:/api/live/stream?url=<encodeURIComponent(target)>。+ * 查询串不参与网关路径归一化,全平台行为一致;旧路径形式仍由 [url] 路由兼容。+ */+export async function GET(req: Request) {+ const targetUrl = new URL(req.url).searchParams.get('url');+ if (!targetUrl) {+ return new Response(JSON.stringify({ error: '缺少 url 参数' }), {+ status: 400,+ headers: { 'Content-Type': 'application/json' },+ });+ }+ return handleLiveStreamRequest(req, targetUrl);+}diff --git a/src/app/api/proxy/[url]/route.ts b/src/app/api/proxy/[url]/route.tsindex 69b43ee..f24ed26 100644--- a/src/app/api/proxy/[url]/route.ts+++ b/src/app/api/proxy/[url]/route.ts@@ -1,138 +1,9 @@-import { NextResponse } from 'next/server';-import { guardRequest } from '@/lib/api-guard';-import { isBlockedByDNS, isValidProxyUrl } from '@/lib/ssrf';-import { fetchWithSafeRedirects } from '@/lib/fetch-utils';-import { rewriteM3u8 } from '@/lib/m3u8';+import { decodePathTarget, handleProxyRequest } from '@/lib/proxy-handlers';export const runtime = 'nodejs';-const TIMEOUT_MS = parseInt(process.env.REQUEST_TIMEOUT || '8000', 10);-const MAX_RETRIES = parseInt(process.env.MAX_RETRIES || '1', 10);-const UA =- process.env.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';--/**- * 精确域名匹配:仅 `douban.com` 本身及其子域放行。- * 不能用 endsWith('douban.com')——那样 `evil-douban.com` 也会命中,形成鉴权绕过。- */-function isDoubanHost(host: string): boolean {- const h = host.toLowerCase();- return (- h === 'douban.com' || h.endsWith('.douban.com') ||- h === 'doubanio.com' || h.endsWith('.doubanio.com')- );-}--/**- * 未登录即可代理的图片域白名单(精确后缀匹配,防 `evil-bgm.tv` 类绕过):- * 豆瓣封面需要 Referer 伪装;热榜 cover_proxy 镜像与 Bangumi 封面- * 均为公开图片 CDN,无 Referer 校验,仅需防开放代理滥用。- */-function isAnonymousImageHost(host: string): boolean {- const h = host.toLowerCase();- return (- isDoubanHost(h) ||- h === 'doubanio.viki.moe' || h.endsWith('.doubanio.viki.moe') ||- h === 'bgm.tv' || h.endsWith('.bgm.tv')- );-}--// 未鉴权的图片等资源也允许走代理(豆瓣防盗链需要 Referer 伪装);-// 但为防止被当作开放代理滥用,仅放行上述公开图片域,其余必须已登录。-function looksLikeImageUrl(target: string): boolean {- const host = (() => {- try { return new URL(target).hostname; } catch { return ''; }- })();- return isAnonymousImageHost(host);-}--/**- * 通用流式代理:- * - 已登录会话(httpOnly cookie)→ m3u8 重写后的分片同源请求自动携带,不再有旧版丢鉴权参数的问题;- * - 未登录仅放行图片目标(豆瓣封面等),且同样受 SSRF 防护约束;- * - m3u8 文本重写为代理路径,分片/key/map 全部经本站转发,规避上游 CORS。- */+/** 旧路径形式的通用代理:/api/proxy/<encodeURIComponent(target)>,保持兼容(详见 proxy-handlers.ts) */export async function GET(req: Request, ctx: { params: Promise<{ url: string }> }) {const { url: encodedUrl } = await ctx.params;- const targetUrl = (() => {- try { return decodeURIComponent(encodedUrl); } catch { return encodedUrl; }- })();-- const guarded = guardRequest(req);- if (guarded && !looksLikeImageUrl(targetUrl)) return guarded;-- if (!isValidProxyUrl(targetUrl)) {- return new NextResponse('无效的 URL', { status: 400 });- }- if (await isBlockedByDNS(targetUrl)) {- return new NextResponse('不允许访问私有/保留网络地址', { status: 403 });- }-- const headers: Record<string, string> = { 'User-Agent': UA, Accept: '*/*' };- try {- if (isDoubanHost(new URL(targetUrl).hostname)) {- headers.Referer = 'https://movie.douban.com/';- }- } catch { /* 忽略非法 URL */ }-- const range = req.headers.get('range');- if (range) headers.Range = range;-- let response: Response | undefined;- let finalUrl = targetUrl;- let lastError: unknown = null;- for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {- try {- const result = await fetchWithSafeRedirects(targetUrl, {- headers,- signal: AbortSignal.timeout(TIMEOUT_MS),- });- response = result.res;- finalUrl = result.finalUrl;- lastError = null;- break;- } catch (err) {- lastError = err;- }- }- if (!response) {- return new NextResponse(- `代理请求失败: ${lastError instanceof Error ? lastError.message : '未知错误'}`,- { status: 502 }- );- }-- const contentType = response.headers.get('content-type') || '';- const isM3u8 =- contentType.includes('mpegurl') || contentType.includes('x-mpegurl') ||- targetUrl.toLowerCase().endsWith('.m3u8');-- // m3u8 文本:重写为代理路径(以重定向后的最终 URL 为 base 解析相对地址)- if (isM3u8) {- const text = await response.text();- return new NextResponse(rewriteM3u8(text, finalUrl), {- status: response.status,- headers: {- 'Content-Type': 'application/vnd.apple.mpegurl',- 'Cache-Control': 'no-store',- 'Access-Control-Allow-Origin': '*',- },- });- }-- // 其余(图片 / JSON / 分片 / key)流式透传- const outHeaders = new Headers();- for (const name of ['content-type', 'accept-ranges', 'content-range', 'etag', 'last-modified']) {- const v = response.headers.get(name);- if (v) outHeaders.set(name, v);- }- // fetch 会自动解压,转发时必须去掉长度相关头避免浏览器二次解压- outHeaders.set('Cache-Control', 'public, max-age=3600');- outHeaders.set('Access-Control-Allow-Origin', '*');-- return new NextResponse(response.body, {- status: response.status,- headers: outHeaders,- });+ return handleProxyRequest(req, decodePathTarget(encodedUrl));}diff --git a/src/app/api/proxy/route.ts b/src/app/api/proxy/route.tsnew file mode 100644index 0000000..903d9ae--- /dev/null+++ b/src/app/api/proxy/route.ts@@ -0,0 +1,15 @@+import { NextResponse } from 'next/server';+import { handleProxyRequest } from '@/lib/proxy-handlers';++export const runtime = 'nodejs';++/**+ * 查询串形式的通用代理:/api/proxy?url=<encodeURIComponent(target)>。+ * 查询串不参与网关路径归一化(EdgeOne 等会把路径里的 %2F 解码成 /),+ * 全平台行为一致;旧路径形式 /api/proxy/<encoded> 仍由 [url] 路由兼容。+ */+export async function GET(req: Request) {+ const targetUrl = new URL(req.url).searchParams.get('url');+ if (!targetUrl) return new NextResponse('缺少 url 参数', { status: 400 });+ return handleProxyRequest(req, targetUrl);+}diff --git a/src/components/live-player.tsx b/src/components/live-player.tsxindex 5e1cfb5..93b1a80 100644--- a/src/components/live-player.tsx+++ b/src/components/live-player.tsx@@ -11,11 +11,14 @@ import { Spinner } from './states';* mp4/webm 等原生容器 → <video> 直接播放;* - 无扩展名的地址(如 /channel/xxx?token=...)默认按 HLS 处理,* HLS 直连与代理均失败后**回退原生播放**一次(覆盖"内容是 MP4 却无 .m3u8 后缀"的源);- * - 每级直连失败自动切换到 /api/live/stream/ 代理通道重试一次;+ * - 每级直连失败自动切换到 /api/live/stream 代理通道重试一次;* - 直播态 UI:无进度条、无倍速、无截图、无连播。*/-const STREAM_PROXY_PREFIX = '/api/live/stream/';+/** 代理地址前缀(新旧形式 /api/live/stream/… 与 /api/live/stream?url=… 的共同前缀,用于防二次代理) */+const STREAM_PROXY_PREFIX = '/api/live/stream';+/** 代理地址(查询串形式:路径里的 %2F 会被 EdgeOne 等网关归一化,查询串不受影响) */+const STREAM_PROXY_BASE = '/api/live/stream?url=';export function isFlvUrl(url: string): boolean {return /\.flv(\?|$)/i.test(url);@@ -33,7 +36,7 @@ function engineOf(url: string): Engine {}function proxyUrl(url: string): string {- return STREAM_PROXY_PREFIX + encodeURIComponent(url);+ return STREAM_PROXY_BASE + encodeURIComponent(url);}interface LivePlayerProps {diff --git a/src/components/player-shell.tsx b/src/components/player-shell.tsxindex 05ba73e..c05e4e9 100644--- a/src/components/player-shell.tsx+++ b/src/components/player-shell.tsx@@ -133,11 +133,11 @@ export function PlayerShell({case Hls.ErrorTypes.NETWORK_ERROR:if (allowProxyFallback &&- !mediaUrl.startsWith('/api/proxy/') &&+ !mediaUrl.startsWith('/api/proxy') &&(errorCount >= 2 || data.details === 'manifestLoadError')) {showHint('直连失败,改用代理重试...');- setupHls(video, `/api/proxy/${encodeURIComponent(mediaUrl)}`, false);+ setupHls(video, `/api/proxy?url=${encodeURIComponent(mediaUrl)}`, false);return;}hls.startLoad();diff --git a/src/lib/m3u8.test.ts b/src/lib/m3u8.test.tsindex 8ca97d9..12aee4b 100644--- a/src/lib/m3u8.test.ts+++ b/src/lib/m3u8.test.ts@@ -1,10 +1,10 @@import { describe, expect, it } from 'vitest';-import { filterAdsFromM3u8, rewriteM3u8 } from './m3u8';+import { filterAdsFromM3u8, isProxiedUri, rewriteM3u8 } from './m3u8';const BASE = 'https://cdn.example.com/live/index.m3u8';describe('rewriteM3u8', () => {- it('把分片、嵌套播放列表、key、map 全部改写为代理路径', () => {+ it('把分片、嵌套播放列表、key、map 全部改写为代理地址(查询串形式)', () => {const input = ['#EXTM3U','#EXT-X-STREAM-INF:BANDWIDTH=1280000',@@ -18,19 +18,28 @@ describe('rewriteM3u8', () => {const out = rewriteM3u8(input, BASE);- expect(out).toContain('/api/proxy/' + encodeURIComponent('https://cdn.example.com/live/720p.m3u8'));- expect(out).toContain('/api/proxy/' + encodeURIComponent('https://cdn.example.com/key.bin'));- expect(out).toContain('/api/proxy/' + encodeURIComponent('https://cdn.example.com/live/init.mp4'));- expect(out).toContain('/api/proxy/' + encodeURIComponent('https://cdn.example.com/relative/seg1.ts'));- expect(out).toContain('/api/proxy/' + encodeURIComponent('https://cdn.example.com/live/seg2.ts'));+ expect(out).toContain('/api/proxy?url=' + encodeURIComponent('https://cdn.example.com/live/720p.m3u8'));+ expect(out).toContain('/api/proxy?url=' + encodeURIComponent('https://cdn.example.com/key.bin'));+ expect(out).toContain('/api/proxy?url=' + encodeURIComponent('https://cdn.example.com/live/init.mp4'));+ expect(out).toContain('/api/proxy?url=' + encodeURIComponent('https://cdn.example.com/relative/seg1.ts'));+ expect(out).toContain('/api/proxy?url=' + encodeURIComponent('https://cdn.example.com/live/seg2.ts'));// 非地址行保持不变expect(out).toContain('#EXTM3U');expect(out).toContain('#EXT-X-ENDLIST');});- it('已是代理路径的行不重复改写', () => {- const input = '/api/proxy/' + encodeURIComponent('https://x.com/a.ts');- expect(rewriteM3u8(input, BASE)).toBe(input);+ it('直播前缀改写为 /api/live/stream?url= 形式', () => {+ const out = rewriteM3u8('https://cdn.example.com/live/seg1.ts', BASE, 0, '/api/live/stream?url=');+ expect(out).toBe('/api/live/stream?url=' + encodeURIComponent('https://cdn.example.com/live/seg1.ts'));+ });++ it('已是代理地址的行(新旧两种形式)不重复改写', () => {+ const legacy = '/api/proxy/' + encodeURIComponent('https://x.com/a.ts');+ expect(rewriteM3u8(legacy, BASE)).toBe(legacy);+ const modern = '/api/proxy?url=' + encodeURIComponent('https://x.com/a.ts');+ expect(rewriteM3u8(modern, BASE)).toBe(modern);+ const legacyLive = '/api/live/stream/' + encodeURIComponent('https://x.com/live.m3u8');+ expect(rewriteM3u8(legacyLive, BASE, 0, '/api/live/stream?url=')).toBe(legacyLive);});it('超过递归深度限制时原样返回', () => {@@ -39,6 +48,16 @@ describe('rewriteM3u8', () => {});});+describe('isProxiedUri', () => {+ it('新旧两种代理形式均识别', () => {+ expect(isProxiedUri('/api/proxy/' + encodeURIComponent('https://x.com/a.ts'))).toBe(true);+ expect(isProxiedUri('/api/proxy?url=' + encodeURIComponent('https://x.com/a.ts'))).toBe(true);+ expect(isProxiedUri('/api/live/stream?url=' + encodeURIComponent('https://x.com/live.m3u8'))).toBe(true);+ expect(isProxiedUri('https://cdn.example.com/seg1.ts')).toBe(false);+ expect(isProxiedUri('/relative/seg1.ts')).toBe(false);+ });+});+describe('filterAdsFromM3u8', () => {it('剔除 DISCONTINUITY 标记,保留其余内容', () => {const input = ['#EXTM3U', '#EXT-X-DISCONTINUITY', 'ad.ts', '#EXTINF:10,', 'video.ts', '#EXT-X-DISCONTINUITY'].join('\n');diff --git a/src/lib/m3u8.ts b/src/lib/m3u8.tsindex 1304711..d8936ae 100644--- a/src/lib/m3u8.ts+++ b/src/lib/m3u8.ts@@ -6,7 +6,15 @@* 从根本上修复旧版「重写分片丢失鉴权参数导致 401」的问题。*/-export const PROXY_PREFIX = '/api/proxy/';+/** 点播代理地址(查询串形式,路径形式会被 EdgeOne 等网关的 URL 归一化破坏,见 proxy-handlers.ts) */+export const PROXY_BASE = '/api/proxy?url=';+/** 直播流代理地址(查询串形式) */+export const LIVE_STREAM_BASE = '/api/live/stream?url=';++/** URI 已是本站代理地址(新旧两种形式:/api/proxy/…、/api/proxy?url=…、/api/live/stream/…、/api/live/stream?url=…)时不再二次改写 */+export function isProxiedUri(uri: string): boolean {+ return uri.startsWith('/api/proxy') || uri.startsWith('/api/live/stream');+}export function makeAbsolute(url: string, base: string): string {try {@@ -17,24 +25,24 @@ export function makeAbsolute(url: string, base: string): string {}/** 将 m3u8 中的地址改写为经过本站代理的地址(分片/key/map 同样改写)。- * prefix 可指定代理前缀(直播流走 /api/live/stream/,点播默认 /api/proxy/) */+ * prefix 可指定代理地址基座(直播流走 /api/live/stream?url=,点播默认 /api/proxy?url=) */export function rewriteM3u8(content: string,baseUrl: string,depth = 0,- prefix: string = PROXY_PREFIX+ prefix: string = PROXY_BASE): string {if (depth > 5) return content;const lines = content.split('\n');const out = lines.map((line) => {if (line.startsWith('#EXT-X-KEY') || line.startsWith('#EXT-X-MAP')) {return line.replace(/(URI=")([^"]+)(")/g, (m, p1: string, uri: string, p2: string) => {- if (uri.startsWith(prefix)) return m;+ if (isProxiedUri(uri)) return m;return p1 + prefix + encodeURIComponent(makeAbsolute(uri, baseUrl)) + p2;});}if (line.startsWith('#') || line.trim() === '') return line;- if (line.startsWith(prefix)) return line;+ if (isProxiedUri(line)) return line;return prefix + encodeURIComponent(makeAbsolute(line, baseUrl));});return out.join('\n');diff --git a/src/lib/proxy-handlers.ts b/src/lib/proxy-handlers.tsnew file mode 100644index 0000000..12a3cc8--- /dev/null+++ b/src/lib/proxy-handlers.ts@@ -0,0 +1,238 @@+import { NextResponse } from 'next/server';+import { guardRequest, jsonError } from '@/lib/api-guard';+import { checkLiveUrlAllowed, isBlockedByDNS, isValidProxyUrl } from '@/lib/ssrf';+import { fetchWithSafeRedirects } from '@/lib/fetch-utils';+import { rewriteM3u8, LIVE_STREAM_BASE } from '@/lib/m3u8';++/**+ * 代理目标地址的两种传入形式:+ * - 路径段:/api/proxy/<encodeURIComponent(url)>(旧形式,保持兼容);+ * - 查询串:/api/proxy?url=<encodeURIComponent(url)>(新形式)。+ *+ * 路径形式在 EdgeOne 等会做 URL 归一化的网关上有致命缺陷:路径里的 %2F+ * 会在路由匹配前被解码成 /,多段路径令单段动态路由 [url] 匹配失败(404)。+ * 查询串不参与路径归一化,全平台行为一致;路由同时支持两种形式,+ * 旧地址(缓存页 / 已下发的播放列表)不受影响。+ */++const TIMEOUT_MS = parseInt(process.env.REQUEST_TIMEOUT || '8000', 10);+const MAX_RETRIES = parseInt(process.env.MAX_RETRIES || '1', 10);+const HEADER_TIMEOUT_MS = 15_000;+const UA =+ process.env.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';++/**+ * 精确域名匹配:仅 `douban.com` 本身及其子域放行。+ * 不能用 endsWith('douban.com')——那样 `evil-douban.com` 也会命中,形成鉴权绕过。+ */+function isDoubanHost(host: string): boolean {+ const h = host.toLowerCase();+ return (+ h === 'douban.com' || h.endsWith('.douban.com') ||+ h === 'doubanio.com' || h.endsWith('.doubanio.com')+ );+}++/**+ * 未登录即可代理的图片域白名单(精确后缀匹配,防 `evil-bgm.tv` 类绕过):+ * 豆瓣封面需要 Referer 伪装;热榜 cover_proxy 镜像与 Bangumi 封面+ * 均为公开图片 CDN,无 Referer 校验,仅需防开放代理滥用。+ */+function isAnonymousImageHost(host: string): boolean {+ const h = host.toLowerCase();+ return (+ isDoubanHost(h) ||+ h === 'doubanio.viki.moe' || h.endsWith('.doubanio.viki.moe') ||+ h === 'bgm.tv' || h.endsWith('.bgm.tv')+ );+}++// 未鉴权的图片等资源也允许走代理(豆瓣防盗链需要 Referer 伪装);+// 但为防止被当作开放代理滥用,仅放行上述公开图片域,其余必须已登录。+function looksLikeImageUrl(target: string): boolean {+ const host = (() => {+ try { return new URL(target).hostname; } catch { return ''; }+ })();+ return isAnonymousImageHost(host);+}++/** 解码路径段形式的代理目标(网关可能已把 %2F 解码为 /,失败时原样返回) */+export function decodePathTarget(encodedUrl: string): string {+ try { return decodeURIComponent(encodedUrl); } catch { return encodedUrl; }+}++/**+ * 通用流式代理(点播 / 图片):+ * - 已登录会话(httpOnly cookie)→ m3u8 重写后的分片同源请求自动携带,不再有旧版丢鉴权参数的问题;+ * - 未登录仅放行图片目标(豆瓣封面等),且同样受 SSRF 防护约束;+ * - m3u8 文本重写为代理地址,分片/key/map 全部经本站转发,规避上游 CORS。+ */+export async function handleProxyRequest(req: Request, targetUrl: string): Promise<Response> {+ const guarded = guardRequest(req);+ if (guarded && !looksLikeImageUrl(targetUrl)) return guarded;++ if (!isValidProxyUrl(targetUrl)) {+ return new NextResponse('无效的 URL', { status: 400 });+ }+ if (await isBlockedByDNS(targetUrl)) {+ return new NextResponse('不允许访问私有/保留网络地址', { status: 403 });+ }++ const headers: Record<string, string> = { 'User-Agent': UA, Accept: '*/*' };+ try {+ if (isDoubanHost(new URL(targetUrl).hostname)) {+ headers.Referer = 'https://movie.douban.com/';+ }+ } catch { /* 忽略非法 URL */ }++ const range = req.headers.get('range');+ if (range) headers.Range = range;++ let response: Response | undefined;+ let finalUrl = targetUrl;+ let lastError: unknown = null;+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {+ try {+ const result = await fetchWithSafeRedirects(targetUrl, {+ headers,+ signal: AbortSignal.timeout(TIMEOUT_MS),+ });+ response = result.res;+ finalUrl = result.finalUrl;+ lastError = null;+ break;+ } catch (err) {+ lastError = err;+ }+ }+ if (!response) {+ return new NextResponse(+ `代理请求失败: ${lastError instanceof Error ? lastError.message : '未知错误'}`,+ { status: 502 }+ );+ }++ const contentType = response.headers.get('content-type') || '';+ const isM3u8 =+ contentType.includes('mpegurl') || contentType.includes('x-mpegurl') ||+ targetUrl.toLowerCase().endsWith('.m3u8');++ // m3u8 文本:重写为代理地址(以重定向后的最终 URL 为 base 解析相对地址)+ if (isM3u8) {+ const text = await response.text();+ return new NextResponse(rewriteM3u8(text, finalUrl), {+ status: response.status,+ headers: {+ 'Content-Type': 'application/vnd.apple.mpegurl',+ 'Cache-Control': 'no-store',+ 'Access-Control-Allow-Origin': '*',+ },+ });+ }++ // 其余(图片 / JSON / 分片 / key)流式透传+ const outHeaders = new Headers();+ for (const name of ['content-type', 'accept-ranges', 'content-range', 'etag', 'last-modified']) {+ const v = response.headers.get(name);+ if (v) outHeaders.set(name, v);+ }+ // fetch 会自动解压,转发时必须去掉长度相关头避免浏览器二次解压+ outHeaders.set('Cache-Control', 'public, max-age=3600');+ outHeaders.set('Access-Control-Allow-Origin', '*');++ return new NextResponse(response.body, {+ status: response.status,+ headers: outHeaders,+ });+}++/**+ * 直播流专用长连接代理(不复用 /api/proxy):+ *+ * /api/proxy 的 AbortSignal.timeout(TIMEOUT_MS) 作用于整个响应流,+ * 8 秒后即切断长连接——对 HTTP-FLV(单一无限长连接)是致命的。+ * 本路由改为「仅对响应头等待设超时」(fetchWithSafeRedirects 的+ * headerTimeoutMs):fetch 拿到响应头后立即清除计时器,+ * 之后 body 无限时长流式透传,直到客户端断开。+ *+ * - 不重试(重试对直播无意义);+ * - m3u8 manifest 仍需重写(变体/分片地址改指本路由),FLV 等纯透传;+ * - 每一跳都强制 SSRF 校验(不信任解析阶段的校验结果);+ * - 部署者可设 LIVE_ALLOW_PRIVATE=1 显式放行内网自建源(默认拒绝)。+ */+export async function handleLiveStreamRequest(req: Request, targetUrl: string): Promise<Response> {+ const guarded = guardRequest(req);+ if (guarded) return guarded;++ const verdict = await checkLiveUrlAllowed(targetUrl);+ if (!verdict.ok) return jsonError(verdict.reason, 403);++ const controller = new AbortController();+ // 客户端断开(切台/关页)时终止上游连接,防止连接泄漏+ const onClientAbort = () => controller.abort();+ req.signal.addEventListener('abort', onClientAbort, { once: true });++ const headers: Record<string, string> = { 'User-Agent': UA, Accept: '*/*' };++ let response: Response;+ let finalUrl: string;+ try {+ // 客户端断开(切台/关页)时经 controller.signal 终止上游连接,防止连接泄漏+ const result = await fetchWithSafeRedirects(+ targetUrl,+ { headers, signal: controller.signal },+ { allowPrivate: true, headerTimeoutMs: HEADER_TIMEOUT_MS }+ );+ response = result.res;+ finalUrl = result.finalUrl;+ } catch (err) {+ return jsonError(+ `直播流连接失败: ${err instanceof Error ? err.message : '未知错误'}`,+ 502+ );+ }++ if (!response.ok && response.body) {+ // 非直播正常响应(403/404 等):透传原始状态码便于前端与开发者工具定位+ // (一律包成 502 会掩盖「token 过期 403」与「源瞬断」的区别)+ try { await response.body.cancel(); } catch { /* 忽略 */ }+ return NextResponse.json(+ { error: `直播流上游返回 ${response.status}` },+ {+ status: response.status,+ headers: { 'Cache-Control': 'no-store', 'X-Live-Upstream-Status': String(response.status) },+ }+ );+ }++ const contentType = response.headers.get('content-type') || '';+ const isM3u8 =+ contentType.includes('mpegurl') || contentType.includes('x-mpegurl') ||+ targetUrl.toLowerCase().split('?')[0].endsWith('.m3u8');++ // HLS manifest:重写变体/分片地址指向本路由,保证后续请求同源同鉴权。+ // 关键:以重定向后的最终 URL 为 base 解析相对地址(gslb 调度源 302 后路径会变)+ if (isM3u8) {+ const text = await response.text();+ return new NextResponse(rewriteM3u8(text, finalUrl, 0, LIVE_STREAM_BASE), {+ status: response.status,+ headers: {+ 'Content-Type': 'application/vnd.apple.mpegurl',+ 'Cache-Control': 'no-store',+ },+ });+ }++ // FLV / TS 等流媒体:纯流式透传(禁止缓冲与缓存)+ const outHeaders = new Headers();+ const ct = contentType || 'video/mp2t';+ outHeaders.set('Content-Type', ct);+ outHeaders.set('Cache-Control', 'no-store, no-transform');+ outHeaders.set('X-Accel-Buffering', 'no');++ return new NextResponse(response.body, {+ status: response.status,+ headers: outHeaders,+ });+}diff --git a/src/lib/utils.ts b/src/lib/utils.tsindex 0787327..ca04879 100644--- a/src/lib/utils.ts+++ b/src/lib/utils.ts@@ -32,6 +32,8 @@ export function formatDisableTtl(ms: number): string {/*** 封面图加载地址:direct 直连 / proxy 内置代理 / custom 自定义模板({url} 占位符或直接拼接)。* 默认 proxy(内置代理),规避豆瓣防盗链与部分采集站图床直连失败。+ * 代理走查询串形式(/api/proxy?url=…):路径里的 %2F 会被 EdgeOne 等网关+ * 在路由匹配前解码成 /,查询串不受影响,全平台行为一致。*/export function buildImageUrl(url: string | undefined,@@ -39,7 +41,7 @@ export function buildImageUrl(customTemplate: string): string | undefined {if (!url) return undefined;- if (mode === 'proxy') return `/api/proxy/${encodeURIComponent(url)}`;+ if (mode === 'proxy') return `/api/proxy?url=${encodeURIComponent(url)}`;if (mode === 'custom' && customTemplate) {return customTemplate.includes('{url}')? customTemplate.replace('{url}', encodeURIComponent(url))