UNPKG

@nasriya/cachify

Version:

A lightweight, extensible in-memory caching library for storing anything, with built-in TTL and customizable cache types.

61 lines (60 loc) 1.94 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const crypto_1 = __importDefault(require("crypto")); const helpers_1 = __importDefault(require("../helpers")); const stream_1 = require("stream"); class EncryptStream extends stream_1.Transform { #_key; #_chunkProcessor = helpers_1.default.createChunkProcessor(); #_iv = null; #_cipher; #_handler = null; #ivSent = false; constructor(key) { super(); if (key.length !== 32) { throw new Error('Key must be 32 bytes (256 bits) long'); } this.#_key = key; this.#_iv = crypto_1.default.randomBytes(16); // 128-bit IV for AES-256-CBC this.#_cipher = crypto_1.default.createCipheriv('aes-256-cbc', this.#_key, this.#_iv); } #encrypt(data) { return this.#_cipher.update(data); } #setHandler(callback) { this.#_handler = helpers_1.default.createCallbackHandler(callback, this.#encrypt.bind(this)); } #processChunk(chunk) { return this.#_chunkProcessor(chunk, this.#_handler); } _transform(chunk, encoding, callback) { this.#setHandler(callback); try { if (!this.#ivSent) { // Push the IV first so decryptor can read it this.push(this.#_iv); this.#ivSent = true; } this.#processChunk(chunk); } catch (err) { callback(err); } } _flush(callback) { this.#setHandler(callback); try { this.#_chunkProcessor.flush(this.#_handler); const final = this.#_cipher.final(); this.push(final); } catch (err) { callback(err); } } } exports.default = EncryptStream;