    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};


    AesCbcCryptor.prototype.decryptStream = function (encryptedStream) {
        return __awaiter(this, void 0, void 0, function () {
            var decryptedStream, bIv, aes, onReadable;
            var _this = this;
            return __generator(this, function (_a) {
                decryptedStream = new stream_1.PassThrough();
                bIv = Buffer.alloc(0);
                aes = null;
                onReadable = function () {
                    var data = encryptedStream.stream.read();
                    while (data !== null) {
                        if (data) {
                            var bChunk = Buffer.from(data);
                            var sliceLen = encryptedStream.metadataLength - bIv.byteLength;
                            if (bChunk.byteLength < sliceLen) {
                                bIv = Buffer.concat([bIv, bChunk]);
                            }
                            else {
                                bIv = Buffer.concat([bIv, bChunk.slice(0, sliceLen)]);
                                aes = (0, crypto_1.createDecipheriv)(_this.algo, _this.getKey(), bIv);
                                aes.pipe(decryptedStream);
                                aes.write(bChunk.slice(sliceLen));
                            }
                        }
                        data = encryptedStream.stream.read();
                    }
                };
                encryptedStream.stream.on('readable', onReadable);
                encryptedStream.stream.on('end', function () {
                    if (aes) {
                        aes.end();
                    }
                    decryptedStream.end();
                });
                return [2 /*return*/, decryptedStream];
            });
        });
    };

The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others.


function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }


    function AesCbcCryptor(configuration) {
        this.cipherKey = configuration.cipherKey;
    }


            data: Buffer.concat([aes.update(bPlain), aes.final()]),
        };


function verb(n) { return function (v) { return step([n, v]); }; }


var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;


function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }


return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;


function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }


        get: function () {
            return '';
        },


var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


    LegacyCryptor.prototype.encrypt = function (data) {
        if (data.length === 0)
            throw new Error('encryption error. empty content');
        return {
            data: this.cryptor.encrypt(data),
            metadata: null,
        };
    };
    LegacyCryptor.prototype.decrypt = function (encryptedData) {
        var data = typeof encryptedData.data === 'string' ? encryptedData.data : (0, base64_codec_1.encode)(encryptedData.data);
        return this.cryptor.decrypt(data);
    };
    LegacyCryptor.prototype.encryptFile = function (file, File) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.fileCryptor.encryptFile(this.config.cipherKey, file, File)];
            });
        });
    };
    LegacyCryptor.prototype.decryptFile = function (file, File) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.fileCryptor.decryptFile(this.config.cipherKey, file, File)];
            });
        });
    };
    return LegacyCryptor;
}());


            data: this.cryptor.encrypt(data),
            metadata: null,
        };
    };


    LegacyCryptor.prototype.decrypt = function (encryptedData) {
        var data = typeof encryptedData.data === 'string' ? encryptedData.data : (0, base64_codec_1.encode)(encryptedData.data);
        return this.cryptor.decrypt(data);
    };


var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};


function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }


    LegacyCryptor.prototype.encryptFile = function (file, File) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.fileCryptor.encryptFile(this.config.cipherKey, file, File)];
            });
        });
    };


    LegacyCryptor.prototype.decryptFile = function (file, File) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.fileCryptor.decryptFile(this.config.cipherKey, file, File)];
            });
        });
    };


    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }


    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};


function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }


    function LegacyCryptor(config) {
        this.config = config;
        this.cryptor = new index_1.default({ config: config });
        this.fileCryptor = new node_1.default();
    }


function verb(n) { return function (v) { return step([n, v]); }; }


    CryptoModule.prototype.onStreamReadable = function (stream, file, File) {
        return __awaiter(this, void 0, void 0, function () {
            var magicBytes, versionByte, identifier, cryptor, headerSize, _a, _b;
            var _c;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        stream.removeAllListeners('readable');
                        magicBytes = stream.read(4);
                        if (!CryptorHeader.isSentinel(magicBytes)) {
                            if (magicBytes === null)
                                throw new Error('decryption error. empty content');
                            stream.unshift(magicBytes);
                            return [2 /*return*/, this.decryptLegacyFileStream(stream, file, File)];
                        }
                        versionByte = stream.read(1);
                        CryptorHeader.validateVersion(versionByte[0]);
                        identifier = stream.read(4);
                        cryptor = this.getCryptorFromId(CryptorHeader.tryGetIdentifier(identifier));
                        headerSize = CryptorHeader.tryGetMetadataSizeFromStream(stream);
                        if (file.contentLength <= CryptorHeader.MIN_HEADER_LEGTH + headerSize)
                            throw new Error('decryption error. empty content');
                        _b = (_a = File).create;
                        _c = {
                            name: file.name,
                            mimeType: 'application/octet-stream'
                        };
                        return [4 /*yield*/, cryptor.decryptStream({ stream: stream, metadataLength: headerSize })];
                    case 1: return [2 /*return*/, _b.apply(_a, [(_c.stream = _d.sent(),
                                _c)])];
                }
            });
        });
    };


    CryptoModule.prototype.encrypt = function (data) {
        var encrypted = this.defaultCryptor.encrypt(data);
        if (!encrypted.metadata)
            return encrypted.data;
        var header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata);
        var headerData = new Uint8Array(header.length);
        var pos = 0;
        headerData.set(header.data, pos);
        pos = header.length - encrypted.metadata.length;
        headerData.set(encrypted.metadata, pos);
        return Buffer.concat([headerData, Buffer.from(encrypted.data)]);
    };


    CryptorHeader.tryGetIdentifier = function (data) {
        if (data.byteLength < 4) {
            throw new Error('unknown cryptor error. decryption failed');
        }
        else {
            return data.toString('utf8');
        }
    };


    CryptorHeader.tryParse = function (encryptedData) {
        var sentinel = '';
        var version = null;
        if (encryptedData.length >= 4) {
            sentinel = encryptedData.slice(0, 4);
            if (sentinel.toString('utf8') !== CryptorHeader.SENTINEL)
                return '';
        }
        if (encryptedData.length >= 5) {
            version = encryptedData[4];
        }
        else {
            throw new Error('decryption error. invalid header version');
        }
        if (version > CryptorHeader.MAX_VERSION)
            throw new Error('unknown cryptor error');
        var identifier;
        var pos = 5 + CryptorHeader.IDENTIFIER_LENGTH;
        if (encryptedData.length >= pos) {
            identifier = encryptedData.slice(5, pos);
        }
        else {
            throw new Error('decryption error. invalid crypto identifier');
        }
        var metadataLength = null;
        if (encryptedData.length >= pos + 1) {
            metadataLength = encryptedData[pos];
        }
        else {
            throw new Error('decryption error. invalid metadata length');
        }
        pos += 1;
        if (metadataLength === 255 && encryptedData.length >= pos + 2) {
            metadataLength = new Uint16Array(encryptedData.slice(pos, pos + 2)).reduce(function (acc, val) { return (acc << 8) + val; }, 0);
            pos += 2;
        }
        return new CryptorHeaderV1(identifier.toString('utf8'), metadataLength);
    };


var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;


    CryptorHeader.from = function (id, metadata) {
        if (id === CryptorHeader.LEGACY_IDENTIFIER)
            return;
        return new CryptorHeaderV1(id, metadata.length);
    };


    CryptorHeader.validateVersion = function (data) {
        if (data && data > CryptorHeader.MAX_VERSION)
            throw new Error('decryption error. invalid header version');
        return data;
    };


    CryptoModule.prototype.decryptLegacyFileStream = function (stream, file, File) {
        return __awaiter(this, void 0, void 0, function () {
            var cryptor;
            return __generator(this, function (_a) {
                if (file.contentLength <= 16)
                    throw new Error('decryption error: empty content');
                cryptor = this.getLegacyCryptor();
                if (cryptor) {
                    return [2 /*return*/, cryptor.decryptFile(File.create({
                            name: file.name,
                            stream: stream,
                        }), File)];
                }
                else {
                    throw new Error('unknown cryptor error');
                }
                return [2 /*return*/];
            });
        });
    };


function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }


return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;


function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }


var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};


var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};


    CryptoModule.prototype.getCryptorFromId = function (id) {
        var cryptor = this.getAllCryptors().find(function (c) { return id === c.identifier; });
        if (cryptor) {
            return cryptor;
        }
        throw new Error('unknown cryptor error');
    };


        get: function () {
            return this._identifier;
        },


    CryptoModule.prototype.getCryptor = function (header) {
        if (header === '') {
            var cryptor = this.getAllCryptors().find(function (c) { return c.identifier === ''; });
            if (cryptor)
                return cryptor;
            throw new Error('unknown cryptor error');
        }
        else if (header instanceof CryptorHeaderV1) {
            return this.getCryptorFromId(header.identifier);
        }
    };


    CryptorHeader.tryGetMetadataSizeFromStream = function (stream) {
        var sizeBuf = stream.read(1);
        if (sizeBuf && sizeBuf[0] < 255) {
            return sizeBuf[0];
        }
        if (sizeBuf[0] === 255) {
            var nextBuf = stream.read(2);
            if (nextBuf.length >= 2) {
                return new Uint16Array([nextBuf[0], nextBuf[1]]).reduce(function (acc, val) { return (acc << 8) + val; }, 0);
            }
        }
        throw new Error('decryption error. Invalid metadata size');
    };


var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};


function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }


            default: new legacyCryptor_1.default({
                cipherKey: config.cipherKey,
                useRandomIVs: (_a = config.useRandomIVs) !== null && _a !== void 0 ? _a : true,
            }),
            cryptors: [new aesCbcCryptor_1.default({ cipherKey: config.cipherKey })],
        });


    CryptoModule.legacyCryptoModule = function (config) {
        var _a;
        return new this({
            default: new legacyCryptor_1.default({
                cipherKey: config.cipherKey,
                useRandomIVs: (_a = config.useRandomIVs) !== null && _a !== void 0 ? _a : true,
            }),
            cryptors: [new aesCbcCryptor_1.default({ cipherKey: config.cipherKey })],
        });


    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }


    CryptorHeader.isSentinel = function (bytes) {
        if (bytes && bytes.byteLength >= 4) {
            if (bytes.toString('utf8') == CryptorHeader.SENTINEL)
                return true;
        }
    };


                            data: Buffer.from(this.decrypt(file === null || file === void 0 ? void 0 : file.data)),
                        })];
                }


    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};


    CryptoModule.withDefaultCryptor = function (defaultCryptor) {
        return new this({ default: defaultCryptor });
    };


    CryptoModule.prototype.getAllCryptors = function () {
        return __spreadArray([this.defaultCryptor], __read(this.cryptors), false);
    };


    function CryptoModule(cryptoModuleConfiguration) {
        var _a;
        this.defaultCryptor = cryptoModuleConfiguration.default;
        this.cryptors = (_a = cryptoModuleConfiguration.cryptors) !== null && _a !== void 0 ? _a : [];
    }


function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }


        set: function (value) {
            this._identifier = value;
        },


            data: encryptedData.slice(header.length),
            metadata: metadata,
        });
    };


                                    data: Buffer.from(this.encrypt(file.data)),
                                })];
                        }
                        if (!(file.data instanceof stream_1.Readable)) return [3 /*break*/, 2];
                        if (file.contentLength === 0)
                            throw new Error('encryption error. empty content');
                        return [4 /*yield*/, this.defaultCryptor.encryptStream(file.data)];
                    case 1:
                        encryptedStream = _a.sent();
                        header = CryptorHeader.from(this.defaultCryptor.identifier, encryptedStream.metadata);
                        payload = new Uint8Array(header.length);
                        pos = 0;
                        payload.set(header.data, pos);
                        pos += header.length;
                        if (encryptedStream.metadata) {
                            pos -= encryptedStream.metadata.length;
                            payload.set(encryptedStream.metadata, pos);
                        }
                        output = new stream_1.PassThrough();
                        output.write(payload);
                        encryptedStream.stream.pipe(output);
                        return [2 /*return*/, File.create({
                                name: file.name,
                                mimeType: 'application/octet-stream',
                                stream: output,
                            })];
                    case 2: return [2 /*return*/];
                }


    function CryptorHeaderV1(id, metadataLength) {
        this._identifier = id;
        this._metadataLength = metadataLength;
    }


    CryptoModule.prototype.getLegacyCryptor = function () {
        return this.getAllCryptors().find(function (c) { return c.identifier === ''; });
    };


function verb(n) { return function (v) { return step([n, v]); }; }


var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;


function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }


return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;


function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }


        get: function () {
            return 'AES-CBC';
        },


var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


            data: (0, base64_codec_1.decode)(this.CryptoJS.AES.encrypt(data, this.encryptedKey, {
                iv: this.bufferToWordArray(abIv),
                mode: this.CryptoJS.mode.CBC,
            }).ciphertext.toString(this.CryptoJS.enc.Base64)),


var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};


function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }


    AesCbcCryptor.prototype.decrypt = function (encryptedData) {
        var iv = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.metadata));
        var data = this.bufferToWordArray(new Uint8ClampedArray(encryptedData.data));
        return AesCbcCryptor.encoder.encode(this.CryptoJS.AES.decrypt({ ciphertext: data }, this.encryptedKey, {
            iv: iv,
            mode: this.CryptoJS.mode.CBC,
        }).toString(this.CryptoJS.enc.Utf8)).buffer;
    };


    AesCbcCryptor.prototype.getIv = function () {
        return crypto.getRandomValues(new Uint8Array(AesCbcCryptor.BLOCK_SIZE));
    };


    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }


    AesCbcCryptor.prototype.getKey = function () {
        return __awaiter(this, void 0, void 0, function () {
            var bKey, abHash;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        bKey = AesCbcCryptor.encoder.encode(this.cipherKey);
                        return [4 /*yield*/, crypto.subtle.digest('SHA-256', bKey.buffer)];
                    case 1:
                        abHash = _a.sent();
                        return [2 /*return*/, crypto.subtle.importKey('raw', abHash, this.algo, true, ['encrypt', 'decrypt'])];
                }
            });
        });
    };


    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};


function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }


    AesCbcCryptor.prototype.bufferToWordArray = function (b) {
        var wa = [];
        var i;
        for (i = 0; i < b.length; i += 1) {
            wa[(i / 4) | 0] |= b[i] << (24 - 8 * i);
        }
        return this.CryptoJS.lib.WordArray.create(wa, b.length);
    };


    AesCbcCryptor.prototype.encryptFileData = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            var key, iv;
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this.getKey()];
                    case 1:
                        key = _b.sent();
                        iv = this.getIv();
                        _a = {};
                        return [4 /*yield*/, crypto.subtle.encrypt({ name: this.algo, iv: iv }, key, data)];
                    case 2: return [2 /*return*/, (_a.data = _b.sent(),
                            _a.metadata = iv,
                            _a)];
                }
            });
        });
    };


    AesCbcCryptor.prototype.decryptFileData = function (encryptedData) {
        return __awaiter(this, void 0, void 0, function () {
            var key;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.getKey()];
                    case 1:
                        key = _a.sent();
                        return [2 /*return*/, crypto.subtle.decrypt({ name: this.algo, iv: encryptedData.metadata }, key, encryptedData.data)];
                }
            });
        });
    };


    function AesCbcCryptor(configuration) {
        this.cipherKey = configuration.cipherKey;
        this.CryptoJS = hmac_sha256_1.default;
        this.encryptedKey = this.CryptoJS.SHA256(this.cipherKey);
    }


function verb(n) { return function (v) { return step([n, v]); }; }


var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;


function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }


return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;


function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }


        get: function () {
            return '';
        },


var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


    LegacyCryptor.prototype.encrypt = function (data) {
        var stringData = typeof data === 'string' ? data : new TextDecoder().decode(data);
        return {
            data: this.cryptor.encrypt(stringData),
            metadata: null,
        };
    };
    LegacyCryptor.prototype.decrypt = function (encryptedData) {
        var data = typeof encryptedData.data === 'string' ? encryptedData.data : (0, base64_codec_1.encode)(encryptedData.data);
        return this.cryptor.decrypt(data);
    };
    LegacyCryptor.prototype.encryptFile = function (file, File) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_b) {
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                //@ts-ignore: can not detect cipherKey from old Config
                return [2 /*return*/, this.fileCryptor.encryptFile((_a = this.config) === null || _a === void 0 ? void 0 : _a.cipherKey, file, File)];
            });
        });
    };
    LegacyCryptor.prototype.decryptFile = function (file, File) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                //@ts-ignore: can not detect cipherKey from old Config
                return [2 /*return*/, this.fileCryptor.decryptFile(this.config.cipherKey, file, File)];
            });
        });
    };
    return LegacyCryptor;
}());


    LegacyCryptor.prototype.decrypt = function (encryptedData) {
        var data = typeof encryptedData.data === 'string' ? encryptedData.data : (0, base64_codec_1.encode)(encryptedData.data);
        return this.cryptor.decrypt(data);
    };


var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};


function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }


            data: this.cryptor.encrypt(stringData),
            metadata: null,
        };
    };


    LegacyCryptor.prototype.encryptFile = function (file, File) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_b) {
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                //@ts-ignore: can not detect cipherKey from old Config
                return [2 /*return*/, this.fileCryptor.encryptFile((_a = this.config) === null || _a === void 0 ? void 0 : _a.cipherKey, file, File)];
            });
        });
    };


    LegacyCryptor.prototype.decryptFile = function (file, File) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                //@ts-ignore: can not detect cipherKey from old Config
                return [2 /*return*/, this.fileCryptor.decryptFile(this.config.cipherKey, file, File)];
            });
        });
    };


    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }


    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};


function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }


    function LegacyCryptor(config) {
        this.config = config;
        this.cryptor = new index_1.default({ config: config });
        this.fileCryptor = new web_1.default();
    }


function verb(n) { return function (v) { return step([n, v]); }; }


    CryptoModule.prototype.encrypt = function (data) {
        var encrypted = this.defaultCryptor.encrypt(data);
        if (!encrypted.metadata)
            return encrypted.data;
        var headerData = this.getHeaderData(encrypted);
        return this.concatArrayBuffer(headerData, encrypted.data);
    };


                                data: data.slice(header.length),
                                metadata: metadata,
                            })];
                    case 2: return [2 /*return*/, _b.apply(_a, [(_c.data = _d.sent(),
                                _c)])];
                }
            });


var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;


    CryptorHeader.from = function (id, metadata) {
        if (id === CryptorHeader.LEGACY_IDENTIFIER)
            return;
        return new CryptorHeaderV1(id, metadata.byteLength);
    };


function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }


return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;


function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }


var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};


var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};


var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};


    CryptoModule.prototype.getCryptorFromId = function (id) {
        var cryptor = this.getAllCryptors().find(function (c) { return id === c.identifier; });
        if (cryptor) {
            return cryptor;
        }
        throw Error('unknown cryptor error');
    };


        get: function () {
            return this._identifier;
        },


    CryptoModule.prototype.getCryptor = function (header) {
        if (header === '') {
            var cryptor = this.getAllCryptors().find(function (c) { return c.identifier === ''; });
            if (cryptor)
                return cryptor;
            throw new Error('unknown cryptor error');
        }
        else if (header instanceof CryptorHeaderV1) {
            return this.getCryptorFromId(header.identifier);
        }
    };


    CryptoModule.prototype.getFileData = function (input) {
        if (input instanceof ArrayBuffer) {
            return input;
        }
        if (typeof input === 'string') {
            return CryptoModule.encoder.encode(input);
        }
        throw new Error('Cannot decrypt/encrypt file. In browsers file decryption supports only string or ArrayBuffer');
    };


var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};


function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }


    CryptoModule.prototype.getHeaderData = function (encrypted) {
        if (!encrypted.metadata)
            return;
        var header = CryptorHeader.from(this.defaultCryptor.identifier, encrypted.metadata);
        var headerData = new Uint8Array(header.length);
        var pos = 0;
        headerData.set(header.data, pos);
        pos += header.length - encrypted.metadata.byteLength;
        headerData.set(new Uint8Array(encrypted.metadata), pos);
        return headerData.buffer;
    };


            default: new legacyCryptor_1.default({
                cipherKey: config.cipherKey,
                useRandomIVs: (_a = config.useRandomIVs) !== null && _a !== void 0 ? _a : true,
            }),
            cryptors: [new aesCbcCryptor_1.default({ cipherKey: config.cipherKey })],
        });


    CryptorHeader.tryParse = function (data) {
        var encryptedData = new Uint8Array(data);
        var sentinel = '';
        var version = null;
        if (encryptedData.byteLength >= 4) {
            sentinel = encryptedData.slice(0, 4);
            if (this.decoder.decode(sentinel) !== CryptorHeader.SENTINEL)
                return '';
        }
        if (encryptedData.byteLength >= 5) {
            version = encryptedData[4];
        }
        else {
            throw new Error('decryption error. invalid header version');
        }
        if (version > CryptorHeader.MAX_VERSION)
            throw new Error('unknown cryptor error');
        var identifier = '';
        var pos = 5 + CryptorHeader.IDENTIFIER_LENGTH;
        if (encryptedData.byteLength >= pos) {
            identifier = encryptedData.slice(5, pos);
        }
        else {
            throw new Error('decryption error. invalid crypto identifier');
        }
        var metadataLength = null;
        if (encryptedData.byteLength >= pos + 1) {
            metadataLength = encryptedData[pos];
        }
        else {
            throw new Error('decryption error. invalid metadata length');
        }
        pos += 1;
        if (metadataLength === 255 && encryptedData.byteLength >= pos + 2) {
            metadataLength = new Uint16Array(encryptedData.slice(pos, pos + 2)).reduce(function (acc, val) { return (acc << 8) + val; }, 0);
            pos += 2;
        }
        return new CryptorHeaderV1(this.decoder.decode(identifier), metadataLength);
    };


    CryptoModule.legacyCryptoModule = function (config) {
        var _a;
        return new this({
            default: new legacyCryptor_1.default({
                cipherKey: config.cipherKey,
                useRandomIVs: (_a = config.useRandomIVs) !== null && _a !== void 0 ? _a : true,
            }),
            cryptors: [new aesCbcCryptor_1.default({ cipherKey: config.cipherKey })],
        });


                                data: this.concatArrayBuffer(this.getHeaderData(encrypted), encrypted.data),
                            })];
                }


    CryptoModule.prototype.concatArrayBuffer = function (ab1, ab2) {
        var tmp = new Uint8Array(ab1.byteLength + ab2.byteLength);
        tmp.set(new Uint8Array(ab1), 0);
        tmp.set(new Uint8Array(ab2), ab1.byteLength);
        return tmp.buffer;
    };


    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }


        set: function (value) {
            this._identifier = value;
        },


    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};


    CryptoModule.withDefaultCryptor = function (defaultCryptor) {
        return new this({ default: defaultCryptor });
    };


    CryptoModule.prototype.getAllCryptors = function () {
        return __spreadArray([this.defaultCryptor], __read(this.cryptors), false);
    };


    function CryptoModule(cryptoModuleConfiguration) {
        var _a;
        this.defaultCryptor = cryptoModuleConfiguration.default;
        this.cryptors = (_a = cryptoModuleConfiguration.cryptors) !== null && _a !== void 0 ? _a : [];
    }


function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }


            data: encryptedData.slice(header.length),
            metadata: metadata,
        });
    };


    function CryptorHeaderV1(id, metadataLength) {
        this._identifier = id;
        this._metadataLength = metadataLength;
    }


function verb(n) { return function (v) { return step([n, v]); }; }


                        transform: function (chunk, _, cb) {
                            if (!inited) {
                                inited = true;
                                this.push(Buffer.concat([bIv, chunk]));
                            }
                            else {
                                this.push(chunk);
                            }
                            cb();
                        },


    NodeCryptography.prototype.encryptStream = function (key, stream) {
        return __awaiter(this, void 0, void 0, function () {
            var bIv, aes, inited;
            return __generator(this, function (_a) {
                bIv = this.getIv();
                aes = (0, crypto_1.createCipheriv)('aes-256-cbc', key, bIv).setAutoPadding(true);
                inited = false;
                return [2 /*return*/, stream.pipe(aes).pipe(new stream_1.Transform({
                        transform: function (chunk, _, cb) {
                            if (!inited) {
                                inited = true;
                                this.push(Buffer.concat([bIv, chunk]));
                            }
                            else {
                                this.push(chunk);
                            }
                            cb();
                        },
                    }))];
            });
        });
    };


    NodeCryptography.prototype.encryptFile = function (key, file, File) {
        return __awaiter(this, void 0, void 0, function () {
            var bKey, _a, _b, _c, _d;
            var _e, _f;
            return __generator(this, function (_g) {
                switch (_g.label) {
                    case 0:
                        bKey = this.getKey(key);
                        if (!(file.data instanceof Buffer)) return [3 /*break*/, 2];
                        if (file.data.byteLength <= 0)
                            throw new Error('encryption error. empty content');
                        _b = (_a = File).create;
                        _e = {
                            name: file.name,
                            mimeType: 'application/octet-stream'
                        };
                        return [4 /*yield*/, this.encryptBuffer(bKey, file.data)];
                    case 1: return [2 /*return*/, _b.apply(_a, [(_e.data = _g.sent(),
                                _e)])];
                    case 2:
                        if (!(file.data instanceof stream_1.Readable)) return [3 /*break*/, 4];
                        if (file.contentLength === 0)
                            throw new Error('encryption error. empty content');
                        _d = (_c = File).create;
                        _f = {
                            name: file.name,
                            mimeType: 'application/octet-stream'
                        };
                        return [4 /*yield*/, this.encryptStream(bKey, file.data)];
                    case 3: return [2 /*return*/, _d.apply(_c, [(_f.stream = _g.sent(),
                                _f)])];
                    case 4: throw new Error('Cannot encrypt this file. In Node.js file encryption supports only string, Buffer or Stream.');
                }
            });
        });
    };


    NodeCryptography.prototype.decryptBuffer = function (key, ciphertext) {
        var bIv = ciphertext.slice(0, NodeCryptography.IV_LENGTH);
        var bCiphertext = ciphertext.slice(NodeCryptography.IV_LENGTH);
        if (bCiphertext.byteLength <= 0)
            throw new Error('decryption error: empty content');
        var aes = (0, crypto_1.createDecipheriv)(this.algo, key, bIv);
        return Buffer.concat([aes.update(bCiphertext), aes.final()]);
    };


    WebCryptography.prototype.decryptArrayBuffer = function (key, ciphertext) {
        return __awaiter(this, void 0, void 0, function () {
            var abIv, data;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        abIv = ciphertext.slice(0, 16);
                        if (ciphertext.slice(WebCryptography.IV_LENGTH).byteLength <= 0)
                            throw new Error('decryption error: empty content');
                        return [4 /*yield*/, crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, ciphertext.slice(WebCryptography.IV_LENGTH))];
                    case 1:
                        data = _a.sent();
                        return [2 /*return*/, data];
                }
            });
        });
    };


    WebCryptography.prototype.encryptString = function (key, plaintext) {
        return __awaiter(this, void 0, void 0, function () {
            var abIv, abPlaintext, abPayload, ciphertext;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        abIv = crypto.getRandomValues(new Uint8Array(16));
                        abPlaintext = WebCryptography.encoder.encode(plaintext).buffer;
                        return [4 /*yield*/, crypto.subtle.encrypt({ name: 'AES-CBC', iv: abIv }, key, abPlaintext)];
                    case 1:
                        abPayload = _a.sent();
                        ciphertext = concatArrayBuffer(abIv.buffer, abPayload);
                        return [2 /*return*/, WebCryptography.decoder.decode(ciphertext)];
                }
            });
        });
    };


    WebCryptography.prototype.decryptFile = function (key, file, File) {
        return __awaiter(this, void 0, void 0, function () {
            var bKey, abCipherdata, abPlaindata;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.getKey(key)];
                    case 1:
                        bKey = _a.sent();
                        return [4 /*yield*/, file.data.arrayBuffer()];
                    case 2:
                        abCipherdata = _a.sent();
                        return [4 /*yield*/, this.decryptArrayBuffer(bKey, abCipherdata)];
                    case 3:
                        abPlaindata = _a.sent();
                        return [2 /*return*/, File.create({
                                name: file.name,
                                data: abPlaindata,
                            })];
                }
            });
        });
    };


    WebCryptography.prototype.decryptString = function (key, ciphertext) {
        return __awaiter(this, void 0, void 0, function () {
            var abCiphertext, abIv, abPayload, abPlaintext;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        abCiphertext = WebCryptography.encoder.encode(ciphertext).buffer;
                        abIv = abCiphertext.slice(0, 16);
                        abPayload = abCiphertext.slice(16);
                        return [4 /*yield*/, crypto.subtle.decrypt({ name: 'AES-CBC', iv: abIv }, key, abPayload)];
                    case 1:
                        abPlaintext = _a.sent();
                        return [2 /*return*/, WebCryptography.decoder.decode(abPlaintext)];
                }
            });
        });
    };


    WebCryptography.prototype.encryptFile = function (key, file, File) {
        return __awaiter(this, void 0, void 0, function () {
            var bKey, abPlaindata, abCipherdata;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (file.data.byteLength <= 0)
                            throw new Error('encryption error. empty content');
                        return [4 /*yield*/, this.getKey(key)];
                    case 1:
                        bKey = _a.sent();
                        return [4 /*yield*/, file.data.arrayBuffer()];
                    case 2:
                        abPlaindata = _a.sent();
                        return [4 /*yield*/, this.encryptArrayBuffer(bKey, abPlaindata)];
                    case 3:
                        abCipherdata = _a.sent();
                        return [2 /*return*/, File.create({
                                name: file.name,
                                mimeType: 'application/octet-stream',
                                data: abCipherdata,
                            })];
                }
            });
        });
    };


    WebCryptography.prototype.getKey = function (key) {
        return __awaiter(this, void 0, void 0, function () {
            var digest, hashHex, abKey;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, crypto.subtle.digest('SHA-256', WebCryptography.encoder.encode(key))];
                    case 1:
                        digest = _a.sent();
                        hashHex = Array.from(new Uint8Array(digest))
                            .map(function (b) { return b.toString(16).padStart(2, '0'); })
                            .join('');
                        abKey = WebCryptography.encoder.encode(hashHex.slice(0, 32)).buffer;
                        return [2 /*return*/, crypto.subtle.importKey('raw', abKey, 'AES-CBC', true, ['encrypt', 'decrypt'])];
                }
            });
        });
    };


var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};


        function PubNubFile(_a) {
            var stream = _a.stream, data = _a.data, encoding = _a.encoding, name = _a.name, mimeType = _a.mimeType;
            if (stream instanceof stream_1.Readable) {
                this.data = stream;
                if (stream instanceof fs_1.default.ReadStream) {
                    // $FlowFixMe: incomplete flow node definitions
                    this.name = (0, path_1.basename)(stream.path);
                    this.contentLength = fs_1.default.statSync(stream.path).size;
                }
            }
            else if (data instanceof Buffer) {
                this.data = Buffer.from(data);
            }
            else if (typeof data === 'string') {
                // $FlowFixMe: incomplete flow node definitions
                this.data = Buffer.from(data, encoding !== null && encoding !== void 0 ? encoding : 'utf8');
            }
            if (name) {
                this.name = (0, path_1.basename)(name);
            }
            if (mimeType) {
                this.mimeType = mimeType;
            }
            if (this.data === undefined) {
                throw new Error("Couldn't construct a file out of supplied options.");
            }
            if (this.name === undefined) {
                throw new Error("Couldn't guess filename out of the options. Please provide one.");
            }
        }


                    cryptors: [new nodeCryptoModule_1.AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })],
                });
            };


                    default: new nodeCryptoModule_1.LegacyCryptor({
                        cipherKey: cryptoConfiguration.cipherKey,
                        useRandomIVs: cryptoConfiguration.useRandomIVs,
                    }),
                    cryptors: [new nodeCryptoModule_1.AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })],
                });
            };
            if (!('ssl' in setup)) {
                setup.ssl = true;
            }
            _this = _super.call(this, setup) || this;
            return _this;
        }


            setup.initCryptoModule = function (cryptoConfiguration) {
                return new nodeCryptoModule_1.CryptoModule({
                    default: new nodeCryptoModule_1.LegacyCryptor({
                        cipherKey: cryptoConfiguration.cipherKey,
                        useRandomIVs: cryptoConfiguration.useRandomIVs,
                    }),
                    cryptors: [new nodeCryptoModule_1.AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })],
                });
            };
            if (!('ssl' in setup)) {
                setup.ssl = true;
            }
            _this = _super.call(this, setup) || this;
            return _this;
        }
        return class_1;
    }(pubnub_common_1.default)),


                cryptors: [new webCryptoModule_1.AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })],
            });
        };


                default: new webCryptoModule_1.LegacyCryptor({
                    cipherKey: cryptoConfiguration.cipherKey,
                    useRandomIVs: cryptoConfiguration.useRandomIVs,
                }),
                cryptors: [new webCryptoModule_1.AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })],
            });
        };
        _this = _super.call(this, setup) || this;
        if (listenToBrowserNetworkEvents) {
            // mount network events.
            window.addEventListener('offline', function () {
                _this.networkDownDetected();
            });
            window.addEventListener('online', function () {
                _this.networkUpDetected();
            });
        }
        return _this;
    }


        setup.initCryptoModule = function (cryptoConfiguration) {
            return new webCryptoModule_1.CryptoModule({
                default: new webCryptoModule_1.LegacyCryptor({
                    cipherKey: cryptoConfiguration.cipherKey,
                    useRandomIVs: cryptoConfiguration.useRandomIVs,
                }),
                cryptors: [new webCryptoModule_1.AesCbcCryptor({ cipherKey: cryptoConfiguration.cipherKey })],
            });
        };
        _this = _super.call(this, setup) || this;
        if (listenToBrowserNetworkEvents) {
            // mount network events.
            window.addEventListener('offline', function () {
                _this.networkDownDetected();
            });
            window.addEventListener('online', function () {
                _this.networkUpDetected();
            });
        }
        return _this;
    }
    default_1.CryptoModule = webCryptoModule_1.CryptoModule;
    return default_1;
}(pubnub_common_1.default));


export function encode(input: ArrayBuffer): string {
  let base64 = '';
  const encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

  const bytes = new Uint8Array(input);
  const byteLength = bytes.byteLength;
  const byteRemainder = byteLength % 3;
  const mainLength = byteLength - byteRemainder;

  let a, b, c, d;
  let chunk;

  // Main loop deals with bytes in chunks of 3
  for (let i = 0; i < mainLength; i = i + 3) {
    // Combine the three bytes into a single integer
    chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];

    // Use bitmasks to extract 6-bit segments from the triplet
    a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18
    b = (chunk & 258048) >> 12; // 258048   = (2^6 - 1) << 12
    c = (chunk & 4032) >> 6; // 4032     = (2^6 - 1) << 6
    d = chunk & 63; // 63       = 2^6 - 1

    // Convert the raw binary segments to the appropriate ASCII encoding
    base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
  }

  // Deal with the remaining bytes and padding
  if (byteRemainder == 1) {
    chunk = bytes[mainLength];

    a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2

    // Set the 4 least significant bits to zero
    b = (chunk & 3) << 4; // 3   = 2^2 - 1

    base64 += encodings[a] + encodings[b] + '==';
  } else if (byteRemainder == 2) {
    chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1];

    a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10
    b = (chunk & 1008) >> 4; // 1008  = (2^6 - 1) << 4

    // Set the 2 least significant bits to zero
    c = (chunk & 15) << 2; // 15    = 2^4 - 1

    base64 += encodings[a] + encodings[b] + encodings[c] + '=';
  }

  return base64;
}


  constructor({
    subscribeEndpoint,
    leaveEndpoint,
    heartbeatEndpoint,
    setStateEndpoint,
    timeEndpoint,
    getFileUrl,
    config,
    crypto,
    listenerManager,
    cryptoModule,
  }) {
    this._listenerManager = listenerManager;
    this._config = config;

    this._leaveEndpoint = leaveEndpoint;
    this._heartbeatEndpoint = heartbeatEndpoint;
    this._setStateEndpoint = setStateEndpoint;
    this._subscribeEndpoint = subscribeEndpoint;
    this._getFileUrl = getFileUrl;

    this._crypto = crypto;
    this._cryptoModule = cryptoModule;

    this._channels = {};
    this._presenceChannels = {};

    this._heartbeatChannels = {};
    this._heartbeatChannelGroups = {};

    this._channelGroups = {};
    this._presenceChannelGroups = {};

    this._pendingChannelSubscriptions = [];
    this._pendingChannelGroupSubscriptions = [];

    this._currentTimetoken = 0;
    this._lastTimetoken = 0;
    this._storedTimetoken = null;

    this._subscriptionStatusAnnounced = false;

    this._isOnline = true;

    this._reconnectionManager = new ReconnectionManager({ timeEndpoint });
    this._dedupingManager = new DedupingManager({ config });

    if (this._cryptoModule) this._decoder = new TextDecoder();
  }


          url: this._getFileUrl({
            id: msgPayload.file.id,
            name: msgPayload.file.name,
            channel,
          }),
        };

        this._listenerManager.announceFile(announce);
      } else {
        const announce = {};
        announce.channel = null;
        announce.subscription = null;

        // deprecated -->
        announce.actualChannel = subscriptionMatch != null ? channel : null;
        announce.subscribedChannel = subscriptionMatch != null ? subscriptionMatch : channel;
        // <-- deprecated

        announce.channel = channel;
        announce.subscription = subscriptionMatch;
        announce.timetoken = publishMetaData.publishTimetoken;
        announce.publisher = message.issuingClientId;

        if (message.userMetadata) {
          announce.userMetadata = message.userMetadata;
        }

        if (this._cryptoModule) {
          let decryptedPayload;
          try {
            const decryptedData = this._cryptoModule.decrypt(message.payload);
            decryptedPayload =
              decryptedData instanceof ArrayBuffer ? JSON.parse(this._decoder.decode(decryptedData)) : decryptedData;
          } catch (e) {
            decryptedPayload = null;
            // eslint-disable-next-line
            if (console && console.log) {
              console.log('decryption error', e.message); //eslint-disable-line
            }
          }
          if (decryptedPayload != null) {
            announce.message = decryptedPayload;
          } else {
            announce.message = message.payload;
          }
        } else {
          announce.message = message.payload;
        }

        this._listenerManager.announceMessage(announce);
      }
    });


function stringToArrayBuffer(str) {
  var buf = new ArrayBuffer(str.length * 2);
  var bufView = new Uint16Array(buf);
  for (var i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}


  getFilePath(filename) {
    return getFilePath(filename);
  }


  get defaultInstance() {
    return defaultInstance;
  }

Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')

The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.


function start(args, returnPromise) {
  let command = crpath;
  if (!fs.existsSync(command)) {
    console.log('Could not find chromedriver in default path: ', command);
    console.log('Falling back to use global chromedriver bin');
    command = process.platform === 'win32' ? 'chromedriver.exe' : 'chromedriver';
  }
  const cp = require('child_process').spawn(command, args);
  cp.stdout.pipe(process.stdout);
  cp.stderr.pipe(process.stderr);
  defaultInstance = cp;
  if (!returnPromise)
    return cp;
  const port = getPortFromArgs(args);
  const pollInterval = 100;
  const timeout = 10000;
  return tcpPortUsed.waitUntilUsed(port, pollInterval, timeout)
    .then(function () {
      return cp;
    });
}


function getPortFromArgs(args) {
  let port = 9515;
  if (!args)
    return port;
  const portRegexp = /--port=(\d*)/;
  const portArg = args.find(function (arg) {
    return portRegexp.test(arg);
  });
  if (portArg)
    port = parseInt(portRegexp.exec(portArg)[1]);
  return port;
}


function stop() {
  if (defaultInstance != null)
    defaultInstance.kill();
  defaultInstance = null;
}


async function writeUpdate(newVersion, shouldCommit) {
  const helper = fs.readFileSync('./lib/chromedriver.js', 'utf8');
  const versionExport = 'const version';
  const regex = new RegExp(`^.*${versionExport}.*$`, 'gm');
  const updated = helper.replace(regex, `${versionExport} = '${newVersion}';`);
  const currentMajor = semver.major(currentVersionInPackageJson);
  const newMajor = semver.major(semver.coerce(newVersion));
  const version = currentMajor !== newMajor ? `${newMajor}.0.0` : semver.inc(currentVersionInPackageJson, 'patch');
  execSync(`npm version ${version} --git-tag-version=false`);
  fs.writeFileSync('./lib/chromedriver.js', updated, 'utf8');
  if (!shouldCommit) return;
  execSync('git add :/');
  execSync(`git commit -m "Bump version to ${version}"`);
  execSync(`git tag -s ${version} -m ${version}`);
}


                        'X-Pimcore-Csrf-Token': $newCustomerButton.data('token')
                    },
                    success: function (data) {
                        var objectId = data.id;
                        if ('undefined' !== typeof window.top.pimcore) {
                            window.top.pimcore.helpers.openObject(objectId, 'object');
                        } else {
                            app.Logger.error(
                                'Pimcore is not available (e.g. backend opened outside iframe) - can\'t load object with ID',
                                objectId
                            );
                        }
                    }
                });
            });

The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.


        registerNewCustomerAction: function () {
            var $newCustomerButton = $('#add-new-customer');
            var isPimcoreAvailable = ('undefined' !== typeof window.top.pimcore);
            if(!isPimcoreAvailable) $newCustomerButton.hide();
            $newCustomerButton.on('click', function (e) {
                if (!isPimcoreAvailable) {
                    app.Logger.error(
                        'Pimcore is not available (e.g. backend opened outside iframe) - can\'t load object with ID',
                        objectId
                    );
                    return false;
                }
                $.ajax({
                    method : 'POST',
                    url: '/admin/customermanagementframework/customers/new',
                    headers: {
                        'X-Pimcore-Csrf-Token': $newCustomerButton.data('token')
                    },
                    success: function (data) {
                        var objectId = data.id;
                        if ('undefined' !== typeof window.top.pimcore) {
                            window.top.pimcore.helpers.openObject(objectId, 'object');
                        } else {
                            app.Logger.error(
                                'Pimcore is not available (e.g. backend opened outside iframe) - can\'t load object with ID',
                                objectId
                            );
                        }
                    }
                });
            });
        }
    });
})(jQuery);


const url = (location, omitQuery = false) => {
  const query = Query.parse(location.search)

  const next = query.n || appRoot

  if (omitQuery) {
    return next.split('?')[0]
  }

  // Only allow relative redirects to prevent open redirects.
  if (!next.startsWith('/') || next.startsWith('//')) {
    return appRoot
  }

  return next
}

URL Redirection to Untrusted Site ('Open Redirect')

A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.


function buildAttributesMap(attrStr, jPath) {
  if (!this.options.ignoreAttributes && typeof attrStr === 'string') {
    // attrStr = attrStr.replace(/\r?\n/g, ' ');
    //attrStr = attrStr || attrStr.trim();

    const matches = util.getAllMatches(attrStr, attrsRegx);
    const len = matches.length; //don't make it inline
    const attrs = {};
    for (let i = 0; i < len; i++) {
      const attrName = this.resolveNameSpace(matches[i][1]);
      let oldVal = matches[i][4];
      let aName = this.options.attributeNamePrefix + attrName;
      if (attrName.length) {
        if (this.options.transformAttributeName) {
          aName = this.options.transformAttributeName(aName);
        }
        if(aName === "__proto__") aName  = "#__proto__";
        if (oldVal !== undefined) {
          if (this.options.trimValues) {
            oldVal = oldVal.trim();
          }
          oldVal = this.replaceEntitiesValue(oldVal);
          const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);
          if(newVal === null || newVal === undefined){
            //don't parse
            attrs[aName] = oldVal;
          }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){
            //overwrite
            attrs[aName] = newVal;
          }else{
            //parse
            attrs[aName] = parseValue(
              oldVal,
              this.options.parseAttributeValue,
              this.options.numberParseOptions
            );
          }
        } else if (this.options.allowBooleanAttributes) {
          attrs[aName] = true;
        }
      }
    }
    if (!Object.keys(attrs).length) {
      return;
    }
    if (this.options.attributesGroupName) {
      const attrCollection = {};
      attrCollection[this.options.attributesGroupName] = attrs;
      return attrCollection;
    }
    return attrs;
  }
}

Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution')

The product receives input from an upstream component that specifies attributes that are to be initialized or updated in an object, but it does not properly control modifications of attributes of the object prototype.


  add(key,val){
    // this.child.push( {name : key, val: val, isCdata: isCdata });
    if(key === "__proto__") key = "#__proto__";
    this.child.push( {[key]: val });
  }


  addChild(node) {
    if(node.tagname === "__proto__") node.tagname = "#__proto__";
    if(node[":@"] && Object.keys(node[":@"]).length > 0){
      this.child.push( { [node.tagname]: node.child, [":@"]: node[":@"] });
    }else{
      this.child.push( { [node.tagname]: node.child });
    }
  };


function isEntity(xmlData, i){
    if(xmlData[i+1] === '!' &&
    xmlData[i+2] === 'E' &&
    xmlData[i+3] === 'N' &&
    xmlData[i+4] === 'T' &&
    xmlData[i+5] === 'I' &&
    xmlData[i+6] === 'T' &&
    xmlData[i+7] === 'Y') return true
    return false
}

Inefficient Regular Expression Complexity

The product uses a regular expression with an inefficient, possibly exponential worst-case computational complexity that consumes excessive CPU cycles.


function isElement(xmlData, i){
    if(xmlData[i+1] === '!' &&
    xmlData[i+2] === 'E' &&
    xmlData[i+3] === 'L' &&
    xmlData[i+4] === 'E' &&
    xmlData[i+5] === 'M' &&
    xmlData[i+6] === 'E' &&
    xmlData[i+7] === 'N' &&
    xmlData[i+8] === 'T') return true
    return false
}


function isNotation(xmlData, i){
    if(xmlData[i+1] === '!' &&
    xmlData[i+2] === 'N' &&
    xmlData[i+3] === 'O' &&
    xmlData[i+4] === 'T' &&
    xmlData[i+5] === 'A' &&
    xmlData[i+6] === 'T' &&
    xmlData[i+7] === 'I' &&
    xmlData[i+8] === 'O' &&
    xmlData[i+9] === 'N') return true
    return false
}


                            regx : RegExp( `&${entityName};`,"g"),
                            val: val
                        };
                }
                else if( hasBody && isElement(xmlData, i))  i += 8;//Not supported
                else if( hasBody && isAttlist(xmlData, i))  i += 8;//Not supported
                else if( hasBody && isNotation(xmlData, i)) i += 9;//Not supported
                else if( isComment)                         comment = true;
                else                                        throw new Error("Invalid DOCTYPE");

                angleBracketsCount++;
                exp = "";
            } else if (xmlData[i] === '>') { //Read tag content
                if(comment){
                    if( xmlData[i - 1] === "-" && xmlData[i - 2] === "-"){
                        comment = false;
                        angleBracketsCount--;
                    }
                }else{
                    angleBracketsCount--;
                }
                if (angleBracketsCount === 0) {
                  break;
                }
            }else if( xmlData[i] === '['){
                hasBody = true;
            }else{
                exp += xmlData[i];
            }
        }
        if(angleBracketsCount !== 0){
            throw new Error(`Unclosed DOCTYPE`);
        }
    }else{
        throw new Error(`Invalid Tag instead of DOCTYPE`);
    }
    return {entities, i};
}


function readEntityExp(xmlData,i){
    //External entities are not supported
    //    <!ENTITY ext SYSTEM "http://normal-website.com" >

    //Parameter entities are not supported
    //    <!ENTITY entityname "&anotherElement;">

    //Internal entities are supported
    //    <!ENTITY entityname "replacement text">

    //read EntityName
    let entityName = "";
    for (; i < xmlData.length && (xmlData[i] !== "'" && xmlData[i] !== '"' ); i++) {
        // if(xmlData[i] === " ") continue;
        // else
        entityName += xmlData[i];
    }
    entityName = entityName.trim();
    if(entityName.indexOf(" ") !== -1) throw new Error("External entites are not supported");

    //read Entity Value
    const startChar = xmlData[i++];
    let val = ""
    for (; i < xmlData.length && xmlData[i] !== startChar ; i++) {
        val += xmlData[i];
    }
    return [entityName, val, i];
}


function isAttlist(xmlData, i){
    if(xmlData[i+1] === '!' &&
    xmlData[i+2] === 'A' &&
    xmlData[i+3] === 'T' &&
    xmlData[i+4] === 'T' &&
    xmlData[i+5] === 'L' &&
    xmlData[i+6] === 'I' &&
    xmlData[i+7] === 'S' &&
    xmlData[i+8] === 'T') return true
    return false
}


function isComment(xmlData, i){
    if(xmlData[i+1] === '!' &&
    xmlData[i+2] === '-' &&
    xmlData[i+3] === '-') return true
    return false
}


function validateEntityName(name){
    for (let i = 0; i < specialChar.length; i++) {
        const ch = specialChar[i];
        if(name.indexOf(ch) !== -1) throw new Error(`Invalid character ${ch} in entity name`);
    }
    return name;
}


Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')

The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.


    save: function (callback) {
      if (this.loading) {
        return;
      }

      this.loading = true;
      this.$spinner.removeClass('hidden');

      var formData = Garnish.getPostData(this.$form),
        data = $.extend({enabled: 1}, formData, this.params);

      Craft.postActionRequest(
        'entries/save-entry',
        data,
        (response, textStatus) => {
          this.loading = false;
          this.$spinner.addClass('hidden');

          if (this.$errorList) {
            this.$errorList.children().remove();
          }

          if (textStatus === 'success') {
            if (response.success) {
              Craft.cp.displayNotice(Craft.t('app', 'Entry saved.'));
              callback(response);
            } else {
              Craft.cp.displayError(Craft.t('app', 'Couldn’t save entry.'));

              if (response.errors) {
                if (!this.$errorList) {
                  this.$errorList = $('<ul class="errors"/>').insertAfter(
                    this.$form
                  );
                }

                for (var attribute in response.errors) {
                  if (!response.errors.hasOwnProperty(attribute)) {
                    continue;
                  }

                  for (var i = 0; i < response.errors[attribute].length; i++) {
                    var error = response.errors[attribute][i];
                    $('<li/>', {
                      text: error,
                    }).appendTo(this.$errorList);
                  }
                }
              }
            }
          }
        }
      );
    },


            label: Craft.escapeHtml(o.label),
            value: o.attr,
          };
        }),


        options: this.elementIndex.getSortOptions(this.$source).map((o) => {
          return {
            label: Craft.escapeHtml(o.label),
            value: o.attr,
          };
        }),
      })


              label: Craft.escapeHtml(o.label),
              value: o.attr,
            };
          }),


          options: this.sourceData.sortOptions.map((o) => {
            return {
              label: Craft.escapeHtml(o.label),
              value: o.attr,
            };
          }),
          value: this.sourceData.defaultSort[0],
        })


      dir: path.join(__dirname, './coverage'),
      subdir: '.',
      reporters: [
        {type: 'lcov'},
      ],
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    customLaunchers: {
      ChromeHeadlessCI: {
        base: 'ChromeHeadless',
        flags: ['--disable-gpu'],
      },
    },
    singleRun: false,
  });
};

Exposure of Sensitive Information to an Unauthorized Actor

The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.


function renderRestrictedPipeline(node) {
        var gui = '';
        gui += '
' + node.name + '
';
        if (node.message) {
            gui += '
' + _.escape(node.message) + '
';
        }
        gui += '
';
        gui += '<button class="pin" title="Keep dependencies highlighted" />
';
        return gui;
    }


function renderWarning(node) {
        var gui = '';
        if (node.message) {
            gui += '
' + _.escape(node.message) + '
';
        }
        return gui;
    }


function renderDeletedPipeline(node) {
        var gui = '';
        gui += '
' + node.name + '
';
        if (node.message) {
            gui += '
' + _.escape(node.message) + '
';
        }
        gui += '
<button class="pin" title="Keep dependencies highlighted" />
';
        return gui;
    }


function renderScmInstance(instance) {

        return '
'
                + '
Revision: ' + '' + instance.revision + '' + '
'
                + '
' + parseComment(instance.comment) + '
'
                + '
'
                + '
' + _.escape(instance.user) + '
'
                + '
' + _.escape(instance.modified_time) + '
'
                + '
'
                + '
';
    }


function parseComment(comment) {
        if (/"TYPE":"PACKAGE_MATERIAL"/.test(comment)) {
            var comment_markup = "";
            var comment_map = JSON.parse(comment);
            var package_comment = comment_map['COMMENT'];
            var trackback_url = comment_map['TRACKBACK_URL'];
            if (typeof package_comment !== "undefined" || package_comment != null) {
                comment_markup = _.escape(package_comment) + "
";
            }
            if (typeof trackback_url !== "undefined" || trackback_url != null) {
                return comment_markup + "Trackback: " + "" + _.escape(trackback_url) + "";
            }
            return comment_markup + "Trackback: " + "Not Provided";
        }
        return _.escape(comment);
    }


    function parseCommentForTooltip(comment) {
        if (/"TYPE":"PACKAGE_MATERIAL"/.test(comment)) {
            var comment_tooltip = "";
            var comment_map = JSON.parse(comment);
            var package_comment = comment_map['COMMENT'];
            var trackback_url = comment_map['TRACKBACK_URL'];
            if (typeof package_comment !== "undefined" || package_comment != null) {
                comment_tooltip = _.escape(package_comment) + "\n";
            }
            if (typeof trackback_url !== "undefined" || trackback_url != null) {
                return comment_tooltip + "Trackback: " + _.escape(trackback_url);
            }
            return comment_tooltip + "Trackback: " + "Not Provided";
        }
        return _.escape(comment);
    }


function is_content_type(request, ...types) {
	const type = request.headers.get('content-type')?.split(';', 1)[0].trim() ?? '';
	return types.includes(type.toLowerCase());
}


			const newWrapped = (error, sst) => {
				const sandboxSst = ensureThis(sst);
				if (localArrayIsArray(sst)) {
					if (sst === sandboxSst) {
						for (let i=0; i < sst.length; i++) {
							const cs = sst[i];
							if (typeof cs === 'object' && localReflectGetPrototypeOf(cs) === OriginalCallSite.prototype) {
								sst[i] = new CallSite(cs);
							}
						}
					} else {
						sst = [];
						for (let i=0; i < sandboxSst.length; i++) {
							const cs = sandboxSst[i];
							localReflectDefineProperty(sst, i, {
								__proto__: null,
								value: new CallSite(cs),
								enumerable: true,
								configurable: true,
								writable: true
							});
						}
					}
				} else {
					sst = sandboxSst;
				}
				return value(error, sst);
			};
			localReflectApply(localWeakMapSet, wrappedPrepareStackTrace, [value, newWrapped]);
			localReflectApply(localWeakMapSet, wrappedPrepareStackTrace, [newWrapped, newWrapped]);
			currentPrepareStackTrace = newWrapped;
		}

Improper Control of Dynamically-Managed Code Resources

The product does not properly restrict reading from or writing to dynamically-managed code resources such as variables, objects, classes, attributes, functions, or executable instructions or statements.


								value: new CallSite(cs),
								enumerable: true,
								configurable: true,
								writable: true
							});
						}
					}
				} else {
					sst = sandboxSst;
				}
				return value(error, sst);
			};


				coder: () => ')'
			});
		} else if (nodeType === 'Identifier') {
			if (node.name === INTERNAL_STATE_NAME) {
				if (internStateValiable === undefined || internStateValiable.start > node.start) {
					internStateValiable = node;
				}
			} else if (node.name.startsWith(tmpname)) {
				tmpname = node.name + '_UNIQUE';
			}
		} else if (nodeType === 'ImportExpression') {
			insertions.push({
				__proto__: null,
				pos: node.start,
				order: TO_RIGHT,
				coder: () => INTERNAL_STATE_NAME + '.'
			});
		}
	});

	if (internStateValiable) {
		throw makeNiceSyntaxError('Use of internal vm2 state variable', code, filename, internStateValiable.start, {
			__proto__: null,
			start: internStateValiable.start,
			end: internStateValiable.end
		});
	}

	if (insertions.length === 0) return {__proto__: null, code, hasAsync};

	insertions.sort((a, b) => (a.pos == b.pos ? a.order - b.order : a.pos - b.pos));

	let ncode = '';
	let curr = 0;
	for (let i = 0; i < insertions.length; i++) {
		const change = insertions[i];
		ncode += code.substring(curr, change.pos) + change.coder();
		curr = change.pos;
	}
	ncode += code.substring(curr);

	return {__proto__: null, code: ncode, hasAsync};
}


						coder: () => `catch(${tmpname}){try{throw(${tmpname}=${INTERNAL_STATE_NAME}.handleException(${tmpname}));}`
					});


							coder: () => `${name}=${INTERNAL_STATE_NAME}.handleException(${name});`
						});


						args[1] = function wrapper(error) {
							error = ensureThis(error);
							return localReflectApply(onRejected, this, [error]);
						};


			apply(target, thiz, args) {
				if (args.length > 1) {
					const onRejected = args[1];
					if (typeof onRejected === 'function') {
						args[1] = function wrapper(error) {
							error = ensureThis(error);
							return localReflectApply(onRejected, this, [error]);
						};
					}
				}
				return localReflectApply(target, thiz, args);
			}


function wrapProxyHandler(args) {
	if (args.length < 2) return args;
	const handler = args[1];
	args[1] = new LocalProxy({__proto__: null, handler}, proxyHandlerHandler);
	return args;
}


	construct(target, args, newTarget) {
		return localReflectConstruct(target, makeSafeHandlerArgs(args), newTarget);
	}


	get(target, name, receiver) {
		const value = target.handler[name];
		if (typeof value !== 'function') return value;
		return new LocalProxy(value, makeSafeArgs);
	}


function makeSafeHandlerArgs(args) {
	const sArgs = ensureThis(args);
	if (sArgs === args) return args;
	const a = [];
	for (let i=0; i < sArgs.length; i++) {
		localReflectDefineProperty(a, i, {
			__proto__: null,
			value: sArgs[i],
			enumerable: true,
			configurable: true,
			writable: true
		});
	}
	return a;
}


	apply(target, thiz, args) {
		return localReflectApply(target, thiz, makeSafeHandlerArgs(args));
	},


				value: bridge.from(sandboxGlobal),
				enumerable: true
			},
			_runScript: {__proto__: null, value: runScript},
			_makeReadonly: {__proto__: null, value: makeReadonly},
			_makeProtected: {__proto__: null, value: makeProtected},
			_addProtoMapping: {__proto__: null, value: addProtoMapping},
			_addProtoMappingFactory: {__proto__: null, value: addProtoMappingFactory},
			_compiler: {__proto__: null, value: resolvedCompiler},
			_allowAsync: {__proto__: null, value: allowAsync}
		});

		this.readonly(inspect);

		// prepare global sandbox
		if (sandbox) {
			this.setGlobals(sandbox);
		}
	}


        const readFiles = function(files) {
        fs.readFile(files[0], Tesseract.outputEncoding, function(err, data) {
          if (err) {
            callback(err, null);
            return;
          }

          var index = Tesseract.tmpFiles.indexOf(output);
          if (~index) Tesseract.tmpFiles.splice(index, 1);

          fs.unlinkSync(files[0]);

          callback(null, data, extra);
        });
        };

Improper Neutralization of Special Elements used in a Command ('Command Injection')

The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.


The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.


"da, mi, en, de-DE")};EditorUi.prototype.loadUrl=function(d,g,k,l,p,q,x,y){EditorUi.logEvent("SHOULD NOT BE CALLED: loadUrl");return this.editor.loadUrl(d,g,k,l,p,q,x,y)};EditorUi.prototype.loadFonts=function(d){EditorUi.logEvent("SHOULD NOT BE CALLED: loadFonts");return this.editor.loadFonts(d)};EditorUi.prototype.createSvgDataUri=function(d){EditorUi.logEvent("SHOULD NOT BE CALLED: createSvgDataUri");return Editor.createSvgDataUri(d)};EditorUi.prototype.embedCssFonts=function(d,g){EditorUi.logEvent("SHOULD NOT BE CALLED: embedCssFonts");


Graph.prototype.getFlowAnimationStyleCss=function(a){return"."+a+" {\nanimation: "+a+" 0.5s linear;\nanimation-iteration-count: infinite;\n}\n@keyframes "+a+" {\nto {\nstroke-dashoffset: "+-16*this.view.scale+";\n}\n}"};Graph.prototype.stringToBytes=function(a){return Graph.stringToBytes(a)};Graph.prototype.bytesToString=function(a){return Graph.bytesToString(a)};Graph.prototype.compressNode=function(a){return Graph.compressNode(a)};Graph.prototype.compress=function(a,b){return Graph.compress(a,b)};


0),!1,null,l,q));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,.5*l,q-.5*l));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,0,q-l));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,0,.5*(q-l)));return c};A.prototype.getConstraints=function(c,h,q){c=[];h=Math.max(0,Math.min(q,parseFloat(mxUtils.getValue(this.style,"size",this.size))));c.push(new mxConnectionConstraint(new mxPoint(.5,0),!1));c.push(new mxConnectionConstraint(new mxPoint(0,.5),!1));c.push(new mxConnectionConstraint(new mxPoint(.5,
1),!1));c.push(new mxConnectionConstraint(new mxPoint(1,.5),!1));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,0,h));c.push(new mxConnectionConstraint(new mxPoint(1,0),!1,null,0,h));c.push(new mxConnectionConstraint(new mxPoint(1,1),!1,null,0,-h));c.push(new mxConnectionConstraint(new mxPoint(0,1),!1,null,0,-h));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,0,h+.5*(.5*q-h)));c.push(new mxConnectionConstraint(new mxPoint(1,0),!1,null,0,h+.5*(.5*q-h)));c.push(new mxConnectionConstraint(new mxPoint(1,
0),!1,null,0,q-h-.5*(.5*q-h)));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,0,q-h-.5*(.5*q-h)));c.push(new mxConnectionConstraint(new mxPoint(.145,0),!1,null,0,.29*h));c.push(new mxConnectionConstraint(new mxPoint(.855,0),!1,null,0,.29*h));c.push(new mxConnectionConstraint(new mxPoint(.855,1),!1,null,0,.29*-h));c.push(new mxConnectionConstraint(new mxPoint(.145,1),!1,null,0,.29*-h));return c};F.prototype.getConstraints=function(c,h,q){c=[];var l=Math.max(0,Math.min(h,parseFloat(mxUtils.getValue(this.style,