UNPKG

@nasriya/cachify

Version:

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

67 lines (66 loc) 1.97 kB
import crypto from 'crypto'; import helpers from "../helpers.js"; import { Transform } from "stream"; class DecryptStream extends Transform { #_key; #_ivExtractHandler = helpers.createExtractIVHandler(); #_chunkProcessor = helpers.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.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.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; } } } export default DecryptStream;