Harden API CORS and Docker build

This commit is contained in:
dahyeon committed 2026-07-03 05:29:31 -07:00
1 parent ffcba26e64
commit 8476526dd7
6 files changed
+251 -1

No files matched your search

+7 -1
View File
@@ -29,7 +29,8 @@ describe('bootstrap', () => {
const mockListen = jest
.fn<ReturnType<ListenFunction>, Parameters<ListenFunction>>()
.mockResolvedValue(undefined);
const mockApp = { listen: mockListen };
const mockEnableCors = jest.fn();
const mockApp = { enableCors: mockEnableCors, listen: mockListen };
const mockedNestFactory = NestFactory as unknown as {
create: jest.MockedFunction<() => Promise<typeof mockApp>>;
};
@@ -37,6 +38,11 @@ describe('bootstrap', () => {
await bootstrap();
expect(mockEnableCors).toHaveBeenCalledWith({
origin: expect.any(Function),
credentials: true,
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
});
expect(configureApp).toHaveBeenCalledWith(mockApp);
expect(mockListen).toHaveBeenCalledWith('3123');
});
+7
View File
@@ -1,9 +1,16 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { configureApp } from './app.setup';
import { createCorsOrigin } from './cors-origin';
export async function bootstrap(): Promise<void> {
const app = await NestFactory.create(AppModule);
const nodeEnv = process.env.NODE_ENV;
app.enableCors({
origin: createCorsOrigin(nodeEnv),
credentials: true,
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
});
configureApp(app);
await app.listen(process.env.PORT ?? 3000);
}
+70
View File
@@ -0,0 +1,70 @@
import {
createCorsOrigin,
isAllowedCorsOrigin,
resolveWebOrigins,
} from './cors-origin';
describe('CORS origin resolution', () => {
it('allows Cloudflare Pages preview origins in dev and staging', () => {
const origin = 'https://807e0ea6.persona-lenz.pages.dev';
expect(isAllowedCorsOrigin(origin, 'dev')).toBe(true);
expect(isAllowedCorsOrigin(origin, 'staging')).toBe(true);
});
it('does not allow Cloudflare Pages preview origins in prod', () => {
expect(
isAllowedCorsOrigin('https://807e0ea6.persona-lenz.pages.dev', 'prod'),
).toBe(false);
});
it('rejects similar but unsafe Pages origins', () => {
expect(
isAllowedCorsOrigin('http://807e0ea6.persona-lenz.pages.dev', 'staging'),
).toBe(false);
expect(
isAllowedCorsOrigin('https://persona-lenz.pages.dev', 'staging'),
).toBe(false);
expect(
isAllowedCorsOrigin('https://a.b.persona-lenz.pages.dev', 'staging'),
).toBe(false);
expect(
isAllowedCorsOrigin(
'https://807e0ea6.persona-lenz.pages.dev.evil.com',
'staging',
),
).toBe(false);
expect(
isAllowedCorsOrigin('https://807e0ea6.lolympus.pages.dev', 'staging'),
).toBe(false);
});
it('keeps configured web origins allowed', () => {
expect(
isAllowedCorsOrigin('https://example.com', 'prod', [
'https://example.com',
]),
).toBe(true);
});
it('falls back to default web origins when WEB_ORIGIN is empty', () => {
expect(resolveWebOrigins('')).toContain('http://localhost:5173');
});
it('creates a Nest CORS callback from the same rules', (done) => {
const corsOrigin = createCorsOrigin('staging');
expect(corsOrigin).not.toBe(true);
if (corsOrigin === true) return;
corsOrigin('https://807e0ea6.persona-lenz.pages.dev', (error, allow) => {
expect(error).toBeNull();
expect(allow).toBe(true);
done();
});
});
it('keeps dev CORS permissive for local development', () => {
expect(createCorsOrigin('dev')).toBe(true);
});
});
+101
View File
@@ -0,0 +1,101 @@
import type { CustomOrigin } from '@nestjs/common/interfaces/external/cors-options.interface';
const DEFAULT_WEB_ORIGINS = [
'http://localhost:5173',
'http://126.dahyeon.us:5173',
'https://persona-lenz.dahyeon.us',
];
const PAGES_DEV_ORIGIN_HOST_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.persona-lenz\.pages\.dev$/i;
const PAGES_DEV_CORS_ENVIRONMENTS = new Set(['dev', 'staging']);
function parseOrigin(origin: string, allowPath: boolean): URL | null {
const trimmedOrigin = origin.trim();
if (trimmedOrigin.length === 0) return null;
try {
const url = new URL(trimmedOrigin);
if (
!allowPath &&
(url.pathname !== '/' || url.search !== '' || url.hash !== '')
) {
return null;
}
return url;
} catch {
return null;
}
}
function normalizeOrigin(origin: string, allowPath = false): string | null {
const url = parseOrigin(origin, allowPath);
if (!url) return null;
return `${url.protocol}//${url.host}`;
}
export function resolveWebOrigins(
webOrigin = process.env.WEB_ORIGIN,
): string[] {
const configuredOrigins = webOrigin
?.split(',')
.map((origin) => normalizeOrigin(origin, true))
.filter((origin): origin is string => origin !== null);
if (configuredOrigins && configuredOrigins.length > 0) {
return configuredOrigins;
}
return [...DEFAULT_WEB_ORIGINS];
}
export function isPersonaLenzPagesDevOrigin(origin: string): boolean {
const url = parseOrigin(origin, false);
if (!url) return false;
return (
url.protocol === 'https:' &&
url.port === '' &&
PAGES_DEV_ORIGIN_HOST_PATTERN.test(url.hostname)
);
}
export function isAllowedCorsOrigin(
requestOrigin: string | undefined,
nodeEnv = process.env.NODE_ENV,
webOrigins = resolveWebOrigins(),
): boolean {
if (!requestOrigin) return false;
const normalizedRequestOrigin = normalizeOrigin(requestOrigin);
if (!normalizedRequestOrigin) return false;
const normalizedWebOrigins = webOrigins
.map((origin) => normalizeOrigin(origin, true))
.filter((origin): origin is string => origin !== null);
if (normalizedWebOrigins.includes(normalizedRequestOrigin)) {
return true;
}
return (
PAGES_DEV_CORS_ENVIRONMENTS.has(nodeEnv ?? '') &&
isPersonaLenzPagesDevOrigin(requestOrigin)
);
}
export function createCorsOrigin(
nodeEnv = process.env.NODE_ENV,
webOrigin = process.env.WEB_ORIGIN,
): true | CustomOrigin {
if (nodeEnv === 'dev') return true;
const webOrigins = resolveWebOrigins(webOrigin);
return (requestOrigin, callback) => {
callback(null, isAllowedCorsOrigin(requestOrigin, nodeEnv, webOrigins));
};
}