@dimzxzzx07/file-watcher 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/.env +13 -0
  2. package/.eslintrc.json +128 -0
  3. package/.prettierrc +18 -0
  4. package/Dimzxzzx07.png +0 -0
  5. package/README.md +1024 -0
  6. package/dist/core/BackupManager.d.ts +25 -0
  7. package/dist/core/BackupManager.d.ts.map +1 -0
  8. package/dist/core/BackupManager.js +290 -0
  9. package/dist/core/BackupManager.js.map +1 -0
  10. package/dist/core/IntegrityValidator.d.ts +18 -0
  11. package/dist/core/IntegrityValidator.d.ts.map +1 -0
  12. package/dist/core/IntegrityValidator.js +212 -0
  13. package/dist/core/IntegrityValidator.js.map +1 -0
  14. package/dist/core/SecurityManager.d.ts +40 -0
  15. package/dist/core/SecurityManager.d.ts.map +1 -0
  16. package/dist/core/SecurityManager.js +320 -0
  17. package/dist/core/SecurityManager.js.map +1 -0
  18. package/dist/core/WatcherEngine.d.ts +44 -0
  19. package/dist/core/WatcherEngine.d.ts.map +1 -0
  20. package/dist/core/WatcherEngine.js +470 -0
  21. package/dist/core/WatcherEngine.js.map +1 -0
  22. package/dist/crypto/HashGenerator.d.ts +26 -0
  23. package/dist/crypto/HashGenerator.d.ts.map +1 -0
  24. package/dist/crypto/HashGenerator.js +220 -0
  25. package/dist/crypto/HashGenerator.js.map +1 -0
  26. package/dist/crypto/KeyManager.d.ts +30 -0
  27. package/dist/crypto/KeyManager.d.ts.map +1 -0
  28. package/dist/crypto/KeyManager.js +235 -0
  29. package/dist/crypto/KeyManager.js.map +1 -0
  30. package/dist/crypto/SignatureValidator.d.ts +11 -0
  31. package/dist/crypto/SignatureValidator.d.ts.map +1 -0
  32. package/dist/crypto/SignatureValidator.js +102 -0
  33. package/dist/crypto/SignatureValidator.js.map +1 -0
  34. package/dist/detectors/AnomalyDetector.d.ts +24 -0
  35. package/dist/detectors/AnomalyDetector.d.ts.map +1 -0
  36. package/dist/detectors/AnomalyDetector.js +209 -0
  37. package/dist/detectors/AnomalyDetector.js.map +1 -0
  38. package/dist/detectors/InjectionDetector.d.ts +14 -0
  39. package/dist/detectors/InjectionDetector.d.ts.map +1 -0
  40. package/dist/detectors/InjectionDetector.js +204 -0
  41. package/dist/detectors/InjectionDetector.js.map +1 -0
  42. package/dist/detectors/PatternMatcher.d.ts +28 -0
  43. package/dist/detectors/PatternMatcher.d.ts.map +1 -0
  44. package/dist/detectors/PatternMatcher.js +283 -0
  45. package/dist/detectors/PatternMatcher.js.map +1 -0
  46. package/dist/guards/FileGuard.d.ts +35 -0
  47. package/dist/guards/FileGuard.d.ts.map +1 -0
  48. package/dist/guards/FileGuard.js +357 -0
  49. package/dist/guards/FileGuard.js.map +1 -0
  50. package/dist/guards/MemoryGuard.d.ts +28 -0
  51. package/dist/guards/MemoryGuard.d.ts.map +1 -0
  52. package/dist/guards/MemoryGuard.js +256 -0
  53. package/dist/guards/MemoryGuard.js.map +1 -0
  54. package/dist/guards/ProcessGuard.d.ts +25 -0
  55. package/dist/guards/ProcessGuard.d.ts.map +1 -0
  56. package/dist/guards/ProcessGuard.js +221 -0
  57. package/dist/guards/ProcessGuard.js.map +1 -0
  58. package/dist/index.d.ts +19 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +186 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/types/index.d.ts +69 -0
  63. package/dist/types/index.d.ts.map +1 -0
  64. package/dist/types/index.js +3 -0
  65. package/dist/types/index.js.map +1 -0
  66. package/dist/utils/Constants.d.ts +407 -0
  67. package/dist/utils/Constants.d.ts.map +1 -0
  68. package/dist/utils/Constants.js +505 -0
  69. package/dist/utils/Constants.js.map +1 -0
  70. package/dist/utils/Logger.d.ts +45 -0
  71. package/dist/utils/Logger.d.ts.map +1 -0
  72. package/dist/utils/Logger.js +285 -0
  73. package/dist/utils/Logger.js.map +1 -0
  74. package/dist/utils/Validator.d.ts +27 -0
  75. package/dist/utils/Validator.d.ts.map +1 -0
  76. package/dist/utils/Validator.js +245 -0
  77. package/dist/utils/Validator.js.map +1 -0
  78. package/favicon.png +0 -0
  79. package/jest.config.js +69 -0
  80. package/package.json +69 -0
  81. package/src/core/BackupManager.ts +305 -0
  82. package/src/core/IntegrityValidator.ts +200 -0
  83. package/src/core/SecurityManager.ts +348 -0
  84. package/src/core/WatcherEngine.ts +537 -0
  85. package/src/crypto/HashGenerator.ts +234 -0
  86. package/src/crypto/KeyManager.ts +249 -0
  87. package/src/crypto/SignatureValidator.ts +76 -0
  88. package/src/detectors/AnomalyDetector.ts +247 -0
  89. package/src/detectors/InjectionDetector.ts +233 -0
  90. package/src/detectors/PatternMatcher.ts +319 -0
  91. package/src/guards/FileGuard.ts +385 -0
  92. package/src/guards/MemoryGuard.ts +263 -0
  93. package/src/guards/ProcessGuard.ts +219 -0
  94. package/src/index.ts +189 -0
  95. package/src/types/index.ts +72 -0
  96. package/src/utils/Constants.ts +532 -0
  97. package/src/utils/Logger.ts +279 -0
  98. package/src/utils/Validator.ts +248 -0
  99. package/tests/setup.ts +80 -0
  100. package/tsconfig.json +42 -0
@@ -0,0 +1,263 @@
1
+ import * as crypto from 'crypto';
2
+ import * as v8 from 'v8';
3
+ import { Logger } from '../utils/Logger';
4
+
5
+ export class MemoryGuard {
6
+ private static instance: MemoryGuard;
7
+ private readonly logger: Logger;
8
+ private readonly memorySnapshots: Map<string, Buffer>;
9
+ private readonly secureHeap: Map<string, Buffer>;
10
+ private isCompromised: boolean = false;
11
+ private readonly encryptionKey: Buffer;
12
+
13
+ private constructor() {
14
+ this.logger = Logger.getInstance();
15
+ this.memorySnapshots = new Map();
16
+ this.secureHeap = new Map();
17
+ this.encryptionKey = crypto.randomBytes(32);
18
+
19
+ this.initializeSecureHeap();
20
+ this.startMemoryMonitoring();
21
+ }
22
+
23
+ public static getInstance(): MemoryGuard {
24
+ if (!MemoryGuard.instance) {
25
+ MemoryGuard.instance = new MemoryGuard();
26
+ }
27
+ return MemoryGuard.instance;
28
+ }
29
+
30
+ private initializeSecureHeap(): void {
31
+ const secureSize = 64 * 1024 * 1024;
32
+ const secureBuffer = Buffer.alloc(secureSize);
33
+
34
+ crypto.randomFillSync(secureBuffer);
35
+
36
+ this.secureHeap.set('secure_region', secureBuffer);
37
+
38
+ this.lockMemory(secureBuffer);
39
+ }
40
+
41
+ private lockMemory(buffer: Buffer): void {
42
+ try {
43
+ if (process.platform === 'linux') {
44
+ const mlock = require('mlock');
45
+ mlock(buffer);
46
+ }
47
+ } catch (error) {
48
+ this.logger.warning('Failed to lock memory', { error });
49
+ }
50
+ }
51
+
52
+ private startMemoryMonitoring(): void {
53
+ this.takeMemorySnapshot('baseline');
54
+
55
+ setInterval(() => {
56
+ this.checkMemoryIntegrity();
57
+ }, 30000);
58
+ }
59
+
60
+ public takeMemorySnapshot(name: string): void {
61
+ try {
62
+ const snapshot = v8.getHeapSnapshot();
63
+ const chunks: Buffer[] = [];
64
+
65
+ snapshot.on('data', (chunk) => chunks.push(chunk));
66
+ snapshot.on('end', () => {
67
+ const fullSnapshot = Buffer.concat(chunks);
68
+
69
+ const encrypted = this.encryptSnapshot(fullSnapshot);
70
+ this.memorySnapshots.set(name, encrypted);
71
+
72
+ if (this.memorySnapshots.size > 5) {
73
+ const oldest = Array.from(this.memorySnapshots.keys())[0];
74
+ if (oldest) {
75
+ this.memorySnapshots.delete(oldest);
76
+ }
77
+ }
78
+ });
79
+
80
+ snapshot.on('error', (error) => {
81
+ this.logger.error('Failed to take memory snapshot', { error });
82
+ });
83
+ } catch (error) {
84
+ this.logger.error('Error taking memory snapshot', { error });
85
+ }
86
+ }
87
+
88
+ private encryptSnapshot(snapshot: Buffer): Buffer {
89
+ const iv = crypto.randomBytes(16);
90
+ const cipher = crypto.createCipheriv('aes-256-gcm', this.encryptionKey, iv);
91
+
92
+ const encrypted = Buffer.concat([
93
+ cipher.update(snapshot),
94
+ cipher.final()
95
+ ]);
96
+
97
+ const authTag = cipher.getAuthTag();
98
+
99
+ return Buffer.concat([iv, authTag, encrypted]);
100
+ }
101
+
102
+ private checkMemoryIntegrity(): void {
103
+ const currentMemory = process.memoryUsage();
104
+
105
+ this.checkHeapAnomalies(currentMemory);
106
+ this.checkStackIntegrity();
107
+ this.checkSecureHeap();
108
+ this.checkForDebugger();
109
+ }
110
+
111
+ private checkHeapAnomalies(memory: NodeJS.MemoryUsage): void {
112
+ const heapUsed = memory.heapUsed;
113
+ const heapTotal = memory.heapTotal;
114
+ const ratio = heapUsed / heapTotal;
115
+
116
+ if (ratio > 0.95) {
117
+ this.logger.warning('Critical heap usage detected', {
118
+ used: heapUsed,
119
+ total: heapTotal,
120
+ ratio
121
+ });
122
+ }
123
+ }
124
+
125
+ private checkStackIntegrity(): void {
126
+ try {
127
+ const stack = new Error().stack;
128
+
129
+ if (!stack) {
130
+ this.logger.warning('Stack trace unavailable');
131
+ return;
132
+ }
133
+
134
+ const frames = stack.split('\n');
135
+
136
+ const hasEval = frames.some(frame => frame.includes('eval'));
137
+ if (hasEval) {
138
+ this.logger.warning('Eval detected in stack trace');
139
+ }
140
+
141
+ if (frames.length > 100) {
142
+ this.logger.warning('Excessive stack depth', { depth: frames.length });
143
+ }
144
+ } catch (error) {
145
+ this.logger.error('Stack integrity check failed', { error });
146
+ }
147
+ }
148
+
149
+ private checkSecureHeap(): void {
150
+ const secureRegion = this.secureHeap.get('secure_region');
151
+ if (!secureRegion) {
152
+ this.logger.critical('Secure heap region missing!');
153
+ this.terminateCompromised();
154
+ return;
155
+ }
156
+
157
+ const checksum = this.calculateChecksum(secureRegion);
158
+ const storedChecksum = this.secureHeap.get('secure_checksum')?.toString();
159
+
160
+ if (storedChecksum && checksum !== storedChecksum) {
161
+ this.logger.critical('Secure heap tampering detected!');
162
+ this.terminateCompromised();
163
+ } else {
164
+ this.secureHeap.set('secure_checksum', Buffer.from(checksum));
165
+ }
166
+ }
167
+
168
+ private checkForDebugger(): void {
169
+ const debugIndicators = [
170
+ process.execArgv.some(arg => arg.includes('--inspect')),
171
+ process.execArgv.some(arg => arg.includes('--debug')),
172
+ process.env.NODE_OPTIONS?.includes('--inspect'),
173
+ process.env.NODE_OPTIONS?.includes('--debug'),
174
+ process.argv.some(arg => arg.includes('--inspect')),
175
+ process.argv.some(arg => arg.includes('--debug'))
176
+ ];
177
+
178
+ if (debugIndicators.some(Boolean)) {
179
+ this.logger.warning('Debugger detected in memory check');
180
+ }
181
+ }
182
+
183
+ public protectSensitiveData(data: Buffer): Buffer {
184
+ const id = crypto.randomBytes(16).toString('hex');
185
+ const iv = crypto.randomBytes(16);
186
+
187
+ const cipher = crypto.createCipheriv('aes-256-gcm', this.encryptionKey, iv);
188
+ const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
189
+ const authTag = cipher.getAuthTag();
190
+
191
+ const protectedData = Buffer.concat([iv, authTag, encrypted]);
192
+ this.secureHeap.set(id, protectedData);
193
+
194
+ return Buffer.from(id);
195
+ }
196
+
197
+ public retrieveSensitiveData(id: Buffer): Buffer | null {
198
+ const protectedData = this.secureHeap.get(id.toString());
199
+ if (!protectedData) return null;
200
+
201
+ const iv = protectedData.subarray(0, 16);
202
+ const authTag = protectedData.subarray(16, 32);
203
+ const encrypted = protectedData.subarray(32);
204
+
205
+ try {
206
+ const decipher = crypto.createDecipheriv('aes-256-gcm', this.encryptionKey, iv);
207
+ decipher.setAuthTag(authTag);
208
+
209
+ return Buffer.concat([
210
+ decipher.update(encrypted),
211
+ decipher.final()
212
+ ]);
213
+ } catch {
214
+ return null;
215
+ }
216
+ }
217
+
218
+ public wipeSensitiveData(id: Buffer): void {
219
+ const key = id.toString();
220
+ const data = this.secureHeap.get(key);
221
+
222
+ if (data) {
223
+ crypto.randomFillSync(data);
224
+ this.secureHeap.delete(key);
225
+ }
226
+ }
227
+
228
+ public forceGarbageCollection(): void {
229
+ if (global.gc) {
230
+ global.gc();
231
+ this.logger.debug('Garbage collection forced');
232
+ }
233
+ }
234
+
235
+ private calculateChecksum(data: Buffer): string {
236
+ return crypto.createHash('sha256')
237
+ .update(data)
238
+ .digest('hex');
239
+ }
240
+
241
+ private terminateCompromised(): void {
242
+ if (this.isCompromised) return;
243
+
244
+ this.isCompromised = true;
245
+ this.logger.emergency('Memory compromised - terminating process');
246
+
247
+ this.secureHeap.clear();
248
+
249
+ this.forceGarbageCollection();
250
+
251
+ process.kill(process.pid, 'SIGKILL');
252
+ }
253
+
254
+ public getStatus(): any {
255
+ return {
256
+ isCompromised: this.isCompromised,
257
+ secureHeapSize: this.secureHeap.size,
258
+ snapshotsCount: this.memorySnapshots.size,
259
+ memoryUsage: process.memoryUsage(),
260
+ heapStats: v8.getHeapStatistics()
261
+ };
262
+ }
263
+ }
@@ -0,0 +1,219 @@
1
+ import * as process from 'process';
2
+ import { Logger } from '../utils/Logger';
3
+
4
+ export class ProcessGuard {
5
+ private static instance: ProcessGuard;
6
+ private readonly logger: Logger;
7
+ private readonly originalEnv: NodeJS.ProcessEnv;
8
+ private readonly protectedProperties: Set<string>;
9
+ private memorySnapshots: Map<string, Buffer>;
10
+ private isCompromised: boolean = false;
11
+
12
+ private constructor() {
13
+ this.logger = Logger.getInstance();
14
+ this.originalEnv = { ...process.env };
15
+ this.protectedProperties = new Set([
16
+ 'argv', 'execPath', 'execArgv', 'pid', 'ppid',
17
+ 'title', 'version', 'versions', 'arch', 'platform',
18
+ 'release', 'features', 'moduleLoadList'
19
+ ]);
20
+ this.memorySnapshots = new Map();
21
+
22
+ this.freezeProcess();
23
+ this.monitorMemory();
24
+ this.hookSystemCalls();
25
+ }
26
+
27
+ public static getInstance(): ProcessGuard {
28
+ if (!ProcessGuard.instance) {
29
+ ProcessGuard.instance = new ProcessGuard();
30
+ }
31
+ return ProcessGuard.instance;
32
+ }
33
+
34
+ public protectProcess(): void {
35
+ this.logger.info('ProcessGuard initialized');
36
+
37
+ this.preventDebugger();
38
+
39
+ this.protectEnvironment();
40
+
41
+ this.monitorAnomalies();
42
+ }
43
+
44
+ private freezeProcess(): void {
45
+ Object.keys(process).forEach(key => {
46
+ if (this.protectedProperties.has(key)) {
47
+ try {
48
+ Object.defineProperty(process, key, {
49
+ configurable: false,
50
+ enumerable: true,
51
+ writable: false
52
+ });
53
+ } catch (error) {
54
+ this.logger.warning(`Failed to freeze process.${key}`, { error });
55
+ }
56
+ }
57
+ });
58
+
59
+ Object.seal(process);
60
+ }
61
+
62
+ private preventDebugger(): void {
63
+ const checkDebugger = () => {
64
+ if (this.detectDebugger()) {
65
+ this.logger.critical('Debugger detected!');
66
+ this.terminateCompromised();
67
+ }
68
+ };
69
+
70
+ setInterval(checkDebugger, 1000);
71
+ checkDebugger();
72
+ }
73
+
74
+ public detectDebugger(): boolean {
75
+ const debugIndicators = [
76
+ process.execArgv.some(arg => arg.includes('--inspect')),
77
+ process.execArgv.some(arg => arg.includes('--debug')),
78
+ process.env.NODE_OPTIONS?.includes('--inspect'),
79
+ process.env.NODE_OPTIONS?.includes('--debug'),
80
+ process.argv.some(arg => arg.includes('--inspect')),
81
+ process.argv.some(arg => arg.includes('--debug')),
82
+ process.argv.some(arg => arg.includes('debug'))
83
+ ];
84
+
85
+ return debugIndicators.some(Boolean);
86
+ }
87
+
88
+ private protectEnvironment(): void {
89
+ Object.keys(process.env).forEach(key => {
90
+ try {
91
+ Object.defineProperty(process.env, key, {
92
+ configurable: false,
93
+ writable: false
94
+ });
95
+ } catch (error) {
96
+ }
97
+ });
98
+
99
+ setInterval(() => {
100
+ const currentEnv = { ...process.env };
101
+
102
+ for (const [key, value] of Object.entries(currentEnv)) {
103
+ if (this.originalEnv[key] !== value) {
104
+ this.logger.critical('Environment variable modified!', { key });
105
+ this.terminateCompromised();
106
+ }
107
+ }
108
+
109
+ for (const key of Object.keys(currentEnv)) {
110
+ if (!this.originalEnv.hasOwnProperty(key)) {
111
+ this.logger.critical('New environment variable detected!', { key });
112
+ this.terminateCompromised();
113
+ }
114
+ }
115
+ }, 5000);
116
+ }
117
+
118
+ private monitorMemory(): void {
119
+ setInterval(() => {
120
+ this.takeMemorySnapshot();
121
+ }, 60000);
122
+
123
+ setInterval(() => {
124
+ this.validateMemoryIntegrity();
125
+ }, 10000);
126
+ }
127
+
128
+ private takeMemorySnapshot(): void {
129
+ return;
130
+ }
131
+
132
+ public validateMemoryIntegrity(): void {
133
+ const memoryUsage = process.memoryUsage();
134
+
135
+ const heapUsed = memoryUsage.heapUsed;
136
+ const heapTotal = memoryUsage.heapTotal;
137
+ const ratio = heapUsed / heapTotal;
138
+
139
+ if (ratio > 0.95) {
140
+ this.logger.warning('High memory usage detected', { ratio });
141
+ }
142
+ }
143
+
144
+ private hookSystemCalls(): void {
145
+ const fs = require('fs');
146
+ const originalReadFile = fs.readFile;
147
+ const originalWriteFile = fs.writeFile;
148
+
149
+ fs.readFile = function(...args: any[]) {
150
+ Logger.getInstance().debug('File read', { file: args[0] });
151
+ return originalReadFile.apply(this, args);
152
+ };
153
+
154
+ fs.writeFile = function(...args: any[]) {
155
+ Logger.getInstance().debug('File write', { file: args[0] });
156
+
157
+ const filePath = args[0];
158
+ if (filePath.includes(__filename) || filePath.includes('node_modules')) {
159
+ Logger.getInstance().critical('Critical file modification attempt!', { filePath });
160
+ throw new Error('Critical file modification blocked');
161
+ }
162
+
163
+ return originalWriteFile.apply(this, args);
164
+ };
165
+ }
166
+
167
+ private async monitorAnomalies(): Promise<void> {
168
+ setInterval(async () => {
169
+ try {
170
+ const stats = await this.getProcessStats();
171
+ if (stats.cpu > 80) {
172
+ this.logger.warning('High CPU usage detected', { cpu: stats.cpu });
173
+ }
174
+
175
+ const processes = await this.getProcesses();
176
+ const nodeProcesses = processes.length || 0;
177
+
178
+ if (nodeProcesses > 10) {
179
+ this.logger.critical('Too many Node.js processes detected!', { count: nodeProcesses });
180
+ this.terminateCompromised();
181
+ }
182
+
183
+ } catch (error) {
184
+ this.logger.error('Anomaly monitoring error', { error });
185
+ }
186
+ }, 30000);
187
+ }
188
+
189
+ private async getProcessStats(): Promise<any> {
190
+ return { cpu: 0 };
191
+ }
192
+
193
+ private async getProcesses(): Promise<any[]> {
194
+ return [];
195
+ }
196
+
197
+ private terminateCompromised(): void {
198
+ if (this.isCompromised) return;
199
+
200
+ this.isCompromised = true;
201
+ this.logger.emergency('Process compromised - terminating');
202
+
203
+ this.memorySnapshots.clear();
204
+
205
+ process.kill(process.pid, 'SIGKILL');
206
+ }
207
+
208
+ public getStatus(): any {
209
+ return {
210
+ pid: process.pid,
211
+ uptime: process.uptime(),
212
+ memoryUsage: process.memoryUsage(),
213
+ cpuUsage: process.cpuUsage(),
214
+ debuggerDetected: this.detectDebugger(),
215
+ isCompromised: this.isCompromised,
216
+ protectedProperties: Array.from(this.protectedProperties)
217
+ };
218
+ }
219
+ }
package/src/index.ts ADDED
@@ -0,0 +1,189 @@
1
+ #!/usr/bin/env node
2
+
3
+ import * as path from 'path';
4
+ import { WatcherEngine } from './core/WatcherEngine';
5
+ import { SecurityConfig } from './types';
6
+ import { Logger } from './utils/Logger';
7
+ import { ProcessGuard } from './guards/ProcessGuard';
8
+ import { SecurityManager } from './core/SecurityManager';
9
+
10
+ class SecureFileWatcher {
11
+ private watcher: WatcherEngine | null = null;
12
+ private readonly logger: Logger;
13
+ private readonly processGuard: ProcessGuard;
14
+
15
+ constructor() {
16
+ this.logger = Logger.getInstance();
17
+ this.processGuard = ProcessGuard.getInstance();
18
+
19
+ this.initialize();
20
+ }
21
+
22
+ private async initialize(): Promise<void> {
23
+ try {
24
+ this.displayBanner();
25
+
26
+ await this.validateEnvironment();
27
+
28
+ const config = this.loadConfiguration();
29
+
30
+ SecurityManager.getInstance(config);
31
+
32
+ this.processGuard.protectProcess();
33
+
34
+ this.watcher = new WatcherEngine(config);
35
+
36
+ this.setupEventHandlers();
37
+
38
+ this.watcher.startWatching();
39
+
40
+ this.logger.info('Secure File Watcher started successfully');
41
+
42
+ } catch (error) {
43
+ this.logger.emergency('Failed to start Secure File Watcher', { error });
44
+ process.exit(1);
45
+ }
46
+ }
47
+
48
+ private displayBanner(): void {
49
+ const banner = `
50
+ Secure file security - Powered By Dimzxzzx07
51
+ `;
52
+
53
+ console.log('\x1b[36m%s\x1b[0m', banner);
54
+ }
55
+
56
+ private async validateEnvironment(): Promise<void> {
57
+ const nodeVersion = process.versions.node;
58
+ const majorVersion = parseInt(nodeVersion.split('.')[0] || '0');
59
+
60
+ if (majorVersion < 18) {
61
+ throw new Error(`Node.js 18+ required (current: ${nodeVersion})`);
62
+ }
63
+
64
+ const requiredEnvVars = ['NODE_ENV'];
65
+ for (const envVar of requiredEnvVars) {
66
+ if (!process.env[envVar]) {
67
+ this.logger.warning(`Environment variable ${envVar} not set`);
68
+ }
69
+ }
70
+
71
+ if (process.getuid && process.getuid() === 0) {
72
+ this.logger.warning('Running as root - this is not recommended');
73
+ }
74
+ }
75
+
76
+ private loadConfiguration(): SecurityConfig {
77
+ const watchDir = process.env.WATCH_DIR || process.cwd();
78
+
79
+ return {
80
+ watchDir,
81
+ hashAlgorithm: (process.env.HASH_ALGORITHM as any) || 'sha512',
82
+ backupDir: path.join(watchDir, '.secure_backup'),
83
+ quarantineDir: path.join(watchDir, '.secure_quarantine'),
84
+ maxFileSize: parseInt(process.env.MAX_FILE_SIZE || '10485760'),
85
+ scanInterval: parseInt(process.env.SCAN_INTERVAL || '60'),
86
+ realtimeMonitoring: process.env.REALTIME_MONITORING !== 'false',
87
+ autoRollback: process.env.AUTO_ROLLBACK !== 'false',
88
+ quarantineEnabled: process.env.QUARANTINE_ENABLED !== 'false',
89
+ signatureVerification: process.env.SIGNATURE_VERIFICATION === 'true',
90
+ integrityLevel: (process.env.INTEGRITY_LEVEL as any) || 'advanced',
91
+ alertThreshold: (process.env.ALERT_THRESHOLD as any) || 'medium',
92
+ allowedExtensions: (process.env.ALLOWED_EXTENSIONS || '.js,.ts,.json,.txt').split(','),
93
+ blockedPatterns: [
94
+ /eval\s*\(/i,
95
+ /Function\s*\(/i,
96
+ /child_process/,
97
+ /exec(File)?/i
98
+ ],
99
+ trustedSigners: (process.env.TRUSTED_SIGNERS || '').split(',')
100
+ };
101
+ }
102
+
103
+ private setupEventHandlers(): void {
104
+ if (!this.watcher) return;
105
+
106
+ this.watcher.on('file:added', (data) => {
107
+ this.logger.info(`File added: ${data.filePath}`);
108
+ });
109
+
110
+ this.watcher.on('file:changed', (data) => {
111
+ this.logger.info(`File changed: ${data.filePath}`);
112
+ });
113
+
114
+ this.watcher.on('file:deleted', (data) => {
115
+ this.logger.warning(`File deleted: ${data.filePath}`);
116
+ });
117
+
118
+ this.watcher.on('file:restored', (data) => {
119
+ this.logger.info(`File restored: ${data.filePath}`);
120
+ });
121
+
122
+ this.watcher.on('integrity:violation', (violation) => {
123
+ this.logger.critical('Integrity violation!', violation);
124
+
125
+ if (violation.severity === 'critical') {
126
+ this.handleCriticalViolation(violation);
127
+ }
128
+ });
129
+
130
+ this.watcher.on('security:alert', (alert) => {
131
+ this.logger.warning('Security alert', alert);
132
+ });
133
+
134
+ this.watcher.on('security:critical', (alert) => {
135
+ this.logger.emergency('Critical security event!', alert);
136
+ this.handleCriticalEvent();
137
+ });
138
+
139
+ this.watcher.on('error', (error) => {
140
+ this.logger.error('Watcher error', { error });
141
+ });
142
+ }
143
+
144
+ private handleCriticalViolation(violation: any): void {
145
+ this.logger.emergency('Handling critical violation', violation);
146
+ }
147
+
148
+ private handleCriticalEvent(): void {
149
+ this.logger.emergency('Critical event detected - initiating emergency protocol');
150
+ }
151
+
152
+ public getStatus(): any {
153
+ if (!this.watcher) {
154
+ return { status: 'not initialized' };
155
+ }
156
+
157
+ return {
158
+ watcher: this.watcher.getStatus(),
159
+ process: this.processGuard.getStatus(),
160
+ uptime: process.uptime(),
161
+ memoryUsage: process.memoryUsage(),
162
+ timestamp: new Date().toISOString()
163
+ };
164
+ }
165
+ }
166
+
167
+ new SecureFileWatcher();
168
+
169
+ process.on('SIGINT', () => {
170
+ Logger.getInstance().info('Received SIGINT - shutting down gracefully');
171
+ process.exit(0);
172
+ });
173
+
174
+ process.on('SIGTERM', () => {
175
+ Logger.getInstance().info('Received SIGTERM - shutting down gracefully');
176
+ process.exit(0);
177
+ });
178
+
179
+ process.on('uncaughtException', (error) => {
180
+ Logger.getInstance().emergency('Uncaught exception', { error });
181
+ process.exit(1);
182
+ });
183
+
184
+ process.on('unhandledRejection', (reason) => {
185
+ Logger.getInstance().emergency('Unhandled rejection', { reason });
186
+ process.exit(1);
187
+ });
188
+
189
+ export { SecureFileWatcher, WatcherEngine, SecurityConfig };