@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,220 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.HashGenerator = void 0;
37
+ const crypto = __importStar(require("crypto"));
38
+ class HashGenerator {
39
+ config;
40
+ algorithms;
41
+ salt;
42
+ constructor(config) {
43
+ this.config = config;
44
+ this.algorithms = ['sha256', 'sha384', 'sha512', 'blake2b512'];
45
+ this.salt = crypto.randomBytes(32);
46
+ }
47
+ generateHash(data) {
48
+ const input = typeof data === 'string' ? Buffer.from(data) : data;
49
+ const hash1 = crypto.createHash(this.config.hashAlgorithm)
50
+ .update(input)
51
+ .update(this.salt)
52
+ .digest('hex');
53
+ const hash2 = crypto.createHash('blake2b512')
54
+ .update(input)
55
+ .update(hash1)
56
+ .digest('hex');
57
+ return this.combineHashes([hash1, hash2]);
58
+ }
59
+ generateEncryptedHash(data) {
60
+ const input = typeof data === 'string' ? Buffer.from(data) : data;
61
+ const normalHash = this.generateHash(input);
62
+ const key = crypto.scryptSync(normalHash, this.salt, 32);
63
+ const iv = crypto.randomBytes(16);
64
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
65
+ const encrypted = Buffer.concat([
66
+ cipher.update(Buffer.from(normalHash, 'hex')),
67
+ cipher.final()
68
+ ]);
69
+ const authTag = cipher.getAuthTag();
70
+ return Buffer.concat([iv, authTag, encrypted]).toString('base64');
71
+ }
72
+ generateMultiHash(data) {
73
+ const hashes = [];
74
+ for (const algorithm of this.algorithms) {
75
+ const hash = crypto.createHash(algorithm)
76
+ .update(data)
77
+ .update(this.salt)
78
+ .digest('hex');
79
+ hashes.push(hash);
80
+ }
81
+ return hashes;
82
+ }
83
+ generateRollingHash(data, chunkSize = 1024) {
84
+ const hashes = [];
85
+ for (let i = 0; i < data.length; i += chunkSize) {
86
+ const chunk = data.subarray(i, Math.min(i + chunkSize, data.length));
87
+ const hash = crypto.createHash('sha256')
88
+ .update(chunk)
89
+ .digest('hex');
90
+ hashes.push(hash);
91
+ }
92
+ return hashes;
93
+ }
94
+ generateMerkleRoot(data) {
95
+ const leaves = [];
96
+ const chunkSize = 1024;
97
+ for (let i = 0; i < data.length; i += chunkSize) {
98
+ const chunk = data.subarray(i, Math.min(i + chunkSize, data.length));
99
+ const hash = crypto.createHash('sha256')
100
+ .update(chunk)
101
+ .digest();
102
+ leaves.push(hash.toString('hex'));
103
+ }
104
+ return this.buildMerkleTree(leaves);
105
+ }
106
+ buildMerkleTree(leaves) {
107
+ if (leaves.length === 1) {
108
+ return leaves[0];
109
+ }
110
+ const newLevel = [];
111
+ for (let i = 0; i < leaves.length; i += 2) {
112
+ if (i + 1 < leaves.length) {
113
+ const left = leaves[i];
114
+ const right = leaves[i + 1];
115
+ const combined = left + right;
116
+ const hash = crypto.createHash('sha256')
117
+ .update(Buffer.from(combined, 'hex'))
118
+ .digest('hex');
119
+ newLevel.push(hash);
120
+ }
121
+ else {
122
+ newLevel.push(leaves[i]);
123
+ }
124
+ }
125
+ return this.buildMerkleTree(newLevel);
126
+ }
127
+ generateHMAC(data, key) {
128
+ const secretKey = key || crypto.randomBytes(32);
129
+ const input = typeof data === 'string' ? Buffer.from(data) : data;
130
+ const hmac = crypto.createHmac('sha512', secretKey)
131
+ .update(input)
132
+ .digest('hex');
133
+ return hmac;
134
+ }
135
+ generateKeyedHash(data, key) {
136
+ const prk = crypto.createHmac('sha256', key)
137
+ .update(data)
138
+ .digest();
139
+ const okm = crypto.createHmac('sha256', prk)
140
+ .update(Buffer.from([0x01]))
141
+ .digest();
142
+ return okm.toString('hex');
143
+ }
144
+ generateTimeBasedHash(data, timestamp = Date.now()) {
145
+ const timeBuffer = Buffer.alloc(8);
146
+ timeBuffer.writeBigUInt64BE(BigInt(timestamp));
147
+ const combined = Buffer.concat([data, timeBuffer]);
148
+ return crypto.createHash('sha512')
149
+ .update(combined)
150
+ .update(this.salt)
151
+ .digest('hex');
152
+ }
153
+ generateHashChain(data, chainLength = 10) {
154
+ const chain = [];
155
+ let current = data;
156
+ for (let i = 0; i < chainLength; i++) {
157
+ const hash = crypto.createHash('sha256')
158
+ .update(current)
159
+ .digest();
160
+ chain.push(hash.toString('hex'));
161
+ current = hash;
162
+ }
163
+ return chain;
164
+ }
165
+ verifyHashChain(chain) {
166
+ for (let i = 0; i < chain.length - 1; i++) {
167
+ const hash = crypto.createHash('sha256')
168
+ .update(Buffer.from(chain[i], 'hex'))
169
+ .digest('hex');
170
+ if (hash !== chain[i + 1]) {
171
+ return false;
172
+ }
173
+ }
174
+ return true;
175
+ }
176
+ generateFingerprint(data) {
177
+ const features = [
178
+ data.length.toString(),
179
+ this.generateHash(data).substring(0, 16),
180
+ this.calculateEntropy(data).toString(),
181
+ this.getFirstBytes(data, 32).toString('hex'),
182
+ this.getLastBytes(data, 32).toString('hex')
183
+ ];
184
+ return this.generateHash(features.join('|'));
185
+ }
186
+ calculateEntropy(data) {
187
+ const frequencies = {};
188
+ for (const byte of data) {
189
+ frequencies[byte] = (frequencies[byte] || 0) + 1;
190
+ }
191
+ let entropy = 0;
192
+ const length = data.length;
193
+ for (const freq of Object.values(frequencies)) {
194
+ const probability = freq / length;
195
+ entropy -= probability * Math.log2(probability);
196
+ }
197
+ return entropy;
198
+ }
199
+ getFirstBytes(data, count) {
200
+ return data.subarray(0, Math.min(count, data.length));
201
+ }
202
+ getLastBytes(data, count) {
203
+ const start = Math.max(0, data.length - count);
204
+ return data.subarray(start);
205
+ }
206
+ combineHashes(hashes) {
207
+ const combined = hashes.join('');
208
+ return crypto.createHash('sha512')
209
+ .update(combined)
210
+ .digest('hex');
211
+ }
212
+ getSalt() {
213
+ return Buffer.from(this.salt);
214
+ }
215
+ getAlgorithms() {
216
+ return [...this.algorithms];
217
+ }
218
+ }
219
+ exports.HashGenerator = HashGenerator;
220
+ //# sourceMappingURL=HashGenerator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"HashGenerator.js","sourceRoot":"","sources":["../../src/crypto/HashGenerator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAAiC;AAGjC,MAAa,aAAa;IACL,MAAM,CAAiB;IACvB,UAAU,CAAW;IACrB,IAAI,CAAS;IAE9B,YAAY,MAAsB;QAC9B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,UAAU,GAAG,CAAC,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,YAAY,CAAC,CAAC;QAC/D,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;IACvC,CAAC;IAEM,YAAY,CAAC,IAAqB;QACrC,MAAM,KAAK,GAAG,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QAElE,MAAM,KAAK,GAAG,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC;aACrD,MAAM,CAAC,KAAK,CAAC;aACb,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC;aACjB,MAAM,CAAC,KAAK,CAAC,CAAC;QAEnB,MAAM,KAAK,GAAG,MAAM,CAAC,UAAU,CAAC,YAAY,CAAC;aACxC,MAAM,CAAC,KAAK,CAAC;aACb,MAAM,CAAC,KAAK,CAAC;aACb,MAAM,CAAC,KAAK,CAAC,CAAC;QAEnB,OAAO,IAAI,CAAC,aAAa,CAAC,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;IAC9C,CA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I,CAAC,CAAC;IAClC,CAAC;IAEM,aAAa;QAChB,OAAO,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC;IAChC,CAAC;CACJ;AAtOD,sCAsOC","sourcesContent":["import * as crypto from 'crypto';\nimport { SecurityConfig } from '../types';\n\nexport class HashGenerator {\n private readonly config: SecurityConfig;\n private readonly algorithms: string[];\n private readonly salt: Buffer;\n\n constructor(config: SecurityConfig) {\n this.config = config;\n this.algorithms = ['sha256', 'sha384', 'sha512', 'blake2b512'];\n this.salt = crypto.randomBytes(32);\n }\n\n public generateHash(data: Buffer | string): string {\n const input = typeof data === 'string' ? Buffer.from(data) : data;\n \n const hash1 = crypto.createHash(this.config.hashAlgorithm)\n .update(input)\n .update(this.salt)\n .digest('hex');\n \n const hash2 = crypto.createHash('blake2b512')\n .update(input)\n .update(hash1)\n .digest('hex');\n \n return this.combineHashes([hash1, hash2]);\n }\n\n public generateEncryptedHash(data: Buffer | string): string {\n const input = typeof data === 'string' ? Buffer.from(data) : data;\n \n const normalHash = this.generateHash(input);\n \n const key = crypto.scryptSync(normalHash, this.salt, 32);\n const iv = crypto.randomBytes(16);\n \n const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);\n const encrypted = Buffer.concat([\n cipher.update(Buffer.from(normalHash, 'hex')),\n cipher.final()\n ]);\n \n const authTag = cipher.getAuthTag();\n \n return Buffer.concat([iv, authTag, encrypted]).toString('base64');\n }\n\n public generateMultiHash(data: Buffer): string[] {\n const hashes: string[] = [];\n \n for (const algorithm of this.algorithms) {\n const hash = crypto.createHash(algorithm)\n .update(data)\n .update(this.salt)\n .digest('hex');\n hashes.push(hash);\n }\n \n return hashes;\n }\n\n public generateRollingHash(data: Buffer, chunkSize: number = 1024): string[] {\n const hashes: string[] = [];\n \n for (let i = 0; i < data.length; i += chunkSize) {\n const chunk = data.subarray(i, Math.min(i + chunkSize, data.length));\n const hash = crypto.createHash('sha256')\n .update(chunk)\n .digest('hex');\n hashes.push(hash);\n }\n \n return hashes;\n }\n\n public generateMerkleRoot(data: Buffer): string {\n const leaves: string[] = [];\n const chunkSize = 1024;\n \n for (let i = 0; i < data.length; i += chunkSize) {\n const chunk = data.subarray(i, Math.min(i + chunkSize, data.length));\n const hash = crypto.createHash('sha256')\n .update(chunk)\n .digest();\n leaves.push(hash.toString('hex'));\n }\n \n return this.buildMerkleTree(leaves);\n }\n\n private buildMerkleTree(leaves: string[]): string {\n if (leaves.length === 1) {\n return leaves[0] as string;\n }\n \n const newLevel: string[] = [];\n \n for (let i = 0; i < leaves.length; i += 2) {\n if (i + 1 < leaves.length) {\n const left = leaves[i] as string;\n const right = leaves[i + 1] as string;\n const combined = left + right;\n const hash = crypto.createHash('sha256')\n .update(Buffer.from(combined, 'hex'))\n .digest('hex');\n newLevel.push(hash);\n } else {\n newLevel.push(leaves[i] as string);\n }\n }\n \n return this.buildMerkleTree(newLevel);\n }\n\n public generateHMAC(data: Buffer | string, key?: Buffer): string {\n const secretKey = key || crypto.randomBytes(32);\n const input = typeof data === 'string' ? Buffer.from(data) : data;\n \n const hmac = crypto.createHmac('sha512', secretKey)\n .update(input)\n .digest('hex');\n \n return hmac;\n }\n\n public generateKeyedHash(data: Buffer, key: Buffer): string {\n const prk = crypto.createHmac('sha256', key)\n .update(data)\n .digest();\n \n const okm = crypto.createHmac('sha256', prk)\n .update(Buffer.from([0x01]))\n .digest();\n \n return okm.toString('hex');\n }\n\n public generateTimeBasedHash(data: Buffer, timestamp: number = Date.now()): string {\n const timeBuffer = Buffer.alloc(8);\n timeBuffer.writeBigUInt64BE(BigInt(timestamp));\n \n const combined = Buffer.concat([data, timeBuffer]);\n \n return crypto.createHash('sha512')\n .update(combined)\n .update(this.salt)\n .digest('hex');\n }\n\n public generateHashChain(data: Buffer, chainLength: number = 10): string[] {\n const chain: string[] = [];\n let current = data;\n \n for (let i = 0; i < chainLength; i++) {\n const hash = crypto.createHash('sha256')\n .update(current)\n .digest();\n chain.push(hash.toString('hex'));\n current = hash;\n }\n \n return chain;\n }\n\n public verifyHashChain(chain: string[]): boolean {\n for (let i = 0; i < chain.length - 1; i++) {\n const hash = crypto.createHash('sha256')\n .update(Buffer.from(chain[i] as string, 'hex'))\n .digest('hex');\n \n if (hash !== chain[i + 1]) {\n return false;\n }\n }\n \n return true;\n }\n\n public generateFingerprint(data: Buffer): string {\n const features = [\n data.length.toString(),\n this.generateHash(data).substring(0, 16),\n this.calculateEntropy(data).toString(),\n this.getFirstBytes(data, 32).toString('hex'),\n this.getLastBytes(data, 32).toString('hex')\n ];\n \n return this.generateHash(features.join('|'));\n }\n\n private calculateEntropy(data: Buffer): number {\n const frequencies: { [key: number]: number } = {};\n \n for (const byte of data) {\n frequencies[byte] = (frequencies[byte] || 0) + 1;\n }\n \n let entropy = 0;\n const length = data.length;\n \n for (const freq of Object.values(frequencies)) {\n const probability = freq / length;\n entropy -= probability * Math.log2(probability);\n }\n \n return entropy;\n }\n\n private getFirstBytes(data: Buffer, count: number): Buffer {\n return data.subarray(0, Math.min(count, data.length));\n }\n\n private getLastBytes(data: Buffer, count: number): Buffer {\n const start = Math.max(0, data.length - count);\n return data.subarray(start);\n }\n\n private combineHashes(hashes: string[]): string {\n const combined = hashes.join('');\n return crypto.createHash('sha512')\n .update(combined)\n .digest('hex');\n }\n\n public getSalt(): Buffer {\n return Buffer.from(this.salt);\n }\n\n public getAlgorithms(): string[] {\n return [...this.algorithms];\n }\n}"]}
@@ -0,0 +1,30 @@
1
+ import { SecurityConfig } from '../types';
2
+ export declare class KeyManager {
3
+ private readonly keys;
4
+ private readonly keyDir;
5
+ private masterKey;
6
+ constructor(config: SecurityConfig);
7
+ private initializeKeyStorage;
8
+ private loadMasterKey;
9
+ generateKey(keyId: string, length?: number): Buffer;
10
+ generateKeyPair(keyId: string): Promise<{
11
+ publicKey: Buffer;
12
+ privateKey: Buffer;
13
+ }>;
14
+ getKey(keyId: string): Buffer | undefined;
15
+ rotateKey(keyId: string): Promise<Buffer>;
16
+ deriveKey(password: string, salt?: Buffer): Promise<Buffer>;
17
+ generateSessionKey(): Buffer;
18
+ generateIV(): Buffer;
19
+ encryptWithMasterKey(data: Buffer): Promise<Buffer>;
20
+ decryptWithMasterKey(encryptedData: Buffer): Promise<Buffer>;
21
+ signData(keyId: string, data: Buffer): Promise<Buffer>;
22
+ verifySignature(keyId: string, data: Buffer, signature: Buffer): Promise<boolean>;
23
+ private saveKeyToDisk;
24
+ private encryptMasterKey;
25
+ private decryptMasterKey;
26
+ private getPlatformKey;
27
+ private archiveKey;
28
+ getStatus(): any;
29
+ }
30
+ //# sourceMappingURL=KeyManager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KeyManager.d.ts","sourceRoot":"","sources":["../../src/crypto/KeyManager.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAG1C,qBAAa,UAAU;IACnB,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAsB;IAC3C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,OAAO,CAAC,SAAS,CAAuB;gBAE5B,MAAM,EAAE,cAAc;YAOpB,oBAAoB;YASpB,aAAa;IAapB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,GAAE,MAAW,GAAG,MAAM;IAMjD,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;QACjD,SAAS,EAAE,MAAM,CAAC;QAClB,UAAU,EAAE,MAAM,CAAC;KACtB,CAAC;IAsBK,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS;IAInC,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAYzC,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAWjE,kBAAkB,IAAI,MAAM;IAI5B,UAAU,IAAI,MAAM;IAId,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAkBnD,oBAAoB,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAkB5D,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAgBtD,eAAe,CACxB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,MAAM,GAClB,OAAO,CAAC,OAAO,CAAC;YAgBL,aAAa;YAUb,gBAAgB;YAgBhB,gBAAgB;YAgBhB,cAAc;YAYd,UAAU;IASjB,SAAS,IAAI,GAAG;CAO1B"}
@@ -0,0 +1,235 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.KeyManager = void 0;
37
+ const crypto = __importStar(require("crypto"));
38
+ const fs = __importStar(require("fs/promises"));
39
+ const path = __importStar(require("path"));
40
+ const Logger_1 = require("../utils/Logger");
41
+ class KeyManager {
42
+ keys;
43
+ keyDir;
44
+ masterKey = null;
45
+ constructor(config) {
46
+ this.keys = new Map();
47
+ this.keyDir = path.join(config.watchDir, '.secure', 'keys');
48
+ this.initializeKeyStorage();
49
+ }
50
+ async initializeKeyStorage() {
51
+ try {
52
+ await fs.mkdir(this.keyDir, { recursive: true, mode: 0o700 });
53
+ await this.loadMasterKey();
54
+ }
55
+ catch (error) {
56
+ Logger_1.Logger.getInstance().error('Failed to initialize key storage', { error });
57
+ }
58
+ }
59
+ async loadMasterKey() {
60
+ const masterKeyPath = path.join(this.keyDir, 'master.key');
61
+ try {
62
+ const encryptedKey = await fs.readFile(masterKeyPath);
63
+ this.masterKey = await this.decryptMasterKey(encryptedKey);
64
+ }
65
+ catch {
66
+ this.masterKey = crypto.randomBytes(32);
67
+ const encryptedKey = await this.encryptMasterKey(this.masterKey);
68
+ await fs.writeFile(masterKeyPath, encryptedKey, { mode: 0o400 });
69
+ }
70
+ }
71
+ generateKey(keyId, length = 32) {
72
+ const key = crypto.randomBytes(length);
73
+ this.keys.set(keyId, key);
74
+ return key;
75
+ }
76
+ async generateKeyPair(keyId) {
77
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
78
+ modulusLength: 2048,
79
+ publicKeyEncoding: {
80
+ type: 'spki',
81
+ format: 'der'
82
+ },
83
+ privateKeyEncoding: {
84
+ type: 'pkcs8',
85
+ format: 'der'
86
+ }
87
+ });
88
+ this.keys.set(`${keyId}_public`, publicKey);
89
+ this.keys.set(`${keyId}_private`, privateKey);
90
+ await this.saveKeyToDisk(`${keyId}_public`, publicKey);
91
+ await this.saveKeyToDisk(`${keyId}_private`, privateKey);
92
+ return { publicKey, privateKey };
93
+ }
94
+ getKey(keyId) {
95
+ return this.keys.get(keyId);
96
+ }
97
+ async rotateKey(keyId) {
98
+ const newKey = this.generateKey(`${keyId}_${Date.now()}`);
99
+ this.keys.set(keyId, newKey);
100
+ const oldKey = this.keys.get(`${keyId}_old`);
101
+ if (oldKey) {
102
+ await this.archiveKey(keyId, oldKey);
103
+ }
104
+ return newKey;
105
+ }
106
+ async deriveKey(password, salt) {
107
+ const useSalt = salt || crypto.randomBytes(16);
108
+ return new Promise((resolve, reject) => {
109
+ crypto.scrypt(password, useSalt, 32, (err, derivedKey) => {
110
+ if (err)
111
+ reject(err);
112
+ else
113
+ resolve(derivedKey);
114
+ });
115
+ });
116
+ }
117
+ generateSessionKey() {
118
+ return crypto.randomBytes(32);
119
+ }
120
+ generateIV() {
121
+ return crypto.randomBytes(16);
122
+ }
123
+ async encryptWithMasterKey(data) {
124
+ if (!this.masterKey) {
125
+ throw new Error('Master key not initialized');
126
+ }
127
+ const iv = crypto.randomBytes(16);
128
+ const cipher = crypto.createCipheriv('aes-256-gcm', this.masterKey, iv);
129
+ const encrypted = Buffer.concat([
130
+ cipher.update(data),
131
+ cipher.final()
132
+ ]);
133
+ const authTag = cipher.getAuthTag();
134
+ return Buffer.concat([iv, authTag, encrypted]);
135
+ }
136
+ async decryptWithMasterKey(encryptedData) {
137
+ if (!this.masterKey) {
138
+ throw new Error('Master key not initialized');
139
+ }
140
+ const iv = encryptedData.subarray(0, 16);
141
+ const authTag = encryptedData.subarray(16, 32);
142
+ const data = encryptedData.subarray(32);
143
+ const decipher = crypto.createDecipheriv('aes-256-gcm', this.masterKey, iv);
144
+ decipher.setAuthTag(authTag);
145
+ return Buffer.concat([
146
+ decipher.update(data),
147
+ decipher.final()
148
+ ]);
149
+ }
150
+ async signData(keyId, data) {
151
+ const privateKey = this.keys.get(keyId);
152
+ if (!privateKey) {
153
+ throw new Error(`Key not found: ${keyId}`);
154
+ }
155
+ const sign = crypto.createSign('RSA-SHA256');
156
+ sign.update(data);
157
+ return sign.sign({
158
+ key: privateKey,
159
+ format: 'der',
160
+ type: 'pkcs8'
161
+ });
162
+ }
163
+ async verifySignature(keyId, data, signature) {
164
+ const publicKey = this.keys.get(keyId);
165
+ if (!publicKey) {
166
+ throw new Error(`Key not found: ${keyId}`);
167
+ }
168
+ const verify = crypto.createVerify('RSA-SHA256');
169
+ verify.update(data);
170
+ return verify.verify({
171
+ key: publicKey,
172
+ format: 'der',
173
+ type: 'spki'
174
+ }, signature);
175
+ }
176
+ async saveKeyToDisk(keyId, keyData) {
177
+ try {
178
+ const keyPath = path.join(this.keyDir, `${keyId}.key`);
179
+ const encrypted = await this.encryptWithMasterKey(keyData);
180
+ await fs.writeFile(keyPath, encrypted, { mode: 0o400 });
181
+ }
182
+ catch (error) {
183
+ Logger_1.Logger.getInstance().error(`Failed to save key: ${keyId}`, { error });
184
+ }
185
+ }
186
+ async encryptMasterKey(key) {
187
+ const platformKey = await this.getPlatformKey();
188
+ const iv = crypto.randomBytes(16);
189
+ const cipher = crypto.createCipheriv('aes-256-gcm', platformKey, iv);
190
+ const encrypted = Buffer.concat([
191
+ cipher.update(key),
192
+ cipher.final()
193
+ ]);
194
+ const authTag = cipher.getAuthTag();
195
+ return Buffer.concat([iv, authTag, encrypted]);
196
+ }
197
+ async decryptMasterKey(encrypted) {
198
+ const platformKey = await this.getPlatformKey();
199
+ const iv = encrypted.subarray(0, 16);
200
+ const authTag = encrypted.subarray(16, 32);
201
+ const data = encrypted.subarray(32);
202
+ const decipher = crypto.createDecipheriv('aes-256-gcm', platformKey, iv);
203
+ decipher.setAuthTag(authTag);
204
+ return Buffer.concat([
205
+ decipher.update(data),
206
+ decipher.final()
207
+ ]);
208
+ }
209
+ async getPlatformKey() {
210
+ const platformData = [
211
+ process.platform,
212
+ process.arch,
213
+ process.cwd(),
214
+ __filename,
215
+ process.pid
216
+ ].join('|');
217
+ return crypto.createHash('sha256').update(platformData).digest();
218
+ }
219
+ async archiveKey(keyId, keyData) {
220
+ const archiveDir = path.join(this.keyDir, 'archive');
221
+ await fs.mkdir(archiveDir, { recursive: true });
222
+ const archivePath = path.join(archiveDir, `${keyId}_${Date.now()}.key.old`);
223
+ const encrypted = await this.encryptWithMasterKey(keyData);
224
+ await fs.writeFile(archivePath, encrypted, { mode: 0o400 });
225
+ }
226
+ getStatus() {
227
+ return {
228
+ keyCount: this.keys.size,
229
+ masterKeyInitialized: this.masterKey !== null,
230
+ keyDirectory: this.keyDir
231
+ };
232
+ }
233
+ }
234
+ exports.KeyManager = KeyManager;
235
+ //# sourceMappingURL=KeyManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KeyManager.js","sourceRoot":"","sources":["../../src/crypto/KeyManager.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAAiC;AACjC,gDAAkC;AAClC,2CAA6B;AAE7B,4CAAyC;AAEzC,MAAa,UAAU;IACF,IAAI,CAAsB;IAC1B,MAAM,CAAS;IACxB,SAAS,GAAkB,IAAI,CAAC;IAExC,YAAY,MAAsB;QAC9B,IAAI,CAAC,IAAI,GAAG,IAAI,GAAG,EAAE,CAAC;QACtB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;QAE5D,IAAI,CAAC,oBAAoB,EAAE,CAAC;IAChC,CAAC;IAEO,KAAK,CAAC,oBAAoB;QAC9B,IAAI,CAAC;YACD,MAAM,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;YAC9D,MAAM,IAAI,CAAC,aAAa,EAAE,CAAC;QAC/B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,eAAM,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,kCAAkC,EAAE,EAAE,KAAK,EAAE,C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,IAAI,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC;QAC3D,MAAM,EAAE,CAAC,SAAS,CAAC,WAAW,EAAE,SAAS,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IAChE,CAAC;IAEM,SAAS;QACZ,OAAO;YACH,QAAQ,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI;YACxB,oBAAoB,EAAE,IAAI,CAAC,SAAS,KAAK,IAAI;YAC7C,YAAY,EAAE,IAAI,CAAC,MAAM;SAC5B,CAAC;IACN,CAAC;CACJ;AAlPD,gCAkPC","sourcesContent":["import * as crypto from 'crypto';\nimport * as fs from 'fs/promises';\nimport * as path from 'path';\nimport { SecurityConfig } from '../types';\nimport { Logger } from '../utils/Logger';\n\nexport class KeyManager {\n private readonly keys: Map<string, Buffer>;\n private readonly keyDir: string;\n private masterKey: Buffer | null = null;\n\n constructor(config: SecurityConfig) {\n this.keys = new Map();\n this.keyDir = path.join(config.watchDir, '.secure', 'keys');\n \n this.initializeKeyStorage();\n }\n\n private async initializeKeyStorage(): Promise<void> {\n try {\n await fs.mkdir(this.keyDir, { recursive: true, mode: 0o700 });\n await this.loadMasterKey();\n } catch (error) {\n Logger.getInstance().error('Failed to initialize key storage', { error });\n }\n }\n\n private async loadMasterKey(): Promise<void> {\n const masterKeyPath = path.join(this.keyDir, 'master.key');\n \n try {\n const encryptedKey = await fs.readFile(masterKeyPath);\n this.masterKey = await this.decryptMasterKey(encryptedKey);\n } catch {\n this.masterKey = crypto.randomBytes(32);\n const encryptedKey = await this.encryptMasterKey(this.masterKey);\n await fs.writeFile(masterKeyPath, encryptedKey, { mode: 0o400 });\n }\n }\n\n public generateKey(keyId: string, length: number = 32): Buffer {\n const key = crypto.randomBytes(length);\n this.keys.set(keyId, key);\n return key;\n }\n\n public async generateKeyPair(keyId: string): Promise<{\n publicKey: Buffer;\n privateKey: Buffer;\n }> {\n const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {\n modulusLength: 2048,\n publicKeyEncoding: {\n type: 'spki',\n format: 'der'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'der'\n }\n });\n\n this.keys.set(`${keyId}_public`, publicKey);\n this.keys.set(`${keyId}_private`, privateKey);\n\n await this.saveKeyToDisk(`${keyId}_public`, publicKey);\n await this.saveKeyToDisk(`${keyId}_private`, privateKey);\n\n return { publicKey, privateKey };\n }\n\n public getKey(keyId: string): Buffer | undefined {\n return this.keys.get(keyId);\n }\n\n public async rotateKey(keyId: string): Promise<Buffer> {\n const newKey = this.generateKey(`${keyId}_${Date.now()}`);\n this.keys.set(keyId, newKey);\n \n const oldKey = this.keys.get(`${keyId}_old`);\n if (oldKey) {\n await this.archiveKey(keyId, oldKey);\n }\n \n return newKey;\n }\n\n public async deriveKey(password: string, salt?: Buffer): Promise<Buffer> {\n const useSalt = salt || crypto.randomBytes(16);\n \n return new Promise((resolve, reject) => {\n crypto.scrypt(password, useSalt, 32, (err, derivedKey) => {\n if (err) reject(err);\n else resolve(derivedKey);\n });\n });\n }\n\n public generateSessionKey(): Buffer {\n return crypto.randomBytes(32);\n }\n\n public generateIV(): Buffer {\n return crypto.randomBytes(16);\n }\n\n public async encryptWithMasterKey(data: Buffer): Promise<Buffer> {\n if (!this.masterKey) {\n throw new Error('Master key not initialized');\n }\n\n const iv = crypto.randomBytes(16);\n const cipher = crypto.createCipheriv('aes-256-gcm', this.masterKey, iv);\n \n const encrypted = Buffer.concat([\n cipher.update(data),\n cipher.final()\n ]);\n \n const authTag = cipher.getAuthTag();\n \n return Buffer.concat([iv, authTag, encrypted]);\n }\n\n public async decryptWithMasterKey(encryptedData: Buffer): Promise<Buffer> {\n if (!this.masterKey) {\n throw new Error('Master key not initialized');\n }\n\n const iv = encryptedData.subarray(0, 16);\n const authTag = encryptedData.subarray(16, 32);\n const data = encryptedData.subarray(32);\n\n const decipher = crypto.createDecipheriv('aes-256-gcm', this.masterKey, iv);\n decipher.setAuthTag(authTag);\n\n return Buffer.concat([\n decipher.update(data),\n decipher.final()\n ]);\n }\n\n public async signData(keyId: string, data: Buffer): Promise<Buffer> {\n const privateKey = this.keys.get(keyId);\n if (!privateKey) {\n throw new Error(`Key not found: ${keyId}`);\n }\n\n const sign = crypto.createSign('RSA-SHA256');\n sign.update(data);\n \n return sign.sign({\n key: privateKey,\n format: 'der',\n type: 'pkcs8'\n });\n }\n\n public async verifySignature(\n keyId: string,\n data: Buffer,\n signature: Buffer\n ): Promise<boolean> {\n const publicKey = this.keys.get(keyId);\n if (!publicKey) {\n throw new Error(`Key not found: ${keyId}`);\n }\n\n const verify = crypto.createVerify('RSA-SHA256');\n verify.update(data);\n\n return verify.verify({\n key: publicKey,\n format: 'der',\n type: 'spki'\n }, signature);\n }\n\n private async saveKeyToDisk(keyId: string, keyData: Buffer): Promise<void> {\n try {\n const keyPath = path.join(this.keyDir, `${keyId}.key`);\n const encrypted = await this.encryptWithMasterKey(keyData);\n await fs.writeFile(keyPath, encrypted, { mode: 0o400 });\n } catch (error) {\n Logger.getInstance().error(`Failed to save key: ${keyId}`, { error });\n }\n }\n\n private async encryptMasterKey(key: Buffer): Promise<Buffer> {\n const platformKey = await this.getPlatformKey();\n \n const iv = crypto.randomBytes(16);\n const cipher = crypto.createCipheriv('aes-256-gcm', platformKey, iv);\n \n const encrypted = Buffer.concat([\n cipher.update(key),\n cipher.final()\n ]);\n \n const authTag = cipher.getAuthTag();\n \n return Buffer.concat([iv, authTag, encrypted]);\n }\n\n private async decryptMasterKey(encrypted: Buffer): Promise<Buffer> {\n const platformKey = await this.getPlatformKey();\n \n const iv = encrypted.subarray(0, 16);\n const authTag = encrypted.subarray(16, 32);\n const data = encrypted.subarray(32);\n\n const decipher = crypto.createDecipheriv('aes-256-gcm', platformKey, iv);\n decipher.setAuthTag(authTag);\n\n return Buffer.concat([\n decipher.update(data),\n decipher.final()\n ]);\n }\n\n private async getPlatformKey(): Promise<Buffer> {\n const platformData = [\n process.platform,\n process.arch,\n process.cwd(),\n __filename,\n process.pid\n ].join('|');\n\n return crypto.createHash('sha256').update(platformData).digest();\n }\n\n private async archiveKey(keyId: string, keyData: Buffer): Promise<void> {\n const archiveDir = path.join(this.keyDir, 'archive');\n await fs.mkdir(archiveDir, { recursive: true });\n \n const archivePath = path.join(archiveDir, `${keyId}_${Date.now()}.key.old`);\n const encrypted = await this.encryptWithMasterKey(keyData);\n await fs.writeFile(archivePath, encrypted, { mode: 0o400 });\n }\n\n public getStatus(): any {\n return {\n keyCount: this.keys.size,\n masterKeyInitialized: this.masterKey !== null,\n keyDirectory: this.keyDir\n };\n }\n}"]}
@@ -0,0 +1,11 @@
1
+ export declare class SignatureValidator {
2
+ private readonly logger;
3
+ private readonly keyPair;
4
+ constructor();
5
+ private generateKeyPair;
6
+ generateSignature(data: Buffer): Promise<string>;
7
+ validateSignature(data: Buffer, signature: string): Promise<boolean>;
8
+ exportPublicKey(): string;
9
+ getStatus(): any;
10
+ }
11
+ //# sourceMappingURL=SignatureValidator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SignatureValidator.d.ts","sourceRoot":"","sources":["../../src/crypto/SignatureValidator.ts"],"names":[],"mappings":"AAGA,qBAAa,kBAAkB;IAC3B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA4C;;IAQpE,OAAO,CAAC,eAAe;IAgBV,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAkBhD,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAgB1E,eAAe,IAAI,MAAM;IAIzB,SAAS,IAAI,GAAG;CAQ1B"}