UNPKG

83db

Version:

Entirely encrypted and GZip compressed JSON Database

83 lines (80 loc) 2.25 kB
const zlib = require("zlib"); const fs = require("fs"); const path = require("path"); const crypto = require('crypto'); class Database { constructor(file, options = { dir: "", decryptionKey: "" }) { file = path.join(options.dir, file); this.file = file; this.key = options.decryptionKey; if (fs.existsSync(file)) { const data = zlib.gunzipSync(fs.readFileSync(file)); this.data = options.decryptionKey ? JSON.parse(decrypt(data.toString(), options.decryptionKey)) : JSON.parse(data); } else { this.data = {}; const data = zlib.gzipSync(options.decryptionKey ? encrypt(JSON.stringify({}), options.decryptionKey) : JSON.stringify({})); fs.writeFileSync(file, data); } } get(key) { return this.data[key]; } set(key, value) { this.data[key] = value; return this; } delete(key) { delete this.data[key]; return this; } list(prefix) { var keys = Object.keys(this.data); if (prefix) { return keys.filter(x => x.startsWith(prefix)); } return keys; } empty() { this.data = {}; return this; } exists(key) { return !!this.data[key]; } write(encryptionKey = this.key) { const buffer = JSON.stringify(this.data); const data = encryptionKey ? encrypt(buffer, encryptionKey) : buffer; const compressed = zlib.gzipSync(Buffer.from(data)); fs.writeFileSync(this.file, compressed); return this; } getAll() { return this.data; } setAll(obj) { this.data = obj; return this; } } function encrypt(buffer, key) { let iv = crypto.randomBytes(16); let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv); let encrypted = cipher.update(buffer); encrypted = Buffer.concat([ encrypted, cipher.final() ]); return iv.toString('hex') + ':' + encrypted.toString('hex'); } function decrypt(encrypted, key) { let encryptedParts = encrypted.split(':'); let iv = Buffer.from(encryptedParts.shift(), 'hex'); let encryptedText = Buffer.from(encryptedParts + [], 'hex'); let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv); let decrypted = decipher.update(encryptedText); return Buffer.concat([decrypted, decipher.final()]); } module.exports = Database;