feat: allow wildcard web origins for local tunnel testing

This commit is contained in:
陈煜 committed 2026-10-01 17:58:28 +08:00
1 parent 2a650853ee
commit e4f4ff42e1
9 files changed
+115 -70

No files matched your search

+19 -1
View File
@@ -22,6 +22,20 @@ import { credentials } from './validation';
export type UserRequest = Request & { userId: string; sessionId: string; revealed: boolean };
const Public = () => SetMetadata('public', true);
const digest = (s: string) => createHash('sha256').update(s).digest('hex');
export function allowedOrigin(
origin: string | undefined,
configured: string | undefined,
production = false,
) {
if (configured !== '*') return !!origin && origin === configured;
if (production || !origin) return false;
try {
const url = new URL(origin);
return ['http:', 'https:'].includes(url.protocol) && url.origin === origin;
} catch {
return false;
}
}
@Injectable()
export class AuthService {
private attempts = new Map<string, { count: number; until: number }>();
@@ -87,7 +101,11 @@ export class AuthGuard implements CanActivate {
const req = ctx.switchToHttp().getRequest<UserRequest>();
if (
!['GET', 'HEAD', 'OPTIONS'].includes(req.method) &&
req.headers.origin !== process.env.WEB_ORIGIN
!allowedOrigin(
req.headers.origin,
process.env.WEB_ORIGIN,
process.env.NODE_ENV === 'production',
)
)
throw new ForbiddenException('请求来源不受信任');
if (this.reflector.get<boolean>('public', ctx.getHandler())) return true;
+2
View File
@@ -48,6 +48,8 @@ class AppModule {}
async function bootstrap() {
if (!process.env.DATABASE_URL || !process.env.WEB_ORIGIN)
throw Error('Missing local environment configuration');
if (process.env.NODE_ENV === 'production' && process.env.WEB_ORIGIN === '*')
throw Error('Production requires an explicit web origin');
if (process.env.NODE_ENV === 'production' && process.env.COOKIE_SECURE !== 'true')
throw Error('Production requires secure cookies');
const app = await NestFactory.create(AppModule, { logger: false, bodyParser: false });