CSP 처리
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
// CSP 설정을 위한 환경별 구성 (img-src만)
|
||||
export const CSP_CONFIG = {
|
||||
development: {
|
||||
"img-src": ["'self'", "data:", "https:", "blob:", "http://localhost:*"]
|
||||
},
|
||||
production: {
|
||||
"img-src": ["'self'", "data:", "https:", "blob:"]
|
||||
}
|
||||
};
|
||||
|
||||
// CSP 헤더 값을 생성하는 함수
|
||||
export function generateCSPHeader(environment: 'development' | 'production' = 'development'): string {
|
||||
const config = CSP_CONFIG[environment];
|
||||
|
||||
return Object.entries(config)
|
||||
.map(([key, values]) => {
|
||||
return `${key} ${values.join(' ')}`;
|
||||
})
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
// img-src에 특정 도메인 추가하는 함수
|
||||
export function addImageDomain(domain: string, environment: 'development' | 'production' = 'development'): string {
|
||||
const config = CSP_CONFIG[environment];
|
||||
const currentImgSrc = config["img-src"];
|
||||
|
||||
if (!currentImgSrc.includes(domain)) {
|
||||
currentImgSrc.push(domain);
|
||||
}
|
||||
|
||||
return `img-src ${currentImgSrc.join(' ')};`;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
// CSP 위반 모니터링 및 보고 스크립트
|
||||
|
||||
interface CSPViolation {
|
||||
documentURI: string;
|
||||
blockedURI: string;
|
||||
violatedDirective: string;
|
||||
originalPolicy: string;
|
||||
sourceFile?: string;
|
||||
lineNumber?: number;
|
||||
columnNumber?: number;
|
||||
}
|
||||
|
||||
class CSPMonitor {
|
||||
private reportEndpoint: string;
|
||||
|
||||
constructor(reportEndpoint: string = '/api/csp-violation') {
|
||||
this.reportEndpoint = reportEndpoint;
|
||||
this.init();
|
||||
}
|
||||
|
||||
private init(): void {
|
||||
// CSP 위반 이벤트 리스너 등록
|
||||
document.addEventListener('securitypolicyviolation', (event) => {
|
||||
this.handleViolation(event);
|
||||
});
|
||||
|
||||
// 페이지 로드 시 CSP 정책 확인
|
||||
this.checkCSPPolicy();
|
||||
}
|
||||
|
||||
private handleViolation(event: SecurityPolicyViolationEvent): void {
|
||||
const violation: CSPViolation = {
|
||||
documentURI: event.documentURI,
|
||||
blockedURI: event.blockedURI,
|
||||
violatedDirective: event.violatedDirective,
|
||||
originalPolicy: event.originalPolicy,
|
||||
sourceFile: event.sourceFile,
|
||||
lineNumber: event.lineNumber,
|
||||
columnNumber: event.columnNumber
|
||||
};
|
||||
|
||||
// 콘솔에 위반 정보 출력
|
||||
console.warn('CSP Violation detected:', violation);
|
||||
|
||||
// 서버로 위반 정보 전송
|
||||
this.reportViolation(violation);
|
||||
}
|
||||
|
||||
private async reportViolation(violation: CSPViolation): Promise<void> {
|
||||
try {
|
||||
const response = await fetch(this.reportEndpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(violation),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('Failed to report CSP violation:', response.statusText);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error reporting CSP violation:', error);
|
||||
}
|
||||
}
|
||||
|
||||
private checkCSPPolicy(): void {
|
||||
// CSP 헤더 확인
|
||||
const cspHeader = document.querySelector('meta[http-equiv="Content-Security-Policy"]');
|
||||
if (cspHeader) {
|
||||
console.log('CSP Policy found in meta tag:', cspHeader.getAttribute('content'));
|
||||
} else {
|
||||
console.log('No CSP meta tag found, relying on HTTP headers');
|
||||
}
|
||||
}
|
||||
|
||||
// CSP 정책 테스트 함수
|
||||
public testCSPPolicy(): void {
|
||||
console.log('Testing CSP policy...');
|
||||
|
||||
// 인라인 스크립트 테스트
|
||||
try {
|
||||
eval('console.log("CSP test: inline script execution")');
|
||||
} catch {
|
||||
console.log('CSP blocked inline script execution');
|
||||
}
|
||||
|
||||
// 외부 스크립트 로드 테스트
|
||||
const testScript = document.createElement('script');
|
||||
testScript.src = 'https://example.com/test.js';
|
||||
testScript.onload = () => console.log('External script loaded successfully');
|
||||
testScript.onerror = () => console.log('CSP blocked external script');
|
||||
document.head.appendChild(testScript);
|
||||
}
|
||||
|
||||
// CSP 위반 통계 수집
|
||||
public getViolationStats(): Promise<unknown> {
|
||||
return fetch(`${this.reportEndpoint}/stats`)
|
||||
.then(response => response.json())
|
||||
.catch(error => {
|
||||
console.error('Error fetching CSP violation stats:', error);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 전역 CSP 모니터 인스턴스 생성
|
||||
export const cspMonitor = new CSPMonitor();
|
||||
|
||||
// 개발 환경에서만 CSP 테스트 실행
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
// 페이지 로드 후 CSP 정책 테스트
|
||||
window.addEventListener('load', () => {
|
||||
setTimeout(() => {
|
||||
cspMonitor.testCSPPolicy();
|
||||
}, 1000);
|
||||
});
|
||||
}
|
||||
|
||||
export default CSPMonitor;
|
||||
@@ -0,0 +1,61 @@
|
||||
import { generateCSPHeader } from '../config/csp';
|
||||
|
||||
// CSP 위반 인터페이스 정의
|
||||
interface CSPViolationData {
|
||||
documentURI: string;
|
||||
blockedURI: string;
|
||||
violatedDirective: string;
|
||||
originalPolicy: string;
|
||||
sourceFile?: string;
|
||||
lineNumber?: number;
|
||||
columnNumber?: number;
|
||||
}
|
||||
|
||||
// CSP 헤더를 설정하는 유틸리티 함수 (img-src만)
|
||||
export function setCSPHeaders(response: Response): Response {
|
||||
const environment = process.env.NODE_ENV as 'development' | 'production';
|
||||
const cspValue = generateCSPHeader(environment);
|
||||
|
||||
response.headers.set('Content-Security-Policy', cspValue);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
// CSP 위반을 로깅하는 함수
|
||||
export function logCSPViolation(violation: CSPViolationData): void {
|
||||
console.warn('CSP Violation:', {
|
||||
documentURI: violation.documentURI,
|
||||
blockedURI: violation.blockedURI,
|
||||
violatedDirective: violation.violatedDirective,
|
||||
originalPolicy: violation.originalPolicy,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
|
||||
// img-src 정책을 검증하는 함수
|
||||
export function validateImgSrcPolicy(policy: string): boolean {
|
||||
return policy.includes('img-src');
|
||||
}
|
||||
|
||||
// 개발 환경에서 CSP를 비활성화하는 함수 (디버깅용)
|
||||
export function disableCSPForDevelopment(): boolean {
|
||||
return process.env.NODE_ENV === 'development' &&
|
||||
process.env.DISABLE_CSP === 'true';
|
||||
}
|
||||
|
||||
// img-src에 도메인 추가하는 함수
|
||||
export function addDomainToImgSrc(
|
||||
currentPolicy: string,
|
||||
domain: string
|
||||
): string {
|
||||
if (currentPolicy.includes('img-src')) {
|
||||
// 기존 img-src에 도메인 추가
|
||||
return currentPolicy.replace(
|
||||
/img-src ([^;]+)/,
|
||||
`img-src $1 ${domain}`
|
||||
);
|
||||
} else {
|
||||
// img-src가 없으면 새로 생성
|
||||
return `${currentPolicy}; img-src 'self' ${domain};`;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user