1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
|
// lib/file-download.ts
// 공용 파일 다운로드 유틸리티 (보안 및 로깅 강화)
import { toast } from "sonner";
/**
* 파일 타입 정보
*/
export interface FileInfo {
type: 'pdf' | 'document' | 'spreadsheet' | 'image' | 'archive' | 'other';
canPreview: boolean;
icon: string;
mimeType?: string;
}
/**
* 파일 다운로드 옵션
*/
export interface FileDownloadOptions {
/** 다운로드 액션 타입 */
action?: 'download' | 'preview';
/** 에러 시 토스트 표시 여부 */
showToast?: boolean;
/** 성공 시 토스트 표시 여부 */
showSuccessToast?: boolean;
/** 커스텀 에러 핸들러 */
onError?: (error: string) => void;
/** 커스텀 성공 핸들러 */
onSuccess?: (fileName: string, fileSize?: number) => void;
/** 진행률 콜백 (큰 파일용) */
onProgress?: (progress: number) => void;
/** 로깅 비활성화 */
disableLogging?: boolean;
}
/**
* 파일 다운로드 결과
*/
export interface FileDownloadResult {
success: boolean;
error?: string;
fileSize?: number;
fileInfo?: FileInfo;
downloadDuration?: number;
}
/**
* 보안 설정
*/
const SECURITY_CONFIG = {
// 허용된 파일 확장자
ALLOWED_EXTENSIONS: new Set([
'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx',
'txt', 'csv', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'svg',
'dwg', 'dxf', 'zip', 'rar', '7z', 'webp'
]),
// 최대 파일 크기 (100MB)
MAX_FILE_SIZE: 100 * 1024 * 1024,
// 허용된 도메인 (선택적)
ALLOWED_DOMAINS: [
window.location.hostname,
'localhost',
'127.0.0.1'
],
// Rate limiting (클라이언트 사이드)
MAX_DOWNLOADS_PER_MINUTE: 10,
// 타임아웃 설정
FETCH_TIMEOUT: 30000, // 30초
};
/**
* Rate limiting 추적
*/
class RateLimiter {
private downloadAttempts: number[] = [];
canDownload(): boolean {
const now = Date.now();
const oneMinuteAgo = now - 60000;
// 1분 이전 기록 제거
this.downloadAttempts = this.downloadAttempts.filter(time => time > oneMinuteAgo);
if (this.downloadAttempts.length >= SECURITY_CONFIG.MAX_DOWNLOADS_PER_MINUTE) {
return false;
}
this.downloadAttempts.push(now);
return true;
}
getRemainingDownloads(): number {
const now = Date.now();
const oneMinuteAgo = now - 60000;
this.downloadAttempts = this.downloadAttempts.filter(time => time > oneMinuteAgo);
return Math.max(0, SECURITY_CONFIG.MAX_DOWNLOADS_PER_MINUTE - this.downloadAttempts.length);
}
}
const rateLimiter = new RateLimiter();
/**
* 클라이언트 사이드 로깅 서비스
*/
class ClientLogger {
private static async logToServer(event: string, data: any) {
try {
// 로깅이 비활성화된 경우 서버 전송 안함
if (data.disableLogging) {
console.log(`[CLIENT LOG] ${event}:`, data);
return;
}
await fetch('/api/client-logs', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
event,
data: {
...data,
timestamp: new Date().toISOString(),
userAgent: navigator.userAgent,
url: window.location.href,
sessionId: this.getSessionId(),
},
}),
}).catch(error => {
// 로깅 실패해도 메인 기능에 영향 없도록
console.warn('로깅 실패:', error);
});
} catch (error) {
console.warn('로깅 실패:', error);
}
}
private static getSessionId(): string {
let sessionId = sessionStorage.getItem('client-session-id');
if (!sessionId) {
sessionId = crypto.randomUUID();
sessionStorage.setItem('client-session-id', sessionId);
}
return sessionId;
}
static logDownloadAttempt(filePath: string, fileName: string, action: string, options?: any) {
this.logToServer('download_attempt', {
filePath,
fileName,
action,
fileExtension: fileName.split('.').pop()?.toLowerCase(),
...options,
});
}
static logDownloadSuccess(filePath: string, fileName: string, fileSize?: number, duration?: number) {
this.logToServer('download_success', {
filePath,
fileName,
fileSize,
duration,
fileExtension: fileName.split('.').pop()?.toLowerCase(),
});
}
static logDownloadError(filePath: string, fileName: string, error: string, duration?: number) {
this.logToServer('download_error', {
filePath,
fileName,
error,
duration,
fileExtension: fileName.split('.').pop()?.toLowerCase(),
});
}
static logSecurityViolation(type: string, details: any) {
this.logToServer('security_violation', {
type,
...details,
});
}
}
/**
* 보안 검증 함수들
*/
const SecurityValidator = {
validateFileExtension(fileName: string): boolean {
const extension = fileName.split('.').pop()?.toLowerCase();
return extension ? SECURITY_CONFIG.ALLOWED_EXTENSIONS.has(extension) : false;
},
validateFileName(fileName: string): boolean {
// 위험한 문자 체크
const dangerousPatterns = [
/[<>:"'|?*]/, // 특수문자
/[\x00-\x1f]/, // 제어문자
/^\./, // 숨김 파일
/\.(exe|bat|cmd|scr|vbs|js|jar)$/i, // 실행 파일
];
return !dangerousPatterns.some(pattern => pattern.test(fileName));
},
validateFilePath(filePath: string): boolean {
// 경로 탐색 공격 방지
const dangerousPatterns = [
/\.\./, // 상위 디렉토리 접근
/\/\//, // 이중 슬래시
/\\+/, // 백슬래시
/[<>:"'|?*]/, // 특수문자
];
return !dangerousPatterns.some(pattern => pattern.test(filePath));
},
validateUrl(url: string): boolean {
try {
const urlObj = new URL(url);
// HTTPS 강제 (개발 환경 제외)
if (window.location.protocol === 'https:' && urlObj.protocol !== 'https:') {
if (!['localhost', '127.0.0.1'].includes(urlObj.hostname)) {
return false;
}
}
// 허용된 도메인 검사 (상대 URL은 허용)
if (urlObj.hostname && !SECURITY_CONFIG.ALLOWED_DOMAINS.includes(urlObj.hostname)) {
return false;
}
return true;
} catch {
return false;
}
},
validateFileSize(size: number): boolean {
return size <= SECURITY_CONFIG.MAX_FILE_SIZE;
},
};
/**
* 파일 정보 가져오기
*/
export const getFileInfo = (fileName: string): FileInfo => {
const ext = fileName.toLowerCase().split('.').pop();
const fileTypes: Record<string, FileInfo> = {
pdf: { type: 'pdf', canPreview: true, icon: '📄', mimeType: 'application/pdf' },
doc: { type: 'document', canPreview: false, icon: '📝', mimeType: 'application/msword' },
docx: { type: 'document', canPreview: false, icon: '📝', mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' },
xls: { type: 'spreadsheet', canPreview: false, icon: '📊', mimeType: 'application/vnd.ms-excel' },
xlsx: { type: 'spreadsheet', canPreview: false, icon: '📊', mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' },
ppt: { type: 'document', canPreview: false, icon: '📑', mimeType: 'application/vnd.ms-powerpoint' },
pptx: { type: 'document', canPreview: false, icon: '📑', mimeType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' },
jpg: { type: 'image', canPreview: true, icon: '🖼️', mimeType: 'image/jpeg' },
jpeg: { type: 'image', canPreview: true, icon: '🖼️', mimeType: 'image/jpeg' },
png: { type: 'image', canPreview: true, icon: '🖼️', mimeType: 'image/png' },
gif: { type: 'image', canPreview: true, icon: '🖼️', mimeType: 'image/gif' },
webp: { type: 'image', canPreview: true, icon: '🖼️', mimeType: 'image/webp' },
svg: { type: 'image', canPreview: true, icon: '🖼️', mimeType: 'image/svg+xml' },
zip: { type: 'archive', canPreview: false, icon: '📦', mimeType: 'application/zip' },
rar: { type: 'archive', canPreview: false, icon: '📦', mimeType: 'application/x-rar-compressed' },
'7z': { type: 'archive', canPreview: false, icon: '📦', mimeType: 'application/x-7z-compressed' },
txt: { type: 'document', canPreview: true, icon: '📝', mimeType: 'text/plain' },
csv: { type: 'spreadsheet', canPreview: true, icon: '📊', mimeType: 'text/csv' },
};
return fileTypes[ext || ''] || { type: 'other', canPreview: false, icon: '📎', mimeType: 'application/octet-stream' };
};
/**
* 파일 크기를 읽기 쉬운 형태로 변환
*/
export const formatFileSize = (bytes: number): string => {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
/**
* 타임아웃이 적용된 fetch
*/
const fetchWithTimeout = async (url: string, options: RequestInit = {}): Promise<Response> => {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), SECURITY_CONFIG.FETCH_TIMEOUT);
try {
const response = await fetch(url, {
...options,
credentials: 'include',
signal: controller.signal,
});
clearTimeout(timeoutId);
return response;
} catch (error) {
clearTimeout(timeoutId);
throw error;
}
};
/**
* 파일 메타데이터 확인
*/
export const checkFileMetadata = async (url: string): Promise<{
exists: boolean;
size?: number;
contentType?: string;
lastModified?: Date;
error?: string;
}> => {
try {
// URL 보안 검증
if (!SecurityValidator.validateUrl(url)) {
return { exists: false, error: "허용되지 않은 URL입니다" };
}
const response = await fetchWithTimeout(url, {
method: 'HEAD',
headers: { 'Cache-Control': 'no-cache' }
});
if (!response.ok) {
let error = "파일 접근 실패";
switch (response.status) {
case 404:
error = "파일을 찾을 수 없습니다";
break;
case 403:
error = "파일 접근 권한이 없습니다";
break;
case 429:
error = "요청이 너무 많습니다. 잠시 후 다시 시도해주세요";
break;
case 500:
error = "서버 오류가 발생했습니다";
break;
default:
error = `파일 접근 실패 (${response.status})`;
}
return { exists: false, error };
}
const contentLength = response.headers.get('Content-Length');
const contentType = response.headers.get('Content-Type');
const lastModified = response.headers.get('Last-Modified');
const size = contentLength ? parseInt(contentLength, 10) : undefined;
// 파일 크기 검증
if (size && !SecurityValidator.validateFileSize(size)) {
return {
exists: false,
error: `파일이 너무 큽니다 (최대 ${formatFileSize(SECURITY_CONFIG.MAX_FILE_SIZE)})`
};
}
return {
exists: true,
size,
contentType: contentType || undefined,
lastModified: lastModified ? new Date(lastModified) : undefined,
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "네트워크 오류가 발생했습니다";
return { exists: false, error: errorMessage };
}
};
/**
* 메인 파일 다운로드 함수
*/
export const downloadFile = async (
filePath: string,
fileName: string,
options: FileDownloadOptions = {}
): Promise<FileDownloadResult> => {
const startTime = Date.now();
const { action = 'download', showToast = true, onError, onSuccess, disableLogging = false } = options;
// 로깅
if (!disableLogging) {
ClientLogger.logDownloadAttempt(filePath, fileName, action, {
userInitiated: true,
disableLogging
});
}
try {
// Rate limiting 체크
if (!rateLimiter.canDownload()) {
const error = `다운로드 제한 초과. ${rateLimiter.getRemainingDownloads()}회 남음`;
if (showToast) toast.error(error);
if (onError) onError(error);
if (!disableLogging) {
ClientLogger.logSecurityViolation('rate_limit_exceeded', { filePath, fileName });
}
return { success: false, error };
}
// 보안 검증
if (!SecurityValidator.validateFileName(fileName)) {
const error = "안전하지 않은 파일명입니다";
if (showToast) toast.error(error);
if (onError) onError(error);
if (!disableLogging) {
ClientLogger.logSecurityViolation('invalid_filename', { filePath, fileName });
}
return { success: false, error };
}
if (!SecurityValidator.validateFilePath(filePath)) {
const error = "안전하지 않은 파일 경로입니다";
if (showToast) toast.error(error);
if (onError) onError(error);
if (!disableLogging) {
ClientLogger.logSecurityViolation('invalid_filepath', { filePath, fileName });
}
return { success: false, error };
}
if (!SecurityValidator.validateFileExtension(fileName)) {
const error = "허용되지 않은 파일 형식입니다";
if (showToast) toast.error(error);
if (onError) onError(error);
if (!disableLogging) {
ClientLogger.logSecurityViolation('invalid_extension', { filePath, fileName });
}
return { success: false, error };
}
// URL 구성
const baseUrl = filePath.startsWith('http')
? filePath
: `${window.location.origin}${filePath}`;
const url = new URL(baseUrl);
if (action === 'download') {
url.searchParams.set('download', 'true');
}
const fullUrl = url.toString();
// URL 보안 검증
if (!SecurityValidator.validateUrl(fullUrl)) {
const error = "허용되지 않은 URL입니다";
if (showToast) toast.error(error);
if (onError) onError(error);
if (!disableLogging) {
ClientLogger.logSecurityViolation('invalid_url', { fullUrl, fileName });
}
return { success: false, error };
}
console.log(fullUrl,"fullUrl")
// 파일 정보 확인
const metadata = await checkFileMetadata(fullUrl);
if (!metadata.exists) {
const error = metadata.error || "파일을 찾을 수 없습니다";
if (showToast) toast.error(error);
if (onError) onError(error);
const duration = Date.now() - startTime;
if (!disableLogging) {
ClientLogger.logDownloadError(filePath, fileName, error, duration);
}
return { success: false, error, downloadDuration: duration };
}
const fileInfo = getFileInfo(fileName);
// 미리보기 처리
if (action === 'preview' && fileInfo.canPreview) {
const previewUrl = filePath.startsWith('http')
? filePath
: `${window.location.origin}${filePath}`;
// 안전한 새 창 열기
const newWindow = window.open('', '_blank', 'noopener,noreferrer');
if (newWindow) {
newWindow.location.href = previewUrl;
if (showToast) toast.success(`${fileInfo.icon} 파일을 새 탭에서 열었습니다`);
if (onSuccess) onSuccess(fileName, metadata.size);
const duration = Date.now() - startTime;
if (!disableLogging) {
ClientLogger.logDownloadSuccess(filePath, fileName, metadata.size, duration);
}
return { success: true, fileSize: metadata.size, fileInfo, downloadDuration: duration };
} else {
throw new Error("팝업이 차단되었습니다. 팝업 차단을 해제해주세요.");
}
}
// 안전한 다운로드
console.log(`📥 보안 검증된 다운로드: ${fullUrl}`);
const response = await fetchWithTimeout(fullUrl);
if (!response.ok) {
throw new Error(`다운로드 실패: ${response.status}`);
}
// Content-Type 검증
const contentType = response.headers.get('Content-Type');
if (contentType && fileInfo.mimeType && !contentType.includes(fileInfo.mimeType.split(';')[0])) {
console.warn('⚠️ MIME 타입 불일치:', { expected: fileInfo.mimeType, actual: contentType });
}
// Blob으로 변환
const blob = await response.blob();
// 최종 파일 크기 검증
if (!SecurityValidator.validateFileSize(blob.size)) {
const error = `파일이 너무 큽니다 (최대 ${formatFileSize(SECURITY_CONFIG.MAX_FILE_SIZE)})`;
if (showToast) toast.error(error);
if (onError) onError(error);
const duration = Date.now() - startTime;
if (!disableLogging) {
ClientLogger.logDownloadError(filePath, fileName, error, duration);
}
return { success: false, error, downloadDuration: duration };
}
// 브라우저 호환성을 고려한 안전한 다운로드
const downloadUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.download = fileName;
link.style.display = 'none';
link.setAttribute('data-download-source', 'secure-download-utility');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// 메모리 정리
setTimeout(() => URL.revokeObjectURL(downloadUrl), 100);
// 성공 처리
const duration = Date.now() - startTime;
if (showToast) {
const sizeText = blob.size ? ` (${formatFileSize(blob.size)})` : '';
toast.success(`${fileInfo.icon} 파일 다운로드 완료: ${fileName}${sizeText}`);
}
if (onSuccess) onSuccess(fileName, blob.size);
if (!disableLogging) {
ClientLogger.logDownloadSuccess(filePath, fileName, blob.size, duration);
}
return {
success: true,
fileSize: blob.size,
fileInfo,
downloadDuration: duration
};
} catch (error) {
const duration = Date.now() - startTime;
const errorMessage = error instanceof Error ? error.message : "파일 처리 중 오류가 발생했습니다";
console.error("❌ 다운로드 오류:", error);
if (showToast) toast.error(errorMessage);
if (onError) onError(errorMessage);
if (!disableLogging) {
ClientLogger.logDownloadError(filePath, fileName, errorMessage, duration);
}
return {
success: false,
error: errorMessage,
downloadDuration: duration
};
}
};
/**
* 간편 다운로드 함수
*/
export const quickDownload = (filePath: string, fileName: string) => {
return downloadFile(filePath, fileName, { action: 'download' });
};
/**
* 간편 미리보기 함수
*/
export const quickPreview = (filePath: string, fileName: string) => {
const fileInfo = getFileInfo(fileName);
if (!fileInfo.canPreview) {
toast.warning("이 파일 형식은 미리보기를 지원하지 않습니다. 다운로드를 진행합니다.");
return downloadFile(filePath, fileName, { action: 'download' });
}
return downloadFile(filePath, fileName, { action: 'preview' });
};
/**
* 파일 다운로드 또는 미리보기 (자동 판단)
*/
export const smartFileAction = (filePath: string, fileName: string) => {
const fileInfo = getFileInfo(fileName);
const action = fileInfo.canPreview ? 'preview' : 'download';
return downloadFile(filePath, fileName, { action });
};
/**
* 보안 정보 조회
*/
export const getSecurityInfo = () => {
return {
allowedExtensions: Array.from(SECURITY_CONFIG.ALLOWED_EXTENSIONS),
maxFileSize: SECURITY_CONFIG.MAX_FILE_SIZE,
maxFileSizeFormatted: formatFileSize(SECURITY_CONFIG.MAX_FILE_SIZE),
remainingDownloads: rateLimiter.getRemainingDownloads(),
allowedDomains: SECURITY_CONFIG.ALLOWED_DOMAINS,
};
};
|