修复/api/server-config暴露externalServerAuth的安全问题

This commit is contained in:
mtvpls
2025-12-26 22:13:13 +08:00
parent 3050cd48a9
commit fb9f55136d
5 changed files with 76 additions and 4 deletions

View File

@@ -13,11 +13,12 @@ export async function GET(request: NextRequest) {
const storageType = process.env.NEXT_PUBLIC_STORAGE_TYPE || 'localstorage';
// 观影室配置从环境变量读取
// 注意:不要暴露 externalServerAuth 到前端,这是敏感凭据
const watchRoomConfig = {
enabled: process.env.WATCH_ROOM_ENABLED === 'true',
serverType: (process.env.WATCH_ROOM_SERVER_TYPE as 'internal' | 'external') || 'internal',
externalServerUrl: process.env.WATCH_ROOM_EXTERNAL_SERVER_URL,
externalServerAuth: process.env.WATCH_ROOM_EXTERNAL_SERVER_AUTH,
// externalServerAuth 不应该暴露给前端
};
// 如果使用 localStorage返回默认配置

View File

@@ -0,0 +1,30 @@
/* eslint-disable no-console */
import { NextRequest, NextResponse } from 'next/server';
import { getAuthInfoFromCookie } from '@/lib/auth';
export const runtime = 'nodejs';
/**
* GET /api/watch-room-auth
*
* 需要登录才能访问的接口,返回观影室外部服务器的认证信息
* 这样可以避免将敏感的 externalServerAuth 暴露给未登录用户
*/
export async function GET(request: NextRequest) {
console.log('watch-room-auth called: ', request.url);
// 从 cookie 获取用户信息
const authInfo = getAuthInfoFromCookie(request);
if (!authInfo || !authInfo.username) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// 返回外部服务器认证信息
const externalServerAuth = process.env.WATCH_ROOM_EXTERNAL_SERVER_AUTH;
return NextResponse.json({
externalServerAuth: externalServerAuth || null,
});
}

View File

@@ -157,8 +157,27 @@ export function WatchRoomProvider({ children }: WatchRoomProviderProps) {
enabled: data.WatchRoom?.enabled ?? false, // 默认不启用
serverType: data.WatchRoom?.serverType ?? 'internal',
externalServerUrl: data.WatchRoom?.externalServerUrl,
externalServerAuth: data.WatchRoom?.externalServerAuth,
};
// 如果使用外部服务器,需要获取认证信息(需要登录)
if (watchRoomConfig.serverType === 'external' && watchRoomConfig.enabled) {
try {
const authResponse = await fetch('/api/watch-room-auth');
if (authResponse.ok) {
const authData = await authResponse.json();
watchRoomConfig.externalServerAuth = authData.externalServerAuth;
} else {
console.error('[WatchRoom] Failed to load auth info:', authResponse.status);
// 如果无法获取认证信息,禁用观影室
watchRoomConfig.enabled = false;
}
} catch (error) {
console.error('[WatchRoom] Error loading auth info:', error);
// 如果无法获取认证信息,禁用观影室
watchRoomConfig.enabled = false;
}
}
setConfig(watchRoomConfig);
setIsEnabled(watchRoomConfig.enabled);

View File

@@ -129,7 +129,7 @@ export interface WatchRoomConfig {
enabled: boolean;
serverType: 'internal' | 'external';
externalServerUrl?: string;
externalServerAuth?: string;
externalServerAuth?: string; // 通过 /api/watch-room-auth 接口获取(需要登录)
}
// LocalStorage 存储的房间信息