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
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
/**
 *  Secure Build Script - Fort-Knox Level Security
 * 
 * สคริปต์สร้างแอปแบบปลอดภัยสูงสุด รวม:
 * 1. Code Obfuscation - ทำให้โค้ดอ่านยาก
 * 2. Integrity Verification - ตรวจสอบความครบถ้วน
 * 3. Digital Signature - ลงลายเซ็นดิจิทัล
 * 4. Anti-Tampering Protection - ป้องกันการแก้ไข
 */

const fs = require('fs');
const path = require('path');
const { exec, spawn } = require('child_process');
const crypto = require('crypto');
const JavaScriptObfuscator = require('javascript-obfuscator');

// โหลด configuration
const obfuscatorConfig = require('../config/obfuscator.config.js');

class SecureBuildSystem {
    constructor() {
        this.projectRoot = path.resolve(__dirname, '..');
        this.buildDir = path.join(this.projectRoot, 'dist');
        this.tempDir = path.join(this.projectRoot, 'temp_secure_build');
        this.backupDir = path.join(this.projectRoot, 'backup_original');
        
        // ไฟล์ที่ต้อง obfuscate
        this.filesToObfuscate = [
            'main.js',
            'validation_gateway.js',
            'debug-manager.js',
            'preload.js',
            'debugger.js',
            'modules*.js',
            'backend*.js'
        ];
        
        // ไฟล์ที่ไม่ควร obfuscate
        this.excludeFromObfuscation = [
            'node_modules/**',
            'test/**',
            'tests/**',
            'spec/**',
            '**/*.test.js',
            '**/*.spec.js',
            'vendor/**',
            'build_assets/**',
            'plugins/**', // ปลั๊กอินอาจมีปัญหาถ้าโดน obfuscate
            'generate-*.js'
        ];

        console.log(' Secure Build System initialized');
    }

    /**
     * เริ่มขั้นตอนการ build แบบปลอดภัย
     */
    async startSecureBuild() {
        try {
            console.log(' Starting Fort-Knox Level Secure Build Process...');
            console.log('='.repeat(60));
            
            // 1. เตรียมการ
            await this.prepareBuildEnvironment();
            
            // 2. สำรองไฟล์ต้นฉบับ
            await this.backupOriginalFiles();
            
            // 3. Obfuscate code
            await this.obfuscateCode();
            
            // 4. Generate checksums และ signature
            await this.generateSecurityFiles();
            
            // 5. Copy user guides and documentation
            await this.copyUserDocumentation();
            
            // 6. Build Electron app
            await this.buildElectronApp();
            
            // 7. Post-build security verification
            await this.verifyBuildSecurity();
            
            // 7. Restore original files
            await this.restoreOriginalFiles();
            
            console.log(' Fort-Knox Level Secure Build completed successfully!');
            this.printBuildSummary();
            
        } catch (error) {
            console.error(' Secure Build failed:', error.message);
            
            // Restore files ในกรณีที่ build ล้มเหลว
            try {
                await this.restoreOriginalFiles();
            } catch (restoreError) {
                console.error(' Failed to restore original files:', restoreError.message);
            }
            
            process.exit(1);
        }
    }

    /**
     * เตรียมสภาพแวดล้อมสำหรับ build
     */
    async prepareBuildEnvironment() {
        console.log(' Preparing build environment...');
        
        // สร้างโฟลเดอร์ temp และ backup
        if (fs.existsSync(this.tempDir)) {
            fs.rmSync(this.tempDir, { recursive: true, force: true });
        }
        fs.mkdirSync(this.tempDir, { recursive: true });
        
        if (fs.existsSync(this.backupDir)) {
            fs.rmSync(this.backupDir, { recursive: true, force: true });
        }
        fs.mkdirSync(this.backupDir, { recursive: true });
        
        // ตรวจสอบ dependencies
        await this.checkDependencies();
        
        console.log(' Build environment prepared');
    }

    /**
     * ตรวจสอบ dependencies ที่จำเป็น
     */
    async checkDependencies() {
        const requiredPackages = [
            'javascript-obfuscator',
            'electron-builder'
        ];
        
        for (const pkg of requiredPackages) {
            try {
                require.resolve(pkg);
                console.log(` ${pkg} found`);
            } catch (error) {
                throw new Error(`Missing required package: ${pkg}. Run: npm install ${pkg}`);
            }
        }
    }

    /**
     * สำรองไฟล์ต้นฉบับ
     */
    async backupOriginalFiles() {
        console.log(' Backing up original files...');
        
        for (const filePattern of this.filesToObfuscate) {
            const files = await this.globFiles(filePattern);
            
            for (const file of files) {
                if (fs.existsSync(file)) {
                    const relativePath = path.relative(this.projectRoot, file);
                    const backupPath = path.join(this.backupDir, relativePath);
                    
                    // สร้างโฟลเดอร์ถ้าไม่มี
                    fs.mkdirSync(path.dirname(backupPath), { recursive: true });
                    
                    // Copy file
                    fs.copyFileSync(file, backupPath);
                    console.log(` Backed up: ${relativePath}`);
                }
            }
        }
        
        console.log(' Original files backed up');
    }

    /**
     * Obfuscate โค้ด JavaScript
     */
    async obfuscateCode() {
        console.log(' Starting code obfuscation...');
        
        let obfuscatedCount = 0;
        
        for (const filePattern of this.filesToObfuscate) {
            const files = await this.globFiles(filePattern);
            
            for (const file of files) {
                if (fs.existsSync(file) && !this.shouldExcludeFromObfuscation(file)) {
                    try {
                        await this.obfuscateFile(file);
                        obfuscatedCount++;
                    } catch (error) {
                        console.warn(` Failed to obfuscate ${file}: ${error.message}`);
                    }
                }
            }
        }
        
        console.log(` Code obfuscation completed (${obfuscatedCount} files processed)`);
    }

    /**
     * Obfuscate ไฟล์เดียว
     */
    async obfuscateFile(filePath) {
        const relativePath = path.relative(this.projectRoot, filePath);
        console.log(` Obfuscating: ${relativePath}`);
        
        // อ่านไฟล์ต้นฉบับ
        const originalCode = fs.readFileSync(filePath, 'utf8');
        
        // Obfuscate ด้วย configuration ที่กำหนด
        const obfuscationResult = JavaScriptObfuscator.obfuscate(originalCode, {
            ...obfuscatorConfig,
            sourceMap: false, // ไม่ต้องการ source map ใน production
            inputFileName: path.basename(filePath)
            // ลบ sourceMapFileName ออกเพราะทำให้เกิด error
        });
        
        // เขียนไฟล์ที่ obfuscate แล้วทับของเดิม
        fs.writeFileSync(filePath, obfuscationResult.getObfuscatedCode());
        
        // แสดงสถิติ
        const originalSize = Buffer.byteLength(originalCode, 'utf8');
        const obfuscatedSize = Buffer.byteLength(obfuscationResult.getObfuscatedCode(), 'utf8');
        const sizeIncrease = ((obfuscatedSize - originalSize) / originalSize * 100).toFixed(1);
        
        console.log(`   Size: ${originalSize}  ${obfuscatedSize} bytes (+${sizeIncrease}%)`);
    }

    /**
     * ตรวจสอบว่าไฟล์ควรถูกยกเว้นจาก obfuscation หรือไม่
     */
    shouldExcludeFromObfuscation(filePath) {
        const relativePath = path.relative(this.projectRoot, filePath).replace(/\\/g, '/');
        
        for (const excludePattern of this.excludeFromObfuscation) {
            if (this.matchPattern(relativePath, excludePattern)) {
                return true;
            }
        }
        
        return false;
    }

    /**
     * สร้างไฟล์ความปลอดภัย (checksums และ signature)
     */
    async generateSecurityFiles() {
        console.log(' Generating security files...');
        
        // รัน generate-checksums.js
        await this.runCommand('node generate-checksums.js');
        
        console.log(' Security files generated');
    }

    /**
     * Build Electron app
     */
    async buildElectronApp() {
        console.log(' Building Electron application...');
        
        // รันคำสั่ง electron-builder
        await this.runCommand('npm run build-msi');
        
        console.log(' Electron app built successfully');
    }

    /**
     * ตรวจสอบความปลอดภัยหลัง build
     */
    async verifyBuildSecurity() {
        console.log(' Verifying build security...');
        
        // ตรวจสอบว่าไฟล์ที่สำคัญถูก obfuscate แล้ว
        const mainJsPath = path.join(this.projectRoot, 'main.js');
        if (fs.existsSync(mainJsPath)) {
            const content = fs.readFileSync(mainJsPath, 'utf8');
            
            // ตรวจสอบว่าโค้ดถูก obfuscate แล้ว (มี pattern ของ obfuscated code)
            const hasObfuscatedPattern = (
                content.includes('_0x') || // Hexadecimal identifiers
                content.includes('var _') || // Obfuscated variables
                content.length < 1000 || // Code เป็น one-liner
                !/function\s+\w+/.test(content) // ไม่มี readable function names
            );
            
            if (hasObfuscatedPattern) {
                console.log(' Code obfuscation verified');
            } else {
                console.warn(' Code may not be properly obfuscated');
            }
        }
        
        // ตรวจสอบว่ามีไฟล์ checksums
        const checksumsPath = path.join(this.projectRoot, 'checksums.json');
        const signaturePath = path.join(this.projectRoot, 'checksums.sig');
        
        if (fs.existsSync(checksumsPath) && fs.existsSync(signaturePath)) {
            console.log(' Integrity verification files present');
        } else {
            throw new Error('Missing integrity verification files');
        }
        
        console.log(' Build security verification completed');
    }

    /**
     * กู้คืนไฟล์ต้นฉบับ
     */
    async restoreOriginalFiles() {
        console.log(' Restoring original files...');
        
        if (!fs.existsSync(this.backupDir)) {
            console.log('ℹ No backup directory found, skipping restore');
            return;
        }
        
        // Copy ไฟล์จาก backup กลับมา
        await this.copyDirectory(this.backupDir, this.projectRoot);
        
        // ลบโฟลเดอร์ backup และ temp
        fs.rmSync(this.backupDir, { recursive: true, force: true });
        fs.rmSync(this.tempDir, { recursive: true, force: true });
        
        console.log(' Original files restored');
    }

    /**
     * แสดงสรุปผลการ build
     */
    printBuildSummary() {
        console.log('\n' + '='.repeat(60));
        console.log(' FORT-KNOX LEVEL SECURE BUILD COMPLETED');
        console.log('='.repeat(60));
        console.log(' Security Features Applied:');
        console.log('   Code Obfuscation (Maximum Level)');
        console.log('   Anti-Debugging Protection');
        console.log('   IPC Command Sanitization');
        console.log('   Digital Signature Verification');
        console.log('   File Integrity Checking');
        console.log('');
        console.log(' Build Output:');
        console.log(`   ${this.buildDir}`);
        console.log('');
        console.log('  IMPORTANT:');
        console.log('  - Keep private_key.pem safe and secure');
        console.log('  - Test the built app thoroughly');
        console.log('  - The obfuscated version may run 5-15% slower');
        console.log('  - Anti-debugging will trigger in production mode');
        console.log('='.repeat(60));
    }

    // ===== HELPER METHODS =====

    async runCommand(command) {
        return new Promise((resolve, reject) => {
            console.log(` Running: ${command}`);
            exec(command, { cwd: this.projectRoot }, (error, stdout, stderr) => {
                if (error) {
                    console.error(` Command failed: ${error.message}`);
                    reject(error);
                } else {
                    if (stdout) console.log(stdout);
                    if (stderr) console.warn(stderr);
                    resolve({ stdout, stderr });
                }
            });
        });
    }

    async globFiles(pattern) {
        // Simple glob implementation
        const basePath = this.projectRoot;
        
        if (pattern.includes('**')) {
            // Recursive pattern
            const prefix = pattern.split('**')[0];
            const suffix = pattern.split('**')[1].replace('/', '');
            return this.findFilesRecursive(path.join(basePath, prefix), suffix);
        } else {
            // Direct file
            const filePath = path.join(basePath, pattern);
            return fs.existsSync(filePath) ? [filePath] : [];
        }
    }

    findFilesRecursive(dir, suffix) {
        const results = [];
        
        if (!fs.existsSync(dir)) return results;
        
        const items = fs.readdirSync(dir, { withFileTypes: true });
        
        for (const item of items) {
            const fullPath = path.join(dir, item.name);
            
            if (item.isDirectory()) {
                results.push(...this.findFilesRecursive(fullPath, suffix));
            } else if (item.name.endsWith(suffix)) {
                results.push(fullPath);
            }
        }
        
        return results;
    }

    matchPattern(path, pattern) {
        // Simple pattern matching
        const regexPattern = pattern
            .replace(/\*\*/g, '.*')
            .replace(/\*/g, '[^/]*')
            .replace(/\./g, '\\.');
        
        return new RegExp(`^${regexPattern}$`).test(path);
    }

    async copyDirectory(src, dest) {
        const items = fs.readdirSync(src, { withFileTypes: true });
        
        for (const item of items) {
            const srcPath = path.join(src, item.name);
            const destPath = path.join(dest, item.name);
            
            if (item.isDirectory()) {
                fs.mkdirSync(destPath, { recursive: true });
                await this.copyDirectory(srcPath, destPath);
            } else {
                fs.mkdirSync(path.dirname(destPath), { recursive: true });
                fs.copyFileSync(srcPath, destPath);
            }
        }
    }
    
    /**
     *  คัดลอกไฟล์คู่มือและเอกสารผู้ใช้
     */
    async copyUserDocumentation() {
        console.log(' Copying user documentation...');
        
        const documentationFiles = [
            {
                src: path.join(this.projectRoot, 'build_assets', 'plugins', 'USER_GUIDE_EN.md'),
                dest: path.join(this.projectRoot, 'USER_GUIDE_EN.md')
            },
            {
                src: path.join(this.projectRoot, 'build_assets', 'plugins', 'USER_GUIDE_TH.md'),
                dest: path.join(this.projectRoot, 'USER_GUIDE_TH.md')
            }
        ];
        
        let copiedCount = 0;
        
        for (const { src, dest } of documentationFiles) {
            try {
                if (fs.existsSync(src)) {
                    // สร้างโฟลเดอร์ปลายทางถ้ายังไม่มี
                    fs.mkdirSync(path.dirname(dest), { recursive: true });
                    
                    // คัดลอกไฟล์
                    fs.copyFileSync(src, dest);
                    console.log(`   Copied: ${path.basename(src)}  ${path.relative(this.projectRoot, dest)}`);
                    copiedCount++;
                } else {
                    console.log(`    Source not found: ${path.relative(this.projectRoot, src)}`);
                }
            } catch (error) {
                console.error(`   Failed to copy ${path.basename(src)}: ${error.message}`);
            }
        }
        
        if (copiedCount > 0) {
            console.log(` Documentation copied successfully (${copiedCount} files)`);
        } else {
            console.log('  No documentation files were copied');
        }
    }
}

// รันสคริปต์ถ้าถูกเรียกใช้โดยตรง
if (require.main === module) {
    const buildSystem = new SecureBuildSystem();
    buildSystem.startSecureBuild().catch(console.error);
}

module.exports = SecureBuildSystem;