Files
katelyatv/src/middleware.ts
T
jinghui d5443d97c9
Docker Build & Test / build (push) Canceled after 0s
Docker Build & Test / test (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/amd64) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm/v7) (push) Canceled after 0s
Build & Push Docker image / build-and-push (linux/arm64) (push) Canceled after 0s
Build & Push Docker image / merge-images (push) Canceled after 0s
Release / release (push) Canceled after 0s
Release / docker (push) Canceled after 0s
fix: 移除首访强制跳转/ipv6 与图片代理拼接修复 (fixed105)
- 删除 Ipv6FirstVisitGate 首访强制跳转(layout.tsx 不再挂载),首页直接加载数据
- 开启 NEXT_PUBLIC_IMAGE_PROXY=/api/image-proxy,海报走站内代理
- 修复 processImageUrl 缺少 ?url= 分隔符导致的非法图片 URL
- 实测: 30/30 海报加载成功, 无跳转, IPv6 推荐浮层正常显示
2026-11-10 02:14:18 +08:00

188 lines
5.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* eslint-disable no-console */
import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth';
// 每IP限流(内存计数,防恶意刷接口/直播):api 10000次/分钟,直播 1000次/分钟
const __rlMap = new Map<string, { w0: number; n: number; live: number }>();
function checkRateLimit(ip: string, url: string): boolean {
const now = Date.now();
let e = __rlMap.get(ip);
if (!e || now - e.w0 > 60000) {
e = { w0: now, n: 0, live: 0 };
if (__rlMap.size > 20000) __rlMap.clear();
__rlMap.set(ip, e);
}
e.n++;
const isLive = url.indexOf('/api/tvbox') === 0 && /live=(ts|m3u8|lines|ch)/.test(url);
if (isLive) e.live++;
return e.n <= 10000 && !(isLive && e.live > 1000);
}
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// 限流先行(含公开 API)
const xff = request.headers.get('x-forwarded-for');
const ip = (xff ? xff.split(',')[0].trim() : '') || 'unknown';
const fullUrl = pathname + request.nextUrl.search;
if (!checkRateLimit(ip, fullUrl)) {
return new NextResponse('Too Many Requests', {
status: 429,
headers: { 'Retry-After': '60' },
});
}
// 访问日志(源码化,替代旧 patches/patch_access_log.js 运行时注入 next 内部 start-server):
// middleware 覆盖全部路由请求,跳过静态资源
if (pathname.indexOf('/_next/static') !== 0 && pathname !== '/favicon.ico') {
const ua = (request.headers.get('user-agent') || '-').slice(0, 90);
const ref = request.headers.get('referer');
console.log(
`[ACCESS] ${new Date().toISOString()} ip=${ip} ${request.method} ${fullUrl} ua=${JSON.stringify(ua)}${ref ? ` ref=${ref.slice(0, 80)}` : ''}`
);
}
// 跳过不需要认证的路径
if (shouldSkipAuth(pathname)) {
return NextResponse.next();
}
// 首次访问不再强制跳转 /ipv6 选线路页:首页直接加载数据,线路由顶栏「IPV4/IPV6」切换
const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
if (!process.env.AUTH_PASSWORD) {
// 未配置 AUTH_PASSWORD 时直接放行,不强制访问控制
return NextResponse.next();
}
// 从cookie获取认证信息
const authInfo = getAuthInfoFromCookie(request);
if (!authInfo) {
return handleAuthFailure(request, pathname);
}
// localstorage模式:在middleware中完成验证
if (storageType === 'localstorage') {
if (!authInfo.password || authInfo.password !== process.env.AUTH_PASSWORD) {
return handleAuthFailure(request, pathname);
}
return NextResponse.next();
}
// 其他模式:只验证签名
// 检查是否有用户名(非localStorage模式下密码不存储在cookie中)
if (!authInfo.username || !authInfo.signature) {
return handleAuthFailure(request, pathname);
}
// 验证签名(如果存在)
if (authInfo.signature) {
const isValidSignature = await verifySignature(
authInfo.username,
authInfo.signature,
process.env.AUTH_PASSWORD || ''
);
// 签名验证通过即可
if (isValidSignature) {
return NextResponse.next();
}
}
// 签名验证失败或不存在签名
return handleAuthFailure(request, pathname);
}
// 验证签名
async function verifySignature(
data: string,
signature: string,
secret: string
): Promise<boolean> {
const encoder = new TextEncoder();
const keyData = encoder.encode(secret);
const messageData = encoder.encode(data);
try {
// 导入密钥
const key = await crypto.subtle.importKey(
'raw',
keyData,
{ name: 'HMAC', hash: 'SHA-256' },
false,
['verify']
);
// 将十六进制字符串转换为Uint8Array
const signatureBuffer = new Uint8Array(
signature.match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16)) || []
);
// 验证签名
return await crypto.subtle.verify(
'HMAC',
key,
signatureBuffer,
messageData
);
} catch (error) {
console.error('签名验证失败:', error);
return false;
}
}
// 处理认证失败的情况
function handleAuthFailure(
request: NextRequest,
pathname: string
): NextResponse {
// 如果是 API 路由,返回 401 状态码
if (pathname.startsWith('/api')) {
return new NextResponse('Unauthorized', { status: 401 });
}
// 否则重定向到登录页面
const loginUrl = new URL('/login', request.url);
// 保留完整的URL,包括查询参数
const fullUrl = `${pathname}${request.nextUrl.search}`;
loginUrl.searchParams.set('redirect', fullUrl);
return NextResponse.redirect(loginUrl);
}
// 判断是否需要跳过认证的路径
function shouldSkipAuth(pathname: string): boolean {
const skipPaths = [
'/_next',
'/favicon.ico',
'/robots.txt',
'/manifest.json',
'/icons/',
'/logo.png',
'/screenshot.png',
'/ipv6',
'/live',
'/user-admin.js',
'/hls.min.js',
'/mpegts.min.js',
'/api/tvbox',
'/api/filter',
'/api/license-config',
'/api/douban-comments',
'/api/douban-detail',
'/api/douban-related',
];
return skipPaths.some((path) => pathname.startsWith(path));
}
// 配置middleware匹配规则
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|login|warning|hls.min.js|mpegts.min.js|api/login|api/register|api/logout|api/cron|api/server-config|api/search|api/detail|api/image-proxy|api/license-config|api/douban-comments|api/douban-detail|api/douban-related).*)',
],
};