UNPKG

@peculiar/fortify-webcomponents

Version:

Web-components for creating CSR or Certificate and viewing certificates list using Fortify

1,478 lines (1,475 loc) 337 kB
/*! * © Peculiar Ventures https://peculiarventures.com/ - BSD 3-Clause License */ var WebcryptoSocket = function (exports, protobufjs, WebSocket) { /*! * MIT License * * Copyright (c) 2017-2022 Peculiar Ventures, LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ const ARRAY_BUFFER_NAME = "[object ArrayBuffer]"; class BufferSourceConverter { static isArrayBuffer(data) { return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME; } static toArrayBuffer(data) { if (this.isArrayBuffer(data)) { return data; } if (data.byteLength === data.buffer.byteLength) { return data.buffer; } if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) { return data.buffer; } return this.toUint8Array(data.buffer).slice(data.byteOffset, data.byteOffset + data.byteLength).buffer; } static toUint8Array(data) { return this.toView(data, Uint8Array); } static toView(data, type) { if (data.constructor === type) { return data; } if (this.isArrayBuffer(data)) { return new type(data); } if (this.isArrayBufferView(data)) { return new type(data.buffer, data.byteOffset, data.byteLength); } throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'"); } static isBufferSource(data) { return this.isArrayBufferView(data) || this.isArrayBuffer(data); } static isArrayBufferView(data) { return ArrayBuffer.isView(data) || data && this.isArrayBuffer(data.buffer); } static isEqual(a, b) { const aView = BufferSourceConverter.toUint8Array(a); const bView = BufferSourceConverter.toUint8Array(b); if (aView.length !== bView.byteLength) { return false; } for (let i = 0; i < aView.length; i++) { if (aView[i] !== bView[i]) { return false; } } return true; } static concat(...args) { let buffers; if (Array.isArray(args[0]) && !(args[1] instanceof Function)) { buffers = args[0]; } else if (Array.isArray(args[0]) && args[1] instanceof Function) { buffers = args[0]; } else { if (args[args.length - 1] instanceof Function) { buffers = args.slice(0, args.length - 1); } else { buffers = args; } } let size = 0; for (const buffer of buffers) { size += buffer.byteLength; } const res = new Uint8Array(size); let offset = 0; for (const buffer of buffers) { const view = this.toUint8Array(buffer); res.set(view, offset); offset += view.length; } if (args[args.length - 1] instanceof Function) { return this.toView(res, args[args.length - 1]); } return res.buffer; } } const STRING_TYPE = "string"; const HEX_REGEX = /^[0-9a-f]+$/i; const BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; const BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/; class Utf8Converter { static fromString(text) { const s = unescape(encodeURIComponent(text)); const uintArray = new Uint8Array(s.length); for (let i = 0; i < s.length; i++) { uintArray[i] = s.charCodeAt(i); } return uintArray.buffer; } static toString(buffer) { const buf = BufferSourceConverter.toUint8Array(buffer); let encodedString = ""; for (let i = 0; i < buf.length; i++) { encodedString += String.fromCharCode(buf[i]); } const decodedString = decodeURIComponent(escape(encodedString)); return decodedString; } } class Utf16Converter { static toString(buffer, littleEndian = false) { const arrayBuffer = BufferSourceConverter.toArrayBuffer(buffer); const dataView = new DataView(arrayBuffer); let res = ""; for (let i = 0; i < arrayBuffer.byteLength; i += 2) { const code = dataView.getUint16(i, littleEndian); res += String.fromCharCode(code); } return res; } static fromString(text, littleEndian = false) { const res = new ArrayBuffer(text.length * 2); const dataView = new DataView(res); for (let i = 0; i < text.length; i++) { dataView.setUint16(i * 2, text.charCodeAt(i), littleEndian); } return res; } } class Convert { static isHex(data) { return typeof data === STRING_TYPE && HEX_REGEX.test(data); } static isBase64(data) { return typeof data === STRING_TYPE && BASE64_REGEX.test(data); } static isBase64Url(data) { return typeof data === STRING_TYPE && BASE64URL_REGEX.test(data); } static ToString(buffer, enc = "utf8") { const buf = BufferSourceConverter.toUint8Array(buffer); switch (enc.toLowerCase()) { case "utf8": return this.ToUtf8String(buf); case "binary": return this.ToBinary(buf); case "hex": return this.ToHex(buf); case "base64": return this.ToBase64(buf); case "base64url": return this.ToBase64Url(buf); case "utf16le": return Utf16Converter.toString(buf, true); case "utf16": case "utf16be": return Utf16Converter.toString(buf); default: throw new Error(`Unknown type of encoding '${enc}'`); } } static FromString(str, enc = "utf8") { if (!str) { return new ArrayBuffer(0); } switch (enc.toLowerCase()) { case "utf8": return this.FromUtf8String(str); case "binary": return this.FromBinary(str); case "hex": return this.FromHex(str); case "base64": return this.FromBase64(str); case "base64url": return this.FromBase64Url(str); case "utf16le": return Utf16Converter.fromString(str, true); case "utf16": case "utf16be": return Utf16Converter.fromString(str); default: throw new Error(`Unknown type of encoding '${enc}'`); } } static ToBase64(buffer) { const buf = BufferSourceConverter.toUint8Array(buffer); if (typeof btoa !== "undefined") { const binary = this.ToString(buf, "binary"); return btoa(binary); } else { return Buffer.from(buf).toString("base64"); } } static FromBase64(base64) { const formatted = this.formatString(base64); if (!formatted) { return new ArrayBuffer(0); } if (!Convert.isBase64(formatted)) { throw new TypeError("Argument 'base64Text' is not Base64 encoded"); } if (typeof atob !== "undefined") { return this.FromBinary(atob(formatted)); } else { return new Uint8Array(Buffer.from(formatted, "base64")).buffer; } } static FromBase64Url(base64url) { const formatted = this.formatString(base64url); if (!formatted) { return new ArrayBuffer(0); } if (!Convert.isBase64Url(formatted)) { throw new TypeError("Argument 'base64url' is not Base64Url encoded"); } return this.FromBase64(this.Base64Padding(formatted.replace(/\-/g, "+").replace(/\_/g, "/"))); } static ToBase64Url(data) { return this.ToBase64(data).replace(/\+/g, "-").replace(/\//g, "_").replace(/\=/g, ""); } static FromUtf8String(text, encoding = Convert.DEFAULT_UTF8_ENCODING) { switch (encoding) { case "ascii": return this.FromBinary(text); case "utf8": return Utf8Converter.fromString(text); case "utf16": case "utf16be": return Utf16Converter.fromString(text); case "utf16le": case "usc2": return Utf16Converter.fromString(text, true); default: throw new Error(`Unknown type of encoding '${encoding}'`); } } static ToUtf8String(buffer, encoding = Convert.DEFAULT_UTF8_ENCODING) { switch (encoding) { case "ascii": return this.ToBinary(buffer); case "utf8": return Utf8Converter.toString(buffer); case "utf16": case "utf16be": return Utf16Converter.toString(buffer); case "utf16le": case "usc2": return Utf16Converter.toString(buffer, true); default: throw new Error(`Unknown type of encoding '${encoding}'`); } } static FromBinary(text) { const stringLength = text.length; const resultView = new Uint8Array(stringLength); for (let i = 0; i < stringLength; i++) { resultView[i] = text.charCodeAt(i); } return resultView.buffer; } static ToBinary(buffer) { const buf = BufferSourceConverter.toUint8Array(buffer); let res = ""; for (let i = 0; i < buf.length; i++) { res += String.fromCharCode(buf[i]); } return res; } static ToHex(buffer) { const buf = BufferSourceConverter.toUint8Array(buffer); let result = ""; const len = buf.length; for (let i = 0; i < len; i++) { const byte = buf[i]; if (byte < 16) { result += "0"; } result += byte.toString(16); } return result; } static FromHex(hexString) { let formatted = this.formatString(hexString); if (!formatted) { return new ArrayBuffer(0); } if (!Convert.isHex(formatted)) { throw new TypeError("Argument 'hexString' is not HEX encoded"); } if (formatted.length % 2) { formatted = `0${formatted}`; } const res = new Uint8Array(formatted.length / 2); for (let i = 0; i < formatted.length; i = i + 2) { const c = formatted.slice(i, i + 2); res[i / 2] = parseInt(c, 16); } return res.buffer; } static ToUtf16String(buffer, littleEndian = false) { return Utf16Converter.toString(buffer, littleEndian); } static FromUtf16String(text, littleEndian = false) { return Utf16Converter.fromString(text, littleEndian); } static Base64Padding(base64) { const padCount = 4 - base64.length % 4; if (padCount < 4) { for (let i = 0; i < padCount; i++) { base64 += "="; } } return base64; } static formatString(data) { return (data === null || data === void 0 ? void 0 : data.replace(/[\n\r\t ]/g, "")) || ""; } } Convert.DEFAULT_UTF8_ENCODING = "utf8"; function assign(target, ...sources) { const res = arguments[0]; for (let i = 1; i < arguments.length; i++) { const obj = arguments[i]; for (const prop in obj) { res[prop] = obj[prop]; } } return res; } function combine(...buf) { const totalByteLength = buf.map(item => item.byteLength).reduce((prev, cur) => prev + cur); const res = new Uint8Array(totalByteLength); let currentPos = 0; buf.map(item => new Uint8Array(item)).forEach(arr => { for (const item2 of arr) { res[currentPos++] = item2; } }); return res.buffer; } function isEqual(bytes1, bytes2) { if (!(bytes1 && bytes2)) { return false; } if (bytes1.byteLength !== bytes2.byteLength) { return false; } const b1 = new Uint8Array(bytes1); const b2 = new Uint8Array(bytes2); for (let i = 0; i < bytes1.byteLength; i++) { if (b1[i] !== b2[i]) { return false; } } return true; } /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; class ArrayBufferConverter { static async set(value) { return new Uint8Array(value); } static async get(value) { return new Uint8Array(value).buffer; } } function ProtobufElement(params) { return target => { const t = target; t.localName = params.name || t.name || t.toString().match(/^function\s*([^\s(]+)/)[1]; t.items = t.items || {}; t.target = target; t.items = assign({}, t.items); const scheme = new protobufjs.Type(t.localName); for (const key in t.items) { const item = t.items[key]; let rule = void 0; if (item.repeated) { rule = "repeated"; } else if (item.required) { rule = "required"; } scheme.add(new protobufjs.Field(item.name, item.id, item.type, rule)); } t.protobuf = scheme; }; } function defineProperty(target, key, params) { const propertyKey = `_${key}`; const opt = { set: function (v) { if (this[propertyKey] !== v) { this.raw = null; this[propertyKey] = v; } }, get: function () { if (this[propertyKey] === void 0) { let defaultValue = params.defaultValue; if (params.parser && !params.repeated) { defaultValue = new params.parser(); } this[propertyKey] = defaultValue; } return this[propertyKey]; }, enumerable: true }; Object.defineProperty(target, propertyKey, { writable: true, enumerable: false }); Object.defineProperty(target, key, opt); } function ProtobufProperty(params) { return (target, propertyKey) => { const t = target.constructor; const key = propertyKey; t.items = t.items || {}; if (t.target !== t) { t.items = assign({}, t.items); t.target = t; } t.items[key] = { id: params.id, type: params.type || "bytes", defaultValue: params.defaultValue, converter: params.converter || null, parser: params.parser || null, name: params.name || key, required: params.required || false, repeated: params.repeated || false }; defineProperty(target, key, t.items[key]); }; } class ObjectProto { static async importProto(data) { const res = new this(); await res.importProto(data); return res; } isEmpty() { return this.raw === undefined; } hasChanged() { if (this.raw === null) { return true; } const thisStatic = this.constructor; const that = this; for (const key in thisStatic.items) { const item = thisStatic.items[key]; if (item.repeated) { if (item.parser) { return that[key].some(arrayItem => arrayItem.hasChanged()); } } else { if (item.parser && that[key] && that[key].hasChanged()) { return true; } } } return false; } async importProto(data) { const thisStatic = this.constructor; const that = this; let scheme; let raw; if (data instanceof ObjectProto) { raw = await data.exportProto(); } else { raw = data; } try { if (!thisStatic.protobuf) { throw new Error("Protobuf schema doesn't contain 'protobuf' property"); } scheme = thisStatic.protobuf.decode(new Uint8Array(raw)); } catch (e) { const err = e instanceof Error ? e : new Error("Unknown error"); throw new Error(`Cannot decode message for ${thisStatic.localName}.\n$ProtobufError: ${err.message}`); } for (const key in thisStatic.items) { const item = thisStatic.items[key]; let schemeValues = scheme[item.name]; if (ArrayBuffer.isView(schemeValues)) { schemeValues = new Uint8Array(schemeValues); } if (!Array.isArray(schemeValues)) { if (item.repeated) { that[key] = schemeValues = []; } else { schemeValues = [schemeValues]; } } if (item.repeated && !that[key]) { that[key] = []; } for (const schemeValue of schemeValues) { if (item.repeated) { that[key].push(await this.importItem(item, schemeValue)); } else { that[key] = await this.importItem(item, schemeValue); } } } this.raw = raw; } async exportProto() { if (!this.hasChanged()) { return this.raw; } const thisStatic = this.constructor; const that = this; const protobuf = {}; for (const key in thisStatic.items) { const item = thisStatic.items[key]; let values = that[key]; if (!Array.isArray(values)) { values = values === void 0 ? [] : [values]; } for (const value of values) { const protobufValue = await this.exportItem(item, value); if (item.repeated) { if (!protobuf[item.name]) { protobuf[item.name] = []; } protobuf[item.name].push(protobufValue); } else { protobuf[item.name] = protobufValue; } } } this.raw = new Uint8Array(thisStatic.protobuf.encode(protobuf).finish()).buffer; return this.raw; } async exportItem(template, value) { const thisStatic = this.constructor; let result; if (template.parser) { const obj = value; const raw = await obj.exportProto(); if (template.required && !raw) { throw new Error(`Parameter '${template.name}' is required in '${thisStatic.localName}' protobuf message.`); } if (raw) { result = new Uint8Array(raw); } } else { if (template.required && value === undefined) { throw new Error(`Parameter '${template.name}' is required in '${thisStatic.localName}' protobuf message.`); } if (template.converter) { if (value !== undefined) { result = await template.converter.set(value); } } else { if (value instanceof ArrayBuffer) { value = new Uint8Array(value); } result = value; } } return result; } async importItem(template, value) { const thisStatic = this.constructor; let result; if (template.parser) { const parser = template.parser; if (value && value.byteLength) { result = await parser.importProto(new Uint8Array(value).buffer); } else if (template.required) { throw new Error(`Parameter '${template.name}' is required in '${thisStatic.localName}' protobuf message.`); } } else if (template.converter) { if (value && value.byteLength) { result = await template.converter.get(value); } else if (template.required) { throw new Error(`Parameter '${template.name}' is required in '${thisStatic.localName}' protobuf message.`); } } else { result = value; } return result; } } function EventHandlers() {} EventHandlers.prototype = Object.create(null); function EventEmitter() { EventEmitter.init.call(this); } EventEmitter.EventEmitter = EventEmitter; EventEmitter.usingDomains = false; EventEmitter.prototype.domain = undefined; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; EventEmitter.defaultMaxListeners = 10; EventEmitter.init = function () { this.domain = null; if (!this._events || this._events === Object.getPrototypeOf(this)._events) { this._events = new EventHandlers(); this._eventsCount = 0; } this._maxListeners = this._maxListeners || undefined; }; EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || isNaN(n)) throw new TypeError('"n" argument must be a positive number'); this._maxListeners = n; return this; }; function $getMaxListeners(that) { if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return $getMaxListeners(this); }; function emitNone(handler, isFn, self) { if (isFn) handler.call(self);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self); } } function emitOne(handler, isFn, self, arg1) { if (isFn) handler.call(self, arg1);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1); } } function emitTwo(handler, isFn, self, arg1, arg2) { if (isFn) handler.call(self, arg1, arg2);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2); } } function emitThree(handler, isFn, self, arg1, arg2, arg3) { if (isFn) handler.call(self, arg1, arg2, arg3);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].call(self, arg1, arg2, arg3); } } function emitMany(handler, isFn, self, args) { if (isFn) handler.apply(self, args);else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) listeners[i].apply(self, args); } } EventEmitter.prototype.emit = function emit(type) { var er, handler, len, args, i, events, domain; var doError = type === 'error'; events = this._events; if (events) doError = doError && events.error == null;else if (!doError) return false; domain = this.domain; if (doError) { er = arguments[1]; if (domain) { if (!er) er = new Error('Uncaught, unspecified "error" event'); er.domainEmitter = this; er.domain = domain; er.domainThrown = false; domain.emit('error', er); } else if (er instanceof Error) { throw er; } else { var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } return false; } handler = events[type]; if (!handler) return false; var isFn = typeof handler === 'function'; len = arguments.length; switch (len) { case 1: emitNone(handler, isFn, this); break; case 2: emitOne(handler, isFn, this, arguments[1]); break; case 3: emitTwo(handler, isFn, this, arguments[1], arguments[2]); break; case 4: emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); break; default: args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; emitMany(handler, isFn, this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = target._events; if (!events) { events = target._events = new EventHandlers(); target._eventsCount = 0; } else { if (events.newListener) { target.emit('newListener', type, listener.listener ? listener.listener : listener); events = target._events; } existing = events[type]; } if (!existing) { existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === 'function') { existing = events[type] = prepend ? [listener, existing] : [existing, listener]; } else { if (prepend) { existing.unshift(listener); } else { existing.push(listener); } } if (!existing.warned) { m = $getMaxListeners(target); if (m && m > 0 && existing.length > m) { existing.warned = true; var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + type + ' listeners added. ' + 'Use emitter.setMaxListeners() to increase limit'); w.name = 'MaxListenersExceededWarning'; w.emitter = target; w.type = type; w.count = existing.length; emitWarning(w); } } } return target; } function emitWarning(e) { typeof console.warn === 'function' ? console.warn(e) : console.log(e); } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function _onceWrap(target, type, listener) { var fired = false; function g() { target.removeListener(type, g); if (!fired) { fired = true; listener.apply(target, arguments); } } g.listener = listener; return g; } EventEmitter.prototype.once = function once(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = this._events; if (!events) return this; list = events[type]; if (!list) return this; if (list === listener || list.listener && list.listener === listener) { if (--this._eventsCount === 0) this._events = new EventHandlers();else { delete events[type]; if (events.removeListener) this.emit('removeListener', type, list.listener || listener); } } else if (typeof list !== 'function') { position = -1; for (i = list.length; i-- > 0;) { if (list[i] === listener || list[i].listener && list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (list.length === 1) { list[0] = undefined; if (--this._eventsCount === 0) { this._events = new EventHandlers(); return this; } else { delete events[type]; } } else { spliceOne(list, position); } if (events.removeListener) this.emit('removeListener', type, originalListener || listener); } return this; }; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events; events = this._events; if (!events) return this; if (!events.removeListener) { if (arguments.length === 0) { this._events = new EventHandlers(); this._eventsCount = 0; } else if (events[type]) { if (--this._eventsCount === 0) this._events = new EventHandlers();else delete events[type]; } return this; } if (arguments.length === 0) { var keys = Object.keys(events); for (var i = 0, key; i < keys.length; ++i) { key = keys[i]; if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = new EventHandlers(); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners) { do { this.removeListener(type, listeners[listeners.length - 1]); } while (listeners[0]); } return this; }; EventEmitter.prototype.listeners = function listeners(type) { var evlistener; var ret; var events = this._events; if (!events) ret = [];else { evlistener = events[type]; if (!evlistener) ret = [];else if (typeof evlistener === 'function') ret = [evlistener.listener || evlistener];else ret = unwrapListeners(evlistener); } return ret; }; EventEmitter.listenerCount = function (emitter, type) { if (typeof emitter.listenerCount === 'function') { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events) { var evlistener = events[type]; if (typeof evlistener === 'function') { return 1; } else if (evlistener) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; }; function spliceOne(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) list[i] = list[k]; list.pop(); } function arrayClone(arr, i) { var copy = new Array(i); while (i--) copy[i] = arr[i]; return copy; } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } const SIGN_ALGORITHM_NAME = "ECDSA"; const DH_ALGORITHM_NAME = "ECDH"; const SECRET_KEY_NAME = "AES-CBC"; const HASH_NAME = "SHA-256"; const HMAC_NAME = "HMAC"; const MAX_RATCHET_STACK_SIZE = 20; const INFO_TEXT = Convert.FromBinary("InfoText"); const INFO_RATCHET = Convert.FromBinary("InfoRatchet"); const INFO_MESSAGE_KEYS = Convert.FromBinary("InfoMessageKeys"); let engine = null; if (typeof self !== "undefined") { engine = { crypto: self.crypto, name: "WebCrypto" }; } function setEngine(name, crypto) { engine = { crypto, name }; } function getEngine() { if (!engine) { throw new Error("WebCrypto engine is empty. Use setEngine to resolve it."); } return engine; } let Curve = (() => { class Curve { static async generateKeyPair(type, extractable) { const name = type; const usage = type === "ECDSA" ? ["sign", "verify"] : ["deriveKey", "deriveBits"]; const keys = await getEngine().crypto.subtle.generateKey({ name, namedCurve: this.NAMED_CURVE }, extractable, usage); const publicKey = await ECPublicKey.create(keys.publicKey); const res = { privateKey: keys.privateKey, publicKey }; return res; } static deriveBytes(privateKey, publicKey) { return getEngine().crypto.subtle.deriveBits({ name: "ECDH", public: publicKey.key }, privateKey, 256); } static verify(signingKey, message, signature) { return getEngine().crypto.subtle.verify({ name: "ECDSA", hash: this.DIGEST_ALGORITHM }, signingKey.key, signature, message); } static async sign(signingKey, message) { return getEngine().crypto.subtle.sign({ name: "ECDSA", hash: this.DIGEST_ALGORITHM }, signingKey, message); } static async ecKeyPairToJson(key) { return { privateKey: key.privateKey, publicKey: key.publicKey.key, thumbprint: await key.publicKey.thumbprint() }; } static async ecKeyPairFromJson(keys) { return { privateKey: keys.privateKey, publicKey: await ECPublicKey.create(keys.publicKey) }; } } Curve.NAMED_CURVE = "P-256"; Curve.DIGEST_ALGORITHM = "SHA-512"; return Curve; })(); const AES_ALGORITHM = { name: "AES-CBC", length: 256 }; class Secret { static randomBytes(size) { const array = new Uint8Array(size); getEngine().crypto.getRandomValues(array); return array.buffer; } static digest(alg, message) { return getEngine().crypto.subtle.digest(alg, message); } static encrypt(key, data, iv) { return getEngine().crypto.subtle.encrypt({ name: SECRET_KEY_NAME, iv: new Uint8Array(iv) }, key, data); } static decrypt(key, data, iv) { return getEngine().crypto.subtle.decrypt({ name: SECRET_KEY_NAME, iv: new Uint8Array(iv) }, key, data); } static importHMAC(raw) { return getEngine().crypto.subtle.importKey("raw", raw, { name: HMAC_NAME, hash: { name: HASH_NAME } }, false, ["sign", "verify"]); } static importAES(raw) { return getEngine().crypto.subtle.importKey("raw", raw, AES_ALGORITHM, false, ["encrypt", "decrypt"]); } static async sign(key, data) { return await getEngine().crypto.subtle.sign({ name: HMAC_NAME, hash: HASH_NAME }, key, data); } static async HKDF(IKM, keysCount = 1, salt, info = new ArrayBuffer(0)) { if (!salt) { salt = await this.importHMAC(new Uint8Array(32).buffer); } const PRKBytes = await this.sign(salt, IKM); const PRK = await this.importHMAC(PRKBytes); const T = [new ArrayBuffer(0)]; for (let i = 0; i < keysCount; i++) { T[i + 1] = await this.sign(PRK, combine(T[i], info, new Uint8Array([i + 1]).buffer)); } return T.slice(1); } } class ECPublicKey { static async create(publicKey) { const res = new this(); const algName = publicKey.algorithm.name.toUpperCase(); if (!(algName === "ECDH" || algName === "ECDSA")) { throw new Error("Error: Unsupported asymmetric key algorithm."); } if (publicKey.type !== "public") { throw new Error("Error: Expected key type to be public but it was not."); } res.key = publicKey; const jwk = await getEngine().crypto.subtle.exportKey("jwk", publicKey); if (!(jwk.x && jwk.y)) { throw new Error("Wrong JWK data for EC public key. Parameters x and y are required."); } const x = Convert.FromBase64Url(jwk.x); const y = Convert.FromBase64Url(jwk.y); const xy = Convert.ToBinary(x) + Convert.ToBinary(y); res.serialized = Convert.FromBinary(xy); res.id = await res.thumbprint(); return res; } static async importKey(bytes, type) { const x = Convert.ToBase64Url(bytes.slice(0, 32)); const y = Convert.ToBase64Url(bytes.slice(32)); const jwk = { crv: Curve.NAMED_CURVE, kty: "EC", x, y }; const usage = type === "ECDSA" ? ["verify"] : []; const key = await getEngine().crypto.subtle.importKey("jwk", jwk, { name: type, namedCurve: Curve.NAMED_CURVE }, true, usage); const res = await ECPublicKey.create(key); return res; } serialize() { return this.serialized; } async thumbprint() { const bytes = await this.serialize(); const thumbprint = await Secret.digest("SHA-256", bytes); return Convert.ToHex(thumbprint); } async isEqual(other) { if (!(other && other instanceof ECPublicKey)) { return false; } return isEqual(this.serialized, other.serialized); } } class Identity { constructor(id, signingKey, exchangeKey) { this.id = id; this.signingKey = signingKey; this.exchangeKey = exchangeKey; this.preKeys = []; this.signedPreKeys = []; } static async fromJSON(obj) { const signingKey = await Curve.ecKeyPairFromJson(obj.signingKey); const exchangeKey = await Curve.ecKeyPairFromJson(obj.exchangeKey); const res = new this(obj.id, signingKey, exchangeKey); res.createdAt = new Date(obj.createdAt); await res.fromJSON(obj); return res; } static async create(id, signedPreKeyAmount = 0, preKeyAmount = 0, extractable = false) { const signingKey = await Curve.generateKeyPair(SIGN_ALGORITHM_NAME, extractable); const exchangeKey = await Curve.generateKeyPair(DH_ALGORITHM_NAME, extractable); const res = new Identity(id, signingKey, exchangeKey); res.createdAt = new Date(); for (let i = 0; i < preKeyAmount; i++) { res.preKeys.push(await Curve.generateKeyPair("ECDH", extractable)); } for (let i = 0; i < signedPreKeyAmount; i++) { res.signedPreKeys.push(await Curve.generateKeyPair("ECDH", extractable)); } return res; } async toJSON() { const preKeys = []; const signedPreKeys = []; for (const key of this.preKeys) { preKeys.push(await Curve.ecKeyPairToJson(key)); } for (const key of this.signedPreKeys) { signedPreKeys.push(await Curve.ecKeyPairToJson(key)); } return { createdAt: this.createdAt.toISOString(), exchangeKey: await Curve.ecKeyPairToJson(this.exchangeKey), id: this.id, preKeys, signedPreKeys, signingKey: await Curve.ecKeyPairToJson(this.signingKey) }; } async fromJSON(obj) { this.id = obj.id; this.signingKey = await Curve.ecKeyPairFromJson(obj.signingKey); this.exchangeKey = await Curve.ecKeyPairFromJson(obj.exchangeKey); this.preKeys = []; for (const key of obj.preKeys) { this.preKeys.push(await Curve.ecKeyPairFromJson(key)); } this.signedPreKeys = []; for (const key of obj.signedPreKeys) { this.signedPreKeys.push(await Curve.ecKeyPairFromJson(key)); } } } class RemoteIdentity { static fill(protocol) { const res = new RemoteIdentity(); res.fill(protocol); return res; } static async fromJSON(obj) { const res = new this(); await res.fromJSON(obj); return res; } fill(protocol) { this.signingKey = protocol.signingKey; this.exchangeKey = protocol.exchangeKey; this.signature = protocol.signature; this.createdAt = protocol.createdAt; } verify() { return Curve.verify(this.signingKey, this.exchangeKey.serialize(), this.signature); } async toJSON() { return { createdAt: this.createdAt.toISOString(), exchangeKey: await this.exchangeKey.key, id: this.id, signature: this.signature, signingKey: await this.signingKey.key, thumbprint: await this.signingKey.thumbprint() }; } async fromJSON(obj) { this.id = obj.id; this.signature = obj.signature; this.signingKey = await ECPublicKey.create(obj.signingKey); this.exchangeKey = await ECPublicKey.create(obj.exchangeKey); this.createdAt = new Date(obj.createdAt); const ok = await this.verify(); if (!ok) { throw new Error("Error: Wrong signature for RemoteIdentity"); } } } let BaseProtocol = (() => { let BaseProtocol = class BaseProtocol extends ObjectProto {}; __decorate([ProtobufProperty({ id: 0, type: "uint32", defaultValue: 1 })], BaseProtocol.prototype, "version", void 0); BaseProtocol = __decorate([ProtobufElement({ name: "Base" })], BaseProtocol); return BaseProtocol; })(); class ECDSAPublicKeyConverter { static async set(value) { return new Uint8Array(value.serialize()); } static async get(value) { return ECPublicKey.importKey(value.buffer, "ECDSA"); } } class ECDHPublicKeyConverter { static async set(value) { return new Uint8Array(value.serialize()); } static async get(value) { return ECPublicKey.importKey(value.buffer, "ECDH"); } } let DateConverter$1 = class DateConverter { static async set(value) { return new Uint8Array(Convert.FromString(value.toISOString())); } static async get(value) { return new Date(Convert.ToString(value)); } }; let IdentityProtocol = (() => { var IdentityProtocol_1; let IdentityProtocol = IdentityProtocol_1 = class IdentityProtocol extends BaseProtocol { static async fill(identity) { const res = new IdentityProtocol_1(); await res.fill(identity); return res; } async sign(key) { this.signature = await Curve.sign(key, this.exchangeKey.serialize()); } async verify() { return await Curve.verify(this.signingKey, this.exchangeKey.serialize(), this.signature); } async fill(identity) { this.signingKey = identity.signingKey.publicKey; this.exchangeKey = identity.exchangeKey.publicKey; this.createdAt = identity.createdAt; await this.sign(identity.signingKey.privateKey); } }; __decorate([ProtobufProperty({ id: 1, converter: ECDSAPublicKeyConverter })], IdentityProtocol.prototype, "signingKey", void 0); __decorate([ProtobufProperty({ id: 2, converter: ECDHPublicKeyConverter })], IdentityProtocol.prototype, "exchangeKey", void 0); __decorate([ProtobufProperty({ id: 3 })], IdentityProtocol.prototype, "signature", void 0); __decorate([ProtobufProperty({ id: 4, converter: DateConverter$1 })], IdentityProtocol.prototype, "createdAt", void 0); IdentityProtocol = IdentityProtocol_1 = __decorate([ProtobufElement({ name: "Identity" })], IdentityProtocol); return IdentityProtocol; })(); let MessageProtocol = (() => { let MessageProtocol = class MessageProtocol extends BaseProtocol {}; __decorate([ProtobufProperty({ id: 1, converter: ECDHPublicKeyConverter, required: true })], MessageProtocol.prototype, "senderRatchetKey", void 0); __decorate([ProtobufProperty({ id: 2, type: "uint32", required: true })], MessageProtocol.prototype, "counter", void 0); __decorate([ProtobufProperty({ id: 3, type: "uint32", required: true })], MessageProtocol.prototype, "previousCounter", void 0); __decorate([ProtobufProperty({ id: 4, converter: ArrayBufferConverter, required: true })], MessageProtocol.prototype, "cipherText", void 0); MessageProtocol = __decorate([ProtobufElement({ name: "Message" })], MessageProtocol); return MessageProtocol; })(); let MessageSignedProtocol = (() => { let MessageSignedProtocol = class MessageSignedProtocol extends BaseProtocol { async sign(hmacKey) { this.signature = await this.signHMAC(hmacKey); } async verify(hmacKey) { const signature = await this.signHMAC(hmacKey); return isEqual(signature, this.signature); } async getSignedRaw() { const receiverKey = this.receiverKey.serialize(); const senderKey = this.senderKey.serialize(); const message = await this.message.exportProto(); const data = combine(receiverKey, senderKey, message); return data; } async signHMAC(macKey) { const data = await this.getSignedRaw(); const signature = await Secret.sign(macKey, data); return signature; } }; __decorate([ProtobufProperty({ id: 1, converter: ECDSAPublicKeyConverter, required: true })], MessageSignedProtocol.prototype, "senderKey", void 0); __decorate([ProtobufProperty({ id: 2, parser: MessageProtocol, required: true })], MessageSignedProtocol.prototype, "message", void 0); __decorate([ProtobufProperty({ id: 3, required: true })], MessageSignedProtocol.prototype, "signature", void 0); MessageSignedProtocol = __decorate([ProtobufElement({ name: "MessageSigned" })], MessageSignedProtocol); return MessageSignedProtocol; })(); let PreKeyMessageProtocol = (() => { let PreKeyMessageProtocol = class PreKeyMessageProtocol extends BaseProtocol {}; __decorate([ProtobufProperty({ id: 1, type: "uint32", required: true })], PreKeyMessageProtocol.prototype, "registrationId", void 0); __decorate([ProtobufProperty({ id: 2, type: "uint32" })], PreKeyMessageProtocol.prototype, "preKeyId", void 0); __decorate([ProtobufProperty({ id: 3, type: "uint32", required: true })], PreKeyMessageProtocol.prototype, "preKeySignedId", void 0); __decorate([ProtobufProperty({ id: 4, converter: ECDHPublicKeyConverter, required: true })], PreKeyMessageProtocol.prototype, "baseKey", void 0); __decorate([ProtobufProperty({ id: 5, parser: IdentityProtocol, required: true })], PreKeyMessageProtocol.prototype, "identity", void 0); __decorate([ProtobufProperty({ id: 6, parser: MessageSignedProtocol, required: true })], PreKeyMessageProtocol.prototype, "signedMessage", void 0); PreKeyMessageProtocol = __decorate([ProtobufElement({ name: "PreKeyMessage" })], PreKeyMessageProtocol); return PreKeyMessageProtocol; })(); let PreKeyProtocol = (() => { let PreKeyProtocol = class PreKeyProtocol extends BaseProtocol {}; __decorate([ProtobufProperty({ id: 1, type: "uint32", required: true })], PreKeyProtocol.prototype, "id", void 0); __decorate([ProtobufProperty({ id: 2, converter: ECDHPublicKeyConverter, required: true })], PreKeyProtocol.prototype, "key", void 0); PreKeyProtocol = __decorate([ProtobufElement({ name: "PreKey" })], PreKeyProtocol); return PreKeyProtocol; })(); let PreKeySignedProtocol = (() => { let PreKeySignedProtocol = class PreKeySignedProtocol extends PreKeyProtocol { async sign(key) { this.signature = await Curve.sign(key, this.key.serialize()); } verify(key) { return Curve.verify(key, this.key.serialize(), this.signature); } }; __decorate([ProtobufProperty({ id: 3, converter: ArrayBufferConverter, required: true })], PreKeySignedProtocol.prototype, "signature", void 0); PreKeySignedProtocol = __decorate([ProtobufElement({ name: "PreKeySigned" })], PreKeySignedProtocol); return PreKeySignedProtocol; })(); let PreKeyBundleProtocol = (() => { let PreKeyBundleProtocol = class PreKeyBundleProtocol extends BaseProtocol {}; __decorate([ProtobufProperty({ id: 1, type: "uint32", required: true })], PreKeyBundleProtocol.prototype, "registrationId", void 0); __decorate([ProtobufProperty({ id: 2, parser: IdentityProtocol, required: true })], PreKeyBundleProtocol.prototype, "identity", void 0); __decorate([ProtobufProperty({ id: 3, parser: PreKeyProtocol })], PreKeyBundleProtocol.prototype, "preKey", void 0); __decorate([ProtobufProperty({ id: 4, parser: PreKeySignedProtocol, required: true })], P