json-database-st 1.0.6 → 1.0.7
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.
- package/JSONDatabase.js +490 -484
- package/LICENSE +1 -1
- package/package.json +1 -1
package/JSONDatabase.js
CHANGED
|
@@ -1,485 +1,491 @@
|
|
|
1
|
-
// File: JSONDatabase.js
|
|
2
|
-
// Final, Complete, and Secure Version
|
|
3
|
-
|
|
4
|
-
const fs = require('fs').promises;
|
|
5
|
-
const path = require('path');
|
|
6
|
-
const crypto = require('crypto');
|
|
7
|
-
const _ = require('lodash');
|
|
8
|
-
const EventEmitter = require('events');
|
|
9
|
-
|
|
10
|
-
// --- Custom Error Classes for Better Error Handling ---
|
|
11
|
-
|
|
12
|
-
/** Base error for all database-specific issues. */
|
|
13
|
-
class DBError extends Error {
|
|
14
|
-
constructor(message) {
|
|
15
|
-
super(message);
|
|
16
|
-
this.name = this.constructor.name;
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
/** Error during database file initialization or parsing. */
|
|
20
|
-
class DBInitializationError extends DBError {}
|
|
21
|
-
/** Error within a user-provided transaction function. */
|
|
22
|
-
class TransactionError extends DBError {}
|
|
23
|
-
/** Error when data fails schema validation. */
|
|
24
|
-
class ValidationError extends DBError {
|
|
25
|
-
constructor(message, validationIssues) {
|
|
26
|
-
super(message);
|
|
27
|
-
this.issues = validationIssues; // e.g., from Zod/Joi
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
/** Error related to index integrity (e.g., unique constraint violation). */
|
|
31
|
-
class IndexViolationError extends DBError {}
|
|
32
|
-
/** Error for security-related issues like path traversal or bad keys. */
|
|
33
|
-
class SecurityError extends DBError {}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
// --- Type Definitions for Clarity ---
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* @typedef {object} BatchOperationSet
|
|
40
|
-
* @property {'set'} type
|
|
41
|
-
* @property {string | string[]} path
|
|
42
|
-
* @property {any} value
|
|
43
|
-
*/
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* @typedef {object} BatchOperationDelete
|
|
47
|
-
* @property {'delete'} type
|
|
48
|
-
* @property {string | string[]} path
|
|
49
|
-
*/
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* @typedef {object} BatchOperationPush
|
|
53
|
-
* @property {'push'} type
|
|
54
|
-
* @property {string | string[]} path
|
|
55
|
-
* @property {any[]} values - Items to push uniquely using deep comparison.
|
|
56
|
-
*/
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* @typedef {object} BatchOperationPull
|
|
60
|
-
* @property {'pull'} type
|
|
61
|
-
* @property {string | string[]} path
|
|
62
|
-
* @property {any[]} values - Items to remove using deep comparison.
|
|
63
|
-
*/
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* @typedef {BatchOperationSet | BatchOperationDelete | BatchOperationPush | BatchOperationPull} BatchOperation
|
|
67
|
-
*/
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* @typedef {object} IndexDefinition
|
|
71
|
-
* @property {string} name - The unique name for the index.
|
|
72
|
-
* @property {string | string[]} path - The lodash path to the collection object (e.g., 'users').
|
|
73
|
-
* @property {string} field - The property field within each collection item to index (e.g., 'email').
|
|
74
|
-
* @property {boolean} [unique=false] - If true, enforces that the indexed field must be unique across the collection.
|
|
75
|
-
*/
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
// --- Cryptography Constants ---
|
|
79
|
-
const ALGORITHM = 'aes-256-gcm';
|
|
80
|
-
const IV_LENGTH = 16;
|
|
81
|
-
const AUTH_TAG_LENGTH = 16;
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* A robust, secure, promise-based JSON file database with atomic operations, indexing, schema validation, and events.
|
|
86
|
-
* Includes encryption-at-rest and path traversal protection.
|
|
87
|
-
*
|
|
88
|
-
* @class JSONDatabase
|
|
89
|
-
* @extends {EventEmitter}
|
|
90
|
-
*/
|
|
91
|
-
class JSONDatabase extends EventEmitter {
|
|
92
|
-
/**
|
|
93
|
-
* Creates a database instance.
|
|
94
|
-
*
|
|
95
|
-
* @param {string} filename - Database file path.
|
|
96
|
-
* @param {object} [options] - Configuration options.
|
|
97
|
-
* @param {string} [options.encryptionKey=null] - A 32-byte (64-character hex) secret key for encryption. If provided, enables encryption-at-rest. **MANAGE THIS KEY SECURELY.**
|
|
98
|
-
* @param {boolean} [options.prettyPrint=false] - Pretty-print JSON output (only if not encrypted).
|
|
99
|
-
* @param {boolean} [options.writeOnChange=true] - Only write to disk if data has changed.
|
|
100
|
-
* @param {object} [options.schema=null] - A validation schema (e.g., from Zod) with a `safeParse` method.
|
|
101
|
-
* @param {IndexDefinition[]} [options.indices=[]] - An array of index definitions for fast lookups.
|
|
102
|
-
* @throws {SecurityError} If the filename is invalid or attempts path traversal.
|
|
103
|
-
* @throws {SecurityError} If an encryption key is provided but is not the correct length.
|
|
104
|
-
*/
|
|
105
|
-
constructor(filename, options = {}) {
|
|
106
|
-
super();
|
|
107
|
-
|
|
108
|
-
// --- Security Check: Path Traversal ---
|
|
109
|
-
const resolvedPath = path.resolve(filename);
|
|
110
|
-
const workingDir = process.cwd();
|
|
111
|
-
if (!resolvedPath.startsWith(workingDir)) {
|
|
112
|
-
throw new SecurityError(`Path traversal detected. Database path must be within the project directory: ${workingDir}`);
|
|
113
|
-
}
|
|
114
|
-
this.filename = /\.json$/.test(resolvedPath) ? resolvedPath : `${resolvedPath}.json`;
|
|
115
|
-
|
|
116
|
-
// --- Security Check: Encryption Key ---
|
|
117
|
-
if (options.encryptionKey && (!options.encryptionKey || Buffer.from(options.encryptionKey, 'hex').length !== 32)) {
|
|
118
|
-
throw new SecurityError('Encryption key must be a 32-byte (64-character hex) string.');
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
this.config = {
|
|
122
|
-
prettyPrint: options.prettyPrint === true,
|
|
123
|
-
writeOnChange: options.writeOnChange !== false,
|
|
124
|
-
schema: options.schema || null,
|
|
125
|
-
indices: options.indices || [],
|
|
126
|
-
encryptionKey: options.encryptionKey ? Buffer.from(options.encryptionKey, 'hex') : null,
|
|
127
|
-
};
|
|
128
|
-
|
|
129
|
-
this.cache = null;
|
|
130
|
-
this.writeLock = Promise.resolve();
|
|
131
|
-
this.stats = { reads: 0, writes: 0, cacheHits: 0 };
|
|
132
|
-
this._indices = new Map();
|
|
133
|
-
|
|
134
|
-
// Asynchronously initialize. Operations will queue behind this promise.
|
|
135
|
-
this._initPromise = this._initialize();
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
// --- Encryption & Decryption ---
|
|
139
|
-
_encrypt(data) {
|
|
140
|
-
const iv = crypto.randomBytes(IV_LENGTH);
|
|
141
|
-
const cipher = crypto.createCipheriv(ALGORITHM, this.config.encryptionKey, iv);
|
|
142
|
-
const jsonString = JSON.stringify(data);
|
|
143
|
-
const encrypted = Buffer.concat([cipher.update(jsonString, 'utf8'), cipher.final()]);
|
|
144
|
-
const authTag = cipher.getAuthTag();
|
|
145
|
-
return JSON.stringify({
|
|
146
|
-
iv: iv.toString('hex'),
|
|
147
|
-
tag: authTag.toString('hex'),
|
|
148
|
-
content: encrypted.toString('hex'),
|
|
149
|
-
});
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
_decrypt(encryptedPayload) {
|
|
153
|
-
try {
|
|
154
|
-
const payload = JSON.parse(encryptedPayload);
|
|
155
|
-
const iv = Buffer.from(payload.iv, 'hex');
|
|
156
|
-
const authTag = Buffer.from(payload.tag, 'hex');
|
|
157
|
-
const encryptedContent = Buffer.from(payload.content, 'hex');
|
|
158
|
-
const decipher = crypto.createDecipheriv(ALGORITHM, this.config.encryptionKey, iv);
|
|
159
|
-
decipher.setAuthTag(authTag);
|
|
160
|
-
const decrypted = decipher.update(encryptedContent, 'hex', 'utf8') + decipher.final('utf8');
|
|
161
|
-
return JSON.parse(decrypted);
|
|
162
|
-
} catch (e) {
|
|
163
|
-
throw new SecurityError('Decryption failed. The file may be corrupted, tampered with, or the encryption key is incorrect.');
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
// --- Private Core Methods ---
|
|
168
|
-
|
|
169
|
-
/** @private Kicks off the initialization process. */
|
|
170
|
-
async _initialize() {
|
|
171
|
-
try {
|
|
172
|
-
await this._refreshCache();
|
|
173
|
-
this._rebuildAllIndices();
|
|
174
|
-
} catch (err) {
|
|
175
|
-
const initError = new DBInitializationError(`Failed to initialize database: ${err.message}`);
|
|
176
|
-
this.emit('error', initError);
|
|
177
|
-
console.error(`[JSONDatabase] FATAL: Initialization failed for ${this.filename}. The database is in an unusable state.`, err);
|
|
178
|
-
throw initError;
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
/** @private Reads file, decrypts if necessary, and populates cache. */
|
|
183
|
-
async _refreshCache() {
|
|
184
|
-
try {
|
|
185
|
-
const fileContent = await fs.readFile(this.filename, 'utf8');
|
|
186
|
-
if (this.config.encryptionKey) {
|
|
187
|
-
this.cache = fileContent.trim() === '' ? {} : this._decrypt(fileContent);
|
|
188
|
-
} else {
|
|
189
|
-
this.cache = fileContent.trim() === '' ? {} : JSON.parse(fileContent);
|
|
190
|
-
}
|
|
191
|
-
this.stats.reads++;
|
|
192
|
-
} catch (err) {
|
|
193
|
-
if (err.code === 'ENOENT') {
|
|
194
|
-
console.warn(`[JSONDatabase] File ${this.filename} not found. Creating.`);
|
|
195
|
-
this.cache = {};
|
|
196
|
-
const initialContent = this.config.encryptionKey ? this._encrypt({}) : '{}';
|
|
197
|
-
await fs.writeFile(this.filename, initialContent, 'utf8');
|
|
198
|
-
this.stats.writes++;
|
|
199
|
-
} else if (err instanceof SyntaxError && !this.config.encryptionKey) {
|
|
200
|
-
throw new DBInitializationError(`Failed to parse JSON from ${this.filename}. File is corrupted.`);
|
|
201
|
-
} else {
|
|
202
|
-
throw err; // Re-throw security, crypto, and other errors
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
/** @private Ensures all operations wait for initialization to complete. */
|
|
208
|
-
async _ensureInitialized() {
|
|
209
|
-
return this._initPromise;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
/** @private Performs an atomic write operation. */
|
|
213
|
-
async _atomicWrite(operationFn) {
|
|
214
|
-
await this._ensureInitialized();
|
|
215
|
-
|
|
216
|
-
this.writeLock = this.writeLock.then(async () => {
|
|
217
|
-
const oldData = this.cache;
|
|
218
|
-
const dataToModify = _.cloneDeep(oldData);
|
|
219
|
-
|
|
220
|
-
try {
|
|
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
|
-
this.
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
this.
|
|
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
|
-
const
|
|
283
|
-
|
|
284
|
-
const
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
const
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
const
|
|
291
|
-
|
|
292
|
-
const
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
const
|
|
316
|
-
const
|
|
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
|
-
return _.
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
async
|
|
347
|
-
await this.
|
|
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
|
-
this.
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
1
|
+
// File: JSONDatabase.js
|
|
2
|
+
// Final, Complete, and Secure Version (Patched)
|
|
3
|
+
|
|
4
|
+
const fs = require('fs').promises;
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const crypto = require('crypto');
|
|
7
|
+
const _ = require('lodash');
|
|
8
|
+
const EventEmitter = require('events');
|
|
9
|
+
|
|
10
|
+
// --- Custom Error Classes for Better Error Handling ---
|
|
11
|
+
|
|
12
|
+
/** Base error for all database-specific issues. */
|
|
13
|
+
class DBError extends Error {
|
|
14
|
+
constructor(message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = this.constructor.name;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/** Error during database file initialization or parsing. */
|
|
20
|
+
class DBInitializationError extends DBError {}
|
|
21
|
+
/** Error within a user-provided transaction function. */
|
|
22
|
+
class TransactionError extends DBError {}
|
|
23
|
+
/** Error when data fails schema validation. */
|
|
24
|
+
class ValidationError extends DBError {
|
|
25
|
+
constructor(message, validationIssues) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.issues = validationIssues; // e.g., from Zod/Joi
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** Error related to index integrity (e.g., unique constraint violation). */
|
|
31
|
+
class IndexViolationError extends DBError {}
|
|
32
|
+
/** Error for security-related issues like path traversal or bad keys. */
|
|
33
|
+
class SecurityError extends DBError {}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
// --- Type Definitions for Clarity ---
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @typedef {object} BatchOperationSet
|
|
40
|
+
* @property {'set'} type
|
|
41
|
+
* @property {string | string[]} path
|
|
42
|
+
* @property {any} value
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @typedef {object} BatchOperationDelete
|
|
47
|
+
* @property {'delete'} type
|
|
48
|
+
* @property {string | string[]} path
|
|
49
|
+
*/
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* @typedef {object} BatchOperationPush
|
|
53
|
+
* @property {'push'} type
|
|
54
|
+
* @property {string | string[]} path
|
|
55
|
+
* @property {any[]} values - Items to push uniquely using deep comparison.
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @typedef {object} BatchOperationPull
|
|
60
|
+
* @property {'pull'} type
|
|
61
|
+
* @property {string | string[]} path
|
|
62
|
+
* @property {any[]} values - Items to remove using deep comparison.
|
|
63
|
+
*/
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* @typedef {BatchOperationSet | BatchOperationDelete | BatchOperationPush | BatchOperationPull} BatchOperation
|
|
67
|
+
*/
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* @typedef {object} IndexDefinition
|
|
71
|
+
* @property {string} name - The unique name for the index.
|
|
72
|
+
* @property {string | string[]} path - The lodash path to the collection object (e.g., 'users').
|
|
73
|
+
* @property {string} field - The property field within each collection item to index (e.g., 'email').
|
|
74
|
+
* @property {boolean} [unique=false] - If true, enforces that the indexed field must be unique across the collection.
|
|
75
|
+
*/
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
// --- Cryptography Constants ---
|
|
79
|
+
const ALGORITHM = 'aes-256-gcm';
|
|
80
|
+
const IV_LENGTH = 16;
|
|
81
|
+
const AUTH_TAG_LENGTH = 16;
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* A robust, secure, promise-based JSON file database with atomic operations, indexing, schema validation, and events.
|
|
86
|
+
* Includes encryption-at-rest and path traversal protection.
|
|
87
|
+
*
|
|
88
|
+
* @class JSONDatabase
|
|
89
|
+
* @extends {EventEmitter}
|
|
90
|
+
*/
|
|
91
|
+
class JSONDatabase extends EventEmitter {
|
|
92
|
+
/**
|
|
93
|
+
* Creates a database instance.
|
|
94
|
+
*
|
|
95
|
+
* @param {string} filename - Database file path.
|
|
96
|
+
* @param {object} [options] - Configuration options.
|
|
97
|
+
* @param {string} [options.encryptionKey=null] - A 32-byte (64-character hex) secret key for encryption. If provided, enables encryption-at-rest. **MANAGE THIS KEY SECURELY.**
|
|
98
|
+
* @param {boolean} [options.prettyPrint=false] - Pretty-print JSON output (only if not encrypted).
|
|
99
|
+
* @param {boolean} [options.writeOnChange=true] - Only write to disk if data has changed.
|
|
100
|
+
* @param {object} [options.schema=null] - A validation schema (e.g., from Zod) with a `safeParse` method.
|
|
101
|
+
* @param {IndexDefinition[]} [options.indices=[]] - An array of index definitions for fast lookups.
|
|
102
|
+
* @throws {SecurityError} If the filename is invalid or attempts path traversal.
|
|
103
|
+
* @throws {SecurityError} If an encryption key is provided but is not the correct length.
|
|
104
|
+
*/
|
|
105
|
+
constructor(filename, options = {}) {
|
|
106
|
+
super();
|
|
107
|
+
|
|
108
|
+
// --- Security Check: Path Traversal ---
|
|
109
|
+
const resolvedPath = path.resolve(filename);
|
|
110
|
+
const workingDir = process.cwd();
|
|
111
|
+
if (!resolvedPath.startsWith(workingDir)) {
|
|
112
|
+
throw new SecurityError(`Path traversal detected. Database path must be within the project directory: ${workingDir}`);
|
|
113
|
+
}
|
|
114
|
+
this.filename = /\.json$/.test(resolvedPath) ? resolvedPath : `${resolvedPath}.json`;
|
|
115
|
+
|
|
116
|
+
// --- Security Check: Encryption Key ---
|
|
117
|
+
if (options.encryptionKey && (!options.encryptionKey || Buffer.from(options.encryptionKey, 'hex').length !== 32)) {
|
|
118
|
+
throw new SecurityError('Encryption key must be a 32-byte (64-character hex) string.');
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
this.config = {
|
|
122
|
+
prettyPrint: options.prettyPrint === true,
|
|
123
|
+
writeOnChange: options.writeOnChange !== false,
|
|
124
|
+
schema: options.schema || null,
|
|
125
|
+
indices: options.indices || [],
|
|
126
|
+
encryptionKey: options.encryptionKey ? Buffer.from(options.encryptionKey, 'hex') : null,
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
this.cache = null;
|
|
130
|
+
this.writeLock = Promise.resolve();
|
|
131
|
+
this.stats = { reads: 0, writes: 0, cacheHits: 0 };
|
|
132
|
+
this._indices = new Map();
|
|
133
|
+
|
|
134
|
+
// Asynchronously initialize. Operations will queue behind this promise.
|
|
135
|
+
this._initPromise = this._initialize();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// --- Encryption & Decryption ---
|
|
139
|
+
_encrypt(data) {
|
|
140
|
+
const iv = crypto.randomBytes(IV_LENGTH);
|
|
141
|
+
const cipher = crypto.createCipheriv(ALGORITHM, this.config.encryptionKey, iv);
|
|
142
|
+
const jsonString = JSON.stringify(data);
|
|
143
|
+
const encrypted = Buffer.concat([cipher.update(jsonString, 'utf8'), cipher.final()]);
|
|
144
|
+
const authTag = cipher.getAuthTag();
|
|
145
|
+
return JSON.stringify({
|
|
146
|
+
iv: iv.toString('hex'),
|
|
147
|
+
tag: authTag.toString('hex'),
|
|
148
|
+
content: encrypted.toString('hex'),
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
_decrypt(encryptedPayload) {
|
|
153
|
+
try {
|
|
154
|
+
const payload = JSON.parse(encryptedPayload);
|
|
155
|
+
const iv = Buffer.from(payload.iv, 'hex');
|
|
156
|
+
const authTag = Buffer.from(payload.tag, 'hex');
|
|
157
|
+
const encryptedContent = Buffer.from(payload.content, 'hex');
|
|
158
|
+
const decipher = crypto.createDecipheriv(ALGORITHM, this.config.encryptionKey, iv);
|
|
159
|
+
decipher.setAuthTag(authTag);
|
|
160
|
+
const decrypted = decipher.update(encryptedContent, 'hex', 'utf8') + decipher.final('utf8');
|
|
161
|
+
return JSON.parse(decrypted);
|
|
162
|
+
} catch (e) {
|
|
163
|
+
throw new SecurityError('Decryption failed. The file may be corrupted, tampered with, or the encryption key is incorrect.');
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// --- Private Core Methods ---
|
|
168
|
+
|
|
169
|
+
/** @private Kicks off the initialization process. */
|
|
170
|
+
async _initialize() {
|
|
171
|
+
try {
|
|
172
|
+
await this._refreshCache();
|
|
173
|
+
this._rebuildAllIndices();
|
|
174
|
+
} catch (err) {
|
|
175
|
+
const initError = new DBInitializationError(`Failed to initialize database: ${err.message}`);
|
|
176
|
+
this.emit('error', initError);
|
|
177
|
+
console.error(`[JSONDatabase] FATAL: Initialization failed for ${this.filename}. The database is in an unusable state.`, err);
|
|
178
|
+
throw initError;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** @private Reads file, decrypts if necessary, and populates cache. */
|
|
183
|
+
async _refreshCache() {
|
|
184
|
+
try {
|
|
185
|
+
const fileContent = await fs.readFile(this.filename, 'utf8');
|
|
186
|
+
if (this.config.encryptionKey) {
|
|
187
|
+
this.cache = fileContent.trim() === '' ? {} : this._decrypt(fileContent);
|
|
188
|
+
} else {
|
|
189
|
+
this.cache = fileContent.trim() === '' ? {} : JSON.parse(fileContent);
|
|
190
|
+
}
|
|
191
|
+
this.stats.reads++;
|
|
192
|
+
} catch (err) {
|
|
193
|
+
if (err.code === 'ENOENT') {
|
|
194
|
+
console.warn(`[JSONDatabase] File ${this.filename} not found. Creating.`);
|
|
195
|
+
this.cache = {};
|
|
196
|
+
const initialContent = this.config.encryptionKey ? this._encrypt({}) : '{}';
|
|
197
|
+
await fs.writeFile(this.filename, initialContent, 'utf8');
|
|
198
|
+
this.stats.writes++;
|
|
199
|
+
} else if (err instanceof SyntaxError && !this.config.encryptionKey) {
|
|
200
|
+
throw new DBInitializationError(`Failed to parse JSON from ${this.filename}. File is corrupted.`);
|
|
201
|
+
} else {
|
|
202
|
+
throw err; // Re-throw security, crypto, and other errors
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** @private Ensures all operations wait for initialization to complete. */
|
|
208
|
+
async _ensureInitialized() {
|
|
209
|
+
return this._initPromise;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** @private Performs an atomic write operation. */
|
|
213
|
+
async _atomicWrite(operationFn) {
|
|
214
|
+
await this._ensureInitialized();
|
|
215
|
+
|
|
216
|
+
this.writeLock = this.writeLock.then(async () => {
|
|
217
|
+
const oldData = this.cache;
|
|
218
|
+
const dataToModify = _.cloneDeep(oldData);
|
|
219
|
+
|
|
220
|
+
try {
|
|
221
|
+
// --- FIX: Await the operation function in case it's async ---
|
|
222
|
+
const newData = await operationFn(dataToModify);
|
|
223
|
+
|
|
224
|
+
if (newData === undefined) {
|
|
225
|
+
throw new TransactionError("Atomic operation function returned undefined. Aborting to prevent data loss.");
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (this.config.schema) {
|
|
229
|
+
const validationResult = this.config.schema.safeParse(newData);
|
|
230
|
+
if (!validationResult.success) {
|
|
231
|
+
throw new ValidationError('Schema validation failed.', validationResult.error.issues);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (this.config.writeOnChange && _.isEqual(newData, oldData)) {
|
|
236
|
+
return oldData;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
this._updateIndices(oldData, newData);
|
|
240
|
+
|
|
241
|
+
const contentToWrite = this.config.encryptionKey
|
|
242
|
+
? this._encrypt(newData)
|
|
243
|
+
: JSON.stringify(newData, null, this.config.prettyPrint ? 2 : 0);
|
|
244
|
+
|
|
245
|
+
await fs.writeFile(this.filename, contentToWrite, 'utf8');
|
|
246
|
+
|
|
247
|
+
this.cache = newData;
|
|
248
|
+
this.stats.writes++;
|
|
249
|
+
|
|
250
|
+
this.emit('write', { filename: this.filename, timestamp: Date.now() });
|
|
251
|
+
this.emit('change', { oldValue: oldData, newValue: newData });
|
|
252
|
+
|
|
253
|
+
return newData;
|
|
254
|
+
|
|
255
|
+
} catch (error) {
|
|
256
|
+
this.emit('error', error);
|
|
257
|
+
console.error("[JSONDatabase] Atomic write failed. No changes were saved.", error);
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
return this.writeLock;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// --- Indexing ---
|
|
266
|
+
|
|
267
|
+
/** @private Clears and rebuilds all defined indices from the current cache. */
|
|
268
|
+
_rebuildAllIndices() {
|
|
269
|
+
this._indices.clear();
|
|
270
|
+
for (const indexDef of this.config.indices) {
|
|
271
|
+
this._indices.set(indexDef.name, new Map());
|
|
272
|
+
}
|
|
273
|
+
if (this.config.indices.length > 0 && !_.isEmpty(this.cache)) {
|
|
274
|
+
this._updateIndices({}, this.cache); // Treat it as a full "add" operation
|
|
275
|
+
}
|
|
276
|
+
console.log(`[JSONDatabase] Rebuilt ${this.config.indices.length} indices for ${this.filename}.`);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** @private Compares old and new data to update indices efficiently. */
|
|
280
|
+
_updateIndices(oldData, newData) {
|
|
281
|
+
for (const indexDef of this.config.indices) {
|
|
282
|
+
const collectionPath = indexDef.path;
|
|
283
|
+
const field = indexDef.field;
|
|
284
|
+
const indexMap = this._indices.get(indexDef.name);
|
|
285
|
+
|
|
286
|
+
const oldCollection = _.get(oldData, collectionPath, {});
|
|
287
|
+
const newCollection = _.get(newData, collectionPath, {});
|
|
288
|
+
|
|
289
|
+
const oldKeys = Object.keys(oldCollection);
|
|
290
|
+
const newKeys = Object.keys(newCollection);
|
|
291
|
+
|
|
292
|
+
const addedKeys = _.difference(newKeys, oldKeys);
|
|
293
|
+
const removedKeys = _.difference(oldKeys, newKeys);
|
|
294
|
+
const potentiallyModifiedKeys = _.intersection(oldKeys, newKeys);
|
|
295
|
+
|
|
296
|
+
for (const key of removedKeys) {
|
|
297
|
+
const oldItem = oldCollection[key];
|
|
298
|
+
if (oldItem && oldItem[field] !== undefined) {
|
|
299
|
+
indexMap.delete(oldItem[field]);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
for (const key of addedKeys) {
|
|
304
|
+
const newItem = newCollection[key];
|
|
305
|
+
const indexValue = newItem?.[field];
|
|
306
|
+
if (indexValue !== undefined) {
|
|
307
|
+
if (indexDef.unique && indexMap.has(indexValue)) {
|
|
308
|
+
throw new IndexViolationError(`Unique index '${indexDef.name}' violated for value '${indexValue}'.`);
|
|
309
|
+
}
|
|
310
|
+
indexMap.set(indexValue, key);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
for (const key of potentiallyModifiedKeys) {
|
|
315
|
+
const oldItem = oldCollection[key];
|
|
316
|
+
const newItem = newCollection[key];
|
|
317
|
+
const oldIndexValue = oldItem?.[field];
|
|
318
|
+
const newIndexValue = newItem?.[field];
|
|
319
|
+
|
|
320
|
+
if (!_.isEqual(oldItem, newItem) && oldIndexValue !== newIndexValue) {
|
|
321
|
+
if (oldIndexValue !== undefined) indexMap.delete(oldIndexValue);
|
|
322
|
+
if (newIndexValue !== undefined) {
|
|
323
|
+
if (indexDef.unique && indexMap.has(newIndexValue)) {
|
|
324
|
+
throw new IndexViolationError(`Unique index '${indexDef.name}' violated for value '${newIndexValue}'.`);
|
|
325
|
+
}
|
|
326
|
+
indexMap.set(newIndexValue, key);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
// --- Public API ---
|
|
335
|
+
|
|
336
|
+
async get(path, defaultValue) {
|
|
337
|
+
await this._ensureInitialized();
|
|
338
|
+
this.stats.cacheHits++;
|
|
339
|
+
// --- FIX: Handle undefined/null path to get the entire object ---
|
|
340
|
+
if (path === undefined || path === null) {
|
|
341
|
+
return this.cache;
|
|
342
|
+
}
|
|
343
|
+
return _.get(this.cache, path, defaultValue);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async has(path) {
|
|
347
|
+
await this._ensureInitialized();
|
|
348
|
+
this.stats.cacheHits++;
|
|
349
|
+
return _.has(this.cache, path);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
async set(path, value) {
|
|
353
|
+
await this._atomicWrite(data => {
|
|
354
|
+
_.set(data, path, value);
|
|
355
|
+
return data;
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
async delete(path) {
|
|
360
|
+
let deleted = false;
|
|
361
|
+
await this._atomicWrite(data => {
|
|
362
|
+
deleted = _.unset(data, path);
|
|
363
|
+
return data;
|
|
364
|
+
});
|
|
365
|
+
return deleted;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async push(path, ...items) {
|
|
369
|
+
if (items.length === 0) return;
|
|
370
|
+
await this._atomicWrite(data => {
|
|
371
|
+
const arr = _.get(data, path);
|
|
372
|
+
const targetArray = Array.isArray(arr) ? arr : [];
|
|
373
|
+
items.forEach(item => {
|
|
374
|
+
if (!targetArray.some(existing => _.isEqual(existing, item))) {
|
|
375
|
+
targetArray.push(item);
|
|
376
|
+
}
|
|
377
|
+
});
|
|
378
|
+
_.set(data, path, targetArray);
|
|
379
|
+
return data;
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
async pull(path, ...itemsToRemove) {
|
|
384
|
+
if (itemsToRemove.length === 0) return;
|
|
385
|
+
await this._atomicWrite(data => {
|
|
386
|
+
const arr = _.get(data, path);
|
|
387
|
+
if (Array.isArray(arr)) {
|
|
388
|
+
_.pullAllWith(arr, itemsToRemove, _.isEqual);
|
|
389
|
+
}
|
|
390
|
+
return data;
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
async transaction(transactionFn) {
|
|
395
|
+
return this._atomicWrite(transactionFn);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
async batch(ops, options = { stopOnError: false }) {
|
|
399
|
+
if (!Array.isArray(ops) || ops.length === 0) return;
|
|
400
|
+
|
|
401
|
+
await this._atomicWrite(data => {
|
|
402
|
+
for (const [index, op] of ops.entries()) {
|
|
403
|
+
try {
|
|
404
|
+
if (!op || !op.type || op.path === undefined) throw new Error("Invalid operation format: missing type or path.");
|
|
405
|
+
|
|
406
|
+
switch (op.type) {
|
|
407
|
+
case 'set':
|
|
408
|
+
if (!op.hasOwnProperty('value')) throw new Error("Set operation missing 'value'.");
|
|
409
|
+
_.set(data, op.path, op.value);
|
|
410
|
+
break;
|
|
411
|
+
case 'delete':
|
|
412
|
+
_.unset(data, op.path);
|
|
413
|
+
break;
|
|
414
|
+
case 'push':
|
|
415
|
+
if (!Array.isArray(op.values)) throw new Error("Push operation 'values' must be an array.");
|
|
416
|
+
const arr = _.get(data, op.path);
|
|
417
|
+
const targetArray = Array.isArray(arr) ? arr : [];
|
|
418
|
+
op.values.forEach(item => {
|
|
419
|
+
if (!targetArray.some(existing => _.isEqual(existing, item))) targetArray.push(item);
|
|
420
|
+
});
|
|
421
|
+
_.set(data, op.path, targetArray);
|
|
422
|
+
break;
|
|
423
|
+
case 'pull':
|
|
424
|
+
if (!Array.isArray(op.values)) throw new Error("Pull operation 'values' must be an array.");
|
|
425
|
+
const pullArr = _.get(data, op.path);
|
|
426
|
+
if (Array.isArray(pullArr)) _.pullAllWith(pullArr, op.values, _.isEqual);
|
|
427
|
+
break;
|
|
428
|
+
default:
|
|
429
|
+
throw new Error(`Unsupported operation type: '${op.type}'.`);
|
|
430
|
+
}
|
|
431
|
+
} catch (err) {
|
|
432
|
+
const errorMessage = `[JSONDatabase] Batch failed at operation index ${index} (type: ${op?.type}): ${err.message}`;
|
|
433
|
+
if (options.stopOnError) {
|
|
434
|
+
throw new Error(errorMessage);
|
|
435
|
+
} else {
|
|
436
|
+
console.error(errorMessage);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
return data;
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
async find(collectionPath, predicate) {
|
|
445
|
+
await this._ensureInitialized();
|
|
446
|
+
const collection = _.get(this.cache, collectionPath);
|
|
447
|
+
if (typeof collection !== 'object' || collection === null) return undefined;
|
|
448
|
+
|
|
449
|
+
this.stats.cacheHits++;
|
|
450
|
+
return _.find(collection, predicate);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
async findByIndex(indexName, value) {
|
|
454
|
+
await this._ensureInitialized();
|
|
455
|
+
if (!this._indices.has(indexName)) {
|
|
456
|
+
throw new Error(`Index with name '${indexName}' does not exist.`);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
this.stats.cacheHits++;
|
|
460
|
+
const indexMap = this._indices.get(indexName);
|
|
461
|
+
const objectKey = indexMap.get(value);
|
|
462
|
+
|
|
463
|
+
if (objectKey === undefined) return undefined;
|
|
464
|
+
|
|
465
|
+
const indexDef = this.config.indices.find(i => i.name === indexName);
|
|
466
|
+
return _.get(this.cache, [..._.toPath(indexDef.path), objectKey]);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
async clear() {
|
|
470
|
+
console.warn(`[JSONDatabase] Clearing all data from ${this.filename}.`);
|
|
471
|
+
await this._atomicWrite(() => ({}));
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
getStats() {
|
|
475
|
+
return { ...this.stats };
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
async close() {
|
|
479
|
+
await this.writeLock;
|
|
480
|
+
|
|
481
|
+
this.cache = null;
|
|
482
|
+
this._indices.clear();
|
|
483
|
+
this.removeAllListeners();
|
|
484
|
+
this._initPromise = null;
|
|
485
|
+
|
|
486
|
+
const finalStats = JSON.stringify(this.getStats());
|
|
487
|
+
console.log(`[JSONDatabase] Closed connection to ${this.filename}. Final Stats: ${finalStats}`);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
485
491
|
module.exports = JSONDatabase;
|
package/LICENSE
CHANGED
|
@@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
|
18
18
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
19
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
20
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
21
|
+
SOFTWARE.
|
package/package.json
CHANGED