@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,348 @@
1
+ import * as crypto from 'crypto';
2
+ import { SecurityConfig, FileMetadata, SecurityAlert } from '../types';
3
+ import { Logger } from '../utils/Logger';
4
+
5
+ export class SecurityManager {
6
+ private static instance: SecurityManager;
7
+ private readonly config: SecurityConfig;
8
+ private readonly logger: Logger;
9
+ private readonly secureChannel: Map<string, any>;
10
+ private readonly alertHistory: SecurityAlert[];
11
+ private readonly memoryLocks: Set<string>;
12
+ private isInitialized: boolean = false;
13
+ private encryptionKey: Buffer | null = null;
14
+
15
+ private constructor(config: SecurityConfig) {
16
+ this.config = config;
17
+ this.logger = Logger.getInstance();
18
+ this.secureChannel = new Map();
19
+ this.alertHistory = [];
20
+ this.memoryLocks = new Set();
21
+
22
+ this.initialize();
23
+ }
24
+
25
+ public static getInstance(config?: SecurityConfig): SecurityManager {
26
+ if (!SecurityManager.instance && config) {
27
+ SecurityManager.instance = new SecurityManager(config);
28
+ }
29
+ return SecurityManager.instance;
30
+ }
31
+
32
+ private async initialize(): Promise<void> {
33
+ try {
34
+ await this.generateEncryptionKey();
35
+ await this.initializeSecureMemory();
36
+ await this.setupSecurityPolicies();
37
+
38
+ this.isInitialized = true;
39
+ this.logger.info('SecurityManager initialized successfully');
40
+ } catch (error) {
41
+ this.logger.error('Failed to initialize SecurityManager', { error });
42
+ throw error;
43
+ }
44
+ }
45
+
46
+ private async generateEncryptionKey(): Promise<void> {
47
+ this.encryptionKey = crypto.randomBytes(32);
48
+ Object.freeze(this.encryptionKey);
49
+ }
50
+
51
+ private async initializeSecureMemory(): Promise<void> {
52
+ const secureMemorySize = 1024 * 1024;
53
+ const secureBuffer = Buffer.alloc(secureMemorySize);
54
+
55
+ crypto.randomFillSync(secureBuffer);
56
+
57
+ this.memoryLocks.add('secure_buffer');
58
+ }
59
+
60
+ private async setupSecurityPolicies(): Promise<void> {
61
+ switch (this.config.integrityLevel) {
62
+ case 'paranoid':
63
+ this.enableParanoidMode();
64
+ break;
65
+ case 'advanced':
66
+ this.enableAdvancedMode();
67
+ break;
68
+ default:
69
+ this.enableBasicMode();
70
+ }
71
+ }
72
+
73
+ private enableParanoidMode(): void {
74
+ this.logger.info('Enabling PARANOID security mode');
75
+
76
+ setInterval(() => {
77
+ this.checkForRootkits();
78
+ this.validateSystemIntegrity();
79
+ this.scanForMalware();
80
+ }, 10000);
81
+ }
82
+
83
+ private enableAdvancedMode(): void {
84
+ this.logger.info('Enabling ADVANCED security mode');
85
+
86
+ setInterval(() => {
87
+ this.validateSystemIntegrity();
88
+ }, 30000);
89
+ }
90
+
91
+ private enableBasicMode(): void {
92
+ this.logger.info('Enabling BASIC security mode');
93
+ }
94
+
95
+ public async createSecureChannel(): Promise<any> {
96
+ const channelId = crypto.randomBytes(16).toString('hex');
97
+
98
+ const channel = {
99
+ id: channelId,
100
+ created: new Date(),
101
+ encryptionKey: crypto.randomBytes(32),
102
+ iv: crypto.randomBytes(16),
103
+ lastActivity: new Date()
104
+ };
105
+
106
+ this.secureChannel.set(channelId, channel);
107
+
108
+ setTimeout(() => {
109
+ this.secureChannel.delete(channelId);
110
+ }, 3600000);
111
+
112
+ return channel;
113
+ }
114
+
115
+ public setDebugMode(enabled: boolean): void {
116
+ if (enabled) {
117
+ this.logger.warning('Debug mode enabled - reduced security');
118
+ }
119
+ }
120
+
121
+ public async scanFile(filePath: string): Promise<boolean> {
122
+ try {
123
+ const stats = await require('fs').promises.stat(filePath);
124
+ if (stats.size > this.config.maxFileSize) {
125
+ this.logger.warning(`File too large: ${filePath}`);
126
+ return false;
127
+ }
128
+
129
+ const hasMalware = await this.detectMalware(filePath);
130
+ if (hasMalware) {
131
+ this.logger.warning(`Malware detected in: ${filePath}`);
132
+ return false;
133
+ }
134
+
135
+ if (stats.mode & 0o7777) {
136
+ this.logger.warning(`Suspicious permissions on: ${filePath}`);
137
+ return false;
138
+ }
139
+
140
+ return true;
141
+ } catch (error) {
142
+ this.logger.error(`Error scanning file: ${filePath}`, { error });
143
+ return false;
144
+ }
145
+ }
146
+
147
+ private async detectMalware(filePath: string): Promise<boolean> {
148
+ const malwareSignatures = [
149
+ 'eval(atob(',
150
+ 'new Function(atob(',
151
+ 'Buffer.from(',
152
+ 'process.binding',
153
+ 'Reflect.construct'
154
+ ];
155
+
156
+ try {
157
+ const content = await require('fs').promises.readFile(filePath, 'utf8');
158
+ const contentStr = content.toString().toLowerCase();
159
+
160
+ for (const signature of malwareSignatures) {
161
+ if (contentStr.includes(signature.toLowerCase())) {
162
+ return true;
163
+ }
164
+ }
165
+
166
+ const base64Pattern = /[A-Za-z0-9+/]{100,}={0,2}/g;
167
+ const matches = contentStr.match(base64Pattern);
168
+
169
+ if (matches) {
170
+ for (const match of matches) {
171
+ try {
172
+ const decoded = Buffer.from(match, 'base64').toString();
173
+ if (decoded.includes('eval') || decoded.includes('require')) {
174
+ return true;
175
+ }
176
+ } catch {
177
+ }
178
+ }
179
+ }
180
+ } catch {
181
+ }
182
+
183
+ return false;
184
+ }
185
+
186
+ public async isAuthorizedChange(
187
+ filePath: string,
188
+ oldMetadata: FileMetadata,
189
+ newMetadata: FileMetadata
190
+ ): Promise<boolean> {
191
+ const callerStack = new Error().stack;
192
+
193
+ if (callerStack?.includes('node_modules')) {
194
+ this.logger.warning('Change from node_modules', { filePath });
195
+ return false;
196
+ }
197
+
198
+ const oldHash = oldMetadata.hash.substring(0, 8);
199
+ const newHash = newMetadata.hash.substring(0, 8);
200
+
201
+ if (oldHash !== newHash) {
202
+ return false;
203
+ }
204
+
205
+ const timeDiff = newMetadata.modified.getTime() - oldMetadata.modified.getTime();
206
+ if (timeDiff < 100) {
207
+ this.logger.warning('Suspiciously fast modification', { filePath, timeDiff });
208
+ return false;
209
+ }
210
+
211
+ return true;
212
+ }
213
+
214
+ public async encryptFile(filePath: string): Promise<void> {
215
+ if (!this.encryptionKey) {
216
+ throw new Error('Encryption key not initialized');
217
+ }
218
+
219
+ try {
220
+ const content = await require('fs').promises.readFile(filePath);
221
+
222
+ const iv = crypto.randomBytes(16);
223
+
224
+ const cipher = crypto.createCipheriv('aes-256-cbc', this.encryptionKey, iv);
225
+
226
+ const encrypted = Buffer.concat([
227
+ cipher.update(content),
228
+ cipher.final()
229
+ ]);
230
+
231
+ const output = Buffer.concat([iv, encrypted]);
232
+ await require('fs').promises.writeFile(filePath + '.encrypted', output);
233
+
234
+ this.logger.info(`File encrypted: ${filePath}`);
235
+ } catch (error) {
236
+ this.logger.error(`Failed to encrypt file: ${filePath}`, { error });
237
+ throw error;
238
+ }
239
+ }
240
+
241
+ public async encryptSensitiveData(): Promise<void> {
242
+ this.logger.info('Encrypting sensitive data...');
243
+
244
+ this.secureChannel.clear();
245
+ this.alertHistory.length = 0;
246
+
247
+ if (global.gc) {
248
+ global.gc();
249
+ }
250
+ }
251
+
252
+ public validateMemoryIntegrity(): void {
253
+ const memoryUsage = process.memoryUsage();
254
+
255
+ if (memoryUsage.heapUsed > memoryUsage.heapTotal * 0.9) {
256
+ this.logger.warning('High heap usage detected', memoryUsage);
257
+ }
258
+
259
+ if (this.secureChannel.size > 100) {
260
+ this.logger.warning('Large number of secure channels', { count: this.secureChannel.size });
261
+ }
262
+ }
263
+
264
+ private async checkForRootkits(): Promise<void> {
265
+ const rootkitChecks = [
266
+ this.checkHiddenProcesses(),
267
+ this.checkFileSystemHooks(),
268
+ this.checkKernelModules()
269
+ ];
270
+
271
+ await Promise.all(rootkitChecks);
272
+ }
273
+
274
+ private async checkHiddenProcesses(): Promise<boolean> {
275
+ return false;
276
+ }
277
+
278
+ private async checkFileSystemHooks(): Promise<boolean> {
279
+ return false;
280
+ }
281
+
282
+ private async checkKernelModules(): Promise<boolean> {
283
+ return false;
284
+ }
285
+
286
+ private async validateSystemIntegrity(): Promise<void> {
287
+ const criticalFiles = [
288
+ '/etc/passwd',
289
+ '/etc/shadow',
290
+ process.execPath
291
+ ];
292
+
293
+ for (const file of criticalFiles) {
294
+ try {
295
+ await require('fs').promises.access(file);
296
+ const stats = await require('fs').promises.stat(file);
297
+
298
+ const age = Date.now() - stats.mtimeMs;
299
+ if (age < 60000) {
300
+ this.logger.critical(`Critical file modified: ${file}`);
301
+ }
302
+ } catch {
303
+ }
304
+ }
305
+ }
306
+
307
+ private async scanForMalware(): Promise<void> {
308
+ const processes = await this.getRunningProcesses();
309
+
310
+ for (const proc of processes) {
311
+ if (this.isSuspiciousProcess(proc)) {
312
+ this.logger.critical(`Suspicious process detected: ${proc.name}`);
313
+ }
314
+ }
315
+ }
316
+
317
+ private async getRunningProcesses(): Promise<any[]> {
318
+ return [];
319
+ }
320
+
321
+ private isSuspiciousProcess(proc: any): boolean {
322
+ const suspiciousNames = ['miner', 'xmr', 'crypt', 'unknown'];
323
+ return suspiciousNames.some(name => proc.name?.includes(name));
324
+ }
325
+
326
+ public logAlert(alert: SecurityAlert): void {
327
+ this.alertHistory.push(alert);
328
+
329
+ if (this.alertHistory.length > 100) {
330
+ this.alertHistory.shift();
331
+ }
332
+ }
333
+
334
+ public getAlerts(): SecurityAlert[] {
335
+ return [...this.alertHistory];
336
+ }
337
+
338
+ public getStatus(): any {
339
+ return {
340
+ initialized: this.isInitialized,
341
+ secureChannels: this.secureChannel.size,
342
+ memoryLocks: Array.from(this.memoryLocks),
343
+ alertCount: this.alertHistory.length,
344
+ mode: this.config.integrityLevel,
345
+ keyInitialized: this.encryptionKey !== null
346
+ };
347
+ }
348
+ }