UNPKG

@nasriya/cachify

Version:

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

72 lines (71 loc) 2.29 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 DecryptStream extends stream_1.Transform { #_key; #_ivExtractHandler = helpers_1.default.createExtractIVHandler(); #_chunkProcessor = helpers_1.default.createChunkProcessor(); #_iv = null; #_decipher = null; #_handler = null; constructor(key) { super(); if (key.length !== 32) { throw new Error('Key must be 32 bytes (256 bits) long'); } this.#_key = key; } #decrept(data) { return this.#_decipher.update(data); } #setHandler(callback) { this.#_handler = helpers_1.default.createCallbackHandler(callback, this.#decrept.bind(this)); } #processChunk(chunk) { return this.#_chunkProcessor(chunk, this.#_handler); } _transform(chunk, encoding, callback) { this.#setHandler(callback); try { if (Buffer.isBuffer(this.#_iv)) { return this.#processChunk(chunk); } const res = this.#_ivExtractHandler(chunk); if (!res.found) { return callback(); } this.#_iv = res.iv; this.#_decipher = crypto_1.default.createDecipheriv('aes-256-cbc', this.#_key, this.#_iv); return this.#processChunk(res.rest); } catch (error) { callback(error); } } _flush(callback) { this.#setHandler(callback); try { if (!this.#_decipher) { // No data processed at all return callback(); } this.#_chunkProcessor.flush(this.#_handler); const final = this.#_decipher.final(); this.push(final); } catch (err) { callback(err); } finally { this.#_handler = null; this.#_iv = null; this.#_decipher = null; } } } exports.default = DecryptStream;