summaryrefslogtreecommitdiff
path: root/lib/file-stroage.ts
blob: cb6fdfbd0d9aa0bbd8c0f63d12ac700a71b584f2 (plain)
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
// lib/file-storage.ts - 보안이 강화된 파일 저장 유틸리티

import { promises as fs, createWriteStream } from "fs";
import path from "path";
import crypto from "crypto";
import { createHash } from "crypto";
import { Readable } from 'stream'

interface FileStorageConfig {
  baseDir: string;
  publicUrl: string;
  isProduction: boolean;
}

// 보안 설정
const SECURITY_CONFIG = {
  // 허용된 파일 확장자
  ALLOWED_EXTENSIONS: new Set([
    'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx',
    'txt', 'csv', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp',
    // SVG 제거 - XSS 위험으로 인해
    // 'svg',
    'dwg', 'dxf', 'zip', 'rar', '7z'
  ]),
  
  // 금지된 파일 확장자 (실행 파일 등)
  FORBIDDEN_EXTENSIONS: new Set([
    'exe', 'bat', 'cmd', 'scr', 'vbs', 'js', 'jar', 'com', 'pif',
    'msi', 'reg', 'ps1', 'sh', 'php', 'asp', 'jsp', 'py', 'pl',
    // XSS 방지를 위한 추가 확장자
    'html', 'htm', 'xhtml', 'xml', 'xsl', 'xslt','svg',
    // 돌체 블랙리스트 추가
    'dll', 'vbs', 'js', 'aspx', 'cmd'
  ]),
  
  // 허용된 MIME 타입
  ALLOWED_MIME_TYPES: new Set([
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp',
    // SVG 제거 - XSS 위험으로 인해
    // 'image/svg+xml', 
    'text/plain', 'text/csv',
    'application/zip', 'application/x-rar-compressed', 'application/x-7z-compressed'
  ]),
  
  // 최대 파일 크기 (1GB)
  MAX_FILE_SIZE: 1024 * 1024 * 1024,
  
  // 파일명 최대 길이
  MAX_FILENAME_LENGTH: 255,
};

// 보안 검증 클래스
class FileSecurityValidator {
  // 파일 확장자 검증
  static validateExtension(fileName: string): { valid: boolean; error?: string } {
    const extension = path.extname(fileName).toLowerCase().substring(1);
    
    if (!extension) {
      return { valid: false, error: "파일 확장자가 없습니다" };
    }
    
    if (SECURITY_CONFIG.FORBIDDEN_EXTENSIONS.has(extension)) {
      return { valid: false, error: `금지된 파일 형식입니다: .${extension}` };
    }
    
    // if (!SECURITY_CONFIG.ALLOWED_EXTENSIONS.has(extension)) {
    //   return { valid: false, error: `허용되지 않은 파일 형식입니다: .${extension}` };
    // }
    
    return { valid: true };
  }
  
  // 파일명 안전성 검증
  static validateFileName(fileName: string): { valid: boolean; error?: string } {
    // 길이 체크
    if (fileName.length > SECURITY_CONFIG.MAX_FILENAME_LENGTH) {
      return { valid: false, error: "파일명이 너무 깁니다" };
    }
    
    // 위험한 문자 체크 (XSS 방지 강화)
    const dangerousPatterns = [
      /[<>:"|?*]/,      // HTML 태그 및 특수문자
      /[\x00-\x1f]/,    // 제어문자
      /^\./,            // 숨김 파일
      /\.\./,           // 상위 디렉토리 접근
      /\/|\\$/,         // 경로 구분자
      /javascript:/i,   // JavaScript 프로토콜
      /data:/i,         // Data URI
      /vbscript:/i,     // VBScript 프로토콜
      /on\w+=/i,        // 이벤트 핸들러 (onclick=, onload= 등)
      /<script/i,       // Script 태그
      /<iframe/i,       // Iframe 태그
    ];
    
    for (const pattern of dangerousPatterns) {
      if (pattern.test(fileName)) {
        return { valid: false, error: "안전하지 않은 파일명입니다" };
      }
    }
    
    // 예약된 Windows 파일명 체크
    const reservedNames = ['CON', 'PRN', 'AUX', 'NUL', 'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9', 'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9'];
    const nameWithoutExt = path.basename(fileName, path.extname(fileName)).toUpperCase();
    
    if (reservedNames.includes(nameWithoutExt)) {
      return { valid: false, error: "예약된 파일명입니다" };
    }
    
    return { valid: true };
  }
  
  // 파일 크기 검증
  static validateFileSize(size: number): { valid: boolean; error?: string } {
    if (size <= 0) {
      return { valid: false, error: "파일이 비어있습니다" };
    }
    
    if (size > SECURITY_CONFIG.MAX_FILE_SIZE) {
      const maxSizeMB = Math.round(SECURITY_CONFIG.MAX_FILE_SIZE / (1024 * 1024));
      return { valid: false, error: `파일 크기가 너무 큽니다 (최대 ${maxSizeMB}MB)` };
    }
    
    return { valid: true };
  }
  
  // MIME 타입 검증
  static validateMimeType(mimeType: string, fileName: string): { valid: boolean; error?: string } {
    if (!mimeType) {
      // xlsx 파일의 경우 MIME 타입이 누락될 수 있으므로 경고만 표시
      const extension = path.extname(fileName).toLowerCase().substring(1);
      if (['xlsx', 'xls', 'docx', 'doc', 'pptx', 'ppt', 'pdf', 'dwg', 'dxf', 'zip', 'rar', '7z'].includes(extension)) {
        console.warn(`⚠️ MIME 타입 누락 (Office 파일 및 주요 확장자): ${fileName}, 확장자 기반으로 허용`);
        return { valid: true }; // 확장자 기반으로 허용
      }
      return { valid: false, error: "MIME 타입을 확인할 수 없습니다" };
    }
    
    // 기본 MIME 타입 체크
    const baseMimeType = mimeType.split(';')[0].toLowerCase();
    
    // if (!SECURITY_CONFIG.ALLOWED_MIME_TYPES.has(baseMimeType)) {
    //   return { valid: false, error: `허용되지 않은 파일 형식입니다: ${baseMimeType}` };
    // }
    
    // 확장자와 MIME 타입 일치성 체크
    const extension = path.extname(fileName).toLowerCase().substring(1);
    const expectedMimeTypes = this.getExpectedMimeTypes(extension);
    
    if (expectedMimeTypes.length > 0 && !expectedMimeTypes.includes(baseMimeType)) {
      console.warn(`⚠️ MIME 타입 불일치: ${fileName} (확장자: ${extension}, MIME: ${baseMimeType})`);
      // 경고만 하고 허용 (일부 브라우저에서 MIME 타입이 다를 수 있음)
    }
    
    return { valid: true };
  }
  
  // 확장자별 예상되는 MIME 타입들
  private static getExpectedMimeTypes(extension: string): string[] {
    const mimeMap: Record<string, string[]> = {
      'pdf': ['application/pdf'],
      'doc': ['application/msword'],
      'docx': ['application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
      'xls': ['application/vnd.ms-excel'],
      'xlsx': ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
      'jpg': ['image/jpeg'],
      'jpeg': ['image/jpeg'],
      'png': ['image/png'],
      'gif': ['image/gif'],
      'bmp': ['image/bmp'],
      'svg': ['image/svg+xml'],
      'webp': ['image/webp'],
      'txt': ['text/plain'],
      'csv': ['text/csv', 'application/csv'],
      'zip': ['application/zip'],
      'rar': ['application/x-rar-compressed'],
      '7z': ['application/x-7z-compressed'],
    };
    
    return mimeMap[extension] || [];
  }
  
  // 디렉터리 기본 안전성 검증 (경로 탐색 공격 방지)
  static validateDirectory(directory: string): { valid: boolean; error?: string } {
    // 경로 정규화
    const normalizedDir = path.normalize(directory).replace(/^\/+/, '');
    
    // 경로 탐색 공격 방지
    if (normalizedDir.includes('..') || normalizedDir.includes('//')) {
      return { valid: false, error: "안전하지 않은 디렉터리 경로입니다" };
    }
    
    // 절대 경로 방지
    if (path.isAbsolute(directory)) {
      return { valid: false, error: "절대 경로는 사용할 수 없습니다" };
    }
    
    return { valid: true };
  }
  
  // 파일 내용 기본 검증 (매직 넘버 체크(비활성화) + XSS 패턴 검사)
  static async validateFileContent(buffer: Buffer, fileName: string): Promise<{ valid: boolean; error?: string }> {
    try {
      const extension = path.extname(fileName).toLowerCase().substring(1);
      
      // 파일 시그니처 (매직 넘버) 검증 << DRM 파일 처리 불가로 주석 처리
      // const fileSignatures: Record<string, Buffer[]> = {
      //   'pdf': [Buffer.from([0x25, 0x50, 0x44, 0x46])], // %PDF
      //   'jpg': [Buffer.from([0xFF, 0xD8, 0xFF])],
      //   'jpeg': [Buffer.from([0xFF, 0xD8, 0xFF])],
      //   'png': [Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])],
      //   'gif': [Buffer.from([0x47, 0x49, 0x46, 0x38])], // GIF8
      //   'zip': [Buffer.from([0x50, 0x4B, 0x03, 0x04]), Buffer.from([0x50, 0x4B, 0x05, 0x06])],
      // };
      
      // const expectedSignatures = fileSignatures[extension];
      // if (expectedSignatures) {
      //   const hasValidSignature = expectedSignatures.some(signature => 
      //     buffer.subarray(0, signature.length).equals(signature)
      //   );
        
      //   if (!hasValidSignature) {
      //     return { valid: false, error: `파일 내용이 확장자와 일치하지 않습니다: ${extension}` };
      //   }
      // }
      
      // 실행 파일 패턴 검색
      const executablePatterns = [
        Buffer.from([0x4D, 0x5A]), // MZ (Windows executable)
        Buffer.from([0x7F, 0x45, 0x4C, 0x46]), // ELF (Linux executable)
      ];
      
      for (const pattern of executablePatterns) {
        if (buffer.subarray(0, pattern.length).equals(pattern)) {
          return { valid: false, error: "실행 파일은 업로드할 수 없습니다" };
        }
      }
      
      // XSS 패턴 검사 (텍스트 기반 파일용)
      const textBasedExtensions = ['txt', 'csv', 'xml', 'svg', 'html', 'htm'];
      if (textBasedExtensions.includes(extension)) {
        const content = buffer.toString('utf8', 0, Math.min(buffer.length, 8192)); // 첫 8KB만 검사
        
        const xssPatterns = [
          /<script[\s\S]*?>/i,                    // <script> 태그
          /<iframe[\s\S]*?>/i,                    // <iframe> 태그
          /on\w+\s*=\s*["'][^"']*["']/i,         // 이벤트 핸들러 (onclick="...")
          /javascript\s*:/i,                      // javascript: 프로토콜
          /vbscript\s*:/i,                       // vbscript: 프로토콜
          /data\s*:\s*text\/html/i,              // data:text/html
          /<meta[\s\S]*?http-equiv[\s\S]*?>/i,   // meta refresh
          /<object[\s\S]*?>/i,                   // object 태그
          /<embed[\s\S]*?>/i,                    // embed 태그
          /<form[\s\S]*?action[\s\S]*?>/i,       // form 태그
        ];
        
        for (const pattern of xssPatterns) {
          if (pattern.test(content)) {
            return { valid: false, error: "파일에 잠재적으로 위험한 스크립트가 포함되어 있습니다" };
          }
        }
      }
      
      return { valid: true };
    } catch (error) {
      console.error("파일 내용 검증 오류:", error);
      return { valid: false, error: "파일 내용을 검증할 수 없습니다" };
    }
  }
}

// 파일 업로드 로깅 클래스
class FileUploadLogger {
  static logUploadAttempt(fileName: string, size: number, directory: string, userId?: string) {
    console.log(`📤 파일 업로드 시도:`, {
      fileName,
      size: this.formatFileSize(size),
      directory,
      userId,
      timestamp: new Date().toISOString(),
    });
  }
  
  static logUploadSuccess(fileName: string, hashedFileName: string, size: number, directory: string, userId?: string) {
    console.log(`✅ 파일 업로드 성공:`, {
      originalName: fileName,
      savedName: hashedFileName,
      size: this.formatFileSize(size),
      directory,
      userId,
      timestamp: new Date().toISOString(),
    });
  }
  
  static logUploadError(fileName: string, error: string, userId?: string) {
    console.error(`❌ 파일 업로드 실패:`, {
      fileName,
      error,
      userId,
      timestamp: new Date().toISOString(),
    });
  }
  
  static logSecurityViolation(fileName: string, violation: string, userId?: string) {
    console.warn(`🚨 파일 업로드 보안 위반:`, {
      fileName,
      violation,
      userId,
      timestamp: new Date().toISOString(),
    });
  }
  
  private static 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];
  }
}

// 파일명 해시 생성 유틸리티
export function generateHashedFileName(originalName: string): string {
  const fileExtension = path.extname(originalName);
  const fileNameWithoutExt = path.basename(originalName, fileExtension);
  
  const timestamp = Date.now();
  const randomHash = crypto.createHash('md5')
    .update(`${fileNameWithoutExt}-${timestamp}-${Math.random()}`)
    .digest('hex')
    .substring(0, 8);

  return `${timestamp}-${randomHash}${fileExtension}`;
}

// HTML safe한 파일명 생성 (XSS 방지)
export function sanitizeFileNameForDisplay(fileName: string): string {
  return fileName
    .replace(/&/g, '&amp;')     // & → &amp;
    .replace(/</g, '&lt;')      // < → &lt;
    .replace(/>/g, '&gt;')      // > → &gt;
    .replace(/"/g, '&quot;')    // " → &quot;
    .replace(/'/g, '&#39;')     // ' → &#39;
    .replace(/\//g, '&#47;')    // / → &#47;
    .replace(/\\/g, '&#92;');   // \ → &#92;
}

// 파일명에서 위험한 문자 제거 (저장용)
export function sanitizeFileNameForStorage(fileName: string): string {
  return fileName
    .replace(/[<>:"'|?*\\\/]/g, '_')  // 위험한 문자를 언더스코어로
    .replace(/[\x00-\x1f]/g, '')      // 제어문자 제거
    .replace(/\s+/g, '_')             // 공백을 언더스코어로
    .replace(/_{2,}/g, '_')           // 연속된 언더스코어를 하나로
    .replace(/^_+|_+$/g, '')          // 앞뒤 언더스코어 제거
    .substring(0, 200);               // 길이 제한
}

// 보안 강화된 파일 저장 옵션들
interface SaveFileOptions {
  file: File;
  directory: string;
  originalName?: string;
  userId?: string;
}

interface SaveBufferOptions {
  buffer: Buffer | ArrayBuffer;
  fileName: string;
  directory: string;
  originalName?: string;
  userId?: string;
}

export interface SaveFileResult {
  success: boolean;
  filePath?: string;
  publicPath?: string;
  fileName?: string;
  originalName?: string;
  fileSize?: number;
  error?: string;
  securityChecks?: {
    extensionCheck: boolean;
    fileNameCheck: boolean;
    sizeCheck: boolean;
    mimeTypeCheck: boolean;
    contentCheck: boolean;
  };
}

const nasPath = process.env.NAS_PATH || "/evcp_nas";

// 환경별 설정
function getStorageConfig(): FileStorageConfig {
  const isProduction = process.env.NODE_ENV === "production";
  
  if (isProduction) {
    return {
      baseDir: nasPath,
      publicUrl: "/api/files",
      isProduction: true,
    };
  } else {
    return {
      baseDir: path.join(process.cwd(), "public"),
      publicUrl: "",
      isProduction: false,
    };
  }
}

// 보안이 강화된 File 객체 저장 함수
export async function saveFile({
  file,
  directory,
  originalName,
  userId,
}: SaveFileOptions): Promise<SaveFileResult> {
  const finalFileName = originalName || file.name;
  
  // 초기 로깅
  FileUploadLogger.logUploadAttempt(finalFileName, file.size, directory, userId);
  
  try {
    const config = getStorageConfig();
    const securityChecks = {
      extensionCheck: false,
      fileNameCheck: false,
      sizeCheck: false,
      mimeTypeCheck: false,
      contentCheck: false,
    };

    // 1. 디렉터리 기본 안전성 검증
    const dirValidation = FileSecurityValidator.validateDirectory(directory);
    if (!dirValidation.valid) {
      FileUploadLogger.logSecurityViolation(finalFileName, `Directory: ${dirValidation.error}`, userId);
      return { success: false, error: dirValidation.error, securityChecks };
    }

    // 2. 파일 확장자 검증
    const extValidation = FileSecurityValidator.validateExtension(finalFileName);
    if (!extValidation.valid) {
      FileUploadLogger.logSecurityViolation(finalFileName, `Extension: ${extValidation.error}`, userId);
      return { success: false, error: extValidation.error, securityChecks };
    }
    securityChecks.extensionCheck = true;

    // 3. 파일명 안전성 검증
    const nameValidation = FileSecurityValidator.validateFileName(finalFileName);
    if (!nameValidation.valid) {
      FileUploadLogger.logSecurityViolation(finalFileName, `FileName: ${nameValidation.error}`, userId);
      return { success: false, error: nameValidation.error, securityChecks };
    }
    securityChecks.fileNameCheck = true;

    // 4. 파일 크기 검증
    const sizeValidation = FileSecurityValidator.validateFileSize(file.size);
    if (!sizeValidation.valid) {
      FileUploadLogger.logSecurityViolation(finalFileName, `Size: ${sizeValidation.error}`, userId);
      return { success: false, error: sizeValidation.error, securityChecks };
    }
    securityChecks.sizeCheck = true;

    // 5. MIME 타입 검증
    const mimeValidation = FileSecurityValidator.validateMimeType(file.type, finalFileName);
    if (!mimeValidation.valid) {
      FileUploadLogger.logSecurityViolation(finalFileName, `MIME: ${mimeValidation.error}`, userId);
      return { success: false, error: mimeValidation.error, securityChecks };
    }
    securityChecks.mimeTypeCheck = true;

    // 6. 파일 내용 추출 및 검증
    const arrayBuffer = await file.arrayBuffer();
    const dataBuffer = Buffer.from(arrayBuffer);

    const contentValidation = await FileSecurityValidator.validateFileContent(dataBuffer, finalFileName);
    if (!contentValidation.valid) {
      FileUploadLogger.logSecurityViolation(finalFileName, `Content: ${contentValidation.error}`, userId);
      return { success: false, error: contentValidation.error, securityChecks };
    }
    securityChecks.contentCheck = true;

    // 7. 안전한 파일명 전처리
    const safeOriginalName = sanitizeFileNameForStorage(finalFileName);
    const hashedFileName = generateHashedFileName(safeOriginalName);

    // 8. 저장 경로 설정
    const saveDir = path.join(config.baseDir, directory);
    const filePath = path.join(saveDir, hashedFileName);

    // 9. 웹 접근 경로
    let publicPath: string;
    if (config.isProduction) {
      publicPath = `${config.publicUrl}/${directory}/${hashedFileName}`;
    } else {
      publicPath = `/${directory}/${hashedFileName}`;
    }

    console.log(`📄 보안 검증 완료 - File 객체 저장: ${finalFileName}`);
    console.log(`📁 저장 위치: ${filePath}`);
    console.log(`🌐 웹 접근 경로: ${publicPath}`);

    // 10. 디렉토리 생성
    await fs.mkdir(saveDir, { recursive: true });

    // 11. 파일 저장
    await fs.writeFile(filePath, dataBuffer);

    // 12. 성공 로깅
    FileUploadLogger.logUploadSuccess(finalFileName, hashedFileName, file.size, directory, userId);

    return {
      success: true,
      filePath,
      publicPath,
      fileName: hashedFileName,
      originalName: finalFileName,
      fileSize: file.size,
      securityChecks,
    };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : "File 저장 중 오류가 발생했습니다.";
    FileUploadLogger.logUploadError(finalFileName, errorMessage, userId);
    return {
      success: false,
      error: errorMessage,
    };
  }
}

// 보안이 강화된 Buffer 저장 함수
export async function saveBuffer({
  buffer,
  fileName,
  directory,
  originalName,
  userId,
}: SaveBufferOptions): Promise<SaveFileResult> {
  const finalFileName = originalName || fileName;
  const dataBuffer = buffer instanceof ArrayBuffer ? Buffer.from(buffer) : buffer;
  
  // 초기 로깅
  FileUploadLogger.logUploadAttempt(finalFileName, dataBuffer.length, directory, userId);
  
  try {
    const config = getStorageConfig();
    const securityChecks = {
      extensionCheck: false,
      fileNameCheck: false,
      sizeCheck: false,
      mimeTypeCheck: true, // Buffer는 MIME 타입 검증 스킵
      contentCheck: false,
    };

    // 1. 디렉터리 기본 안전성 검증
    const dirValidation = FileSecurityValidator.validateDirectory(directory);
    if (!dirValidation.valid) {
      FileUploadLogger.logSecurityViolation(finalFileName, `Directory: ${dirValidation.error}`, userId);
      return { success: false, error: dirValidation.error, securityChecks };
    }

    // 2. 파일 확장자 검증
    const extValidation = FileSecurityValidator.validateExtension(finalFileName);
    if (!extValidation.valid) {
      FileUploadLogger.logSecurityViolation(finalFileName, `Extension: ${extValidation.error}`, userId);
      return { success: false, error: extValidation.error, securityChecks };
    }
    securityChecks.extensionCheck = true;

    // 3. 파일명 안전성 검증
    const nameValidation = FileSecurityValidator.validateFileName(finalFileName);
    if (!nameValidation.valid) {
      FileUploadLogger.logSecurityViolation(finalFileName, `FileName: ${nameValidation.error}`, userId);
      return { success: false, error: nameValidation.error, securityChecks };
    }
    securityChecks.fileNameCheck = true;

    // 4. 파일 크기 검증
    const sizeValidation = FileSecurityValidator.validateFileSize(dataBuffer.length);
    if (!sizeValidation.valid) {
      FileUploadLogger.logSecurityViolation(finalFileName, `Size: ${sizeValidation.error}`, userId);
      return { success: false, error: sizeValidation.error, securityChecks };
    }
    securityChecks.sizeCheck = true;

    // 5. 파일 내용 검증
    const contentValidation = await FileSecurityValidator.validateFileContent(dataBuffer, finalFileName);
    if (!contentValidation.valid) {
      FileUploadLogger.logSecurityViolation(finalFileName, `Content: ${contentValidation.error}`, userId);
      return { success: false, error: contentValidation.error, securityChecks };
    }
    securityChecks.contentCheck = true;

    // 6. 안전한 파일명 전처리
    const safeOriginalName = sanitizeFileNameForStorage(finalFileName);
    const hashedFileName = generateHashedFileName(safeOriginalName);

    // 7. 저장 경로 설정
    const saveDir = path.join(config.baseDir, directory);
    const filePath = path.join(saveDir, hashedFileName);

    // 8. 웹 접근 경로
    let publicPath: string;
    if (config.isProduction) {
      publicPath = `${config.publicUrl}/${directory}/${hashedFileName}`;
    } else {
      publicPath = `/${directory}/${hashedFileName}`;
    }

    console.log(`🔓 보안 검증 완료 - Buffer 저장: ${finalFileName}`);
    console.log(`📁 저장 위치: ${filePath}`);
    console.log(`🌐 웹 접근 경로: ${publicPath}`);

    // 9. 디렉토리 생성
    await fs.mkdir(saveDir, { recursive: true });

    // 10. 파일 저장
    await fs.writeFile(filePath, dataBuffer);

    // 11. 성공 로깅
    FileUploadLogger.logUploadSuccess(finalFileName, hashedFileName, dataBuffer.length, directory, userId);

    return {
      success: true,
      filePath,
      publicPath,
      fileName: hashedFileName,
      originalName: finalFileName,
      fileSize: dataBuffer.length,
      securityChecks,
    };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : "Buffer 저장 중 오류가 발생했습니다.";
    FileUploadLogger.logUploadError(finalFileName, errorMessage, userId);
    return {
      success: false,
      error: errorMessage,
    };
  }
}

// 업데이트 함수들 (보안 검증 포함)
export async function updateFile(
  options: SaveFileOptions,
  oldFilePath?: string
): Promise<SaveFileResult> {
  try {
    const result = await saveFile(options);
    
    if (result.success && oldFilePath) {
      await deleteFile(oldFilePath);
    }
    
    return result;
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : "File 업데이트 중 오류가 발생했습니다.";
    FileUploadLogger.logUploadError(options.originalName || options.file.name, errorMessage, options.userId);
    return { success: false, error: errorMessage };
  }
}

export async function updateBuffer(
  options: SaveBufferOptions,
  oldFilePath?: string
): Promise<SaveFileResult> {
  try {
    const result = await saveBuffer(options);
    
    if (result.success && oldFilePath) {
      await deleteFile(oldFilePath);
    }
    
    return result;
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : "Buffer 업데이트 중 오류가 발생했습니다.";
    FileUploadLogger.logUploadError(options.originalName || options.fileName, errorMessage, options.userId);
    return { success: false, error: errorMessage };
  }
}

// 안전한 파일 삭제 함수
export async function deleteFile(publicPath: string): Promise<boolean> {
  try {
    const config = getStorageConfig();
    
    let absolutePath: string;
    if (config.isProduction) {
      const relativePath = publicPath.replace('/api/files/', '');
      absolutePath = path.join(nasPath, relativePath);
    } else {
      absolutePath = path.join(process.cwd(), 'public', publicPath);
    }

    // 경로 안전성 검증
    const normalizedPath = path.normalize(absolutePath);
    if (normalizedPath.includes('..')) {
      console.error("🚨 위험한 파일 삭제 시도:", absolutePath);
      return false;
    }

    console.log(`🗑️ 파일 삭제: ${absolutePath}`);

    await fs.access(absolutePath);
    await fs.unlink(absolutePath);
    return true;
  } catch (error) {
    console.log("파일 삭제 실패 또는 파일이 없음:", error);
    return false;
  }
}

// 편의 함수들 (하위 호환성)
export const save = {
  file: saveFile,
  buffer: saveBuffer,
};

// DRM 워크플로우 통합 함수 (보안 강화)
export async function saveDRMFile(
  originalFile: File,
  decryptFunction: (file: File) => Promise<ArrayBuffer>,
  directory: string,
  userId?: string
): Promise<SaveFileResult> {
  try {
    console.log(`🔐 DRM 파일 처리 시작: ${originalFile.name}`);
    
    // 1. DRM 복호화
    const decryptedData = await decryptFunction(originalFile);
    
    // 2. 보안 검증과 함께 복호화된 데이터 저장
    const result = await saveBuffer({
      buffer: decryptedData,
      fileName: originalFile.name,
      directory,
      userId,
    });
    
    if (result.success) {
      console.log(`✅ DRM 파일 처리 완료: ${originalFile.name}`);
    }
    
    return result;
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : "DRM 파일 처리 중 오류가 발생했습니다.";
    console.error(`❌ DRM 파일 처리 실패: ${originalFile.name}`, error);
    FileUploadLogger.logUploadError(originalFile.name, errorMessage, userId);
    return { success: false, error: errorMessage };
  }
}

// 보안 설정 조회 함수
export function getSecurityConfig() {
  return {
    allowedExtensions: Array.from(SECURITY_CONFIG.ALLOWED_EXTENSIONS),
    forbiddenExtensions: Array.from(SECURITY_CONFIG.FORBIDDEN_EXTENSIONS),
    allowedMimeTypes: Array.from(SECURITY_CONFIG.ALLOWED_MIME_TYPES),
    maxFileSize: SECURITY_CONFIG.MAX_FILE_SIZE,
    maxFileSizeFormatted: FileUploadLogger['formatFileSize'](SECURITY_CONFIG.MAX_FILE_SIZE),
    maxFilenameLength: SECURITY_CONFIG.MAX_FILENAME_LENGTH,
  };
}

export async function saveFileStream({
  file,
  directory,
  originalName,
  userId,
}: SaveFileOptions): Promise<SaveFileResult> {
  const finalFileName = originalName || file.name
  
  try {
    console.log(`🚀 스트리밍 저장 시작: ${finalFileName}`)
    
    // 기본 보안 검증들 (확장자, 파일명 등)
    const extValidation = FileSecurityValidator.validateExtension(finalFileName)
    if (!extValidation.valid) {
      return { success: false, error: extValidation.error }
    }

    const nameValidation = FileSecurityValidator.validateFileName(finalFileName)
    if (!nameValidation.valid) {
      return { success: false, error: nameValidation.error }
    }

    const sizeValidation = FileSecurityValidator.validateFileSize(file.size)
    if (!sizeValidation.valid) {
      return { success: false, error: sizeValidation.error }
    }

    const config = getStorageConfig()
    const safeOriginalName = sanitizeFileNameForStorage(finalFileName)
    const hashedFileName = generateHashedFileName(safeOriginalName)
    
    const saveDir = path.join(config.baseDir, directory)
    const filePath = path.join(saveDir, hashedFileName)
    
    // 디렉토리 생성
    await fs.mkdir(saveDir, { recursive: true })
    
    // Node.js 스트림으로 변환하여 저장
    const nodeStream = Readable.fromWeb(file.stream() as ReadableStream)
    const writeStream = createWriteStream(filePath)
    
    // 스트림 파이프라인으로 메모리 효율적 저장
    await new Promise((resolve, reject) => {
      nodeStream.pipe(writeStream)
      writeStream.on('finish', resolve)
      writeStream.on('error', reject)
      nodeStream.on('error', reject)
    })

    console.log(`✅ 스트리밍 저장 완료: ${finalFileName}`)

    // 저장 후 첫 부분만 샘플링하여 내용 검증
    const contentValidation = await validateLargeFileContentSample(filePath, finalFileName)
    if (!contentValidation.valid) {
      await fs.unlink(filePath) // 검증 실패 시 파일 삭제
      return { success: false, error: contentValidation.error }
    }

    const publicPath = config.isProduction 
      ? `${config.publicUrl}/${directory}/${hashedFileName}`
      : `/${directory}/${hashedFileName}`

    return {
      success: true,
      filePath,
      publicPath,
      fileName: hashedFileName,
      originalName: finalFileName,
      fileSize: file.size,
    }

  } catch (error) {
    console.error(`❌ 스트리밍 저장 실패: ${finalFileName}`, error)
    return { 
      success: false, 
      error: error instanceof Error ? error.message : '스트리밍 저장 실패' 
    }
  }
}

// 4. 대용량 파일 샘플 검증
async function validateLargeFileContentSample(
  filePath: string, 
  fileName: string
): Promise<{ valid: boolean; error?: string }> {
  try {
    const fileHandle = await fs.open(filePath, 'r')
    
    // 파일 시작 부분 64KB만 읽어서 검증
    const sampleSize = Math.min(64 * 1024, (await fileHandle.stat()).size)
    const buffer = Buffer.allocUnsafe(sampleSize)
    const { bytesRead } = await fileHandle.read(buffer, 0, sampleSize, 0)
    await fileHandle.close()

    const sampleBuffer = buffer.subarray(0, bytesRead)
    return await FileSecurityValidator.validateFileContent(sampleBuffer, fileName)
  } catch (error) {
    console.error('파일 샘플 검증 실패:', error)
    return { valid: false, error: '파일 내용 검증 실패' }
  }
}