Skip to content

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

2.2.0

bestZwei3140e882c748
diff --git a/docs/Home.md b/docs/Home.md
index bc72a05..7538971 100644
--- a/docs/Home.md
+++ b/docs/Home.md
@@ -29,10 +29,12 @@ PASSWORD=dev-password npm run dev # http://localhost:8080
## 核心特性
- **聚合搜索**:多采集站服务端并行搜索,单源失败不影响整体,用户 IP 不暴露给第三方
+- **跨源同名聚合**:同名影片合并为一张卡片,展开即可比较和选择各来源
- **HLS 播放**:ArtPlayer + hls.js,广告分片过滤、自动连播、倍速、快捷键、移动端长按 3 倍速
- **智能回退**:视频直连失败(CORS / 防盗链)时自动改走内置代理重试
- **进度同步**:播放进度与观看历史存于本机 IndexedDB,精确到秒的续播
- **换源测速**:跨源搜索同名资源并测速排序,一键切换保留集数位置
+- **源测试与订阅**:一键探活数据源;订阅远程源列表(LibreTV-SourceList JSON),可导出分享
- **豆瓣推荐**:电影 / 剧集分类浏览,服务端直连避免公共 CORS 代理
- **亮暗主题**:跟随系统 / 手动切换,无首屏闪烁
- **PWA**:可安装到桌面 / 主屏幕
diff --git a/package.json b/package.json
index db5c4cb..b4b7680 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "libretv-next",
- "version": "2.1.2",
+ "version": "2.2.0",
"private": true,
"description": "免费在线视频搜索与观看平台(Next.js 重构版)",
"license": "AGPL-3.0-or-later",
diff --git a/src/app/api/proxy/[url]/route.ts b/src/app/api/proxy/[url]/route.ts
index c4e8afc..97e2423 100644
--- a/src/app/api/proxy/[url]/route.ts
+++ b/src/app/api/proxy/[url]/route.ts
@@ -1,8 +1,7 @@
import { NextResponse } from 'next/server';
import { guardRequest } from '@/lib/api-guard';
-import { isBlockedByDNS, isValidProxyUrl } from '@/lib/ssrf';
+import { checkUpstreamAllowed, isBlockedByDNS, isValidProxyUrl } from '@/lib/ssrf';
import { rewriteM3u8 } from '@/lib/m3u8';
-import { fetchUpstream } from '@/lib/fetch-utils';
export const runtime = 'nodejs';
@@ -12,6 +11,37 @@ 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';
+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
+const MAX_REDIRECT_HOPS = 5;
+
+/**
+ * 代理专用上游抓取:手动逐跳跟随跳转,每一跳重新执行 SSRF 校验。
+ * 不能用 redirect:'follow'——预检之后 fetch 自动跟随的 3xx 可把请求
+ * 带进内网/元数据地址,绕过下方对首跳的校验。
+ */
+async function proxyFetch(
+ targetUrl: string,
+ init: { headers: Record<string, string> }
+): Promise<Response> {
+ let current = targetUrl;
+ for (let hop = 0; hop <= MAX_REDIRECT_HOPS; hop++) {
+ const verdict = await checkUpstreamAllowed(current);
+ if (!verdict.ok) {
+ throw new Error(`跳转目标被拒绝: ${verdict.reason}`);
+ }
+ const res = await fetch(current, {
+ headers: init.headers,
+ redirect: 'manual',
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ if (!REDIRECT_STATUSES.has(res.status)) return res;
+ const location = res.headers.get('location');
+ if (!location) return res;
+ current = new URL(location, current).href;
+ }
+ throw new Error('重定向次数过多');
+}
+
/**
* 精确域名匹配:仅 `douban.com` 本身及其子域放行。
* 不能用 endsWith('douban.com')——那样 `evil-douban.com` 也会命中,形成鉴权绕过。
@@ -65,17 +95,20 @@ export async function GET(req: Request, ctx: { params: Promise<{ url: string }>
const range = req.headers.get('range');
if (range) headers.Range = range;
- let response: Response;
- try {
- response = await fetchUpstream(targetUrl, {
- timeoutMs: TIMEOUT_MS,
- retries: MAX_RETRIES,
- headers,
- redirect: 'follow',
- });
- } catch (err) {
+ let response: Response | undefined;
+ let lastError: unknown = null;
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
+ try {
+ response = await proxyFetch(targetUrl, { headers });
+ lastError = null;
+ break;
+ } catch (err) {
+ lastError = err;
+ }
+ }
+ if (!response) {
return new NextResponse(
- `代理请求失败: ${err instanceof Error ? err.message : '未知错误'}`,
+ `代理请求失败: ${lastError instanceof Error ? lastError.message : '未知错误'}`,
{ status: 502 }
);
}
diff --git a/src/app/page.tsx b/src/app/page.tsx
index c435964..61ee3e7 100644
--- a/src/app/page.tsx
+++ b/src/app/page.tsx
@@ -6,7 +6,7 @@ import { useQuery } from '@tanstack/react-query';
import { Header } from '@/components/header';
import { DoubanSection } from '@/components/douban-section';
import { DetailModal } from '@/components/detail-modal';
-import { VideoCard } from '@/components/video-card';
+import { AggregatedCard, aggregateResults } from '@/components/video-card';
import { useAppStore, resolveSource } from '@/lib/store';
import { api } from '@/lib/client-api';
import type { SearchResultItem } from '@/lib/types';
@@ -79,8 +79,10 @@ function HomeContent() {
addSearchHistory(query).catch(() => {});
};
- const list = searchQuery.data?.list ?? [];
+ const list = useMemo(() => searchQuery.data?.list ?? [], [searchQuery.data]);
const failures = searchQuery.data?.failures ?? [];
+ // 跨源同名聚合:同名影片合并为一张卡片,展开后可选择具体来源
+ const groups = useMemo(() => aggregateResults(list), [list]);
// 失败源显示友好名称而非裸 key
const failureNames = failures.map(
(f) =>
@@ -188,7 +190,9 @@ function HomeContent() {
<h2 className="text-sm text-muted">
“<span className="text-content">{urlQuery}</span>” 的搜索结果
{searchQuery.data && (
- <span className="text-faint">({list.length} 条{failures.length > 0 && `,${failures.length} 个源失败`})</span>
+ <span className="text-faint">
+ ({groups.length} 部影片 · {list.length} 条结果{failures.length > 0 && `,${failures.length} 个源失败`})
+ </span>
)}
</h2>
</div>
@@ -213,9 +217,13 @@ function HomeContent() {
<p className="text-sm text-faint mt-1">请尝试其他关键词或更换数据源</p>
</div>
) : (
- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
- {list.map((item) => (
- <VideoCard key={`${item.sourceKey}_${item.vodId}`} item={item} onClick={() => setDetailItem(item)} />
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 items-start">
+ {groups.map((group) => (
+ <AggregatedCard
+ key={group.key}
+ group={group}
+ onOpen={(item) => setDetailItem(item)}
+ />
))}
</div>
)}
diff --git a/src/components/video-card.tsx b/src/components/video-card.tsx
index 59ffee9..a15a449 100644
--- a/src/components/video-card.tsx
+++ b/src/components/video-card.tsx
@@ -1,12 +1,208 @@
'use client';
-import { useEffect, useState } from 'react';
+import { useEffect, useMemo, useState } from 'react';
import type { SearchResultItem } from '@/lib/types';
import { buildImageUrl } from '@/lib/utils';
import { useAppStore } from '@/lib/store';
import { cn } from '@/lib/utils';
-/** 影片卡片:封面加载失败时逐级降级到占位图 */
+// —— 跨源同名聚合 ——
+
+export interface AggregatedGroup {
+ key: string;
+ name: string;
+ year?: string;
+ typeName?: string;
+ pic?: string;
+ remarks?: string;
+ items: SearchResultItem[];
+}
+
+function buildGroup(name: string, year: string | undefined, items: SearchResultItem[]): AggregatedGroup {
+ return {
+ key: `${name}|${year ?? ''}|${items.map((i) => `${i.sourceKey}_${i.vodId}`).join(',')}`,
+ name,
+ year,
+ typeName: items.find((i) => i.typeName)?.typeName,
+ pic: items.find((i) => i.pic)?.pic,
+ remarks: items.find((i) => i.remarks)?.remarks,
+ items,
+ };
+}
+
+/**
+ * 把扁平的跨源搜索结果按「同名影片」聚合:
+ * - 以名称分桶;桶内年份不一致时(同名翻拍)按年份拆分,无年份的条目并入年份桶;
+ * - 保持传入顺序(搜索结果已按名称排序)。
+ */
+export function aggregateResults(list: SearchResultItem[]): AggregatedGroup[] {
+ const byName = new Map<string, SearchResultItem[]>();
+ for (const item of list) {
+ const k = (item.name || '').trim();
+ if (!k) continue;
+ if (!byName.has(k)) byName.set(k, []);
+ byName.get(k)!.push(item);
+ }
+ const groups: AggregatedGroup[] = [];
+ for (const [name, items] of byName) {
+ const years = [...new Set(items.map((i) => i.year).filter(Boolean))] as string[];
+ if (years.length > 1) {
+ for (const y of years) {
+ groups.push(buildGroup(name, y, items.filter((i) => i.year === y)));
+ }
+ const noYear = items.filter((i) => !i.year);
+ if (noYear.length) groups.push(buildGroup(name, undefined, noYear));
+ } else {
+ groups.push(buildGroup(name, years[0], items));
+ }
+ }
+ return groups;
+}
+
+/**
+ * 聚合影片卡片:
+ * - 单源:点击直接打开该源详情(与旧体验一致);
+ * - 多源:显示「N 个来源」徽章,点击展开各源列表,选择具体源后打开详情。
+ */
+export function AggregatedCard({
+ group,
+ onOpen,
+}: {
+ group: AggregatedGroup;
+ onOpen: (item: SearchResultItem) => void;
+}) {
+ const imageProxyMode = useAppStore((s) => s.imageProxyMode);
+ const customImageProxy = useAppStore((s) => s.customImageProxy);
+ const [imgFailed, setImgFailed] = useState(false);
+ const [expanded, setExpanded] = useState(false);
+ const primary = buildImageUrl(group.pic, imageProxyMode, customImageProxy);
+ useEffect(() => setImgFailed(false), [primary]);
+ const showImg = primary && !imgFailed;
+
+ const multi = group.items.length > 1;
+ const adult = useMemo(() => group.items.some((i) => i.isAdult), [group.items]);
+
+ const activate = () => {
+ if (multi) setExpanded((v) => !v);
+ else onOpen(group.items[0]);
+ };
+
+ return (
+ <div className={cn('card', multi && expanded && 'ring-1 ring-accent/40')}>
+ {/* 不用 h-full:展开面板需要撑高卡片,等高裁切会让面板不可见 */}
+ <div
+ className={cn('flex h-full', multi ? 'cursor-pointer' : 'cursor-pointer hover:scale-[1.02]')}
+ role="button"
+ tabIndex={0}
+ aria-expanded={multi ? expanded : undefined}
+ onClick={activate}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ activate();
+ }
+ }}
+ >
+ {showImg ? (
+ <div className="relative flex-shrink-0 w-[105px] sm:w-[120px] aspect-[2/3] bg-chip">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img
+ src={primary}
+ alt={group.name}
+ className="absolute inset-0 h-full w-full object-cover"
+ loading="lazy"
+ onError={() => setImgFailed(true)}
+ />
+ <div className="absolute inset-0 bg-gradient-to-r from-black/30 to-transparent" />
+ {multi && (
+ <span className="absolute top-1.5 left-1.5 tag bg-black/70 text-accent font-medium">
+ {group.items.length} 源
+ </span>
+ )}
+ </div>
+ ) : (
+ <div className="relative flex-shrink-0 w-[105px] sm:w-[120px] aspect-[2/3] bg-chip flex items-center justify-center">
+ <svg className="w-8 h-8 text-faint" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 4v16m10-16v16M3 6a1 1 0 011-1h1a1 1 0 011 1v12a1 1 0 01-1 1H4a1 1 0 01-1-1V6zm4 0a1 1 0 011-1h1a1 1 0 011 1v12a1 1 0 01-1 1h-1a1 1 0 01-1-1V6zm8 0a1 1 0 011-1h1a1 1 0 011 1v12a1 1 0 01-1 1h-1a1 1 0 01-1-1V6zm4 0a1 1 0 011-1h1a1 1 0 011 1v12a1 1 0 01-1 1h-1a1 1 0 01-1-1V6z" />
+ </svg>
+ {multi && (
+ <span className="absolute top-1.5 left-1.5 tag bg-black/70 text-accent font-medium">
+ {group.items.length} 源
+ </span>
+ )}
+ </div>
+ )}
+
+ <div className="p-2.5 flex flex-col flex-grow min-w-0">
+ <div className="flex-grow">
+ <h3 className="font-semibold text-sm text-content mb-1.5 line-clamp-2" title={group.name}>
+ {group.name}
+ </h3>
+ <div className="flex flex-wrap gap-1 mb-1.5">
+ {group.typeName && <span className="tag bg-accent/15 text-accent">{group.typeName}</span>}
+ {group.year && <span className="tag bg-purple-500/15 text-purple-600 dark:text-purple-300">{group.year}</span>}
+ {adult && <span className="tag bg-pink-500/15 text-pink-500">(18+)</span>}
+ </div>
+ <p className="text-xs text-muted line-clamp-2 mb-2">{group.remarks || '暂无介绍'}</p>
+ </div>
+ <div className="flex items-center justify-between mt-auto pt-1.5 border-t border-line">
+ <span className="tag bg-chip text-muted truncate max-w-[80%]">
+ {multi ? `${group.items.length} 个来源` : group.items[0].sourceName}
+ </span>
+ {multi && (
+ <svg
+ className={cn('w-4 h-4 text-faint transition-transform', expanded && 'rotate-180')}
+ fill="none"
+ stroke="currentColor"
+ viewBox="0 0 24 24"
+ aria-hidden
+ >
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
+ </svg>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {multi && expanded && (
+ <div className="border-t border-line p-2.5 animate-fade-in">
+ <p className="text-[10px] text-faint mb-1.5">选择来源播放</p>
+ <div className="flex flex-wrap gap-1.5">
+ {group.items.map((item) => (
+ <button
+ key={`${item.sourceKey}_${item.vodId}`}
+ className={cn(
+ 'group inline-flex items-center gap-1.5 max-w-full rounded-lg border px-2.5 py-1.5',
+ 'text-xs transition-all cursor-pointer',
+ 'border-line bg-chip hover:border-accent hover:bg-accent/10',
+ item.isAdult && 'border-pink-500/30'
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ onOpen(item);
+ }}
+ aria-label={`使用 ${item.sourceName} 播放`}
+ >
+ <span className="font-medium text-content truncate max-w-[9em]">{item.sourceName}</span>
+ <span className="text-faint truncate max-w-[7em]">{item.remarks || '暂无介绍'}</span>
+ <svg
+ className="w-3.5 h-3.5 text-accent shrink-0 transition-transform group-hover:scale-110"
+ fill="currentColor"
+ viewBox="0 0 24 24"
+ aria-hidden
+ >
+ <path d="M8 5v14l11-7z" />
+ </svg>
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** 影片卡片:封面加载失败时逐级降级到占位图(未聚合的单一结果使用) */
export function VideoCard({ item, onClick }: { item: SearchResultItem; onClick: () => void }) {
const imageProxyMode = useAppStore((s) => s.imageProxyMode);
const customImageProxy = useAppStore((s) => s.customImageProxy);
diff --git a/src/lib/fetch-utils.test.ts b/src/lib/fetch-utils.test.ts
new file mode 100644
index 0000000..0d79a26
--- /dev/null
+++ b/src/lib/fetch-utils.test.ts
@@ -0,0 +1,57 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { fetchUpstream } from './fetch-utils';
+
+/**
+ * 安全跳转测试:mock 全局 fetch,验证 302 跳转到内网地址会被拒绝,
+ * 跳转到公网地址则正常跟随。使用字面量公网 IP 避免 DNS 依赖。
+ */
+
+const PUBLIC_URL = 'https://93.184.216.34/a';
+
+function mockFetch(handlers: Array<(url: string) => Response>) {
+ const fn = vi.fn((url: string | URL) => {
+ const handler = handlers.shift();
+ if (!handler) throw new Error('意外的额外请求: ' + url);
+ return Promise.resolve(handler(String(url)));
+ });
+ vi.stubGlobal('fetch', fn);
+ return fn as unknown as ReturnType<typeof vi.fn> & { mock: { calls: unknown[][] } };
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('fetchUpstream 安全跳转', () => {
+ it('302 跳转到内网地址时拒绝,且不发起第二跳请求', async () => {
+ const spy = mockFetch([
+ () => new Response(null, { status: 302, headers: { location: 'http://127.0.0.1:8080/secret' } }),
+ ]);
+ await expect(fetchUpstream(PUBLIC_URL)).rejects.toThrow(/跳转目标被拒绝/);
+ expect(spy.mock.calls.length).toBe(1); // 预检在请求前拦截,内网地址未实际请求
+ });
+
+ it('302 跳转到公网地址时正常跟随并返回最终响应', async () => {
+ mockFetch([
+ () => new Response(null, { status: 302, headers: { location: 'https://93.184.216.34/b' } }),
+ () => new Response('ok', { status: 200 }),
+ ]);
+ const res = await fetchUpstream(PUBLIC_URL);
+ expect(res.status).toBe(200);
+ expect(await res.text()).toBe('ok');
+ });
+
+ it('无跳转时直接返回响应', async () => {
+ const spy = mockFetch([() => new Response('direct', { status: 200 })]);
+ const res = await fetchUpstream(PUBLIC_URL);
+ expect(await res.text()).toBe('direct');
+ expect(spy.mock.calls.length).toBe(1);
+ });
+
+ it('重定向超过上限时抛错', async () => {
+ mockFetch(Array.from({ length: 10 }, () => (url: string) =>
+ new Response(null, { status: 302, headers: { location: url } })
+ ));
+ await expect(fetchUpstream(PUBLIC_URL)).rejects.toThrow(/重定向次数过多/);
+ });
+});
diff --git a/src/lib/fetch-utils.ts b/src/lib/fetch-utils.ts
index 42919be..44b200e 100644
--- a/src/lib/fetch-utils.ts
+++ b/src/lib/fetch-utils.ts
@@ -1,20 +1,50 @@
-/** 服务端上游请求工具:超时、重试、JSON 解析 */
+/** 服务端上游请求工具:超时、重试、安全跳转、JSON 解析 */
+
+import { checkUpstreamAllowed } from './ssrf';
export interface FetchOptions extends RequestInit {
timeoutMs?: number;
retries?: number;
+ /**
+ * 安全跳转(默认开启):禁用 fetch 的自动跟随,改为手动逐跳跟随,
+ * 每一跳重新执行 SSRF 校验——否则公网 URL 可 302 跳转到内网地址绕过预检。
+ */
+ safeRedirects?: boolean;
}
+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
+const MAX_REDIRECT_HOPS = 5;
+
export async function fetchUpstream(url: string, options: FetchOptions = {}): Promise<Response> {
- const { timeoutMs = 8000, retries = 0, ...init } = options;
+ const { timeoutMs = 8000, retries = 0, safeRedirects = true, ...init } = options;
let lastError: unknown;
for (let attempt = 0; attempt <= retries; attempt++) {
try {
- return await fetch(url, {
- ...init,
- signal: AbortSignal.timeout(timeoutMs),
- redirect: init.redirect ?? 'follow',
- });
+ if (!safeRedirects) {
+ return await fetch(url, {
+ ...init,
+ signal: AbortSignal.timeout(timeoutMs),
+ redirect: init.redirect ?? 'follow',
+ });
+ }
+ // 手动逐跳跟随,每一跳重新过 SSRF 校验
+ let current = url;
+ for (let hop = 0; hop <= MAX_REDIRECT_HOPS; hop++) {
+ const verdict = await checkUpstreamAllowed(current);
+ if (!verdict.ok) {
+ throw new Error(`跳转目标被拒绝: ${verdict.reason}`);
+ }
+ const res = await fetch(current, {
+ ...init,
+ redirect: 'manual',
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ if (!REDIRECT_STATUSES.has(res.status)) return res;
+ const location = res.headers.get('location');
+ if (!location) return res;
+ current = new URL(location, current).href;
+ }
+ throw new Error('重定向次数过多');
} catch (err) {
lastError = err;
}