From 0d0469d919cba3a1f91b5626dfe1bef50ac0d5f4 Mon Sep 17 00:00:00 2001 From: lesleyrs <19632758+lesleyrs@users.noreply.github.com> Date: Tue, 30 Jul 2024 00:49:46 +0200 Subject: [PATCH] fix --- src/public/LoginThread.js | 18873 ----------------- src/public/worker.js | 40296 ------------------------------------ 2 files changed, 59169 deletions(-) delete mode 100644 src/public/LoginThread.js delete mode 100644 src/public/worker.js diff --git a/src/public/LoginThread.js b/src/public/LoginThread.js deleted file mode 100644 index b0f05b2d..00000000 --- a/src/public/LoginThread.js +++ /dev/null @@ -1,18873 +0,0 @@ -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { - get: (a, b) => (typeof require !== "undefined" ? require : a)[b] -}) : x)(function(x) { - if (typeof require !== "undefined") return require.apply(this, arguments); - throw Error('Dynamic require of "' + x + '" is not supported'); -}); -var __commonJS = (cb, mod) => function __require2() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); - -// node_modules/node-forge/lib/forge.js -var require_forge = __commonJS({ - "node_modules/node-forge/lib/forge.js"(exports, module) { - module.exports = { - // default options - options: { - usePureJavaScript: false - } - }; - } -}); - -// node_modules/node-forge/lib/baseN.js -var require_baseN = __commonJS({ - "node_modules/node-forge/lib/baseN.js"(exports, module) { - var api = {}; - module.exports = api; - var _reverseAlphabets = {}; - api.encode = function(input, alphabet, maxline) { - if (typeof alphabet !== "string") { - throw new TypeError('"alphabet" must be a string.'); - } - if (maxline !== void 0 && typeof maxline !== "number") { - throw new TypeError('"maxline" must be a number.'); - } - var output = ""; - if (!(input instanceof Uint8Array)) { - output = _encodeWithByteBuffer(input, alphabet); - } else { - var i = 0; - var base = alphabet.length; - var first = alphabet.charAt(0); - var digits = [0]; - for (i = 0; i < input.length; ++i) { - for (var j = 0, carry = input[i]; j < digits.length; ++j) { - carry += digits[j] << 8; - digits[j] = carry % base; - carry = carry / base | 0; - } - while (carry > 0) { - digits.push(carry % base); - carry = carry / base | 0; - } - } - for (i = 0; input[i] === 0 && i < input.length - 1; ++i) { - output += first; - } - for (i = digits.length - 1; i >= 0; --i) { - output += alphabet[digits[i]]; - } - } - if (maxline) { - var regex = new RegExp(".{1," + maxline + "}", "g"); - output = output.match(regex).join("\r\n"); - } - return output; - }; - api.decode = function(input, alphabet) { - if (typeof input !== "string") { - throw new TypeError('"input" must be a string.'); - } - if (typeof alphabet !== "string") { - throw new TypeError('"alphabet" must be a string.'); - } - var table = _reverseAlphabets[alphabet]; - if (!table) { - table = _reverseAlphabets[alphabet] = []; - for (var i = 0; i < alphabet.length; ++i) { - table[alphabet.charCodeAt(i)] = i; - } - } - input = input.replace(/\s/g, ""); - var base = alphabet.length; - var first = alphabet.charAt(0); - var bytes = [0]; - for (var i = 0; i < input.length; i++) { - var value = table[input.charCodeAt(i)]; - if (value === void 0) { - return; - } - for (var j = 0, carry = value; j < bytes.length; ++j) { - carry += bytes[j] * base; - bytes[j] = carry & 255; - carry >>= 8; - } - while (carry > 0) { - bytes.push(carry & 255); - carry >>= 8; - } - } - for (var k = 0; input[k] === first && k < input.length - 1; ++k) { - bytes.push(0); - } - if (typeof Buffer !== "undefined") { - return Buffer.from(bytes.reverse()); - } - return new Uint8Array(bytes.reverse()); - }; - function _encodeWithByteBuffer(input, alphabet) { - var i = 0; - var base = alphabet.length; - var first = alphabet.charAt(0); - var digits = [0]; - for (i = 0; i < input.length(); ++i) { - for (var j = 0, carry = input.at(i); j < digits.length; ++j) { - carry += digits[j] << 8; - digits[j] = carry % base; - carry = carry / base | 0; - } - while (carry > 0) { - digits.push(carry % base); - carry = carry / base | 0; - } - } - var output = ""; - for (i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) { - output += first; - } - for (i = digits.length - 1; i >= 0; --i) { - output += alphabet[digits[i]]; - } - return output; - } - } -}); - -// node_modules/node-forge/lib/util.js -var require_util = __commonJS({ - "node_modules/node-forge/lib/util.js"(exports, module) { - var forge3 = require_forge(); - var baseN = require_baseN(); - var util = module.exports = forge3.util = forge3.util || {}; - (function() { - if (typeof process !== "undefined" && process.nextTick && !process.browser) { - util.nextTick = process.nextTick; - if (typeof setImmediate === "function") { - util.setImmediate = setImmediate; - } else { - util.setImmediate = util.nextTick; - } - return; - } - if (typeof setImmediate === "function") { - util.setImmediate = function() { - return setImmediate.apply(void 0, arguments); - }; - util.nextTick = function(callback) { - return setImmediate(callback); - }; - return; - } - util.setImmediate = function(callback) { - setTimeout(callback, 0); - }; - if (typeof window !== "undefined" && typeof window.postMessage === "function") { - let handler2 = function(event) { - if (event.source === window && event.data === msg) { - event.stopPropagation(); - var copy = callbacks.slice(); - callbacks.length = 0; - copy.forEach(function(callback) { - callback(); - }); - } - }; - var handler = handler2; - var msg = "forge.setImmediate"; - var callbacks = []; - util.setImmediate = function(callback) { - callbacks.push(callback); - if (callbacks.length === 1) { - window.postMessage(msg, "*"); - } - }; - window.addEventListener("message", handler2, true); - } - if (typeof MutationObserver !== "undefined") { - var now = Date.now(); - var attr = true; - var div = document.createElement("div"); - var callbacks = []; - new MutationObserver(function() { - var copy = callbacks.slice(); - callbacks.length = 0; - copy.forEach(function(callback) { - callback(); - }); - }).observe(div, { attributes: true }); - var oldSetImmediate = util.setImmediate; - util.setImmediate = function(callback) { - if (Date.now() - now > 15) { - now = Date.now(); - oldSetImmediate(callback); - } else { - callbacks.push(callback); - if (callbacks.length === 1) { - div.setAttribute("a", attr = !attr); - } - } - }; - } - util.nextTick = util.setImmediate; - })(); - util.isNodejs = typeof process !== "undefined" && process.versions && process.versions.node; - util.globalScope = function() { - if (util.isNodejs) { - return global; - } - return typeof self === "undefined" ? window : self; - }(); - util.isArray = Array.isArray || function(x) { - return Object.prototype.toString.call(x) === "[object Array]"; - }; - util.isArrayBuffer = function(x) { - return typeof ArrayBuffer !== "undefined" && x instanceof ArrayBuffer; - }; - util.isArrayBufferView = function(x) { - return x && util.isArrayBuffer(x.buffer) && x.byteLength !== void 0; - }; - function _checkBitsParam(n) { - if (!(n === 8 || n === 16 || n === 24 || n === 32)) { - throw new Error("Only 8, 16, 24, or 32 bits supported: " + n); - } - } - util.ByteBuffer = ByteStringBuffer; - function ByteStringBuffer(b) { - this.data = ""; - this.read = 0; - if (typeof b === "string") { - this.data = b; - } else if (util.isArrayBuffer(b) || util.isArrayBufferView(b)) { - if (typeof Buffer !== "undefined" && b instanceof Buffer) { - this.data = b.toString("binary"); - } else { - var arr = new Uint8Array(b); - try { - this.data = String.fromCharCode.apply(null, arr); - } catch (e) { - for (var i = 0; i < arr.length; ++i) { - this.putByte(arr[i]); - } - } - } - } else if (b instanceof ByteStringBuffer || typeof b === "object" && typeof b.data === "string" && typeof b.read === "number") { - this.data = b.data; - this.read = b.read; - } - this._constructedStringLength = 0; - } - util.ByteStringBuffer = ByteStringBuffer; - var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; - util.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { - this._constructedStringLength += x; - if (this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { - this.data.substr(0, 1); - this._constructedStringLength = 0; - } - }; - util.ByteStringBuffer.prototype.length = function() { - return this.data.length - this.read; - }; - util.ByteStringBuffer.prototype.isEmpty = function() { - return this.length() <= 0; - }; - util.ByteStringBuffer.prototype.putByte = function(b) { - return this.putBytes(String.fromCharCode(b)); - }; - util.ByteStringBuffer.prototype.fillWithByte = function(b, n) { - b = String.fromCharCode(b); - var d = this.data; - while (n > 0) { - if (n & 1) { - d += b; - } - n >>>= 1; - if (n > 0) { - b += b; - } - } - this.data = d; - this._optimizeConstructedString(n); - return this; - }; - util.ByteStringBuffer.prototype.putBytes = function(bytes) { - this.data += bytes; - this._optimizeConstructedString(bytes.length); - return this; - }; - util.ByteStringBuffer.prototype.putString = function(str) { - return this.putBytes(util.encodeUtf8(str)); - }; - util.ByteStringBuffer.prototype.putInt16 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt24 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt32 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 24 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt16Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt24Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i >> 16 & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt32Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 24 & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt = function(i, n) { - _checkBitsParam(n); - var bytes = ""; - do { - n -= 8; - bytes += String.fromCharCode(i >> n & 255); - } while (n > 0); - return this.putBytes(bytes); - }; - util.ByteStringBuffer.prototype.putSignedInt = function(i, n) { - if (i < 0) { - i += 2 << n - 1; - } - return this.putInt(i, n); - }; - util.ByteStringBuffer.prototype.putBuffer = function(buffer) { - return this.putBytes(buffer.getBytes()); - }; - util.ByteStringBuffer.prototype.getByte = function() { - return this.data.charCodeAt(this.read++); - }; - util.ByteStringBuffer.prototype.getInt16 = function() { - var rval = this.data.charCodeAt(this.read) << 8 ^ this.data.charCodeAt(this.read + 1); - this.read += 2; - return rval; - }; - util.ByteStringBuffer.prototype.getInt24 = function() { - var rval = this.data.charCodeAt(this.read) << 16 ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2); - this.read += 3; - return rval; - }; - util.ByteStringBuffer.prototype.getInt32 = function() { - var rval = this.data.charCodeAt(this.read) << 24 ^ this.data.charCodeAt(this.read + 1) << 16 ^ this.data.charCodeAt(this.read + 2) << 8 ^ this.data.charCodeAt(this.read + 3); - this.read += 4; - return rval; - }; - util.ByteStringBuffer.prototype.getInt16Le = function() { - var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8; - this.read += 2; - return rval; - }; - util.ByteStringBuffer.prototype.getInt24Le = function() { - var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16; - this.read += 3; - return rval; - }; - util.ByteStringBuffer.prototype.getInt32Le = function() { - var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16 ^ this.data.charCodeAt(this.read + 3) << 24; - this.read += 4; - return rval; - }; - util.ByteStringBuffer.prototype.getInt = function(n) { - _checkBitsParam(n); - var rval = 0; - do { - rval = (rval << 8) + this.data.charCodeAt(this.read++); - n -= 8; - } while (n > 0); - return rval; - }; - util.ByteStringBuffer.prototype.getSignedInt = function(n) { - var x = this.getInt(n); - var max = 2 << n - 2; - if (x >= max) { - x -= max << 1; - } - return x; - }; - util.ByteStringBuffer.prototype.getBytes = function(count) { - var rval; - if (count) { - count = Math.min(this.length(), count); - rval = this.data.slice(this.read, this.read + count); - this.read += count; - } else if (count === 0) { - rval = ""; - } else { - rval = this.read === 0 ? this.data : this.data.slice(this.read); - this.clear(); - } - return rval; - }; - util.ByteStringBuffer.prototype.bytes = function(count) { - return typeof count === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count); - }; - util.ByteStringBuffer.prototype.at = function(i) { - return this.data.charCodeAt(this.read + i); - }; - util.ByteStringBuffer.prototype.setAt = function(i, b) { - this.data = this.data.substr(0, this.read + i) + String.fromCharCode(b) + this.data.substr(this.read + i + 1); - return this; - }; - util.ByteStringBuffer.prototype.last = function() { - return this.data.charCodeAt(this.data.length - 1); - }; - util.ByteStringBuffer.prototype.copy = function() { - var c = util.createBuffer(this.data); - c.read = this.read; - return c; - }; - util.ByteStringBuffer.prototype.compact = function() { - if (this.read > 0) { - this.data = this.data.slice(this.read); - this.read = 0; - } - return this; - }; - util.ByteStringBuffer.prototype.clear = function() { - this.data = ""; - this.read = 0; - return this; - }; - util.ByteStringBuffer.prototype.truncate = function(count) { - var len = Math.max(0, this.length() - count); - this.data = this.data.substr(this.read, len); - this.read = 0; - return this; - }; - util.ByteStringBuffer.prototype.toHex = function() { - var rval = ""; - for (var i = this.read; i < this.data.length; ++i) { - var b = this.data.charCodeAt(i); - if (b < 16) { - rval += "0"; - } - rval += b.toString(16); - } - return rval; - }; - util.ByteStringBuffer.prototype.toString = function() { - return util.decodeUtf8(this.bytes()); - }; - function DataBuffer(b, options) { - options = options || {}; - this.read = options.readOffset || 0; - this.growSize = options.growSize || 1024; - var isArrayBuffer = util.isArrayBuffer(b); - var isArrayBufferView = util.isArrayBufferView(b); - if (isArrayBuffer || isArrayBufferView) { - if (isArrayBuffer) { - this.data = new DataView(b); - } else { - this.data = new DataView(b.buffer, b.byteOffset, b.byteLength); - } - this.write = "writeOffset" in options ? options.writeOffset : this.data.byteLength; - return; - } - this.data = new DataView(new ArrayBuffer(0)); - this.write = 0; - if (b !== null && b !== void 0) { - this.putBytes(b); - } - if ("writeOffset" in options) { - this.write = options.writeOffset; - } - } - util.DataBuffer = DataBuffer; - util.DataBuffer.prototype.length = function() { - return this.write - this.read; - }; - util.DataBuffer.prototype.isEmpty = function() { - return this.length() <= 0; - }; - util.DataBuffer.prototype.accommodate = function(amount, growSize) { - if (this.length() >= amount) { - return this; - } - growSize = Math.max(growSize || this.growSize, amount); - var src = new Uint8Array( - this.data.buffer, - this.data.byteOffset, - this.data.byteLength - ); - var dst = new Uint8Array(this.length() + growSize); - dst.set(src); - this.data = new DataView(dst.buffer); - return this; - }; - util.DataBuffer.prototype.putByte = function(b) { - this.accommodate(1); - this.data.setUint8(this.write++, b); - return this; - }; - util.DataBuffer.prototype.fillWithByte = function(b, n) { - this.accommodate(n); - for (var i = 0; i < n; ++i) { - this.data.setUint8(b); - } - return this; - }; - util.DataBuffer.prototype.putBytes = function(bytes, encoding) { - if (util.isArrayBufferView(bytes)) { - var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); - var len = src.byteLength - src.byteOffset; - this.accommodate(len); - var dst = new Uint8Array(this.data.buffer, this.write); - dst.set(src); - this.write += len; - return this; - } - if (util.isArrayBuffer(bytes)) { - var src = new Uint8Array(bytes); - this.accommodate(src.byteLength); - var dst = new Uint8Array(this.data.buffer); - dst.set(src, this.write); - this.write += src.byteLength; - return this; - } - if (bytes instanceof util.DataBuffer || typeof bytes === "object" && typeof bytes.read === "number" && typeof bytes.write === "number" && util.isArrayBufferView(bytes.data)) { - var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); - this.accommodate(src.byteLength); - var dst = new Uint8Array(bytes.data.byteLength, this.write); - dst.set(src); - this.write += src.byteLength; - return this; - } - if (bytes instanceof util.ByteStringBuffer) { - bytes = bytes.data; - encoding = "binary"; - } - encoding = encoding || "binary"; - if (typeof bytes === "string") { - var view; - if (encoding === "hex") { - this.accommodate(Math.ceil(bytes.length / 2)); - view = new Uint8Array(this.data.buffer, this.write); - this.write += util.binary.hex.decode(bytes, view, this.write); - return this; - } - if (encoding === "base64") { - this.accommodate(Math.ceil(bytes.length / 4) * 3); - view = new Uint8Array(this.data.buffer, this.write); - this.write += util.binary.base64.decode(bytes, view, this.write); - return this; - } - if (encoding === "utf8") { - bytes = util.encodeUtf8(bytes); - encoding = "binary"; - } - if (encoding === "binary" || encoding === "raw") { - this.accommodate(bytes.length); - view = new Uint8Array(this.data.buffer, this.write); - this.write += util.binary.raw.decode(view); - return this; - } - if (encoding === "utf16") { - this.accommodate(bytes.length * 2); - view = new Uint16Array(this.data.buffer, this.write); - this.write += util.text.utf16.encode(view); - return this; - } - throw new Error("Invalid encoding: " + encoding); - } - throw Error("Invalid parameter: " + bytes); - }; - util.DataBuffer.prototype.putBuffer = function(buffer) { - this.putBytes(buffer); - buffer.clear(); - return this; - }; - util.DataBuffer.prototype.putString = function(str) { - return this.putBytes(str, "utf16"); - }; - util.DataBuffer.prototype.putInt16 = function(i) { - this.accommodate(2); - this.data.setInt16(this.write, i); - this.write += 2; - return this; - }; - util.DataBuffer.prototype.putInt24 = function(i) { - this.accommodate(3); - this.data.setInt16(this.write, i >> 8 & 65535); - this.data.setInt8(this.write, i >> 16 & 255); - this.write += 3; - return this; - }; - util.DataBuffer.prototype.putInt32 = function(i) { - this.accommodate(4); - this.data.setInt32(this.write, i); - this.write += 4; - return this; - }; - util.DataBuffer.prototype.putInt16Le = function(i) { - this.accommodate(2); - this.data.setInt16(this.write, i, true); - this.write += 2; - return this; - }; - util.DataBuffer.prototype.putInt24Le = function(i) { - this.accommodate(3); - this.data.setInt8(this.write, i >> 16 & 255); - this.data.setInt16(this.write, i >> 8 & 65535, true); - this.write += 3; - return this; - }; - util.DataBuffer.prototype.putInt32Le = function(i) { - this.accommodate(4); - this.data.setInt32(this.write, i, true); - this.write += 4; - return this; - }; - util.DataBuffer.prototype.putInt = function(i, n) { - _checkBitsParam(n); - this.accommodate(n / 8); - do { - n -= 8; - this.data.setInt8(this.write++, i >> n & 255); - } while (n > 0); - return this; - }; - util.DataBuffer.prototype.putSignedInt = function(i, n) { - _checkBitsParam(n); - this.accommodate(n / 8); - if (i < 0) { - i += 2 << n - 1; - } - return this.putInt(i, n); - }; - util.DataBuffer.prototype.getByte = function() { - return this.data.getInt8(this.read++); - }; - util.DataBuffer.prototype.getInt16 = function() { - var rval = this.data.getInt16(this.read); - this.read += 2; - return rval; - }; - util.DataBuffer.prototype.getInt24 = function() { - var rval = this.data.getInt16(this.read) << 8 ^ this.data.getInt8(this.read + 2); - this.read += 3; - return rval; - }; - util.DataBuffer.prototype.getInt32 = function() { - var rval = this.data.getInt32(this.read); - this.read += 4; - return rval; - }; - util.DataBuffer.prototype.getInt16Le = function() { - var rval = this.data.getInt16(this.read, true); - this.read += 2; - return rval; - }; - util.DataBuffer.prototype.getInt24Le = function() { - var rval = this.data.getInt8(this.read) ^ this.data.getInt16(this.read + 1, true) << 8; - this.read += 3; - return rval; - }; - util.DataBuffer.prototype.getInt32Le = function() { - var rval = this.data.getInt32(this.read, true); - this.read += 4; - return rval; - }; - util.DataBuffer.prototype.getInt = function(n) { - _checkBitsParam(n); - var rval = 0; - do { - rval = (rval << 8) + this.data.getInt8(this.read++); - n -= 8; - } while (n > 0); - return rval; - }; - util.DataBuffer.prototype.getSignedInt = function(n) { - var x = this.getInt(n); - var max = 2 << n - 2; - if (x >= max) { - x -= max << 1; - } - return x; - }; - util.DataBuffer.prototype.getBytes = function(count) { - var rval; - if (count) { - count = Math.min(this.length(), count); - rval = this.data.slice(this.read, this.read + count); - this.read += count; - } else if (count === 0) { - rval = ""; - } else { - rval = this.read === 0 ? this.data : this.data.slice(this.read); - this.clear(); - } - return rval; - }; - util.DataBuffer.prototype.bytes = function(count) { - return typeof count === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count); - }; - util.DataBuffer.prototype.at = function(i) { - return this.data.getUint8(this.read + i); - }; - util.DataBuffer.prototype.setAt = function(i, b) { - this.data.setUint8(i, b); - return this; - }; - util.DataBuffer.prototype.last = function() { - return this.data.getUint8(this.write - 1); - }; - util.DataBuffer.prototype.copy = function() { - return new util.DataBuffer(this); - }; - util.DataBuffer.prototype.compact = function() { - if (this.read > 0) { - var src = new Uint8Array(this.data.buffer, this.read); - var dst = new Uint8Array(src.byteLength); - dst.set(src); - this.data = new DataView(dst); - this.write -= this.read; - this.read = 0; - } - return this; - }; - util.DataBuffer.prototype.clear = function() { - this.data = new DataView(new ArrayBuffer(0)); - this.read = this.write = 0; - return this; - }; - util.DataBuffer.prototype.truncate = function(count) { - this.write = Math.max(0, this.length() - count); - this.read = Math.min(this.read, this.write); - return this; - }; - util.DataBuffer.prototype.toHex = function() { - var rval = ""; - for (var i = this.read; i < this.data.byteLength; ++i) { - var b = this.data.getUint8(i); - if (b < 16) { - rval += "0"; - } - rval += b.toString(16); - } - return rval; - }; - util.DataBuffer.prototype.toString = function(encoding) { - var view = new Uint8Array(this.data, this.read, this.length()); - encoding = encoding || "utf8"; - if (encoding === "binary" || encoding === "raw") { - return util.binary.raw.encode(view); - } - if (encoding === "hex") { - return util.binary.hex.encode(view); - } - if (encoding === "base64") { - return util.binary.base64.encode(view); - } - if (encoding === "utf8") { - return util.text.utf8.decode(view); - } - if (encoding === "utf16") { - return util.text.utf16.decode(view); - } - throw new Error("Invalid encoding: " + encoding); - }; - util.createBuffer = function(input, encoding) { - encoding = encoding || "raw"; - if (input !== void 0 && encoding === "utf8") { - input = util.encodeUtf8(input); - } - return new util.ByteBuffer(input); - }; - util.fillString = function(c, n) { - var s = ""; - while (n > 0) { - if (n & 1) { - s += c; - } - n >>>= 1; - if (n > 0) { - c += c; - } - } - return s; - }; - util.xorBytes = function(s1, s2, n) { - var s3 = ""; - var b = ""; - var t = ""; - var i = 0; - var c = 0; - for (; n > 0; --n, ++i) { - b = s1.charCodeAt(i) ^ s2.charCodeAt(i); - if (c >= 10) { - s3 += t; - t = ""; - c = 0; - } - t += String.fromCharCode(b); - ++c; - } - s3 += t; - return s3; - }; - util.hexToBytes = function(hex) { - var rval = ""; - var i = 0; - if (hex.length & true) { - i = 1; - rval += String.fromCharCode(parseInt(hex[0], 16)); - } - for (; i < hex.length; i += 2) { - rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); - } - return rval; - }; - util.bytesToHex = function(bytes) { - return util.createBuffer(bytes).toHex(); - }; - util.int32ToBytes = function(i) { - return String.fromCharCode(i >> 24 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255); - }; - var _base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - var _base64Idx = [ - /*43 -43 = 0*/ - /*'+', 1, 2, 3,'/' */ - 62, - -1, - -1, - -1, - 63, - /*'0','1','2','3','4','5','6','7','8','9' */ - 52, - 53, - 54, - 55, - 56, - 57, - 58, - 59, - 60, - 61, - /*15, 16, 17,'=', 19, 20, 21 */ - -1, - -1, - -1, - 64, - -1, - -1, - -1, - /*65 - 43 = 22*/ - /*'A','B','C','D','E','F','G','H','I','J','K','L','M', */ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - /*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */ - 13, - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, - 24, - 25, - /*91 - 43 = 48 */ - /*48, 49, 50, 51, 52, 53 */ - -1, - -1, - -1, - -1, - -1, - -1, - /*97 - 43 = 54*/ - /*'a','b','c','d','e','f','g','h','i','j','k','l','m' */ - 26, - 27, - 28, - 29, - 30, - 31, - 32, - 33, - 34, - 35, - 36, - 37, - 38, - /*'n','o','p','q','r','s','t','u','v','w','x','y','z' */ - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 46, - 47, - 48, - 49, - 50, - 51 - ]; - var _base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; - util.encode64 = function(input, maxline) { - var line = ""; - var output = ""; - var chr1, chr2, chr3; - var i = 0; - while (i < input.length) { - chr1 = input.charCodeAt(i++); - chr2 = input.charCodeAt(i++); - chr3 = input.charCodeAt(i++); - line += _base64.charAt(chr1 >> 2); - line += _base64.charAt((chr1 & 3) << 4 | chr2 >> 4); - if (isNaN(chr2)) { - line += "=="; - } else { - line += _base64.charAt((chr2 & 15) << 2 | chr3 >> 6); - line += isNaN(chr3) ? "=" : _base64.charAt(chr3 & 63); - } - if (maxline && line.length > maxline) { - output += line.substr(0, maxline) + "\r\n"; - line = line.substr(maxline); - } - } - output += line; - return output; - }; - util.decode64 = function(input) { - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); - var output = ""; - var enc1, enc2, enc3, enc4; - var i = 0; - while (i < input.length) { - enc1 = _base64Idx[input.charCodeAt(i++) - 43]; - enc2 = _base64Idx[input.charCodeAt(i++) - 43]; - enc3 = _base64Idx[input.charCodeAt(i++) - 43]; - enc4 = _base64Idx[input.charCodeAt(i++) - 43]; - output += String.fromCharCode(enc1 << 2 | enc2 >> 4); - if (enc3 !== 64) { - output += String.fromCharCode((enc2 & 15) << 4 | enc3 >> 2); - if (enc4 !== 64) { - output += String.fromCharCode((enc3 & 3) << 6 | enc4); - } - } - } - return output; - }; - util.encodeUtf8 = function(str) { - return unescape(encodeURIComponent(str)); - }; - util.decodeUtf8 = function(str) { - return decodeURIComponent(escape(str)); - }; - util.binary = { - raw: {}, - hex: {}, - base64: {}, - base58: {}, - baseN: { - encode: baseN.encode, - decode: baseN.decode - } - }; - util.binary.raw.encode = function(bytes) { - return String.fromCharCode.apply(null, bytes); - }; - util.binary.raw.decode = function(str, output, offset) { - var out = output; - if (!out) { - out = new Uint8Array(str.length); - } - offset = offset || 0; - var j = offset; - for (var i = 0; i < str.length; ++i) { - out[j++] = str.charCodeAt(i); - } - return output ? j - offset : out; - }; - util.binary.hex.encode = util.bytesToHex; - util.binary.hex.decode = function(hex, output, offset) { - var out = output; - if (!out) { - out = new Uint8Array(Math.ceil(hex.length / 2)); - } - offset = offset || 0; - var i = 0, j = offset; - if (hex.length & 1) { - i = 1; - out[j++] = parseInt(hex[0], 16); - } - for (; i < hex.length; i += 2) { - out[j++] = parseInt(hex.substr(i, 2), 16); - } - return output ? j - offset : out; - }; - util.binary.base64.encode = function(input, maxline) { - var line = ""; - var output = ""; - var chr1, chr2, chr3; - var i = 0; - while (i < input.byteLength) { - chr1 = input[i++]; - chr2 = input[i++]; - chr3 = input[i++]; - line += _base64.charAt(chr1 >> 2); - line += _base64.charAt((chr1 & 3) << 4 | chr2 >> 4); - if (isNaN(chr2)) { - line += "=="; - } else { - line += _base64.charAt((chr2 & 15) << 2 | chr3 >> 6); - line += isNaN(chr3) ? "=" : _base64.charAt(chr3 & 63); - } - if (maxline && line.length > maxline) { - output += line.substr(0, maxline) + "\r\n"; - line = line.substr(maxline); - } - } - output += line; - return output; - }; - util.binary.base64.decode = function(input, output, offset) { - var out = output; - if (!out) { - out = new Uint8Array(Math.ceil(input.length / 4) * 3); - } - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); - offset = offset || 0; - var enc1, enc2, enc3, enc4; - var i = 0, j = offset; - while (i < input.length) { - enc1 = _base64Idx[input.charCodeAt(i++) - 43]; - enc2 = _base64Idx[input.charCodeAt(i++) - 43]; - enc3 = _base64Idx[input.charCodeAt(i++) - 43]; - enc4 = _base64Idx[input.charCodeAt(i++) - 43]; - out[j++] = enc1 << 2 | enc2 >> 4; - if (enc3 !== 64) { - out[j++] = (enc2 & 15) << 4 | enc3 >> 2; - if (enc4 !== 64) { - out[j++] = (enc3 & 3) << 6 | enc4; - } - } - } - return output ? j - offset : out.subarray(0, j); - }; - util.binary.base58.encode = function(input, maxline) { - return util.binary.baseN.encode(input, _base58, maxline); - }; - util.binary.base58.decode = function(input, maxline) { - return util.binary.baseN.decode(input, _base58, maxline); - }; - util.text = { - utf8: {}, - utf16: {} - }; - util.text.utf8.encode = function(str, output, offset) { - str = util.encodeUtf8(str); - var out = output; - if (!out) { - out = new Uint8Array(str.length); - } - offset = offset || 0; - var j = offset; - for (var i = 0; i < str.length; ++i) { - out[j++] = str.charCodeAt(i); - } - return output ? j - offset : out; - }; - util.text.utf8.decode = function(bytes) { - return util.decodeUtf8(String.fromCharCode.apply(null, bytes)); - }; - util.text.utf16.encode = function(str, output, offset) { - var out = output; - if (!out) { - out = new Uint8Array(str.length * 2); - } - var view = new Uint16Array(out.buffer); - offset = offset || 0; - var j = offset; - var k = offset; - for (var i = 0; i < str.length; ++i) { - view[k++] = str.charCodeAt(i); - j += 2; - } - return output ? j - offset : out; - }; - util.text.utf16.decode = function(bytes) { - return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); - }; - util.deflate = function(api, bytes, raw) { - bytes = util.decode64(api.deflate(util.encode64(bytes)).rval); - if (raw) { - var start = 2; - var flg = bytes.charCodeAt(1); - if (flg & 32) { - start = 6; - } - bytes = bytes.substring(start, bytes.length - 4); - } - return bytes; - }; - util.inflate = function(api, bytes, raw) { - var rval = api.inflate(util.encode64(bytes)).rval; - return rval === null ? null : util.decode64(rval); - }; - var _setStorageObject = function(api, id, obj) { - if (!api) { - throw new Error("WebStorage not available."); - } - var rval; - if (obj === null) { - rval = api.removeItem(id); - } else { - obj = util.encode64(JSON.stringify(obj)); - rval = api.setItem(id, obj); - } - if (typeof rval !== "undefined" && rval.rval !== true) { - var error = new Error(rval.error.message); - error.id = rval.error.id; - error.name = rval.error.name; - throw error; - } - }; - var _getStorageObject = function(api, id) { - if (!api) { - throw new Error("WebStorage not available."); - } - var rval = api.getItem(id); - if (api.init) { - if (rval.rval === null) { - if (rval.error) { - var error = new Error(rval.error.message); - error.id = rval.error.id; - error.name = rval.error.name; - throw error; - } - rval = null; - } else { - rval = rval.rval; - } - } - if (rval !== null) { - rval = JSON.parse(util.decode64(rval)); - } - return rval; - }; - var _setItem = function(api, id, key, data) { - var obj = _getStorageObject(api, id); - if (obj === null) { - obj = {}; - } - obj[key] = data; - _setStorageObject(api, id, obj); - }; - var _getItem = function(api, id, key) { - var rval = _getStorageObject(api, id); - if (rval !== null) { - rval = key in rval ? rval[key] : null; - } - return rval; - }; - var _removeItem = function(api, id, key) { - var obj = _getStorageObject(api, id); - if (obj !== null && key in obj) { - delete obj[key]; - var empty = true; - for (var prop in obj) { - empty = false; - break; - } - if (empty) { - obj = null; - } - _setStorageObject(api, id, obj); - } - }; - var _clearItems = function(api, id) { - _setStorageObject(api, id, null); - }; - var _callStorageFunction = function(func, args, location) { - var rval = null; - if (typeof location === "undefined") { - location = ["web", "flash"]; - } - var type; - var done = false; - var exception = null; - for (var idx in location) { - type = location[idx]; - try { - if (type === "flash" || type === "both") { - if (args[0] === null) { - throw new Error("Flash local storage not available."); - } - rval = func.apply(this, args); - done = type === "flash"; - } - if (type === "web" || type === "both") { - args[0] = localStorage; - rval = func.apply(this, args); - done = true; - } - } catch (ex) { - exception = ex; - } - if (done) { - break; - } - } - if (!done) { - throw exception; - } - return rval; - }; - util.setItem = function(api, id, key, data, location) { - _callStorageFunction(_setItem, arguments, location); - }; - util.getItem = function(api, id, key, location) { - return _callStorageFunction(_getItem, arguments, location); - }; - util.removeItem = function(api, id, key, location) { - _callStorageFunction(_removeItem, arguments, location); - }; - util.clearItems = function(api, id, location) { - _callStorageFunction(_clearItems, arguments, location); - }; - util.isEmpty = function(obj) { - for (var prop in obj) { - if (obj.hasOwnProperty(prop)) { - return false; - } - } - return true; - }; - util.format = function(format) { - var re = /%./g; - var match; - var part; - var argi = 0; - var parts = []; - var last = 0; - while (match = re.exec(format)) { - part = format.substring(last, re.lastIndex - 2); - if (part.length > 0) { - parts.push(part); - } - last = re.lastIndex; - var code = match[0][1]; - switch (code) { - case "s": - case "o": - if (argi < arguments.length) { - parts.push(arguments[argi++ + 1]); - } else { - parts.push(""); - } - break; - case "%": - parts.push("%"); - break; - default: - parts.push("<%" + code + "?>"); - } - } - parts.push(format.substring(last)); - return parts.join(""); - }; - util.formatNumber = function(number, decimals, dec_point, thousands_sep) { - var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; - var d = dec_point === void 0 ? "," : dec_point; - var t = thousands_sep === void 0 ? "." : thousands_sep, s = n < 0 ? "-" : ""; - var i = parseInt(n = Math.abs(+n || 0).toFixed(c), 10) + ""; - var j = i.length > 3 ? i.length % 3 : 0; - return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); - }; - util.formatSize = function(size) { - if (size >= 1073741824) { - size = util.formatNumber(size / 1073741824, 2, ".", "") + " GiB"; - } else if (size >= 1048576) { - size = util.formatNumber(size / 1048576, 2, ".", "") + " MiB"; - } else if (size >= 1024) { - size = util.formatNumber(size / 1024, 0) + " KiB"; - } else { - size = util.formatNumber(size, 0) + " bytes"; - } - return size; - }; - util.bytesFromIP = function(ip) { - if (ip.indexOf(".") !== -1) { - return util.bytesFromIPv4(ip); - } - if (ip.indexOf(":") !== -1) { - return util.bytesFromIPv6(ip); - } - return null; - }; - util.bytesFromIPv4 = function(ip) { - ip = ip.split("."); - if (ip.length !== 4) { - return null; - } - var b = util.createBuffer(); - for (var i = 0; i < ip.length; ++i) { - var num = parseInt(ip[i], 10); - if (isNaN(num)) { - return null; - } - b.putByte(num); - } - return b.getBytes(); - }; - util.bytesFromIPv6 = function(ip) { - var blanks = 0; - ip = ip.split(":").filter(function(e) { - if (e.length === 0) ++blanks; - return true; - }); - var zeros = (8 - ip.length + blanks) * 2; - var b = util.createBuffer(); - for (var i = 0; i < 8; ++i) { - if (!ip[i] || ip[i].length === 0) { - b.fillWithByte(0, zeros); - zeros = 0; - continue; - } - var bytes = util.hexToBytes(ip[i]); - if (bytes.length < 2) { - b.putByte(0); - } - b.putBytes(bytes); - } - return b.getBytes(); - }; - util.bytesToIP = function(bytes) { - if (bytes.length === 4) { - return util.bytesToIPv4(bytes); - } - if (bytes.length === 16) { - return util.bytesToIPv6(bytes); - } - return null; - }; - util.bytesToIPv4 = function(bytes) { - if (bytes.length !== 4) { - return null; - } - var ip = []; - for (var i = 0; i < bytes.length; ++i) { - ip.push(bytes.charCodeAt(i)); - } - return ip.join("."); - }; - util.bytesToIPv6 = function(bytes) { - if (bytes.length !== 16) { - return null; - } - var ip = []; - var zeroGroups = []; - var zeroMaxGroup = 0; - for (var i = 0; i < bytes.length; i += 2) { - var hex = util.bytesToHex(bytes[i] + bytes[i + 1]); - while (hex[0] === "0" && hex !== "0") { - hex = hex.substr(1); - } - if (hex === "0") { - var last = zeroGroups[zeroGroups.length - 1]; - var idx = ip.length; - if (!last || idx !== last.end + 1) { - zeroGroups.push({ start: idx, end: idx }); - } else { - last.end = idx; - if (last.end - last.start > zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start) { - zeroMaxGroup = zeroGroups.length - 1; - } - } - } - ip.push(hex); - } - if (zeroGroups.length > 0) { - var group = zeroGroups[zeroMaxGroup]; - if (group.end - group.start > 0) { - ip.splice(group.start, group.end - group.start + 1, ""); - if (group.start === 0) { - ip.unshift(""); - } - if (group.end === 7) { - ip.push(""); - } - } - } - return ip.join(":"); - }; - util.estimateCores = function(options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; - } - options = options || {}; - if ("cores" in util && !options.update) { - return callback(null, util.cores); - } - if (typeof navigator !== "undefined" && "hardwareConcurrency" in navigator && navigator.hardwareConcurrency > 0) { - util.cores = navigator.hardwareConcurrency; - return callback(null, util.cores); - } - if (typeof Worker === "undefined") { - util.cores = 1; - return callback(null, util.cores); - } - if (typeof Blob === "undefined") { - util.cores = 2; - return callback(null, util.cores); - } - var blobUrl = URL.createObjectURL(new Blob([ - "(", - function() { - self.addEventListener("message", function(e) { - var st = Date.now(); - var et = st + 4; - while (Date.now() < et) ; - self.postMessage({ st, et }); - }); - }.toString(), - ")()" - ], { type: "application/javascript" })); - sample([], 5, 16); - function sample(max, samples, numWorkers) { - if (samples === 0) { - var avg = Math.floor(max.reduce(function(avg2, x) { - return avg2 + x; - }, 0) / max.length); - util.cores = Math.max(1, avg); - URL.revokeObjectURL(blobUrl); - return callback(null, util.cores); - } - map(numWorkers, function(err, results) { - max.push(reduce(numWorkers, results)); - sample(max, samples - 1, numWorkers); - }); - } - function map(numWorkers, callback2) { - var workers = []; - var results = []; - for (var i = 0; i < numWorkers; ++i) { - var worker = new Worker(blobUrl); - worker.addEventListener("message", function(e) { - results.push(e.data); - if (results.length === numWorkers) { - for (var i2 = 0; i2 < numWorkers; ++i2) { - workers[i2].terminate(); - } - callback2(null, results); - } - }); - workers.push(worker); - } - for (var i = 0; i < numWorkers; ++i) { - workers[i].postMessage(i); - } - } - function reduce(numWorkers, results) { - var overlaps = []; - for (var n = 0; n < numWorkers; ++n) { - var r1 = results[n]; - var overlap = overlaps[n] = []; - for (var i = 0; i < numWorkers; ++i) { - if (n === i) { - continue; - } - var r2 = results[i]; - if (r1.st > r2.st && r1.st < r2.et || r2.st > r1.st && r2.st < r1.et) { - overlap.push(i); - } - } - } - return overlaps.reduce(function(max, overlap2) { - return Math.max(max, overlap2.length); - }, 0); - } - }; - } -}); - -// node_modules/node-forge/lib/cipher.js -var require_cipher = __commonJS({ - "node_modules/node-forge/lib/cipher.js"(exports, module) { - var forge3 = require_forge(); - require_util(); - module.exports = forge3.cipher = forge3.cipher || {}; - forge3.cipher.algorithms = forge3.cipher.algorithms || {}; - forge3.cipher.createCipher = function(algorithm, key) { - var api = algorithm; - if (typeof api === "string") { - api = forge3.cipher.getAlgorithm(api); - if (api) { - api = api(); - } - } - if (!api) { - throw new Error("Unsupported algorithm: " + algorithm); - } - return new forge3.cipher.BlockCipher({ - algorithm: api, - key, - decrypt: false - }); - }; - forge3.cipher.createDecipher = function(algorithm, key) { - var api = algorithm; - if (typeof api === "string") { - api = forge3.cipher.getAlgorithm(api); - if (api) { - api = api(); - } - } - if (!api) { - throw new Error("Unsupported algorithm: " + algorithm); - } - return new forge3.cipher.BlockCipher({ - algorithm: api, - key, - decrypt: true - }); - }; - forge3.cipher.registerAlgorithm = function(name, algorithm) { - name = name.toUpperCase(); - forge3.cipher.algorithms[name] = algorithm; - }; - forge3.cipher.getAlgorithm = function(name) { - name = name.toUpperCase(); - if (name in forge3.cipher.algorithms) { - return forge3.cipher.algorithms[name]; - } - return null; - }; - var BlockCipher = forge3.cipher.BlockCipher = function(options) { - this.algorithm = options.algorithm; - this.mode = this.algorithm.mode; - this.blockSize = this.mode.blockSize; - this._finish = false; - this._input = null; - this.output = null; - this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt; - this._decrypt = options.decrypt; - this.algorithm.initialize(options); - }; - BlockCipher.prototype.start = function(options) { - options = options || {}; - var opts = {}; - for (var key in options) { - opts[key] = options[key]; - } - opts.decrypt = this._decrypt; - this._finish = false; - this._input = forge3.util.createBuffer(); - this.output = options.output || forge3.util.createBuffer(); - this.mode.start(opts); - }; - BlockCipher.prototype.update = function(input) { - if (input) { - this._input.putBuffer(input); - } - while (!this._op.call(this.mode, this._input, this.output, this._finish) && !this._finish) { - } - this._input.compact(); - }; - BlockCipher.prototype.finish = function(pad) { - if (pad && (this.mode.name === "ECB" || this.mode.name === "CBC")) { - this.mode.pad = function(input) { - return pad(this.blockSize, input, false); - }; - this.mode.unpad = function(output) { - return pad(this.blockSize, output, true); - }; - } - var options = {}; - options.decrypt = this._decrypt; - options.overflow = this._input.length() % this.blockSize; - if (!this._decrypt && this.mode.pad) { - if (!this.mode.pad(this._input, options)) { - return false; - } - } - this._finish = true; - this.update(); - if (this._decrypt && this.mode.unpad) { - if (!this.mode.unpad(this.output, options)) { - return false; - } - } - if (this.mode.afterFinish) { - if (!this.mode.afterFinish(this.output, options)) { - return false; - } - } - return true; - }; - } -}); - -// node_modules/node-forge/lib/cipherModes.js -var require_cipherModes = __commonJS({ - "node_modules/node-forge/lib/cipherModes.js"(exports, module) { - var forge3 = require_forge(); - require_util(); - forge3.cipher = forge3.cipher || {}; - var modes = module.exports = forge3.cipher.modes = forge3.cipher.modes || {}; - modes.ecb = function(options) { - options = options || {}; - this.name = "ECB"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); - }; - modes.ecb.prototype.start = function(options) { - }; - modes.ecb.prototype.encrypt = function(input, output, finish) { - if (input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } - this.cipher.encrypt(this._inBlock, this._outBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); - } - }; - modes.ecb.prototype.decrypt = function(input, output, finish) { - if (input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } - this.cipher.decrypt(this._inBlock, this._outBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); - } - }; - modes.ecb.prototype.pad = function(input, options) { - var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length(); - input.fillWithByte(padding, padding); - return true; - }; - modes.ecb.prototype.unpad = function(output, options) { - if (options.overflow > 0) { - return false; - } - var len = output.length(); - var count = output.at(len - 1); - if (count > this.blockSize << 2) { - return false; - } - output.truncate(count); - return true; - }; - modes.cbc = function(options) { - options = options || {}; - this.name = "CBC"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); - }; - modes.cbc.prototype.start = function(options) { - if (options.iv === null) { - if (!this._prev) { - throw new Error("Invalid IV parameter."); - } - this._iv = this._prev.slice(0); - } else if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } else { - this._iv = transformIV(options.iv, this.blockSize); - this._prev = this._iv.slice(0); - } - }; - modes.cbc.prototype.encrypt = function(input, output, finish) { - if (input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._prev[i] ^ input.getInt32(); - } - this.cipher.encrypt(this._inBlock, this._outBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); - } - this._prev = this._outBlock; - }; - modes.cbc.prototype.decrypt = function(input, output, finish) { - if (input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } - this.cipher.decrypt(this._inBlock, this._outBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._prev[i] ^ this._outBlock[i]); - } - this._prev = this._inBlock.slice(0); - }; - modes.cbc.prototype.pad = function(input, options) { - var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length(); - input.fillWithByte(padding, padding); - return true; - }; - modes.cbc.prototype.unpad = function(output, options) { - if (options.overflow > 0) { - return false; - } - var len = output.length(); - var count = output.at(len - 1); - if (count > this.blockSize << 2) { - return false; - } - output.truncate(count); - return true; - }; - modes.cfb = function(options) { - options = options || {}; - this.name = "CFB"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialBlock = new Array(this._ints); - this._partialOutput = forge3.util.createBuffer(); - this._partialBytes = 0; - }; - modes.cfb.prototype.start = function(options) { - if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; - }; - modes.cfb.prototype.encrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32() ^ this._outBlock[i]; - output.putInt32(this._inBlock[i]); - } - return; - } - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialBlock[i] = input.getInt32() ^ this._outBlock[i]; - this._partialOutput.putInt32(this._partialBlock[i]); - } - if (partialBytes > 0) { - input.read -= this.blockSize; - } else { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._partialBlock[i]; - } - } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if (partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; - } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; - }; - modes.cfb.prototype.decrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - output.putInt32(this._inBlock[i] ^ this._outBlock[i]); - } - return; - } - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialBlock[i] = input.getInt32(); - this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]); - } - if (partialBytes > 0) { - input.read -= this.blockSize; - } else { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._partialBlock[i]; - } - } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if (partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; - } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; - }; - modes.ofb = function(options) { - options = options || {}; - this.name = "OFB"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialOutput = forge3.util.createBuffer(); - this._partialBytes = 0; - }; - modes.ofb.prototype.start = function(options) { - if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; - }; - modes.ofb.prototype.encrypt = function(input, output, finish) { - var inputLength = input.length(); - if (input.length() === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - output.putInt32(input.getInt32() ^ this._outBlock[i]); - this._inBlock[i] = this._outBlock[i]; - } - return; - } - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); - } - if (partialBytes > 0) { - input.read -= this.blockSize; - } else { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._outBlock[i]; - } - } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if (partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; - } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; - }; - modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt; - modes.ctr = function(options) { - options = options || {}; - this.name = "CTR"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialOutput = forge3.util.createBuffer(); - this._partialBytes = 0; - }; - modes.ctr.prototype.start = function(options) { - if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; - }; - modes.ctr.prototype.encrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - output.putInt32(input.getInt32() ^ this._outBlock[i]); - } - } else { - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); - } - if (partialBytes > 0) { - input.read -= this.blockSize; - } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if (partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; - } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; - } - inc32(this._inBlock); - }; - modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt; - modes.gcm = function(options) { - options = options || {}; - this.name = "GCM"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); - this._partialOutput = forge3.util.createBuffer(); - this._partialBytes = 0; - this._R = 3774873600; - }; - modes.gcm.prototype.start = function(options) { - if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } - var iv = forge3.util.createBuffer(options.iv); - this._cipherLength = 0; - var additionalData; - if ("additionalData" in options) { - additionalData = forge3.util.createBuffer(options.additionalData); - } else { - additionalData = forge3.util.createBuffer(); - } - if ("tagLength" in options) { - this._tagLength = options.tagLength; - } else { - this._tagLength = 128; - } - this._tag = null; - if (options.decrypt) { - this._tag = forge3.util.createBuffer(options.tag).getBytes(); - if (this._tag.length !== this._tagLength / 8) { - throw new Error("Authentication tag does not match tag length."); - } - } - this._hashBlock = new Array(this._ints); - this.tag = null; - this._hashSubkey = new Array(this._ints); - this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey); - this.componentBits = 4; - this._m = this.generateHashTable(this._hashSubkey, this.componentBits); - var ivLength = iv.length(); - if (ivLength === 12) { - this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1]; - } else { - this._j0 = [0, 0, 0, 0]; - while (iv.length() > 0) { - this._j0 = this.ghash( - this._hashSubkey, - this._j0, - [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()] - ); - } - this._j0 = this.ghash( - this._hashSubkey, - this._j0, - [0, 0].concat(from64To32(ivLength * 8)) - ); - } - this._inBlock = this._j0.slice(0); - inc32(this._inBlock); - this._partialBytes = 0; - additionalData = forge3.util.createBuffer(additionalData); - this._aDataLength = from64To32(additionalData.length() * 8); - var overflow = additionalData.length() % this.blockSize; - if (overflow) { - additionalData.fillWithByte(0, this.blockSize - overflow); - } - this._s = [0, 0, 0, 0]; - while (additionalData.length() > 0) { - this._s = this.ghash(this._hashSubkey, this._s, [ - additionalData.getInt32(), - additionalData.getInt32(), - additionalData.getInt32(), - additionalData.getInt32() - ]); - } - }; - modes.gcm.prototype.encrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i] ^= input.getInt32()); - } - this._cipherLength += this.blockSize; - } else { - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); - } - if (partialBytes <= 0 || finish) { - if (finish) { - var overflow = inputLength % this.blockSize; - this._cipherLength += overflow; - this._partialOutput.truncate(this.blockSize - overflow); - } else { - this._cipherLength += this.blockSize; - } - for (var i = 0; i < this._ints; ++i) { - this._outBlock[i] = this._partialOutput.getInt32(); - } - this._partialOutput.read -= this.blockSize; - } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if (partialBytes > 0 && !finish) { - input.read -= this.blockSize; - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; - } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; - } - this._s = this.ghash(this._hashSubkey, this._s, this._outBlock); - inc32(this._inBlock); - }; - modes.gcm.prototype.decrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength < this.blockSize && !(finish && inputLength > 0)) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - inc32(this._inBlock); - this._hashBlock[0] = input.getInt32(); - this._hashBlock[1] = input.getInt32(); - this._hashBlock[2] = input.getInt32(); - this._hashBlock[3] = input.getInt32(); - this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i] ^ this._hashBlock[i]); - } - if (inputLength < this.blockSize) { - this._cipherLength += inputLength % this.blockSize; - } else { - this._cipherLength += this.blockSize; - } - }; - modes.gcm.prototype.afterFinish = function(output, options) { - var rval = true; - if (options.decrypt && options.overflow) { - output.truncate(this.blockSize - options.overflow); - } - this.tag = forge3.util.createBuffer(); - var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8)); - this._s = this.ghash(this._hashSubkey, this._s, lengths); - var tag = []; - this.cipher.encrypt(this._j0, tag); - for (var i = 0; i < this._ints; ++i) { - this.tag.putInt32(this._s[i] ^ tag[i]); - } - this.tag.truncate(this.tag.length() % (this._tagLength / 8)); - if (options.decrypt && this.tag.bytes() !== this._tag) { - rval = false; - } - return rval; - }; - modes.gcm.prototype.multiply = function(x, y) { - var z_i = [0, 0, 0, 0]; - var v_i = y.slice(0); - for (var i = 0; i < 128; ++i) { - var x_i = x[i / 32 | 0] & 1 << 31 - i % 32; - if (x_i) { - z_i[0] ^= v_i[0]; - z_i[1] ^= v_i[1]; - z_i[2] ^= v_i[2]; - z_i[3] ^= v_i[3]; - } - this.pow(v_i, v_i); - } - return z_i; - }; - modes.gcm.prototype.pow = function(x, out) { - var lsb = x[3] & 1; - for (var i = 3; i > 0; --i) { - out[i] = x[i] >>> 1 | (x[i - 1] & 1) << 31; - } - out[0] = x[0] >>> 1; - if (lsb) { - out[0] ^= this._R; - } - }; - modes.gcm.prototype.tableMultiply = function(x) { - var z = [0, 0, 0, 0]; - for (var i = 0; i < 32; ++i) { - var idx = i / 8 | 0; - var x_i = x[idx] >>> (7 - i % 8) * 4 & 15; - var ah = this._m[i][x_i]; - z[0] ^= ah[0]; - z[1] ^= ah[1]; - z[2] ^= ah[2]; - z[3] ^= ah[3]; - } - return z; - }; - modes.gcm.prototype.ghash = function(h, y, x) { - y[0] ^= x[0]; - y[1] ^= x[1]; - y[2] ^= x[2]; - y[3] ^= x[3]; - return this.tableMultiply(y); - }; - modes.gcm.prototype.generateHashTable = function(h, bits) { - var multiplier = 8 / bits; - var perInt = 4 * multiplier; - var size = 16 * multiplier; - var m = new Array(size); - for (var i = 0; i < size; ++i) { - var tmp = [0, 0, 0, 0]; - var idx = i / perInt | 0; - var shft = (perInt - 1 - i % perInt) * bits; - tmp[idx] = 1 << bits - 1 << shft; - m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits); - } - return m; - }; - modes.gcm.prototype.generateSubHashTable = function(mid, bits) { - var size = 1 << bits; - var half = size >>> 1; - var m = new Array(size); - m[half] = mid.slice(0); - var i = half >>> 1; - while (i > 0) { - this.pow(m[2 * i], m[i] = []); - i >>= 1; - } - i = 2; - while (i < half) { - for (var j = 1; j < i; ++j) { - var m_i = m[i]; - var m_j = m[j]; - m[i + j] = [ - m_i[0] ^ m_j[0], - m_i[1] ^ m_j[1], - m_i[2] ^ m_j[2], - m_i[3] ^ m_j[3] - ]; - } - i *= 2; - } - m[0] = [0, 0, 0, 0]; - for (i = half + 1; i < size; ++i) { - var c = m[i ^ half]; - m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]]; - } - return m; - }; - function transformIV(iv, blockSize) { - if (typeof iv === "string") { - iv = forge3.util.createBuffer(iv); - } - if (forge3.util.isArray(iv) && iv.length > 4) { - var tmp = iv; - iv = forge3.util.createBuffer(); - for (var i = 0; i < tmp.length; ++i) { - iv.putByte(tmp[i]); - } - } - if (iv.length() < blockSize) { - throw new Error( - "Invalid IV length; got " + iv.length() + " bytes and expected " + blockSize + " bytes." - ); - } - if (!forge3.util.isArray(iv)) { - var ints = []; - var blocks = blockSize / 4; - for (var i = 0; i < blocks; ++i) { - ints.push(iv.getInt32()); - } - iv = ints; - } - return iv; - } - function inc32(block) { - block[block.length - 1] = block[block.length - 1] + 1 & 4294967295; - } - function from64To32(num) { - return [num / 4294967296 | 0, num & 4294967295]; - } - } -}); - -// node_modules/node-forge/lib/aes.js -var require_aes = __commonJS({ - "node_modules/node-forge/lib/aes.js"(exports, module) { - var forge3 = require_forge(); - require_cipher(); - require_cipherModes(); - require_util(); - module.exports = forge3.aes = forge3.aes || {}; - forge3.aes.startEncrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key, - output, - decrypt: false, - mode - }); - cipher.start(iv); - return cipher; - }; - forge3.aes.createEncryptionCipher = function(key, mode) { - return _createCipher({ - key, - output: null, - decrypt: false, - mode - }); - }; - forge3.aes.startDecrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key, - output, - decrypt: true, - mode - }); - cipher.start(iv); - return cipher; - }; - forge3.aes.createDecryptionCipher = function(key, mode) { - return _createCipher({ - key, - output: null, - decrypt: true, - mode - }); - }; - forge3.aes.Algorithm = function(name, mode) { - if (!init) { - initialize(); - } - var self2 = this; - self2.name = name; - self2.mode = new mode({ - blockSize: 16, - cipher: { - encrypt: function(inBlock, outBlock) { - return _updateBlock(self2._w, inBlock, outBlock, false); - }, - decrypt: function(inBlock, outBlock) { - return _updateBlock(self2._w, inBlock, outBlock, true); - } - } - }); - self2._init = false; - }; - forge3.aes.Algorithm.prototype.initialize = function(options) { - if (this._init) { - return; - } - var key = options.key; - var tmp; - if (typeof key === "string" && (key.length === 16 || key.length === 24 || key.length === 32)) { - key = forge3.util.createBuffer(key); - } else if (forge3.util.isArray(key) && (key.length === 16 || key.length === 24 || key.length === 32)) { - tmp = key; - key = forge3.util.createBuffer(); - for (var i = 0; i < tmp.length; ++i) { - key.putByte(tmp[i]); - } - } - if (!forge3.util.isArray(key)) { - tmp = key; - key = []; - var len = tmp.length(); - if (len === 16 || len === 24 || len === 32) { - len = len >>> 2; - for (var i = 0; i < len; ++i) { - key.push(tmp.getInt32()); - } - } - } - if (!forge3.util.isArray(key) || !(key.length === 4 || key.length === 6 || key.length === 8)) { - throw new Error("Invalid key parameter."); - } - var mode = this.mode.name; - var encryptOp = ["CFB", "OFB", "CTR", "GCM"].indexOf(mode) !== -1; - this._w = _expandKey(key, options.decrypt && !encryptOp); - this._init = true; - }; - forge3.aes._expandKey = function(key, decrypt) { - if (!init) { - initialize(); - } - return _expandKey(key, decrypt); - }; - forge3.aes._updateBlock = _updateBlock; - registerAlgorithm("AES-ECB", forge3.cipher.modes.ecb); - registerAlgorithm("AES-CBC", forge3.cipher.modes.cbc); - registerAlgorithm("AES-CFB", forge3.cipher.modes.cfb); - registerAlgorithm("AES-OFB", forge3.cipher.modes.ofb); - registerAlgorithm("AES-CTR", forge3.cipher.modes.ctr); - registerAlgorithm("AES-GCM", forge3.cipher.modes.gcm); - function registerAlgorithm(name, mode) { - var factory = function() { - return new forge3.aes.Algorithm(name, mode); - }; - forge3.cipher.registerAlgorithm(name, factory); - } - var init = false; - var Nb = 4; - var sbox; - var isbox; - var rcon; - var mix; - var imix; - function initialize() { - init = true; - rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54]; - var xtime = new Array(256); - for (var i = 0; i < 128; ++i) { - xtime[i] = i << 1; - xtime[i + 128] = i + 128 << 1 ^ 283; - } - sbox = new Array(256); - isbox = new Array(256); - mix = new Array(4); - imix = new Array(4); - for (var i = 0; i < 4; ++i) { - mix[i] = new Array(256); - imix[i] = new Array(256); - } - var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime; - for (var i = 0; i < 256; ++i) { - sx = ei ^ ei << 1 ^ ei << 2 ^ ei << 3 ^ ei << 4; - sx = sx >> 8 ^ sx & 255 ^ 99; - sbox[e] = sx; - isbox[sx] = e; - sx2 = xtime[sx]; - e2 = xtime[e]; - e4 = xtime[e2]; - e8 = xtime[e4]; - me = sx2 << 24 ^ // 2 - sx << 16 ^ // 1 - sx << 8 ^ // 1 - (sx ^ sx2); - ime = (e2 ^ e4 ^ e8) << 24 ^ // E (14) - (e ^ e8) << 16 ^ // 9 - (e ^ e4 ^ e8) << 8 ^ // D (13) - (e ^ e2 ^ e8); - for (var n = 0; n < 4; ++n) { - mix[n][e] = me; - imix[n][sx] = ime; - me = me << 24 | me >>> 8; - ime = ime << 24 | ime >>> 8; - } - if (e === 0) { - e = ei = 1; - } else { - e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]]; - ei ^= xtime[xtime[ei]]; - } - } - } - function _expandKey(key, decrypt) { - var w = key.slice(0); - var temp, iNk = 1; - var Nk = w.length; - var Nr1 = Nk + 6 + 1; - var end = Nb * Nr1; - for (var i = Nk; i < end; ++i) { - temp = w[i - 1]; - if (i % Nk === 0) { - temp = sbox[temp >>> 16 & 255] << 24 ^ sbox[temp >>> 8 & 255] << 16 ^ sbox[temp & 255] << 8 ^ sbox[temp >>> 24] ^ rcon[iNk] << 24; - iNk++; - } else if (Nk > 6 && i % Nk === 4) { - temp = sbox[temp >>> 24] << 24 ^ sbox[temp >>> 16 & 255] << 16 ^ sbox[temp >>> 8 & 255] << 8 ^ sbox[temp & 255]; - } - w[i] = w[i - Nk] ^ temp; - } - if (decrypt) { - var tmp; - var m0 = imix[0]; - var m1 = imix[1]; - var m2 = imix[2]; - var m3 = imix[3]; - var wnew = w.slice(0); - end = w.length; - for (var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) { - if (i === 0 || i === end - Nb) { - wnew[i] = w[wi]; - wnew[i + 1] = w[wi + 3]; - wnew[i + 2] = w[wi + 2]; - wnew[i + 3] = w[wi + 1]; - } else { - for (var n = 0; n < Nb; ++n) { - tmp = w[wi + n]; - wnew[i + (3 & -n)] = m0[sbox[tmp >>> 24]] ^ m1[sbox[tmp >>> 16 & 255]] ^ m2[sbox[tmp >>> 8 & 255]] ^ m3[sbox[tmp & 255]]; - } - } - } - w = wnew; - } - return w; - } - function _updateBlock(w, input, output, decrypt) { - var Nr = w.length / 4 - 1; - var m0, m1, m2, m3, sub; - if (decrypt) { - m0 = imix[0]; - m1 = imix[1]; - m2 = imix[2]; - m3 = imix[3]; - sub = isbox; - } else { - m0 = mix[0]; - m1 = mix[1]; - m2 = mix[2]; - m3 = mix[3]; - sub = sbox; - } - var a, b, c, d, a2, b2, c2; - a = input[0] ^ w[0]; - b = input[decrypt ? 3 : 1] ^ w[1]; - c = input[2] ^ w[2]; - d = input[decrypt ? 1 : 3] ^ w[3]; - var i = 3; - for (var round = 1; round < Nr; ++round) { - a2 = m0[a >>> 24] ^ m1[b >>> 16 & 255] ^ m2[c >>> 8 & 255] ^ m3[d & 255] ^ w[++i]; - b2 = m0[b >>> 24] ^ m1[c >>> 16 & 255] ^ m2[d >>> 8 & 255] ^ m3[a & 255] ^ w[++i]; - c2 = m0[c >>> 24] ^ m1[d >>> 16 & 255] ^ m2[a >>> 8 & 255] ^ m3[b & 255] ^ w[++i]; - d = m0[d >>> 24] ^ m1[a >>> 16 & 255] ^ m2[b >>> 8 & 255] ^ m3[c & 255] ^ w[++i]; - a = a2; - b = b2; - c = c2; - } - output[0] = sub[a >>> 24] << 24 ^ sub[b >>> 16 & 255] << 16 ^ sub[c >>> 8 & 255] << 8 ^ sub[d & 255] ^ w[++i]; - output[decrypt ? 3 : 1] = sub[b >>> 24] << 24 ^ sub[c >>> 16 & 255] << 16 ^ sub[d >>> 8 & 255] << 8 ^ sub[a & 255] ^ w[++i]; - output[2] = sub[c >>> 24] << 24 ^ sub[d >>> 16 & 255] << 16 ^ sub[a >>> 8 & 255] << 8 ^ sub[b & 255] ^ w[++i]; - output[decrypt ? 1 : 3] = sub[d >>> 24] << 24 ^ sub[a >>> 16 & 255] << 16 ^ sub[b >>> 8 & 255] << 8 ^ sub[c & 255] ^ w[++i]; - } - function _createCipher(options) { - options = options || {}; - var mode = (options.mode || "CBC").toUpperCase(); - var algorithm = "AES-" + mode; - var cipher; - if (options.decrypt) { - cipher = forge3.cipher.createDecipher(algorithm, options.key); - } else { - cipher = forge3.cipher.createCipher(algorithm, options.key); - } - var start = cipher.start; - cipher.start = function(iv, options2) { - var output = null; - if (options2 instanceof forge3.util.ByteBuffer) { - output = options2; - options2 = {}; - } - options2 = options2 || {}; - options2.output = output; - options2.iv = iv; - start.call(cipher, options2); - }; - return cipher; - } - } -}); - -// node_modules/node-forge/lib/oids.js -var require_oids = __commonJS({ - "node_modules/node-forge/lib/oids.js"(exports, module) { - var forge3 = require_forge(); - forge3.pki = forge3.pki || {}; - var oids = module.exports = forge3.pki.oids = forge3.oids = forge3.oids || {}; - function _IN(id, name) { - oids[id] = name; - oids[name] = id; - } - function _I_(id, name) { - oids[id] = name; - } - _IN("1.2.840.113549.1.1.1", "rsaEncryption"); - _IN("1.2.840.113549.1.1.4", "md5WithRSAEncryption"); - _IN("1.2.840.113549.1.1.5", "sha1WithRSAEncryption"); - _IN("1.2.840.113549.1.1.7", "RSAES-OAEP"); - _IN("1.2.840.113549.1.1.8", "mgf1"); - _IN("1.2.840.113549.1.1.9", "pSpecified"); - _IN("1.2.840.113549.1.1.10", "RSASSA-PSS"); - _IN("1.2.840.113549.1.1.11", "sha256WithRSAEncryption"); - _IN("1.2.840.113549.1.1.12", "sha384WithRSAEncryption"); - _IN("1.2.840.113549.1.1.13", "sha512WithRSAEncryption"); - _IN("1.3.101.112", "EdDSA25519"); - _IN("1.2.840.10040.4.3", "dsa-with-sha1"); - _IN("1.3.14.3.2.7", "desCBC"); - _IN("1.3.14.3.2.26", "sha1"); - _IN("1.3.14.3.2.29", "sha1WithRSASignature"); - _IN("2.16.840.1.101.3.4.2.1", "sha256"); - _IN("2.16.840.1.101.3.4.2.2", "sha384"); - _IN("2.16.840.1.101.3.4.2.3", "sha512"); - _IN("2.16.840.1.101.3.4.2.4", "sha224"); - _IN("2.16.840.1.101.3.4.2.5", "sha512-224"); - _IN("2.16.840.1.101.3.4.2.6", "sha512-256"); - _IN("1.2.840.113549.2.2", "md2"); - _IN("1.2.840.113549.2.5", "md5"); - _IN("1.2.840.113549.1.7.1", "data"); - _IN("1.2.840.113549.1.7.2", "signedData"); - _IN("1.2.840.113549.1.7.3", "envelopedData"); - _IN("1.2.840.113549.1.7.4", "signedAndEnvelopedData"); - _IN("1.2.840.113549.1.7.5", "digestedData"); - _IN("1.2.840.113549.1.7.6", "encryptedData"); - _IN("1.2.840.113549.1.9.1", "emailAddress"); - _IN("1.2.840.113549.1.9.2", "unstructuredName"); - _IN("1.2.840.113549.1.9.3", "contentType"); - _IN("1.2.840.113549.1.9.4", "messageDigest"); - _IN("1.2.840.113549.1.9.5", "signingTime"); - _IN("1.2.840.113549.1.9.6", "counterSignature"); - _IN("1.2.840.113549.1.9.7", "challengePassword"); - _IN("1.2.840.113549.1.9.8", "unstructuredAddress"); - _IN("1.2.840.113549.1.9.14", "extensionRequest"); - _IN("1.2.840.113549.1.9.20", "friendlyName"); - _IN("1.2.840.113549.1.9.21", "localKeyId"); - _IN("1.2.840.113549.1.9.22.1", "x509Certificate"); - _IN("1.2.840.113549.1.12.10.1.1", "keyBag"); - _IN("1.2.840.113549.1.12.10.1.2", "pkcs8ShroudedKeyBag"); - _IN("1.2.840.113549.1.12.10.1.3", "certBag"); - _IN("1.2.840.113549.1.12.10.1.4", "crlBag"); - _IN("1.2.840.113549.1.12.10.1.5", "secretBag"); - _IN("1.2.840.113549.1.12.10.1.6", "safeContentsBag"); - _IN("1.2.840.113549.1.5.13", "pkcs5PBES2"); - _IN("1.2.840.113549.1.5.12", "pkcs5PBKDF2"); - _IN("1.2.840.113549.1.12.1.1", "pbeWithSHAAnd128BitRC4"); - _IN("1.2.840.113549.1.12.1.2", "pbeWithSHAAnd40BitRC4"); - _IN("1.2.840.113549.1.12.1.3", "pbeWithSHAAnd3-KeyTripleDES-CBC"); - _IN("1.2.840.113549.1.12.1.4", "pbeWithSHAAnd2-KeyTripleDES-CBC"); - _IN("1.2.840.113549.1.12.1.5", "pbeWithSHAAnd128BitRC2-CBC"); - _IN("1.2.840.113549.1.12.1.6", "pbewithSHAAnd40BitRC2-CBC"); - _IN("1.2.840.113549.2.7", "hmacWithSHA1"); - _IN("1.2.840.113549.2.8", "hmacWithSHA224"); - _IN("1.2.840.113549.2.9", "hmacWithSHA256"); - _IN("1.2.840.113549.2.10", "hmacWithSHA384"); - _IN("1.2.840.113549.2.11", "hmacWithSHA512"); - _IN("1.2.840.113549.3.7", "des-EDE3-CBC"); - _IN("2.16.840.1.101.3.4.1.2", "aes128-CBC"); - _IN("2.16.840.1.101.3.4.1.22", "aes192-CBC"); - _IN("2.16.840.1.101.3.4.1.42", "aes256-CBC"); - _IN("2.5.4.3", "commonName"); - _IN("2.5.4.4", "surname"); - _IN("2.5.4.5", "serialNumber"); - _IN("2.5.4.6", "countryName"); - _IN("2.5.4.7", "localityName"); - _IN("2.5.4.8", "stateOrProvinceName"); - _IN("2.5.4.9", "streetAddress"); - _IN("2.5.4.10", "organizationName"); - _IN("2.5.4.11", "organizationalUnitName"); - _IN("2.5.4.12", "title"); - _IN("2.5.4.13", "description"); - _IN("2.5.4.15", "businessCategory"); - _IN("2.5.4.17", "postalCode"); - _IN("2.5.4.42", "givenName"); - _IN("1.3.6.1.4.1.311.60.2.1.2", "jurisdictionOfIncorporationStateOrProvinceName"); - _IN("1.3.6.1.4.1.311.60.2.1.3", "jurisdictionOfIncorporationCountryName"); - _IN("2.16.840.1.113730.1.1", "nsCertType"); - _IN("2.16.840.1.113730.1.13", "nsComment"); - _I_("2.5.29.1", "authorityKeyIdentifier"); - _I_("2.5.29.2", "keyAttributes"); - _I_("2.5.29.3", "certificatePolicies"); - _I_("2.5.29.4", "keyUsageRestriction"); - _I_("2.5.29.5", "policyMapping"); - _I_("2.5.29.6", "subtreesConstraint"); - _I_("2.5.29.7", "subjectAltName"); - _I_("2.5.29.8", "issuerAltName"); - _I_("2.5.29.9", "subjectDirectoryAttributes"); - _I_("2.5.29.10", "basicConstraints"); - _I_("2.5.29.11", "nameConstraints"); - _I_("2.5.29.12", "policyConstraints"); - _I_("2.5.29.13", "basicConstraints"); - _IN("2.5.29.14", "subjectKeyIdentifier"); - _IN("2.5.29.15", "keyUsage"); - _I_("2.5.29.16", "privateKeyUsagePeriod"); - _IN("2.5.29.17", "subjectAltName"); - _IN("2.5.29.18", "issuerAltName"); - _IN("2.5.29.19", "basicConstraints"); - _I_("2.5.29.20", "cRLNumber"); - _I_("2.5.29.21", "cRLReason"); - _I_("2.5.29.22", "expirationDate"); - _I_("2.5.29.23", "instructionCode"); - _I_("2.5.29.24", "invalidityDate"); - _I_("2.5.29.25", "cRLDistributionPoints"); - _I_("2.5.29.26", "issuingDistributionPoint"); - _I_("2.5.29.27", "deltaCRLIndicator"); - _I_("2.5.29.28", "issuingDistributionPoint"); - _I_("2.5.29.29", "certificateIssuer"); - _I_("2.5.29.30", "nameConstraints"); - _IN("2.5.29.31", "cRLDistributionPoints"); - _IN("2.5.29.32", "certificatePolicies"); - _I_("2.5.29.33", "policyMappings"); - _I_("2.5.29.34", "policyConstraints"); - _IN("2.5.29.35", "authorityKeyIdentifier"); - _I_("2.5.29.36", "policyConstraints"); - _IN("2.5.29.37", "extKeyUsage"); - _I_("2.5.29.46", "freshestCRL"); - _I_("2.5.29.54", "inhibitAnyPolicy"); - _IN("1.3.6.1.4.1.11129.2.4.2", "timestampList"); - _IN("1.3.6.1.5.5.7.1.1", "authorityInfoAccess"); - _IN("1.3.6.1.5.5.7.3.1", "serverAuth"); - _IN("1.3.6.1.5.5.7.3.2", "clientAuth"); - _IN("1.3.6.1.5.5.7.3.3", "codeSigning"); - _IN("1.3.6.1.5.5.7.3.4", "emailProtection"); - _IN("1.3.6.1.5.5.7.3.8", "timeStamping"); - } -}); - -// node_modules/node-forge/lib/asn1.js -var require_asn1 = __commonJS({ - "node_modules/node-forge/lib/asn1.js"(exports, module) { - var forge3 = require_forge(); - require_util(); - require_oids(); - var asn1 = module.exports = forge3.asn1 = forge3.asn1 || {}; - asn1.Class = { - UNIVERSAL: 0, - APPLICATION: 64, - CONTEXT_SPECIFIC: 128, - PRIVATE: 192 - }; - asn1.Type = { - NONE: 0, - BOOLEAN: 1, - INTEGER: 2, - BITSTRING: 3, - OCTETSTRING: 4, - NULL: 5, - OID: 6, - ODESC: 7, - EXTERNAL: 8, - REAL: 9, - ENUMERATED: 10, - EMBEDDED: 11, - UTF8: 12, - ROID: 13, - SEQUENCE: 16, - SET: 17, - PRINTABLESTRING: 19, - IA5STRING: 22, - UTCTIME: 23, - GENERALIZEDTIME: 24, - BMPSTRING: 30 - }; - asn1.create = function(tagClass, type, constructed, value, options) { - if (forge3.util.isArray(value)) { - var tmp = []; - for (var i = 0; i < value.length; ++i) { - if (value[i] !== void 0) { - tmp.push(value[i]); - } - } - value = tmp; - } - var obj = { - tagClass, - type, - constructed, - composed: constructed || forge3.util.isArray(value), - value - }; - if (options && "bitStringContents" in options) { - obj.bitStringContents = options.bitStringContents; - obj.original = asn1.copy(obj); - } - return obj; - }; - asn1.copy = function(obj, options) { - var copy; - if (forge3.util.isArray(obj)) { - copy = []; - for (var i = 0; i < obj.length; ++i) { - copy.push(asn1.copy(obj[i], options)); - } - return copy; - } - if (typeof obj === "string") { - return obj; - } - copy = { - tagClass: obj.tagClass, - type: obj.type, - constructed: obj.constructed, - composed: obj.composed, - value: asn1.copy(obj.value, options) - }; - if (options && !options.excludeBitStringContents) { - copy.bitStringContents = obj.bitStringContents; - } - return copy; - }; - asn1.equals = function(obj1, obj2, options) { - if (forge3.util.isArray(obj1)) { - if (!forge3.util.isArray(obj2)) { - return false; - } - if (obj1.length !== obj2.length) { - return false; - } - for (var i = 0; i < obj1.length; ++i) { - if (!asn1.equals(obj1[i], obj2[i])) { - return false; - } - } - return true; - } - if (typeof obj1 !== typeof obj2) { - return false; - } - if (typeof obj1 === "string") { - return obj1 === obj2; - } - var equal = obj1.tagClass === obj2.tagClass && obj1.type === obj2.type && obj1.constructed === obj2.constructed && obj1.composed === obj2.composed && asn1.equals(obj1.value, obj2.value); - if (options && options.includeBitStringContents) { - equal = equal && obj1.bitStringContents === obj2.bitStringContents; - } - return equal; - }; - asn1.getBerValueLength = function(b) { - var b2 = b.getByte(); - if (b2 === 128) { - return void 0; - } - var length; - var longForm = b2 & 128; - if (!longForm) { - length = b2; - } else { - length = b.getInt((b2 & 127) << 3); - } - return length; - }; - function _checkBufferLength(bytes, remaining, n) { - if (n > remaining) { - var error = new Error("Too few bytes to parse DER."); - error.available = bytes.length(); - error.remaining = remaining; - error.requested = n; - throw error; - } - } - var _getValueLength = function(bytes, remaining) { - var b2 = bytes.getByte(); - remaining--; - if (b2 === 128) { - return void 0; - } - var length; - var longForm = b2 & 128; - if (!longForm) { - length = b2; - } else { - var longFormBytes = b2 & 127; - _checkBufferLength(bytes, remaining, longFormBytes); - length = bytes.getInt(longFormBytes << 3); - } - if (length < 0) { - throw new Error("Negative length: " + length); - } - return length; - }; - asn1.fromDer = function(bytes, options) { - if (options === void 0) { - options = { - strict: true, - parseAllBytes: true, - decodeBitStrings: true - }; - } - if (typeof options === "boolean") { - options = { - strict: options, - parseAllBytes: true, - decodeBitStrings: true - }; - } - if (!("strict" in options)) { - options.strict = true; - } - if (!("parseAllBytes" in options)) { - options.parseAllBytes = true; - } - if (!("decodeBitStrings" in options)) { - options.decodeBitStrings = true; - } - if (typeof bytes === "string") { - bytes = forge3.util.createBuffer(bytes); - } - var byteCount = bytes.length(); - var value = _fromDer(bytes, bytes.length(), 0, options); - if (options.parseAllBytes && bytes.length() !== 0) { - var error = new Error("Unparsed DER bytes remain after ASN.1 parsing."); - error.byteCount = byteCount; - error.remaining = bytes.length(); - throw error; - } - return value; - }; - function _fromDer(bytes, remaining, depth, options) { - var start; - _checkBufferLength(bytes, remaining, 2); - var b1 = bytes.getByte(); - remaining--; - var tagClass = b1 & 192; - var type = b1 & 31; - start = bytes.length(); - var length = _getValueLength(bytes, remaining); - remaining -= start - bytes.length(); - if (length !== void 0 && length > remaining) { - if (options.strict) { - var error = new Error("Too few bytes to read ASN.1 value."); - error.available = bytes.length(); - error.remaining = remaining; - error.requested = length; - throw error; - } - length = remaining; - } - var value; - var bitStringContents; - var constructed = (b1 & 32) === 32; - if (constructed) { - value = []; - if (length === void 0) { - for (; ; ) { - _checkBufferLength(bytes, remaining, 2); - if (bytes.bytes(2) === String.fromCharCode(0, 0)) { - bytes.getBytes(2); - remaining -= 2; - break; - } - start = bytes.length(); - value.push(_fromDer(bytes, remaining, depth + 1, options)); - remaining -= start - bytes.length(); - } - } else { - while (length > 0) { - start = bytes.length(); - value.push(_fromDer(bytes, length, depth + 1, options)); - remaining -= start - bytes.length(); - length -= start - bytes.length(); - } - } - } - if (value === void 0 && tagClass === asn1.Class.UNIVERSAL && type === asn1.Type.BITSTRING) { - bitStringContents = bytes.bytes(length); - } - if (value === void 0 && options.decodeBitStrings && tagClass === asn1.Class.UNIVERSAL && // FIXME: OCTET STRINGs not yet supported here - // .. other parts of forge expect to decode OCTET STRINGs manually - type === asn1.Type.BITSTRING && length > 1) { - var savedRead = bytes.read; - var savedRemaining = remaining; - var unused = 0; - if (type === asn1.Type.BITSTRING) { - _checkBufferLength(bytes, remaining, 1); - unused = bytes.getByte(); - remaining--; - } - if (unused === 0) { - try { - start = bytes.length(); - var subOptions = { - // enforce strict mode to avoid parsing ASN.1 from plain data - strict: true, - decodeBitStrings: true - }; - var composed = _fromDer(bytes, remaining, depth + 1, subOptions); - var used = start - bytes.length(); - remaining -= used; - if (type == asn1.Type.BITSTRING) { - used++; - } - var tc = composed.tagClass; - if (used === length && (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) { - value = [composed]; - } - } catch (ex) { - } - } - if (value === void 0) { - bytes.read = savedRead; - remaining = savedRemaining; - } - } - if (value === void 0) { - if (length === void 0) { - if (options.strict) { - throw new Error("Non-constructed ASN.1 object of indefinite length."); - } - length = remaining; - } - if (type === asn1.Type.BMPSTRING) { - value = ""; - for (; length > 0; length -= 2) { - _checkBufferLength(bytes, remaining, 2); - value += String.fromCharCode(bytes.getInt16()); - remaining -= 2; - } - } else { - value = bytes.getBytes(length); - remaining -= length; - } - } - var asn1Options = bitStringContents === void 0 ? null : { - bitStringContents - }; - return asn1.create(tagClass, type, constructed, value, asn1Options); - } - asn1.toDer = function(obj) { - var bytes = forge3.util.createBuffer(); - var b1 = obj.tagClass | obj.type; - var value = forge3.util.createBuffer(); - var useBitStringContents = false; - if ("bitStringContents" in obj) { - useBitStringContents = true; - if (obj.original) { - useBitStringContents = asn1.equals(obj, obj.original); - } - } - if (useBitStringContents) { - value.putBytes(obj.bitStringContents); - } else if (obj.composed) { - if (obj.constructed) { - b1 |= 32; - } else { - value.putByte(0); - } - for (var i = 0; i < obj.value.length; ++i) { - if (obj.value[i] !== void 0) { - value.putBuffer(asn1.toDer(obj.value[i])); - } - } - } else { - if (obj.type === asn1.Type.BMPSTRING) { - for (var i = 0; i < obj.value.length; ++i) { - value.putInt16(obj.value.charCodeAt(i)); - } - } else { - if (obj.type === asn1.Type.INTEGER && obj.value.length > 1 && // leading 0x00 for positive integer - (obj.value.charCodeAt(0) === 0 && (obj.value.charCodeAt(1) & 128) === 0 || // leading 0xFF for negative integer - obj.value.charCodeAt(0) === 255 && (obj.value.charCodeAt(1) & 128) === 128)) { - value.putBytes(obj.value.substr(1)); - } else { - value.putBytes(obj.value); - } - } - } - bytes.putByte(b1); - if (value.length() <= 127) { - bytes.putByte(value.length() & 127); - } else { - var len = value.length(); - var lenBytes = ""; - do { - lenBytes += String.fromCharCode(len & 255); - len = len >>> 8; - } while (len > 0); - bytes.putByte(lenBytes.length | 128); - for (var i = lenBytes.length - 1; i >= 0; --i) { - bytes.putByte(lenBytes.charCodeAt(i)); - } - } - bytes.putBuffer(value); - return bytes; - }; - asn1.oidToDer = function(oid) { - var values = oid.split("."); - var bytes = forge3.util.createBuffer(); - bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10)); - var last, valueBytes, value, b; - for (var i = 2; i < values.length; ++i) { - last = true; - valueBytes = []; - value = parseInt(values[i], 10); - do { - b = value & 127; - value = value >>> 7; - if (!last) { - b |= 128; - } - valueBytes.push(b); - last = false; - } while (value > 0); - for (var n = valueBytes.length - 1; n >= 0; --n) { - bytes.putByte(valueBytes[n]); - } - } - return bytes; - }; - asn1.derToOid = function(bytes) { - var oid; - if (typeof bytes === "string") { - bytes = forge3.util.createBuffer(bytes); - } - var b = bytes.getByte(); - oid = Math.floor(b / 40) + "." + b % 40; - var value = 0; - while (bytes.length() > 0) { - b = bytes.getByte(); - value = value << 7; - if (b & 128) { - value += b & 127; - } else { - oid += "." + (value + b); - value = 0; - } - } - return oid; - }; - asn1.utcTimeToDate = function(utc) { - var date = /* @__PURE__ */ new Date(); - var year = parseInt(utc.substr(0, 2), 10); - year = year >= 50 ? 1900 + year : 2e3 + year; - var MM = parseInt(utc.substr(2, 2), 10) - 1; - var DD = parseInt(utc.substr(4, 2), 10); - var hh = parseInt(utc.substr(6, 2), 10); - var mm = parseInt(utc.substr(8, 2), 10); - var ss = 0; - if (utc.length > 11) { - var c = utc.charAt(10); - var end = 10; - if (c !== "+" && c !== "-") { - ss = parseInt(utc.substr(10, 2), 10); - end += 2; - } - } - date.setUTCFullYear(year, MM, DD); - date.setUTCHours(hh, mm, ss, 0); - if (end) { - c = utc.charAt(end); - if (c === "+" || c === "-") { - var hhoffset = parseInt(utc.substr(end + 1, 2), 10); - var mmoffset = parseInt(utc.substr(end + 4, 2), 10); - var offset = hhoffset * 60 + mmoffset; - offset *= 6e4; - if (c === "+") { - date.setTime(+date - offset); - } else { - date.setTime(+date + offset); - } - } - } - return date; - }; - asn1.generalizedTimeToDate = function(gentime) { - var date = /* @__PURE__ */ new Date(); - var YYYY = parseInt(gentime.substr(0, 4), 10); - var MM = parseInt(gentime.substr(4, 2), 10) - 1; - var DD = parseInt(gentime.substr(6, 2), 10); - var hh = parseInt(gentime.substr(8, 2), 10); - var mm = parseInt(gentime.substr(10, 2), 10); - var ss = parseInt(gentime.substr(12, 2), 10); - var fff = 0; - var offset = 0; - var isUTC = false; - if (gentime.charAt(gentime.length - 1) === "Z") { - isUTC = true; - } - var end = gentime.length - 5, c = gentime.charAt(end); - if (c === "+" || c === "-") { - var hhoffset = parseInt(gentime.substr(end + 1, 2), 10); - var mmoffset = parseInt(gentime.substr(end + 4, 2), 10); - offset = hhoffset * 60 + mmoffset; - offset *= 6e4; - if (c === "+") { - offset *= -1; - } - isUTC = true; - } - if (gentime.charAt(14) === ".") { - fff = parseFloat(gentime.substr(14), 10) * 1e3; - } - if (isUTC) { - date.setUTCFullYear(YYYY, MM, DD); - date.setUTCHours(hh, mm, ss, fff); - date.setTime(+date + offset); - } else { - date.setFullYear(YYYY, MM, DD); - date.setHours(hh, mm, ss, fff); - } - return date; - }; - asn1.dateToUtcTime = function(date) { - if (typeof date === "string") { - return date; - } - var rval = ""; - var format = []; - format.push(("" + date.getUTCFullYear()).substr(2)); - format.push("" + (date.getUTCMonth() + 1)); - format.push("" + date.getUTCDate()); - format.push("" + date.getUTCHours()); - format.push("" + date.getUTCMinutes()); - format.push("" + date.getUTCSeconds()); - for (var i = 0; i < format.length; ++i) { - if (format[i].length < 2) { - rval += "0"; - } - rval += format[i]; - } - rval += "Z"; - return rval; - }; - asn1.dateToGeneralizedTime = function(date) { - if (typeof date === "string") { - return date; - } - var rval = ""; - var format = []; - format.push("" + date.getUTCFullYear()); - format.push("" + (date.getUTCMonth() + 1)); - format.push("" + date.getUTCDate()); - format.push("" + date.getUTCHours()); - format.push("" + date.getUTCMinutes()); - format.push("" + date.getUTCSeconds()); - for (var i = 0; i < format.length; ++i) { - if (format[i].length < 2) { - rval += "0"; - } - rval += format[i]; - } - rval += "Z"; - return rval; - }; - asn1.integerToDer = function(x) { - var rval = forge3.util.createBuffer(); - if (x >= -128 && x < 128) { - return rval.putSignedInt(x, 8); - } - if (x >= -32768 && x < 32768) { - return rval.putSignedInt(x, 16); - } - if (x >= -8388608 && x < 8388608) { - return rval.putSignedInt(x, 24); - } - if (x >= -2147483648 && x < 2147483648) { - return rval.putSignedInt(x, 32); - } - var error = new Error("Integer too large; max is 32-bits."); - error.integer = x; - throw error; - }; - asn1.derToInteger = function(bytes) { - if (typeof bytes === "string") { - bytes = forge3.util.createBuffer(bytes); - } - var n = bytes.length() * 8; - if (n > 32) { - throw new Error("Integer too large; max is 32-bits."); - } - return bytes.getSignedInt(n); - }; - asn1.validate = function(obj, v, capture, errors) { - var rval = false; - if ((obj.tagClass === v.tagClass || typeof v.tagClass === "undefined") && (obj.type === v.type || typeof v.type === "undefined")) { - if (obj.constructed === v.constructed || typeof v.constructed === "undefined") { - rval = true; - if (v.value && forge3.util.isArray(v.value)) { - var j = 0; - for (var i = 0; rval && i < v.value.length; ++i) { - rval = v.value[i].optional || false; - if (obj.value[j]) { - rval = asn1.validate(obj.value[j], v.value[i], capture, errors); - if (rval) { - ++j; - } else if (v.value[i].optional) { - rval = true; - } - } - if (!rval && errors) { - errors.push( - "[" + v.name + '] Tag class "' + v.tagClass + '", type "' + v.type + '" expected value length "' + v.value.length + '", got "' + obj.value.length + '"' - ); - } - } - } - if (rval && capture) { - if (v.capture) { - capture[v.capture] = obj.value; - } - if (v.captureAsn1) { - capture[v.captureAsn1] = obj; - } - if (v.captureBitStringContents && "bitStringContents" in obj) { - capture[v.captureBitStringContents] = obj.bitStringContents; - } - if (v.captureBitStringValue && "bitStringContents" in obj) { - var value; - if (obj.bitStringContents.length < 2) { - capture[v.captureBitStringValue] = ""; - } else { - var unused = obj.bitStringContents.charCodeAt(0); - if (unused !== 0) { - throw new Error( - "captureBitStringValue only supported for zero unused bits" - ); - } - capture[v.captureBitStringValue] = obj.bitStringContents.slice(1); - } - } - } - } else if (errors) { - errors.push( - "[" + v.name + '] Expected constructed "' + v.constructed + '", got "' + obj.constructed + '"' - ); - } - } else if (errors) { - if (obj.tagClass !== v.tagClass) { - errors.push( - "[" + v.name + '] Expected tag class "' + v.tagClass + '", got "' + obj.tagClass + '"' - ); - } - if (obj.type !== v.type) { - errors.push( - "[" + v.name + '] Expected type "' + v.type + '", got "' + obj.type + '"' - ); - } - } - return rval; - }; - var _nonLatinRegex = /[^\\u0000-\\u00ff]/; - asn1.prettyPrint = function(obj, level, indentation) { - var rval = ""; - level = level || 0; - indentation = indentation || 2; - if (level > 0) { - rval += "\n"; - } - var indent = ""; - for (var i = 0; i < level * indentation; ++i) { - indent += " "; - } - rval += indent + "Tag: "; - switch (obj.tagClass) { - case asn1.Class.UNIVERSAL: - rval += "Universal:"; - break; - case asn1.Class.APPLICATION: - rval += "Application:"; - break; - case asn1.Class.CONTEXT_SPECIFIC: - rval += "Context-Specific:"; - break; - case asn1.Class.PRIVATE: - rval += "Private:"; - break; - } - if (obj.tagClass === asn1.Class.UNIVERSAL) { - rval += obj.type; - switch (obj.type) { - case asn1.Type.NONE: - rval += " (None)"; - break; - case asn1.Type.BOOLEAN: - rval += " (Boolean)"; - break; - case asn1.Type.INTEGER: - rval += " (Integer)"; - break; - case asn1.Type.BITSTRING: - rval += " (Bit string)"; - break; - case asn1.Type.OCTETSTRING: - rval += " (Octet string)"; - break; - case asn1.Type.NULL: - rval += " (Null)"; - break; - case asn1.Type.OID: - rval += " (Object Identifier)"; - break; - case asn1.Type.ODESC: - rval += " (Object Descriptor)"; - break; - case asn1.Type.EXTERNAL: - rval += " (External or Instance of)"; - break; - case asn1.Type.REAL: - rval += " (Real)"; - break; - case asn1.Type.ENUMERATED: - rval += " (Enumerated)"; - break; - case asn1.Type.EMBEDDED: - rval += " (Embedded PDV)"; - break; - case asn1.Type.UTF8: - rval += " (UTF8)"; - break; - case asn1.Type.ROID: - rval += " (Relative Object Identifier)"; - break; - case asn1.Type.SEQUENCE: - rval += " (Sequence)"; - break; - case asn1.Type.SET: - rval += " (Set)"; - break; - case asn1.Type.PRINTABLESTRING: - rval += " (Printable String)"; - break; - case asn1.Type.IA5String: - rval += " (IA5String (ASCII))"; - break; - case asn1.Type.UTCTIME: - rval += " (UTC time)"; - break; - case asn1.Type.GENERALIZEDTIME: - rval += " (Generalized time)"; - break; - case asn1.Type.BMPSTRING: - rval += " (BMP String)"; - break; - } - } else { - rval += obj.type; - } - rval += "\n"; - rval += indent + "Constructed: " + obj.constructed + "\n"; - if (obj.composed) { - var subvalues = 0; - var sub = ""; - for (var i = 0; i < obj.value.length; ++i) { - if (obj.value[i] !== void 0) { - subvalues += 1; - sub += asn1.prettyPrint(obj.value[i], level + 1, indentation); - if (i + 1 < obj.value.length) { - sub += ","; - } - } - } - rval += indent + "Sub values: " + subvalues + sub; - } else { - rval += indent + "Value: "; - if (obj.type === asn1.Type.OID) { - var oid = asn1.derToOid(obj.value); - rval += oid; - if (forge3.pki && forge3.pki.oids) { - if (oid in forge3.pki.oids) { - rval += " (" + forge3.pki.oids[oid] + ") "; - } - } - } - if (obj.type === asn1.Type.INTEGER) { - try { - rval += asn1.derToInteger(obj.value); - } catch (ex) { - rval += "0x" + forge3.util.bytesToHex(obj.value); - } - } else if (obj.type === asn1.Type.BITSTRING) { - if (obj.value.length > 1) { - rval += "0x" + forge3.util.bytesToHex(obj.value.slice(1)); - } else { - rval += "(none)"; - } - if (obj.value.length > 0) { - var unused = obj.value.charCodeAt(0); - if (unused == 1) { - rval += " (1 unused bit shown)"; - } else if (unused > 1) { - rval += " (" + unused + " unused bits shown)"; - } - } - } else if (obj.type === asn1.Type.OCTETSTRING) { - if (!_nonLatinRegex.test(obj.value)) { - rval += "(" + obj.value + ") "; - } - rval += "0x" + forge3.util.bytesToHex(obj.value); - } else if (obj.type === asn1.Type.UTF8) { - try { - rval += forge3.util.decodeUtf8(obj.value); - } catch (e) { - if (e.message === "URI malformed") { - rval += "0x" + forge3.util.bytesToHex(obj.value) + " (malformed UTF8)"; - } else { - throw e; - } - } - } else if (obj.type === asn1.Type.PRINTABLESTRING || obj.type === asn1.Type.IA5String) { - rval += obj.value; - } else if (_nonLatinRegex.test(obj.value)) { - rval += "0x" + forge3.util.bytesToHex(obj.value); - } else if (obj.value.length === 0) { - rval += "[null]"; - } else { - rval += obj.value; - } - } - return rval; - }; - } -}); - -// node_modules/node-forge/lib/md.js -var require_md = __commonJS({ - "node_modules/node-forge/lib/md.js"(exports, module) { - var forge3 = require_forge(); - module.exports = forge3.md = forge3.md || {}; - forge3.md.algorithms = forge3.md.algorithms || {}; - } -}); - -// node_modules/node-forge/lib/hmac.js -var require_hmac = __commonJS({ - "node_modules/node-forge/lib/hmac.js"(exports, module) { - var forge3 = require_forge(); - require_md(); - require_util(); - var hmac = module.exports = forge3.hmac = forge3.hmac || {}; - hmac.create = function() { - var _key = null; - var _md = null; - var _ipadding = null; - var _opadding = null; - var ctx = {}; - ctx.start = function(md, key) { - if (md !== null) { - if (typeof md === "string") { - md = md.toLowerCase(); - if (md in forge3.md.algorithms) { - _md = forge3.md.algorithms[md].create(); - } else { - throw new Error('Unknown hash algorithm "' + md + '"'); - } - } else { - _md = md; - } - } - if (key === null) { - key = _key; - } else { - if (typeof key === "string") { - key = forge3.util.createBuffer(key); - } else if (forge3.util.isArray(key)) { - var tmp = key; - key = forge3.util.createBuffer(); - for (var i = 0; i < tmp.length; ++i) { - key.putByte(tmp[i]); - } - } - var keylen = key.length(); - if (keylen > _md.blockLength) { - _md.start(); - _md.update(key.bytes()); - key = _md.digest(); - } - _ipadding = forge3.util.createBuffer(); - _opadding = forge3.util.createBuffer(); - keylen = key.length(); - for (var i = 0; i < keylen; ++i) { - var tmp = key.at(i); - _ipadding.putByte(54 ^ tmp); - _opadding.putByte(92 ^ tmp); - } - if (keylen < _md.blockLength) { - var tmp = _md.blockLength - keylen; - for (var i = 0; i < tmp; ++i) { - _ipadding.putByte(54); - _opadding.putByte(92); - } - } - _key = key; - _ipadding = _ipadding.bytes(); - _opadding = _opadding.bytes(); - } - _md.start(); - _md.update(_ipadding); - }; - ctx.update = function(bytes) { - _md.update(bytes); - }; - ctx.getMac = function() { - var inner = _md.digest().bytes(); - _md.start(); - _md.update(_opadding); - _md.update(inner); - return _md.digest(); - }; - ctx.digest = ctx.getMac; - return ctx; - }; - } -}); - -// node_modules/node-forge/lib/md5.js -var require_md5 = __commonJS({ - "node_modules/node-forge/lib/md5.js"(exports, module) { - var forge3 = require_forge(); - require_md(); - require_util(); - var md5 = module.exports = forge3.md5 = forge3.md5 || {}; - forge3.md.md5 = forge3.md.algorithms.md5 = md5; - md5.create = function() { - if (!_initialized) { - _init(); - } - var _state = null; - var _input = forge3.util.createBuffer(); - var _w = new Array(16); - var md = { - algorithm: "md5", - blockLength: 64, - digestLength: 16, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; - md.start = function() { - md.messageLength = 0; - md.fullMessageLength = md.messageLength64 = []; - var int32s = md.messageLengthSize / 4; - for (var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); - } - _input = forge3.util.createBuffer(); - _state = { - h0: 1732584193, - h1: 4023233417, - h2: 2562383102, - h3: 271733878 - }; - return md; - }; - md.start(); - md.update = function(msg, encoding) { - if (encoding === "utf8") { - msg = forge3.util.encodeUtf8(msg); - } - var len = msg.length; - md.messageLength += len; - len = [len / 4294967296 >>> 0, len >>> 0]; - for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + (md.fullMessageLength[i] / 4294967296 >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = len[1] / 4294967296 >>> 0; - } - _input.putBytes(msg); - _update(_state, _w, _input); - if (_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - return md; - }; - md.digest = function() { - var finalBlock = forge3.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; - var overflow = remaining & md.blockLength - 1; - finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); - var bits, carry = 0; - for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { - bits = md.fullMessageLength[i] * 8 + carry; - carry = bits / 4294967296 >>> 0; - finalBlock.putInt32Le(bits >>> 0); - } - var s2 = { - h0: _state.h0, - h1: _state.h1, - h2: _state.h2, - h3: _state.h3 - }; - _update(s2, _w, finalBlock); - var rval = forge3.util.createBuffer(); - rval.putInt32Le(s2.h0); - rval.putInt32Le(s2.h1); - rval.putInt32Le(s2.h2); - rval.putInt32Le(s2.h3); - return rval; - }; - return md; - }; - var _padding = null; - var _g = null; - var _r = null; - var _k = null; - var _initialized = false; - function _init() { - _padding = String.fromCharCode(128); - _padding += forge3.util.fillString(String.fromCharCode(0), 64); - _g = [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 1, - 6, - 11, - 0, - 5, - 10, - 15, - 4, - 9, - 14, - 3, - 8, - 13, - 2, - 7, - 12, - 5, - 8, - 11, - 14, - 1, - 4, - 7, - 10, - 13, - 0, - 3, - 6, - 9, - 12, - 15, - 2, - 0, - 7, - 14, - 5, - 12, - 3, - 10, - 1, - 8, - 15, - 6, - 13, - 4, - 11, - 2, - 9 - ]; - _r = [ - 7, - 12, - 17, - 22, - 7, - 12, - 17, - 22, - 7, - 12, - 17, - 22, - 7, - 12, - 17, - 22, - 5, - 9, - 14, - 20, - 5, - 9, - 14, - 20, - 5, - 9, - 14, - 20, - 5, - 9, - 14, - 20, - 4, - 11, - 16, - 23, - 4, - 11, - 16, - 23, - 4, - 11, - 16, - 23, - 4, - 11, - 16, - 23, - 6, - 10, - 15, - 21, - 6, - 10, - 15, - 21, - 6, - 10, - 15, - 21, - 6, - 10, - 15, - 21 - ]; - _k = new Array(64); - for (var i = 0; i < 64; ++i) { - _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296); - } - _initialized = true; - } - function _update(s, w, bytes) { - var t, a, b, c, d, f, r, i; - var len = bytes.length(); - while (len >= 64) { - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; - for (i = 0; i < 16; ++i) { - w[i] = bytes.getInt32Le(); - f = d ^ b & (c ^ d); - t = a + f + _k[i] + w[i]; - r = _r[i]; - a = d; - d = c; - c = b; - b += t << r | t >>> 32 - r; - } - for (; i < 32; ++i) { - f = c ^ d & (b ^ c); - t = a + f + _k[i] + w[_g[i]]; - r = _r[i]; - a = d; - d = c; - c = b; - b += t << r | t >>> 32 - r; - } - for (; i < 48; ++i) { - f = b ^ c ^ d; - t = a + f + _k[i] + w[_g[i]]; - r = _r[i]; - a = d; - d = c; - c = b; - b += t << r | t >>> 32 - r; - } - for (; i < 64; ++i) { - f = c ^ (b | ~d); - t = a + f + _k[i] + w[_g[i]]; - r = _r[i]; - a = d; - d = c; - c = b; - b += t << r | t >>> 32 - r; - } - s.h0 = s.h0 + a | 0; - s.h1 = s.h1 + b | 0; - s.h2 = s.h2 + c | 0; - s.h3 = s.h3 + d | 0; - len -= 64; - } - } - } -}); - -// node_modules/node-forge/lib/pem.js -var require_pem = __commonJS({ - "node_modules/node-forge/lib/pem.js"(exports, module) { - var forge3 = require_forge(); - require_util(); - var pem = module.exports = forge3.pem = forge3.pem || {}; - pem.encode = function(msg, options) { - options = options || {}; - var rval = "-----BEGIN " + msg.type + "-----\r\n"; - var header; - if (msg.procType) { - header = { - name: "Proc-Type", - values: [String(msg.procType.version), msg.procType.type] - }; - rval += foldHeader(header); - } - if (msg.contentDomain) { - header = { name: "Content-Domain", values: [msg.contentDomain] }; - rval += foldHeader(header); - } - if (msg.dekInfo) { - header = { name: "DEK-Info", values: [msg.dekInfo.algorithm] }; - if (msg.dekInfo.parameters) { - header.values.push(msg.dekInfo.parameters); - } - rval += foldHeader(header); - } - if (msg.headers) { - for (var i = 0; i < msg.headers.length; ++i) { - rval += foldHeader(msg.headers[i]); - } - } - if (msg.procType) { - rval += "\r\n"; - } - rval += forge3.util.encode64(msg.body, options.maxline || 64) + "\r\n"; - rval += "-----END " + msg.type + "-----\r\n"; - return rval; - }; - pem.decode = function(str) { - var rval = []; - var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g; - var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/; - var rCRLF = /\r?\n/; - var match; - while (true) { - match = rMessage.exec(str); - if (!match) { - break; - } - var type = match[1]; - if (type === "NEW CERTIFICATE REQUEST") { - type = "CERTIFICATE REQUEST"; - } - var msg = { - type, - procType: null, - contentDomain: null, - dekInfo: null, - headers: [], - body: forge3.util.decode64(match[3]) - }; - rval.push(msg); - if (!match[2]) { - continue; - } - var lines = match[2].split(rCRLF); - var li = 0; - while (match && li < lines.length) { - var line = lines[li].replace(/\s+$/, ""); - for (var nl = li + 1; nl < lines.length; ++nl) { - var next = lines[nl]; - if (!/\s/.test(next[0])) { - break; - } - line += next; - li = nl; - } - match = line.match(rHeader); - if (match) { - var header = { name: match[1], values: [] }; - var values = match[2].split(","); - for (var vi = 0; vi < values.length; ++vi) { - header.values.push(ltrim(values[vi])); - } - if (!msg.procType) { - if (header.name !== "Proc-Type") { - throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".'); - } else if (header.values.length !== 2) { - throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.'); - } - msg.procType = { version: values[0], type: values[1] }; - } else if (!msg.contentDomain && header.name === "Content-Domain") { - msg.contentDomain = values[0] || ""; - } else if (!msg.dekInfo && header.name === "DEK-Info") { - if (header.values.length === 0) { - throw new Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.'); - } - msg.dekInfo = { algorithm: values[0], parameters: values[1] || null }; - } else { - msg.headers.push(header); - } - } - ++li; - } - if (msg.procType === "ENCRYPTED" && !msg.dekInfo) { - throw new Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".'); - } - } - if (rval.length === 0) { - throw new Error("Invalid PEM formatted message."); - } - return rval; - }; - function foldHeader(header) { - var rval = header.name + ": "; - var values = []; - var insertSpace = function(match, $1) { - return " " + $1; - }; - for (var i = 0; i < header.values.length; ++i) { - values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace)); - } - rval += values.join(",") + "\r\n"; - var length = 0; - var candidate = -1; - for (var i = 0; i < rval.length; ++i, ++length) { - if (length > 65 && candidate !== -1) { - var insert = rval[candidate]; - if (insert === ",") { - ++candidate; - rval = rval.substr(0, candidate) + "\r\n " + rval.substr(candidate); - } else { - rval = rval.substr(0, candidate) + "\r\n" + insert + rval.substr(candidate + 1); - } - length = i - candidate - 1; - candidate = -1; - ++i; - } else if (rval[i] === " " || rval[i] === " " || rval[i] === ",") { - candidate = i; - } - } - return rval; - } - function ltrim(str) { - return str.replace(/^\s+/, ""); - } - } -}); - -// node_modules/node-forge/lib/des.js -var require_des = __commonJS({ - "node_modules/node-forge/lib/des.js"(exports, module) { - var forge3 = require_forge(); - require_cipher(); - require_cipherModes(); - require_util(); - module.exports = forge3.des = forge3.des || {}; - forge3.des.startEncrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key, - output, - decrypt: false, - mode: mode || (iv === null ? "ECB" : "CBC") - }); - cipher.start(iv); - return cipher; - }; - forge3.des.createEncryptionCipher = function(key, mode) { - return _createCipher({ - key, - output: null, - decrypt: false, - mode - }); - }; - forge3.des.startDecrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key, - output, - decrypt: true, - mode: mode || (iv === null ? "ECB" : "CBC") - }); - cipher.start(iv); - return cipher; - }; - forge3.des.createDecryptionCipher = function(key, mode) { - return _createCipher({ - key, - output: null, - decrypt: true, - mode - }); - }; - forge3.des.Algorithm = function(name, mode) { - var self2 = this; - self2.name = name; - self2.mode = new mode({ - blockSize: 8, - cipher: { - encrypt: function(inBlock, outBlock) { - return _updateBlock(self2._keys, inBlock, outBlock, false); - }, - decrypt: function(inBlock, outBlock) { - return _updateBlock(self2._keys, inBlock, outBlock, true); - } - } - }); - self2._init = false; - }; - forge3.des.Algorithm.prototype.initialize = function(options) { - if (this._init) { - return; - } - var key = forge3.util.createBuffer(options.key); - if (this.name.indexOf("3DES") === 0) { - if (key.length() !== 24) { - throw new Error("Invalid Triple-DES key size: " + key.length() * 8); - } - } - this._keys = _createKeys(key); - this._init = true; - }; - registerAlgorithm("DES-ECB", forge3.cipher.modes.ecb); - registerAlgorithm("DES-CBC", forge3.cipher.modes.cbc); - registerAlgorithm("DES-CFB", forge3.cipher.modes.cfb); - registerAlgorithm("DES-OFB", forge3.cipher.modes.ofb); - registerAlgorithm("DES-CTR", forge3.cipher.modes.ctr); - registerAlgorithm("3DES-ECB", forge3.cipher.modes.ecb); - registerAlgorithm("3DES-CBC", forge3.cipher.modes.cbc); - registerAlgorithm("3DES-CFB", forge3.cipher.modes.cfb); - registerAlgorithm("3DES-OFB", forge3.cipher.modes.ofb); - registerAlgorithm("3DES-CTR", forge3.cipher.modes.ctr); - function registerAlgorithm(name, mode) { - var factory = function() { - return new forge3.des.Algorithm(name, mode); - }; - forge3.cipher.registerAlgorithm(name, factory); - } - var spfunction1 = [16843776, 0, 65536, 16843780, 16842756, 66564, 4, 65536, 1024, 16843776, 16843780, 1024, 16778244, 16842756, 16777216, 4, 1028, 16778240, 16778240, 66560, 66560, 16842752, 16842752, 16778244, 65540, 16777220, 16777220, 65540, 0, 1028, 66564, 16777216, 65536, 16843780, 4, 16842752, 16843776, 16777216, 16777216, 1024, 16842756, 65536, 66560, 16777220, 1024, 4, 16778244, 66564, 16843780, 65540, 16842752, 16778244, 16777220, 1028, 66564, 16843776, 1028, 16778240, 16778240, 0, 65540, 66560, 0, 16842756]; - var spfunction2 = [-2146402272, -2147450880, 32768, 1081376, 1048576, 32, -2146435040, -2147450848, -2147483616, -2146402272, -2146402304, -2147483648, -2147450880, 1048576, 32, -2146435040, 1081344, 1048608, -2147450848, 0, -2147483648, 32768, 1081376, -2146435072, 1048608, -2147483616, 0, 1081344, 32800, -2146402304, -2146435072, 32800, 0, 1081376, -2146435040, 1048576, -2147450848, -2146435072, -2146402304, 32768, -2146435072, -2147450880, 32, -2146402272, 1081376, 32, 32768, -2147483648, 32800, -2146402304, 1048576, -2147483616, 1048608, -2147450848, -2147483616, 1048608, 1081344, 0, -2147450880, 32800, -2147483648, -2146435040, -2146402272, 1081344]; - var spfunction3 = [520, 134349312, 0, 134348808, 134218240, 0, 131592, 134218240, 131080, 134217736, 134217736, 131072, 134349320, 131080, 134348800, 520, 134217728, 8, 134349312, 512, 131584, 134348800, 134348808, 131592, 134218248, 131584, 131072, 134218248, 8, 134349320, 512, 134217728, 134349312, 134217728, 131080, 520, 131072, 134349312, 134218240, 0, 512, 131080, 134349320, 134218240, 134217736, 512, 0, 134348808, 134218248, 131072, 134217728, 134349320, 8, 131592, 131584, 134217736, 134348800, 134218248, 520, 134348800, 131592, 8, 134348808, 131584]; - var spfunction4 = [8396801, 8321, 8321, 128, 8396928, 8388737, 8388609, 8193, 0, 8396800, 8396800, 8396929, 129, 0, 8388736, 8388609, 1, 8192, 8388608, 8396801, 128, 8388608, 8193, 8320, 8388737, 1, 8320, 8388736, 8192, 8396928, 8396929, 129, 8388736, 8388609, 8396800, 8396929, 129, 0, 0, 8396800, 8320, 8388736, 8388737, 1, 8396801, 8321, 8321, 128, 8396929, 129, 1, 8192, 8388609, 8193, 8396928, 8388737, 8193, 8320, 8388608, 8396801, 128, 8388608, 8192, 8396928]; - var spfunction5 = [256, 34078976, 34078720, 1107296512, 524288, 256, 1073741824, 34078720, 1074266368, 524288, 33554688, 1074266368, 1107296512, 1107820544, 524544, 1073741824, 33554432, 1074266112, 1074266112, 0, 1073742080, 1107820800, 1107820800, 33554688, 1107820544, 1073742080, 0, 1107296256, 34078976, 33554432, 1107296256, 524544, 524288, 1107296512, 256, 33554432, 1073741824, 34078720, 1107296512, 1074266368, 33554688, 1073741824, 1107820544, 34078976, 1074266368, 256, 33554432, 1107820544, 1107820800, 524544, 1107296256, 1107820800, 34078720, 0, 1074266112, 1107296256, 524544, 33554688, 1073742080, 524288, 0, 1074266112, 34078976, 1073742080]; - var spfunction6 = [536870928, 541065216, 16384, 541081616, 541065216, 16, 541081616, 4194304, 536887296, 4210704, 4194304, 536870928, 4194320, 536887296, 536870912, 16400, 0, 4194320, 536887312, 16384, 4210688, 536887312, 16, 541065232, 541065232, 0, 4210704, 541081600, 16400, 4210688, 541081600, 536870912, 536887296, 16, 541065232, 4210688, 541081616, 4194304, 16400, 536870928, 4194304, 536887296, 536870912, 16400, 536870928, 541081616, 4210688, 541065216, 4210704, 541081600, 0, 541065232, 16, 16384, 541065216, 4210704, 16384, 4194320, 536887312, 0, 541081600, 536870912, 4194320, 536887312]; - var spfunction7 = [2097152, 69206018, 67110914, 0, 2048, 67110914, 2099202, 69208064, 69208066, 2097152, 0, 67108866, 2, 67108864, 69206018, 2050, 67110912, 2099202, 2097154, 67110912, 67108866, 69206016, 69208064, 2097154, 69206016, 2048, 2050, 69208066, 2099200, 2, 67108864, 2099200, 67108864, 2099200, 2097152, 67110914, 67110914, 69206018, 69206018, 2, 2097154, 67108864, 67110912, 2097152, 69208064, 2050, 2099202, 69208064, 2050, 67108866, 69208066, 69206016, 2099200, 0, 2, 69208066, 0, 2099202, 69206016, 2048, 67108866, 67110912, 2048, 2097154]; - var spfunction8 = [268439616, 4096, 262144, 268701760, 268435456, 268439616, 64, 268435456, 262208, 268697600, 268701760, 266240, 268701696, 266304, 4096, 64, 268697600, 268435520, 268439552, 4160, 266240, 262208, 268697664, 268701696, 4160, 0, 0, 268697664, 268435520, 268439552, 266304, 262144, 266304, 262144, 268701696, 4096, 64, 268697664, 4096, 266304, 268439552, 64, 268435520, 268697600, 268697664, 268435456, 262144, 268439616, 0, 268701760, 262208, 268435520, 268697600, 268439552, 268439616, 0, 268701760, 266240, 266240, 4160, 4160, 262208, 268435456, 268701696]; - function _createKeys(key) { - var pc2bytes0 = [0, 4, 536870912, 536870916, 65536, 65540, 536936448, 536936452, 512, 516, 536871424, 536871428, 66048, 66052, 536936960, 536936964], pc2bytes1 = [0, 1, 1048576, 1048577, 67108864, 67108865, 68157440, 68157441, 256, 257, 1048832, 1048833, 67109120, 67109121, 68157696, 68157697], pc2bytes2 = [0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272, 0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272], pc2bytes3 = [0, 2097152, 134217728, 136314880, 8192, 2105344, 134225920, 136323072, 131072, 2228224, 134348800, 136445952, 139264, 2236416, 134356992, 136454144], pc2bytes4 = [0, 262144, 16, 262160, 0, 262144, 16, 262160, 4096, 266240, 4112, 266256, 4096, 266240, 4112, 266256], pc2bytes5 = [0, 1024, 32, 1056, 0, 1024, 32, 1056, 33554432, 33555456, 33554464, 33555488, 33554432, 33555456, 33554464, 33555488], pc2bytes6 = [0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746, 0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746], pc2bytes7 = [0, 65536, 2048, 67584, 536870912, 536936448, 536872960, 536938496, 131072, 196608, 133120, 198656, 537001984, 537067520, 537004032, 537069568], pc2bytes8 = [0, 262144, 0, 262144, 2, 262146, 2, 262146, 33554432, 33816576, 33554432, 33816576, 33554434, 33816578, 33554434, 33816578], pc2bytes9 = [0, 268435456, 8, 268435464, 0, 268435456, 8, 268435464, 1024, 268436480, 1032, 268436488, 1024, 268436480, 1032, 268436488], pc2bytes10 = [0, 32, 0, 32, 1048576, 1048608, 1048576, 1048608, 8192, 8224, 8192, 8224, 1056768, 1056800, 1056768, 1056800], pc2bytes11 = [0, 16777216, 512, 16777728, 2097152, 18874368, 2097664, 18874880, 67108864, 83886080, 67109376, 83886592, 69206016, 85983232, 69206528, 85983744], pc2bytes12 = [0, 4096, 134217728, 134221824, 524288, 528384, 134742016, 134746112, 16, 4112, 134217744, 134221840, 524304, 528400, 134742032, 134746128], pc2bytes13 = [0, 4, 256, 260, 0, 4, 256, 260, 1, 5, 257, 261, 1, 5, 257, 261]; - var iterations = key.length() > 8 ? 3 : 1; - var keys = []; - var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; - var n = 0, tmp; - for (var j = 0; j < iterations; j++) { - var left = key.getInt32(); - var right = key.getInt32(); - tmp = (left >>> 4 ^ right) & 252645135; - right ^= tmp; - left ^= tmp << 4; - tmp = (right >>> -16 ^ left) & 65535; - left ^= tmp; - right ^= tmp << -16; - tmp = (left >>> 2 ^ right) & 858993459; - right ^= tmp; - left ^= tmp << 2; - tmp = (right >>> -16 ^ left) & 65535; - left ^= tmp; - right ^= tmp << -16; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - tmp = (right >>> 8 ^ left) & 16711935; - left ^= tmp; - right ^= tmp << 8; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - tmp = left << 8 | right >>> 20 & 240; - left = right << 24 | right << 8 & 16711680 | right >>> 8 & 65280 | right >>> 24 & 240; - right = tmp; - for (var i = 0; i < shifts.length; ++i) { - if (shifts[i]) { - left = left << 2 | left >>> 26; - right = right << 2 | right >>> 26; - } else { - left = left << 1 | left >>> 27; - right = right << 1 | right >>> 27; - } - left &= -15; - right &= -15; - var lefttmp = pc2bytes0[left >>> 28] | pc2bytes1[left >>> 24 & 15] | pc2bytes2[left >>> 20 & 15] | pc2bytes3[left >>> 16 & 15] | pc2bytes4[left >>> 12 & 15] | pc2bytes5[left >>> 8 & 15] | pc2bytes6[left >>> 4 & 15]; - var righttmp = pc2bytes7[right >>> 28] | pc2bytes8[right >>> 24 & 15] | pc2bytes9[right >>> 20 & 15] | pc2bytes10[right >>> 16 & 15] | pc2bytes11[right >>> 12 & 15] | pc2bytes12[right >>> 8 & 15] | pc2bytes13[right >>> 4 & 15]; - tmp = (righttmp >>> 16 ^ lefttmp) & 65535; - keys[n++] = lefttmp ^ tmp; - keys[n++] = righttmp ^ tmp << 16; - } - } - return keys; - } - function _updateBlock(keys, input, output, decrypt) { - var iterations = keys.length === 32 ? 3 : 9; - var looping; - if (iterations === 3) { - looping = decrypt ? [30, -2, -2] : [0, 32, 2]; - } else { - looping = decrypt ? [94, 62, -2, 32, 64, 2, 30, -2, -2] : [0, 32, 2, 62, 30, -2, 64, 96, 2]; - } - var tmp; - var left = input[0]; - var right = input[1]; - tmp = (left >>> 4 ^ right) & 252645135; - right ^= tmp; - left ^= tmp << 4; - tmp = (left >>> 16 ^ right) & 65535; - right ^= tmp; - left ^= tmp << 16; - tmp = (right >>> 2 ^ left) & 858993459; - left ^= tmp; - right ^= tmp << 2; - tmp = (right >>> 8 ^ left) & 16711935; - left ^= tmp; - right ^= tmp << 8; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - left = left << 1 | left >>> 31; - right = right << 1 | right >>> 31; - for (var j = 0; j < iterations; j += 3) { - var endloop = looping[j + 1]; - var loopinc = looping[j + 2]; - for (var i = looping[j]; i != endloop; i += loopinc) { - var right1 = right ^ keys[i]; - var right2 = (right >>> 4 | right << 28) ^ keys[i + 1]; - tmp = left; - left = right; - right = tmp ^ (spfunction2[right1 >>> 24 & 63] | spfunction4[right1 >>> 16 & 63] | spfunction6[right1 >>> 8 & 63] | spfunction8[right1 & 63] | spfunction1[right2 >>> 24 & 63] | spfunction3[right2 >>> 16 & 63] | spfunction5[right2 >>> 8 & 63] | spfunction7[right2 & 63]); - } - tmp = left; - left = right; - right = tmp; - } - left = left >>> 1 | left << 31; - right = right >>> 1 | right << 31; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - tmp = (right >>> 8 ^ left) & 16711935; - left ^= tmp; - right ^= tmp << 8; - tmp = (right >>> 2 ^ left) & 858993459; - left ^= tmp; - right ^= tmp << 2; - tmp = (left >>> 16 ^ right) & 65535; - right ^= tmp; - left ^= tmp << 16; - tmp = (left >>> 4 ^ right) & 252645135; - right ^= tmp; - left ^= tmp << 4; - output[0] = left; - output[1] = right; - } - function _createCipher(options) { - options = options || {}; - var mode = (options.mode || "CBC").toUpperCase(); - var algorithm = "DES-" + mode; - var cipher; - if (options.decrypt) { - cipher = forge3.cipher.createDecipher(algorithm, options.key); - } else { - cipher = forge3.cipher.createCipher(algorithm, options.key); - } - var start = cipher.start; - cipher.start = function(iv, options2) { - var output = null; - if (options2 instanceof forge3.util.ByteBuffer) { - output = options2; - options2 = {}; - } - options2 = options2 || {}; - options2.output = output; - options2.iv = iv; - start.call(cipher, options2); - }; - return cipher; - } - } -}); - -// node_modules/node-forge/lib/pbkdf2.js -var require_pbkdf2 = __commonJS({ - "node_modules/node-forge/lib/pbkdf2.js"(exports, module) { - var forge3 = require_forge(); - require_hmac(); - require_md(); - require_util(); - var pkcs5 = forge3.pkcs5 = forge3.pkcs5 || {}; - var crypto; - if (forge3.util.isNodejs && !forge3.options.usePureJavaScript) { - crypto = __require("crypto"); - } - module.exports = forge3.pbkdf2 = pkcs5.pbkdf2 = function(p, s, c, dkLen, md, callback) { - if (typeof md === "function") { - callback = md; - md = null; - } - if (forge3.util.isNodejs && !forge3.options.usePureJavaScript && crypto.pbkdf2 && (md === null || typeof md !== "object") && (crypto.pbkdf2Sync.length > 4 || (!md || md === "sha1"))) { - if (typeof md !== "string") { - md = "sha1"; - } - p = Buffer.from(p, "binary"); - s = Buffer.from(s, "binary"); - if (!callback) { - if (crypto.pbkdf2Sync.length === 4) { - return crypto.pbkdf2Sync(p, s, c, dkLen).toString("binary"); - } - return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString("binary"); - } - if (crypto.pbkdf2Sync.length === 4) { - return crypto.pbkdf2(p, s, c, dkLen, function(err2, key) { - if (err2) { - return callback(err2); - } - callback(null, key.toString("binary")); - }); - } - return crypto.pbkdf2(p, s, c, dkLen, md, function(err2, key) { - if (err2) { - return callback(err2); - } - callback(null, key.toString("binary")); - }); - } - if (typeof md === "undefined" || md === null) { - md = "sha1"; - } - if (typeof md === "string") { - if (!(md in forge3.md.algorithms)) { - throw new Error("Unknown hash algorithm: " + md); - } - md = forge3.md[md].create(); - } - var hLen = md.digestLength; - if (dkLen > 4294967295 * hLen) { - var err = new Error("Derived key is too long."); - if (callback) { - return callback(err); - } - throw err; - } - var len = Math.ceil(dkLen / hLen); - var r = dkLen - (len - 1) * hLen; - var prf = forge3.hmac.create(); - prf.start(md, p); - var dk = ""; - var xor, u_c, u_c1; - if (!callback) { - for (var i = 1; i <= len; ++i) { - prf.start(null, null); - prf.update(s); - prf.update(forge3.util.int32ToBytes(i)); - xor = u_c1 = prf.digest().getBytes(); - for (var j = 2; j <= c; ++j) { - prf.start(null, null); - prf.update(u_c1); - u_c = prf.digest().getBytes(); - xor = forge3.util.xorBytes(xor, u_c, hLen); - u_c1 = u_c; - } - dk += i < len ? xor : xor.substr(0, r); - } - return dk; - } - var i = 1, j; - function outer() { - if (i > len) { - return callback(null, dk); - } - prf.start(null, null); - prf.update(s); - prf.update(forge3.util.int32ToBytes(i)); - xor = u_c1 = prf.digest().getBytes(); - j = 2; - inner(); - } - function inner() { - if (j <= c) { - prf.start(null, null); - prf.update(u_c1); - u_c = prf.digest().getBytes(); - xor = forge3.util.xorBytes(xor, u_c, hLen); - u_c1 = u_c; - ++j; - return forge3.util.setImmediate(inner); - } - dk += i < len ? xor : xor.substr(0, r); - ++i; - outer(); - } - outer(); - }; - } -}); - -// node_modules/node-forge/lib/sha256.js -var require_sha256 = __commonJS({ - "node_modules/node-forge/lib/sha256.js"(exports, module) { - var forge3 = require_forge(); - require_md(); - require_util(); - var sha256 = module.exports = forge3.sha256 = forge3.sha256 || {}; - forge3.md.sha256 = forge3.md.algorithms.sha256 = sha256; - sha256.create = function() { - if (!_initialized) { - _init(); - } - var _state = null; - var _input = forge3.util.createBuffer(); - var _w = new Array(64); - var md = { - algorithm: "sha256", - blockLength: 64, - digestLength: 32, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; - md.start = function() { - md.messageLength = 0; - md.fullMessageLength = md.messageLength64 = []; - var int32s = md.messageLengthSize / 4; - for (var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); - } - _input = forge3.util.createBuffer(); - _state = { - h0: 1779033703, - h1: 3144134277, - h2: 1013904242, - h3: 2773480762, - h4: 1359893119, - h5: 2600822924, - h6: 528734635, - h7: 1541459225 - }; - return md; - }; - md.start(); - md.update = function(msg, encoding) { - if (encoding === "utf8") { - msg = forge3.util.encodeUtf8(msg); - } - var len = msg.length; - md.messageLength += len; - len = [len / 4294967296 >>> 0, len >>> 0]; - for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + (md.fullMessageLength[i] / 4294967296 >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = len[1] / 4294967296 >>> 0; - } - _input.putBytes(msg); - _update(_state, _w, _input); - if (_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - return md; - }; - md.digest = function() { - var finalBlock = forge3.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; - var overflow = remaining & md.blockLength - 1; - finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); - var next, carry; - var bits = md.fullMessageLength[0] * 8; - for (var i = 0; i < md.fullMessageLength.length - 1; ++i) { - next = md.fullMessageLength[i + 1] * 8; - carry = next / 4294967296 >>> 0; - bits += carry; - finalBlock.putInt32(bits >>> 0); - bits = next >>> 0; - } - finalBlock.putInt32(bits); - var s2 = { - h0: _state.h0, - h1: _state.h1, - h2: _state.h2, - h3: _state.h3, - h4: _state.h4, - h5: _state.h5, - h6: _state.h6, - h7: _state.h7 - }; - _update(s2, _w, finalBlock); - var rval = forge3.util.createBuffer(); - rval.putInt32(s2.h0); - rval.putInt32(s2.h1); - rval.putInt32(s2.h2); - rval.putInt32(s2.h3); - rval.putInt32(s2.h4); - rval.putInt32(s2.h5); - rval.putInt32(s2.h6); - rval.putInt32(s2.h7); - return rval; - }; - return md; - }; - var _padding = null; - var _initialized = false; - var _k = null; - function _init() { - _padding = String.fromCharCode(128); - _padding += forge3.util.fillString(String.fromCharCode(0), 64); - _k = [ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 - ]; - _initialized = true; - } - function _update(s, w, bytes) { - var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h; - var len = bytes.length(); - while (len >= 64) { - for (i = 0; i < 16; ++i) { - w[i] = bytes.getInt32(); - } - for (; i < 64; ++i) { - t1 = w[i - 2]; - t1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10; - t2 = w[i - 15]; - t2 = (t2 >>> 7 | t2 << 25) ^ (t2 >>> 18 | t2 << 14) ^ t2 >>> 3; - w[i] = t1 + w[i - 7] + t2 + w[i - 16] | 0; - } - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; - e = s.h4; - f = s.h5; - g = s.h6; - h = s.h7; - for (i = 0; i < 64; ++i) { - s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7); - ch = g ^ e & (f ^ g); - s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); - maj = a & b | c & (a ^ b); - t1 = h + s1 + ch + _k[i] + w[i]; - t2 = s0 + maj; - h = g; - g = f; - f = e; - e = d + t1 >>> 0; - d = c; - c = b; - b = a; - a = t1 + t2 >>> 0; - } - s.h0 = s.h0 + a | 0; - s.h1 = s.h1 + b | 0; - s.h2 = s.h2 + c | 0; - s.h3 = s.h3 + d | 0; - s.h4 = s.h4 + e | 0; - s.h5 = s.h5 + f | 0; - s.h6 = s.h6 + g | 0; - s.h7 = s.h7 + h | 0; - len -= 64; - } - } - } -}); - -// node_modules/node-forge/lib/prng.js -var require_prng = __commonJS({ - "node_modules/node-forge/lib/prng.js"(exports, module) { - var forge3 = require_forge(); - require_util(); - var _crypto = null; - if (forge3.util.isNodejs && !forge3.options.usePureJavaScript && !process.versions["node-webkit"]) { - _crypto = __require("crypto"); - } - var prng = module.exports = forge3.prng = forge3.prng || {}; - prng.create = function(plugin) { - var ctx = { - plugin, - key: null, - seed: null, - time: null, - // number of reseeds so far - reseeds: 0, - // amount of data generated so far - generated: 0, - // no initial key bytes - keyBytes: "" - }; - var md = plugin.md; - var pools = new Array(32); - for (var i = 0; i < 32; ++i) { - pools[i] = md.create(); - } - ctx.pools = pools; - ctx.pool = 0; - ctx.generate = function(count, callback) { - if (!callback) { - return ctx.generateSync(count); - } - var cipher = ctx.plugin.cipher; - var increment = ctx.plugin.increment; - var formatKey = ctx.plugin.formatKey; - var formatSeed = ctx.plugin.formatSeed; - var b = forge3.util.createBuffer(); - ctx.key = null; - generate(); - function generate(err) { - if (err) { - return callback(err); - } - if (b.length() >= count) { - return callback(null, b.getBytes(count)); - } - if (ctx.generated > 1048575) { - ctx.key = null; - } - if (ctx.key === null) { - return forge3.util.nextTick(function() { - _reseed(generate); - }); - } - var bytes = cipher(ctx.key, ctx.seed); - ctx.generated += bytes.length; - b.putBytes(bytes); - ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); - ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); - forge3.util.setImmediate(generate); - } - }; - ctx.generateSync = function(count) { - var cipher = ctx.plugin.cipher; - var increment = ctx.plugin.increment; - var formatKey = ctx.plugin.formatKey; - var formatSeed = ctx.plugin.formatSeed; - ctx.key = null; - var b = forge3.util.createBuffer(); - while (b.length() < count) { - if (ctx.generated > 1048575) { - ctx.key = null; - } - if (ctx.key === null) { - _reseedSync(); - } - var bytes = cipher(ctx.key, ctx.seed); - ctx.generated += bytes.length; - b.putBytes(bytes); - ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); - ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); - } - return b.getBytes(count); - }; - function _reseed(callback) { - if (ctx.pools[0].messageLength >= 32) { - _seed(); - return callback(); - } - var needed = 32 - ctx.pools[0].messageLength << 5; - ctx.seedFile(needed, function(err, bytes) { - if (err) { - return callback(err); - } - ctx.collect(bytes); - _seed(); - callback(); - }); - } - function _reseedSync() { - if (ctx.pools[0].messageLength >= 32) { - return _seed(); - } - var needed = 32 - ctx.pools[0].messageLength << 5; - ctx.collect(ctx.seedFileSync(needed)); - _seed(); - } - function _seed() { - ctx.reseeds = ctx.reseeds === 4294967295 ? 0 : ctx.reseeds + 1; - var md2 = ctx.plugin.md.create(); - md2.update(ctx.keyBytes); - var _2powK = 1; - for (var k = 0; k < 32; ++k) { - if (ctx.reseeds % _2powK === 0) { - md2.update(ctx.pools[k].digest().getBytes()); - ctx.pools[k].start(); - } - _2powK = _2powK << 1; - } - ctx.keyBytes = md2.digest().getBytes(); - md2.start(); - md2.update(ctx.keyBytes); - var seedBytes = md2.digest().getBytes(); - ctx.key = ctx.plugin.formatKey(ctx.keyBytes); - ctx.seed = ctx.plugin.formatSeed(seedBytes); - ctx.generated = 0; - } - function defaultSeedFile(needed) { - var getRandomValues = null; - var globalScope = forge3.util.globalScope; - var _crypto2 = globalScope.crypto || globalScope.msCrypto; - if (_crypto2 && _crypto2.getRandomValues) { - getRandomValues = function(arr) { - return _crypto2.getRandomValues(arr); - }; - } - var b = forge3.util.createBuffer(); - if (getRandomValues) { - while (b.length() < needed) { - var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4); - var entropy = new Uint32Array(Math.floor(count)); - try { - getRandomValues(entropy); - for (var i2 = 0; i2 < entropy.length; ++i2) { - b.putInt32(entropy[i2]); - } - } catch (e) { - if (!(typeof QuotaExceededError !== "undefined" && e instanceof QuotaExceededError)) { - throw e; - } - } - } - } - if (b.length() < needed) { - var hi, lo, next; - var seed = Math.floor(Math.random() * 65536); - while (b.length() < needed) { - lo = 16807 * (seed & 65535); - hi = 16807 * (seed >> 16); - lo += (hi & 32767) << 16; - lo += hi >> 15; - lo = (lo & 2147483647) + (lo >> 31); - seed = lo & 4294967295; - for (var i2 = 0; i2 < 3; ++i2) { - next = seed >>> (i2 << 3); - next ^= Math.floor(Math.random() * 256); - b.putByte(next & 255); - } - } - } - return b.getBytes(needed); - } - if (_crypto) { - ctx.seedFile = function(needed, callback) { - _crypto.randomBytes(needed, function(err, bytes) { - if (err) { - return callback(err); - } - callback(null, bytes.toString()); - }); - }; - ctx.seedFileSync = function(needed) { - return _crypto.randomBytes(needed).toString(); - }; - } else { - ctx.seedFile = function(needed, callback) { - try { - callback(null, defaultSeedFile(needed)); - } catch (e) { - callback(e); - } - }; - ctx.seedFileSync = defaultSeedFile; - } - ctx.collect = function(bytes) { - var count = bytes.length; - for (var i2 = 0; i2 < count; ++i2) { - ctx.pools[ctx.pool].update(bytes.substr(i2, 1)); - ctx.pool = ctx.pool === 31 ? 0 : ctx.pool + 1; - } - }; - ctx.collectInt = function(i2, n) { - var bytes = ""; - for (var x = 0; x < n; x += 8) { - bytes += String.fromCharCode(i2 >> x & 255); - } - ctx.collect(bytes); - }; - ctx.registerWorker = function(worker) { - if (worker === self) { - ctx.seedFile = function(needed, callback) { - function listener2(e) { - var data = e.data; - if (data.forge && data.forge.prng) { - self.removeEventListener("message", listener2); - callback(data.forge.prng.err, data.forge.prng.bytes); - } - } - self.addEventListener("message", listener2); - self.postMessage({ forge: { prng: { needed } } }); - }; - } else { - var listener = function(e) { - var data = e.data; - if (data.forge && data.forge.prng) { - ctx.seedFile(data.forge.prng.needed, function(err, bytes) { - worker.postMessage({ forge: { prng: { err, bytes } } }); - }); - } - }; - worker.addEventListener("message", listener); - } - }; - return ctx; - }; - } -}); - -// node_modules/node-forge/lib/random.js -var require_random = __commonJS({ - "node_modules/node-forge/lib/random.js"(exports, module) { - var forge3 = require_forge(); - require_aes(); - require_sha256(); - require_prng(); - require_util(); - (function() { - if (forge3.random && forge3.random.getBytes) { - module.exports = forge3.random; - return; - } - (function(jQuery2) { - var prng_aes = {}; - var _prng_aes_output = new Array(4); - var _prng_aes_buffer = forge3.util.createBuffer(); - prng_aes.formatKey = function(key2) { - var tmp = forge3.util.createBuffer(key2); - key2 = new Array(4); - key2[0] = tmp.getInt32(); - key2[1] = tmp.getInt32(); - key2[2] = tmp.getInt32(); - key2[3] = tmp.getInt32(); - return forge3.aes._expandKey(key2, false); - }; - prng_aes.formatSeed = function(seed) { - var tmp = forge3.util.createBuffer(seed); - seed = new Array(4); - seed[0] = tmp.getInt32(); - seed[1] = tmp.getInt32(); - seed[2] = tmp.getInt32(); - seed[3] = tmp.getInt32(); - return seed; - }; - prng_aes.cipher = function(key2, seed) { - forge3.aes._updateBlock(key2, seed, _prng_aes_output, false); - _prng_aes_buffer.putInt32(_prng_aes_output[0]); - _prng_aes_buffer.putInt32(_prng_aes_output[1]); - _prng_aes_buffer.putInt32(_prng_aes_output[2]); - _prng_aes_buffer.putInt32(_prng_aes_output[3]); - return _prng_aes_buffer.getBytes(); - }; - prng_aes.increment = function(seed) { - ++seed[3]; - return seed; - }; - prng_aes.md = forge3.md.sha256; - function spawnPrng() { - var ctx = forge3.prng.create(prng_aes); - ctx.getBytes = function(count, callback) { - return ctx.generate(count, callback); - }; - ctx.getBytesSync = function(count) { - return ctx.generate(count); - }; - return ctx; - } - var _ctx = spawnPrng(); - var getRandomValues = null; - var globalScope = forge3.util.globalScope; - var _crypto = globalScope.crypto || globalScope.msCrypto; - if (_crypto && _crypto.getRandomValues) { - getRandomValues = function(arr) { - return _crypto.getRandomValues(arr); - }; - } - if (forge3.options.usePureJavaScript || !forge3.util.isNodejs && !getRandomValues) { - if (typeof window === "undefined" || window.document === void 0) { - } - _ctx.collectInt(+/* @__PURE__ */ new Date(), 32); - if (typeof navigator !== "undefined") { - var _navBytes = ""; - for (var key in navigator) { - try { - if (typeof navigator[key] == "string") { - _navBytes += navigator[key]; - } - } catch (e) { - } - } - _ctx.collect(_navBytes); - _navBytes = null; - } - if (jQuery2) { - jQuery2().mousemove(function(e) { - _ctx.collectInt(e.clientX, 16); - _ctx.collectInt(e.clientY, 16); - }); - jQuery2().keypress(function(e) { - _ctx.collectInt(e.charCode, 8); - }); - } - } - if (!forge3.random) { - forge3.random = _ctx; - } else { - for (var key in _ctx) { - forge3.random[key] = _ctx[key]; - } - } - forge3.random.createInstance = spawnPrng; - module.exports = forge3.random; - })(typeof jQuery !== "undefined" ? jQuery : null); - })(); - } -}); - -// node_modules/node-forge/lib/rc2.js -var require_rc2 = __commonJS({ - "node_modules/node-forge/lib/rc2.js"(exports, module) { - var forge3 = require_forge(); - require_util(); - var piTable = [ - 217, - 120, - 249, - 196, - 25, - 221, - 181, - 237, - 40, - 233, - 253, - 121, - 74, - 160, - 216, - 157, - 198, - 126, - 55, - 131, - 43, - 118, - 83, - 142, - 98, - 76, - 100, - 136, - 68, - 139, - 251, - 162, - 23, - 154, - 89, - 245, - 135, - 179, - 79, - 19, - 97, - 69, - 109, - 141, - 9, - 129, - 125, - 50, - 189, - 143, - 64, - 235, - 134, - 183, - 123, - 11, - 240, - 149, - 33, - 34, - 92, - 107, - 78, - 130, - 84, - 214, - 101, - 147, - 206, - 96, - 178, - 28, - 115, - 86, - 192, - 20, - 167, - 140, - 241, - 220, - 18, - 117, - 202, - 31, - 59, - 190, - 228, - 209, - 66, - 61, - 212, - 48, - 163, - 60, - 182, - 38, - 111, - 191, - 14, - 218, - 70, - 105, - 7, - 87, - 39, - 242, - 29, - 155, - 188, - 148, - 67, - 3, - 248, - 17, - 199, - 246, - 144, - 239, - 62, - 231, - 6, - 195, - 213, - 47, - 200, - 102, - 30, - 215, - 8, - 232, - 234, - 222, - 128, - 82, - 238, - 247, - 132, - 170, - 114, - 172, - 53, - 77, - 106, - 42, - 150, - 26, - 210, - 113, - 90, - 21, - 73, - 116, - 75, - 159, - 208, - 94, - 4, - 24, - 164, - 236, - 194, - 224, - 65, - 110, - 15, - 81, - 203, - 204, - 36, - 145, - 175, - 80, - 161, - 244, - 112, - 57, - 153, - 124, - 58, - 133, - 35, - 184, - 180, - 122, - 252, - 2, - 54, - 91, - 37, - 85, - 151, - 49, - 45, - 93, - 250, - 152, - 227, - 138, - 146, - 174, - 5, - 223, - 41, - 16, - 103, - 108, - 186, - 201, - 211, - 0, - 230, - 207, - 225, - 158, - 168, - 44, - 99, - 22, - 1, - 63, - 88, - 226, - 137, - 169, - 13, - 56, - 52, - 27, - 171, - 51, - 255, - 176, - 187, - 72, - 12, - 95, - 185, - 177, - 205, - 46, - 197, - 243, - 219, - 71, - 229, - 165, - 156, - 119, - 10, - 166, - 32, - 104, - 254, - 127, - 193, - 173 - ]; - var s = [1, 2, 3, 5]; - var rol = function(word, bits) { - return word << bits & 65535 | (word & 65535) >> 16 - bits; - }; - var ror = function(word, bits) { - return (word & 65535) >> bits | word << 16 - bits & 65535; - }; - module.exports = forge3.rc2 = forge3.rc2 || {}; - forge3.rc2.expandKey = function(key, effKeyBits) { - if (typeof key === "string") { - key = forge3.util.createBuffer(key); - } - effKeyBits = effKeyBits || 128; - var L = key; - var T = key.length(); - var T1 = effKeyBits; - var T8 = Math.ceil(T1 / 8); - var TM = 255 >> (T1 & 7); - var i; - for (i = T; i < 128; i++) { - L.putByte(piTable[L.at(i - 1) + L.at(i - T) & 255]); - } - L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]); - for (i = 127 - T8; i >= 0; i--) { - L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]); - } - return L; - }; - var createCipher = function(key, bits, encrypt) { - var _finish = false, _input = null, _output = null, _iv = null; - var mixRound, mashRound; - var i, j, K = []; - key = forge3.rc2.expandKey(key, bits); - for (i = 0; i < 64; i++) { - K.push(key.getInt16Le()); - } - if (encrypt) { - mixRound = function(R) { - for (i = 0; i < 4; i++) { - R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + (~R[(i + 3) % 4] & R[(i + 1) % 4]); - R[i] = rol(R[i], s[i]); - j++; - } - }; - mashRound = function(R) { - for (i = 0; i < 4; i++) { - R[i] += K[R[(i + 3) % 4] & 63]; - } - }; - } else { - mixRound = function(R) { - for (i = 3; i >= 0; i--) { - R[i] = ror(R[i], s[i]); - R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + (~R[(i + 3) % 4] & R[(i + 1) % 4]); - j--; - } - }; - mashRound = function(R) { - for (i = 3; i >= 0; i--) { - R[i] -= K[R[(i + 3) % 4] & 63]; - } - }; - } - var runPlan = function(plan) { - var R = []; - for (i = 0; i < 4; i++) { - var val = _input.getInt16Le(); - if (_iv !== null) { - if (encrypt) { - val ^= _iv.getInt16Le(); - } else { - _iv.putInt16Le(val); - } - } - R.push(val & 65535); - } - j = encrypt ? 0 : 63; - for (var ptr = 0; ptr < plan.length; ptr++) { - for (var ctr = 0; ctr < plan[ptr][0]; ctr++) { - plan[ptr][1](R); - } - } - for (i = 0; i < 4; i++) { - if (_iv !== null) { - if (encrypt) { - _iv.putInt16Le(R[i]); - } else { - R[i] ^= _iv.getInt16Le(); - } - } - _output.putInt16Le(R[i]); - } - }; - var cipher = null; - cipher = { - /** - * Starts or restarts the encryption or decryption process, whichever - * was previously configured. - * - * To use the cipher in CBC mode, iv may be given either as a string - * of bytes, or as a byte buffer. For ECB mode, give null as iv. - * - * @param iv the initialization vector to use, null for ECB mode. - * @param output the output the buffer to write to, null to create one. - */ - start: function(iv, output) { - if (iv) { - if (typeof iv === "string") { - iv = forge3.util.createBuffer(iv); - } - } - _finish = false; - _input = forge3.util.createBuffer(); - _output = output || new forge3.util.createBuffer(); - _iv = iv; - cipher.output = _output; - }, - /** - * Updates the next block. - * - * @param input the buffer to read from. - */ - update: function(input) { - if (!_finish) { - _input.putBuffer(input); - } - while (_input.length() >= 8) { - runPlan([ - [5, mixRound], - [1, mashRound], - [6, mixRound], - [1, mashRound], - [5, mixRound] - ]); - } - }, - /** - * Finishes encrypting or decrypting. - * - * @param pad a padding function to use, null for PKCS#7 padding, - * signature(blockSize, buffer, decrypt). - * - * @return true if successful, false on error. - */ - finish: function(pad) { - var rval = true; - if (encrypt) { - if (pad) { - rval = pad(8, _input, !encrypt); - } else { - var padding = _input.length() === 8 ? 8 : 8 - _input.length(); - _input.fillWithByte(padding, padding); - } - } - if (rval) { - _finish = true; - cipher.update(); - } - if (!encrypt) { - rval = _input.length() === 0; - if (rval) { - if (pad) { - rval = pad(8, _output, !encrypt); - } else { - var len = _output.length(); - var count = _output.at(len - 1); - if (count > len) { - rval = false; - } else { - _output.truncate(count); - } - } - } - } - return rval; - } - }; - return cipher; - }; - forge3.rc2.startEncrypting = function(key, iv, output) { - var cipher = forge3.rc2.createEncryptionCipher(key, 128); - cipher.start(iv, output); - return cipher; - }; - forge3.rc2.createEncryptionCipher = function(key, bits) { - return createCipher(key, bits, true); - }; - forge3.rc2.startDecrypting = function(key, iv, output) { - var cipher = forge3.rc2.createDecryptionCipher(key, 128); - cipher.start(iv, output); - return cipher; - }; - forge3.rc2.createDecryptionCipher = function(key, bits) { - return createCipher(key, bits, false); - }; - } -}); - -// node_modules/node-forge/lib/jsbn.js -var require_jsbn = __commonJS({ - "node_modules/node-forge/lib/jsbn.js"(exports, module) { - var forge3 = require_forge(); - module.exports = forge3.jsbn = forge3.jsbn || {}; - var dbits; - var canary = 244837814094590; - var j_lm = (canary & 16777215) == 15715070; - function BigInteger2(a, b, c) { - this.data = []; - if (a != null) - if ("number" == typeof a) this.fromNumber(a, b, c); - else if (b == null && "string" != typeof a) this.fromString(a, 256); - else this.fromString(a, b); - } - forge3.jsbn.BigInteger = BigInteger2; - function nbi() { - return new BigInteger2(null); - } - function am1(i, x, w, j, c, n) { - while (--n >= 0) { - var v = x * this.data[i++] + w.data[j] + c; - c = Math.floor(v / 67108864); - w.data[j++] = v & 67108863; - } - return c; - } - function am2(i, x, w, j, c, n) { - var xl = x & 32767, xh = x >> 15; - while (--n >= 0) { - var l = this.data[i] & 32767; - var h = this.data[i++] >> 15; - var m = xh * l + h * xl; - l = xl * l + ((m & 32767) << 15) + w.data[j] + (c & 1073741823); - c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); - w.data[j++] = l & 1073741823; - } - return c; - } - function am3(i, x, w, j, c, n) { - var xl = x & 16383, xh = x >> 14; - while (--n >= 0) { - var l = this.data[i] & 16383; - var h = this.data[i++] >> 14; - var m = xh * l + h * xl; - l = xl * l + ((m & 16383) << 14) + w.data[j] + c; - c = (l >> 28) + (m >> 14) + xh * h; - w.data[j++] = l & 268435455; - } - return c; - } - if (typeof navigator === "undefined") { - BigInteger2.prototype.am = am3; - dbits = 28; - } else if (j_lm && navigator.appName == "Microsoft Internet Explorer") { - BigInteger2.prototype.am = am2; - dbits = 30; - } else if (j_lm && navigator.appName != "Netscape") { - BigInteger2.prototype.am = am1; - dbits = 26; - } else { - BigInteger2.prototype.am = am3; - dbits = 28; - } - BigInteger2.prototype.DB = dbits; - BigInteger2.prototype.DM = (1 << dbits) - 1; - BigInteger2.prototype.DV = 1 << dbits; - var BI_FP = 52; - BigInteger2.prototype.FV = Math.pow(2, BI_FP); - BigInteger2.prototype.F1 = BI_FP - dbits; - BigInteger2.prototype.F2 = 2 * dbits - BI_FP; - var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; - var BI_RC = new Array(); - var rr; - var vv; - rr = "0".charCodeAt(0); - for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; - rr = "a".charCodeAt(0); - for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - rr = "A".charCodeAt(0); - for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - function int2char(n) { - return BI_RM.charAt(n); - } - function intAt(s, i) { - var c = BI_RC[s.charCodeAt(i)]; - return c == null ? -1 : c; - } - function bnpCopyTo(r) { - for (var i = this.t - 1; i >= 0; --i) r.data[i] = this.data[i]; - r.t = this.t; - r.s = this.s; - } - function bnpFromInt(x) { - this.t = 1; - this.s = x < 0 ? -1 : 0; - if (x > 0) this.data[0] = x; - else if (x < -1) this.data[0] = x + this.DV; - else this.t = 0; - } - function nbv(i) { - var r = nbi(); - r.fromInt(i); - return r; - } - function bnpFromString(s, b) { - var k; - if (b == 16) k = 4; - else if (b == 8) k = 3; - else if (b == 256) k = 8; - else if (b == 2) k = 1; - else if (b == 32) k = 5; - else if (b == 4) k = 2; - else { - this.fromRadix(s, b); - return; - } - this.t = 0; - this.s = 0; - var i = s.length, mi = false, sh = 0; - while (--i >= 0) { - var x = k == 8 ? s[i] & 255 : intAt(s, i); - if (x < 0) { - if (s.charAt(i) == "-") mi = true; - continue; - } - mi = false; - if (sh == 0) - this.data[this.t++] = x; - else if (sh + k > this.DB) { - this.data[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh; - this.data[this.t++] = x >> this.DB - sh; - } else - this.data[this.t - 1] |= x << sh; - sh += k; - if (sh >= this.DB) sh -= this.DB; - } - if (k == 8 && (s[0] & 128) != 0) { - this.s = -1; - if (sh > 0) this.data[this.t - 1] |= (1 << this.DB - sh) - 1 << sh; - } - this.clamp(); - if (mi) BigInteger2.ZERO.subTo(this, this); - } - function bnpClamp() { - var c = this.s & this.DM; - while (this.t > 0 && this.data[this.t - 1] == c) --this.t; - } - function bnToString(b) { - if (this.s < 0) return "-" + this.negate().toString(b); - var k; - if (b == 16) k = 4; - else if (b == 8) k = 3; - else if (b == 2) k = 1; - else if (b == 32) k = 5; - else if (b == 4) k = 2; - else return this.toRadix(b); - var km = (1 << k) - 1, d, m = false, r = "", i = this.t; - var p = this.DB - i * this.DB % k; - if (i-- > 0) { - if (p < this.DB && (d = this.data[i] >> p) > 0) { - m = true; - r = int2char(d); - } - while (i >= 0) { - if (p < k) { - d = (this.data[i] & (1 << p) - 1) << k - p; - d |= this.data[--i] >> (p += this.DB - k); - } else { - d = this.data[i] >> (p -= k) & km; - if (p <= 0) { - p += this.DB; - --i; - } - } - if (d > 0) m = true; - if (m) r += int2char(d); - } - } - return m ? r : "0"; - } - function bnNegate() { - var r = nbi(); - BigInteger2.ZERO.subTo(this, r); - return r; - } - function bnAbs() { - return this.s < 0 ? this.negate() : this; - } - function bnCompareTo(a) { - var r = this.s - a.s; - if (r != 0) return r; - var i = this.t; - r = i - a.t; - if (r != 0) return this.s < 0 ? -r : r; - while (--i >= 0) if ((r = this.data[i] - a.data[i]) != 0) return r; - return 0; - } - function nbits(x) { - var r = 1, t; - if ((t = x >>> 16) != 0) { - x = t; - r += 16; - } - if ((t = x >> 8) != 0) { - x = t; - r += 8; - } - if ((t = x >> 4) != 0) { - x = t; - r += 4; - } - if ((t = x >> 2) != 0) { - x = t; - r += 2; - } - if ((t = x >> 1) != 0) { - x = t; - r += 1; - } - return r; - } - function bnBitLength() { - if (this.t <= 0) return 0; - return this.DB * (this.t - 1) + nbits(this.data[this.t - 1] ^ this.s & this.DM); - } - function bnpDLShiftTo(n, r) { - var i; - for (i = this.t - 1; i >= 0; --i) r.data[i + n] = this.data[i]; - for (i = n - 1; i >= 0; --i) r.data[i] = 0; - r.t = this.t + n; - r.s = this.s; - } - function bnpDRShiftTo(n, r) { - for (var i = n; i < this.t; ++i) r.data[i - n] = this.data[i]; - r.t = Math.max(this.t - n, 0); - r.s = this.s; - } - function bnpLShiftTo(n, r) { - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << cbs) - 1; - var ds = Math.floor(n / this.DB), c = this.s << bs & this.DM, i; - for (i = this.t - 1; i >= 0; --i) { - r.data[i + ds + 1] = this.data[i] >> cbs | c; - c = (this.data[i] & bm) << bs; - } - for (i = ds - 1; i >= 0; --i) r.data[i] = 0; - r.data[ds] = c; - r.t = this.t + ds + 1; - r.s = this.s; - r.clamp(); - } - function bnpRShiftTo(n, r) { - r.s = this.s; - var ds = Math.floor(n / this.DB); - if (ds >= this.t) { - r.t = 0; - return; - } - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << bs) - 1; - r.data[0] = this.data[ds] >> bs; - for (var i = ds + 1; i < this.t; ++i) { - r.data[i - ds - 1] |= (this.data[i] & bm) << cbs; - r.data[i - ds] = this.data[i] >> bs; - } - if (bs > 0) r.data[this.t - ds - 1] |= (this.s & bm) << cbs; - r.t = this.t - ds; - r.clamp(); - } - function bnpSubTo(a, r) { - var i = 0, c = 0, m = Math.min(a.t, this.t); - while (i < m) { - c += this.data[i] - a.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - if (a.t < this.t) { - c -= a.s; - while (i < this.t) { - c += this.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c -= a.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - c -= a.s; - } - r.s = c < 0 ? -1 : 0; - if (c < -1) r.data[i++] = this.DV + c; - else if (c > 0) r.data[i++] = c; - r.t = i; - r.clamp(); - } - function bnpMultiplyTo(a, r) { - var x = this.abs(), y = a.abs(); - var i = x.t; - r.t = i + y.t; - while (--i >= 0) r.data[i] = 0; - for (i = 0; i < y.t; ++i) r.data[i + x.t] = x.am(0, y.data[i], r, i, 0, x.t); - r.s = 0; - r.clamp(); - if (this.s != a.s) BigInteger2.ZERO.subTo(r, r); - } - function bnpSquareTo(r) { - var x = this.abs(); - var i = r.t = 2 * x.t; - while (--i >= 0) r.data[i] = 0; - for (i = 0; i < x.t - 1; ++i) { - var c = x.am(i, x.data[i], r, 2 * i, 0, 1); - if ((r.data[i + x.t] += x.am(i + 1, 2 * x.data[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { - r.data[i + x.t] -= x.DV; - r.data[i + x.t + 1] = 1; - } - } - if (r.t > 0) r.data[r.t - 1] += x.am(i, x.data[i], r, 2 * i, 0, 1); - r.s = 0; - r.clamp(); - } - function bnpDivRemTo(m, q, r) { - var pm = m.abs(); - if (pm.t <= 0) return; - var pt = this.abs(); - if (pt.t < pm.t) { - if (q != null) q.fromInt(0); - if (r != null) this.copyTo(r); - return; - } - if (r == null) r = nbi(); - var y = nbi(), ts = this.s, ms = m.s; - var nsh = this.DB - nbits(pm.data[pm.t - 1]); - if (nsh > 0) { - pm.lShiftTo(nsh, y); - pt.lShiftTo(nsh, r); - } else { - pm.copyTo(y); - pt.copyTo(r); - } - var ys = y.t; - var y0 = y.data[ys - 1]; - if (y0 == 0) return; - var yt = y0 * (1 << this.F1) + (ys > 1 ? y.data[ys - 2] >> this.F2 : 0); - var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2; - var i = r.t, j = i - ys, t = q == null ? nbi() : q; - y.dlShiftTo(j, t); - if (r.compareTo(t) >= 0) { - r.data[r.t++] = 1; - r.subTo(t, r); - } - BigInteger2.ONE.dlShiftTo(ys, t); - t.subTo(y, y); - while (y.t < ys) y.data[y.t++] = 0; - while (--j >= 0) { - var qd = r.data[--i] == y0 ? this.DM : Math.floor(r.data[i] * d1 + (r.data[i - 1] + e) * d2); - if ((r.data[i] += y.am(0, qd, r, j, 0, ys)) < qd) { - y.dlShiftTo(j, t); - r.subTo(t, r); - while (r.data[i] < --qd) r.subTo(t, r); - } - } - if (q != null) { - r.drShiftTo(ys, q); - if (ts != ms) BigInteger2.ZERO.subTo(q, q); - } - r.t = ys; - r.clamp(); - if (nsh > 0) r.rShiftTo(nsh, r); - if (ts < 0) BigInteger2.ZERO.subTo(r, r); - } - function bnMod(a) { - var r = nbi(); - this.abs().divRemTo(a, null, r); - if (this.s < 0 && r.compareTo(BigInteger2.ZERO) > 0) a.subTo(r, r); - return r; - } - function Classic(m) { - this.m = m; - } - function cConvert(x) { - if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); - else return x; - } - function cRevert(x) { - return x; - } - function cReduce(x) { - x.divRemTo(this.m, null, x); - } - function cMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - function cSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - Classic.prototype.convert = cConvert; - Classic.prototype.revert = cRevert; - Classic.prototype.reduce = cReduce; - Classic.prototype.mulTo = cMulTo; - Classic.prototype.sqrTo = cSqrTo; - function bnpInvDigit() { - if (this.t < 1) return 0; - var x = this.data[0]; - if ((x & 1) == 0) return 0; - var y = x & 3; - y = y * (2 - (x & 15) * y) & 15; - y = y * (2 - (x & 255) * y) & 255; - y = y * (2 - ((x & 65535) * y & 65535)) & 65535; - y = y * (2 - x * y % this.DV) % this.DV; - return y > 0 ? this.DV - y : -y; - } - function Montgomery(m) { - this.m = m; - this.mp = m.invDigit(); - this.mpl = this.mp & 32767; - this.mph = this.mp >> 15; - this.um = (1 << m.DB - 15) - 1; - this.mt2 = 2 * m.t; - } - function montConvert(x) { - var r = nbi(); - x.abs().dlShiftTo(this.m.t, r); - r.divRemTo(this.m, null, r); - if (x.s < 0 && r.compareTo(BigInteger2.ZERO) > 0) this.m.subTo(r, r); - return r; - } - function montRevert(x) { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } - function montReduce(x) { - while (x.t <= this.mt2) - x.data[x.t++] = 0; - for (var i = 0; i < this.m.t; ++i) { - var j = x.data[i] & 32767; - var u0 = j * this.mpl + ((j * this.mph + (x.data[i] >> 15) * this.mpl & this.um) << 15) & x.DM; - j = i + this.m.t; - x.data[j] += this.m.am(0, u0, x, i, 0, this.m.t); - while (x.data[j] >= x.DV) { - x.data[j] -= x.DV; - x.data[++j]++; - } - } - x.clamp(); - x.drShiftTo(this.m.t, x); - if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); - } - function montSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - function montMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - Montgomery.prototype.convert = montConvert; - Montgomery.prototype.revert = montRevert; - Montgomery.prototype.reduce = montReduce; - Montgomery.prototype.mulTo = montMulTo; - Montgomery.prototype.sqrTo = montSqrTo; - function bnpIsEven() { - return (this.t > 0 ? this.data[0] & 1 : this.s) == 0; - } - function bnpExp(e, z) { - if (e > 4294967295 || e < 1) return BigInteger2.ONE; - var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e) - 1; - g.copyTo(r); - while (--i >= 0) { - z.sqrTo(r, r2); - if ((e & 1 << i) > 0) z.mulTo(r2, g, r); - else { - var t = r; - r = r2; - r2 = t; - } - } - return z.revert(r); - } - function bnModPowInt(e, m) { - var z; - if (e < 256 || m.isEven()) z = new Classic(m); - else z = new Montgomery(m); - return this.exp(e, z); - } - BigInteger2.prototype.copyTo = bnpCopyTo; - BigInteger2.prototype.fromInt = bnpFromInt; - BigInteger2.prototype.fromString = bnpFromString; - BigInteger2.prototype.clamp = bnpClamp; - BigInteger2.prototype.dlShiftTo = bnpDLShiftTo; - BigInteger2.prototype.drShiftTo = bnpDRShiftTo; - BigInteger2.prototype.lShiftTo = bnpLShiftTo; - BigInteger2.prototype.rShiftTo = bnpRShiftTo; - BigInteger2.prototype.subTo = bnpSubTo; - BigInteger2.prototype.multiplyTo = bnpMultiplyTo; - BigInteger2.prototype.squareTo = bnpSquareTo; - BigInteger2.prototype.divRemTo = bnpDivRemTo; - BigInteger2.prototype.invDigit = bnpInvDigit; - BigInteger2.prototype.isEven = bnpIsEven; - BigInteger2.prototype.exp = bnpExp; - BigInteger2.prototype.toString = bnToString; - BigInteger2.prototype.negate = bnNegate; - BigInteger2.prototype.abs = bnAbs; - BigInteger2.prototype.compareTo = bnCompareTo; - BigInteger2.prototype.bitLength = bnBitLength; - BigInteger2.prototype.mod = bnMod; - BigInteger2.prototype.modPowInt = bnModPowInt; - BigInteger2.ZERO = nbv(0); - BigInteger2.ONE = nbv(1); - function bnClone() { - var r = nbi(); - this.copyTo(r); - return r; - } - function bnIntValue() { - if (this.s < 0) { - if (this.t == 1) return this.data[0] - this.DV; - else if (this.t == 0) return -1; - } else if (this.t == 1) return this.data[0]; - else if (this.t == 0) return 0; - return (this.data[1] & (1 << 32 - this.DB) - 1) << this.DB | this.data[0]; - } - function bnByteValue() { - return this.t == 0 ? this.s : this.data[0] << 24 >> 24; - } - function bnShortValue() { - return this.t == 0 ? this.s : this.data[0] << 16 >> 16; - } - function bnpChunkSize(r) { - return Math.floor(Math.LN2 * this.DB / Math.log(r)); - } - function bnSigNum() { - if (this.s < 0) return -1; - else if (this.t <= 0 || this.t == 1 && this.data[0] <= 0) return 0; - else return 1; - } - function bnpToRadix(b) { - if (b == null) b = 10; - if (this.signum() == 0 || b < 2 || b > 36) return "0"; - var cs = this.chunkSize(b); - var a = Math.pow(b, cs); - var d = nbv(a), y = nbi(), z = nbi(), r = ""; - this.divRemTo(d, y, z); - while (y.signum() > 0) { - r = (a + z.intValue()).toString(b).substr(1) + r; - y.divRemTo(d, y, z); - } - return z.intValue().toString(b) + r; - } - function bnpFromRadix(s, b) { - this.fromInt(0); - if (b == null) b = 10; - var cs = this.chunkSize(b); - var d = Math.pow(b, cs), mi = false, j = 0, w = 0; - for (var i = 0; i < s.length; ++i) { - var x = intAt(s, i); - if (x < 0) { - if (s.charAt(i) == "-" && this.signum() == 0) mi = true; - continue; - } - w = b * w + x; - if (++j >= cs) { - this.dMultiply(d); - this.dAddOffset(w, 0); - j = 0; - w = 0; - } - } - if (j > 0) { - this.dMultiply(Math.pow(b, j)); - this.dAddOffset(w, 0); - } - if (mi) BigInteger2.ZERO.subTo(this, this); - } - function bnpFromNumber(a, b, c) { - if ("number" == typeof b) { - if (a < 2) this.fromInt(1); - else { - this.fromNumber(a, c); - if (!this.testBit(a - 1)) - this.bitwiseTo(BigInteger2.ONE.shiftLeft(a - 1), op_or, this); - if (this.isEven()) this.dAddOffset(1, 0); - while (!this.isProbablePrime(b)) { - this.dAddOffset(2, 0); - if (this.bitLength() > a) this.subTo(BigInteger2.ONE.shiftLeft(a - 1), this); - } - } - } else { - var x = new Array(), t = a & 7; - x.length = (a >> 3) + 1; - b.nextBytes(x); - if (t > 0) x[0] &= (1 << t) - 1; - else x[0] = 0; - this.fromString(x, 256); - } - } - function bnToByteArray() { - var i = this.t, r = new Array(); - r[0] = this.s; - var p = this.DB - i * this.DB % 8, d, k = 0; - if (i-- > 0) { - if (p < this.DB && (d = this.data[i] >> p) != (this.s & this.DM) >> p) - r[k++] = d | this.s << this.DB - p; - while (i >= 0) { - if (p < 8) { - d = (this.data[i] & (1 << p) - 1) << 8 - p; - d |= this.data[--i] >> (p += this.DB - 8); - } else { - d = this.data[i] >> (p -= 8) & 255; - if (p <= 0) { - p += this.DB; - --i; - } - } - if ((d & 128) != 0) d |= -256; - if (k == 0 && (this.s & 128) != (d & 128)) ++k; - if (k > 0 || d != this.s) r[k++] = d; - } - } - return r; - } - function bnEquals(a) { - return this.compareTo(a) == 0; - } - function bnMin(a) { - return this.compareTo(a) < 0 ? this : a; - } - function bnMax(a) { - return this.compareTo(a) > 0 ? this : a; - } - function bnpBitwiseTo(a, op, r) { - var i, f, m = Math.min(a.t, this.t); - for (i = 0; i < m; ++i) r.data[i] = op(this.data[i], a.data[i]); - if (a.t < this.t) { - f = a.s & this.DM; - for (i = m; i < this.t; ++i) r.data[i] = op(this.data[i], f); - r.t = this.t; - } else { - f = this.s & this.DM; - for (i = m; i < a.t; ++i) r.data[i] = op(f, a.data[i]); - r.t = a.t; - } - r.s = op(this.s, a.s); - r.clamp(); - } - function op_and(x, y) { - return x & y; - } - function bnAnd(a) { - var r = nbi(); - this.bitwiseTo(a, op_and, r); - return r; - } - function op_or(x, y) { - return x | y; - } - function bnOr(a) { - var r = nbi(); - this.bitwiseTo(a, op_or, r); - return r; - } - function op_xor(x, y) { - return x ^ y; - } - function bnXor(a) { - var r = nbi(); - this.bitwiseTo(a, op_xor, r); - return r; - } - function op_andnot(x, y) { - return x & ~y; - } - function bnAndNot(a) { - var r = nbi(); - this.bitwiseTo(a, op_andnot, r); - return r; - } - function bnNot() { - var r = nbi(); - for (var i = 0; i < this.t; ++i) r.data[i] = this.DM & ~this.data[i]; - r.t = this.t; - r.s = ~this.s; - return r; - } - function bnShiftLeft(n) { - var r = nbi(); - if (n < 0) this.rShiftTo(-n, r); - else this.lShiftTo(n, r); - return r; - } - function bnShiftRight(n) { - var r = nbi(); - if (n < 0) this.lShiftTo(-n, r); - else this.rShiftTo(n, r); - return r; - } - function lbit(x) { - if (x == 0) return -1; - var r = 0; - if ((x & 65535) == 0) { - x >>= 16; - r += 16; - } - if ((x & 255) == 0) { - x >>= 8; - r += 8; - } - if ((x & 15) == 0) { - x >>= 4; - r += 4; - } - if ((x & 3) == 0) { - x >>= 2; - r += 2; - } - if ((x & 1) == 0) ++r; - return r; - } - function bnGetLowestSetBit() { - for (var i = 0; i < this.t; ++i) - if (this.data[i] != 0) return i * this.DB + lbit(this.data[i]); - if (this.s < 0) return this.t * this.DB; - return -1; - } - function cbit(x) { - var r = 0; - while (x != 0) { - x &= x - 1; - ++r; - } - return r; - } - function bnBitCount() { - var r = 0, x = this.s & this.DM; - for (var i = 0; i < this.t; ++i) r += cbit(this.data[i] ^ x); - return r; - } - function bnTestBit(n) { - var j = Math.floor(n / this.DB); - if (j >= this.t) return this.s != 0; - return (this.data[j] & 1 << n % this.DB) != 0; - } - function bnpChangeBit(n, op) { - var r = BigInteger2.ONE.shiftLeft(n); - this.bitwiseTo(r, op, r); - return r; - } - function bnSetBit(n) { - return this.changeBit(n, op_or); - } - function bnClearBit(n) { - return this.changeBit(n, op_andnot); - } - function bnFlipBit(n) { - return this.changeBit(n, op_xor); - } - function bnpAddTo(a, r) { - var i = 0, c = 0, m = Math.min(a.t, this.t); - while (i < m) { - c += this.data[i] + a.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - if (a.t < this.t) { - c += a.s; - while (i < this.t) { - c += this.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c += a.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - c += a.s; - } - r.s = c < 0 ? -1 : 0; - if (c > 0) r.data[i++] = c; - else if (c < -1) r.data[i++] = this.DV + c; - r.t = i; - r.clamp(); - } - function bnAdd(a) { - var r = nbi(); - this.addTo(a, r); - return r; - } - function bnSubtract(a) { - var r = nbi(); - this.subTo(a, r); - return r; - } - function bnMultiply(a) { - var r = nbi(); - this.multiplyTo(a, r); - return r; - } - function bnDivide(a) { - var r = nbi(); - this.divRemTo(a, r, null); - return r; - } - function bnRemainder(a) { - var r = nbi(); - this.divRemTo(a, null, r); - return r; - } - function bnDivideAndRemainder(a) { - var q = nbi(), r = nbi(); - this.divRemTo(a, q, r); - return new Array(q, r); - } - function bnpDMultiply(n) { - this.data[this.t] = this.am(0, n - 1, this, 0, 0, this.t); - ++this.t; - this.clamp(); - } - function bnpDAddOffset(n, w) { - if (n == 0) return; - while (this.t <= w) this.data[this.t++] = 0; - this.data[w] += n; - while (this.data[w] >= this.DV) { - this.data[w] -= this.DV; - if (++w >= this.t) this.data[this.t++] = 0; - ++this.data[w]; - } - } - function NullExp() { - } - function nNop(x) { - return x; - } - function nMulTo(x, y, r) { - x.multiplyTo(y, r); - } - function nSqrTo(x, r) { - x.squareTo(r); - } - NullExp.prototype.convert = nNop; - NullExp.prototype.revert = nNop; - NullExp.prototype.mulTo = nMulTo; - NullExp.prototype.sqrTo = nSqrTo; - function bnPow(e) { - return this.exp(e, new NullExp()); - } - function bnpMultiplyLowerTo(a, n, r) { - var i = Math.min(this.t + a.t, n); - r.s = 0; - r.t = i; - while (i > 0) r.data[--i] = 0; - var j; - for (j = r.t - this.t; i < j; ++i) r.data[i + this.t] = this.am(0, a.data[i], r, i, 0, this.t); - for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a.data[i], r, i, 0, n - i); - r.clamp(); - } - function bnpMultiplyUpperTo(a, n, r) { - --n; - var i = r.t = this.t + a.t - n; - r.s = 0; - while (--i >= 0) r.data[i] = 0; - for (i = Math.max(n - this.t, 0); i < a.t; ++i) - r.data[this.t + i - n] = this.am(n - i, a.data[i], r, 0, 0, this.t + i - n); - r.clamp(); - r.drShiftTo(1, r); - } - function Barrett(m) { - this.r2 = nbi(); - this.q3 = nbi(); - BigInteger2.ONE.dlShiftTo(2 * m.t, this.r2); - this.mu = this.r2.divide(m); - this.m = m; - } - function barrettConvert(x) { - if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); - else if (x.compareTo(this.m) < 0) return x; - else { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } - } - function barrettRevert(x) { - return x; - } - function barrettReduce(x) { - x.drShiftTo(this.m.t - 1, this.r2); - if (x.t > this.m.t + 1) { - x.t = this.m.t + 1; - x.clamp(); - } - this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); - this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); - while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); - x.subTo(this.r2, x); - while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); - } - function barrettSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - function barrettMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - Barrett.prototype.convert = barrettConvert; - Barrett.prototype.revert = barrettRevert; - Barrett.prototype.reduce = barrettReduce; - Barrett.prototype.mulTo = barrettMulTo; - Barrett.prototype.sqrTo = barrettSqrTo; - function bnModPow(e, m) { - var i = e.bitLength(), k, r = nbv(1), z; - if (i <= 0) return r; - else if (i < 18) k = 1; - else if (i < 48) k = 3; - else if (i < 144) k = 4; - else if (i < 768) k = 5; - else k = 6; - if (i < 8) - z = new Classic(m); - else if (m.isEven()) - z = new Barrett(m); - else - z = new Montgomery(m); - var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1; - g[1] = z.convert(this); - if (k > 1) { - var g2 = nbi(); - z.sqrTo(g[1], g2); - while (n <= km) { - g[n] = nbi(); - z.mulTo(g2, g[n - 2], g[n]); - n += 2; - } - } - var j = e.t - 1, w, is1 = true, r2 = nbi(), t; - i = nbits(e.data[j]) - 1; - while (j >= 0) { - if (i >= k1) w = e.data[j] >> i - k1 & km; - else { - w = (e.data[j] & (1 << i + 1) - 1) << k1 - i; - if (j > 0) w |= e.data[j - 1] >> this.DB + i - k1; - } - n = k; - while ((w & 1) == 0) { - w >>= 1; - --n; - } - if ((i -= n) < 0) { - i += this.DB; - --j; - } - if (is1) { - g[w].copyTo(r); - is1 = false; - } else { - while (n > 1) { - z.sqrTo(r, r2); - z.sqrTo(r2, r); - n -= 2; - } - if (n > 0) z.sqrTo(r, r2); - else { - t = r; - r = r2; - r2 = t; - } - z.mulTo(r2, g[w], r); - } - while (j >= 0 && (e.data[j] & 1 << i) == 0) { - z.sqrTo(r, r2); - t = r; - r = r2; - r2 = t; - if (--i < 0) { - i = this.DB - 1; - --j; - } - } - } - return z.revert(r); - } - function bnGCD(a) { - var x = this.s < 0 ? this.negate() : this.clone(); - var y = a.s < 0 ? a.negate() : a.clone(); - if (x.compareTo(y) < 0) { - var t = x; - x = y; - y = t; - } - var i = x.getLowestSetBit(), g = y.getLowestSetBit(); - if (g < 0) return x; - if (i < g) g = i; - if (g > 0) { - x.rShiftTo(g, x); - y.rShiftTo(g, y); - } - while (x.signum() > 0) { - if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); - if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); - if (x.compareTo(y) >= 0) { - x.subTo(y, x); - x.rShiftTo(1, x); - } else { - y.subTo(x, y); - y.rShiftTo(1, y); - } - } - if (g > 0) y.lShiftTo(g, y); - return y; - } - function bnpModInt(n) { - if (n <= 0) return 0; - var d = this.DV % n, r = this.s < 0 ? n - 1 : 0; - if (this.t > 0) - if (d == 0) r = this.data[0] % n; - else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this.data[i]) % n; - return r; - } - function bnModInverse(m) { - var ac = m.isEven(); - if (this.isEven() && ac || m.signum() == 0) return BigInteger2.ZERO; - var u = m.clone(), v = this.clone(); - var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); - while (u.signum() != 0) { - while (u.isEven()) { - u.rShiftTo(1, u); - if (ac) { - if (!a.isEven() || !b.isEven()) { - a.addTo(this, a); - b.subTo(m, b); - } - a.rShiftTo(1, a); - } else if (!b.isEven()) b.subTo(m, b); - b.rShiftTo(1, b); - } - while (v.isEven()) { - v.rShiftTo(1, v); - if (ac) { - if (!c.isEven() || !d.isEven()) { - c.addTo(this, c); - d.subTo(m, d); - } - c.rShiftTo(1, c); - } else if (!d.isEven()) d.subTo(m, d); - d.rShiftTo(1, d); - } - if (u.compareTo(v) >= 0) { - u.subTo(v, u); - if (ac) a.subTo(c, a); - b.subTo(d, b); - } else { - v.subTo(u, v); - if (ac) c.subTo(a, c); - d.subTo(b, d); - } - } - if (v.compareTo(BigInteger2.ONE) != 0) return BigInteger2.ZERO; - if (d.compareTo(m) >= 0) return d.subtract(m); - if (d.signum() < 0) d.addTo(m, d); - else return d; - if (d.signum() < 0) return d.add(m); - else return d; - } - var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509]; - var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; - function bnIsProbablePrime(t) { - var i, x = this.abs(); - if (x.t == 1 && x.data[0] <= lowprimes[lowprimes.length - 1]) { - for (i = 0; i < lowprimes.length; ++i) - if (x.data[0] == lowprimes[i]) return true; - return false; - } - if (x.isEven()) return false; - i = 1; - while (i < lowprimes.length) { - var m = lowprimes[i], j = i + 1; - while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; - m = x.modInt(m); - while (i < j) if (m % lowprimes[i++] == 0) return false; - } - return x.millerRabin(t); - } - function bnpMillerRabin(t) { - var n1 = this.subtract(BigInteger2.ONE); - var k = n1.getLowestSetBit(); - if (k <= 0) return false; - var r = n1.shiftRight(k); - var prng = bnGetPrng(); - var a; - for (var i = 0; i < t; ++i) { - do { - a = new BigInteger2(this.bitLength(), prng); - } while (a.compareTo(BigInteger2.ONE) <= 0 || a.compareTo(n1) >= 0); - var y = a.modPow(r, this); - if (y.compareTo(BigInteger2.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1; - while (j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2, this); - if (y.compareTo(BigInteger2.ONE) == 0) return false; - } - if (y.compareTo(n1) != 0) return false; - } - } - return true; - } - function bnGetPrng() { - return { - // x is an array to fill with bytes - nextBytes: function(x) { - for (var i = 0; i < x.length; ++i) { - x[i] = Math.floor(Math.random() * 256); - } - } - }; - } - BigInteger2.prototype.chunkSize = bnpChunkSize; - BigInteger2.prototype.toRadix = bnpToRadix; - BigInteger2.prototype.fromRadix = bnpFromRadix; - BigInteger2.prototype.fromNumber = bnpFromNumber; - BigInteger2.prototype.bitwiseTo = bnpBitwiseTo; - BigInteger2.prototype.changeBit = bnpChangeBit; - BigInteger2.prototype.addTo = bnpAddTo; - BigInteger2.prototype.dMultiply = bnpDMultiply; - BigInteger2.prototype.dAddOffset = bnpDAddOffset; - BigInteger2.prototype.multiplyLowerTo = bnpMultiplyLowerTo; - BigInteger2.prototype.multiplyUpperTo = bnpMultiplyUpperTo; - BigInteger2.prototype.modInt = bnpModInt; - BigInteger2.prototype.millerRabin = bnpMillerRabin; - BigInteger2.prototype.clone = bnClone; - BigInteger2.prototype.intValue = bnIntValue; - BigInteger2.prototype.byteValue = bnByteValue; - BigInteger2.prototype.shortValue = bnShortValue; - BigInteger2.prototype.signum = bnSigNum; - BigInteger2.prototype.toByteArray = bnToByteArray; - BigInteger2.prototype.equals = bnEquals; - BigInteger2.prototype.min = bnMin; - BigInteger2.prototype.max = bnMax; - BigInteger2.prototype.and = bnAnd; - BigInteger2.prototype.or = bnOr; - BigInteger2.prototype.xor = bnXor; - BigInteger2.prototype.andNot = bnAndNot; - BigInteger2.prototype.not = bnNot; - BigInteger2.prototype.shiftLeft = bnShiftLeft; - BigInteger2.prototype.shiftRight = bnShiftRight; - BigInteger2.prototype.getLowestSetBit = bnGetLowestSetBit; - BigInteger2.prototype.bitCount = bnBitCount; - BigInteger2.prototype.testBit = bnTestBit; - BigInteger2.prototype.setBit = bnSetBit; - BigInteger2.prototype.clearBit = bnClearBit; - BigInteger2.prototype.flipBit = bnFlipBit; - BigInteger2.prototype.add = bnAdd; - BigInteger2.prototype.subtract = bnSubtract; - BigInteger2.prototype.multiply = bnMultiply; - BigInteger2.prototype.divide = bnDivide; - BigInteger2.prototype.remainder = bnRemainder; - BigInteger2.prototype.divideAndRemainder = bnDivideAndRemainder; - BigInteger2.prototype.modPow = bnModPow; - BigInteger2.prototype.modInverse = bnModInverse; - BigInteger2.prototype.pow = bnPow; - BigInteger2.prototype.gcd = bnGCD; - BigInteger2.prototype.isProbablePrime = bnIsProbablePrime; - } -}); - -// node_modules/node-forge/lib/sha1.js -var require_sha1 = __commonJS({ - "node_modules/node-forge/lib/sha1.js"(exports, module) { - var forge3 = require_forge(); - require_md(); - require_util(); - var sha1 = module.exports = forge3.sha1 = forge3.sha1 || {}; - forge3.md.sha1 = forge3.md.algorithms.sha1 = sha1; - sha1.create = function() { - if (!_initialized) { - _init(); - } - var _state = null; - var _input = forge3.util.createBuffer(); - var _w = new Array(80); - var md = { - algorithm: "sha1", - blockLength: 64, - digestLength: 20, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; - md.start = function() { - md.messageLength = 0; - md.fullMessageLength = md.messageLength64 = []; - var int32s = md.messageLengthSize / 4; - for (var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); - } - _input = forge3.util.createBuffer(); - _state = { - h0: 1732584193, - h1: 4023233417, - h2: 2562383102, - h3: 271733878, - h4: 3285377520 - }; - return md; - }; - md.start(); - md.update = function(msg, encoding) { - if (encoding === "utf8") { - msg = forge3.util.encodeUtf8(msg); - } - var len = msg.length; - md.messageLength += len; - len = [len / 4294967296 >>> 0, len >>> 0]; - for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + (md.fullMessageLength[i] / 4294967296 >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = len[1] / 4294967296 >>> 0; - } - _input.putBytes(msg); - _update(_state, _w, _input); - if (_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - return md; - }; - md.digest = function() { - var finalBlock = forge3.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; - var overflow = remaining & md.blockLength - 1; - finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); - var next, carry; - var bits = md.fullMessageLength[0] * 8; - for (var i = 0; i < md.fullMessageLength.length - 1; ++i) { - next = md.fullMessageLength[i + 1] * 8; - carry = next / 4294967296 >>> 0; - bits += carry; - finalBlock.putInt32(bits >>> 0); - bits = next >>> 0; - } - finalBlock.putInt32(bits); - var s2 = { - h0: _state.h0, - h1: _state.h1, - h2: _state.h2, - h3: _state.h3, - h4: _state.h4 - }; - _update(s2, _w, finalBlock); - var rval = forge3.util.createBuffer(); - rval.putInt32(s2.h0); - rval.putInt32(s2.h1); - rval.putInt32(s2.h2); - rval.putInt32(s2.h3); - rval.putInt32(s2.h4); - return rval; - }; - return md; - }; - var _padding = null; - var _initialized = false; - function _init() { - _padding = String.fromCharCode(128); - _padding += forge3.util.fillString(String.fromCharCode(0), 64); - _initialized = true; - } - function _update(s, w, bytes) { - var t, a, b, c, d, e, f, i; - var len = bytes.length(); - while (len >= 64) { - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; - e = s.h4; - for (i = 0; i < 16; ++i) { - t = bytes.getInt32(); - w[i] = t; - f = d ^ b & (c ^ d); - t = (a << 5 | a >>> 27) + f + e + 1518500249 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 20; ++i) { - t = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; - t = t << 1 | t >>> 31; - w[i] = t; - f = d ^ b & (c ^ d); - t = (a << 5 | a >>> 27) + f + e + 1518500249 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 32; ++i) { - t = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; - t = t << 1 | t >>> 31; - w[i] = t; - f = b ^ c ^ d; - t = (a << 5 | a >>> 27) + f + e + 1859775393 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 40; ++i) { - t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; - t = t << 2 | t >>> 30; - w[i] = t; - f = b ^ c ^ d; - t = (a << 5 | a >>> 27) + f + e + 1859775393 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 60; ++i) { - t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; - t = t << 2 | t >>> 30; - w[i] = t; - f = b & c | d & (b ^ c); - t = (a << 5 | a >>> 27) + f + e + 2400959708 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 80; ++i) { - t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; - t = t << 2 | t >>> 30; - w[i] = t; - f = b ^ c ^ d; - t = (a << 5 | a >>> 27) + f + e + 3395469782 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - s.h0 = s.h0 + a | 0; - s.h1 = s.h1 + b | 0; - s.h2 = s.h2 + c | 0; - s.h3 = s.h3 + d | 0; - s.h4 = s.h4 + e | 0; - len -= 64; - } - } - } -}); - -// node_modules/node-forge/lib/pkcs1.js -var require_pkcs1 = __commonJS({ - "node_modules/node-forge/lib/pkcs1.js"(exports, module) { - var forge3 = require_forge(); - require_util(); - require_random(); - require_sha1(); - var pkcs1 = module.exports = forge3.pkcs1 = forge3.pkcs1 || {}; - pkcs1.encode_rsa_oaep = function(key, message, options) { - var label; - var seed; - var md; - var mgf1Md; - if (typeof options === "string") { - label = options; - seed = arguments[3] || void 0; - md = arguments[4] || void 0; - } else if (options) { - label = options.label || void 0; - seed = options.seed || void 0; - md = options.md || void 0; - if (options.mgf1 && options.mgf1.md) { - mgf1Md = options.mgf1.md; - } - } - if (!md) { - md = forge3.md.sha1.create(); - } else { - md.start(); - } - if (!mgf1Md) { - mgf1Md = md; - } - var keyLength = Math.ceil(key.n.bitLength() / 8); - var maxLength = keyLength - 2 * md.digestLength - 2; - if (message.length > maxLength) { - var error = new Error("RSAES-OAEP input message length is too long."); - error.length = message.length; - error.maxLength = maxLength; - throw error; - } - if (!label) { - label = ""; - } - md.update(label, "raw"); - var lHash = md.digest(); - var PS = ""; - var PS_length = maxLength - message.length; - for (var i = 0; i < PS_length; i++) { - PS += "\0"; - } - var DB = lHash.getBytes() + PS + "" + message; - if (!seed) { - seed = forge3.random.getBytes(md.digestLength); - } else if (seed.length !== md.digestLength) { - var error = new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length."); - error.seedLength = seed.length; - error.digestLength = md.digestLength; - throw error; - } - var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); - var maskedDB = forge3.util.xorBytes(DB, dbMask, DB.length); - var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); - var maskedSeed = forge3.util.xorBytes(seed, seedMask, seed.length); - return "\0" + maskedSeed + maskedDB; - }; - pkcs1.decode_rsa_oaep = function(key, em, options) { - var label; - var md; - var mgf1Md; - if (typeof options === "string") { - label = options; - md = arguments[3] || void 0; - } else if (options) { - label = options.label || void 0; - md = options.md || void 0; - if (options.mgf1 && options.mgf1.md) { - mgf1Md = options.mgf1.md; - } - } - var keyLength = Math.ceil(key.n.bitLength() / 8); - if (em.length !== keyLength) { - var error = new Error("RSAES-OAEP encoded message length is invalid."); - error.length = em.length; - error.expectedLength = keyLength; - throw error; - } - if (md === void 0) { - md = forge3.md.sha1.create(); - } else { - md.start(); - } - if (!mgf1Md) { - mgf1Md = md; - } - if (keyLength < 2 * md.digestLength + 2) { - throw new Error("RSAES-OAEP key is too short for the hash function."); - } - if (!label) { - label = ""; - } - md.update(label, "raw"); - var lHash = md.digest().getBytes(); - var y = em.charAt(0); - var maskedSeed = em.substring(1, md.digestLength + 1); - var maskedDB = em.substring(1 + md.digestLength); - var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); - var seed = forge3.util.xorBytes(maskedSeed, seedMask, maskedSeed.length); - var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); - var db2 = forge3.util.xorBytes(maskedDB, dbMask, maskedDB.length); - var lHashPrime = db2.substring(0, md.digestLength); - var error = y !== "\0"; - for (var i = 0; i < md.digestLength; ++i) { - error |= lHash.charAt(i) !== lHashPrime.charAt(i); - } - var in_ps = 1; - var index = md.digestLength; - for (var j = md.digestLength; j < db2.length; j++) { - var code = db2.charCodeAt(j); - var is_0 = code & 1 ^ 1; - var error_mask = in_ps ? 65534 : 0; - error |= code & error_mask; - in_ps = in_ps & is_0; - index += in_ps; - } - if (error || db2.charCodeAt(index) !== 1) { - throw new Error("Invalid RSAES-OAEP padding."); - } - return db2.substring(index + 1); - }; - function rsa_mgf1(seed, maskLength, hash) { - if (!hash) { - hash = forge3.md.sha1.create(); - } - var t = ""; - var count = Math.ceil(maskLength / hash.digestLength); - for (var i = 0; i < count; ++i) { - var c = String.fromCharCode( - i >> 24 & 255, - i >> 16 & 255, - i >> 8 & 255, - i & 255 - ); - hash.start(); - hash.update(seed + c); - t += hash.digest().getBytes(); - } - return t.substring(0, maskLength); - } - } -}); - -// node_modules/node-forge/lib/prime.js -var require_prime = __commonJS({ - "node_modules/node-forge/lib/prime.js"(exports, module) { - var forge3 = require_forge(); - require_util(); - require_jsbn(); - require_random(); - (function() { - if (forge3.prime) { - module.exports = forge3.prime; - return; - } - var prime = module.exports = forge3.prime = forge3.prime || {}; - var BigInteger2 = forge3.jsbn.BigInteger; - var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; - var THIRTY = new BigInteger2(null); - THIRTY.fromInt(30); - var op_or = function(x, y) { - return x | y; - }; - prime.generateProbablePrime = function(bits, options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; - } - options = options || {}; - var algorithm = options.algorithm || "PRIMEINC"; - if (typeof algorithm === "string") { - algorithm = { name: algorithm }; - } - algorithm.options = algorithm.options || {}; - var prng = options.prng || forge3.random; - var rng = { - // x is an array to fill with bytes - nextBytes: function(x) { - var b = prng.getBytesSync(x.length); - for (var i = 0; i < x.length; ++i) { - x[i] = b.charCodeAt(i); - } - } - }; - if (algorithm.name === "PRIMEINC") { - return primeincFindPrime(bits, rng, algorithm.options, callback); - } - throw new Error("Invalid prime generation algorithm: " + algorithm.name); - }; - function primeincFindPrime(bits, rng, options, callback) { - if ("workers" in options) { - return primeincFindPrimeWithWorkers(bits, rng, options, callback); - } - return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); - } - function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) { - var num = generateRandom(bits, rng); - var deltaIdx = 0; - var mrTests = getMillerRabinTests(num.bitLength()); - if ("millerRabinTests" in options) { - mrTests = options.millerRabinTests; - } - var maxBlockTime = 10; - if ("maxBlockTime" in options) { - maxBlockTime = options.maxBlockTime; - } - _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); - } - function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) { - var start = +/* @__PURE__ */ new Date(); - do { - if (num.bitLength() > bits) { - num = generateRandom(bits, rng); - } - if (num.isProbablePrime(mrTests)) { - return callback(null, num); - } - num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); - } while (maxBlockTime < 0 || +/* @__PURE__ */ new Date() - start < maxBlockTime); - forge3.util.setImmediate(function() { - _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); - }); - } - function primeincFindPrimeWithWorkers(bits, rng, options, callback) { - if (typeof Worker === "undefined") { - return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); - } - var num = generateRandom(bits, rng); - var numWorkers = options.workers; - var workLoad = options.workLoad || 100; - var range = workLoad * 30 / 8; - var workerScript = options.workerScript || "forge/prime.worker.js"; - if (numWorkers === -1) { - return forge3.util.estimateCores(function(err, cores) { - if (err) { - cores = 2; - } - numWorkers = cores - 1; - generate(); - }); - } - generate(); - function generate() { - numWorkers = Math.max(1, numWorkers); - var workers = []; - for (var i = 0; i < numWorkers; ++i) { - workers[i] = new Worker(workerScript); - } - var running = numWorkers; - for (var i = 0; i < numWorkers; ++i) { - workers[i].addEventListener("message", workerMessage); - } - var found = false; - function workerMessage(e) { - if (found) { - return; - } - --running; - var data = e.data; - if (data.found) { - for (var i2 = 0; i2 < workers.length; ++i2) { - workers[i2].terminate(); - } - found = true; - return callback(null, new BigInteger2(data.prime, 16)); - } - if (num.bitLength() > bits) { - num = generateRandom(bits, rng); - } - var hex = num.toString(16); - e.target.postMessage({ - hex, - workLoad - }); - num.dAddOffset(range, 0); - } - } - } - function generateRandom(bits, rng) { - var num = new BigInteger2(bits, rng); - var bits1 = bits - 1; - if (!num.testBit(bits1)) { - num.bitwiseTo(BigInteger2.ONE.shiftLeft(bits1), op_or, num); - } - num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0); - return num; - } - function getMillerRabinTests(bits) { - if (bits <= 100) return 27; - if (bits <= 150) return 18; - if (bits <= 200) return 15; - if (bits <= 250) return 12; - if (bits <= 300) return 9; - if (bits <= 350) return 8; - if (bits <= 400) return 7; - if (bits <= 500) return 6; - if (bits <= 600) return 5; - if (bits <= 800) return 4; - if (bits <= 1250) return 3; - return 2; - } - })(); - } -}); - -// node_modules/node-forge/lib/rsa.js -var require_rsa = __commonJS({ - "node_modules/node-forge/lib/rsa.js"(exports, module) { - var forge3 = require_forge(); - require_asn1(); - require_jsbn(); - require_oids(); - require_pkcs1(); - require_prime(); - require_random(); - require_util(); - if (typeof BigInteger2 === "undefined") { - BigInteger2 = forge3.jsbn.BigInteger; - } - var BigInteger2; - var _crypto = forge3.util.isNodejs ? __require("crypto") : null; - var asn1 = forge3.asn1; - var util = forge3.util; - forge3.pki = forge3.pki || {}; - module.exports = forge3.pki.rsa = forge3.rsa = forge3.rsa || {}; - var pki = forge3.pki; - var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; - var privateKeyValidator = { - // PrivateKeyInfo - name: "PrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: "PrivateKeyInfo.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyVersion" - }, { - // privateKeyAlgorithm - name: "PrivateKeyInfo.privateKeyAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "privateKeyOid" - }] - }, { - // PrivateKey - name: "PrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "privateKey" - }] - }; - var rsaPrivateKeyValidator = { - // RSAPrivateKey - name: "RSAPrivateKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: "RSAPrivateKey.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyVersion" - }, { - // modulus (n) - name: "RSAPrivateKey.modulus", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyModulus" - }, { - // publicExponent (e) - name: "RSAPrivateKey.publicExponent", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyPublicExponent" - }, { - // privateExponent (d) - name: "RSAPrivateKey.privateExponent", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyPrivateExponent" - }, { - // prime1 (p) - name: "RSAPrivateKey.prime1", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyPrime1" - }, { - // prime2 (q) - name: "RSAPrivateKey.prime2", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyPrime2" - }, { - // exponent1 (d mod (p-1)) - name: "RSAPrivateKey.exponent1", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyExponent1" - }, { - // exponent2 (d mod (q-1)) - name: "RSAPrivateKey.exponent2", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyExponent2" - }, { - // coefficient ((inverse of q) mod p) - name: "RSAPrivateKey.coefficient", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyCoefficient" - }] - }; - var rsaPublicKeyValidator = { - // RSAPublicKey - name: "RSAPublicKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // modulus (n) - name: "RSAPublicKey.modulus", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "publicKeyModulus" - }, { - // publicExponent (e) - name: "RSAPublicKey.exponent", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "publicKeyExponent" - }] - }; - var publicKeyValidator = forge3.pki.rsa.publicKeyValidator = { - name: "SubjectPublicKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "subjectPublicKeyInfo", - value: [{ - name: "SubjectPublicKeyInfo.AlgorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "publicKeyOid" - }] - }, { - // subjectPublicKey - name: "SubjectPublicKeyInfo.subjectPublicKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - value: [{ - // RSAPublicKey - name: "SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: "rsaPublicKey" - }] - }] - }; - var digestInfoValidator = { - name: "DigestInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "DigestInfo.DigestAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "DigestInfo.DigestAlgorithm.algorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "algorithmIdentifier" - }, { - // NULL paramters - name: "DigestInfo.DigestAlgorithm.parameters", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.NULL, - // captured only to check existence for md2 and md5 - capture: "parameters", - optional: true, - constructed: false - }] - }, { - // digest - name: "DigestInfo.digest", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "digest" - }] - }; - var emsaPkcs1v15encode = function(md) { - var oid; - if (md.algorithm in pki.oids) { - oid = pki.oids[md.algorithm]; - } else { - var error = new Error("Unknown message digest algorithm."); - error.algorithm = md.algorithm; - throw error; - } - var oidBytes = asn1.oidToDer(oid).getBytes(); - var digestInfo = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - var digestAlgorithm = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - digestAlgorithm.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - oidBytes - )); - digestAlgorithm.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.NULL, - false, - "" - )); - var digest = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - md.digest().getBytes() - ); - digestInfo.value.push(digestAlgorithm); - digestInfo.value.push(digest); - return asn1.toDer(digestInfo).getBytes(); - }; - var _modPow = function(x, key, pub) { - if (pub) { - return x.modPow(key.e, key.n); - } - if (!key.p || !key.q) { - return x.modPow(key.d, key.n); - } - if (!key.dP) { - key.dP = key.d.mod(key.p.subtract(BigInteger2.ONE)); - } - if (!key.dQ) { - key.dQ = key.d.mod(key.q.subtract(BigInteger2.ONE)); - } - if (!key.qInv) { - key.qInv = key.q.modInverse(key.p); - } - var r; - do { - r = new BigInteger2( - forge3.util.bytesToHex(forge3.random.getBytes(key.n.bitLength() / 8)), - 16 - ); - } while (r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger2.ONE)); - x = x.multiply(r.modPow(key.e, key.n)).mod(key.n); - var xp = x.mod(key.p).modPow(key.dP, key.p); - var xq = x.mod(key.q).modPow(key.dQ, key.q); - while (xp.compareTo(xq) < 0) { - xp = xp.add(key.p); - } - var y = xp.subtract(xq).multiply(key.qInv).mod(key.p).multiply(key.q).add(xq); - y = y.multiply(r.modInverse(key.n)).mod(key.n); - return y; - }; - pki.rsa.encrypt = function(m, key, bt) { - var pub = bt; - var eb; - var k = Math.ceil(key.n.bitLength() / 8); - if (bt !== false && bt !== true) { - pub = bt === 2; - eb = _encodePkcs1_v1_5(m, key, bt); - } else { - eb = forge3.util.createBuffer(); - eb.putBytes(m); - } - var x = new BigInteger2(eb.toHex(), 16); - var y = _modPow(x, key, pub); - var yhex = y.toString(16); - var ed = forge3.util.createBuffer(); - var zeros = k - Math.ceil(yhex.length / 2); - while (zeros > 0) { - ed.putByte(0); - --zeros; - } - ed.putBytes(forge3.util.hexToBytes(yhex)); - return ed.getBytes(); - }; - pki.rsa.decrypt = function(ed, key, pub, ml) { - var k = Math.ceil(key.n.bitLength() / 8); - if (ed.length !== k) { - var error = new Error("Encrypted message length is invalid."); - error.length = ed.length; - error.expected = k; - throw error; - } - var y = new BigInteger2(forge3.util.createBuffer(ed).toHex(), 16); - if (y.compareTo(key.n) >= 0) { - throw new Error("Encrypted message is invalid."); - } - var x = _modPow(y, key, pub); - var xhex = x.toString(16); - var eb = forge3.util.createBuffer(); - var zeros = k - Math.ceil(xhex.length / 2); - while (zeros > 0) { - eb.putByte(0); - --zeros; - } - eb.putBytes(forge3.util.hexToBytes(xhex)); - if (ml !== false) { - return _decodePkcs1_v1_5(eb.getBytes(), key, pub); - } - return eb.getBytes(); - }; - pki.rsa.createKeyPairGenerationState = function(bits, e, options) { - if (typeof bits === "string") { - bits = parseInt(bits, 10); - } - bits = bits || 2048; - options = options || {}; - var prng = options.prng || forge3.random; - var rng = { - // x is an array to fill with bytes - nextBytes: function(x) { - var b = prng.getBytesSync(x.length); - for (var i = 0; i < x.length; ++i) { - x[i] = b.charCodeAt(i); - } - } - }; - var algorithm = options.algorithm || "PRIMEINC"; - var rval; - if (algorithm === "PRIMEINC") { - rval = { - algorithm, - state: 0, - bits, - rng, - eInt: e || 65537, - e: new BigInteger2(null), - p: null, - q: null, - qBits: bits >> 1, - pBits: bits - (bits >> 1), - pqState: 0, - num: null, - keys: null - }; - rval.e.fromInt(rval.eInt); - } else { - throw new Error("Invalid key generation algorithm: " + algorithm); - } - return rval; - }; - pki.rsa.stepKeyPairGenerationState = function(state, n) { - if (!("algorithm" in state)) { - state.algorithm = "PRIMEINC"; - } - var THIRTY = new BigInteger2(null); - THIRTY.fromInt(30); - var deltaIdx = 0; - var op_or = function(x, y) { - return x | y; - }; - var t1 = +/* @__PURE__ */ new Date(); - var t2; - var total = 0; - while (state.keys === null && (n <= 0 || total < n)) { - if (state.state === 0) { - var bits = state.p === null ? state.pBits : state.qBits; - var bits1 = bits - 1; - if (state.pqState === 0) { - state.num = new BigInteger2(bits, state.rng); - if (!state.num.testBit(bits1)) { - state.num.bitwiseTo( - BigInteger2.ONE.shiftLeft(bits1), - op_or, - state.num - ); - } - state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0); - deltaIdx = 0; - ++state.pqState; - } else if (state.pqState === 1) { - if (state.num.bitLength() > bits) { - state.pqState = 0; - } else if (state.num.isProbablePrime( - _getMillerRabinTests(state.num.bitLength()) - )) { - ++state.pqState; - } else { - state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); - } - } else if (state.pqState === 2) { - state.pqState = state.num.subtract(BigInteger2.ONE).gcd(state.e).compareTo(BigInteger2.ONE) === 0 ? 3 : 0; - } else if (state.pqState === 3) { - state.pqState = 0; - if (state.p === null) { - state.p = state.num; - } else { - state.q = state.num; - } - if (state.p !== null && state.q !== null) { - ++state.state; - } - state.num = null; - } - } else if (state.state === 1) { - if (state.p.compareTo(state.q) < 0) { - state.num = state.p; - state.p = state.q; - state.q = state.num; - } - ++state.state; - } else if (state.state === 2) { - state.p1 = state.p.subtract(BigInteger2.ONE); - state.q1 = state.q.subtract(BigInteger2.ONE); - state.phi = state.p1.multiply(state.q1); - ++state.state; - } else if (state.state === 3) { - if (state.phi.gcd(state.e).compareTo(BigInteger2.ONE) === 0) { - ++state.state; - } else { - state.p = null; - state.q = null; - state.state = 0; - } - } else if (state.state === 4) { - state.n = state.p.multiply(state.q); - if (state.n.bitLength() === state.bits) { - ++state.state; - } else { - state.q = null; - state.state = 0; - } - } else if (state.state === 5) { - var d = state.e.modInverse(state.phi); - state.keys = { - privateKey: pki.rsa.setPrivateKey( - state.n, - state.e, - d, - state.p, - state.q, - d.mod(state.p1), - d.mod(state.q1), - state.q.modInverse(state.p) - ), - publicKey: pki.rsa.setPublicKey(state.n, state.e) - }; - } - t2 = +/* @__PURE__ */ new Date(); - total += t2 - t1; - t1 = t2; - } - return state.keys !== null; - }; - pki.rsa.generateKeyPair = function(bits, e, options, callback) { - if (arguments.length === 1) { - if (typeof bits === "object") { - options = bits; - bits = void 0; - } else if (typeof bits === "function") { - callback = bits; - bits = void 0; - } - } else if (arguments.length === 2) { - if (typeof bits === "number") { - if (typeof e === "function") { - callback = e; - e = void 0; - } else if (typeof e !== "number") { - options = e; - e = void 0; - } - } else { - options = bits; - callback = e; - bits = void 0; - e = void 0; - } - } else if (arguments.length === 3) { - if (typeof e === "number") { - if (typeof options === "function") { - callback = options; - options = void 0; - } - } else { - callback = options; - options = e; - e = void 0; - } - } - options = options || {}; - if (bits === void 0) { - bits = options.bits || 2048; - } - if (e === void 0) { - e = options.e || 65537; - } - if (!forge3.options.usePureJavaScript && !options.prng && bits >= 256 && bits <= 16384 && (e === 65537 || e === 3)) { - if (callback) { - if (_detectNodeCrypto("generateKeyPair")) { - return _crypto.generateKeyPair("rsa", { - modulusLength: bits, - publicExponent: e, - publicKeyEncoding: { - type: "spki", - format: "pem" - }, - privateKeyEncoding: { - type: "pkcs8", - format: "pem" - } - }, function(err, pub, priv) { - if (err) { - return callback(err); - } - callback(null, { - privateKey: pki.privateKeyFromPem(priv), - publicKey: pki.publicKeyFromPem(pub) - }); - }); - } - if (_detectSubtleCrypto("generateKey") && _detectSubtleCrypto("exportKey")) { - return util.globalScope.crypto.subtle.generateKey({ - name: "RSASSA-PKCS1-v1_5", - modulusLength: bits, - publicExponent: _intToUint8Array(e), - hash: { name: "SHA-256" } - }, true, ["sign", "verify"]).then(function(pair) { - return util.globalScope.crypto.subtle.exportKey( - "pkcs8", - pair.privateKey - ); - }).then(void 0, function(err) { - callback(err); - }).then(function(pkcs8) { - if (pkcs8) { - var privateKey = pki.privateKeyFromAsn1( - asn1.fromDer(forge3.util.createBuffer(pkcs8)) - ); - callback(null, { - privateKey, - publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) - }); - } - }); - } - if (_detectSubtleMsCrypto("generateKey") && _detectSubtleMsCrypto("exportKey")) { - var genOp = util.globalScope.msCrypto.subtle.generateKey({ - name: "RSASSA-PKCS1-v1_5", - modulusLength: bits, - publicExponent: _intToUint8Array(e), - hash: { name: "SHA-256" } - }, true, ["sign", "verify"]); - genOp.oncomplete = function(e2) { - var pair = e2.target.result; - var exportOp = util.globalScope.msCrypto.subtle.exportKey( - "pkcs8", - pair.privateKey - ); - exportOp.oncomplete = function(e3) { - var pkcs8 = e3.target.result; - var privateKey = pki.privateKeyFromAsn1( - asn1.fromDer(forge3.util.createBuffer(pkcs8)) - ); - callback(null, { - privateKey, - publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) - }); - }; - exportOp.onerror = function(err) { - callback(err); - }; - }; - genOp.onerror = function(err) { - callback(err); - }; - return; - } - } else { - if (_detectNodeCrypto("generateKeyPairSync")) { - var keypair = _crypto.generateKeyPairSync("rsa", { - modulusLength: bits, - publicExponent: e, - publicKeyEncoding: { - type: "spki", - format: "pem" - }, - privateKeyEncoding: { - type: "pkcs8", - format: "pem" - } - }); - return { - privateKey: pki.privateKeyFromPem(keypair.privateKey), - publicKey: pki.publicKeyFromPem(keypair.publicKey) - }; - } - } - } - var state = pki.rsa.createKeyPairGenerationState(bits, e, options); - if (!callback) { - pki.rsa.stepKeyPairGenerationState(state, 0); - return state.keys; - } - _generateKeyPair(state, options, callback); - }; - pki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) { - var key = { - n, - e - }; - key.encrypt = function(data, scheme, schemeOptions) { - if (typeof scheme === "string") { - scheme = scheme.toUpperCase(); - } else if (scheme === void 0) { - scheme = "RSAES-PKCS1-V1_5"; - } - if (scheme === "RSAES-PKCS1-V1_5") { - scheme = { - encode: function(m, key2, pub) { - return _encodePkcs1_v1_5(m, key2, 2).getBytes(); - } - }; - } else if (scheme === "RSA-OAEP" || scheme === "RSAES-OAEP") { - scheme = { - encode: function(m, key2) { - return forge3.pkcs1.encode_rsa_oaep(key2, m, schemeOptions); - } - }; - } else if (["RAW", "NONE", "NULL", null].indexOf(scheme) !== -1) { - scheme = { encode: function(e3) { - return e3; - } }; - } else if (typeof scheme === "string") { - throw new Error('Unsupported encryption scheme: "' + scheme + '".'); - } - var e2 = scheme.encode(data, key, true); - return pki.rsa.encrypt(e2, key, true); - }; - key.verify = function(digest, signature, scheme, options) { - if (typeof scheme === "string") { - scheme = scheme.toUpperCase(); - } else if (scheme === void 0) { - scheme = "RSASSA-PKCS1-V1_5"; - } - if (options === void 0) { - options = { - _parseAllDigestBytes: true - }; - } - if (!("_parseAllDigestBytes" in options)) { - options._parseAllDigestBytes = true; - } - if (scheme === "RSASSA-PKCS1-V1_5") { - scheme = { - verify: function(digest2, d2) { - d2 = _decodePkcs1_v1_5(d2, key, true); - var obj = asn1.fromDer(d2, { - parseAllBytes: options._parseAllDigestBytes - }); - var capture = {}; - var errors = []; - if (!asn1.validate(obj, digestInfoValidator, capture, errors)) { - var error = new Error( - "ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value." - ); - error.errors = errors; - throw error; - } - var oid = asn1.derToOid(capture.algorithmIdentifier); - if (!(oid === forge3.oids.md2 || oid === forge3.oids.md5 || oid === forge3.oids.sha1 || oid === forge3.oids.sha224 || oid === forge3.oids.sha256 || oid === forge3.oids.sha384 || oid === forge3.oids.sha512 || oid === forge3.oids["sha512-224"] || oid === forge3.oids["sha512-256"])) { - var error = new Error( - "Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier." - ); - error.oid = oid; - throw error; - } - if (oid === forge3.oids.md2 || oid === forge3.oids.md5) { - if (!("parameters" in capture)) { - throw new Error( - "ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters." - ); - } - } - return digest2 === capture.digest; - } - }; - } else if (scheme === "NONE" || scheme === "NULL" || scheme === null) { - scheme = { - verify: function(digest2, d2) { - d2 = _decodePkcs1_v1_5(d2, key, true); - return digest2 === d2; - } - }; - } - var d = pki.rsa.decrypt(signature, key, true, false); - return scheme.verify(digest, d, key.n.bitLength()); - }; - return key; - }; - pki.setRsaPrivateKey = pki.rsa.setPrivateKey = function(n, e, d, p, q, dP, dQ, qInv) { - var key = { - n, - e, - d, - p, - q, - dP, - dQ, - qInv - }; - key.decrypt = function(data, scheme, schemeOptions) { - if (typeof scheme === "string") { - scheme = scheme.toUpperCase(); - } else if (scheme === void 0) { - scheme = "RSAES-PKCS1-V1_5"; - } - var d2 = pki.rsa.decrypt(data, key, false, false); - if (scheme === "RSAES-PKCS1-V1_5") { - scheme = { decode: _decodePkcs1_v1_5 }; - } else if (scheme === "RSA-OAEP" || scheme === "RSAES-OAEP") { - scheme = { - decode: function(d3, key2) { - return forge3.pkcs1.decode_rsa_oaep(key2, d3, schemeOptions); - } - }; - } else if (["RAW", "NONE", "NULL", null].indexOf(scheme) !== -1) { - scheme = { decode: function(d3) { - return d3; - } }; - } else { - throw new Error('Unsupported encryption scheme: "' + scheme + '".'); - } - return scheme.decode(d2, key, false); - }; - key.sign = function(md, scheme) { - var bt = false; - if (typeof scheme === "string") { - scheme = scheme.toUpperCase(); - } - if (scheme === void 0 || scheme === "RSASSA-PKCS1-V1_5") { - scheme = { encode: emsaPkcs1v15encode }; - bt = 1; - } else if (scheme === "NONE" || scheme === "NULL" || scheme === null) { - scheme = { encode: function() { - return md; - } }; - bt = 1; - } - var d2 = scheme.encode(md, key.n.bitLength()); - return pki.rsa.encrypt(d2, key, bt); - }; - return key; - }; - pki.wrapRsaPrivateKey = function(rsaKey) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version (0) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(0).getBytes() - ), - // privateKeyAlgorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.rsaEncryption).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]), - // PrivateKey - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(rsaKey).getBytes() - ) - ]); - }; - pki.privateKeyFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - if (asn1.validate(obj, privateKeyValidator, capture, errors)) { - obj = asn1.fromDer(forge3.util.createBuffer(capture.privateKey)); - } - capture = {}; - errors = []; - if (!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) { - var error = new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey."); - error.errors = errors; - throw error; - } - var n, e, d, p, q, dP, dQ, qInv; - n = forge3.util.createBuffer(capture.privateKeyModulus).toHex(); - e = forge3.util.createBuffer(capture.privateKeyPublicExponent).toHex(); - d = forge3.util.createBuffer(capture.privateKeyPrivateExponent).toHex(); - p = forge3.util.createBuffer(capture.privateKeyPrime1).toHex(); - q = forge3.util.createBuffer(capture.privateKeyPrime2).toHex(); - dP = forge3.util.createBuffer(capture.privateKeyExponent1).toHex(); - dQ = forge3.util.createBuffer(capture.privateKeyExponent2).toHex(); - qInv = forge3.util.createBuffer(capture.privateKeyCoefficient).toHex(); - return pki.setRsaPrivateKey( - new BigInteger2(n, 16), - new BigInteger2(e, 16), - new BigInteger2(d, 16), - new BigInteger2(p, 16), - new BigInteger2(q, 16), - new BigInteger2(dP, 16), - new BigInteger2(dQ, 16), - new BigInteger2(qInv, 16) - ); - }; - pki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version (0 = only 2 primes, 1 multiple primes) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(0).getBytes() - ), - // modulus (n) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.n) - ), - // publicExponent (e) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.e) - ), - // privateExponent (d) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.d) - ), - // privateKeyPrime1 (p) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.p) - ), - // privateKeyPrime2 (q) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.q) - ), - // privateKeyExponent1 (dP) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.dP) - ), - // privateKeyExponent2 (dQ) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.dQ) - ), - // coefficient (qInv) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.qInv) - ) - ]); - }; - pki.publicKeyFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - if (asn1.validate(obj, publicKeyValidator, capture, errors)) { - var oid = asn1.derToOid(capture.publicKeyOid); - if (oid !== pki.oids.rsaEncryption) { - var error = new Error("Cannot read public key. Unknown OID."); - error.oid = oid; - throw error; - } - obj = capture.rsaPublicKey; - } - errors = []; - if (!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) { - var error = new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey."); - error.errors = errors; - throw error; - } - var n = forge3.util.createBuffer(capture.publicKeyModulus).toHex(); - var e = forge3.util.createBuffer(capture.publicKeyExponent).toHex(); - return pki.setRsaPublicKey( - new BigInteger2(n, 16), - new BigInteger2(e, 16) - ); - }; - pki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.rsaEncryption).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]), - // subjectPublicKey - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [ - pki.publicKeyToRSAPublicKey(key) - ]) - ]); - }; - pki.publicKeyToRSAPublicKey = function(key) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // modulus (n) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.n) - ), - // publicExponent (e) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.e) - ) - ]); - }; - function _encodePkcs1_v1_5(m, key, bt) { - var eb = forge3.util.createBuffer(); - var k = Math.ceil(key.n.bitLength() / 8); - if (m.length > k - 11) { - var error = new Error("Message is too long for PKCS#1 v1.5 padding."); - error.length = m.length; - error.max = k - 11; - throw error; - } - eb.putByte(0); - eb.putByte(bt); - var padNum = k - 3 - m.length; - var padByte; - if (bt === 0 || bt === 1) { - padByte = bt === 0 ? 0 : 255; - for (var i = 0; i < padNum; ++i) { - eb.putByte(padByte); - } - } else { - while (padNum > 0) { - var numZeros = 0; - var padBytes = forge3.random.getBytes(padNum); - for (var i = 0; i < padNum; ++i) { - padByte = padBytes.charCodeAt(i); - if (padByte === 0) { - ++numZeros; - } else { - eb.putByte(padByte); - } - } - padNum = numZeros; - } - } - eb.putByte(0); - eb.putBytes(m); - return eb; - } - function _decodePkcs1_v1_5(em, key, pub, ml) { - var k = Math.ceil(key.n.bitLength() / 8); - var eb = forge3.util.createBuffer(em); - var first = eb.getByte(); - var bt = eb.getByte(); - if (first !== 0 || pub && bt !== 0 && bt !== 1 || !pub && bt != 2 || pub && bt === 0 && typeof ml === "undefined") { - throw new Error("Encryption block is invalid."); - } - var padNum = 0; - if (bt === 0) { - padNum = k - 3 - ml; - for (var i = 0; i < padNum; ++i) { - if (eb.getByte() !== 0) { - throw new Error("Encryption block is invalid."); - } - } - } else if (bt === 1) { - padNum = 0; - while (eb.length() > 1) { - if (eb.getByte() !== 255) { - --eb.read; - break; - } - ++padNum; - } - } else if (bt === 2) { - padNum = 0; - while (eb.length() > 1) { - if (eb.getByte() === 0) { - --eb.read; - break; - } - ++padNum; - } - } - var zero = eb.getByte(); - if (zero !== 0 || padNum !== k - 3 - eb.length()) { - throw new Error("Encryption block is invalid."); - } - return eb.getBytes(); - } - function _generateKeyPair(state, options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; - } - options = options || {}; - var opts = { - algorithm: { - name: options.algorithm || "PRIMEINC", - options: { - workers: options.workers || 2, - workLoad: options.workLoad || 100, - workerScript: options.workerScript - } - } - }; - if ("prng" in options) { - opts.prng = options.prng; - } - generate(); - function generate() { - getPrime(state.pBits, function(err, num) { - if (err) { - return callback(err); - } - state.p = num; - if (state.q !== null) { - return finish(err, state.q); - } - getPrime(state.qBits, finish); - }); - } - function getPrime(bits, callback2) { - forge3.prime.generateProbablePrime(bits, opts, callback2); - } - function finish(err, num) { - if (err) { - return callback(err); - } - state.q = num; - if (state.p.compareTo(state.q) < 0) { - var tmp = state.p; - state.p = state.q; - state.q = tmp; - } - if (state.p.subtract(BigInteger2.ONE).gcd(state.e).compareTo(BigInteger2.ONE) !== 0) { - state.p = null; - generate(); - return; - } - if (state.q.subtract(BigInteger2.ONE).gcd(state.e).compareTo(BigInteger2.ONE) !== 0) { - state.q = null; - getPrime(state.qBits, finish); - return; - } - state.p1 = state.p.subtract(BigInteger2.ONE); - state.q1 = state.q.subtract(BigInteger2.ONE); - state.phi = state.p1.multiply(state.q1); - if (state.phi.gcd(state.e).compareTo(BigInteger2.ONE) !== 0) { - state.p = state.q = null; - generate(); - return; - } - state.n = state.p.multiply(state.q); - if (state.n.bitLength() !== state.bits) { - state.q = null; - getPrime(state.qBits, finish); - return; - } - var d = state.e.modInverse(state.phi); - state.keys = { - privateKey: pki.rsa.setPrivateKey( - state.n, - state.e, - d, - state.p, - state.q, - d.mod(state.p1), - d.mod(state.q1), - state.q.modInverse(state.p) - ), - publicKey: pki.rsa.setPublicKey(state.n, state.e) - }; - callback(null, state.keys); - } - } - function _bnToBytes(b) { - var hex = b.toString(16); - if (hex[0] >= "8") { - hex = "00" + hex; - } - var bytes = forge3.util.hexToBytes(hex); - if (bytes.length > 1 && // leading 0x00 for positive integer - (bytes.charCodeAt(0) === 0 && (bytes.charCodeAt(1) & 128) === 0 || // leading 0xFF for negative integer - bytes.charCodeAt(0) === 255 && (bytes.charCodeAt(1) & 128) === 128)) { - return bytes.substr(1); - } - return bytes; - } - function _getMillerRabinTests(bits) { - if (bits <= 100) return 27; - if (bits <= 150) return 18; - if (bits <= 200) return 15; - if (bits <= 250) return 12; - if (bits <= 300) return 9; - if (bits <= 350) return 8; - if (bits <= 400) return 7; - if (bits <= 500) return 6; - if (bits <= 600) return 5; - if (bits <= 800) return 4; - if (bits <= 1250) return 3; - return 2; - } - function _detectNodeCrypto(fn) { - return forge3.util.isNodejs && typeof _crypto[fn] === "function"; - } - function _detectSubtleCrypto(fn) { - return typeof util.globalScope !== "undefined" && typeof util.globalScope.crypto === "object" && typeof util.globalScope.crypto.subtle === "object" && typeof util.globalScope.crypto.subtle[fn] === "function"; - } - function _detectSubtleMsCrypto(fn) { - return typeof util.globalScope !== "undefined" && typeof util.globalScope.msCrypto === "object" && typeof util.globalScope.msCrypto.subtle === "object" && typeof util.globalScope.msCrypto.subtle[fn] === "function"; - } - function _intToUint8Array(x) { - var bytes = forge3.util.hexToBytes(x.toString(16)); - var buffer = new Uint8Array(bytes.length); - for (var i = 0; i < bytes.length; ++i) { - buffer[i] = bytes.charCodeAt(i); - } - return buffer; - } - } -}); - -// node_modules/node-forge/lib/pbe.js -var require_pbe = __commonJS({ - "node_modules/node-forge/lib/pbe.js"(exports, module) { - var forge3 = require_forge(); - require_aes(); - require_asn1(); - require_des(); - require_md(); - require_oids(); - require_pbkdf2(); - require_pem(); - require_random(); - require_rc2(); - require_rsa(); - require_util(); - if (typeof BigInteger2 === "undefined") { - BigInteger2 = forge3.jsbn.BigInteger; - } - var BigInteger2; - var asn1 = forge3.asn1; - var pki = forge3.pki = forge3.pki || {}; - module.exports = pki.pbe = forge3.pbe = forge3.pbe || {}; - var oids = pki.oids; - var encryptedPrivateKeyValidator = { - name: "EncryptedPrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EncryptedPrivateKeyInfo.encryptionAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "encryptionOid" - }, { - name: "AlgorithmIdentifier.parameters", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "encryptionParams" - }] - }, { - // encryptedData - name: "EncryptedPrivateKeyInfo.encryptedData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "encryptedData" - }] - }; - var PBES2AlgorithmsValidator = { - name: "PBES2Algorithms", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "PBES2Algorithms.keyDerivationFunc", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "PBES2Algorithms.keyDerivationFunc.oid", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "kdfOid" - }, { - name: "PBES2Algorithms.params", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "PBES2Algorithms.params.salt", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "kdfSalt" - }, { - name: "PBES2Algorithms.params.iterationCount", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "kdfIterationCount" - }, { - name: "PBES2Algorithms.params.keyLength", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - optional: true, - capture: "keyLength" - }, { - // prf - name: "PBES2Algorithms.params.prf", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: "PBES2Algorithms.params.prf.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "prfOid" - }] - }] - }] - }, { - name: "PBES2Algorithms.encryptionScheme", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "PBES2Algorithms.encryptionScheme.oid", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "encOid" - }, { - name: "PBES2Algorithms.encryptionScheme.iv", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "encIv" - }] - }] - }; - var pkcs12PbeParamsValidator = { - name: "pkcs-12PbeParams", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "pkcs-12PbeParams.salt", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "salt" - }, { - name: "pkcs-12PbeParams.iterations", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "iterations" - }] - }; - pki.encryptPrivateKeyInfo = function(obj, password, options) { - options = options || {}; - options.saltSize = options.saltSize || 8; - options.count = options.count || 2048; - options.algorithm = options.algorithm || "aes128"; - options.prfAlgorithm = options.prfAlgorithm || "sha1"; - var salt = forge3.random.getBytesSync(options.saltSize); - var count = options.count; - var countBytes = asn1.integerToDer(count); - var dkLen; - var encryptionAlgorithm; - var encryptedData; - if (options.algorithm.indexOf("aes") === 0 || options.algorithm === "des") { - var ivLen, encOid, cipherFn; - switch (options.algorithm) { - case "aes128": - dkLen = 16; - ivLen = 16; - encOid = oids["aes128-CBC"]; - cipherFn = forge3.aes.createEncryptionCipher; - break; - case "aes192": - dkLen = 24; - ivLen = 16; - encOid = oids["aes192-CBC"]; - cipherFn = forge3.aes.createEncryptionCipher; - break; - case "aes256": - dkLen = 32; - ivLen = 16; - encOid = oids["aes256-CBC"]; - cipherFn = forge3.aes.createEncryptionCipher; - break; - case "des": - dkLen = 8; - ivLen = 8; - encOid = oids["desCBC"]; - cipherFn = forge3.des.createEncryptionCipher; - break; - default: - var error = new Error("Cannot encrypt private key. Unknown encryption algorithm."); - error.algorithm = options.algorithm; - throw error; - } - var prfAlgorithm = "hmacWith" + options.prfAlgorithm.toUpperCase(); - var md = prfAlgorithmToMessageDigest(prfAlgorithm); - var dk = forge3.pkcs5.pbkdf2(password, salt, count, dkLen, md); - var iv = forge3.random.getBytesSync(ivLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(asn1.toDer(obj)); - cipher.finish(); - encryptedData = cipher.output.getBytes(); - var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm); - encryptionAlgorithm = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oids["pkcs5PBES2"]).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // keyDerivationFunc - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oids["pkcs5PBKDF2"]).getBytes() - ), - // PBKDF2-params - params - ]), - // encryptionScheme - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(encOid).getBytes() - ), - // iv - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - iv - ) - ]) - ]) - ] - ); - } else if (options.algorithm === "3des") { - dkLen = 24; - var saltBytes = new forge3.util.ByteBuffer(salt); - var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen); - var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen); - var cipher = forge3.des.createEncryptionCipher(dk); - cipher.start(iv); - cipher.update(asn1.toDer(obj)); - cipher.finish(); - encryptedData = cipher.output.getBytes(); - encryptionAlgorithm = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes() - ), - // pkcs-12PbeParams - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // salt - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), - // iteration count - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - countBytes.getBytes() - ) - ]) - ] - ); - } else { - var error = new Error("Cannot encrypt private key. Unknown encryption algorithm."); - error.algorithm = options.algorithm; - throw error; - } - var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // encryptionAlgorithm - encryptionAlgorithm, - // encryptedData - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - encryptedData - ) - ]); - return rval; - }; - pki.decryptPrivateKeyInfo = function(obj, password) { - var rval = null; - var capture = {}; - var errors = []; - if (!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) { - var error = new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); - error.errors = errors; - throw error; - } - var oid = asn1.derToOid(capture.encryptionOid); - var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password); - var encrypted = forge3.util.createBuffer(capture.encryptedData); - cipher.update(encrypted); - if (cipher.finish()) { - rval = asn1.fromDer(cipher.output); - } - return rval; - }; - pki.encryptedPrivateKeyToPem = function(epki, maxline) { - var msg = { - type: "ENCRYPTED PRIVATE KEY", - body: asn1.toDer(epki).getBytes() - }; - return forge3.pem.encode(msg, { maxline }); - }; - pki.encryptedPrivateKeyFromPem = function(pem) { - var msg = forge3.pem.decode(pem)[0]; - if (msg.type !== "ENCRYPTED PRIVATE KEY") { - var error = new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".'); - error.headerType = msg.type; - throw error; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted."); - } - return asn1.fromDer(msg.body); - }; - pki.encryptRsaPrivateKey = function(rsaKey, password, options) { - options = options || {}; - if (!options.legacy) { - var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey)); - rval = pki.encryptPrivateKeyInfo(rval, password, options); - return pki.encryptedPrivateKeyToPem(rval); - } - var algorithm; - var iv; - var dkLen; - var cipherFn; - switch (options.algorithm) { - case "aes128": - algorithm = "AES-128-CBC"; - dkLen = 16; - iv = forge3.random.getBytesSync(16); - cipherFn = forge3.aes.createEncryptionCipher; - break; - case "aes192": - algorithm = "AES-192-CBC"; - dkLen = 24; - iv = forge3.random.getBytesSync(16); - cipherFn = forge3.aes.createEncryptionCipher; - break; - case "aes256": - algorithm = "AES-256-CBC"; - dkLen = 32; - iv = forge3.random.getBytesSync(16); - cipherFn = forge3.aes.createEncryptionCipher; - break; - case "3des": - algorithm = "DES-EDE3-CBC"; - dkLen = 24; - iv = forge3.random.getBytesSync(8); - cipherFn = forge3.des.createEncryptionCipher; - break; - case "des": - algorithm = "DES-CBC"; - dkLen = 8; - iv = forge3.random.getBytesSync(8); - cipherFn = forge3.des.createEncryptionCipher; - break; - default: - var error = new Error('Could not encrypt RSA private key; unsupported encryption algorithm "' + options.algorithm + '".'); - error.algorithm = options.algorithm; - throw error; - } - var dk = forge3.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey))); - cipher.finish(); - var msg = { - type: "RSA PRIVATE KEY", - procType: { - version: "4", - type: "ENCRYPTED" - }, - dekInfo: { - algorithm, - parameters: forge3.util.bytesToHex(iv).toUpperCase() - }, - body: cipher.output.getBytes() - }; - return forge3.pem.encode(msg); - }; - pki.decryptRsaPrivateKey = function(pem, password) { - var rval = null; - var msg = forge3.pem.decode(pem)[0]; - if (msg.type !== "ENCRYPTED PRIVATE KEY" && msg.type !== "PRIVATE KEY" && msg.type !== "RSA PRIVATE KEY") { - var error = new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".'); - error.headerType = error; - throw error; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - var dkLen; - var cipherFn; - switch (msg.dekInfo.algorithm) { - case "DES-CBC": - dkLen = 8; - cipherFn = forge3.des.createDecryptionCipher; - break; - case "DES-EDE3-CBC": - dkLen = 24; - cipherFn = forge3.des.createDecryptionCipher; - break; - case "AES-128-CBC": - dkLen = 16; - cipherFn = forge3.aes.createDecryptionCipher; - break; - case "AES-192-CBC": - dkLen = 24; - cipherFn = forge3.aes.createDecryptionCipher; - break; - case "AES-256-CBC": - dkLen = 32; - cipherFn = forge3.aes.createDecryptionCipher; - break; - case "RC2-40-CBC": - dkLen = 5; - cipherFn = function(key) { - return forge3.rc2.createDecryptionCipher(key, 40); - }; - break; - case "RC2-64-CBC": - dkLen = 8; - cipherFn = function(key) { - return forge3.rc2.createDecryptionCipher(key, 64); - }; - break; - case "RC2-128-CBC": - dkLen = 16; - cipherFn = function(key) { - return forge3.rc2.createDecryptionCipher(key, 128); - }; - break; - default: - var error = new Error('Could not decrypt private key; unsupported encryption algorithm "' + msg.dekInfo.algorithm + '".'); - error.algorithm = msg.dekInfo.algorithm; - throw error; - } - var iv = forge3.util.hexToBytes(msg.dekInfo.parameters); - var dk = forge3.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(forge3.util.createBuffer(msg.body)); - if (cipher.finish()) { - rval = cipher.output.getBytes(); - } else { - return rval; - } - } else { - rval = msg.body; - } - if (msg.type === "ENCRYPTED PRIVATE KEY") { - rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password); - } else { - rval = asn1.fromDer(rval); - } - if (rval !== null) { - rval = pki.privateKeyFromAsn1(rval); - } - return rval; - }; - pki.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) { - var j, l; - if (typeof md === "undefined" || md === null) { - if (!("sha1" in forge3.md)) { - throw new Error('"sha1" hash algorithm unavailable.'); - } - md = forge3.md.sha1.create(); - } - var u = md.digestLength; - var v = md.blockLength; - var result = new forge3.util.ByteBuffer(); - var passBuf = new forge3.util.ByteBuffer(); - if (password !== null && password !== void 0) { - for (l = 0; l < password.length; l++) { - passBuf.putInt16(password.charCodeAt(l)); - } - passBuf.putInt16(0); - } - var p = passBuf.length(); - var s = salt.length(); - var D = new forge3.util.ByteBuffer(); - D.fillWithByte(id, v); - var Slen = v * Math.ceil(s / v); - var S = new forge3.util.ByteBuffer(); - for (l = 0; l < Slen; l++) { - S.putByte(salt.at(l % s)); - } - var Plen = v * Math.ceil(p / v); - var P = new forge3.util.ByteBuffer(); - for (l = 0; l < Plen; l++) { - P.putByte(passBuf.at(l % p)); - } - var I = S; - I.putBuffer(P); - var c = Math.ceil(n / u); - for (var i = 1; i <= c; i++) { - var buf = new forge3.util.ByteBuffer(); - buf.putBytes(D.bytes()); - buf.putBytes(I.bytes()); - for (var round = 0; round < iter; round++) { - md.start(); - md.update(buf.getBytes()); - buf = md.digest(); - } - var B = new forge3.util.ByteBuffer(); - for (l = 0; l < v; l++) { - B.putByte(buf.at(l % u)); - } - var k = Math.ceil(s / v) + Math.ceil(p / v); - var Inew = new forge3.util.ByteBuffer(); - for (j = 0; j < k; j++) { - var chunk = new forge3.util.ByteBuffer(I.getBytes(v)); - var x = 511; - for (l = B.length() - 1; l >= 0; l--) { - x = x >> 8; - x += B.at(l) + chunk.at(l); - chunk.setAt(l, x & 255); - } - Inew.putBuffer(chunk); - } - I = Inew; - result.putBuffer(buf); - } - result.truncate(result.length() - n); - return result; - }; - pki.pbe.getCipher = function(oid, params, password) { - switch (oid) { - case pki.oids["pkcs5PBES2"]: - return pki.pbe.getCipherForPBES2(oid, params, password); - case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]: - case pki.oids["pbewithSHAAnd40BitRC2-CBC"]: - return pki.pbe.getCipherForPKCS12PBE(oid, params, password); - default: - var error = new Error("Cannot read encrypted PBE data block. Unsupported OID."); - error.oid = oid; - error.supportedOids = [ - "pkcs5PBES2", - "pbeWithSHAAnd3-KeyTripleDES-CBC", - "pbewithSHAAnd40BitRC2-CBC" - ]; - throw error; - } - }; - pki.pbe.getCipherForPBES2 = function(oid, params, password) { - var capture = {}; - var errors = []; - if (!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) { - var error = new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); - error.errors = errors; - throw error; - } - oid = asn1.derToOid(capture.kdfOid); - if (oid !== pki.oids["pkcs5PBKDF2"]) { - var error = new Error("Cannot read encrypted private key. Unsupported key derivation function OID."); - error.oid = oid; - error.supportedOids = ["pkcs5PBKDF2"]; - throw error; - } - oid = asn1.derToOid(capture.encOid); - if (oid !== pki.oids["aes128-CBC"] && oid !== pki.oids["aes192-CBC"] && oid !== pki.oids["aes256-CBC"] && oid !== pki.oids["des-EDE3-CBC"] && oid !== pki.oids["desCBC"]) { - var error = new Error("Cannot read encrypted private key. Unsupported encryption scheme OID."); - error.oid = oid; - error.supportedOids = [ - "aes128-CBC", - "aes192-CBC", - "aes256-CBC", - "des-EDE3-CBC", - "desCBC" - ]; - throw error; - } - var salt = capture.kdfSalt; - var count = forge3.util.createBuffer(capture.kdfIterationCount); - count = count.getInt(count.length() << 3); - var dkLen; - var cipherFn; - switch (pki.oids[oid]) { - case "aes128-CBC": - dkLen = 16; - cipherFn = forge3.aes.createDecryptionCipher; - break; - case "aes192-CBC": - dkLen = 24; - cipherFn = forge3.aes.createDecryptionCipher; - break; - case "aes256-CBC": - dkLen = 32; - cipherFn = forge3.aes.createDecryptionCipher; - break; - case "des-EDE3-CBC": - dkLen = 24; - cipherFn = forge3.des.createDecryptionCipher; - break; - case "desCBC": - dkLen = 8; - cipherFn = forge3.des.createDecryptionCipher; - break; - } - var md = prfOidToMessageDigest(capture.prfOid); - var dk = forge3.pkcs5.pbkdf2(password, salt, count, dkLen, md); - var iv = capture.encIv; - var cipher = cipherFn(dk); - cipher.start(iv); - return cipher; - }; - pki.pbe.getCipherForPKCS12PBE = function(oid, params, password) { - var capture = {}; - var errors = []; - if (!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) { - var error = new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); - error.errors = errors; - throw error; - } - var salt = forge3.util.createBuffer(capture.salt); - var count = forge3.util.createBuffer(capture.iterations); - count = count.getInt(count.length() << 3); - var dkLen, dIvLen, cipherFn; - switch (oid) { - case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]: - dkLen = 24; - dIvLen = 8; - cipherFn = forge3.des.startDecrypting; - break; - case pki.oids["pbewithSHAAnd40BitRC2-CBC"]: - dkLen = 5; - dIvLen = 8; - cipherFn = function(key2, iv2) { - var cipher = forge3.rc2.createDecryptionCipher(key2, 40); - cipher.start(iv2, null); - return cipher; - }; - break; - default: - var error = new Error("Cannot read PKCS #12 PBE data block. Unsupported OID."); - error.oid = oid; - throw error; - } - var md = prfOidToMessageDigest(capture.prfOid); - var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md); - md.start(); - var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md); - return cipherFn(key, iv); - }; - pki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) { - if (typeof md === "undefined" || md === null) { - if (!("md5" in forge3.md)) { - throw new Error('"md5" hash algorithm unavailable.'); - } - md = forge3.md.md5.create(); - } - if (salt === null) { - salt = ""; - } - var digests = [hash(md, password + salt)]; - for (var length = 16, i = 1; length < dkLen; ++i, length += 16) { - digests.push(hash(md, digests[i - 1] + password + salt)); - } - return digests.join("").substr(0, dkLen); - }; - function hash(md, bytes) { - return md.start().update(bytes).digest().getBytes(); - } - function prfOidToMessageDigest(prfOid) { - var prfAlgorithm; - if (!prfOid) { - prfAlgorithm = "hmacWithSHA1"; - } else { - prfAlgorithm = pki.oids[asn1.derToOid(prfOid)]; - if (!prfAlgorithm) { - var error = new Error("Unsupported PRF OID."); - error.oid = prfOid; - error.supported = [ - "hmacWithSHA1", - "hmacWithSHA224", - "hmacWithSHA256", - "hmacWithSHA384", - "hmacWithSHA512" - ]; - throw error; - } - } - return prfAlgorithmToMessageDigest(prfAlgorithm); - } - function prfAlgorithmToMessageDigest(prfAlgorithm) { - var factory = forge3.md; - switch (prfAlgorithm) { - case "hmacWithSHA224": - factory = forge3.md.sha512; - case "hmacWithSHA1": - case "hmacWithSHA256": - case "hmacWithSHA384": - case "hmacWithSHA512": - prfAlgorithm = prfAlgorithm.substr(8).toLowerCase(); - break; - default: - var error = new Error("Unsupported PRF algorithm."); - error.algorithm = prfAlgorithm; - error.supported = [ - "hmacWithSHA1", - "hmacWithSHA224", - "hmacWithSHA256", - "hmacWithSHA384", - "hmacWithSHA512" - ]; - throw error; - } - if (!factory || !(prfAlgorithm in factory)) { - throw new Error("Unknown hash algorithm: " + prfAlgorithm); - } - return factory[prfAlgorithm].create(); - } - function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) { - var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // salt - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - salt - ), - // iteration count - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - countBytes.getBytes() - ) - ]); - if (prfAlgorithm !== "hmacWithSHA1") { - params.value.push( - // key length - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - forge3.util.hexToBytes(dkLen.toString(16)) - ), - // AlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ); - } - return params; - } - } -}); - -// node_modules/node-forge/lib/pkcs7asn1.js -var require_pkcs7asn1 = __commonJS({ - "node_modules/node-forge/lib/pkcs7asn1.js"(exports, module) { - var forge3 = require_forge(); - require_asn1(); - require_util(); - var asn1 = forge3.asn1; - var p7v = module.exports = forge3.pkcs7asn1 = forge3.pkcs7asn1 || {}; - forge3.pkcs7 = forge3.pkcs7 || {}; - forge3.pkcs7.asn1 = p7v; - var contentInfoValidator = { - name: "ContentInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "ContentInfo.ContentType", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "contentType" - }, { - name: "ContentInfo.content", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - captureAsn1: "content" - }] - }; - p7v.contentInfoValidator = contentInfoValidator; - var encryptedContentInfoValidator = { - name: "EncryptedContentInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EncryptedContentInfo.contentType", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "contentType" - }, { - name: "EncryptedContentInfo.contentEncryptionAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EncryptedContentInfo.contentEncryptionAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "encAlgorithm" - }, { - name: "EncryptedContentInfo.contentEncryptionAlgorithm.parameter", - tagClass: asn1.Class.UNIVERSAL, - captureAsn1: "encParameter" - }] - }, { - name: "EncryptedContentInfo.encryptedContent", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - /* The PKCS#7 structure output by OpenSSL somewhat differs from what - * other implementations do generate. - * - * OpenSSL generates a structure like this: - * SEQUENCE { - * ... - * [0] - * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 - * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 - * ... - * } - * - * Whereas other implementations (and this PKCS#7 module) generate: - * SEQUENCE { - * ... - * [0] { - * OCTET STRING - * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 - * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 - * ... - * } - * } - * - * In order to support both, we just capture the context specific - * field here. The OCTET STRING bit is removed below. - */ - capture: "encryptedContent", - captureAsn1: "encryptedContentAsn1" - }] - }; - p7v.envelopedDataValidator = { - name: "EnvelopedData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EnvelopedData.Version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }, { - name: "EnvelopedData.RecipientInfos", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - captureAsn1: "recipientInfos" - }].concat(encryptedContentInfoValidator) - }; - p7v.encryptedDataValidator = { - name: "EncryptedData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EncryptedData.Version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }].concat(encryptedContentInfoValidator) - }; - var signerValidator = { - name: "SignerInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "SignerInfo.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false - }, { - name: "SignerInfo.issuerAndSerialNumber", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "SignerInfo.issuerAndSerialNumber.issuer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "issuer" - }, { - name: "SignerInfo.issuerAndSerialNumber.serialNumber", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "serial" - }] - }, { - name: "SignerInfo.digestAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "SignerInfo.digestAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "digestAlgorithm" - }, { - name: "SignerInfo.digestAlgorithm.parameter", - tagClass: asn1.Class.UNIVERSAL, - constructed: false, - captureAsn1: "digestParameter", - optional: true - }] - }, { - name: "SignerInfo.authenticatedAttributes", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - capture: "authenticatedAttributes" - }, { - name: "SignerInfo.digestEncryptionAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - capture: "signatureAlgorithm" - }, { - name: "SignerInfo.encryptedDigest", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "signature" - }, { - name: "SignerInfo.unauthenticatedAttributes", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - optional: true, - capture: "unauthenticatedAttributes" - }] - }; - p7v.signedDataValidator = { - name: "SignedData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [ - { - name: "SignedData.Version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }, - { - name: "SignedData.DigestAlgorithms", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - captureAsn1: "digestAlgorithms" - }, - contentInfoValidator, - { - name: "SignedData.Certificates", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - optional: true, - captureAsn1: "certificates" - }, - { - name: "SignedData.CertificateRevocationLists", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - optional: true, - captureAsn1: "crls" - }, - { - name: "SignedData.SignerInfos", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - capture: "signerInfos", - optional: true, - value: [signerValidator] - } - ] - }; - p7v.recipientInfoValidator = { - name: "RecipientInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "RecipientInfo.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }, { - name: "RecipientInfo.issuerAndSerial", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "RecipientInfo.issuerAndSerial.issuer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "issuer" - }, { - name: "RecipientInfo.issuerAndSerial.serialNumber", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "serial" - }] - }, { - name: "RecipientInfo.keyEncryptionAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "RecipientInfo.keyEncryptionAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "encAlgorithm" - }, { - name: "RecipientInfo.keyEncryptionAlgorithm.parameter", - tagClass: asn1.Class.UNIVERSAL, - constructed: false, - captureAsn1: "encParameter", - optional: true - }] - }, { - name: "RecipientInfo.encryptedKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "encKey" - }] - }; - } -}); - -// node_modules/node-forge/lib/mgf1.js -var require_mgf1 = __commonJS({ - "node_modules/node-forge/lib/mgf1.js"(exports, module) { - var forge3 = require_forge(); - require_util(); - forge3.mgf = forge3.mgf || {}; - var mgf1 = module.exports = forge3.mgf.mgf1 = forge3.mgf1 = forge3.mgf1 || {}; - mgf1.create = function(md) { - var mgf = { - /** - * Generate mask of specified length. - * - * @param {String} seed The seed for mask generation. - * @param maskLen Number of bytes to generate. - * @return {String} The generated mask. - */ - generate: function(seed, maskLen) { - var t = new forge3.util.ByteBuffer(); - var len = Math.ceil(maskLen / md.digestLength); - for (var i = 0; i < len; i++) { - var c = new forge3.util.ByteBuffer(); - c.putInt32(i); - md.start(); - md.update(seed + c.getBytes()); - t.putBuffer(md.digest()); - } - t.truncate(t.length() - maskLen); - return t.getBytes(); - } - }; - return mgf; - }; - } -}); - -// node_modules/node-forge/lib/mgf.js -var require_mgf = __commonJS({ - "node_modules/node-forge/lib/mgf.js"(exports, module) { - var forge3 = require_forge(); - require_mgf1(); - module.exports = forge3.mgf = forge3.mgf || {}; - forge3.mgf.mgf1 = forge3.mgf1; - } -}); - -// node_modules/node-forge/lib/pss.js -var require_pss = __commonJS({ - "node_modules/node-forge/lib/pss.js"(exports, module) { - var forge3 = require_forge(); - require_random(); - require_util(); - var pss = module.exports = forge3.pss = forge3.pss || {}; - pss.create = function(options) { - if (arguments.length === 3) { - options = { - md: arguments[0], - mgf: arguments[1], - saltLength: arguments[2] - }; - } - var hash = options.md; - var mgf = options.mgf; - var hLen = hash.digestLength; - var salt_ = options.salt || null; - if (typeof salt_ === "string") { - salt_ = forge3.util.createBuffer(salt_); - } - var sLen; - if ("saltLength" in options) { - sLen = options.saltLength; - } else if (salt_ !== null) { - sLen = salt_.length(); - } else { - throw new Error("Salt length not specified or specific salt not given."); - } - if (salt_ !== null && salt_.length() !== sLen) { - throw new Error("Given salt length does not match length of given salt."); - } - var prng = options.prng || forge3.random; - var pssobj = {}; - pssobj.encode = function(md, modBits) { - var i; - var emBits = modBits - 1; - var emLen = Math.ceil(emBits / 8); - var mHash = md.digest().getBytes(); - if (emLen < hLen + sLen + 2) { - throw new Error("Message is too long to encrypt."); - } - var salt; - if (salt_ === null) { - salt = prng.getBytesSync(sLen); - } else { - salt = salt_.bytes(); - } - var m_ = new forge3.util.ByteBuffer(); - m_.fillWithByte(0, 8); - m_.putBytes(mHash); - m_.putBytes(salt); - hash.start(); - hash.update(m_.getBytes()); - var h = hash.digest().getBytes(); - var ps = new forge3.util.ByteBuffer(); - ps.fillWithByte(0, emLen - sLen - hLen - 2); - ps.putByte(1); - ps.putBytes(salt); - var db2 = ps.getBytes(); - var maskLen = emLen - hLen - 1; - var dbMask = mgf.generate(h, maskLen); - var maskedDB = ""; - for (i = 0; i < maskLen; i++) { - maskedDB += String.fromCharCode(db2.charCodeAt(i) ^ dbMask.charCodeAt(i)); - } - var mask = 65280 >> 8 * emLen - emBits & 255; - maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + maskedDB.substr(1); - return maskedDB + h + String.fromCharCode(188); - }; - pssobj.verify = function(mHash, em, modBits) { - var i; - var emBits = modBits - 1; - var emLen = Math.ceil(emBits / 8); - em = em.substr(-emLen); - if (emLen < hLen + sLen + 2) { - throw new Error("Inconsistent parameters to PSS signature verification."); - } - if (em.charCodeAt(emLen - 1) !== 188) { - throw new Error("Encoded message does not end in 0xBC."); - } - var maskLen = emLen - hLen - 1; - var maskedDB = em.substr(0, maskLen); - var h = em.substr(maskLen, hLen); - var mask = 65280 >> 8 * emLen - emBits & 255; - if ((maskedDB.charCodeAt(0) & mask) !== 0) { - throw new Error("Bits beyond keysize not zero as expected."); - } - var dbMask = mgf.generate(h, maskLen); - var db2 = ""; - for (i = 0; i < maskLen; i++) { - db2 += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i)); - } - db2 = String.fromCharCode(db2.charCodeAt(0) & ~mask) + db2.substr(1); - var checkLen = emLen - hLen - sLen - 2; - for (i = 0; i < checkLen; i++) { - if (db2.charCodeAt(i) !== 0) { - throw new Error("Leftmost octets not zero as expected"); - } - } - if (db2.charCodeAt(checkLen) !== 1) { - throw new Error("Inconsistent PSS signature, 0x01 marker not found"); - } - var salt = db2.substr(-sLen); - var m_ = new forge3.util.ByteBuffer(); - m_.fillWithByte(0, 8); - m_.putBytes(mHash); - m_.putBytes(salt); - hash.start(); - hash.update(m_.getBytes()); - var h_ = hash.digest().getBytes(); - return h === h_; - }; - return pssobj; - }; - } -}); - -// node_modules/node-forge/lib/x509.js -var require_x509 = __commonJS({ - "node_modules/node-forge/lib/x509.js"(exports, module) { - var forge3 = require_forge(); - require_aes(); - require_asn1(); - require_des(); - require_md(); - require_mgf(); - require_oids(); - require_pem(); - require_pss(); - require_rsa(); - require_util(); - var asn1 = forge3.asn1; - var pki = module.exports = forge3.pki = forge3.pki || {}; - var oids = pki.oids; - var _shortNames = {}; - _shortNames["CN"] = oids["commonName"]; - _shortNames["commonName"] = "CN"; - _shortNames["C"] = oids["countryName"]; - _shortNames["countryName"] = "C"; - _shortNames["L"] = oids["localityName"]; - _shortNames["localityName"] = "L"; - _shortNames["ST"] = oids["stateOrProvinceName"]; - _shortNames["stateOrProvinceName"] = "ST"; - _shortNames["O"] = oids["organizationName"]; - _shortNames["organizationName"] = "O"; - _shortNames["OU"] = oids["organizationalUnitName"]; - _shortNames["organizationalUnitName"] = "OU"; - _shortNames["E"] = oids["emailAddress"]; - _shortNames["emailAddress"] = "E"; - var publicKeyValidator = forge3.pki.rsa.publicKeyValidator; - var x509CertificateValidator = { - name: "Certificate", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "Certificate.TBSCertificate", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "tbsCertificate", - value: [ - { - name: "Certificate.TBSCertificate.version", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - value: [{ - name: "Certificate.TBSCertificate.version.integer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "certVersion" - }] - }, - { - name: "Certificate.TBSCertificate.serialNumber", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "certSerialNumber" - }, - { - name: "Certificate.TBSCertificate.signature", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "Certificate.TBSCertificate.signature.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "certinfoSignatureOid" - }, { - name: "Certificate.TBSCertificate.signature.parameters", - tagClass: asn1.Class.UNIVERSAL, - optional: true, - captureAsn1: "certinfoSignatureParams" - }] - }, - { - name: "Certificate.TBSCertificate.issuer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "certIssuer" - }, - { - name: "Certificate.TBSCertificate.validity", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - // Note: UTC and generalized times may both appear so the capture - // names are based on their detected order, the names used below - // are only for the common case, which validity time really means - // "notBefore" and which means "notAfter" will be determined by order - value: [{ - // notBefore (Time) (UTC time case) - name: "Certificate.TBSCertificate.validity.notBefore (utc)", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.UTCTIME, - constructed: false, - optional: true, - capture: "certValidity1UTCTime" - }, { - // notBefore (Time) (generalized time case) - name: "Certificate.TBSCertificate.validity.notBefore (generalized)", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.GENERALIZEDTIME, - constructed: false, - optional: true, - capture: "certValidity2GeneralizedTime" - }, { - // notAfter (Time) (only UTC time is supported) - name: "Certificate.TBSCertificate.validity.notAfter (utc)", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.UTCTIME, - constructed: false, - optional: true, - capture: "certValidity3UTCTime" - }, { - // notAfter (Time) (only UTC time is supported) - name: "Certificate.TBSCertificate.validity.notAfter (generalized)", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.GENERALIZEDTIME, - constructed: false, - optional: true, - capture: "certValidity4GeneralizedTime" - }] - }, - { - // Name (subject) (RDNSequence) - name: "Certificate.TBSCertificate.subject", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "certSubject" - }, - // SubjectPublicKeyInfo - publicKeyValidator, - { - // issuerUniqueID (optional) - name: "Certificate.TBSCertificate.issuerUniqueID", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - optional: true, - value: [{ - name: "Certificate.TBSCertificate.issuerUniqueID.id", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - // TODO: support arbitrary bit length ids - captureBitStringValue: "certIssuerUniqueId" - }] - }, - { - // subjectUniqueID (optional) - name: "Certificate.TBSCertificate.subjectUniqueID", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 2, - constructed: true, - optional: true, - value: [{ - name: "Certificate.TBSCertificate.subjectUniqueID.id", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - // TODO: support arbitrary bit length ids - captureBitStringValue: "certSubjectUniqueId" - }] - }, - { - // Extensions (optional) - name: "Certificate.TBSCertificate.extensions", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 3, - constructed: true, - captureAsn1: "certExtensions", - optional: true - } - ] - }, { - // AlgorithmIdentifier (signature algorithm) - name: "Certificate.signatureAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // algorithm - name: "Certificate.signatureAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "certSignatureOid" - }, { - name: "Certificate.TBSCertificate.signature.parameters", - tagClass: asn1.Class.UNIVERSAL, - optional: true, - captureAsn1: "certSignatureParams" - }] - }, { - // SignatureValue - name: "Certificate.signatureValue", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - captureBitStringValue: "certSignature" - }] - }; - var rsassaPssParameterValidator = { - name: "rsapss", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "rsapss.hashAlgorithm", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - value: [{ - name: "rsapss.hashAlgorithm.AlgorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: "rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "hashOid" - /* parameter block omitted, for SHA1 NULL anyhow. */ - }] - }] - }, { - name: "rsapss.maskGenAlgorithm", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - value: [{ - name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "maskGenOid" - }, { - name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.params", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "maskGenHashOid" - /* parameter block omitted, for SHA1 NULL anyhow. */ - }] - }] - }] - }, { - name: "rsapss.saltLength", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 2, - optional: true, - value: [{ - name: "rsapss.saltLength.saltLength", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.INTEGER, - constructed: false, - capture: "saltLength" - }] - }, { - name: "rsapss.trailerField", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 3, - optional: true, - value: [{ - name: "rsapss.trailer.trailer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.INTEGER, - constructed: false, - capture: "trailer" - }] - }] - }; - var certificationRequestInfoValidator = { - name: "CertificationRequestInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "certificationRequestInfo", - value: [ - { - name: "CertificationRequestInfo.integer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "certificationRequestInfoVersion" - }, - { - // Name (subject) (RDNSequence) - name: "CertificationRequestInfo.subject", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "certificationRequestInfoSubject" - }, - // SubjectPublicKeyInfo - publicKeyValidator, - { - name: "CertificationRequestInfo.attributes", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - capture: "certificationRequestInfoAttributes", - value: [{ - name: "CertificationRequestInfo.attributes", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "CertificationRequestInfo.attributes.type", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false - }, { - name: "CertificationRequestInfo.attributes.value", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true - }] - }] - } - ] - }; - var certificationRequestValidator = { - name: "CertificationRequest", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "csr", - value: [ - certificationRequestInfoValidator, - { - // AlgorithmIdentifier (signature algorithm) - name: "CertificationRequest.signatureAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // algorithm - name: "CertificationRequest.signatureAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "csrSignatureOid" - }, { - name: "CertificationRequest.signatureAlgorithm.parameters", - tagClass: asn1.Class.UNIVERSAL, - optional: true, - captureAsn1: "csrSignatureParams" - }] - }, - { - // signature - name: "CertificationRequest.signature", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - captureBitStringValue: "csrSignature" - } - ] - }; - pki.RDNAttributesAsArray = function(rdn, md) { - var rval = []; - var set, attr, obj; - for (var si = 0; si < rdn.value.length; ++si) { - set = rdn.value[si]; - for (var i = 0; i < set.value.length; ++i) { - obj = {}; - attr = set.value[i]; - obj.type = asn1.derToOid(attr.value[0].value); - obj.value = attr.value[1].value; - obj.valueTagClass = attr.value[1].type; - if (obj.type in oids) { - obj.name = oids[obj.type]; - if (obj.name in _shortNames) { - obj.shortName = _shortNames[obj.name]; - } - } - if (md) { - md.update(obj.type); - md.update(obj.value); - } - rval.push(obj); - } - } - return rval; - }; - pki.CRIAttributesAsArray = function(attributes) { - var rval = []; - for (var si = 0; si < attributes.length; ++si) { - var seq = attributes[si]; - var type = asn1.derToOid(seq.value[0].value); - var values = seq.value[1].value; - for (var vi = 0; vi < values.length; ++vi) { - var obj = {}; - obj.type = type; - obj.value = values[vi].value; - obj.valueTagClass = values[vi].type; - if (obj.type in oids) { - obj.name = oids[obj.type]; - if (obj.name in _shortNames) { - obj.shortName = _shortNames[obj.name]; - } - } - if (obj.type === oids.extensionRequest) { - obj.extensions = []; - for (var ei = 0; ei < obj.value.length; ++ei) { - obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei])); - } - } - rval.push(obj); - } - } - return rval; - }; - function _getAttribute(obj, options) { - if (typeof options === "string") { - options = { shortName: options }; - } - var rval = null; - var attr; - for (var i = 0; rval === null && i < obj.attributes.length; ++i) { - attr = obj.attributes[i]; - if (options.type && options.type === attr.type) { - rval = attr; - } else if (options.name && options.name === attr.name) { - rval = attr; - } else if (options.shortName && options.shortName === attr.shortName) { - rval = attr; - } - } - return rval; - } - var _readSignatureParameters = function(oid, obj, fillDefaults) { - var params = {}; - if (oid !== oids["RSASSA-PSS"]) { - return params; - } - if (fillDefaults) { - params = { - hash: { - algorithmOid: oids["sha1"] - }, - mgf: { - algorithmOid: oids["mgf1"], - hash: { - algorithmOid: oids["sha1"] - } - }, - saltLength: 20 - }; - } - var capture = {}; - var errors = []; - if (!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) { - var error = new Error("Cannot read RSASSA-PSS parameter block."); - error.errors = errors; - throw error; - } - if (capture.hashOid !== void 0) { - params.hash = params.hash || {}; - params.hash.algorithmOid = asn1.derToOid(capture.hashOid); - } - if (capture.maskGenOid !== void 0) { - params.mgf = params.mgf || {}; - params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid); - params.mgf.hash = params.mgf.hash || {}; - params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid); - } - if (capture.saltLength !== void 0) { - params.saltLength = capture.saltLength.charCodeAt(0); - } - return params; - }; - var _createSignatureDigest = function(options) { - switch (oids[options.signatureOid]) { - case "sha1WithRSAEncryption": - case "sha1WithRSASignature": - return forge3.md.sha1.create(); - case "md5WithRSAEncryption": - return forge3.md.md5.create(); - case "sha256WithRSAEncryption": - return forge3.md.sha256.create(); - case "sha384WithRSAEncryption": - return forge3.md.sha384.create(); - case "sha512WithRSAEncryption": - return forge3.md.sha512.create(); - case "RSASSA-PSS": - return forge3.md.sha256.create(); - default: - var error = new Error( - "Could not compute " + options.type + " digest. Unknown signature OID." - ); - error.signatureOid = options.signatureOid; - throw error; - } - }; - var _verifySignature = function(options) { - var cert = options.certificate; - var scheme; - switch (cert.signatureOid) { - case oids.sha1WithRSAEncryption: - case oids.sha1WithRSASignature: - break; - case oids["RSASSA-PSS"]: - var hash, mgf; - hash = oids[cert.signatureParameters.mgf.hash.algorithmOid]; - if (hash === void 0 || forge3.md[hash] === void 0) { - var error = new Error("Unsupported MGF hash function."); - error.oid = cert.signatureParameters.mgf.hash.algorithmOid; - error.name = hash; - throw error; - } - mgf = oids[cert.signatureParameters.mgf.algorithmOid]; - if (mgf === void 0 || forge3.mgf[mgf] === void 0) { - var error = new Error("Unsupported MGF function."); - error.oid = cert.signatureParameters.mgf.algorithmOid; - error.name = mgf; - throw error; - } - mgf = forge3.mgf[mgf].create(forge3.md[hash].create()); - hash = oids[cert.signatureParameters.hash.algorithmOid]; - if (hash === void 0 || forge3.md[hash] === void 0) { - var error = new Error("Unsupported RSASSA-PSS hash function."); - error.oid = cert.signatureParameters.hash.algorithmOid; - error.name = hash; - throw error; - } - scheme = forge3.pss.create( - forge3.md[hash].create(), - mgf, - cert.signatureParameters.saltLength - ); - break; - } - return cert.publicKey.verify( - options.md.digest().getBytes(), - options.signature, - scheme - ); - }; - pki.certificateFromPem = function(pem, computeHash, strict) { - var msg = forge3.pem.decode(pem)[0]; - if (msg.type !== "CERTIFICATE" && msg.type !== "X509 CERTIFICATE" && msg.type !== "TRUSTED CERTIFICATE") { - var error = new Error( - 'Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".' - ); - error.headerType = msg.type; - throw error; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error( - "Could not convert certificate from PEM; PEM is encrypted." - ); - } - var obj = asn1.fromDer(msg.body, strict); - return pki.certificateFromAsn1(obj, computeHash); - }; - pki.certificateToPem = function(cert, maxline) { - var msg = { - type: "CERTIFICATE", - body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes() - }; - return forge3.pem.encode(msg, { maxline }); - }; - pki.publicKeyFromPem = function(pem) { - var msg = forge3.pem.decode(pem)[0]; - if (msg.type !== "PUBLIC KEY" && msg.type !== "RSA PUBLIC KEY") { - var error = new Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".'); - error.headerType = msg.type; - throw error; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert public key from PEM; PEM is encrypted."); - } - var obj = asn1.fromDer(msg.body); - return pki.publicKeyFromAsn1(obj); - }; - pki.publicKeyToPem = function(key, maxline) { - var msg = { - type: "PUBLIC KEY", - body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes() - }; - return forge3.pem.encode(msg, { maxline }); - }; - pki.publicKeyToRSAPublicKeyPem = function(key, maxline) { - var msg = { - type: "RSA PUBLIC KEY", - body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes() - }; - return forge3.pem.encode(msg, { maxline }); - }; - pki.getPublicKeyFingerprint = function(key, options) { - options = options || {}; - var md = options.md || forge3.md.sha1.create(); - var type = options.type || "RSAPublicKey"; - var bytes; - switch (type) { - case "RSAPublicKey": - bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes(); - break; - case "SubjectPublicKeyInfo": - bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes(); - break; - default: - throw new Error('Unknown fingerprint type "' + options.type + '".'); - } - md.start(); - md.update(bytes); - var digest = md.digest(); - if (options.encoding === "hex") { - var hex = digest.toHex(); - if (options.delimiter) { - return hex.match(/.{2}/g).join(options.delimiter); - } - return hex; - } else if (options.encoding === "binary") { - return digest.getBytes(); - } else if (options.encoding) { - throw new Error('Unknown encoding "' + options.encoding + '".'); - } - return digest; - }; - pki.certificationRequestFromPem = function(pem, computeHash, strict) { - var msg = forge3.pem.decode(pem)[0]; - if (msg.type !== "CERTIFICATE REQUEST") { - var error = new Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".'); - error.headerType = msg.type; - throw error; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert certification request from PEM; PEM is encrypted."); - } - var obj = asn1.fromDer(msg.body, strict); - return pki.certificationRequestFromAsn1(obj, computeHash); - }; - pki.certificationRequestToPem = function(csr, maxline) { - var msg = { - type: "CERTIFICATE REQUEST", - body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes() - }; - return forge3.pem.encode(msg, { maxline }); - }; - pki.createCertificate = function() { - var cert = {}; - cert.version = 2; - cert.serialNumber = "00"; - cert.signatureOid = null; - cert.signature = null; - cert.siginfo = {}; - cert.siginfo.algorithmOid = null; - cert.validity = {}; - cert.validity.notBefore = /* @__PURE__ */ new Date(); - cert.validity.notAfter = /* @__PURE__ */ new Date(); - cert.issuer = {}; - cert.issuer.getField = function(sn) { - return _getAttribute(cert.issuer, sn); - }; - cert.issuer.addField = function(attr) { - _fillMissingFields([attr]); - cert.issuer.attributes.push(attr); - }; - cert.issuer.attributes = []; - cert.issuer.hash = null; - cert.subject = {}; - cert.subject.getField = function(sn) { - return _getAttribute(cert.subject, sn); - }; - cert.subject.addField = function(attr) { - _fillMissingFields([attr]); - cert.subject.attributes.push(attr); - }; - cert.subject.attributes = []; - cert.subject.hash = null; - cert.extensions = []; - cert.publicKey = null; - cert.md = null; - cert.setSubject = function(attrs, uniqueId) { - _fillMissingFields(attrs); - cert.subject.attributes = attrs; - delete cert.subject.uniqueId; - if (uniqueId) { - cert.subject.uniqueId = uniqueId; - } - cert.subject.hash = null; - }; - cert.setIssuer = function(attrs, uniqueId) { - _fillMissingFields(attrs); - cert.issuer.attributes = attrs; - delete cert.issuer.uniqueId; - if (uniqueId) { - cert.issuer.uniqueId = uniqueId; - } - cert.issuer.hash = null; - }; - cert.setExtensions = function(exts) { - for (var i = 0; i < exts.length; ++i) { - _fillMissingExtensionFields(exts[i], { cert }); - } - cert.extensions = exts; - }; - cert.getExtension = function(options) { - if (typeof options === "string") { - options = { name: options }; - } - var rval = null; - var ext; - for (var i = 0; rval === null && i < cert.extensions.length; ++i) { - ext = cert.extensions[i]; - if (options.id && ext.id === options.id) { - rval = ext; - } else if (options.name && ext.name === options.name) { - rval = ext; - } - } - return rval; - }; - cert.sign = function(key, md) { - cert.md = md || forge3.md.sha1.create(); - var algorithmOid = oids[cert.md.algorithm + "WithRSAEncryption"]; - if (!algorithmOid) { - var error = new Error("Could not compute certificate digest. Unknown message digest algorithm OID."); - error.algorithm = cert.md.algorithm; - throw error; - } - cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid; - cert.tbsCertificate = pki.getTBSCertificate(cert); - var bytes = asn1.toDer(cert.tbsCertificate); - cert.md.update(bytes.getBytes()); - cert.signature = key.sign(cert.md); - }; - cert.verify = function(child) { - var rval = false; - if (!cert.issued(child)) { - var issuer = child.issuer; - var subject = cert.subject; - var error = new Error( - "The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject." - ); - error.expectedIssuer = subject.attributes; - error.actualIssuer = issuer.attributes; - throw error; - } - var md = child.md; - if (md === null) { - md = _createSignatureDigest({ - signatureOid: child.signatureOid, - type: "certificate" - }); - var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child); - var bytes = asn1.toDer(tbsCertificate); - md.update(bytes.getBytes()); - } - if (md !== null) { - rval = _verifySignature({ - certificate: cert, - md, - signature: child.signature - }); - } - return rval; - }; - cert.isIssuer = function(parent) { - var rval = false; - var i = cert.issuer; - var s = parent.subject; - if (i.hash && s.hash) { - rval = i.hash === s.hash; - } else if (i.attributes.length === s.attributes.length) { - rval = true; - var iattr, sattr; - for (var n = 0; rval && n < i.attributes.length; ++n) { - iattr = i.attributes[n]; - sattr = s.attributes[n]; - if (iattr.type !== sattr.type || iattr.value !== sattr.value) { - rval = false; - } - } - } - return rval; - }; - cert.issued = function(child) { - return child.isIssuer(cert); - }; - cert.generateSubjectKeyIdentifier = function() { - return pki.getPublicKeyFingerprint(cert.publicKey, { type: "RSAPublicKey" }); - }; - cert.verifySubjectKeyIdentifier = function() { - var oid = oids["subjectKeyIdentifier"]; - for (var i = 0; i < cert.extensions.length; ++i) { - var ext = cert.extensions[i]; - if (ext.id === oid) { - var ski = cert.generateSubjectKeyIdentifier().getBytes(); - return forge3.util.hexToBytes(ext.subjectKeyIdentifier) === ski; - } - } - return false; - }; - return cert; - }; - pki.certificateFromAsn1 = function(obj, computeHash) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, x509CertificateValidator, capture, errors)) { - var error = new Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate."); - error.errors = errors; - throw error; - } - var oid = asn1.derToOid(capture.publicKeyOid); - if (oid !== pki.oids.rsaEncryption) { - throw new Error("Cannot read public key. OID is not RSA."); - } - var cert = pki.createCertificate(); - cert.version = capture.certVersion ? capture.certVersion.charCodeAt(0) : 0; - var serial = forge3.util.createBuffer(capture.certSerialNumber); - cert.serialNumber = serial.toHex(); - cert.signatureOid = forge3.asn1.derToOid(capture.certSignatureOid); - cert.signatureParameters = _readSignatureParameters( - cert.signatureOid, - capture.certSignatureParams, - true - ); - cert.siginfo.algorithmOid = forge3.asn1.derToOid(capture.certinfoSignatureOid); - cert.siginfo.parameters = _readSignatureParameters( - cert.siginfo.algorithmOid, - capture.certinfoSignatureParams, - false - ); - cert.signature = capture.certSignature; - var validity = []; - if (capture.certValidity1UTCTime !== void 0) { - validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime)); - } - if (capture.certValidity2GeneralizedTime !== void 0) { - validity.push(asn1.generalizedTimeToDate( - capture.certValidity2GeneralizedTime - )); - } - if (capture.certValidity3UTCTime !== void 0) { - validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime)); - } - if (capture.certValidity4GeneralizedTime !== void 0) { - validity.push(asn1.generalizedTimeToDate( - capture.certValidity4GeneralizedTime - )); - } - if (validity.length > 2) { - throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate."); - } - if (validity.length < 2) { - throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime."); - } - cert.validity.notBefore = validity[0]; - cert.validity.notAfter = validity[1]; - cert.tbsCertificate = capture.tbsCertificate; - if (computeHash) { - cert.md = _createSignatureDigest({ - signatureOid: cert.signatureOid, - type: "certificate" - }); - var bytes = asn1.toDer(cert.tbsCertificate); - cert.md.update(bytes.getBytes()); - } - var imd = forge3.md.sha1.create(); - var ibytes = asn1.toDer(capture.certIssuer); - imd.update(ibytes.getBytes()); - cert.issuer.getField = function(sn) { - return _getAttribute(cert.issuer, sn); - }; - cert.issuer.addField = function(attr) { - _fillMissingFields([attr]); - cert.issuer.attributes.push(attr); - }; - cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer); - if (capture.certIssuerUniqueId) { - cert.issuer.uniqueId = capture.certIssuerUniqueId; - } - cert.issuer.hash = imd.digest().toHex(); - var smd = forge3.md.sha1.create(); - var sbytes = asn1.toDer(capture.certSubject); - smd.update(sbytes.getBytes()); - cert.subject.getField = function(sn) { - return _getAttribute(cert.subject, sn); - }; - cert.subject.addField = function(attr) { - _fillMissingFields([attr]); - cert.subject.attributes.push(attr); - }; - cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject); - if (capture.certSubjectUniqueId) { - cert.subject.uniqueId = capture.certSubjectUniqueId; - } - cert.subject.hash = smd.digest().toHex(); - if (capture.certExtensions) { - cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions); - } else { - cert.extensions = []; - } - cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo); - return cert; - }; - pki.certificateExtensionsFromAsn1 = function(exts) { - var rval = []; - for (var i = 0; i < exts.value.length; ++i) { - var extseq = exts.value[i]; - for (var ei = 0; ei < extseq.value.length; ++ei) { - rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei])); - } - } - return rval; - }; - pki.certificateExtensionFromAsn1 = function(ext) { - var e = {}; - e.id = asn1.derToOid(ext.value[0].value); - e.critical = false; - if (ext.value[1].type === asn1.Type.BOOLEAN) { - e.critical = ext.value[1].value.charCodeAt(0) !== 0; - e.value = ext.value[2].value; - } else { - e.value = ext.value[1].value; - } - if (e.id in oids) { - e.name = oids[e.id]; - if (e.name === "keyUsage") { - var ev = asn1.fromDer(e.value); - var b2 = 0; - var b3 = 0; - if (ev.value.length > 1) { - b2 = ev.value.charCodeAt(1); - b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0; - } - e.digitalSignature = (b2 & 128) === 128; - e.nonRepudiation = (b2 & 64) === 64; - e.keyEncipherment = (b2 & 32) === 32; - e.dataEncipherment = (b2 & 16) === 16; - e.keyAgreement = (b2 & 8) === 8; - e.keyCertSign = (b2 & 4) === 4; - e.cRLSign = (b2 & 2) === 2; - e.encipherOnly = (b2 & 1) === 1; - e.decipherOnly = (b3 & 128) === 128; - } else if (e.name === "basicConstraints") { - var ev = asn1.fromDer(e.value); - if (ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) { - e.cA = ev.value[0].value.charCodeAt(0) !== 0; - } else { - e.cA = false; - } - var value = null; - if (ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) { - value = ev.value[0].value; - } else if (ev.value.length > 1) { - value = ev.value[1].value; - } - if (value !== null) { - e.pathLenConstraint = asn1.derToInteger(value); - } - } else if (e.name === "extKeyUsage") { - var ev = asn1.fromDer(e.value); - for (var vi = 0; vi < ev.value.length; ++vi) { - var oid = asn1.derToOid(ev.value[vi].value); - if (oid in oids) { - e[oids[oid]] = true; - } else { - e[oid] = true; - } - } - } else if (e.name === "nsCertType") { - var ev = asn1.fromDer(e.value); - var b2 = 0; - if (ev.value.length > 1) { - b2 = ev.value.charCodeAt(1); - } - e.client = (b2 & 128) === 128; - e.server = (b2 & 64) === 64; - e.email = (b2 & 32) === 32; - e.objsign = (b2 & 16) === 16; - e.reserved = (b2 & 8) === 8; - e.sslCA = (b2 & 4) === 4; - e.emailCA = (b2 & 2) === 2; - e.objCA = (b2 & 1) === 1; - } else if (e.name === "subjectAltName" || e.name === "issuerAltName") { - e.altNames = []; - var gn; - var ev = asn1.fromDer(e.value); - for (var n = 0; n < ev.value.length; ++n) { - gn = ev.value[n]; - var altName = { - type: gn.type, - value: gn.value - }; - e.altNames.push(altName); - switch (gn.type) { - case 1: - case 2: - case 6: - break; - case 7: - altName.ip = forge3.util.bytesToIP(gn.value); - break; - case 8: - altName.oid = asn1.derToOid(gn.value); - break; - default: - } - } - } else if (e.name === "subjectKeyIdentifier") { - var ev = asn1.fromDer(e.value); - e.subjectKeyIdentifier = forge3.util.bytesToHex(ev.value); - } - } - return e; - }; - pki.certificationRequestFromAsn1 = function(obj, computeHash) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, certificationRequestValidator, capture, errors)) { - var error = new Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest."); - error.errors = errors; - throw error; - } - var oid = asn1.derToOid(capture.publicKeyOid); - if (oid !== pki.oids.rsaEncryption) { - throw new Error("Cannot read public key. OID is not RSA."); - } - var csr = pki.createCertificationRequest(); - csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0; - csr.signatureOid = forge3.asn1.derToOid(capture.csrSignatureOid); - csr.signatureParameters = _readSignatureParameters( - csr.signatureOid, - capture.csrSignatureParams, - true - ); - csr.siginfo.algorithmOid = forge3.asn1.derToOid(capture.csrSignatureOid); - csr.siginfo.parameters = _readSignatureParameters( - csr.siginfo.algorithmOid, - capture.csrSignatureParams, - false - ); - csr.signature = capture.csrSignature; - csr.certificationRequestInfo = capture.certificationRequestInfo; - if (computeHash) { - csr.md = _createSignatureDigest({ - signatureOid: csr.signatureOid, - type: "certification request" - }); - var bytes = asn1.toDer(csr.certificationRequestInfo); - csr.md.update(bytes.getBytes()); - } - var smd = forge3.md.sha1.create(); - csr.subject.getField = function(sn) { - return _getAttribute(csr.subject, sn); - }; - csr.subject.addField = function(attr) { - _fillMissingFields([attr]); - csr.subject.attributes.push(attr); - }; - csr.subject.attributes = pki.RDNAttributesAsArray( - capture.certificationRequestInfoSubject, - smd - ); - csr.subject.hash = smd.digest().toHex(); - csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo); - csr.getAttribute = function(sn) { - return _getAttribute(csr, sn); - }; - csr.addAttribute = function(attr) { - _fillMissingFields([attr]); - csr.attributes.push(attr); - }; - csr.attributes = pki.CRIAttributesAsArray( - capture.certificationRequestInfoAttributes || [] - ); - return csr; - }; - pki.createCertificationRequest = function() { - var csr = {}; - csr.version = 0; - csr.signatureOid = null; - csr.signature = null; - csr.siginfo = {}; - csr.siginfo.algorithmOid = null; - csr.subject = {}; - csr.subject.getField = function(sn) { - return _getAttribute(csr.subject, sn); - }; - csr.subject.addField = function(attr) { - _fillMissingFields([attr]); - csr.subject.attributes.push(attr); - }; - csr.subject.attributes = []; - csr.subject.hash = null; - csr.publicKey = null; - csr.attributes = []; - csr.getAttribute = function(sn) { - return _getAttribute(csr, sn); - }; - csr.addAttribute = function(attr) { - _fillMissingFields([attr]); - csr.attributes.push(attr); - }; - csr.md = null; - csr.setSubject = function(attrs) { - _fillMissingFields(attrs); - csr.subject.attributes = attrs; - csr.subject.hash = null; - }; - csr.setAttributes = function(attrs) { - _fillMissingFields(attrs); - csr.attributes = attrs; - }; - csr.sign = function(key, md) { - csr.md = md || forge3.md.sha1.create(); - var algorithmOid = oids[csr.md.algorithm + "WithRSAEncryption"]; - if (!algorithmOid) { - var error = new Error("Could not compute certification request digest. Unknown message digest algorithm OID."); - error.algorithm = csr.md.algorithm; - throw error; - } - csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid; - csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr); - var bytes = asn1.toDer(csr.certificationRequestInfo); - csr.md.update(bytes.getBytes()); - csr.signature = key.sign(csr.md); - }; - csr.verify = function() { - var rval = false; - var md = csr.md; - if (md === null) { - md = _createSignatureDigest({ - signatureOid: csr.signatureOid, - type: "certification request" - }); - var cri = csr.certificationRequestInfo || pki.getCertificationRequestInfo(csr); - var bytes = asn1.toDer(cri); - md.update(bytes.getBytes()); - } - if (md !== null) { - rval = _verifySignature({ - certificate: csr, - md, - signature: csr.signature - }); - } - return rval; - }; - return csr; - }; - function _dnToAsn1(obj) { - var rval = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - var attr, set; - var attrs = obj.attributes; - for (var i = 0; i < attrs.length; ++i) { - attr = attrs[i]; - var value = attr.value; - var valueTagClass = asn1.Type.PRINTABLESTRING; - if ("valueTagClass" in attr) { - valueTagClass = attr.valueTagClass; - if (valueTagClass === asn1.Type.UTF8) { - value = forge3.util.encodeUtf8(value); - } - } - set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AttributeType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(attr.type).getBytes() - ), - // AttributeValue - asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value) - ]) - ]); - rval.value.push(set); - } - return rval; - } - function _fillMissingFields(attrs) { - var attr; - for (var i = 0; i < attrs.length; ++i) { - attr = attrs[i]; - if (typeof attr.name === "undefined") { - if (attr.type && attr.type in pki.oids) { - attr.name = pki.oids[attr.type]; - } else if (attr.shortName && attr.shortName in _shortNames) { - attr.name = pki.oids[_shortNames[attr.shortName]]; - } - } - if (typeof attr.type === "undefined") { - if (attr.name && attr.name in pki.oids) { - attr.type = pki.oids[attr.name]; - } else { - var error = new Error("Attribute type not specified."); - error.attribute = attr; - throw error; - } - } - if (typeof attr.shortName === "undefined") { - if (attr.name && attr.name in _shortNames) { - attr.shortName = _shortNames[attr.name]; - } - } - if (attr.type === oids.extensionRequest) { - attr.valueConstructed = true; - attr.valueTagClass = asn1.Type.SEQUENCE; - if (!attr.value && attr.extensions) { - attr.value = []; - for (var ei = 0; ei < attr.extensions.length; ++ei) { - attr.value.push(pki.certificateExtensionToAsn1( - _fillMissingExtensionFields(attr.extensions[ei]) - )); - } - } - } - if (typeof attr.value === "undefined") { - var error = new Error("Attribute value not specified."); - error.attribute = attr; - throw error; - } - } - } - function _fillMissingExtensionFields(e, options) { - options = options || {}; - if (typeof e.name === "undefined") { - if (e.id && e.id in pki.oids) { - e.name = pki.oids[e.id]; - } - } - if (typeof e.id === "undefined") { - if (e.name && e.name in pki.oids) { - e.id = pki.oids[e.name]; - } else { - var error = new Error("Extension ID not specified."); - error.extension = e; - throw error; - } - } - if (typeof e.value !== "undefined") { - return e; - } - if (e.name === "keyUsage") { - var unused = 0; - var b2 = 0; - var b3 = 0; - if (e.digitalSignature) { - b2 |= 128; - unused = 7; - } - if (e.nonRepudiation) { - b2 |= 64; - unused = 6; - } - if (e.keyEncipherment) { - b2 |= 32; - unused = 5; - } - if (e.dataEncipherment) { - b2 |= 16; - unused = 4; - } - if (e.keyAgreement) { - b2 |= 8; - unused = 3; - } - if (e.keyCertSign) { - b2 |= 4; - unused = 2; - } - if (e.cRLSign) { - b2 |= 2; - unused = 1; - } - if (e.encipherOnly) { - b2 |= 1; - unused = 0; - } - if (e.decipherOnly) { - b3 |= 128; - unused = 7; - } - var value = String.fromCharCode(unused); - if (b3 !== 0) { - value += String.fromCharCode(b2) + String.fromCharCode(b3); - } else if (b2 !== 0) { - value += String.fromCharCode(b2); - } - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - value - ); - } else if (e.name === "basicConstraints") { - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - if (e.cA) { - e.value.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BOOLEAN, - false, - String.fromCharCode(255) - )); - } - if ("pathLenConstraint" in e) { - e.value.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(e.pathLenConstraint).getBytes() - )); - } - } else if (e.name === "extKeyUsage") { - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - var seq = e.value.value; - for (var key in e) { - if (e[key] !== true) { - continue; - } - if (key in oids) { - seq.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oids[key]).getBytes() - )); - } else if (key.indexOf(".") !== -1) { - seq.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(key).getBytes() - )); - } - } - } else if (e.name === "nsCertType") { - var unused = 0; - var b2 = 0; - if (e.client) { - b2 |= 128; - unused = 7; - } - if (e.server) { - b2 |= 64; - unused = 6; - } - if (e.email) { - b2 |= 32; - unused = 5; - } - if (e.objsign) { - b2 |= 16; - unused = 4; - } - if (e.reserved) { - b2 |= 8; - unused = 3; - } - if (e.sslCA) { - b2 |= 4; - unused = 2; - } - if (e.emailCA) { - b2 |= 2; - unused = 1; - } - if (e.objCA) { - b2 |= 1; - unused = 0; - } - var value = String.fromCharCode(unused); - if (b2 !== 0) { - value += String.fromCharCode(b2); - } - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - value - ); - } else if (e.name === "subjectAltName" || e.name === "issuerAltName") { - e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - var altName; - for (var n = 0; n < e.altNames.length; ++n) { - altName = e.altNames[n]; - var value = altName.value; - if (altName.type === 7 && altName.ip) { - value = forge3.util.bytesFromIP(altName.ip); - if (value === null) { - var error = new Error( - 'Extension "ip" value is not a valid IPv4 or IPv6 address.' - ); - error.extension = e; - throw error; - } - } else if (altName.type === 8) { - if (altName.oid) { - value = asn1.oidToDer(asn1.oidToDer(altName.oid)); - } else { - value = asn1.oidToDer(value); - } - } - e.value.value.push(asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - altName.type, - false, - value - )); - } - } else if (e.name === "nsComment" && options.cert) { - if (!/^[\x00-\x7F]*$/.test(e.comment) || e.comment.length < 1 || e.comment.length > 128) { - throw new Error('Invalid "nsComment" content.'); - } - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.IA5STRING, - false, - e.comment - ); - } else if (e.name === "subjectKeyIdentifier" && options.cert) { - var ski = options.cert.generateSubjectKeyIdentifier(); - e.subjectKeyIdentifier = ski.toHex(); - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - ski.getBytes() - ); - } else if (e.name === "authorityKeyIdentifier" && options.cert) { - e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - var seq = e.value.value; - if (e.keyIdentifier) { - var keyIdentifier = e.keyIdentifier === true ? options.cert.generateSubjectKeyIdentifier().getBytes() : e.keyIdentifier; - seq.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier) - ); - } - if (e.authorityCertIssuer) { - var authorityCertIssuer = [ - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [ - _dnToAsn1(e.authorityCertIssuer === true ? options.cert.issuer : e.authorityCertIssuer) - ]) - ]; - seq.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer) - ); - } - if (e.serialNumber) { - var serialNumber = forge3.util.hexToBytes(e.serialNumber === true ? options.cert.serialNumber : e.serialNumber); - seq.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber) - ); - } - } else if (e.name === "cRLDistributionPoints") { - e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - var seq = e.value.value; - var subSeq = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - var fullNameGeneralNames = asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - 0, - true, - [] - ); - var altName; - for (var n = 0; n < e.altNames.length; ++n) { - altName = e.altNames[n]; - var value = altName.value; - if (altName.type === 7 && altName.ip) { - value = forge3.util.bytesFromIP(altName.ip); - if (value === null) { - var error = new Error( - 'Extension "ip" value is not a valid IPv4 or IPv6 address.' - ); - error.extension = e; - throw error; - } - } else if (altName.type === 8) { - if (altName.oid) { - value = asn1.oidToDer(asn1.oidToDer(altName.oid)); - } else { - value = asn1.oidToDer(value); - } - } - fullNameGeneralNames.value.push(asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - altName.type, - false, - value - )); - } - subSeq.value.push(asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - 0, - true, - [fullNameGeneralNames] - )); - seq.push(subSeq); - } - if (typeof e.value === "undefined") { - var error = new Error("Extension value not specified."); - error.extension = e; - throw error; - } - return e; - } - function _signatureParametersToAsn1(oid, params) { - switch (oid) { - case oids["RSASSA-PSS"]: - var parts = []; - if (params.hash.algorithmOid !== void 0) { - parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(params.hash.algorithmOid).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ])); - } - if (params.mgf.algorithmOid !== void 0) { - parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(params.mgf.algorithmOid).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ]) - ])); - } - if (params.saltLength !== void 0) { - parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(params.saltLength).getBytes() - ) - ])); - } - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts); - default: - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ""); - } - } - function _CRIAttributesToAsn1(csr) { - var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []); - if (csr.attributes.length === 0) { - return rval; - } - var attrs = csr.attributes; - for (var i = 0; i < attrs.length; ++i) { - var attr = attrs[i]; - var value = attr.value; - var valueTagClass = asn1.Type.UTF8; - if ("valueTagClass" in attr) { - valueTagClass = attr.valueTagClass; - } - if (valueTagClass === asn1.Type.UTF8) { - value = forge3.util.encodeUtf8(value); - } - var valueConstructed = false; - if ("valueConstructed" in attr) { - valueConstructed = attr.valueConstructed; - } - var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AttributeType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(attr.type).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - // AttributeValue - asn1.create( - asn1.Class.UNIVERSAL, - valueTagClass, - valueConstructed, - value - ) - ]) - ]); - rval.value.push(seq); - } - return rval; - } - var jan_1_1950 = /* @__PURE__ */ new Date("1950-01-01T00:00:00Z"); - var jan_1_2050 = /* @__PURE__ */ new Date("2050-01-01T00:00:00Z"); - function _dateToAsn1(date) { - if (date >= jan_1_1950 && date < jan_1_2050) { - return asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.UTCTIME, - false, - asn1.dateToUtcTime(date) - ); - } else { - return asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.GENERALIZEDTIME, - false, - asn1.dateToGeneralizedTime(date) - ); - } - } - pki.getTBSCertificate = function(cert) { - var notBefore = _dateToAsn1(cert.validity.notBefore); - var notAfter = _dateToAsn1(cert.validity.notAfter); - var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // integer - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(cert.version).getBytes() - ) - ]), - // serialNumber - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - forge3.util.hexToBytes(cert.serialNumber) - ), - // signature - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(cert.siginfo.algorithmOid).getBytes() - ), - // parameters - _signatureParametersToAsn1( - cert.siginfo.algorithmOid, - cert.siginfo.parameters - ) - ]), - // issuer - _dnToAsn1(cert.issuer), - // validity - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - notBefore, - notAfter - ]), - // subject - _dnToAsn1(cert.subject), - // SubjectPublicKeyInfo - pki.publicKeyToAsn1(cert.publicKey) - ]); - if (cert.issuer.uniqueId) { - tbs.value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - // TODO: support arbitrary bit length ids - String.fromCharCode(0) + cert.issuer.uniqueId - ) - ]) - ); - } - if (cert.subject.uniqueId) { - tbs.value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - // TODO: support arbitrary bit length ids - String.fromCharCode(0) + cert.subject.uniqueId - ) - ]) - ); - } - if (cert.extensions.length > 0) { - tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions)); - } - return tbs; - }; - pki.getCertificationRequestInfo = function(csr) { - var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(csr.version).getBytes() - ), - // subject - _dnToAsn1(csr.subject), - // SubjectPublicKeyInfo - pki.publicKeyToAsn1(csr.publicKey), - // attributes - _CRIAttributesToAsn1(csr) - ]); - return cri; - }; - pki.distinguishedNameToAsn1 = function(dn) { - return _dnToAsn1(dn); - }; - pki.certificateToAsn1 = function(cert) { - var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert); - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // TBSCertificate - tbsCertificate, - // AlgorithmIdentifier (signature algorithm) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(cert.signatureOid).getBytes() - ), - // parameters - _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters) - ]), - // SignatureValue - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - String.fromCharCode(0) + cert.signature - ) - ]); - }; - pki.certificateExtensionsToAsn1 = function(exts) { - var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []); - var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - rval.value.push(seq); - for (var i = 0; i < exts.length; ++i) { - seq.value.push(pki.certificateExtensionToAsn1(exts[i])); - } - return rval; - }; - pki.certificateExtensionToAsn1 = function(ext) { - var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - extseq.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(ext.id).getBytes() - )); - if (ext.critical) { - extseq.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BOOLEAN, - false, - String.fromCharCode(255) - )); - } - var value = ext.value; - if (typeof ext.value !== "string") { - value = asn1.toDer(value).getBytes(); - } - extseq.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - value - )); - return extseq; - }; - pki.certificationRequestToAsn1 = function(csr) { - var cri = csr.certificationRequestInfo || pki.getCertificationRequestInfo(csr); - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // CertificationRequestInfo - cri, - // AlgorithmIdentifier (signature algorithm) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(csr.signatureOid).getBytes() - ), - // parameters - _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters) - ]), - // signature - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - String.fromCharCode(0) + csr.signature - ) - ]); - }; - pki.createCaStore = function(certs) { - var caStore = { - // stored certificates - certs: {} - }; - caStore.getIssuer = function(cert2) { - var rval = getBySubject(cert2.issuer); - return rval; - }; - caStore.addCertificate = function(cert2) { - if (typeof cert2 === "string") { - cert2 = forge3.pki.certificateFromPem(cert2); - } - ensureSubjectHasHash(cert2.subject); - if (!caStore.hasCertificate(cert2)) { - if (cert2.subject.hash in caStore.certs) { - var tmp = caStore.certs[cert2.subject.hash]; - if (!forge3.util.isArray(tmp)) { - tmp = [tmp]; - } - tmp.push(cert2); - caStore.certs[cert2.subject.hash] = tmp; - } else { - caStore.certs[cert2.subject.hash] = cert2; - } - } - }; - caStore.hasCertificate = function(cert2) { - if (typeof cert2 === "string") { - cert2 = forge3.pki.certificateFromPem(cert2); - } - var match = getBySubject(cert2.subject); - if (!match) { - return false; - } - if (!forge3.util.isArray(match)) { - match = [match]; - } - var der1 = asn1.toDer(pki.certificateToAsn1(cert2)).getBytes(); - for (var i2 = 0; i2 < match.length; ++i2) { - var der2 = asn1.toDer(pki.certificateToAsn1(match[i2])).getBytes(); - if (der1 === der2) { - return true; - } - } - return false; - }; - caStore.listAllCertificates = function() { - var certList = []; - for (var hash in caStore.certs) { - if (caStore.certs.hasOwnProperty(hash)) { - var value = caStore.certs[hash]; - if (!forge3.util.isArray(value)) { - certList.push(value); - } else { - for (var i2 = 0; i2 < value.length; ++i2) { - certList.push(value[i2]); - } - } - } - } - return certList; - }; - caStore.removeCertificate = function(cert2) { - var result; - if (typeof cert2 === "string") { - cert2 = forge3.pki.certificateFromPem(cert2); - } - ensureSubjectHasHash(cert2.subject); - if (!caStore.hasCertificate(cert2)) { - return null; - } - var match = getBySubject(cert2.subject); - if (!forge3.util.isArray(match)) { - result = caStore.certs[cert2.subject.hash]; - delete caStore.certs[cert2.subject.hash]; - return result; - } - var der1 = asn1.toDer(pki.certificateToAsn1(cert2)).getBytes(); - for (var i2 = 0; i2 < match.length; ++i2) { - var der2 = asn1.toDer(pki.certificateToAsn1(match[i2])).getBytes(); - if (der1 === der2) { - result = match[i2]; - match.splice(i2, 1); - } - } - if (match.length === 0) { - delete caStore.certs[cert2.subject.hash]; - } - return result; - }; - function getBySubject(subject) { - ensureSubjectHasHash(subject); - return caStore.certs[subject.hash] || null; - } - function ensureSubjectHasHash(subject) { - if (!subject.hash) { - var md = forge3.md.sha1.create(); - subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md); - subject.hash = md.digest().toHex(); - } - } - if (certs) { - for (var i = 0; i < certs.length; ++i) { - var cert = certs[i]; - caStore.addCertificate(cert); - } - } - return caStore; - }; - pki.certificateError = { - bad_certificate: "forge.pki.BadCertificate", - unsupported_certificate: "forge.pki.UnsupportedCertificate", - certificate_revoked: "forge.pki.CertificateRevoked", - certificate_expired: "forge.pki.CertificateExpired", - certificate_unknown: "forge.pki.CertificateUnknown", - unknown_ca: "forge.pki.UnknownCertificateAuthority" - }; - pki.verifyCertificateChain = function(caStore, chain, options) { - if (typeof options === "function") { - options = { verify: options }; - } - options = options || {}; - chain = chain.slice(0); - var certs = chain.slice(0); - var validityCheckDate = options.validityCheckDate; - if (typeof validityCheckDate === "undefined") { - validityCheckDate = /* @__PURE__ */ new Date(); - } - var first = true; - var error = null; - var depth = 0; - do { - var cert = chain.shift(); - var parent = null; - var selfSigned = false; - if (validityCheckDate) { - if (validityCheckDate < cert.validity.notBefore || validityCheckDate > cert.validity.notAfter) { - error = { - message: "Certificate is not valid yet or has expired.", - error: pki.certificateError.certificate_expired, - notBefore: cert.validity.notBefore, - notAfter: cert.validity.notAfter, - // TODO: we might want to reconsider renaming 'now' to - // 'validityCheckDate' should this API be changed in the future. - now: validityCheckDate - }; - } - } - if (error === null) { - parent = chain[0] || caStore.getIssuer(cert); - if (parent === null) { - if (cert.isIssuer(cert)) { - selfSigned = true; - parent = cert; - } - } - if (parent) { - var parents = parent; - if (!forge3.util.isArray(parents)) { - parents = [parents]; - } - var verified = false; - while (!verified && parents.length > 0) { - parent = parents.shift(); - try { - verified = parent.verify(cert); - } catch (ex) { - } - } - if (!verified) { - error = { - message: "Certificate signature is invalid.", - error: pki.certificateError.bad_certificate - }; - } - } - if (error === null && (!parent || selfSigned) && !caStore.hasCertificate(cert)) { - error = { - message: "Certificate is not trusted.", - error: pki.certificateError.unknown_ca - }; - } - } - if (error === null && parent && !cert.isIssuer(parent)) { - error = { - message: "Certificate issuer is invalid.", - error: pki.certificateError.bad_certificate - }; - } - if (error === null) { - var se = { - keyUsage: true, - basicConstraints: true - }; - for (var i = 0; error === null && i < cert.extensions.length; ++i) { - var ext = cert.extensions[i]; - if (ext.critical && !(ext.name in se)) { - error = { - message: "Certificate has an unsupported critical extension.", - error: pki.certificateError.unsupported_certificate - }; - } - } - } - if (error === null && (!first || chain.length === 0 && (!parent || selfSigned))) { - var bcExt = cert.getExtension("basicConstraints"); - var keyUsageExt = cert.getExtension("keyUsage"); - if (keyUsageExt !== null) { - if (!keyUsageExt.keyCertSign || bcExt === null) { - error = { - message: "Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.", - error: pki.certificateError.bad_certificate - }; - } - } - if (error === null && bcExt !== null && !bcExt.cA) { - error = { - message: "Certificate basicConstraints indicates the certificate is not a CA.", - error: pki.certificateError.bad_certificate - }; - } - if (error === null && keyUsageExt !== null && "pathLenConstraint" in bcExt) { - var pathLen = depth - 1; - if (pathLen > bcExt.pathLenConstraint) { - error = { - message: "Certificate basicConstraints pathLenConstraint violated.", - error: pki.certificateError.bad_certificate - }; - } - } - } - var vfd = error === null ? true : error.error; - var ret = options.verify ? options.verify(vfd, depth, certs) : vfd; - if (ret === true) { - error = null; - } else { - if (vfd === true) { - error = { - message: "The application rejected the certificate.", - error: pki.certificateError.bad_certificate - }; - } - if (ret || ret === 0) { - if (typeof ret === "object" && !forge3.util.isArray(ret)) { - if (ret.message) { - error.message = ret.message; - } - if (ret.error) { - error.error = ret.error; - } - } else if (typeof ret === "string") { - error.error = ret; - } - } - throw error; - } - first = false; - ++depth; - } while (chain.length > 0); - return true; - }; - } -}); - -// node_modules/node-forge/lib/pkcs12.js -var require_pkcs12 = __commonJS({ - "node_modules/node-forge/lib/pkcs12.js"(exports, module) { - var forge3 = require_forge(); - require_asn1(); - require_hmac(); - require_oids(); - require_pkcs7asn1(); - require_pbe(); - require_random(); - require_rsa(); - require_sha1(); - require_util(); - require_x509(); - var asn1 = forge3.asn1; - var pki = forge3.pki; - var p12 = module.exports = forge3.pkcs12 = forge3.pkcs12 || {}; - var contentInfoValidator = { - name: "ContentInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - // a ContentInfo - constructed: true, - value: [{ - name: "ContentInfo.contentType", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "contentType" - }, { - name: "ContentInfo.content", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - constructed: true, - captureAsn1: "content" - }] - }; - var pfxValidator = { - name: "PFX", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [ - { - name: "PFX.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }, - contentInfoValidator, - { - name: "PFX.macData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: "mac", - value: [{ - name: "PFX.macData.mac", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - // DigestInfo - constructed: true, - value: [{ - name: "PFX.macData.mac.digestAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - // DigestAlgorithmIdentifier - constructed: true, - value: [{ - name: "PFX.macData.mac.digestAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "macAlgorithm" - }, { - name: "PFX.macData.mac.digestAlgorithm.parameters", - tagClass: asn1.Class.UNIVERSAL, - captureAsn1: "macAlgorithmParameters" - }] - }, { - name: "PFX.macData.mac.digest", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "macDigest" - }] - }, { - name: "PFX.macData.macSalt", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "macSalt" - }, { - name: "PFX.macData.iterations", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - optional: true, - capture: "macIterations" - }] - } - ] - }; - var safeBagValidator = { - name: "SafeBag", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "SafeBag.bagId", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "bagId" - }, { - name: "SafeBag.bagValue", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - constructed: true, - captureAsn1: "bagValue" - }, { - name: "SafeBag.bagAttributes", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - optional: true, - capture: "bagAttributes" - }] - }; - var attributeValidator = { - name: "Attribute", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "Attribute.attrId", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "oid" - }, { - name: "Attribute.attrValues", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - capture: "values" - }] - }; - var certBagValidator = { - name: "CertBag", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "CertBag.certId", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "certId" - }, { - name: "CertBag.certValue", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - constructed: true, - /* So far we only support X.509 certificates (which are wrapped in - an OCTET STRING, hence hard code that here). */ - value: [{ - name: "CertBag.certValue[0]", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.OCTETSTRING, - constructed: false, - capture: "cert" - }] - }] - }; - function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) { - var result = []; - for (var i = 0; i < safeContents.length; i++) { - for (var j = 0; j < safeContents[i].safeBags.length; j++) { - var bag = safeContents[i].safeBags[j]; - if (bagType !== void 0 && bag.type !== bagType) { - continue; - } - if (attrName === null) { - result.push(bag); - continue; - } - if (bag.attributes[attrName] !== void 0 && bag.attributes[attrName].indexOf(attrValue) >= 0) { - result.push(bag); - } - } - } - return result; - } - p12.pkcs12FromAsn1 = function(obj, strict, password) { - if (typeof strict === "string") { - password = strict; - strict = true; - } else if (strict === void 0) { - strict = true; - } - var capture = {}; - var errors = []; - if (!asn1.validate(obj, pfxValidator, capture, errors)) { - var error = new Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX."); - error.errors = error; - throw error; - } - var pfx = { - version: capture.version.charCodeAt(0), - safeContents: [], - /** - * Gets bags with matching attributes. - * - * @param filter the attributes to filter by: - * [localKeyId] the localKeyId to search for. - * [localKeyIdHex] the localKeyId in hex to search for. - * [friendlyName] the friendly name to search for. - * [bagType] bag type to narrow each attribute search by. - * - * @return a map of attribute type to an array of matching bags or, if no - * attribute was given but a bag type, the map key will be the - * bag type. - */ - getBags: function(filter) { - var rval = {}; - var localKeyId; - if ("localKeyId" in filter) { - localKeyId = filter.localKeyId; - } else if ("localKeyIdHex" in filter) { - localKeyId = forge3.util.hexToBytes(filter.localKeyIdHex); - } - if (localKeyId === void 0 && !("friendlyName" in filter) && "bagType" in filter) { - rval[filter.bagType] = _getBagsByAttribute( - pfx.safeContents, - null, - null, - filter.bagType - ); - } - if (localKeyId !== void 0) { - rval.localKeyId = _getBagsByAttribute( - pfx.safeContents, - "localKeyId", - localKeyId, - filter.bagType - ); - } - if ("friendlyName" in filter) { - rval.friendlyName = _getBagsByAttribute( - pfx.safeContents, - "friendlyName", - filter.friendlyName, - filter.bagType - ); - } - return rval; - }, - /** - * DEPRECATED: use getBags() instead. - * - * Get bags with matching friendlyName attribute. - * - * @param friendlyName the friendly name to search for. - * @param [bagType] bag type to narrow search by. - * - * @return an array of bags with matching friendlyName attribute. - */ - getBagsByFriendlyName: function(friendlyName, bagType) { - return _getBagsByAttribute( - pfx.safeContents, - "friendlyName", - friendlyName, - bagType - ); - }, - /** - * DEPRECATED: use getBags() instead. - * - * Get bags with matching localKeyId attribute. - * - * @param localKeyId the localKeyId to search for. - * @param [bagType] bag type to narrow search by. - * - * @return an array of bags with matching localKeyId attribute. - */ - getBagsByLocalKeyId: function(localKeyId, bagType) { - return _getBagsByAttribute( - pfx.safeContents, - "localKeyId", - localKeyId, - bagType - ); - } - }; - if (capture.version.charCodeAt(0) !== 3) { - var error = new Error("PKCS#12 PFX of version other than 3 not supported."); - error.version = capture.version.charCodeAt(0); - throw error; - } - if (asn1.derToOid(capture.contentType) !== pki.oids.data) { - var error = new Error("Only PKCS#12 PFX in password integrity mode supported."); - error.oid = asn1.derToOid(capture.contentType); - throw error; - } - var data = capture.content.value[0]; - if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) { - throw new Error("PKCS#12 authSafe content data is not an OCTET STRING."); - } - data = _decodePkcs7Data(data); - if (capture.mac) { - var md = null; - var macKeyBytes = 0; - var macAlgorithm = asn1.derToOid(capture.macAlgorithm); - switch (macAlgorithm) { - case pki.oids.sha1: - md = forge3.md.sha1.create(); - macKeyBytes = 20; - break; - case pki.oids.sha256: - md = forge3.md.sha256.create(); - macKeyBytes = 32; - break; - case pki.oids.sha384: - md = forge3.md.sha384.create(); - macKeyBytes = 48; - break; - case pki.oids.sha512: - md = forge3.md.sha512.create(); - macKeyBytes = 64; - break; - case pki.oids.md5: - md = forge3.md.md5.create(); - macKeyBytes = 16; - break; - } - if (md === null) { - throw new Error("PKCS#12 uses unsupported MAC algorithm: " + macAlgorithm); - } - var macSalt = new forge3.util.ByteBuffer(capture.macSalt); - var macIterations = "macIterations" in capture ? parseInt(forge3.util.bytesToHex(capture.macIterations), 16) : 1; - var macKey = p12.generateKey( - password, - macSalt, - 3, - macIterations, - macKeyBytes, - md - ); - var mac = forge3.hmac.create(); - mac.start(md, macKey); - mac.update(data.value); - var macValue = mac.getMac(); - if (macValue.getBytes() !== capture.macDigest) { - throw new Error("PKCS#12 MAC could not be verified. Invalid password?"); - } - } - _decodeAuthenticatedSafe(pfx, data.value, strict, password); - return pfx; - }; - function _decodePkcs7Data(data) { - if (data.composed || data.constructed) { - var value = forge3.util.createBuffer(); - for (var i = 0; i < data.value.length; ++i) { - value.putBytes(data.value[i].value); - } - data.composed = data.constructed = false; - data.value = value.getBytes(); - } - return data; - } - function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) { - authSafe = asn1.fromDer(authSafe, strict); - if (authSafe.tagClass !== asn1.Class.UNIVERSAL || authSafe.type !== asn1.Type.SEQUENCE || authSafe.constructed !== true) { - throw new Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo"); - } - for (var i = 0; i < authSafe.value.length; i++) { - var contentInfo = authSafe.value[i]; - var capture = {}; - var errors = []; - if (!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) { - var error = new Error("Cannot read ContentInfo."); - error.errors = errors; - throw error; - } - var obj = { - encrypted: false - }; - var safeContents = null; - var data = capture.content.value[0]; - switch (asn1.derToOid(capture.contentType)) { - case pki.oids.data: - if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) { - throw new Error("PKCS#12 SafeContents Data is not an OCTET STRING."); - } - safeContents = _decodePkcs7Data(data).value; - break; - case pki.oids.encryptedData: - safeContents = _decryptSafeContents(data, password); - obj.encrypted = true; - break; - default: - var error = new Error("Unsupported PKCS#12 contentType."); - error.contentType = asn1.derToOid(capture.contentType); - throw error; - } - obj.safeBags = _decodeSafeContents(safeContents, strict, password); - pfx.safeContents.push(obj); - } - } - function _decryptSafeContents(data, password) { - var capture = {}; - var errors = []; - if (!asn1.validate( - data, - forge3.pkcs7.asn1.encryptedDataValidator, - capture, - errors - )) { - var error = new Error("Cannot read EncryptedContentInfo."); - error.errors = errors; - throw error; - } - var oid = asn1.derToOid(capture.contentType); - if (oid !== pki.oids.data) { - var error = new Error( - "PKCS#12 EncryptedContentInfo ContentType is not Data." - ); - error.oid = oid; - throw error; - } - oid = asn1.derToOid(capture.encAlgorithm); - var cipher = pki.pbe.getCipher(oid, capture.encParameter, password); - var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1); - var encrypted = forge3.util.createBuffer(encryptedContentAsn1.value); - cipher.update(encrypted); - if (!cipher.finish()) { - throw new Error("Failed to decrypt PKCS#12 SafeContents."); - } - return cipher.output.getBytes(); - } - function _decodeSafeContents(safeContents, strict, password) { - if (!strict && safeContents.length === 0) { - return []; - } - safeContents = asn1.fromDer(safeContents, strict); - if (safeContents.tagClass !== asn1.Class.UNIVERSAL || safeContents.type !== asn1.Type.SEQUENCE || safeContents.constructed !== true) { - throw new Error( - "PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag." - ); - } - var res = []; - for (var i = 0; i < safeContents.value.length; i++) { - var safeBag = safeContents.value[i]; - var capture = {}; - var errors = []; - if (!asn1.validate(safeBag, safeBagValidator, capture, errors)) { - var error = new Error("Cannot read SafeBag."); - error.errors = errors; - throw error; - } - var bag = { - type: asn1.derToOid(capture.bagId), - attributes: _decodeBagAttributes(capture.bagAttributes) - }; - res.push(bag); - var validator, decoder; - var bagAsn1 = capture.bagValue.value[0]; - switch (bag.type) { - case pki.oids.pkcs8ShroudedKeyBag: - bagAsn1 = pki.decryptPrivateKeyInfo(bagAsn1, password); - if (bagAsn1 === null) { - throw new Error( - "Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?" - ); - } - case pki.oids.keyBag: - try { - bag.key = pki.privateKeyFromAsn1(bagAsn1); - } catch (e) { - bag.key = null; - bag.asn1 = bagAsn1; - } - continue; - case pki.oids.certBag: - validator = certBagValidator; - decoder = function() { - if (asn1.derToOid(capture.certId) !== pki.oids.x509Certificate) { - var error2 = new Error( - "Unsupported certificate type, only X.509 supported." - ); - error2.oid = asn1.derToOid(capture.certId); - throw error2; - } - var certAsn1 = asn1.fromDer(capture.cert, strict); - try { - bag.cert = pki.certificateFromAsn1(certAsn1, true); - } catch (e) { - bag.cert = null; - bag.asn1 = certAsn1; - } - }; - break; - default: - var error = new Error("Unsupported PKCS#12 SafeBag type."); - error.oid = bag.type; - throw error; - } - if (validator !== void 0 && !asn1.validate(bagAsn1, validator, capture, errors)) { - var error = new Error("Cannot read PKCS#12 " + validator.name); - error.errors = errors; - throw error; - } - decoder(); - } - return res; - } - function _decodeBagAttributes(attributes) { - var decodedAttrs = {}; - if (attributes !== void 0) { - for (var i = 0; i < attributes.length; ++i) { - var capture = {}; - var errors = []; - if (!asn1.validate(attributes[i], attributeValidator, capture, errors)) { - var error = new Error("Cannot read PKCS#12 BagAttribute."); - error.errors = errors; - throw error; - } - var oid = asn1.derToOid(capture.oid); - if (pki.oids[oid] === void 0) { - continue; - } - decodedAttrs[pki.oids[oid]] = []; - for (var j = 0; j < capture.values.length; ++j) { - decodedAttrs[pki.oids[oid]].push(capture.values[j].value); - } - } - } - return decodedAttrs; - } - p12.toPkcs12Asn1 = function(key, cert, password, options) { - options = options || {}; - options.saltSize = options.saltSize || 8; - options.count = options.count || 2048; - options.algorithm = options.algorithm || options.encAlgorithm || "aes128"; - if (!("useMac" in options)) { - options.useMac = true; - } - if (!("localKeyId" in options)) { - options.localKeyId = null; - } - if (!("generateLocalKeyId" in options)) { - options.generateLocalKeyId = true; - } - var localKeyId = options.localKeyId; - var bagAttrs; - if (localKeyId !== null) { - localKeyId = forge3.util.hexToBytes(localKeyId); - } else if (options.generateLocalKeyId) { - if (cert) { - var pairedCert = forge3.util.isArray(cert) ? cert[0] : cert; - if (typeof pairedCert === "string") { - pairedCert = pki.certificateFromPem(pairedCert); - } - var sha1 = forge3.md.sha1.create(); - sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes()); - localKeyId = sha1.digest().getBytes(); - } else { - localKeyId = forge3.random.getBytes(20); - } - } - var attrs = []; - if (localKeyId !== null) { - attrs.push( - // localKeyID - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // attrId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.localKeyId).getBytes() - ), - // attrValues - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - localKeyId - ) - ]) - ]) - ); - } - if ("friendlyName" in options) { - attrs.push( - // friendlyName - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // attrId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.friendlyName).getBytes() - ), - // attrValues - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BMPSTRING, - false, - options.friendlyName - ) - ]) - ]) - ); - } - if (attrs.length > 0) { - bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs); - } - var contents = []; - var chain = []; - if (cert !== null) { - if (forge3.util.isArray(cert)) { - chain = cert; - } else { - chain = [cert]; - } - } - var certSafeBags = []; - for (var i = 0; i < chain.length; ++i) { - cert = chain[i]; - if (typeof cert === "string") { - cert = pki.certificateFromPem(cert); - } - var certBagAttrs = i === 0 ? bagAttrs : void 0; - var certAsn1 = pki.certificateToAsn1(cert); - var certSafeBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // bagId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.certBag).getBytes() - ), - // bagValue - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // CertBag - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // certId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.x509Certificate).getBytes() - ), - // certValue (x509Certificate) - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(certAsn1).getBytes() - ) - ]) - ]) - ]), - // bagAttributes (OPTIONAL) - certBagAttrs - ]); - certSafeBags.push(certSafeBag); - } - if (certSafeBags.length > 0) { - var certSafeContents = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - certSafeBags - ); - var certCI = ( - // PKCS#7 ContentInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // contentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - // OID for the content type is 'data' - asn1.oidToDer(pki.oids.data).getBytes() - ), - // content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(certSafeContents).getBytes() - ) - ]) - ]) - ); - contents.push(certCI); - } - var keyBag = null; - if (key !== null) { - var pkAsn1 = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key)); - if (password === null) { - keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // bagId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.keyBag).getBytes() - ), - // bagValue - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // PrivateKeyInfo - pkAsn1 - ]), - // bagAttributes (OPTIONAL) - bagAttrs - ]); - } else { - keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // bagId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes() - ), - // bagValue - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // EncryptedPrivateKeyInfo - pki.encryptPrivateKeyInfo(pkAsn1, password, options) - ]), - // bagAttributes (OPTIONAL) - bagAttrs - ]); - } - var keySafeContents = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]); - var keyCI = ( - // PKCS#7 ContentInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // contentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - // OID for the content type is 'data' - asn1.oidToDer(pki.oids.data).getBytes() - ), - // content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(keySafeContents).getBytes() - ) - ]) - ]) - ); - contents.push(keyCI); - } - var safe = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - contents - ); - var macData; - if (options.useMac) { - var sha1 = forge3.md.sha1.create(); - var macSalt = new forge3.util.ByteBuffer( - forge3.random.getBytes(options.saltSize) - ); - var count = options.count; - var key = p12.generateKey(password, macSalt, 3, count, 20); - var mac = forge3.hmac.create(); - mac.start(sha1, key); - mac.update(asn1.toDer(safe).getBytes()); - var macValue = mac.getMac(); - macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // mac DigestInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // digestAlgorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm = SHA-1 - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.sha1).getBytes() - ), - // parameters = Null - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]), - // digest - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - macValue.getBytes() - ) - ]), - // macSalt OCTET STRING - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - macSalt.getBytes() - ), - // iterations INTEGER (XXX: Only support count < 65536) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(count).getBytes() - ) - ]); - } - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version (3) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(3).getBytes() - ), - // PKCS#7 ContentInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // contentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - // OID for the content type is 'data' - asn1.oidToDer(pki.oids.data).getBytes() - ), - // content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(safe).getBytes() - ) - ]) - ]), - macData - ]); - }; - p12.generateKey = forge3.pbe.generatePkcs12Key; - } -}); - -// node_modules/node-forge/lib/pki.js -var require_pki = __commonJS({ - "node_modules/node-forge/lib/pki.js"(exports, module) { - var forge3 = require_forge(); - require_asn1(); - require_oids(); - require_pbe(); - require_pem(); - require_pbkdf2(); - require_pkcs12(); - require_pss(); - require_rsa(); - require_util(); - require_x509(); - var asn1 = forge3.asn1; - var pki = module.exports = forge3.pki = forge3.pki || {}; - pki.pemToDer = function(pem) { - var msg = forge3.pem.decode(pem)[0]; - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert PEM to DER; PEM is encrypted."); - } - return forge3.util.createBuffer(msg.body); - }; - pki.privateKeyFromPem = function(pem) { - var msg = forge3.pem.decode(pem)[0]; - if (msg.type !== "PRIVATE KEY" && msg.type !== "RSA PRIVATE KEY") { - var error = new Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".'); - error.headerType = msg.type; - throw error; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert private key from PEM; PEM is encrypted."); - } - var obj = asn1.fromDer(msg.body); - return pki.privateKeyFromAsn1(obj); - }; - pki.privateKeyToPem = function(key, maxline) { - var msg = { - type: "RSA PRIVATE KEY", - body: asn1.toDer(pki.privateKeyToAsn1(key)).getBytes() - }; - return forge3.pem.encode(msg, { maxline }); - }; - pki.privateKeyInfoToPem = function(pki2, maxline) { - var msg = { - type: "PRIVATE KEY", - body: asn1.toDer(pki2).getBytes() - }; - return forge3.pem.encode(msg, { maxline }); - }; - } -}); - -// node_modules/node-forge/lib/tls.js -var require_tls = __commonJS({ - "node_modules/node-forge/lib/tls.js"(exports, module) { - var forge3 = require_forge(); - require_asn1(); - require_hmac(); - require_md5(); - require_pem(); - require_pki(); - require_random(); - require_sha1(); - require_util(); - var prf_TLS1 = function(secret, label, seed, length) { - var rval = forge3.util.createBuffer(); - var idx = secret.length >> 1; - var slen = idx + (secret.length & 1); - var s1 = secret.substr(0, slen); - var s2 = secret.substr(idx, slen); - var ai = forge3.util.createBuffer(); - var hmac = forge3.hmac.create(); - seed = label + seed; - var md5itr = Math.ceil(length / 16); - var sha1itr = Math.ceil(length / 20); - hmac.start("MD5", s1); - var md5bytes = forge3.util.createBuffer(); - ai.putBytes(seed); - for (var i = 0; i < md5itr; ++i) { - hmac.start(null, null); - hmac.update(ai.getBytes()); - ai.putBuffer(hmac.digest()); - hmac.start(null, null); - hmac.update(ai.bytes() + seed); - md5bytes.putBuffer(hmac.digest()); - } - hmac.start("SHA1", s2); - var sha1bytes = forge3.util.createBuffer(); - ai.clear(); - ai.putBytes(seed); - for (var i = 0; i < sha1itr; ++i) { - hmac.start(null, null); - hmac.update(ai.getBytes()); - ai.putBuffer(hmac.digest()); - hmac.start(null, null); - hmac.update(ai.bytes() + seed); - sha1bytes.putBuffer(hmac.digest()); - } - rval.putBytes(forge3.util.xorBytes( - md5bytes.getBytes(), - sha1bytes.getBytes(), - length - )); - return rval; - }; - var hmac_sha1 = function(key2, seqNum, record) { - var hmac = forge3.hmac.create(); - hmac.start("SHA1", key2); - var b = forge3.util.createBuffer(); - b.putInt32(seqNum[0]); - b.putInt32(seqNum[1]); - b.putByte(record.type); - b.putByte(record.version.major); - b.putByte(record.version.minor); - b.putInt16(record.length); - b.putBytes(record.fragment.bytes()); - hmac.update(b.getBytes()); - return hmac.digest().getBytes(); - }; - var deflate = function(c, record, s) { - var rval = false; - try { - var bytes = c.deflate(record.fragment.getBytes()); - record.fragment = forge3.util.createBuffer(bytes); - record.length = bytes.length; - rval = true; - } catch (ex) { - } - return rval; - }; - var inflate = function(c, record, s) { - var rval = false; - try { - var bytes = c.inflate(record.fragment.getBytes()); - record.fragment = forge3.util.createBuffer(bytes); - record.length = bytes.length; - rval = true; - } catch (ex) { - } - return rval; - }; - var readVector = function(b, lenBytes) { - var len = 0; - switch (lenBytes) { - case 1: - len = b.getByte(); - break; - case 2: - len = b.getInt16(); - break; - case 3: - len = b.getInt24(); - break; - case 4: - len = b.getInt32(); - break; - } - return forge3.util.createBuffer(b.getBytes(len)); - }; - var writeVector = function(b, lenBytes, v) { - b.putInt(v.length(), lenBytes << 3); - b.putBuffer(v); - }; - var tls = {}; - tls.Versions = { - TLS_1_0: { major: 3, minor: 1 }, - TLS_1_1: { major: 3, minor: 2 }, - TLS_1_2: { major: 3, minor: 3 } - }; - tls.SupportedVersions = [ - tls.Versions.TLS_1_1, - tls.Versions.TLS_1_0 - ]; - tls.Version = tls.SupportedVersions[0]; - tls.MaxFragment = 16384 - 1024; - tls.ConnectionEnd = { - server: 0, - client: 1 - }; - tls.PRFAlgorithm = { - tls_prf_sha256: 0 - }; - tls.BulkCipherAlgorithm = { - none: null, - rc4: 0, - des3: 1, - aes: 2 - }; - tls.CipherType = { - stream: 0, - block: 1, - aead: 2 - }; - tls.MACAlgorithm = { - none: null, - hmac_md5: 0, - hmac_sha1: 1, - hmac_sha256: 2, - hmac_sha384: 3, - hmac_sha512: 4 - }; - tls.CompressionMethod = { - none: 0, - deflate: 1 - }; - tls.ContentType = { - change_cipher_spec: 20, - alert: 21, - handshake: 22, - application_data: 23, - heartbeat: 24 - }; - tls.HandshakeType = { - hello_request: 0, - client_hello: 1, - server_hello: 2, - certificate: 11, - server_key_exchange: 12, - certificate_request: 13, - server_hello_done: 14, - certificate_verify: 15, - client_key_exchange: 16, - finished: 20 - }; - tls.Alert = {}; - tls.Alert.Level = { - warning: 1, - fatal: 2 - }; - tls.Alert.Description = { - close_notify: 0, - unexpected_message: 10, - bad_record_mac: 20, - decryption_failed: 21, - record_overflow: 22, - decompression_failure: 30, - handshake_failure: 40, - bad_certificate: 42, - unsupported_certificate: 43, - certificate_revoked: 44, - certificate_expired: 45, - certificate_unknown: 46, - illegal_parameter: 47, - unknown_ca: 48, - access_denied: 49, - decode_error: 50, - decrypt_error: 51, - export_restriction: 60, - protocol_version: 70, - insufficient_security: 71, - internal_error: 80, - user_canceled: 90, - no_renegotiation: 100 - }; - tls.HeartbeatMessageType = { - heartbeat_request: 1, - heartbeat_response: 2 - }; - tls.CipherSuites = {}; - tls.getCipherSuite = function(twoBytes) { - var rval = null; - for (var key2 in tls.CipherSuites) { - var cs = tls.CipherSuites[key2]; - if (cs.id[0] === twoBytes.charCodeAt(0) && cs.id[1] === twoBytes.charCodeAt(1)) { - rval = cs; - break; - } - } - return rval; - }; - tls.handleUnexpected = function(c, record) { - var ignore = !c.open && c.entity === tls.ConnectionEnd.client; - if (!ignore) { - c.error(c, { - message: "Unexpected message. Received TLS record out of order.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unexpected_message - } - }); - } - }; - tls.handleHelloRequest = function(c, record, length) { - if (!c.handshaking && c.handshakes > 0) { - tls.queue(c, tls.createAlert(c, { - level: tls.Alert.Level.warning, - description: tls.Alert.Description.no_renegotiation - })); - tls.flush(c); - } - c.process(); - }; - tls.parseHelloMessage = function(c, record, length) { - var msg = null; - var client = c.entity === tls.ConnectionEnd.client; - if (length < 38) { - c.error(c, { - message: client ? "Invalid ServerHello message. Message too short." : "Invalid ClientHello message. Message too short.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } else { - var b = record.fragment; - var remaining = b.length(); - msg = { - version: { - major: b.getByte(), - minor: b.getByte() - }, - random: forge3.util.createBuffer(b.getBytes(32)), - session_id: readVector(b, 1), - extensions: [] - }; - if (client) { - msg.cipher_suite = b.getBytes(2); - msg.compression_method = b.getByte(); - } else { - msg.cipher_suites = readVector(b, 2); - msg.compression_methods = readVector(b, 1); - } - remaining = length - (remaining - b.length()); - if (remaining > 0) { - var exts = readVector(b, 2); - while (exts.length() > 0) { - msg.extensions.push({ - type: [exts.getByte(), exts.getByte()], - data: readVector(exts, 2) - }); - } - if (!client) { - for (var i = 0; i < msg.extensions.length; ++i) { - var ext = msg.extensions[i]; - if (ext.type[0] === 0 && ext.type[1] === 0) { - var snl = readVector(ext.data, 2); - while (snl.length() > 0) { - var snType = snl.getByte(); - if (snType !== 0) { - break; - } - c.session.extensions.server_name.serverNameList.push( - readVector(snl, 2).getBytes() - ); - } - } - } - } - } - if (c.session.version) { - if (msg.version.major !== c.session.version.major || msg.version.minor !== c.session.version.minor) { - return c.error(c, { - message: "TLS version change is disallowed during renegotiation.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.protocol_version - } - }); - } - } - if (client) { - c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite); - } else { - var tmp = forge3.util.createBuffer(msg.cipher_suites.bytes()); - while (tmp.length() > 0) { - c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2)); - if (c.session.cipherSuite !== null) { - break; - } - } - } - if (c.session.cipherSuite === null) { - return c.error(c, { - message: "No cipher suites in common.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.handshake_failure - }, - cipherSuite: forge3.util.bytesToHex(msg.cipher_suite) - }); - } - if (client) { - c.session.compressionMethod = msg.compression_method; - } else { - c.session.compressionMethod = tls.CompressionMethod.none; - } - } - return msg; - }; - tls.createSecurityParameters = function(c, msg) { - var client = c.entity === tls.ConnectionEnd.client; - var msgRandom = msg.random.bytes(); - var cRandom = client ? c.session.sp.client_random : msgRandom; - var sRandom = client ? msgRandom : tls.createRandom().getBytes(); - c.session.sp = { - entity: c.entity, - prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256, - bulk_cipher_algorithm: null, - cipher_type: null, - enc_key_length: null, - block_length: null, - fixed_iv_length: null, - record_iv_length: null, - mac_algorithm: null, - mac_length: null, - mac_key_length: null, - compression_algorithm: c.session.compressionMethod, - pre_master_secret: null, - master_secret: null, - client_random: cRandom, - server_random: sRandom - }; - }; - tls.handleServerHello = function(c, record, length) { - var msg = tls.parseHelloMessage(c, record, length); - if (c.fail) { - return; - } - if (msg.version.minor <= c.version.minor) { - c.version.minor = msg.version.minor; - } else { - return c.error(c, { - message: "Incompatible TLS version.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.protocol_version - } - }); - } - c.session.version = c.version; - var sessionId = msg.session_id.bytes(); - if (sessionId.length > 0 && sessionId === c.session.id) { - c.expect = SCC; - c.session.resuming = true; - c.session.sp.server_random = msg.random.bytes(); - } else { - c.expect = SCE; - c.session.resuming = false; - tls.createSecurityParameters(c, msg); - } - c.session.id = sessionId; - c.process(); - }; - tls.handleClientHello = function(c, record, length) { - var msg = tls.parseHelloMessage(c, record, length); - if (c.fail) { - return; - } - var sessionId = msg.session_id.bytes(); - var session = null; - if (c.sessionCache) { - session = c.sessionCache.getSession(sessionId); - if (session === null) { - sessionId = ""; - } else if (session.version.major !== msg.version.major || session.version.minor > msg.version.minor) { - session = null; - sessionId = ""; - } - } - if (sessionId.length === 0) { - sessionId = forge3.random.getBytes(32); - } - c.session.id = sessionId; - c.session.clientHelloVersion = msg.version; - c.session.sp = {}; - if (session) { - c.version = c.session.version = session.version; - c.session.sp = session.sp; - } else { - var version; - for (var i = 1; i < tls.SupportedVersions.length; ++i) { - version = tls.SupportedVersions[i]; - if (version.minor <= msg.version.minor) { - break; - } - } - c.version = { major: version.major, minor: version.minor }; - c.session.version = c.version; - } - if (session !== null) { - c.expect = CCC; - c.session.resuming = true; - c.session.sp.client_random = msg.random.bytes(); - } else { - c.expect = c.verifyClient !== false ? CCE : CKE; - c.session.resuming = false; - tls.createSecurityParameters(c, msg); - } - c.open = true; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createServerHello(c) - })); - if (c.session.resuming) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.change_cipher_spec, - data: tls.createChangeCipherSpec() - })); - c.state.pending = tls.createConnectionState(c); - c.state.current.write = c.state.pending.write; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createFinished(c) - })); - } else { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createCertificate(c) - })); - if (!c.fail) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createServerKeyExchange(c) - })); - if (c.verifyClient !== false) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createCertificateRequest(c) - })); - } - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createServerHelloDone(c) - })); - } - } - tls.flush(c); - c.process(); - }; - tls.handleCertificate = function(c, record, length) { - if (length < 3) { - return c.error(c, { - message: "Invalid Certificate message. Message too short.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } - var b = record.fragment; - var msg = { - certificate_list: readVector(b, 3) - }; - var cert, asn1; - var certs = []; - try { - while (msg.certificate_list.length() > 0) { - cert = readVector(msg.certificate_list, 3); - asn1 = forge3.asn1.fromDer(cert); - cert = forge3.pki.certificateFromAsn1(asn1, true); - certs.push(cert); - } - } catch (ex) { - return c.error(c, { - message: "Could not parse certificate list.", - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.bad_certificate - } - }); - } - var client = c.entity === tls.ConnectionEnd.client; - if ((client || c.verifyClient === true) && certs.length === 0) { - c.error(c, { - message: client ? "No server certificate provided." : "No client certificate provided.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } else if (certs.length === 0) { - c.expect = client ? SKE : CKE; - } else { - if (client) { - c.session.serverCertificate = certs[0]; - } else { - c.session.clientCertificate = certs[0]; - } - if (tls.verifyCertificateChain(c, certs)) { - c.expect = client ? SKE : CKE; - } - } - c.process(); - }; - tls.handleServerKeyExchange = function(c, record, length) { - if (length > 0) { - return c.error(c, { - message: "Invalid key parameters. Only RSA is supported.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unsupported_certificate - } - }); - } - c.expect = SCR; - c.process(); - }; - tls.handleClientKeyExchange = function(c, record, length) { - if (length < 48) { - return c.error(c, { - message: "Invalid key parameters. Only RSA is supported.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unsupported_certificate - } - }); - } - var b = record.fragment; - var msg = { - enc_pre_master_secret: readVector(b, 2).getBytes() - }; - var privateKey = null; - if (c.getPrivateKey) { - try { - privateKey = c.getPrivateKey(c, c.session.serverCertificate); - privateKey = forge3.pki.privateKeyFromPem(privateKey); - } catch (ex) { - c.error(c, { - message: "Could not get private key.", - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } - } - if (privateKey === null) { - return c.error(c, { - message: "No private key set.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } - try { - var sp = c.session.sp; - sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret); - var version = c.session.clientHelloVersion; - if (version.major !== sp.pre_master_secret.charCodeAt(0) || version.minor !== sp.pre_master_secret.charCodeAt(1)) { - throw new Error("TLS version rollback attack detected."); - } - } catch (ex) { - sp.pre_master_secret = forge3.random.getBytes(48); - } - c.expect = CCC; - if (c.session.clientCertificate !== null) { - c.expect = CCV; - } - c.process(); - }; - tls.handleCertificateRequest = function(c, record, length) { - if (length < 3) { - return c.error(c, { - message: "Invalid CertificateRequest. Message too short.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } - var b = record.fragment; - var msg = { - certificate_types: readVector(b, 1), - certificate_authorities: readVector(b, 2) - }; - c.session.certificateRequest = msg; - c.expect = SHD; - c.process(); - }; - tls.handleCertificateVerify = function(c, record, length) { - if (length < 2) { - return c.error(c, { - message: "Invalid CertificateVerify. Message too short.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } - var b = record.fragment; - b.read -= 4; - var msgBytes = b.bytes(); - b.read += 4; - var msg = { - signature: readVector(b, 2).getBytes() - }; - var verify = forge3.util.createBuffer(); - verify.putBuffer(c.session.md5.digest()); - verify.putBuffer(c.session.sha1.digest()); - verify = verify.getBytes(); - try { - var cert = c.session.clientCertificate; - if (!cert.publicKey.verify(verify, msg.signature, "NONE")) { - throw new Error("CertificateVerify signature does not match."); - } - c.session.md5.update(msgBytes); - c.session.sha1.update(msgBytes); - } catch (ex) { - return c.error(c, { - message: "Bad signature in CertificateVerify.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.handshake_failure - } - }); - } - c.expect = CCC; - c.process(); - }; - tls.handleServerHelloDone = function(c, record, length) { - if (length > 0) { - return c.error(c, { - message: "Invalid ServerHelloDone message. Invalid length.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.record_overflow - } - }); - } - if (c.serverCertificate === null) { - var error = { - message: "No server certificate provided. Not enough security.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.insufficient_security - } - }; - var depth = 0; - var ret = c.verify(c, error.alert.description, depth, []); - if (ret !== true) { - if (ret || ret === 0) { - if (typeof ret === "object" && !forge3.util.isArray(ret)) { - if (ret.message) { - error.message = ret.message; - } - if (ret.alert) { - error.alert.description = ret.alert; - } - } else if (typeof ret === "number") { - error.alert.description = ret; - } - } - return c.error(c, error); - } - } - if (c.session.certificateRequest !== null) { - record = tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createCertificate(c) - }); - tls.queue(c, record); - } - record = tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createClientKeyExchange(c) - }); - tls.queue(c, record); - c.expect = SER; - var callback = function(c2, signature) { - if (c2.session.certificateRequest !== null && c2.session.clientCertificate !== null) { - tls.queue(c2, tls.createRecord(c2, { - type: tls.ContentType.handshake, - data: tls.createCertificateVerify(c2, signature) - })); - } - tls.queue(c2, tls.createRecord(c2, { - type: tls.ContentType.change_cipher_spec, - data: tls.createChangeCipherSpec() - })); - c2.state.pending = tls.createConnectionState(c2); - c2.state.current.write = c2.state.pending.write; - tls.queue(c2, tls.createRecord(c2, { - type: tls.ContentType.handshake, - data: tls.createFinished(c2) - })); - c2.expect = SCC; - tls.flush(c2); - c2.process(); - }; - if (c.session.certificateRequest === null || c.session.clientCertificate === null) { - return callback(c, null); - } - tls.getClientSignature(c, callback); - }; - tls.handleChangeCipherSpec = function(c, record) { - if (record.fragment.getByte() !== 1) { - return c.error(c, { - message: "Invalid ChangeCipherSpec message received.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } - var client = c.entity === tls.ConnectionEnd.client; - if (c.session.resuming && client || !c.session.resuming && !client) { - c.state.pending = tls.createConnectionState(c); - } - c.state.current.read = c.state.pending.read; - if (!c.session.resuming && client || c.session.resuming && !client) { - c.state.pending = null; - } - c.expect = client ? SFI : CFI; - c.process(); - }; - tls.handleFinished = function(c, record, length) { - var b = record.fragment; - b.read -= 4; - var msgBytes = b.bytes(); - b.read += 4; - var vd = record.fragment.getBytes(); - b = forge3.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); - var client = c.entity === tls.ConnectionEnd.client; - var label = client ? "server finished" : "client finished"; - var sp = c.session.sp; - var vdl = 12; - var prf = prf_TLS1; - b = prf(sp.master_secret, label, b.getBytes(), vdl); - if (b.getBytes() !== vd) { - return c.error(c, { - message: "Invalid verify_data in Finished message.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.decrypt_error - } - }); - } - c.session.md5.update(msgBytes); - c.session.sha1.update(msgBytes); - if (c.session.resuming && client || !c.session.resuming && !client) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.change_cipher_spec, - data: tls.createChangeCipherSpec() - })); - c.state.current.write = c.state.pending.write; - c.state.pending = null; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createFinished(c) - })); - } - c.expect = client ? SAD : CAD; - c.handshaking = false; - ++c.handshakes; - c.peerCertificate = client ? c.session.serverCertificate : c.session.clientCertificate; - tls.flush(c); - c.isConnected = true; - c.connected(c); - c.process(); - }; - tls.handleAlert = function(c, record) { - var b = record.fragment; - var alert = { - level: b.getByte(), - description: b.getByte() - }; - var msg; - switch (alert.description) { - case tls.Alert.Description.close_notify: - msg = "Connection closed."; - break; - case tls.Alert.Description.unexpected_message: - msg = "Unexpected message."; - break; - case tls.Alert.Description.bad_record_mac: - msg = "Bad record MAC."; - break; - case tls.Alert.Description.decryption_failed: - msg = "Decryption failed."; - break; - case tls.Alert.Description.record_overflow: - msg = "Record overflow."; - break; - case tls.Alert.Description.decompression_failure: - msg = "Decompression failed."; - break; - case tls.Alert.Description.handshake_failure: - msg = "Handshake failure."; - break; - case tls.Alert.Description.bad_certificate: - msg = "Bad certificate."; - break; - case tls.Alert.Description.unsupported_certificate: - msg = "Unsupported certificate."; - break; - case tls.Alert.Description.certificate_revoked: - msg = "Certificate revoked."; - break; - case tls.Alert.Description.certificate_expired: - msg = "Certificate expired."; - break; - case tls.Alert.Description.certificate_unknown: - msg = "Certificate unknown."; - break; - case tls.Alert.Description.illegal_parameter: - msg = "Illegal parameter."; - break; - case tls.Alert.Description.unknown_ca: - msg = "Unknown certificate authority."; - break; - case tls.Alert.Description.access_denied: - msg = "Access denied."; - break; - case tls.Alert.Description.decode_error: - msg = "Decode error."; - break; - case tls.Alert.Description.decrypt_error: - msg = "Decrypt error."; - break; - case tls.Alert.Description.export_restriction: - msg = "Export restriction."; - break; - case tls.Alert.Description.protocol_version: - msg = "Unsupported protocol version."; - break; - case tls.Alert.Description.insufficient_security: - msg = "Insufficient security."; - break; - case tls.Alert.Description.internal_error: - msg = "Internal error."; - break; - case tls.Alert.Description.user_canceled: - msg = "User canceled."; - break; - case tls.Alert.Description.no_renegotiation: - msg = "Renegotiation not supported."; - break; - default: - msg = "Unknown error."; - break; - } - if (alert.description === tls.Alert.Description.close_notify) { - return c.close(); - } - c.error(c, { - message: msg, - send: false, - // origin is the opposite end - origin: c.entity === tls.ConnectionEnd.client ? "server" : "client", - alert - }); - c.process(); - }; - tls.handleHandshake = function(c, record) { - var b = record.fragment; - var type = b.getByte(); - var length = b.getInt24(); - if (length > b.length()) { - c.fragmented = record; - record.fragment = forge3.util.createBuffer(); - b.read -= 4; - return c.process(); - } - c.fragmented = null; - b.read -= 4; - var bytes = b.bytes(length + 4); - b.read += 4; - if (type in hsTable[c.entity][c.expect]) { - if (c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) { - c.handshaking = true; - c.session = { - version: null, - extensions: { - server_name: { - serverNameList: [] - } - }, - cipherSuite: null, - compressionMethod: null, - serverCertificate: null, - clientCertificate: null, - md5: forge3.md.md5.create(), - sha1: forge3.md.sha1.create() - }; - } - if (type !== tls.HandshakeType.hello_request && type !== tls.HandshakeType.certificate_verify && type !== tls.HandshakeType.finished) { - c.session.md5.update(bytes); - c.session.sha1.update(bytes); - } - hsTable[c.entity][c.expect][type](c, record, length); - } else { - tls.handleUnexpected(c, record); - } - }; - tls.handleApplicationData = function(c, record) { - c.data.putBuffer(record.fragment); - c.dataReady(c); - c.process(); - }; - tls.handleHeartbeat = function(c, record) { - var b = record.fragment; - var type = b.getByte(); - var length = b.getInt16(); - var payload = b.getBytes(length); - if (type === tls.HeartbeatMessageType.heartbeat_request) { - if (c.handshaking || length > payload.length) { - return c.process(); - } - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.heartbeat, - data: tls.createHeartbeat( - tls.HeartbeatMessageType.heartbeat_response, - payload - ) - })); - tls.flush(c); - } else if (type === tls.HeartbeatMessageType.heartbeat_response) { - if (payload !== c.expectedHeartbeatPayload) { - return c.process(); - } - if (c.heartbeatReceived) { - c.heartbeatReceived(c, forge3.util.createBuffer(payload)); - } - } - c.process(); - }; - var SHE = 0; - var SCE = 1; - var SKE = 2; - var SCR = 3; - var SHD = 4; - var SCC = 5; - var SFI = 6; - var SAD = 7; - var SER = 8; - var CHE = 0; - var CCE = 1; - var CKE = 2; - var CCV = 3; - var CCC = 4; - var CFI = 5; - var CAD = 6; - var __ = tls.handleUnexpected; - var R0 = tls.handleChangeCipherSpec; - var R1 = tls.handleAlert; - var R2 = tls.handleHandshake; - var R3 = tls.handleApplicationData; - var R4 = tls.handleHeartbeat; - var ctTable = []; - ctTable[tls.ConnectionEnd.client] = [ - // CC,AL,HS,AD,HB - /*SHE*/ - [__, R1, R2, __, R4], - /*SCE*/ - [__, R1, R2, __, R4], - /*SKE*/ - [__, R1, R2, __, R4], - /*SCR*/ - [__, R1, R2, __, R4], - /*SHD*/ - [__, R1, R2, __, R4], - /*SCC*/ - [R0, R1, __, __, R4], - /*SFI*/ - [__, R1, R2, __, R4], - /*SAD*/ - [__, R1, R2, R3, R4], - /*SER*/ - [__, R1, R2, __, R4] - ]; - ctTable[tls.ConnectionEnd.server] = [ - // CC,AL,HS,AD - /*CHE*/ - [__, R1, R2, __, R4], - /*CCE*/ - [__, R1, R2, __, R4], - /*CKE*/ - [__, R1, R2, __, R4], - /*CCV*/ - [__, R1, R2, __, R4], - /*CCC*/ - [R0, R1, __, __, R4], - /*CFI*/ - [__, R1, R2, __, R4], - /*CAD*/ - [__, R1, R2, R3, R4], - /*CER*/ - [__, R1, R2, __, R4] - ]; - var H0 = tls.handleHelloRequest; - var H1 = tls.handleServerHello; - var H2 = tls.handleCertificate; - var H3 = tls.handleServerKeyExchange; - var H4 = tls.handleCertificateRequest; - var H5 = tls.handleServerHelloDone; - var H6 = tls.handleFinished; - var hsTable = []; - hsTable[tls.ConnectionEnd.client] = [ - // HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI - /*SHE*/ - [__, __, H1, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*SCE*/ - [H0, __, __, __, __, __, __, __, __, __, __, H2, H3, H4, H5, __, __, __, __, __, __], - /*SKE*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, H3, H4, H5, __, __, __, __, __, __], - /*SCR*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, H4, H5, __, __, __, __, __, __], - /*SHD*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, H5, __, __, __, __, __, __], - /*SCC*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*SFI*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6], - /*SAD*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*SER*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] - ]; - var H7 = tls.handleClientHello; - var H8 = tls.handleClientKeyExchange; - var H9 = tls.handleCertificateVerify; - hsTable[tls.ConnectionEnd.server] = [ - // 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI - /*CHE*/ - [__, H7, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*CCE*/ - [__, __, __, __, __, __, __, __, __, __, __, H2, __, __, __, __, __, __, __, __, __], - /*CKE*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H8, __, __, __, __], - /*CCV*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H9, __, __, __, __, __], - /*CCC*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*CFI*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6], - /*CAD*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*CER*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] - ]; - tls.generateKeys = function(c, sp) { - var prf = prf_TLS1; - var random = sp.client_random + sp.server_random; - if (!c.session.resuming) { - sp.master_secret = prf( - sp.pre_master_secret, - "master secret", - random, - 48 - ).bytes(); - sp.pre_master_secret = null; - } - random = sp.server_random + sp.client_random; - var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length; - var tls10 = c.version.major === tls.Versions.TLS_1_0.major && c.version.minor === tls.Versions.TLS_1_0.minor; - if (tls10) { - length += 2 * sp.fixed_iv_length; - } - var km = prf(sp.master_secret, "key expansion", random, length); - var rval = { - client_write_MAC_key: km.getBytes(sp.mac_key_length), - server_write_MAC_key: km.getBytes(sp.mac_key_length), - client_write_key: km.getBytes(sp.enc_key_length), - server_write_key: km.getBytes(sp.enc_key_length) - }; - if (tls10) { - rval.client_write_IV = km.getBytes(sp.fixed_iv_length); - rval.server_write_IV = km.getBytes(sp.fixed_iv_length); - } - return rval; - }; - tls.createConnectionState = function(c) { - var client = c.entity === tls.ConnectionEnd.client; - var createMode = function() { - var mode = { - // two 32-bit numbers, first is most significant - sequenceNumber: [0, 0], - macKey: null, - macLength: 0, - macFunction: null, - cipherState: null, - cipherFunction: function(record) { - return true; - }, - compressionState: null, - compressFunction: function(record) { - return true; - }, - updateSequenceNumber: function() { - if (mode.sequenceNumber[1] === 4294967295) { - mode.sequenceNumber[1] = 0; - ++mode.sequenceNumber[0]; - } else { - ++mode.sequenceNumber[1]; - } - } - }; - return mode; - }; - var state = { - read: createMode(), - write: createMode() - }; - state.read.update = function(c2, record) { - if (!state.read.cipherFunction(record, state.read)) { - c2.error(c2, { - message: "Could not decrypt record or bad MAC.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - // doesn't matter if decryption failed or MAC was - // invalid, return the same error so as not to reveal - // which one occurred - description: tls.Alert.Description.bad_record_mac - } - }); - } else if (!state.read.compressFunction(c2, record, state.read)) { - c2.error(c2, { - message: "Could not decompress record.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.decompression_failure - } - }); - } - return !c2.fail; - }; - state.write.update = function(c2, record) { - if (!state.write.compressFunction(c2, record, state.write)) { - c2.error(c2, { - message: "Could not compress record.", - send: false, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } else if (!state.write.cipherFunction(record, state.write)) { - c2.error(c2, { - message: "Could not encrypt record.", - send: false, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } - return !c2.fail; - }; - if (c.session) { - var sp = c.session.sp; - c.session.cipherSuite.initSecurityParameters(sp); - sp.keys = tls.generateKeys(c, sp); - state.read.macKey = client ? sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key; - state.write.macKey = client ? sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key; - c.session.cipherSuite.initConnectionState(state, c, sp); - switch (sp.compression_algorithm) { - case tls.CompressionMethod.none: - break; - case tls.CompressionMethod.deflate: - state.read.compressFunction = inflate; - state.write.compressFunction = deflate; - break; - default: - throw new Error("Unsupported compression algorithm."); - } - } - return state; - }; - tls.createRandom = function() { - var d = /* @__PURE__ */ new Date(); - var utc = +d + d.getTimezoneOffset() * 6e4; - var rval = forge3.util.createBuffer(); - rval.putInt32(utc); - rval.putBytes(forge3.random.getBytes(28)); - return rval; - }; - tls.createRecord = function(c, options) { - if (!options.data) { - return null; - } - var record = { - type: options.type, - version: { - major: c.version.major, - minor: c.version.minor - }, - length: options.data.length(), - fragment: options.data - }; - return record; - }; - tls.createAlert = function(c, alert) { - var b = forge3.util.createBuffer(); - b.putByte(alert.level); - b.putByte(alert.description); - return tls.createRecord(c, { - type: tls.ContentType.alert, - data: b - }); - }; - tls.createClientHello = function(c) { - c.session.clientHelloVersion = { - major: c.version.major, - minor: c.version.minor - }; - var cipherSuites = forge3.util.createBuffer(); - for (var i = 0; i < c.cipherSuites.length; ++i) { - var cs = c.cipherSuites[i]; - cipherSuites.putByte(cs.id[0]); - cipherSuites.putByte(cs.id[1]); - } - var cSuites = cipherSuites.length(); - var compressionMethods = forge3.util.createBuffer(); - compressionMethods.putByte(tls.CompressionMethod.none); - var cMethods = compressionMethods.length(); - var extensions = forge3.util.createBuffer(); - if (c.virtualHost) { - var ext = forge3.util.createBuffer(); - ext.putByte(0); - ext.putByte(0); - var serverName = forge3.util.createBuffer(); - serverName.putByte(0); - writeVector(serverName, 2, forge3.util.createBuffer(c.virtualHost)); - var snList = forge3.util.createBuffer(); - writeVector(snList, 2, serverName); - writeVector(ext, 2, snList); - extensions.putBuffer(ext); - } - var extLength = extensions.length(); - if (extLength > 0) { - extLength += 2; - } - var sessionId = c.session.id; - var length = sessionId.length + 1 + // session ID vector - 2 + // version (major + minor) - 4 + 28 + // random time and random bytes - 2 + cSuites + // cipher suites vector - 1 + cMethods + // compression methods vector - extLength; - var rval = forge3.util.createBuffer(); - rval.putByte(tls.HandshakeType.client_hello); - rval.putInt24(length); - rval.putByte(c.version.major); - rval.putByte(c.version.minor); - rval.putBytes(c.session.sp.client_random); - writeVector(rval, 1, forge3.util.createBuffer(sessionId)); - writeVector(rval, 2, cipherSuites); - writeVector(rval, 1, compressionMethods); - if (extLength > 0) { - writeVector(rval, 2, extensions); - } - return rval; - }; - tls.createServerHello = function(c) { - var sessionId = c.session.id; - var length = sessionId.length + 1 + // session ID vector - 2 + // version (major + minor) - 4 + 28 + // random time and random bytes - 2 + // chosen cipher suite - 1; - var rval = forge3.util.createBuffer(); - rval.putByte(tls.HandshakeType.server_hello); - rval.putInt24(length); - rval.putByte(c.version.major); - rval.putByte(c.version.minor); - rval.putBytes(c.session.sp.server_random); - writeVector(rval, 1, forge3.util.createBuffer(sessionId)); - rval.putByte(c.session.cipherSuite.id[0]); - rval.putByte(c.session.cipherSuite.id[1]); - rval.putByte(c.session.compressionMethod); - return rval; - }; - tls.createCertificate = function(c) { - var client = c.entity === tls.ConnectionEnd.client; - var cert = null; - if (c.getCertificate) { - var hint; - if (client) { - hint = c.session.certificateRequest; - } else { - hint = c.session.extensions.server_name.serverNameList; - } - cert = c.getCertificate(c, hint); - } - var certList = forge3.util.createBuffer(); - if (cert !== null) { - try { - if (!forge3.util.isArray(cert)) { - cert = [cert]; - } - var asn1 = null; - for (var i = 0; i < cert.length; ++i) { - var msg = forge3.pem.decode(cert[i])[0]; - if (msg.type !== "CERTIFICATE" && msg.type !== "X509 CERTIFICATE" && msg.type !== "TRUSTED CERTIFICATE") { - var error = new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".'); - error.headerType = msg.type; - throw error; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert certificate from PEM; PEM is encrypted."); - } - var der = forge3.util.createBuffer(msg.body); - if (asn1 === null) { - asn1 = forge3.asn1.fromDer(der.bytes(), false); - } - var certBuffer = forge3.util.createBuffer(); - writeVector(certBuffer, 3, der); - certList.putBuffer(certBuffer); - } - cert = forge3.pki.certificateFromAsn1(asn1); - if (client) { - c.session.clientCertificate = cert; - } else { - c.session.serverCertificate = cert; - } - } catch (ex) { - return c.error(c, { - message: "Could not send certificate list.", - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.bad_certificate - } - }); - } - } - var length = 3 + certList.length(); - var rval = forge3.util.createBuffer(); - rval.putByte(tls.HandshakeType.certificate); - rval.putInt24(length); - writeVector(rval, 3, certList); - return rval; - }; - tls.createClientKeyExchange = function(c) { - var b = forge3.util.createBuffer(); - b.putByte(c.session.clientHelloVersion.major); - b.putByte(c.session.clientHelloVersion.minor); - b.putBytes(forge3.random.getBytes(46)); - var sp = c.session.sp; - sp.pre_master_secret = b.getBytes(); - var key2 = c.session.serverCertificate.publicKey; - b = key2.encrypt(sp.pre_master_secret); - var length = b.length + 2; - var rval = forge3.util.createBuffer(); - rval.putByte(tls.HandshakeType.client_key_exchange); - rval.putInt24(length); - rval.putInt16(b.length); - rval.putBytes(b); - return rval; - }; - tls.createServerKeyExchange = function(c) { - var length = 0; - var rval = forge3.util.createBuffer(); - if (length > 0) { - rval.putByte(tls.HandshakeType.server_key_exchange); - rval.putInt24(length); - } - return rval; - }; - tls.getClientSignature = function(c, callback) { - var b = forge3.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); - b = b.getBytes(); - c.getSignature = c.getSignature || function(c2, b2, callback2) { - var privateKey = null; - if (c2.getPrivateKey) { - try { - privateKey = c2.getPrivateKey(c2, c2.session.clientCertificate); - privateKey = forge3.pki.privateKeyFromPem(privateKey); - } catch (ex) { - c2.error(c2, { - message: "Could not get private key.", - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } - } - if (privateKey === null) { - c2.error(c2, { - message: "No private key set.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } else { - b2 = privateKey.sign(b2, null); - } - callback2(c2, b2); - }; - c.getSignature(c, b, callback); - }; - tls.createCertificateVerify = function(c, signature) { - var length = signature.length + 2; - var rval = forge3.util.createBuffer(); - rval.putByte(tls.HandshakeType.certificate_verify); - rval.putInt24(length); - rval.putInt16(signature.length); - rval.putBytes(signature); - return rval; - }; - tls.createCertificateRequest = function(c) { - var certTypes = forge3.util.createBuffer(); - certTypes.putByte(1); - var cAs = forge3.util.createBuffer(); - for (var key2 in c.caStore.certs) { - var cert = c.caStore.certs[key2]; - var dn = forge3.pki.distinguishedNameToAsn1(cert.subject); - var byteBuffer = forge3.asn1.toDer(dn); - cAs.putInt16(byteBuffer.length()); - cAs.putBuffer(byteBuffer); - } - var length = 1 + certTypes.length() + 2 + cAs.length(); - var rval = forge3.util.createBuffer(); - rval.putByte(tls.HandshakeType.certificate_request); - rval.putInt24(length); - writeVector(rval, 1, certTypes); - writeVector(rval, 2, cAs); - return rval; - }; - tls.createServerHelloDone = function(c) { - var rval = forge3.util.createBuffer(); - rval.putByte(tls.HandshakeType.server_hello_done); - rval.putInt24(0); - return rval; - }; - tls.createChangeCipherSpec = function() { - var rval = forge3.util.createBuffer(); - rval.putByte(1); - return rval; - }; - tls.createFinished = function(c) { - var b = forge3.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); - var client = c.entity === tls.ConnectionEnd.client; - var sp = c.session.sp; - var vdl = 12; - var prf = prf_TLS1; - var label = client ? "client finished" : "server finished"; - b = prf(sp.master_secret, label, b.getBytes(), vdl); - var rval = forge3.util.createBuffer(); - rval.putByte(tls.HandshakeType.finished); - rval.putInt24(b.length()); - rval.putBuffer(b); - return rval; - }; - tls.createHeartbeat = function(type, payload, payloadLength) { - if (typeof payloadLength === "undefined") { - payloadLength = payload.length; - } - var rval = forge3.util.createBuffer(); - rval.putByte(type); - rval.putInt16(payloadLength); - rval.putBytes(payload); - var plaintextLength = rval.length(); - var paddingLength = Math.max(16, plaintextLength - payloadLength - 3); - rval.putBytes(forge3.random.getBytes(paddingLength)); - return rval; - }; - tls.queue = function(c, record) { - if (!record) { - return; - } - if (record.fragment.length() === 0) { - if (record.type === tls.ContentType.handshake || record.type === tls.ContentType.alert || record.type === tls.ContentType.change_cipher_spec) { - return; - } - } - if (record.type === tls.ContentType.handshake) { - var bytes = record.fragment.bytes(); - c.session.md5.update(bytes); - c.session.sha1.update(bytes); - bytes = null; - } - var records; - if (record.fragment.length() <= tls.MaxFragment) { - records = [record]; - } else { - records = []; - var data = record.fragment.bytes(); - while (data.length > tls.MaxFragment) { - records.push(tls.createRecord(c, { - type: record.type, - data: forge3.util.createBuffer(data.slice(0, tls.MaxFragment)) - })); - data = data.slice(tls.MaxFragment); - } - if (data.length > 0) { - records.push(tls.createRecord(c, { - type: record.type, - data: forge3.util.createBuffer(data) - })); - } - } - for (var i = 0; i < records.length && !c.fail; ++i) { - var rec = records[i]; - var s = c.state.current.write; - if (s.update(c, rec)) { - c.records.push(rec); - } - } - }; - tls.flush = function(c) { - for (var i = 0; i < c.records.length; ++i) { - var record = c.records[i]; - c.tlsData.putByte(record.type); - c.tlsData.putByte(record.version.major); - c.tlsData.putByte(record.version.minor); - c.tlsData.putInt16(record.fragment.length()); - c.tlsData.putBuffer(c.records[i].fragment); - } - c.records = []; - return c.tlsDataReady(c); - }; - var _certErrorToAlertDesc = function(error) { - switch (error) { - case true: - return true; - case forge3.pki.certificateError.bad_certificate: - return tls.Alert.Description.bad_certificate; - case forge3.pki.certificateError.unsupported_certificate: - return tls.Alert.Description.unsupported_certificate; - case forge3.pki.certificateError.certificate_revoked: - return tls.Alert.Description.certificate_revoked; - case forge3.pki.certificateError.certificate_expired: - return tls.Alert.Description.certificate_expired; - case forge3.pki.certificateError.certificate_unknown: - return tls.Alert.Description.certificate_unknown; - case forge3.pki.certificateError.unknown_ca: - return tls.Alert.Description.unknown_ca; - default: - return tls.Alert.Description.bad_certificate; - } - }; - var _alertDescToCertError = function(desc) { - switch (desc) { - case true: - return true; - case tls.Alert.Description.bad_certificate: - return forge3.pki.certificateError.bad_certificate; - case tls.Alert.Description.unsupported_certificate: - return forge3.pki.certificateError.unsupported_certificate; - case tls.Alert.Description.certificate_revoked: - return forge3.pki.certificateError.certificate_revoked; - case tls.Alert.Description.certificate_expired: - return forge3.pki.certificateError.certificate_expired; - case tls.Alert.Description.certificate_unknown: - return forge3.pki.certificateError.certificate_unknown; - case tls.Alert.Description.unknown_ca: - return forge3.pki.certificateError.unknown_ca; - default: - return forge3.pki.certificateError.bad_certificate; - } - }; - tls.verifyCertificateChain = function(c, chain) { - try { - var options = {}; - for (var key2 in c.verifyOptions) { - options[key2] = c.verifyOptions[key2]; - } - options.verify = function(vfd, depth, chain2) { - var desc = _certErrorToAlertDesc(vfd); - var ret = c.verify(c, vfd, depth, chain2); - if (ret !== true) { - if (typeof ret === "object" && !forge3.util.isArray(ret)) { - var error = new Error("The application rejected the certificate."); - error.send = true; - error.alert = { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.bad_certificate - }; - if (ret.message) { - error.message = ret.message; - } - if (ret.alert) { - error.alert.description = ret.alert; - } - throw error; - } - if (ret !== vfd) { - ret = _alertDescToCertError(ret); - } - } - return ret; - }; - forge3.pki.verifyCertificateChain(c.caStore, chain, options); - } catch (ex) { - var err = ex; - if (typeof err !== "object" || forge3.util.isArray(err)) { - err = { - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: _certErrorToAlertDesc(ex) - } - }; - } - if (!("send" in err)) { - err.send = true; - } - if (!("alert" in err)) { - err.alert = { - level: tls.Alert.Level.fatal, - description: _certErrorToAlertDesc(err.error) - }; - } - c.error(c, err); - } - return !c.fail; - }; - tls.createSessionCache = function(cache, capacity) { - var rval = null; - if (cache && cache.getSession && cache.setSession && cache.order) { - rval = cache; - } else { - rval = {}; - rval.cache = cache || {}; - rval.capacity = Math.max(capacity || 100, 1); - rval.order = []; - for (var key2 in cache) { - if (rval.order.length <= capacity) { - rval.order.push(key2); - } else { - delete cache[key2]; - } - } - rval.getSession = function(sessionId) { - var session = null; - var key3 = null; - if (sessionId) { - key3 = forge3.util.bytesToHex(sessionId); - } else if (rval.order.length > 0) { - key3 = rval.order[0]; - } - if (key3 !== null && key3 in rval.cache) { - session = rval.cache[key3]; - delete rval.cache[key3]; - for (var i in rval.order) { - if (rval.order[i] === key3) { - rval.order.splice(i, 1); - break; - } - } - } - return session; - }; - rval.setSession = function(sessionId, session) { - if (rval.order.length === rval.capacity) { - var key3 = rval.order.shift(); - delete rval.cache[key3]; - } - var key3 = forge3.util.bytesToHex(sessionId); - rval.order.push(key3); - rval.cache[key3] = session; - }; - } - return rval; - }; - tls.createConnection = function(options) { - var caStore = null; - if (options.caStore) { - if (forge3.util.isArray(options.caStore)) { - caStore = forge3.pki.createCaStore(options.caStore); - } else { - caStore = options.caStore; - } - } else { - caStore = forge3.pki.createCaStore(); - } - var cipherSuites = options.cipherSuites || null; - if (cipherSuites === null) { - cipherSuites = []; - for (var key2 in tls.CipherSuites) { - cipherSuites.push(tls.CipherSuites[key2]); - } - } - var entity = options.server || false ? tls.ConnectionEnd.server : tls.ConnectionEnd.client; - var sessionCache = options.sessionCache ? tls.createSessionCache(options.sessionCache) : null; - var c = { - version: { major: tls.Version.major, minor: tls.Version.minor }, - entity, - sessionId: options.sessionId, - caStore, - sessionCache, - cipherSuites, - connected: options.connected, - virtualHost: options.virtualHost || null, - verifyClient: options.verifyClient || false, - verify: options.verify || function(cn, vfd, dpth, cts) { - return vfd; - }, - verifyOptions: options.verifyOptions || {}, - getCertificate: options.getCertificate || null, - getPrivateKey: options.getPrivateKey || null, - getSignature: options.getSignature || null, - input: forge3.util.createBuffer(), - tlsData: forge3.util.createBuffer(), - data: forge3.util.createBuffer(), - tlsDataReady: options.tlsDataReady, - dataReady: options.dataReady, - heartbeatReceived: options.heartbeatReceived, - closed: options.closed, - error: function(c2, ex) { - ex.origin = ex.origin || (c2.entity === tls.ConnectionEnd.client ? "client" : "server"); - if (ex.send) { - tls.queue(c2, tls.createAlert(c2, ex.alert)); - tls.flush(c2); - } - var fatal = ex.fatal !== false; - if (fatal) { - c2.fail = true; - } - options.error(c2, ex); - if (fatal) { - c2.close(false); - } - }, - deflate: options.deflate || null, - inflate: options.inflate || null - }; - c.reset = function(clearFail) { - c.version = { major: tls.Version.major, minor: tls.Version.minor }; - c.record = null; - c.session = null; - c.peerCertificate = null; - c.state = { - pending: null, - current: null - }; - c.expect = c.entity === tls.ConnectionEnd.client ? SHE : CHE; - c.fragmented = null; - c.records = []; - c.open = false; - c.handshakes = 0; - c.handshaking = false; - c.isConnected = false; - c.fail = !(clearFail || typeof clearFail === "undefined"); - c.input.clear(); - c.tlsData.clear(); - c.data.clear(); - c.state.current = tls.createConnectionState(c); - }; - c.reset(); - var _update = function(c2, record) { - var aligned = record.type - tls.ContentType.change_cipher_spec; - var handlers = ctTable[c2.entity][c2.expect]; - if (aligned in handlers) { - handlers[aligned](c2, record); - } else { - tls.handleUnexpected(c2, record); - } - }; - var _readRecordHeader = function(c2) { - var rval = 0; - var b = c2.input; - var len = b.length(); - if (len < 5) { - rval = 5 - len; - } else { - c2.record = { - type: b.getByte(), - version: { - major: b.getByte(), - minor: b.getByte() - }, - length: b.getInt16(), - fragment: forge3.util.createBuffer(), - ready: false - }; - var compatibleVersion = c2.record.version.major === c2.version.major; - if (compatibleVersion && c2.session && c2.session.version) { - compatibleVersion = c2.record.version.minor === c2.version.minor; - } - if (!compatibleVersion) { - c2.error(c2, { - message: "Incompatible TLS version.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.protocol_version - } - }); - } - } - return rval; - }; - var _readRecord = function(c2) { - var rval = 0; - var b = c2.input; - var len = b.length(); - if (len < c2.record.length) { - rval = c2.record.length - len; - } else { - c2.record.fragment.putBytes(b.getBytes(c2.record.length)); - b.compact(); - var s = c2.state.current.read; - if (s.update(c2, c2.record)) { - if (c2.fragmented !== null) { - if (c2.fragmented.type === c2.record.type) { - c2.fragmented.fragment.putBuffer(c2.record.fragment); - c2.record = c2.fragmented; - } else { - c2.error(c2, { - message: "Invalid fragmented record.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unexpected_message - } - }); - } - } - c2.record.ready = true; - } - } - return rval; - }; - c.handshake = function(sessionId) { - if (c.entity !== tls.ConnectionEnd.client) { - c.error(c, { - message: "Cannot initiate handshake as a server.", - fatal: false - }); - } else if (c.handshaking) { - c.error(c, { - message: "Handshake already in progress.", - fatal: false - }); - } else { - if (c.fail && !c.open && c.handshakes === 0) { - c.fail = false; - } - c.handshaking = true; - sessionId = sessionId || ""; - var session = null; - if (sessionId.length > 0) { - if (c.sessionCache) { - session = c.sessionCache.getSession(sessionId); - } - if (session === null) { - sessionId = ""; - } - } - if (sessionId.length === 0 && c.sessionCache) { - session = c.sessionCache.getSession(); - if (session !== null) { - sessionId = session.id; - } - } - c.session = { - id: sessionId, - version: null, - cipherSuite: null, - compressionMethod: null, - serverCertificate: null, - certificateRequest: null, - clientCertificate: null, - sp: {}, - md5: forge3.md.md5.create(), - sha1: forge3.md.sha1.create() - }; - if (session) { - c.version = session.version; - c.session.sp = session.sp; - } - c.session.sp.client_random = tls.createRandom().getBytes(); - c.open = true; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createClientHello(c) - })); - tls.flush(c); - } - }; - c.process = function(data) { - var rval = 0; - if (data) { - c.input.putBytes(data); - } - if (!c.fail) { - if (c.record !== null && c.record.ready && c.record.fragment.isEmpty()) { - c.record = null; - } - if (c.record === null) { - rval = _readRecordHeader(c); - } - if (!c.fail && c.record !== null && !c.record.ready) { - rval = _readRecord(c); - } - if (!c.fail && c.record !== null && c.record.ready) { - _update(c, c.record); - } - } - return rval; - }; - c.prepare = function(data) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.application_data, - data: forge3.util.createBuffer(data) - })); - return tls.flush(c); - }; - c.prepareHeartbeatRequest = function(payload, payloadLength) { - if (payload instanceof forge3.util.ByteBuffer) { - payload = payload.bytes(); - } - if (typeof payloadLength === "undefined") { - payloadLength = payload.length; - } - c.expectedHeartbeatPayload = payload; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.heartbeat, - data: tls.createHeartbeat( - tls.HeartbeatMessageType.heartbeat_request, - payload, - payloadLength - ) - })); - return tls.flush(c); - }; - c.close = function(clearFail) { - if (!c.fail && c.sessionCache && c.session) { - var session = { - id: c.session.id, - version: c.session.version, - sp: c.session.sp - }; - session.sp.keys = null; - c.sessionCache.setSession(session.id, session); - } - if (c.open) { - c.open = false; - c.input.clear(); - if (c.isConnected || c.handshaking) { - c.isConnected = c.handshaking = false; - tls.queue(c, tls.createAlert(c, { - level: tls.Alert.Level.warning, - description: tls.Alert.Description.close_notify - })); - tls.flush(c); - } - c.closed(c); - } - c.reset(clearFail); - }; - return c; - }; - module.exports = forge3.tls = forge3.tls || {}; - for (key in tls) { - if (typeof tls[key] !== "function") { - forge3.tls[key] = tls[key]; - } - } - var key; - forge3.tls.prf_tls1 = prf_TLS1; - forge3.tls.hmac_sha1 = hmac_sha1; - forge3.tls.createSessionCache = tls.createSessionCache; - forge3.tls.createConnection = tls.createConnection; - } -}); - -// node_modules/node-forge/lib/aesCipherSuites.js -var require_aesCipherSuites = __commonJS({ - "node_modules/node-forge/lib/aesCipherSuites.js"(exports, module) { - var forge3 = require_forge(); - require_aes(); - require_tls(); - var tls = module.exports = forge3.tls; - tls.CipherSuites["TLS_RSA_WITH_AES_128_CBC_SHA"] = { - id: [0, 47], - name: "TLS_RSA_WITH_AES_128_CBC_SHA", - initSecurityParameters: function(sp) { - sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; - sp.cipher_type = tls.CipherType.block; - sp.enc_key_length = 16; - sp.block_length = 16; - sp.fixed_iv_length = 16; - sp.record_iv_length = 16; - sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; - sp.mac_length = 20; - sp.mac_key_length = 20; - }, - initConnectionState - }; - tls.CipherSuites["TLS_RSA_WITH_AES_256_CBC_SHA"] = { - id: [0, 53], - name: "TLS_RSA_WITH_AES_256_CBC_SHA", - initSecurityParameters: function(sp) { - sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; - sp.cipher_type = tls.CipherType.block; - sp.enc_key_length = 32; - sp.block_length = 16; - sp.fixed_iv_length = 16; - sp.record_iv_length = 16; - sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; - sp.mac_length = 20; - sp.mac_key_length = 20; - }, - initConnectionState - }; - function initConnectionState(state, c, sp) { - var client = c.entity === forge3.tls.ConnectionEnd.client; - state.read.cipherState = { - init: false, - cipher: forge3.cipher.createDecipher("AES-CBC", client ? sp.keys.server_write_key : sp.keys.client_write_key), - iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV - }; - state.write.cipherState = { - init: false, - cipher: forge3.cipher.createCipher("AES-CBC", client ? sp.keys.client_write_key : sp.keys.server_write_key), - iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV - }; - state.read.cipherFunction = decrypt_aes_cbc_sha1; - state.write.cipherFunction = encrypt_aes_cbc_sha1; - state.read.macLength = state.write.macLength = sp.mac_length; - state.read.macFunction = state.write.macFunction = tls.hmac_sha1; - } - function encrypt_aes_cbc_sha1(record, s) { - var rval = false; - var mac = s.macFunction(s.macKey, s.sequenceNumber, record); - record.fragment.putBytes(mac); - s.updateSequenceNumber(); - var iv; - if (record.version.minor === tls.Versions.TLS_1_0.minor) { - iv = s.cipherState.init ? null : s.cipherState.iv; - } else { - iv = forge3.random.getBytesSync(16); - } - s.cipherState.init = true; - var cipher = s.cipherState.cipher; - cipher.start({ iv }); - if (record.version.minor >= tls.Versions.TLS_1_1.minor) { - cipher.output.putBytes(iv); - } - cipher.update(record.fragment); - if (cipher.finish(encrypt_aes_cbc_sha1_padding)) { - record.fragment = cipher.output; - record.length = record.fragment.length(); - rval = true; - } - return rval; - } - function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) { - if (!decrypt) { - var padding = blockSize - input.length() % blockSize; - input.fillWithByte(padding - 1, padding); - } - return true; - } - function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) { - var rval = true; - if (decrypt) { - var len = output.length(); - var paddingLength = output.last(); - for (var i = len - 1 - paddingLength; i < len - 1; ++i) { - rval = rval && output.at(i) == paddingLength; - } - if (rval) { - output.truncate(paddingLength + 1); - } - } - return rval; - } - function decrypt_aes_cbc_sha1(record, s) { - var rval = false; - var iv; - if (record.version.minor === tls.Versions.TLS_1_0.minor) { - iv = s.cipherState.init ? null : s.cipherState.iv; - } else { - iv = record.fragment.getBytes(16); - } - s.cipherState.init = true; - var cipher = s.cipherState.cipher; - cipher.start({ iv }); - cipher.update(record.fragment); - rval = cipher.finish(decrypt_aes_cbc_sha1_padding); - var macLen = s.macLength; - var mac = forge3.random.getBytesSync(macLen); - var len = cipher.output.length(); - if (len >= macLen) { - record.fragment = cipher.output.getBytes(len - macLen); - mac = cipher.output.getBytes(macLen); - } else { - record.fragment = cipher.output.getBytes(); - } - record.fragment = forge3.util.createBuffer(record.fragment); - record.length = record.fragment.length(); - var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record); - s.updateSequenceNumber(); - rval = compareMacs(s.macKey, mac, mac2) && rval; - return rval; - } - function compareMacs(key, mac1, mac2) { - var hmac = forge3.hmac.create(); - hmac.start("SHA1", key); - hmac.update(mac1); - mac1 = hmac.digest().getBytes(); - hmac.start(null, null); - hmac.update(mac2); - mac2 = hmac.digest().getBytes(); - return mac1 === mac2; - } - } -}); - -// node_modules/node-forge/lib/sha512.js -var require_sha512 = __commonJS({ - "node_modules/node-forge/lib/sha512.js"(exports, module) { - var forge3 = require_forge(); - require_md(); - require_util(); - var sha512 = module.exports = forge3.sha512 = forge3.sha512 || {}; - forge3.md.sha512 = forge3.md.algorithms.sha512 = sha512; - var sha384 = forge3.sha384 = forge3.sha512.sha384 = forge3.sha512.sha384 || {}; - sha384.create = function() { - return sha512.create("SHA-384"); - }; - forge3.md.sha384 = forge3.md.algorithms.sha384 = sha384; - forge3.sha512.sha256 = forge3.sha512.sha256 || { - create: function() { - return sha512.create("SHA-512/256"); - } - }; - forge3.md["sha512/256"] = forge3.md.algorithms["sha512/256"] = forge3.sha512.sha256; - forge3.sha512.sha224 = forge3.sha512.sha224 || { - create: function() { - return sha512.create("SHA-512/224"); - } - }; - forge3.md["sha512/224"] = forge3.md.algorithms["sha512/224"] = forge3.sha512.sha224; - sha512.create = function(algorithm) { - if (!_initialized) { - _init(); - } - if (typeof algorithm === "undefined") { - algorithm = "SHA-512"; - } - if (!(algorithm in _states)) { - throw new Error("Invalid SHA-512 algorithm: " + algorithm); - } - var _state = _states[algorithm]; - var _h = null; - var _input = forge3.util.createBuffer(); - var _w = new Array(80); - for (var wi = 0; wi < 80; ++wi) { - _w[wi] = new Array(2); - } - var digestLength = 64; - switch (algorithm) { - case "SHA-384": - digestLength = 48; - break; - case "SHA-512/256": - digestLength = 32; - break; - case "SHA-512/224": - digestLength = 28; - break; - } - var md = { - // SHA-512 => sha512 - algorithm: algorithm.replace("-", "").toLowerCase(), - blockLength: 128, - digestLength, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 16 - }; - md.start = function() { - md.messageLength = 0; - md.fullMessageLength = md.messageLength128 = []; - var int32s = md.messageLengthSize / 4; - for (var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); - } - _input = forge3.util.createBuffer(); - _h = new Array(_state.length); - for (var i = 0; i < _state.length; ++i) { - _h[i] = _state[i].slice(0); - } - return md; - }; - md.start(); - md.update = function(msg, encoding) { - if (encoding === "utf8") { - msg = forge3.util.encodeUtf8(msg); - } - var len = msg.length; - md.messageLength += len; - len = [len / 4294967296 >>> 0, len >>> 0]; - for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + (md.fullMessageLength[i] / 4294967296 >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = len[1] / 4294967296 >>> 0; - } - _input.putBytes(msg); - _update(_h, _w, _input); - if (_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - return md; - }; - md.digest = function() { - var finalBlock = forge3.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; - var overflow = remaining & md.blockLength - 1; - finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); - var next, carry; - var bits = md.fullMessageLength[0] * 8; - for (var i = 0; i < md.fullMessageLength.length - 1; ++i) { - next = md.fullMessageLength[i + 1] * 8; - carry = next / 4294967296 >>> 0; - bits += carry; - finalBlock.putInt32(bits >>> 0); - bits = next >>> 0; - } - finalBlock.putInt32(bits); - var h = new Array(_h.length); - for (var i = 0; i < _h.length; ++i) { - h[i] = _h[i].slice(0); - } - _update(h, _w, finalBlock); - var rval = forge3.util.createBuffer(); - var hlen; - if (algorithm === "SHA-512") { - hlen = h.length; - } else if (algorithm === "SHA-384") { - hlen = h.length - 2; - } else { - hlen = h.length - 4; - } - for (var i = 0; i < hlen; ++i) { - rval.putInt32(h[i][0]); - if (i !== hlen - 1 || algorithm !== "SHA-512/224") { - rval.putInt32(h[i][1]); - } - } - return rval; - }; - return md; - }; - var _padding = null; - var _initialized = false; - var _k = null; - var _states = null; - function _init() { - _padding = String.fromCharCode(128); - _padding += forge3.util.fillString(String.fromCharCode(0), 128); - _k = [ - [1116352408, 3609767458], - [1899447441, 602891725], - [3049323471, 3964484399], - [3921009573, 2173295548], - [961987163, 4081628472], - [1508970993, 3053834265], - [2453635748, 2937671579], - [2870763221, 3664609560], - [3624381080, 2734883394], - [310598401, 1164996542], - [607225278, 1323610764], - [1426881987, 3590304994], - [1925078388, 4068182383], - [2162078206, 991336113], - [2614888103, 633803317], - [3248222580, 3479774868], - [3835390401, 2666613458], - [4022224774, 944711139], - [264347078, 2341262773], - [604807628, 2007800933], - [770255983, 1495990901], - [1249150122, 1856431235], - [1555081692, 3175218132], - [1996064986, 2198950837], - [2554220882, 3999719339], - [2821834349, 766784016], - [2952996808, 2566594879], - [3210313671, 3203337956], - [3336571891, 1034457026], - [3584528711, 2466948901], - [113926993, 3758326383], - [338241895, 168717936], - [666307205, 1188179964], - [773529912, 1546045734], - [1294757372, 1522805485], - [1396182291, 2643833823], - [1695183700, 2343527390], - [1986661051, 1014477480], - [2177026350, 1206759142], - [2456956037, 344077627], - [2730485921, 1290863460], - [2820302411, 3158454273], - [3259730800, 3505952657], - [3345764771, 106217008], - [3516065817, 3606008344], - [3600352804, 1432725776], - [4094571909, 1467031594], - [275423344, 851169720], - [430227734, 3100823752], - [506948616, 1363258195], - [659060556, 3750685593], - [883997877, 3785050280], - [958139571, 3318307427], - [1322822218, 3812723403], - [1537002063, 2003034995], - [1747873779, 3602036899], - [1955562222, 1575990012], - [2024104815, 1125592928], - [2227730452, 2716904306], - [2361852424, 442776044], - [2428436474, 593698344], - [2756734187, 3733110249], - [3204031479, 2999351573], - [3329325298, 3815920427], - [3391569614, 3928383900], - [3515267271, 566280711], - [3940187606, 3454069534], - [4118630271, 4000239992], - [116418474, 1914138554], - [174292421, 2731055270], - [289380356, 3203993006], - [460393269, 320620315], - [685471733, 587496836], - [852142971, 1086792851], - [1017036298, 365543100], - [1126000580, 2618297676], - [1288033470, 3409855158], - [1501505948, 4234509866], - [1607167915, 987167468], - [1816402316, 1246189591] - ]; - _states = {}; - _states["SHA-512"] = [ - [1779033703, 4089235720], - [3144134277, 2227873595], - [1013904242, 4271175723], - [2773480762, 1595750129], - [1359893119, 2917565137], - [2600822924, 725511199], - [528734635, 4215389547], - [1541459225, 327033209] - ]; - _states["SHA-384"] = [ - [3418070365, 3238371032], - [1654270250, 914150663], - [2438529370, 812702999], - [355462360, 4144912697], - [1731405415, 4290775857], - [2394180231, 1750603025], - [3675008525, 1694076839], - [1203062813, 3204075428] - ]; - _states["SHA-512/256"] = [ - [573645204, 4230739756], - [2673172387, 3360449730], - [596883563, 1867755857], - [2520282905, 1497426621], - [2519219938, 2827943907], - [3193839141, 1401305490], - [721525244, 746961066], - [246885852, 2177182882] - ]; - _states["SHA-512/224"] = [ - [2352822216, 424955298], - [1944164710, 2312950998], - [502970286, 855612546], - [1738396948, 1479516111], - [258812777, 2077511080], - [2011393907, 79989058], - [1067287976, 1780299464], - [286451373, 2446758561] - ]; - _initialized = true; - } - function _update(s, w, bytes) { - var t1_hi, t1_lo; - var t2_hi, t2_lo; - var s0_hi, s0_lo; - var s1_hi, s1_lo; - var ch_hi, ch_lo; - var maj_hi, maj_lo; - var a_hi, a_lo; - var b_hi, b_lo; - var c_hi, c_lo; - var d_hi, d_lo; - var e_hi, e_lo; - var f_hi, f_lo; - var g_hi, g_lo; - var h_hi, h_lo; - var i, hi, lo, w2, w7, w15, w16; - var len = bytes.length(); - while (len >= 128) { - for (i = 0; i < 16; ++i) { - w[i][0] = bytes.getInt32() >>> 0; - w[i][1] = bytes.getInt32() >>> 0; - } - for (; i < 80; ++i) { - w2 = w[i - 2]; - hi = w2[0]; - lo = w2[1]; - t1_hi = ((hi >>> 19 | lo << 13) ^ // ROTR 19 - (lo >>> 29 | hi << 3) ^ // ROTR 61/(swap + ROTR 29) - hi >>> 6) >>> 0; - t1_lo = ((hi << 13 | lo >>> 19) ^ // ROTR 19 - (lo << 3 | hi >>> 29) ^ // ROTR 61/(swap + ROTR 29) - (hi << 26 | lo >>> 6)) >>> 0; - w15 = w[i - 15]; - hi = w15[0]; - lo = w15[1]; - t2_hi = ((hi >>> 1 | lo << 31) ^ // ROTR 1 - (hi >>> 8 | lo << 24) ^ // ROTR 8 - hi >>> 7) >>> 0; - t2_lo = ((hi << 31 | lo >>> 1) ^ // ROTR 1 - (hi << 24 | lo >>> 8) ^ // ROTR 8 - (hi << 25 | lo >>> 7)) >>> 0; - w7 = w[i - 7]; - w16 = w[i - 16]; - lo = t1_lo + w7[1] + t2_lo + w16[1]; - w[i][0] = t1_hi + w7[0] + t2_hi + w16[0] + (lo / 4294967296 >>> 0) >>> 0; - w[i][1] = lo >>> 0; - } - a_hi = s[0][0]; - a_lo = s[0][1]; - b_hi = s[1][0]; - b_lo = s[1][1]; - c_hi = s[2][0]; - c_lo = s[2][1]; - d_hi = s[3][0]; - d_lo = s[3][1]; - e_hi = s[4][0]; - e_lo = s[4][1]; - f_hi = s[5][0]; - f_lo = s[5][1]; - g_hi = s[6][0]; - g_lo = s[6][1]; - h_hi = s[7][0]; - h_lo = s[7][1]; - for (i = 0; i < 80; ++i) { - s1_hi = ((e_hi >>> 14 | e_lo << 18) ^ // ROTR 14 - (e_hi >>> 18 | e_lo << 14) ^ // ROTR 18 - (e_lo >>> 9 | e_hi << 23)) >>> 0; - s1_lo = ((e_hi << 18 | e_lo >>> 14) ^ // ROTR 14 - (e_hi << 14 | e_lo >>> 18) ^ // ROTR 18 - (e_lo << 23 | e_hi >>> 9)) >>> 0; - ch_hi = (g_hi ^ e_hi & (f_hi ^ g_hi)) >>> 0; - ch_lo = (g_lo ^ e_lo & (f_lo ^ g_lo)) >>> 0; - s0_hi = ((a_hi >>> 28 | a_lo << 4) ^ // ROTR 28 - (a_lo >>> 2 | a_hi << 30) ^ // ROTR 34/(swap + ROTR 2) - (a_lo >>> 7 | a_hi << 25)) >>> 0; - s0_lo = ((a_hi << 4 | a_lo >>> 28) ^ // ROTR 28 - (a_lo << 30 | a_hi >>> 2) ^ // ROTR 34/(swap + ROTR 2) - (a_lo << 25 | a_hi >>> 7)) >>> 0; - maj_hi = (a_hi & b_hi | c_hi & (a_hi ^ b_hi)) >>> 0; - maj_lo = (a_lo & b_lo | c_lo & (a_lo ^ b_lo)) >>> 0; - lo = h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]; - t1_hi = h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] + (lo / 4294967296 >>> 0) >>> 0; - t1_lo = lo >>> 0; - lo = s0_lo + maj_lo; - t2_hi = s0_hi + maj_hi + (lo / 4294967296 >>> 0) >>> 0; - t2_lo = lo >>> 0; - h_hi = g_hi; - h_lo = g_lo; - g_hi = f_hi; - g_lo = f_lo; - f_hi = e_hi; - f_lo = e_lo; - lo = d_lo + t1_lo; - e_hi = d_hi + t1_hi + (lo / 4294967296 >>> 0) >>> 0; - e_lo = lo >>> 0; - d_hi = c_hi; - d_lo = c_lo; - c_hi = b_hi; - c_lo = b_lo; - b_hi = a_hi; - b_lo = a_lo; - lo = t1_lo + t2_lo; - a_hi = t1_hi + t2_hi + (lo / 4294967296 >>> 0) >>> 0; - a_lo = lo >>> 0; - } - lo = s[0][1] + a_lo; - s[0][0] = s[0][0] + a_hi + (lo / 4294967296 >>> 0) >>> 0; - s[0][1] = lo >>> 0; - lo = s[1][1] + b_lo; - s[1][0] = s[1][0] + b_hi + (lo / 4294967296 >>> 0) >>> 0; - s[1][1] = lo >>> 0; - lo = s[2][1] + c_lo; - s[2][0] = s[2][0] + c_hi + (lo / 4294967296 >>> 0) >>> 0; - s[2][1] = lo >>> 0; - lo = s[3][1] + d_lo; - s[3][0] = s[3][0] + d_hi + (lo / 4294967296 >>> 0) >>> 0; - s[3][1] = lo >>> 0; - lo = s[4][1] + e_lo; - s[4][0] = s[4][0] + e_hi + (lo / 4294967296 >>> 0) >>> 0; - s[4][1] = lo >>> 0; - lo = s[5][1] + f_lo; - s[5][0] = s[5][0] + f_hi + (lo / 4294967296 >>> 0) >>> 0; - s[5][1] = lo >>> 0; - lo = s[6][1] + g_lo; - s[6][0] = s[6][0] + g_hi + (lo / 4294967296 >>> 0) >>> 0; - s[6][1] = lo >>> 0; - lo = s[7][1] + h_lo; - s[7][0] = s[7][0] + h_hi + (lo / 4294967296 >>> 0) >>> 0; - s[7][1] = lo >>> 0; - len -= 128; - } - } - } -}); - -// node_modules/node-forge/lib/asn1-validator.js -var require_asn1_validator = __commonJS({ - "node_modules/node-forge/lib/asn1-validator.js"(exports) { - var forge3 = require_forge(); - require_asn1(); - var asn1 = forge3.asn1; - exports.privateKeyValidator = { - // PrivateKeyInfo - name: "PrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: "PrivateKeyInfo.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyVersion" - }, { - // privateKeyAlgorithm - name: "PrivateKeyInfo.privateKeyAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "privateKeyOid" - }] - }, { - // PrivateKey - name: "PrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "privateKey" - }] - }; - exports.publicKeyValidator = { - name: "SubjectPublicKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "subjectPublicKeyInfo", - value: [ - { - name: "SubjectPublicKeyInfo.AlgorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "publicKeyOid" - }] - }, - // capture group for ed25519PublicKey - { - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - composed: true, - captureBitStringValue: "ed25519PublicKey" - } - // FIXME: this is capture group for rsaPublicKey, use it in this API or - // discard? - /* { - // subjectPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - value: [{ - // RSAPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: 'rsaPublicKey' - }] - } */ - ] - }; - } -}); - -// node_modules/node-forge/lib/ed25519.js -var require_ed25519 = __commonJS({ - "node_modules/node-forge/lib/ed25519.js"(exports, module) { - var forge3 = require_forge(); - require_jsbn(); - require_random(); - require_sha512(); - require_util(); - var asn1Validator = require_asn1_validator(); - var publicKeyValidator = asn1Validator.publicKeyValidator; - var privateKeyValidator = asn1Validator.privateKeyValidator; - if (typeof BigInteger2 === "undefined") { - BigInteger2 = forge3.jsbn.BigInteger; - } - var BigInteger2; - var ByteBuffer = forge3.util.ByteBuffer; - var NativeBuffer = typeof Buffer === "undefined" ? Uint8Array : Buffer; - forge3.pki = forge3.pki || {}; - module.exports = forge3.pki.ed25519 = forge3.ed25519 = forge3.ed25519 || {}; - var ed25519 = forge3.ed25519; - ed25519.constants = {}; - ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32; - ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64; - ed25519.constants.SEED_BYTE_LENGTH = 32; - ed25519.constants.SIGN_BYTE_LENGTH = 64; - ed25519.constants.HASH_BYTE_LENGTH = 64; - ed25519.generateKeyPair = function(options) { - options = options || {}; - var seed = options.seed; - if (seed === void 0) { - seed = forge3.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH); - } else if (typeof seed === "string") { - if (seed.length !== ed25519.constants.SEED_BYTE_LENGTH) { - throw new TypeError( - '"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH + " bytes in length." - ); - } - } else if (!(seed instanceof Uint8Array)) { - throw new TypeError( - '"seed" must be a node.js Buffer, Uint8Array, or a binary string.' - ); - } - seed = messageToNativeBuffer({ message: seed, encoding: "binary" }); - var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); - var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); - for (var i = 0; i < 32; ++i) { - sk[i] = seed[i]; - } - crypto_sign_keypair(pk, sk); - return { publicKey: pk, privateKey: sk }; - }; - ed25519.privateKeyFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - var valid = forge3.asn1.validate(obj, privateKeyValidator, capture, errors); - if (!valid) { - var error = new Error("Invalid Key."); - error.errors = errors; - throw error; - } - var oid = forge3.asn1.derToOid(capture.privateKeyOid); - var ed25519Oid = forge3.oids.EdDSA25519; - if (oid !== ed25519Oid) { - throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".'); - } - var privateKey = capture.privateKey; - var privateKeyBytes = messageToNativeBuffer({ - message: forge3.asn1.fromDer(privateKey).value, - encoding: "binary" - }); - return { privateKeyBytes }; - }; - ed25519.publicKeyFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - var valid = forge3.asn1.validate(obj, publicKeyValidator, capture, errors); - if (!valid) { - var error = new Error("Invalid Key."); - error.errors = errors; - throw error; - } - var oid = forge3.asn1.derToOid(capture.publicKeyOid); - var ed25519Oid = forge3.oids.EdDSA25519; - if (oid !== ed25519Oid) { - throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".'); - } - var publicKeyBytes = capture.ed25519PublicKey; - if (publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { - throw new Error("Key length is invalid."); - } - return messageToNativeBuffer({ - message: publicKeyBytes, - encoding: "binary" - }); - }; - ed25519.publicKeyFromPrivateKey = function(options) { - options = options || {}; - var privateKey = messageToNativeBuffer({ - message: options.privateKey, - encoding: "binary" - }); - if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.privateKey" must have a byte length of ' + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH - ); - } - var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); - for (var i = 0; i < pk.length; ++i) { - pk[i] = privateKey[32 + i]; - } - return pk; - }; - ed25519.sign = function(options) { - options = options || {}; - var msg = messageToNativeBuffer(options); - var privateKey = messageToNativeBuffer({ - message: options.privateKey, - encoding: "binary" - }); - if (privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) { - var keyPair = ed25519.generateKeyPair({ seed: privateKey }); - privateKey = keyPair.privateKey; - } else if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.privateKey" must have a byte length of ' + ed25519.constants.SEED_BYTE_LENGTH + " or " + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH - ); - } - var signedMsg = new NativeBuffer( - ed25519.constants.SIGN_BYTE_LENGTH + msg.length - ); - crypto_sign(signedMsg, msg, msg.length, privateKey); - var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH); - for (var i = 0; i < sig.length; ++i) { - sig[i] = signedMsg[i]; - } - return sig; - }; - ed25519.verify = function(options) { - options = options || {}; - var msg = messageToNativeBuffer(options); - if (options.signature === void 0) { - throw new TypeError( - '"options.signature" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a binary string.' - ); - } - var sig = messageToNativeBuffer({ - message: options.signature, - encoding: "binary" - }); - if (sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) { - throw new TypeError( - '"options.signature" must have a byte length of ' + ed25519.constants.SIGN_BYTE_LENGTH - ); - } - var publicKey = messageToNativeBuffer({ - message: options.publicKey, - encoding: "binary" - }); - if (publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.publicKey" must have a byte length of ' + ed25519.constants.PUBLIC_KEY_BYTE_LENGTH - ); - } - var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); - var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); - var i; - for (i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) { - sm[i] = sig[i]; - } - for (i = 0; i < msg.length; ++i) { - sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i]; - } - return crypto_sign_open(m, sm, sm.length, publicKey) >= 0; - }; - function messageToNativeBuffer(options) { - var message = options.message; - if (message instanceof Uint8Array || message instanceof NativeBuffer) { - return message; - } - var encoding = options.encoding; - if (message === void 0) { - if (options.md) { - message = options.md.digest().getBytes(); - encoding = "binary"; - } else { - throw new TypeError('"options.message" or "options.md" not specified.'); - } - } - if (typeof message === "string" && !encoding) { - throw new TypeError('"options.encoding" must be "binary" or "utf8".'); - } - if (typeof message === "string") { - if (typeof Buffer !== "undefined") { - return Buffer.from(message, encoding); - } - message = new ByteBuffer(message, encoding); - } else if (!(message instanceof ByteBuffer)) { - throw new TypeError( - '"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.' - ); - } - var buffer = new NativeBuffer(message.length()); - for (var i = 0; i < buffer.length; ++i) { - buffer[i] = message.at(i); - } - return buffer; - } - var gf0 = gf(); - var gf1 = gf([1]); - var D = gf([ - 30883, - 4953, - 19914, - 30187, - 55467, - 16705, - 2637, - 112, - 59544, - 30585, - 16505, - 36039, - 65139, - 11119, - 27886, - 20995 - ]); - var D2 = gf([ - 61785, - 9906, - 39828, - 60374, - 45398, - 33411, - 5274, - 224, - 53552, - 61171, - 33010, - 6542, - 64743, - 22239, - 55772, - 9222 - ]); - var X = gf([ - 54554, - 36645, - 11616, - 51542, - 42930, - 38181, - 51040, - 26924, - 56412, - 64982, - 57905, - 49316, - 21502, - 52590, - 14035, - 8553 - ]); - var Y = gf([ - 26200, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214 - ]); - var L = new Float64Array([ - 237, - 211, - 245, - 92, - 26, - 99, - 18, - 88, - 214, - 156, - 247, - 162, - 222, - 249, - 222, - 20, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 16 - ]); - var I = gf([ - 41136, - 18958, - 6951, - 50414, - 58488, - 44335, - 6150, - 12099, - 55207, - 15867, - 153, - 11085, - 57099, - 20417, - 9344, - 11139 - ]); - function sha512(msg, msgLen) { - var md = forge3.md.sha512.create(); - var buffer = new ByteBuffer(msg); - md.update(buffer.getBytes(msgLen), "binary"); - var hash = md.digest().getBytes(); - if (typeof Buffer !== "undefined") { - return Buffer.from(hash, "binary"); - } - var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH); - for (var i = 0; i < 64; ++i) { - out[i] = hash.charCodeAt(i); - } - return out; - } - function crypto_sign_keypair(pk, sk) { - var p = [gf(), gf(), gf(), gf()]; - var i; - var d = sha512(sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - scalarbase(p, d); - pack(pk, p); - for (i = 0; i < 32; ++i) { - sk[i + 32] = pk[i]; - } - return 0; - } - function crypto_sign(sm, m, n, sk) { - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; - var d = sha512(sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - var smlen = n + 64; - for (i = 0; i < n; ++i) { - sm[64 + i] = m[i]; - } - for (i = 0; i < 32; ++i) { - sm[32 + i] = d[32 + i]; - } - var r = sha512(sm.subarray(32), n + 32); - reduce(r); - scalarbase(p, r); - pack(sm, p); - for (i = 32; i < 64; ++i) { - sm[i] = sk[i]; - } - var h = sha512(sm, n + 64); - reduce(h); - for (i = 32; i < 64; ++i) { - x[i] = 0; - } - for (i = 0; i < 32; ++i) { - x[i] = r[i]; - } - for (i = 0; i < 32; ++i) { - for (j = 0; j < 32; j++) { - x[i + j] += h[i] * d[j]; - } - } - modL(sm.subarray(32), x); - return smlen; - } - function crypto_sign_open(m, sm, n, pk) { - var i, mlen; - var t = new NativeBuffer(32); - var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; - mlen = -1; - if (n < 64) { - return -1; - } - if (unpackneg(q, pk)) { - return -1; - } - for (i = 0; i < n; ++i) { - m[i] = sm[i]; - } - for (i = 0; i < 32; ++i) { - m[i + 32] = pk[i]; - } - var h = sha512(m, n); - reduce(h); - scalarmult(p, q, h); - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; ++i) { - m[i] = 0; - } - return -1; - } - for (i = 0; i < n; ++i) { - m[i] = sm[i + 64]; - } - mlen = n; - return mlen; - } - function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = x[j] + 128 >> 8; - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; ++j) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; ++j) { - x[j] -= carry * L[j]; - } - for (i = 0; i < 32; ++i) { - x[i + 1] += x[i] >> 8; - r[i] = x[i] & 255; - } - } - function reduce(r) { - var x = new Float64Array(64); - for (var i = 0; i < 64; ++i) { - x[i] = r[i]; - r[i] = 0; - } - modL(r, x); - } - function add(p, q) { - var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf(); - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); - } - function cswap(p, q, b) { - for (var i = 0; i < 4; ++i) { - sel25519(p[i], q[i], b); - } - } - function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; - } - function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; ++i) { - t[i] = n[i]; - } - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; ++j) { - m[0] = t[0] - 65517; - for (i = 1; i < 15; ++i) { - m[i] = t[i] - 65535 - (m[i - 1] >> 16 & 1); - m[i - 1] &= 65535; - } - m[15] = t[15] - 32767 - (m[14] >> 16 & 1); - b = m[15] >> 16 & 1; - m[14] &= 65535; - sel25519(t, m, 1 - b); - } - for (i = 0; i < 16; i++) { - o[2 * i] = t[i] & 255; - o[2 * i + 1] = t[i] >> 8; - } - } - function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) { - M(r[0], r[0], I); - } - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) { - return -1; - } - if (par25519(r[0]) === p[31] >> 7) { - Z(r[0], gf0, r[0]); - } - M(r[3], r[0], r[1]); - return 0; - } - function unpack25519(o, n) { - var i; - for (i = 0; i < 16; ++i) { - o[i] = n[2 * i] + (n[2 * i + 1] << 8); - } - o[15] &= 32767; - } - function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; ++a) { - c[a] = i[a]; - } - for (a = 250; a >= 0; --a) { - S(c, c); - if (a !== 1) { - M(c, c, i); - } - } - for (a = 0; a < 16; ++a) { - o[a] = c[a]; - } - } - function neq25519(a, b) { - var c = new NativeBuffer(32); - var d = new NativeBuffer(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); - } - function crypto_verify_32(x, xi, y, yi) { - return vn(x, xi, y, yi, 32); - } - function vn(x, xi, y, yi, n) { - var i, d = 0; - for (i = 0; i < n; ++i) { - d |= x[xi + i] ^ y[yi + i]; - } - return (1 & d - 1 >>> 8) - 1; - } - function par25519(a) { - var d = new NativeBuffer(32); - pack25519(d, a); - return d[0] & 1; - } - function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = s[i / 8 | 0] >> (i & 7) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); - } - } - function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); - } - function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) { - r[i] = a[i] | 0; - } - } - function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; ++a) { - c[a] = i[a]; - } - for (a = 253; a >= 0; --a) { - S(c, c); - if (a !== 2 && a !== 4) { - M(c, c, i); - } - } - for (a = 0; a < 16; ++a) { - o[a] = c[a]; - } - } - function car25519(o) { - var i, v, c = 1; - for (i = 0; i < 16; ++i) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; - } - o[0] += c - 1 + 37 * (c - 1); - } - function sel25519(p, q, b) { - var t, c = ~(b - 1); - for (var i = 0; i < 16; ++i) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } - } - function gf(init) { - var i, r = new Float64Array(16); - if (init) { - for (i = 0; i < init.length; ++i) { - r[i] = init[i]; - } - } - return r; - } - function A(o, a, b) { - for (var i = 0; i < 16; ++i) { - o[i] = a[i] + b[i]; - } - } - function Z(o, a, b) { - for (var i = 0; i < 16; ++i) { - o[i] = a[i] - b[i]; - } - } - function S(o, a) { - M(o, a, a); - } - function M(o, a, b) { - var v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15]; - v = a[0]; - t0 += v * b0; - t1 += v * b1; - t2 += v * b2; - t3 += v * b3; - t4 += v * b4; - t5 += v * b5; - t6 += v * b6; - t7 += v * b7; - t8 += v * b8; - t9 += v * b9; - t10 += v * b10; - t11 += v * b11; - t12 += v * b12; - t13 += v * b13; - t14 += v * b14; - t15 += v * b15; - v = a[1]; - t1 += v * b0; - t2 += v * b1; - t3 += v * b2; - t4 += v * b3; - t5 += v * b4; - t6 += v * b5; - t7 += v * b6; - t8 += v * b7; - t9 += v * b8; - t10 += v * b9; - t11 += v * b10; - t12 += v * b11; - t13 += v * b12; - t14 += v * b13; - t15 += v * b14; - t16 += v * b15; - v = a[2]; - t2 += v * b0; - t3 += v * b1; - t4 += v * b2; - t5 += v * b3; - t6 += v * b4; - t7 += v * b5; - t8 += v * b6; - t9 += v * b7; - t10 += v * b8; - t11 += v * b9; - t12 += v * b10; - t13 += v * b11; - t14 += v * b12; - t15 += v * b13; - t16 += v * b14; - t17 += v * b15; - v = a[3]; - t3 += v * b0; - t4 += v * b1; - t5 += v * b2; - t6 += v * b3; - t7 += v * b4; - t8 += v * b5; - t9 += v * b6; - t10 += v * b7; - t11 += v * b8; - t12 += v * b9; - t13 += v * b10; - t14 += v * b11; - t15 += v * b12; - t16 += v * b13; - t17 += v * b14; - t18 += v * b15; - v = a[4]; - t4 += v * b0; - t5 += v * b1; - t6 += v * b2; - t7 += v * b3; - t8 += v * b4; - t9 += v * b5; - t10 += v * b6; - t11 += v * b7; - t12 += v * b8; - t13 += v * b9; - t14 += v * b10; - t15 += v * b11; - t16 += v * b12; - t17 += v * b13; - t18 += v * b14; - t19 += v * b15; - v = a[5]; - t5 += v * b0; - t6 += v * b1; - t7 += v * b2; - t8 += v * b3; - t9 += v * b4; - t10 += v * b5; - t11 += v * b6; - t12 += v * b7; - t13 += v * b8; - t14 += v * b9; - t15 += v * b10; - t16 += v * b11; - t17 += v * b12; - t18 += v * b13; - t19 += v * b14; - t20 += v * b15; - v = a[6]; - t6 += v * b0; - t7 += v * b1; - t8 += v * b2; - t9 += v * b3; - t10 += v * b4; - t11 += v * b5; - t12 += v * b6; - t13 += v * b7; - t14 += v * b8; - t15 += v * b9; - t16 += v * b10; - t17 += v * b11; - t18 += v * b12; - t19 += v * b13; - t20 += v * b14; - t21 += v * b15; - v = a[7]; - t7 += v * b0; - t8 += v * b1; - t9 += v * b2; - t10 += v * b3; - t11 += v * b4; - t12 += v * b5; - t13 += v * b6; - t14 += v * b7; - t15 += v * b8; - t16 += v * b9; - t17 += v * b10; - t18 += v * b11; - t19 += v * b12; - t20 += v * b13; - t21 += v * b14; - t22 += v * b15; - v = a[8]; - t8 += v * b0; - t9 += v * b1; - t10 += v * b2; - t11 += v * b3; - t12 += v * b4; - t13 += v * b5; - t14 += v * b6; - t15 += v * b7; - t16 += v * b8; - t17 += v * b9; - t18 += v * b10; - t19 += v * b11; - t20 += v * b12; - t21 += v * b13; - t22 += v * b14; - t23 += v * b15; - v = a[9]; - t9 += v * b0; - t10 += v * b1; - t11 += v * b2; - t12 += v * b3; - t13 += v * b4; - t14 += v * b5; - t15 += v * b6; - t16 += v * b7; - t17 += v * b8; - t18 += v * b9; - t19 += v * b10; - t20 += v * b11; - t21 += v * b12; - t22 += v * b13; - t23 += v * b14; - t24 += v * b15; - v = a[10]; - t10 += v * b0; - t11 += v * b1; - t12 += v * b2; - t13 += v * b3; - t14 += v * b4; - t15 += v * b5; - t16 += v * b6; - t17 += v * b7; - t18 += v * b8; - t19 += v * b9; - t20 += v * b10; - t21 += v * b11; - t22 += v * b12; - t23 += v * b13; - t24 += v * b14; - t25 += v * b15; - v = a[11]; - t11 += v * b0; - t12 += v * b1; - t13 += v * b2; - t14 += v * b3; - t15 += v * b4; - t16 += v * b5; - t17 += v * b6; - t18 += v * b7; - t19 += v * b8; - t20 += v * b9; - t21 += v * b10; - t22 += v * b11; - t23 += v * b12; - t24 += v * b13; - t25 += v * b14; - t26 += v * b15; - v = a[12]; - t12 += v * b0; - t13 += v * b1; - t14 += v * b2; - t15 += v * b3; - t16 += v * b4; - t17 += v * b5; - t18 += v * b6; - t19 += v * b7; - t20 += v * b8; - t21 += v * b9; - t22 += v * b10; - t23 += v * b11; - t24 += v * b12; - t25 += v * b13; - t26 += v * b14; - t27 += v * b15; - v = a[13]; - t13 += v * b0; - t14 += v * b1; - t15 += v * b2; - t16 += v * b3; - t17 += v * b4; - t18 += v * b5; - t19 += v * b6; - t20 += v * b7; - t21 += v * b8; - t22 += v * b9; - t23 += v * b10; - t24 += v * b11; - t25 += v * b12; - t26 += v * b13; - t27 += v * b14; - t28 += v * b15; - v = a[14]; - t14 += v * b0; - t15 += v * b1; - t16 += v * b2; - t17 += v * b3; - t18 += v * b4; - t19 += v * b5; - t20 += v * b6; - t21 += v * b7; - t22 += v * b8; - t23 += v * b9; - t24 += v * b10; - t25 += v * b11; - t26 += v * b12; - t27 += v * b13; - t28 += v * b14; - t29 += v * b15; - v = a[15]; - t15 += v * b0; - t16 += v * b1; - t17 += v * b2; - t18 += v * b3; - t19 += v * b4; - t20 += v * b5; - t21 += v * b6; - t22 += v * b7; - t23 += v * b8; - t24 += v * b9; - t25 += v * b10; - t26 += v * b11; - t27 += v * b12; - t28 += v * b13; - t29 += v * b14; - t30 += v * b15; - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - c = 1; - v = t0 + c + 65535; - c = Math.floor(v / 65536); - t0 = v - c * 65536; - v = t1 + c + 65535; - c = Math.floor(v / 65536); - t1 = v - c * 65536; - v = t2 + c + 65535; - c = Math.floor(v / 65536); - t2 = v - c * 65536; - v = t3 + c + 65535; - c = Math.floor(v / 65536); - t3 = v - c * 65536; - v = t4 + c + 65535; - c = Math.floor(v / 65536); - t4 = v - c * 65536; - v = t5 + c + 65535; - c = Math.floor(v / 65536); - t5 = v - c * 65536; - v = t6 + c + 65535; - c = Math.floor(v / 65536); - t6 = v - c * 65536; - v = t7 + c + 65535; - c = Math.floor(v / 65536); - t7 = v - c * 65536; - v = t8 + c + 65535; - c = Math.floor(v / 65536); - t8 = v - c * 65536; - v = t9 + c + 65535; - c = Math.floor(v / 65536); - t9 = v - c * 65536; - v = t10 + c + 65535; - c = Math.floor(v / 65536); - t10 = v - c * 65536; - v = t11 + c + 65535; - c = Math.floor(v / 65536); - t11 = v - c * 65536; - v = t12 + c + 65535; - c = Math.floor(v / 65536); - t12 = v - c * 65536; - v = t13 + c + 65535; - c = Math.floor(v / 65536); - t13 = v - c * 65536; - v = t14 + c + 65535; - c = Math.floor(v / 65536); - t14 = v - c * 65536; - v = t15 + c + 65535; - c = Math.floor(v / 65536); - t15 = v - c * 65536; - t0 += c - 1 + 37 * (c - 1); - c = 1; - v = t0 + c + 65535; - c = Math.floor(v / 65536); - t0 = v - c * 65536; - v = t1 + c + 65535; - c = Math.floor(v / 65536); - t1 = v - c * 65536; - v = t2 + c + 65535; - c = Math.floor(v / 65536); - t2 = v - c * 65536; - v = t3 + c + 65535; - c = Math.floor(v / 65536); - t3 = v - c * 65536; - v = t4 + c + 65535; - c = Math.floor(v / 65536); - t4 = v - c * 65536; - v = t5 + c + 65535; - c = Math.floor(v / 65536); - t5 = v - c * 65536; - v = t6 + c + 65535; - c = Math.floor(v / 65536); - t6 = v - c * 65536; - v = t7 + c + 65535; - c = Math.floor(v / 65536); - t7 = v - c * 65536; - v = t8 + c + 65535; - c = Math.floor(v / 65536); - t8 = v - c * 65536; - v = t9 + c + 65535; - c = Math.floor(v / 65536); - t9 = v - c * 65536; - v = t10 + c + 65535; - c = Math.floor(v / 65536); - t10 = v - c * 65536; - v = t11 + c + 65535; - c = Math.floor(v / 65536); - t11 = v - c * 65536; - v = t12 + c + 65535; - c = Math.floor(v / 65536); - t12 = v - c * 65536; - v = t13 + c + 65535; - c = Math.floor(v / 65536); - t13 = v - c * 65536; - v = t14 + c + 65535; - c = Math.floor(v / 65536); - t14 = v - c * 65536; - v = t15 + c + 65535; - c = Math.floor(v / 65536); - t15 = v - c * 65536; - t0 += c - 1 + 37 * (c - 1); - o[0] = t0; - o[1] = t1; - o[2] = t2; - o[3] = t3; - o[4] = t4; - o[5] = t5; - o[6] = t6; - o[7] = t7; - o[8] = t8; - o[9] = t9; - o[10] = t10; - o[11] = t11; - o[12] = t12; - o[13] = t13; - o[14] = t14; - o[15] = t15; - } - } -}); - -// node_modules/node-forge/lib/kem.js -var require_kem = __commonJS({ - "node_modules/node-forge/lib/kem.js"(exports, module) { - var forge3 = require_forge(); - require_util(); - require_random(); - require_jsbn(); - module.exports = forge3.kem = forge3.kem || {}; - var BigInteger2 = forge3.jsbn.BigInteger; - forge3.kem.rsa = {}; - forge3.kem.rsa.create = function(kdf, options) { - options = options || {}; - var prng = options.prng || forge3.random; - var kem = {}; - kem.encrypt = function(publicKey, keyLength) { - var byteLength = Math.ceil(publicKey.n.bitLength() / 8); - var r; - do { - r = new BigInteger2( - forge3.util.bytesToHex(prng.getBytesSync(byteLength)), - 16 - ).mod(publicKey.n); - } while (r.compareTo(BigInteger2.ONE) <= 0); - r = forge3.util.hexToBytes(r.toString(16)); - var zeros = byteLength - r.length; - if (zeros > 0) { - r = forge3.util.fillString(String.fromCharCode(0), zeros) + r; - } - var encapsulation = publicKey.encrypt(r, "NONE"); - var key = kdf.generate(r, keyLength); - return { encapsulation, key }; - }; - kem.decrypt = function(privateKey, encapsulation, keyLength) { - var r = privateKey.decrypt(encapsulation, "NONE"); - return kdf.generate(r, keyLength); - }; - return kem; - }; - forge3.kem.kdf1 = function(md, digestLength) { - _createKDF(this, md, 0, digestLength || md.digestLength); - }; - forge3.kem.kdf2 = function(md, digestLength) { - _createKDF(this, md, 1, digestLength || md.digestLength); - }; - function _createKDF(kdf, md, counterStart, digestLength) { - kdf.generate = function(x, length) { - var key = new forge3.util.ByteBuffer(); - var k = Math.ceil(length / digestLength) + counterStart; - var c = new forge3.util.ByteBuffer(); - for (var i = counterStart; i < k; ++i) { - c.putInt32(i); - md.start(); - md.update(x + c.getBytes()); - var hash = md.digest(); - key.putBytes(hash.getBytes(digestLength)); - } - key.truncate(key.length() - length); - return key.getBytes(); - }; - } - } -}); - -// node_modules/node-forge/lib/log.js -var require_log = __commonJS({ - "node_modules/node-forge/lib/log.js"(exports, module) { - var forge3 = require_forge(); - require_util(); - module.exports = forge3.log = forge3.log || {}; - forge3.log.levels = [ - "none", - "error", - "warning", - "info", - "debug", - "verbose", - "max" - ]; - var sLevelInfo = {}; - var sLoggers = []; - var sConsoleLogger = null; - forge3.log.LEVEL_LOCKED = 1 << 1; - forge3.log.NO_LEVEL_CHECK = 1 << 2; - forge3.log.INTERPOLATE = 1 << 3; - for (i = 0; i < forge3.log.levels.length; ++i) { - level = forge3.log.levels[i]; - sLevelInfo[level] = { - index: i, - name: level.toUpperCase() - }; - } - var level; - var i; - forge3.log.logMessage = function(message) { - var messageLevelIndex = sLevelInfo[message.level].index; - for (var i2 = 0; i2 < sLoggers.length; ++i2) { - var logger2 = sLoggers[i2]; - if (logger2.flags & forge3.log.NO_LEVEL_CHECK) { - logger2.f(message); - } else { - var loggerLevelIndex = sLevelInfo[logger2.level].index; - if (messageLevelIndex <= loggerLevelIndex) { - logger2.f(logger2, message); - } - } - } - }; - forge3.log.prepareStandard = function(message) { - if (!("standard" in message)) { - message.standard = sLevelInfo[message.level].name + //' ' + +message.timestamp + - " [" + message.category + "] " + message.message; - } - }; - forge3.log.prepareFull = function(message) { - if (!("full" in message)) { - var args = [message.message]; - args = args.concat([]); - message.full = forge3.util.format.apply(this, args); - } - }; - forge3.log.prepareStandardFull = function(message) { - if (!("standardFull" in message)) { - forge3.log.prepareStandard(message); - message.standardFull = message.standard; - } - }; - if (true) { - levels = ["error", "warning", "info", "debug", "verbose"]; - for (i = 0; i < levels.length; ++i) { - (function(level2) { - forge3.log[level2] = function(category, message) { - var args = Array.prototype.slice.call(arguments).slice(2); - var msg = { - timestamp: /* @__PURE__ */ new Date(), - level: level2, - category, - message, - "arguments": args - /*standard*/ - /*full*/ - /*fullMessage*/ - }; - forge3.log.logMessage(msg); - }; - })(levels[i]); - } - } - var levels; - var i; - forge3.log.makeLogger = function(logFunction) { - var logger2 = { - flags: 0, - f: logFunction - }; - forge3.log.setLevel(logger2, "none"); - return logger2; - }; - forge3.log.setLevel = function(logger2, level2) { - var rval = false; - if (logger2 && !(logger2.flags & forge3.log.LEVEL_LOCKED)) { - for (var i2 = 0; i2 < forge3.log.levels.length; ++i2) { - var aValidLevel = forge3.log.levels[i2]; - if (level2 == aValidLevel) { - logger2.level = level2; - rval = true; - break; - } - } - } - return rval; - }; - forge3.log.lock = function(logger2, lock2) { - if (typeof lock2 === "undefined" || lock2) { - logger2.flags |= forge3.log.LEVEL_LOCKED; - } else { - logger2.flags &= ~forge3.log.LEVEL_LOCKED; - } - }; - forge3.log.addLogger = function(logger2) { - sLoggers.push(logger2); - }; - if (typeof console !== "undefined" && "log" in console) { - if (console.error && console.warn && console.info && console.debug) { - levelHandlers = { - error: console.error, - warning: console.warn, - info: console.info, - debug: console.debug, - verbose: console.debug - }; - f = function(logger2, message) { - forge3.log.prepareStandard(message); - var handler = levelHandlers[message.level]; - var args = [message.standard]; - args = args.concat(message["arguments"].slice()); - handler.apply(console, args); - }; - logger = forge3.log.makeLogger(f); - } else { - f = function(logger2, message) { - forge3.log.prepareStandardFull(message); - console.log(message.standardFull); - }; - logger = forge3.log.makeLogger(f); - } - forge3.log.setLevel(logger, "debug"); - forge3.log.addLogger(logger); - sConsoleLogger = logger; - } else { - console = { - log: function() { - } - }; - } - var logger; - var levelHandlers; - var f; - if (sConsoleLogger !== null && typeof window !== "undefined" && window.location) { - query = new URL(window.location.href).searchParams; - if (query.has("console.level")) { - forge3.log.setLevel( - sConsoleLogger, - query.get("console.level").slice(-1)[0] - ); - } - if (query.has("console.lock")) { - lock = query.get("console.lock").slice(-1)[0]; - if (lock == "true") { - forge3.log.lock(sConsoleLogger); - } - } - } - var query; - var lock; - forge3.log.consoleLogger = sConsoleLogger; - } -}); - -// node_modules/node-forge/lib/md.all.js -var require_md_all = __commonJS({ - "node_modules/node-forge/lib/md.all.js"(exports, module) { - module.exports = require_md(); - require_md5(); - require_sha1(); - require_sha256(); - require_sha512(); - } -}); - -// node_modules/node-forge/lib/pkcs7.js -var require_pkcs7 = __commonJS({ - "node_modules/node-forge/lib/pkcs7.js"(exports, module) { - var forge3 = require_forge(); - require_aes(); - require_asn1(); - require_des(); - require_oids(); - require_pem(); - require_pkcs7asn1(); - require_random(); - require_util(); - require_x509(); - var asn1 = forge3.asn1; - var p7 = module.exports = forge3.pkcs7 = forge3.pkcs7 || {}; - p7.messageFromPem = function(pem) { - var msg = forge3.pem.decode(pem)[0]; - if (msg.type !== "PKCS7") { - var error = new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".'); - error.headerType = msg.type; - throw error; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted."); - } - var obj = asn1.fromDer(msg.body); - return p7.messageFromAsn1(obj); - }; - p7.messageToPem = function(msg, maxline) { - var pemObj = { - type: "PKCS7", - body: asn1.toDer(msg.toAsn1()).getBytes() - }; - return forge3.pem.encode(pemObj, { maxline }); - }; - p7.messageFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) { - var error = new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo."); - error.errors = errors; - throw error; - } - var contentType = asn1.derToOid(capture.contentType); - var msg; - switch (contentType) { - case forge3.pki.oids.envelopedData: - msg = p7.createEnvelopedData(); - break; - case forge3.pki.oids.encryptedData: - msg = p7.createEncryptedData(); - break; - case forge3.pki.oids.signedData: - msg = p7.createSignedData(); - break; - default: - throw new Error("Cannot read PKCS#7 message. ContentType with OID " + contentType + " is not (yet) supported."); - } - msg.fromAsn1(capture.content.value[0]); - return msg; - }; - p7.createSignedData = function() { - var msg = null; - msg = { - type: forge3.pki.oids.signedData, - version: 1, - certificates: [], - crls: [], - // TODO: add json-formatted signer stuff here? - signers: [], - // populated during sign() - digestAlgorithmIdentifiers: [], - contentInfo: null, - signerInfos: [], - fromAsn1: function(obj) { - _fromAsn1(msg, obj, p7.asn1.signedDataValidator); - msg.certificates = []; - msg.crls = []; - msg.digestAlgorithmIdentifiers = []; - msg.contentInfo = null; - msg.signerInfos = []; - if (msg.rawCapture.certificates) { - var certs = msg.rawCapture.certificates.value; - for (var i = 0; i < certs.length; ++i) { - msg.certificates.push(forge3.pki.certificateFromAsn1(certs[i])); - } - } - }, - toAsn1: function() { - if (!msg.contentInfo) { - msg.sign(); - } - var certs = []; - for (var i = 0; i < msg.certificates.length; ++i) { - certs.push(forge3.pki.certificateToAsn1(msg.certificates[i])); - } - var crls = []; - var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(msg.version).getBytes() - ), - // DigestAlgorithmIdentifiers - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SET, - true, - msg.digestAlgorithmIdentifiers - ), - // ContentInfo - msg.contentInfo - ]) - ]); - if (certs.length > 0) { - signedData.value[0].value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs) - ); - } - if (crls.length > 0) { - signedData.value[0].value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls) - ); - } - signedData.value[0].value.push( - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SET, - true, - msg.signerInfos - ) - ); - return asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [ - // ContentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(msg.type).getBytes() - ), - // [0] SignedData - signedData - ] - ); - }, - /** - * Add (another) entity to list of signers. - * - * Note: If authenticatedAttributes are provided, then, per RFC 2315, - * they must include at least two attributes: content type and - * message digest. The message digest attribute value will be - * auto-calculated during signing and will be ignored if provided. - * - * Here's an example of providing these two attributes: - * - * forge.pkcs7.createSignedData(); - * p7.addSigner({ - * issuer: cert.issuer.attributes, - * serialNumber: cert.serialNumber, - * key: privateKey, - * digestAlgorithm: forge.pki.oids.sha1, - * authenticatedAttributes: [{ - * type: forge.pki.oids.contentType, - * value: forge.pki.oids.data - * }, { - * type: forge.pki.oids.messageDigest - * }] - * }); - * - * TODO: Support [subjectKeyIdentifier] as signer's ID. - * - * @param signer the signer information: - * key the signer's private key. - * [certificate] a certificate containing the public key - * associated with the signer's private key; use this option as - * an alternative to specifying signer.issuer and - * signer.serialNumber. - * [issuer] the issuer attributes (eg: cert.issuer.attributes). - * [serialNumber] the signer's certificate's serial number in - * hexadecimal (eg: cert.serialNumber). - * [digestAlgorithm] the message digest OID, as a string, to use - * (eg: forge.pki.oids.sha1). - * [authenticatedAttributes] an optional array of attributes - * to also sign along with the content. - */ - addSigner: function(signer) { - var issuer = signer.issuer; - var serialNumber = signer.serialNumber; - if (signer.certificate) { - var cert = signer.certificate; - if (typeof cert === "string") { - cert = forge3.pki.certificateFromPem(cert); - } - issuer = cert.issuer.attributes; - serialNumber = cert.serialNumber; - } - var key = signer.key; - if (!key) { - throw new Error( - "Could not add PKCS#7 signer; no private key specified." - ); - } - if (typeof key === "string") { - key = forge3.pki.privateKeyFromPem(key); - } - var digestAlgorithm = signer.digestAlgorithm || forge3.pki.oids.sha1; - switch (digestAlgorithm) { - case forge3.pki.oids.sha1: - case forge3.pki.oids.sha256: - case forge3.pki.oids.sha384: - case forge3.pki.oids.sha512: - case forge3.pki.oids.md5: - break; - default: - throw new Error( - "Could not add PKCS#7 signer; unknown message digest algorithm: " + digestAlgorithm - ); - } - var authenticatedAttributes = signer.authenticatedAttributes || []; - if (authenticatedAttributes.length > 0) { - var contentType = false; - var messageDigest = false; - for (var i = 0; i < authenticatedAttributes.length; ++i) { - var attr = authenticatedAttributes[i]; - if (!contentType && attr.type === forge3.pki.oids.contentType) { - contentType = true; - if (messageDigest) { - break; - } - continue; - } - if (!messageDigest && attr.type === forge3.pki.oids.messageDigest) { - messageDigest = true; - if (contentType) { - break; - } - continue; - } - } - if (!contentType || !messageDigest) { - throw new Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest."); - } - } - msg.signers.push({ - key, - version: 1, - issuer, - serialNumber, - digestAlgorithm, - signatureAlgorithm: forge3.pki.oids.rsaEncryption, - signature: null, - authenticatedAttributes, - unauthenticatedAttributes: [] - }); - }, - /** - * Signs the content. - * @param options Options to apply when signing: - * [detached] boolean. If signing should be done in detached mode. Defaults to false. - */ - sign: function(options) { - options = options || {}; - if (typeof msg.content !== "object" || msg.contentInfo === null) { - msg.contentInfo = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [ - // ContentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(forge3.pki.oids.data).getBytes() - ) - ] - ); - if ("content" in msg) { - var content; - if (msg.content instanceof forge3.util.ByteBuffer) { - content = msg.content.bytes(); - } else if (typeof msg.content === "string") { - content = forge3.util.encodeUtf8(msg.content); - } - if (options.detached) { - msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content); - } else { - msg.contentInfo.value.push( - // [0] EXPLICIT content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - content - ) - ]) - ); - } - } - } - if (msg.signers.length === 0) { - return; - } - var mds = addDigestAlgorithmIds(); - addSignerInfos(mds); - }, - verify: function() { - throw new Error("PKCS#7 signature verification not yet implemented."); - }, - /** - * Add a certificate. - * - * @param cert the certificate to add. - */ - addCertificate: function(cert) { - if (typeof cert === "string") { - cert = forge3.pki.certificateFromPem(cert); - } - msg.certificates.push(cert); - }, - /** - * Add a certificate revokation list. - * - * @param crl the certificate revokation list to add. - */ - addCertificateRevokationList: function(crl) { - throw new Error("PKCS#7 CRL support not yet implemented."); - } - }; - return msg; - function addDigestAlgorithmIds() { - var mds = {}; - for (var i = 0; i < msg.signers.length; ++i) { - var signer = msg.signers[i]; - var oid = signer.digestAlgorithm; - if (!(oid in mds)) { - mds[oid] = forge3.md[forge3.pki.oids[oid]].create(); - } - if (signer.authenticatedAttributes.length === 0) { - signer.md = mds[oid]; - } else { - signer.md = forge3.md[forge3.pki.oids[oid]].create(); - } - } - msg.digestAlgorithmIdentifiers = []; - for (var oid in mds) { - msg.digestAlgorithmIdentifiers.push( - // AlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oid).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ); - } - return mds; - } - function addSignerInfos(mds) { - var content; - if (msg.detachedContent) { - content = msg.detachedContent; - } else { - content = msg.contentInfo.value[1]; - content = content.value[0]; - } - if (!content) { - throw new Error( - "Could not sign PKCS#7 message; there is no content to sign." - ); - } - var contentType = asn1.derToOid(msg.contentInfo.value[0].value); - var bytes = asn1.toDer(content); - bytes.getByte(); - asn1.getBerValueLength(bytes); - bytes = bytes.getBytes(); - for (var oid in mds) { - mds[oid].start().update(bytes); - } - var signingTime = /* @__PURE__ */ new Date(); - for (var i = 0; i < msg.signers.length; ++i) { - var signer = msg.signers[i]; - if (signer.authenticatedAttributes.length === 0) { - if (contentType !== forge3.pki.oids.data) { - throw new Error( - "Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data." - ); - } - } else { - signer.authenticatedAttributesAsn1 = asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - 0, - true, - [] - ); - var attrsAsn1 = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SET, - true, - [] - ); - for (var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) { - var attr = signer.authenticatedAttributes[ai]; - if (attr.type === forge3.pki.oids.messageDigest) { - attr.value = mds[signer.digestAlgorithm].digest(); - } else if (attr.type === forge3.pki.oids.signingTime) { - if (!attr.value) { - attr.value = signingTime; - } - } - attrsAsn1.value.push(_attributeToAsn1(attr)); - signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr)); - } - bytes = asn1.toDer(attrsAsn1).getBytes(); - signer.md.start().update(bytes); - } - signer.signature = signer.key.sign(signer.md, "RSASSA-PKCS1-V1_5"); - } - msg.signerInfos = _signersToAsn1(msg.signers); - } - }; - p7.createEncryptedData = function() { - var msg = null; - msg = { - type: forge3.pki.oids.encryptedData, - version: 0, - encryptedContent: { - algorithm: forge3.pki.oids["aes256-CBC"] - }, - /** - * Reads an EncryptedData content block (in ASN.1 format) - * - * @param obj The ASN.1 representation of the EncryptedData content block - */ - fromAsn1: function(obj) { - _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator); - }, - /** - * Decrypt encrypted content - * - * @param key The (symmetric) key as a byte buffer - */ - decrypt: function(key) { - if (key !== void 0) { - msg.encryptedContent.key = key; - } - _decryptContent(msg); - } - }; - return msg; - }; - p7.createEnvelopedData = function() { - var msg = null; - msg = { - type: forge3.pki.oids.envelopedData, - version: 0, - recipients: [], - encryptedContent: { - algorithm: forge3.pki.oids["aes256-CBC"] - }, - /** - * Reads an EnvelopedData content block (in ASN.1 format) - * - * @param obj the ASN.1 representation of the EnvelopedData content block. - */ - fromAsn1: function(obj) { - var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator); - msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value); - }, - toAsn1: function() { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // ContentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(msg.type).getBytes() - ), - // [0] EnvelopedData - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(msg.version).getBytes() - ), - // RecipientInfos - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SET, - true, - _recipientsToAsn1(msg.recipients) - ), - // EncryptedContentInfo - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - _encryptedContentToAsn1(msg.encryptedContent) - ) - ]) - ]) - ]); - }, - /** - * Find recipient by X.509 certificate's issuer. - * - * @param cert the certificate with the issuer to look for. - * - * @return the recipient object. - */ - findRecipient: function(cert) { - var sAttr = cert.issuer.attributes; - for (var i = 0; i < msg.recipients.length; ++i) { - var r = msg.recipients[i]; - var rAttr = r.issuer; - if (r.serialNumber !== cert.serialNumber) { - continue; - } - if (rAttr.length !== sAttr.length) { - continue; - } - var match = true; - for (var j = 0; j < sAttr.length; ++j) { - if (rAttr[j].type !== sAttr[j].type || rAttr[j].value !== sAttr[j].value) { - match = false; - break; - } - } - if (match) { - return r; - } - } - return null; - }, - /** - * Decrypt enveloped content - * - * @param recipient The recipient object related to the private key - * @param privKey The (RSA) private key object - */ - decrypt: function(recipient, privKey) { - if (msg.encryptedContent.key === void 0 && recipient !== void 0 && privKey !== void 0) { - switch (recipient.encryptedContent.algorithm) { - case forge3.pki.oids.rsaEncryption: - case forge3.pki.oids.desCBC: - var key = privKey.decrypt(recipient.encryptedContent.content); - msg.encryptedContent.key = forge3.util.createBuffer(key); - break; - default: - throw new Error("Unsupported asymmetric cipher, OID " + recipient.encryptedContent.algorithm); - } - } - _decryptContent(msg); - }, - /** - * Add (another) entity to list of recipients. - * - * @param cert The certificate of the entity to add. - */ - addRecipient: function(cert) { - msg.recipients.push({ - version: 0, - issuer: cert.issuer.attributes, - serialNumber: cert.serialNumber, - encryptedContent: { - // We simply assume rsaEncryption here, since forge.pki only - // supports RSA so far. If the PKI module supports other - // ciphers one day, we need to modify this one as well. - algorithm: forge3.pki.oids.rsaEncryption, - key: cert.publicKey - } - }); - }, - /** - * Encrypt enveloped content. - * - * This function supports two optional arguments, cipher and key, which - * can be used to influence symmetric encryption. Unless cipher is - * provided, the cipher specified in encryptedContent.algorithm is used - * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key - * is (re-)used. If that one's not set, a random key will be generated - * automatically. - * - * @param [key] The key to be used for symmetric encryption. - * @param [cipher] The OID of the symmetric cipher to use. - */ - encrypt: function(key, cipher) { - if (msg.encryptedContent.content === void 0) { - cipher = cipher || msg.encryptedContent.algorithm; - key = key || msg.encryptedContent.key; - var keyLen, ivLen, ciphFn; - switch (cipher) { - case forge3.pki.oids["aes128-CBC"]: - keyLen = 16; - ivLen = 16; - ciphFn = forge3.aes.createEncryptionCipher; - break; - case forge3.pki.oids["aes192-CBC"]: - keyLen = 24; - ivLen = 16; - ciphFn = forge3.aes.createEncryptionCipher; - break; - case forge3.pki.oids["aes256-CBC"]: - keyLen = 32; - ivLen = 16; - ciphFn = forge3.aes.createEncryptionCipher; - break; - case forge3.pki.oids["des-EDE3-CBC"]: - keyLen = 24; - ivLen = 8; - ciphFn = forge3.des.createEncryptionCipher; - break; - default: - throw new Error("Unsupported symmetric cipher, OID " + cipher); - } - if (key === void 0) { - key = forge3.util.createBuffer(forge3.random.getBytes(keyLen)); - } else if (key.length() != keyLen) { - throw new Error("Symmetric key has wrong length; got " + key.length() + " bytes, expected " + keyLen + "."); - } - msg.encryptedContent.algorithm = cipher; - msg.encryptedContent.key = key; - msg.encryptedContent.parameter = forge3.util.createBuffer( - forge3.random.getBytes(ivLen) - ); - var ciph = ciphFn(key); - ciph.start(msg.encryptedContent.parameter.copy()); - ciph.update(msg.content); - if (!ciph.finish()) { - throw new Error("Symmetric encryption failed."); - } - msg.encryptedContent.content = ciph.output; - } - for (var i = 0; i < msg.recipients.length; ++i) { - var recipient = msg.recipients[i]; - if (recipient.encryptedContent.content !== void 0) { - continue; - } - switch (recipient.encryptedContent.algorithm) { - case forge3.pki.oids.rsaEncryption: - recipient.encryptedContent.content = recipient.encryptedContent.key.encrypt( - msg.encryptedContent.key.data - ); - break; - default: - throw new Error("Unsupported asymmetric cipher, OID " + recipient.encryptedContent.algorithm); - } - } - } - }; - return msg; - }; - function _recipientFromAsn1(obj) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) { - var error = new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo."); - error.errors = errors; - throw error; - } - return { - version: capture.version.charCodeAt(0), - issuer: forge3.pki.RDNAttributesAsArray(capture.issuer), - serialNumber: forge3.util.createBuffer(capture.serial).toHex(), - encryptedContent: { - algorithm: asn1.derToOid(capture.encAlgorithm), - parameter: capture.encParameter ? capture.encParameter.value : void 0, - content: capture.encKey - } - }; - } - function _recipientToAsn1(obj) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(obj.version).getBytes() - ), - // IssuerAndSerialNumber - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Name - forge3.pki.distinguishedNameToAsn1({ attributes: obj.issuer }), - // Serial - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - forge3.util.hexToBytes(obj.serialNumber) - ) - ]), - // KeyEncryptionAlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(obj.encryptedContent.algorithm).getBytes() - ), - // Parameter, force NULL, only RSA supported for now. - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]), - // EncryptedKey - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - obj.encryptedContent.content - ) - ]); - } - function _recipientsFromAsn1(infos) { - var ret = []; - for (var i = 0; i < infos.length; ++i) { - ret.push(_recipientFromAsn1(infos[i])); - } - return ret; - } - function _recipientsToAsn1(recipients) { - var ret = []; - for (var i = 0; i < recipients.length; ++i) { - ret.push(_recipientToAsn1(recipients[i])); - } - return ret; - } - function _signerToAsn1(obj) { - var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(obj.version).getBytes() - ), - // issuerAndSerialNumber - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // name - forge3.pki.distinguishedNameToAsn1({ attributes: obj.issuer }), - // serial - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - forge3.util.hexToBytes(obj.serialNumber) - ) - ]), - // digestAlgorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(obj.digestAlgorithm).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ]); - if (obj.authenticatedAttributesAsn1) { - rval.value.push(obj.authenticatedAttributesAsn1); - } - rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(obj.signatureAlgorithm).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ])); - rval.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - obj.signature - )); - if (obj.unauthenticatedAttributes.length > 0) { - var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []); - for (var i = 0; i < obj.unauthenticatedAttributes.length; ++i) { - var attr = obj.unauthenticatedAttributes[i]; - attrsAsn1.values.push(_attributeToAsn1(attr)); - } - rval.value.push(attrsAsn1); - } - return rval; - } - function _signersToAsn1(signers) { - var ret = []; - for (var i = 0; i < signers.length; ++i) { - ret.push(_signerToAsn1(signers[i])); - } - return ret; - } - function _attributeToAsn1(attr) { - var value; - if (attr.type === forge3.pki.oids.contentType) { - value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(attr.value).getBytes() - ); - } else if (attr.type === forge3.pki.oids.messageDigest) { - value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - attr.value.bytes() - ); - } else if (attr.type === forge3.pki.oids.signingTime) { - var jan_1_1950 = /* @__PURE__ */ new Date("1950-01-01T00:00:00Z"); - var jan_1_2050 = /* @__PURE__ */ new Date("2050-01-01T00:00:00Z"); - var date = attr.value; - if (typeof date === "string") { - var timestamp = Date.parse(date); - if (!isNaN(timestamp)) { - date = new Date(timestamp); - } else if (date.length === 13) { - date = asn1.utcTimeToDate(date); - } else { - date = asn1.generalizedTimeToDate(date); - } - } - if (date >= jan_1_1950 && date < jan_1_2050) { - value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.UTCTIME, - false, - asn1.dateToUtcTime(date) - ); - } else { - value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.GENERALIZEDTIME, - false, - asn1.dateToGeneralizedTime(date) - ); - } - } - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AttributeType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(attr.type).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - // AttributeValue - value - ]) - ]); - } - function _encryptedContentToAsn1(ec) { - return [ - // ContentType, always Data for the moment - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(forge3.pki.oids.data).getBytes() - ), - // ContentEncryptionAlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(ec.algorithm).getBytes() - ), - // Parameters (IV) - !ec.parameter ? void 0 : asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - ec.parameter.getBytes() - ) - ]), - // [0] EncryptedContent - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - ec.content.getBytes() - ) - ]) - ]; - } - function _fromAsn1(msg, obj, validator) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, validator, capture, errors)) { - var error = new Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message."); - error.errors = error; - throw error; - } - var contentType = asn1.derToOid(capture.contentType); - if (contentType !== forge3.pki.oids.data) { - throw new Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported."); - } - if (capture.encryptedContent) { - var content = ""; - if (forge3.util.isArray(capture.encryptedContent)) { - for (var i = 0; i < capture.encryptedContent.length; ++i) { - if (capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) { - throw new Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects."); - } - content += capture.encryptedContent[i].value; - } - } else { - content = capture.encryptedContent; - } - msg.encryptedContent = { - algorithm: asn1.derToOid(capture.encAlgorithm), - parameter: forge3.util.createBuffer(capture.encParameter.value), - content: forge3.util.createBuffer(content) - }; - } - if (capture.content) { - var content = ""; - if (forge3.util.isArray(capture.content)) { - for (var i = 0; i < capture.content.length; ++i) { - if (capture.content[i].type !== asn1.Type.OCTETSTRING) { - throw new Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects."); - } - content += capture.content[i].value; - } - } else { - content = capture.content; - } - msg.content = forge3.util.createBuffer(content); - } - msg.version = capture.version.charCodeAt(0); - msg.rawCapture = capture; - return capture; - } - function _decryptContent(msg) { - if (msg.encryptedContent.key === void 0) { - throw new Error("Symmetric key not available."); - } - if (msg.content === void 0) { - var ciph; - switch (msg.encryptedContent.algorithm) { - case forge3.pki.oids["aes128-CBC"]: - case forge3.pki.oids["aes192-CBC"]: - case forge3.pki.oids["aes256-CBC"]: - ciph = forge3.aes.createDecryptionCipher(msg.encryptedContent.key); - break; - case forge3.pki.oids["desCBC"]: - case forge3.pki.oids["des-EDE3-CBC"]: - ciph = forge3.des.createDecryptionCipher(msg.encryptedContent.key); - break; - default: - throw new Error("Unsupported symmetric cipher, OID " + msg.encryptedContent.algorithm); - } - ciph.start(msg.encryptedContent.parameter); - ciph.update(msg.encryptedContent.content); - if (!ciph.finish()) { - throw new Error("Symmetric decryption failed."); - } - msg.content = ciph.output; - } - } - } -}); - -// node_modules/node-forge/lib/ssh.js -var require_ssh = __commonJS({ - "node_modules/node-forge/lib/ssh.js"(exports, module) { - var forge3 = require_forge(); - require_aes(); - require_hmac(); - require_md5(); - require_sha1(); - require_util(); - var ssh = module.exports = forge3.ssh = forge3.ssh || {}; - ssh.privateKeyToPutty = function(privateKey, passphrase, comment) { - comment = comment || ""; - passphrase = passphrase || ""; - var algorithm = "ssh-rsa"; - var encryptionAlgorithm = passphrase === "" ? "none" : "aes256-cbc"; - var ppk = "PuTTY-User-Key-File-2: " + algorithm + "\r\n"; - ppk += "Encryption: " + encryptionAlgorithm + "\r\n"; - ppk += "Comment: " + comment + "\r\n"; - var pubbuffer = forge3.util.createBuffer(); - _addStringToBuffer(pubbuffer, algorithm); - _addBigIntegerToBuffer(pubbuffer, privateKey.e); - _addBigIntegerToBuffer(pubbuffer, privateKey.n); - var pub = forge3.util.encode64(pubbuffer.bytes(), 64); - var length = Math.floor(pub.length / 66) + 1; - ppk += "Public-Lines: " + length + "\r\n"; - ppk += pub; - var privbuffer = forge3.util.createBuffer(); - _addBigIntegerToBuffer(privbuffer, privateKey.d); - _addBigIntegerToBuffer(privbuffer, privateKey.p); - _addBigIntegerToBuffer(privbuffer, privateKey.q); - _addBigIntegerToBuffer(privbuffer, privateKey.qInv); - var priv; - if (!passphrase) { - priv = forge3.util.encode64(privbuffer.bytes(), 64); - } else { - var encLen = privbuffer.length() + 16 - 1; - encLen -= encLen % 16; - var padding = _sha1(privbuffer.bytes()); - padding.truncate(padding.length() - encLen + privbuffer.length()); - privbuffer.putBuffer(padding); - var aeskey = forge3.util.createBuffer(); - aeskey.putBuffer(_sha1("\0\0\0\0", passphrase)); - aeskey.putBuffer(_sha1("\0\0\0", passphrase)); - var cipher = forge3.aes.createEncryptionCipher(aeskey.truncate(8), "CBC"); - cipher.start(forge3.util.createBuffer().fillWithByte(0, 16)); - cipher.update(privbuffer.copy()); - cipher.finish(); - var encrypted = cipher.output; - encrypted.truncate(16); - priv = forge3.util.encode64(encrypted.bytes(), 64); - } - length = Math.floor(priv.length / 66) + 1; - ppk += "\r\nPrivate-Lines: " + length + "\r\n"; - ppk += priv; - var mackey = _sha1("putty-private-key-file-mac-key", passphrase); - var macbuffer = forge3.util.createBuffer(); - _addStringToBuffer(macbuffer, algorithm); - _addStringToBuffer(macbuffer, encryptionAlgorithm); - _addStringToBuffer(macbuffer, comment); - macbuffer.putInt32(pubbuffer.length()); - macbuffer.putBuffer(pubbuffer); - macbuffer.putInt32(privbuffer.length()); - macbuffer.putBuffer(privbuffer); - var hmac = forge3.hmac.create(); - hmac.start("sha1", mackey); - hmac.update(macbuffer.bytes()); - ppk += "\r\nPrivate-MAC: " + hmac.digest().toHex() + "\r\n"; - return ppk; - }; - ssh.publicKeyToOpenSSH = function(key, comment) { - var type = "ssh-rsa"; - comment = comment || ""; - var buffer = forge3.util.createBuffer(); - _addStringToBuffer(buffer, type); - _addBigIntegerToBuffer(buffer, key.e); - _addBigIntegerToBuffer(buffer, key.n); - return type + " " + forge3.util.encode64(buffer.bytes()) + " " + comment; - }; - ssh.privateKeyToOpenSSH = function(privateKey, passphrase) { - if (!passphrase) { - return forge3.pki.privateKeyToPem(privateKey); - } - return forge3.pki.encryptRsaPrivateKey( - privateKey, - passphrase, - { legacy: true, algorithm: "aes128" } - ); - }; - ssh.getPublicKeyFingerprint = function(key, options) { - options = options || {}; - var md = options.md || forge3.md.md5.create(); - var type = "ssh-rsa"; - var buffer = forge3.util.createBuffer(); - _addStringToBuffer(buffer, type); - _addBigIntegerToBuffer(buffer, key.e); - _addBigIntegerToBuffer(buffer, key.n); - md.start(); - md.update(buffer.getBytes()); - var digest = md.digest(); - if (options.encoding === "hex") { - var hex = digest.toHex(); - if (options.delimiter) { - return hex.match(/.{2}/g).join(options.delimiter); - } - return hex; - } else if (options.encoding === "binary") { - return digest.getBytes(); - } else if (options.encoding) { - throw new Error('Unknown encoding "' + options.encoding + '".'); - } - return digest; - }; - function _addBigIntegerToBuffer(buffer, val) { - var hexVal = val.toString(16); - if (hexVal[0] >= "8") { - hexVal = "00" + hexVal; - } - var bytes = forge3.util.hexToBytes(hexVal); - buffer.putInt32(bytes.length); - buffer.putBytes(bytes); - } - function _addStringToBuffer(buffer, val) { - buffer.putInt32(val.length); - buffer.putString(val); - } - function _sha1() { - var sha = forge3.md.sha1.create(); - var num = arguments.length; - for (var i = 0; i < num; ++i) { - sha.update(arguments[i]); - } - return sha.digest(); - } - } -}); - -// node_modules/node-forge/lib/index.js -var require_lib = __commonJS({ - "node_modules/node-forge/lib/index.js"(exports, module) { - module.exports = require_forge(); - require_aes(); - require_aesCipherSuites(); - require_asn1(); - require_cipher(); - require_des(); - require_ed25519(); - require_hmac(); - require_kem(); - require_log(); - require_md_all(); - require_mgf1(); - require_pbkdf2(); - require_pem(); - require_pkcs1(); - require_pkcs12(); - require_pkcs7(); - require_pki(); - require_prime(); - require_prng(); - require_pss(); - require_random(); - require_rc2(); - require_ssh(); - require_tls(); - require_util(); - } -}); - -// src/lostcity/server/LoginThread.ts -var import_node_forge2 = __toESM(require_lib(), 1); - -// src/jagex2/io/Packet.ts -var import_node_forge = __toESM(require_lib(), 1); - -// src/jagex2/datastruct/Linkable.ts -var Linkable = class { - key; - next; - prev; - constructor() { - this.key = 0n; - this.next = this; - this.prev = this; - } - unlink() { - if (!this.prev || !this.next) { - return; - } - this.prev.next = this.next; - this.next.prev = this.prev; - this.next = null; - this.prev = null; - } -}; - -// src/jagex2/datastruct/LinkList.ts -var LinkList = class { - sentinel; - cursor = null; - constructor() { - const head = new Linkable(); - head.next = head; - head.prev = head; - this.sentinel = head; - } - addTail(node) { - if (node.prev) { - node.unlink(); - } - node.prev = this.sentinel.prev; - node.next = this.sentinel; - if (node.prev) { - node.prev.next = node; - } - node.next.prev = node; - } - addHead(node) { - if (node.prev) { - node.unlink(); - } - node.prev = this.sentinel; - node.next = this.sentinel.next; - node.prev.next = node; - if (node.next) { - node.next.prev = node; - } - } - removeHead() { - const node = this.sentinel.next; - if (node === this.sentinel) { - return null; - } - node?.unlink(); - return node; - } - head() { - const node = this.sentinel.next; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.next || null; - return node; - } - tail() { - const node = this.sentinel.prev; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.prev || null; - return node; - } - next() { - const node = this.cursor; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.next || null; - return node; - } - prev() { - const node = this.cursor; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.prev || null; - return node; - } - clear() { - while (true) { - const node = this.sentinel.next; - if (node === this.sentinel) { - return; - } - node?.unlink(); - } - } -}; - -// src/jagex2/datastruct/Hashable.ts -var Hashable = class extends Linkable { - nextHashable; - prevHashable; - constructor() { - super(); - this.nextHashable = this; - this.prevHashable = this; - } - uncache() { - if (!this.prevHashable || !this.nextHashable) { - return; - } - this.prevHashable.nextHashable = this.nextHashable; - this.nextHashable.prevHashable = this.prevHashable; - this.nextHashable = null; - this.prevHashable = null; - } -}; - -// src/jagex2/io/Packet.ts -var BigInteger = import_node_forge.default.jsbn.BigInteger; -var Packet = class _Packet extends Hashable { - static crctable = new Int32Array(256); - static bitmask = new Uint32Array(33); - /** - * Reversed CRC-32 polynomial for Cyclic Redundancy Check (CRC). - * This is sometimes referred to as CRC32B. - */ - static crc32b = 3988292384; - static { - for (let i = 0; i < 32; i++) { - this.bitmask[i] = (1 << i) - 1; - } - this.bitmask[32] = 4294967295; - for (let b = 0; b < 256; b++) { - let remainder = b; - for (let bit = 0; bit < 8; bit++) { - if ((remainder & 1) == 1) { - remainder = remainder >>> 1 ^ this.crc32b; - } else { - remainder >>>= 1; - } - } - this.crctable[b] = remainder; - } - } - static getcrc(src, offset, length) { - let crc = 4294967295; - for (let i = offset; i < length; i++) { - crc = crc >>> 8 ^ this.crctable[(crc ^ src[i]) & 255]; - } - return ~crc; - } - static checkcrc(src, offset, length, expected = 0) { - const checksum = _Packet.getcrc(src, offset, length); - return checksum == expected; - } - static alloc(type) { - let packet = null; - if (type === 0 && this.cacheMinCount > 0) { - packet = this.cacheMin.removeHead(); - this.cacheMinCount--; - } else if (type === 1 && this.cacheMidCount > 0) { - packet = this.cacheMid.removeHead(); - this.cacheMidCount--; - } else if (type === 2 && this.cacheMaxCount > 0) { - packet = this.cacheMax.removeHead(); - this.cacheMaxCount--; - } else if (type === 3 && this.cacheBigCount > 0) { - packet = this.cacheBig.removeHead(); - this.cacheBigCount--; - } else if (type === 4 && this.cacheHugeCount > 0) { - packet = this.cacheHuge.removeHead(); - this.cacheHugeCount--; - } else if (type === 5 && this.cacheUnimaginableCount > 0) { - packet = this.cacheUnimaginable.removeHead(); - this.cacheUnimaginableCount--; - } - if (packet !== null) { - packet.pos = 0; - packet.bitPos = 0; - return packet; - } - if (type === 0) { - return new _Packet(new Uint8Array(100)); - } else if (type === 1) { - return new _Packet(new Uint8Array(5e3)); - } else if (type === 2) { - return new _Packet(new Uint8Array(3e4)); - } else if (type === 3) { - return new _Packet(new Uint8Array(1e5)); - } else if (type === 4) { - return new _Packet(new Uint8Array(5e5)); - } else if (type === 5) { - return new _Packet(new Uint8Array(2e6)); - } else { - return new _Packet(new Uint8Array(type)); - } - } - static load(path2, seekToEnd = false) { - const packet = new _Packet(new Uint8Array(fs.readFileSync(path2))); - if (seekToEnd) { - packet.pos = packet.data.length; - } - return packet; - } - static async loadAsync(path2, seekToEnd = false) { - const packet = new _Packet(new Uint8Array(await (await fetch(path2)).arrayBuffer())); - if (seekToEnd) { - packet.pos = packet.data.length; - } - return packet; - } - static cacheMinCount = 0; - static cacheMidCount = 0; - static cacheMaxCount = 0; - static cacheBigCount = 0; - static cacheHugeCount = 0; - static cacheUnimaginableCount = 0; - static cacheMin = new LinkList(); - static cacheMid = new LinkList(); - static cacheMax = new LinkList(); - static cacheBig = new LinkList(); - static cacheHuge = new LinkList(); - static cacheUnimaginable = new LinkList(); - data; - #view; - pos; - bitPos; - constructor(src) { - super(); - this.data = src; - this.#view = new DataView(this.data.buffer); - this.pos = 0; - this.bitPos = 0; - } - get available() { - return this.data.length - this.pos; - } - get length() { - return this.data.length; - } - release() { - this.pos = 0; - this.bitPos = 0; - if (this.data.length === 100 && _Packet.cacheMinCount < 1e3) { - _Packet.cacheMin.addTail(this); - _Packet.cacheMinCount++; - } else if (this.data.length === 5e3 && _Packet.cacheMidCount < 250) { - _Packet.cacheMid.addTail(this); - _Packet.cacheMidCount++; - } else if (this.data.length === 3e4 && _Packet.cacheMaxCount < 50) { - _Packet.cacheMax.addTail(this); - _Packet.cacheMaxCount++; - } else if (this.data.length === 1e5 && _Packet.cacheBigCount < 10) { - _Packet.cacheBig.addTail(this); - _Packet.cacheBigCount++; - } else if (this.data.length === 5e5 && _Packet.cacheHugeCount < 5) { - _Packet.cacheHuge.addTail(this); - _Packet.cacheHugeCount++; - } else if (this.data.length === 2e6 && _Packet.cacheUnimaginableCount < 2) { - _Packet.cacheUnimaginable.addTail(this); - _Packet.cacheUnimaginableCount++; - } - } - save(filePath, length = this.pos, start = 0) { - if (typeof self === "undefined") { - const dir = path.dirname(filePath); - if (!fs.existsSync(dir)) { - fs.mkdirSync(dir, { recursive: true }); - } - fs.writeFileSync(filePath, this.data.subarray(start, start + length)); - } else { - const blob = new Blob([this.data.subarray(start, start + length)], { type: "application/octet-stream" }); - const url = URL.createObjectURL(blob); - self.postMessage({ type: "save", value: url, path: filePath }); - } - } - p1(value) { - this.#view.setUint8(this.pos++, value); - } - p2(value) { - this.#view.setUint16(this.pos, value); - this.pos += 2; - } - ip2(value) { - this.#view.setUint16(this.pos, value, true); - this.pos += 2; - } - p3(value) { - this.#view.setUint8(this.pos++, value >> 16); - this.#view.setUint16(this.pos, value); - this.pos += 2; - } - p4(value) { - this.#view.setInt32(this.pos, value); - this.pos += 4; - } - ip4(value) { - this.#view.setInt32(this.pos, value, true); - this.pos += 4; - } - p8(value) { - this.#view.setBigInt64(this.pos, value); - this.pos += 8; - } - pbool(value) { - this.p1(value ? 1 : 0); - } - pjstr(str, terminator = 10) { - const length = str.length; - for (let i = 0; i < length; i++) { - this.#view.setUint8(this.pos++, str.charCodeAt(i)); - } - this.#view.setUint8(this.pos++, terminator); - } - pdata(src, offset, length) { - this.data.set(src.subarray(offset, offset + length), this.pos); - this.pos += length - offset; - } - psize4(size) { - this.#view.setUint32(this.pos - size - 4, size); - } - psize2(size) { - this.#view.setUint16(this.pos - size - 2, size); - } - psize1(size) { - this.#view.setUint8(this.pos - size - 1, size); - } - psmarts(value) { - if (value < 64 && value >= 64) { - this.p1(value + 64); - } else if (value < 16384 && value >= -16384) { - this.p2(value + 49152); - } else { - throw new Error("Error psmarts out of range: " + value); - } - } - psmart(value) { - if (value >= 0 && value < 128) { - this.p1(value); - } else if (value >= 0 && value < 32768) { - this.p2(value + 32768); - } else { - throw new Error("Error psmart out of range: " + value); - } - } - // ---- - g1() { - return this.#view.getUint8(this.pos++); - } - g1b() { - return this.#view.getInt8(this.pos++); - } - g2() { - this.pos += 2; - return this.#view.getUint16(this.pos - 2); - } - g2s() { - this.pos += 2; - return this.#view.getInt16(this.pos - 2); - } - ig2() { - this.pos += 2; - return this.#view.getUint16(this.pos - 2, true); - } - g3() { - const result = this.#view.getUint8(this.pos++) << 16 | this.#view.getUint16(this.pos); - this.pos += 2; - return result; - } - g4() { - this.pos += 4; - return this.#view.getInt32(this.pos - 4); - } - ig4() { - this.pos += 4; - return this.#view.getInt32(this.pos - 4, true); - } - g8() { - this.pos += 8; - return this.#view.getBigInt64(this.pos - 8); - } - gbool() { - return this.g1() === 1; - } - gjstr(terminator = 10) { - const length = this.data.length; - let str = ""; - let b; - while ((b = this.#view.getUint8(this.pos++)) !== terminator && this.pos < length) { - str += String.fromCharCode(b); - } - return str; - } - gdata(dest, offset, length) { - dest.set(this.data.subarray(this.pos, this.pos + length), offset); - this.pos += length; - } - gsmarts() { - return this.#view.getUint8(this.pos) < 128 ? this.g1() - 64 : this.g2() - 49152; - } - gsmart() { - return this.#view.getUint8(this.pos) < 128 ? this.g1() : this.g2() - 32768; - } - bits() { - this.bitPos = this.pos << 3; - } - bytes() { - this.pos = this.bitPos + 7 >>> 3; - } - gBit(n) { - let bytePos = this.bitPos >>> 3; - let remaining = 8 - (this.bitPos & 7); - let value = 0; - this.bitPos += n; - for (; n > remaining; remaining = 8) { - value += (this.#view.getUint8(bytePos++) & _Packet.bitmask[remaining]) << n - remaining; - n -= remaining; - } - if (n == remaining) { - value += this.#view.getUint8(bytePos) & _Packet.bitmask[remaining]; - } else { - value += this.#view.getUint8(bytePos) >>> remaining - n & _Packet.bitmask[n]; - } - return value; - } - pBit(n, value) { - const pos = this.bitPos; - this.bitPos += n; - let bytePos = pos >>> 3; - let remaining = 8 - (pos & 7); - const view = this.#view; - for (; n > remaining; remaining = 8) { - const shift2 = (1 << remaining) - 1; - const byte2 = view.getUint8(bytePos); - view.setUint8(bytePos++, byte2 & ~shift2 | value >>> n - remaining & shift2); - n -= remaining; - } - const r = remaining - n; - const shift = (1 << n) - 1; - const byte = view.getUint8(bytePos); - view.setUint8(bytePos, byte & ~shift << r | (value & shift) << r); - } - rsaenc(pem) { - const length = this.pos; - this.pos = 0; - const dec = new Uint8Array(length); - this.gdata(dec, 0, dec.length); - const bigRaw = new BigInteger(Array.from(dec)); - const rawEnc = Uint8Array.from(bigRaw.modPow(pem.e, pem.n).toByteArray()); - this.pos = 0; - this.p1(rawEnc.length); - this.pdata(rawEnc, 0, rawEnc.length); - } - rsadec(pem) { - const p = pem.p; - const q = pem.q; - const dP = pem.dP; - const dQ = pem.dQ; - const qInv = pem.qInv; - const enc = new Uint8Array(this.g1()); - this.gdata(enc, 0, enc.length); - const bigRaw = new BigInteger(Array.from(enc)); - const m1 = bigRaw.mod(p).modPow(dP, p); - const m2 = bigRaw.mod(q).modPow(dQ, q); - const h = qInv.multiply(m1.subtract(m2)).mod(p); - const rawDec = new Uint8Array(m2.add(h.multiply(q)).toByteArray()); - this.pos = 0; - this.pdata(rawDec, 0, rawDec.length); - this.pos = 0; - } - // later revs have tinyenc/tinydec methods - // later revs have alt methods for packet obfuscation -}; - -// src/jagex2/jstring/JString.ts -function toBase37(string) { - string = string.trim(); - let l = 0n; - for (let i = 0; i < string.length && i < 12; i++) { - const c = string.charCodeAt(i); - l *= 37n; - if (c >= 65 && c <= 90) { - l += BigInt(c + 1 - 65); - } else if (c >= 97 && c <= 122) { - l += BigInt(c + 1 - 97); - } else if (c >= 48 && c <= 57) { - l += BigInt(c + 27 - 48); - } - } - return l; -} -var BASE37_LOOKUP = [ - "_", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9" -]; -function fromBase37(value) { - if (value < 0n || value >= 6582952005840035281n) { - return "invalid_name"; - } - if (value % 37n === 0n) { - return "invalid_name"; - } - let len = 0; - const chars = Array(12); - while (value !== 0n) { - const l1 = value; - value /= 37n; - chars[11 - len++] = BASE37_LOOKUP[Number(l1 - value * 37n)]; - } - return chars.slice(12 - len).join(""); -} -function toSafeName(name) { - return fromBase37(toBase37(name)); -} - -// src/lostcity/server/LoginServer.ts - -// src/lostcity/server/NetworkStream.ts -var NetworkStream = class { - queue = []; - // queue of data events - available = 0; - // remaining bytes to read - buffer = null; - // current data event - offset = 0; - waiting = 0; - // number of bytes waiting to be read - received(buf) { - this.queue.push(buf); - this.available += buf.length; - } - clear() { - this.queue = []; - this.available = 0; - this.buffer = null; - this.offset = 0; - } - async readByte(socket) { - if (socket === null || socket.closed) { - return 0; - } - if (this.available < 1) { - await new Promise((res) => setTimeout(res, 10)); - return this.readByte(socket); - } - if (this.buffer === null) { - this.buffer = this.queue.shift() ?? null; - this.offset = 0; - } - const value = this.buffer?.[this.offset] ?? 0; - this.offset++; - this.available--; - if (this.buffer && this.offset === this.buffer.length) { - this.buffer = null; - } - return value; - } - async readBytes(socket, destination, offset, length, full = true) { - if (socket === null || socket.closed) { - return 0; - } - if (this.available < length) { - if (full) { - await new Promise((res) => setTimeout(res, 10)); - return this.readBytes(socket, destination, offset, length); - } else { - length = this.available; - } - } - destination.pos = offset; - for (let i = 0; i < length; i++) { - if (this.buffer === null) { - this.buffer = this.queue.shift() ?? null; - this.offset = 0; - } - destination.data[offset + i] = this.buffer?.[this.offset] ?? 0; - this.offset++; - this.available--; - if (this.buffer && this.offset === this.buffer.length) { - this.buffer = null; - } - } - return length; - } -}; - -// src/lostcity/util/Environment.ts - -// src/lostcity/util/TryParse.ts -function tryParseBoolean(value, defaultValue) { - if (value === "true" || value === true) { - return true; - } else if (value === "false" || value === false) { - return false; - } else { - return defaultValue; - } -} -function tryParseInt(value, defaultValue) { - if (typeof value === "number") { - return value; - } - if (typeof value !== "string" && typeof value !== "number") { - return defaultValue; - } - const intValue = parseInt(value); - if (!isNaN(intValue)) { - return intValue; - } - return defaultValue; -} -function tryParseString(value, defaultValue) { - if (typeof value !== "string") { - return defaultValue; - } - return value; -} -function tryParseArray(value, defaultValue) { - if (!Array.isArray(value)) { - return defaultValue; - } - return value; -} - -// src/lostcity/util/Environment.ts -var Environment_default = { - /// web server - WEB_PORT: tryParseInt(void 0, false ? 80 : 8888), - WEB_CORS: tryParseBoolean(void 0, true), - /// game server - // world id - offset by 9, so 1 = 10, 2 = 11, etc - NODE_ID: tryParseInt(void 0, 10), - NODE_PORT: tryParseInt(void 0, 43594), - // members content - NODE_MEMBERS: tryParseBoolean(void 0, true), - // addxp multiplier - NODE_XPRATE: tryParseInt(void 0, 1), - // production mode! - NODE_PRODUCTION: tryParseBoolean(void 0, false), - // automatic shutdown time for production mode on sigint - NODE_KILLTIMER: tryParseInt(void 0, 50), - NODE_ALLOW_CHEATS: tryParseBoolean(void 0, true), - // development mode! - NODE_DEBUG: tryParseBoolean(void 0, true), - // measuring script execution - NODE_DEBUG_PROFILE: tryParseBoolean(void 0, false), - // *only* if no login server is running to authenticate accounts, this provides admin accs by username :) - NODE_STAFF: tryParseArray(void 0, ["pazaz"]), - // todo: add staffmodlevel to database - // no server routefinding until 2009 - NODE_CLIENT_ROUTEFINDER: tryParseBoolean(void 0, true), - // controllable for bot testing - NODE_SOCKET_TIMEOUT: tryParseBoolean(void 0, true), - /// login server - LOGIN_HOST: tryParseString(void 0, "localhost"), - LOGIN_PORT: tryParseInt(void 0, 43500), - LOGIN_KEY: tryParseString(void 0, ""), - /// database - DB_HOST: tryParseString(void 0, "localhost"), - DB_USER: tryParseString(void 0, "root"), - DB_PASS: tryParseString(void 0, "password"), - DB_NAME: tryParseString(void 0, "lostcity"), - /// development - // some users may not be able to change their system PATH for this project - BUILD_JAVA_PATH: tryParseString(void 0, "java"), - // auto-build on startup - BUILD_STARTUP: tryParseBoolean(void 0, true), - // auto-update compiler on startup - BUILD_STARTUP_UPDATE: tryParseBoolean(void 0, true), - // used to check if we're producing the original cache without edits - BUILD_VERIFY: tryParseBoolean(void 0, true), - // used to keep some semblance of sanity in our folder structure - BUILD_VERIFY_FOLDER: tryParseBoolean(void 0, true), - // used for unpacking/custom development - BUILD_VERIFY_PACK: tryParseBoolean(void 0, true), - // used for unpacking/custom development - BUILD_SRC_DIR: tryParseString(void 0, "data/src") -}; - -// src/lostcity/server/LoginServer.ts -var LoginResponse = class { - static SUCCESSFUL = Uint8Array.from([2]); - static INVALID_USER_OR_PASS = Uint8Array.from([3]); - // Invalid username or password. - static ACCOUNT_DISABLED = Uint8Array.from([4]); - // Your account has been disabled. - static LOGGED_IN = Uint8Array.from([5]); - // Your account is already logged in. - static SERVER_UPDATED = Uint8Array.from([6]); - // RuneScape has been updated! - static WORLD_FULL = Uint8Array.from([7]); - // This world is full. - static LOGIN_SERVER_OFFLINE = Uint8Array.from([8]); - // Unable to connect. - static LOGIN_LIMIT_EXCEEDED = Uint8Array.from([9]); - // Login limit exceeded. - static UNABLE_TO_CONNECT = Uint8Array.from([10]); - // Unable to connect. - static LOGIN_REJECTED = Uint8Array.from([11]); - // Login server rejected session. - static NEED_MEMBERS_ACCOUNT = Uint8Array.from([12]); - // You need a members account to login to this world. - static COULD_NOT_COMPLETE = Uint8Array.from([13]); - // Could not complete login. - static SERVER_UPDATING = Uint8Array.from([14]); - // The server is being updated. - static RECONNECTING = Uint8Array.from([15]); - static LOGIN_ATTEMPTS_EXCEEDED = Uint8Array.from([16]); - // Login attempts exceeded. - static STANDING_IN_MEMBERS = Uint8Array.from([17]); - // You are standing in a members-only area. - static STAFF_MOD_LEVEL = Uint8Array.from([18]); -}; -var LoginClient = class { - socket = null; - stream = new NetworkStream(); - async connect() { - if (this.socket) { - return; - } - return new Promise((res) => { - this.socket = net.createConnection({ - port: Environment_default.LOGIN_PORT, - host: Environment_default.LOGIN_HOST - }); - this.socket.setNoDelay(true); - this.socket.setTimeout(1e3); - this.socket.on("data", async (buf) => { - this.stream.received(buf); - }); - this.socket.once("close", () => { - this.disconnect(); - res(); - }); - this.socket.once("error", () => { - this.disconnect(); - res(); - }); - this.socket.once("connect", () => { - res(); - }); - }); - } - disconnect() { - if (this.socket === null) { - return; - } - this.socket.destroy(); - this.socket = null; - this.stream.clear(); - } - async write(socket, opcode, data = null, full = true) { - if (socket === null) { - return; - } - const packet = new Packet(new Uint8Array(1 + 2 + (data !== null ? data?.length : 0))); - packet.p1(opcode); - if (data !== null) { - packet.p2(data.length); - packet.pdata(data, 0, data.length); - } else { - packet.p2(0); - } - const done = socket.write(packet.data); - if (!done && full) { - await new Promise((res) => { - const interval = setInterval(() => { - if (socket === null || socket.closed) { - clearInterval(interval); - res(); - } - }, 100); - socket.once("drain", () => { - clearInterval(interval); - res(); - }); - }); - } - } - async load(username37, password, uid) { - await this.connect(); - if (this.socket === null) { - return { reply: -1, data: null }; - } - const request = new Packet(new Uint8Array(2 + 8 + password.length + 1 + 4)); - request.p2(Environment_default.NODE_ID); - request.p8(username37); - request.pjstr(password); - request.p4(uid); - await this.write(this.socket, 1, request.data); - const reply = await this.stream.readByte(this.socket); - if (reply !== 1) { - this.disconnect(); - return { reply, data: null }; - } - const data = new Packet(new Uint8Array(2)); - await this.stream.readBytes(this.socket, data, 0, 2); - const length = data.g2(); - const data2 = new Packet(new Uint8Array(length)); - await this.stream.readBytes(this.socket, data2, 0, length); - this.disconnect(); - return { reply, data: data2 }; - } - async save(username37, save) { - await this.connect(); - if (this.socket === null) { - return -1; - } - const request = new Packet(new Uint8Array(2 + 8 + 2 + save.length)); - request.p2(Environment_default.NODE_ID); - request.p8(username37); - request.p2(save.length); - request.pdata(save, 0, save.length); - await this.write(this.socket, 2, request.data); - const reply = await this.stream.readByte(this.socket); - this.disconnect(); - return reply; - } - async reset() { - await this.connect(); - if (this.socket === null) { - return -1; - } - const request = new Packet(new Uint8Array(2)); - request.p2(Environment_default.NODE_ID); - await this.write(this.socket, 3, request.data); - this.disconnect(); - } - async count(world) { - await this.connect(); - if (this.socket === null) { - return -1; - } - const request = new Packet(new Uint8Array(2)); - request.p2(world); - await this.write(this.socket, 4, request.data); - const reply = new Packet(new Uint8Array(2)); - await this.stream.readBytes(this.socket, reply, 0, 2); - const count = reply.g2(); - this.disconnect(); - return count; - } - async heartbeat(players) { - await this.connect(); - if (this.socket === null) { - return -1; - } - const request = new Packet(new Uint8Array(2 + 2 + players.length * 8)); - request.p2(Environment_default.NODE_ID); - request.p2(players.length); - for (const player of players) { - request.p8(player); - } - await this.write(this.socket, 5, request.data); - this.disconnect(); - } -}; - -// src/lostcity/server/LoginThread.ts -if (typeof self === "undefined") { - if (!parentPort) throw new Error("This file must be run as a worker thread."); - const priv = import_node_forge2.default.pki.privateKeyFromPem(fs3.readFileSync("data/config/private.pem", "ascii")); - parentPort.on("message", async (msg) => { - try { - if (!parentPort) throw new Error("This file must be run as a worker thread."); - await handleRequests(parentPort, msg, priv); - } catch (err) { - console.error(err); - } - }); -} else { - const priv = import_node_forge2.default.pki.privateKeyFromPem(await (await fetch("data/config/private.pem")).text()); - self.onmessage = async (msg) => { - try { - await handleRequests(self, msg.data, priv); - } catch (err) { - console.error(err); - } - }; -} -async function handleRequests(parentPort2, msg, priv) { - switch (msg.type) { - case "reset": { - if (!Environment_default.LOGIN_KEY) { - return; - } - const login = new LoginClient(); - await login.reset(); - break; - } - case "heartbeat": { - if (!Environment_default.LOGIN_KEY) { - return; - } - const login = new LoginClient(); - await login.heartbeat(msg.players); - break; - } - case "loginreq": { - const { opcode, data, socket } = msg; - const stream = new Packet(data); - const revision = stream.g1(); - if (revision !== 225) { - parentPort2.postMessage({ - type: "loginreply", - status: LoginResponse.SERVER_UPDATED, - socket - }); - return; - } - const info = stream.g1(); - const crcs = new Uint8Array(9 * 4); - stream.gdata(crcs, 0, crcs.length); - stream.rsadec(priv); - if (stream.g1() !== 10) { - parentPort2.postMessage({ - type: "loginreply", - status: LoginResponse.LOGIN_REJECTED, - socket - }); - return; - } - const seed = []; - for (let i = 0; i < 4; i++) { - seed[i] = stream.g4(); - } - const uid = stream.g4(); - const username = stream.gjstr(); - const password = stream.gjstr(); - if (username.length < 1 || username.length > 12) { - parentPort2.postMessage({ - type: "loginreply", - status: LoginResponse.INVALID_USER_OR_PASS, - socket - }); - return; - } - if (Environment_default.LOGIN_KEY) { - if (password.length < 5 || password.length > 20) { - parentPort2.postMessage({ - type: "loginreply", - status: LoginResponse.INVALID_USER_OR_PASS, - socket - }); - return; - } - const login = new LoginClient(); - const request = await login.load(toBase37(toSafeName(username)), password, uid); - if (request.reply === 1 && request.data) { - parentPort2.postMessage({ - type: "loginreply", - status: LoginResponse.SUCCESSFUL, - socket, - info, - seed, - username: toSafeName(username), - save: request.data.data - }); - } else if ((request.reply === 2 || request.reply === 3) && opcode === 16) { - parentPort2.postMessage({ - type: "loginreply", - status: LoginResponse.LOGGED_IN, - socket - }); - return; - } else if (request.reply === 3 && opcode === 18) { - parentPort2.postMessage({ - type: "loginreply", - status: LoginResponse.LOGGED_IN, - socket - }); - return; - } else if (request.reply === 4) { - parentPort2.postMessage({ - type: "loginreply", - status: LoginResponse.SUCCESSFUL, - socket, - info, - seed, - username: toSafeName(username), - save: new Uint8Array() - }); - } else if (request.reply === 5) { - parentPort2.postMessage({ - type: "loginreply", - status: LoginResponse.INVALID_USER_OR_PASS, - socket - }); - return; - } else if (request.reply === -1) { - parentPort2.postMessage({ - type: "loginreply", - status: LoginResponse.LOGIN_SERVER_OFFLINE, - socket - }); - return; - } else { - parentPort2.postMessage({ - type: "loginreply", - status: LoginResponse.LOGIN_REJECTED, - socket - }); - return; - } - } else { - let save = new Uint8Array(); - const safeName = toSafeName(username); - if (typeof self === "undefined") { - if (fs3.existsSync(`data/players/${safeName}.sav`)) { - save = await fsp2.readFile(`data/players/${safeName}.sav`); - } - } else { - const saveFile = await fetch(`data/players/${safeName}.sav`); - if (saveFile.ok) { - save = new Uint8Array(await saveFile.arrayBuffer()); - } - } - parentPort2.postMessage({ - type: "loginreply", - status: LoginResponse.SUCCESSFUL, - socket, - info, - seed, - username: safeName, - save - }); - } - break; - } - case "logout": { - const { username, save } = msg; - if (Environment_default.LOGIN_KEY) { - const login = new LoginClient(); - const reply = await login.save(toBase37(username), save); - if (reply === 0) { - parentPort2.postMessage({ - type: "logoutreply", - username - }); - } - } else { - parentPort2.postMessage({ - type: "logoutreply", - username - }); - } - break; - } - default: - console.error("Unknown message type: " + msg.type); - break; - } -} diff --git a/src/public/worker.js b/src/public/worker.js deleted file mode 100644 index 5b17245f..00000000 --- a/src/public/worker.js +++ /dev/null @@ -1,40296 +0,0 @@ -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { - get: (a, b) => (typeof require !== "undefined" ? require : a)[b] -}) : x)(function(x) { - if (typeof require !== "undefined") return require.apply(this, arguments); - throw Error('Dynamic require of "' + x + '" is not supported'); -}); -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; -}; -var __commonJS = (cb, mod) => function __require2() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); - -// node_modules/node-forge/lib/forge.js -var require_forge = __commonJS({ - "node_modules/node-forge/lib/forge.js"(exports, module) { - module.exports = { - // default options - options: { - usePureJavaScript: false - } - }; - } -}); - -// node_modules/node-forge/lib/baseN.js -var require_baseN = __commonJS({ - "node_modules/node-forge/lib/baseN.js"(exports, module) { - var api = {}; - module.exports = api; - var _reverseAlphabets = {}; - api.encode = function(input, alphabet, maxline) { - if (typeof alphabet !== "string") { - throw new TypeError('"alphabet" must be a string.'); - } - if (maxline !== void 0 && typeof maxline !== "number") { - throw new TypeError('"maxline" must be a number.'); - } - var output = ""; - if (!(input instanceof Uint8Array)) { - output = _encodeWithByteBuffer(input, alphabet); - } else { - var i = 0; - var base = alphabet.length; - var first = alphabet.charAt(0); - var digits = [0]; - for (i = 0; i < input.length; ++i) { - for (var j = 0, carry = input[i]; j < digits.length; ++j) { - carry += digits[j] << 8; - digits[j] = carry % base; - carry = carry / base | 0; - } - while (carry > 0) { - digits.push(carry % base); - carry = carry / base | 0; - } - } - for (i = 0; input[i] === 0 && i < input.length - 1; ++i) { - output += first; - } - for (i = digits.length - 1; i >= 0; --i) { - output += alphabet[digits[i]]; - } - } - if (maxline) { - var regex = new RegExp(".{1," + maxline + "}", "g"); - output = output.match(regex).join("\r\n"); - } - return output; - }; - api.decode = function(input, alphabet) { - if (typeof input !== "string") { - throw new TypeError('"input" must be a string.'); - } - if (typeof alphabet !== "string") { - throw new TypeError('"alphabet" must be a string.'); - } - var table = _reverseAlphabets[alphabet]; - if (!table) { - table = _reverseAlphabets[alphabet] = []; - for (var i = 0; i < alphabet.length; ++i) { - table[alphabet.charCodeAt(i)] = i; - } - } - input = input.replace(/\s/g, ""); - var base = alphabet.length; - var first = alphabet.charAt(0); - var bytes = [0]; - for (var i = 0; i < input.length; i++) { - var value = table[input.charCodeAt(i)]; - if (value === void 0) { - return; - } - for (var j = 0, carry = value; j < bytes.length; ++j) { - carry += bytes[j] * base; - bytes[j] = carry & 255; - carry >>= 8; - } - while (carry > 0) { - bytes.push(carry & 255); - carry >>= 8; - } - } - for (var k = 0; input[k] === first && k < input.length - 1; ++k) { - bytes.push(0); - } - if (typeof Buffer !== "undefined") { - return Buffer.from(bytes.reverse()); - } - return new Uint8Array(bytes.reverse()); - }; - function _encodeWithByteBuffer(input, alphabet) { - var i = 0; - var base = alphabet.length; - var first = alphabet.charAt(0); - var digits = [0]; - for (i = 0; i < input.length(); ++i) { - for (var j = 0, carry = input.at(i); j < digits.length; ++j) { - carry += digits[j] << 8; - digits[j] = carry % base; - carry = carry / base | 0; - } - while (carry > 0) { - digits.push(carry % base); - carry = carry / base | 0; - } - } - var output = ""; - for (i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) { - output += first; - } - for (i = digits.length - 1; i >= 0; --i) { - output += alphabet[digits[i]]; - } - return output; - } - } -}); - -// node_modules/node-forge/lib/util.js -var require_util = __commonJS({ - "node_modules/node-forge/lib/util.js"(exports, module) { - var forge2 = require_forge(); - var baseN = require_baseN(); - var util = module.exports = forge2.util = forge2.util || {}; - (function() { - if (typeof process !== "undefined" && process.nextTick && !process.browser) { - util.nextTick = process.nextTick; - if (typeof setImmediate === "function") { - util.setImmediate = setImmediate; - } else { - util.setImmediate = util.nextTick; - } - return; - } - if (typeof setImmediate === "function") { - util.setImmediate = function() { - return setImmediate.apply(void 0, arguments); - }; - util.nextTick = function(callback) { - return setImmediate(callback); - }; - return; - } - util.setImmediate = function(callback) { - setTimeout(callback, 0); - }; - if (typeof window !== "undefined" && typeof window.postMessage === "function") { - let handler2 = function(event) { - if (event.source === window && event.data === msg) { - event.stopPropagation(); - var copy = callbacks.slice(); - callbacks.length = 0; - copy.forEach(function(callback) { - callback(); - }); - } - }; - var handler = handler2; - var msg = "forge.setImmediate"; - var callbacks = []; - util.setImmediate = function(callback) { - callbacks.push(callback); - if (callbacks.length === 1) { - window.postMessage(msg, "*"); - } - }; - window.addEventListener("message", handler2, true); - } - if (typeof MutationObserver !== "undefined") { - var now = Date.now(); - var attr = true; - var div = document.createElement("div"); - var callbacks = []; - new MutationObserver(function() { - var copy = callbacks.slice(); - callbacks.length = 0; - copy.forEach(function(callback) { - callback(); - }); - }).observe(div, { attributes: true }); - var oldSetImmediate = util.setImmediate; - util.setImmediate = function(callback) { - if (Date.now() - now > 15) { - now = Date.now(); - oldSetImmediate(callback); - } else { - callbacks.push(callback); - if (callbacks.length === 1) { - div.setAttribute("a", attr = !attr); - } - } - }; - } - util.nextTick = util.setImmediate; - })(); - util.isNodejs = typeof process !== "undefined" && process.versions && process.versions.node; - util.globalScope = function() { - if (util.isNodejs) { - return global; - } - return typeof self === "undefined" ? window : self; - }(); - util.isArray = Array.isArray || function(x) { - return Object.prototype.toString.call(x) === "[object Array]"; - }; - util.isArrayBuffer = function(x) { - return typeof ArrayBuffer !== "undefined" && x instanceof ArrayBuffer; - }; - util.isArrayBufferView = function(x) { - return x && util.isArrayBuffer(x.buffer) && x.byteLength !== void 0; - }; - function _checkBitsParam(n) { - if (!(n === 8 || n === 16 || n === 24 || n === 32)) { - throw new Error("Only 8, 16, 24, or 32 bits supported: " + n); - } - } - util.ByteBuffer = ByteStringBuffer; - function ByteStringBuffer(b) { - this.data = ""; - this.read = 0; - if (typeof b === "string") { - this.data = b; - } else if (util.isArrayBuffer(b) || util.isArrayBufferView(b)) { - if (typeof Buffer !== "undefined" && b instanceof Buffer) { - this.data = b.toString("binary"); - } else { - var arr = new Uint8Array(b); - try { - this.data = String.fromCharCode.apply(null, arr); - } catch (e) { - for (var i = 0; i < arr.length; ++i) { - this.putByte(arr[i]); - } - } - } - } else if (b instanceof ByteStringBuffer || typeof b === "object" && typeof b.data === "string" && typeof b.read === "number") { - this.data = b.data; - this.read = b.read; - } - this._constructedStringLength = 0; - } - util.ByteStringBuffer = ByteStringBuffer; - var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; - util.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { - this._constructedStringLength += x; - if (this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { - this.data.substr(0, 1); - this._constructedStringLength = 0; - } - }; - util.ByteStringBuffer.prototype.length = function() { - return this.data.length - this.read; - }; - util.ByteStringBuffer.prototype.isEmpty = function() { - return this.length() <= 0; - }; - util.ByteStringBuffer.prototype.putByte = function(b) { - return this.putBytes(String.fromCharCode(b)); - }; - util.ByteStringBuffer.prototype.fillWithByte = function(b, n) { - b = String.fromCharCode(b); - var d = this.data; - while (n > 0) { - if (n & 1) { - d += b; - } - n >>>= 1; - if (n > 0) { - b += b; - } - } - this.data = d; - this._optimizeConstructedString(n); - return this; - }; - util.ByteStringBuffer.prototype.putBytes = function(bytes) { - this.data += bytes; - this._optimizeConstructedString(bytes.length); - return this; - }; - util.ByteStringBuffer.prototype.putString = function(str) { - return this.putBytes(util.encodeUtf8(str)); - }; - util.ByteStringBuffer.prototype.putInt16 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt24 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt32 = function(i) { - return this.putBytes( - String.fromCharCode(i >> 24 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt16Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt24Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i >> 16 & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt32Le = function(i) { - return this.putBytes( - String.fromCharCode(i & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 24 & 255) - ); - }; - util.ByteStringBuffer.prototype.putInt = function(i, n) { - _checkBitsParam(n); - var bytes = ""; - do { - n -= 8; - bytes += String.fromCharCode(i >> n & 255); - } while (n > 0); - return this.putBytes(bytes); - }; - util.ByteStringBuffer.prototype.putSignedInt = function(i, n) { - if (i < 0) { - i += 2 << n - 1; - } - return this.putInt(i, n); - }; - util.ByteStringBuffer.prototype.putBuffer = function(buffer) { - return this.putBytes(buffer.getBytes()); - }; - util.ByteStringBuffer.prototype.getByte = function() { - return this.data.charCodeAt(this.read++); - }; - util.ByteStringBuffer.prototype.getInt16 = function() { - var rval = this.data.charCodeAt(this.read) << 8 ^ this.data.charCodeAt(this.read + 1); - this.read += 2; - return rval; - }; - util.ByteStringBuffer.prototype.getInt24 = function() { - var rval = this.data.charCodeAt(this.read) << 16 ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2); - this.read += 3; - return rval; - }; - util.ByteStringBuffer.prototype.getInt32 = function() { - var rval = this.data.charCodeAt(this.read) << 24 ^ this.data.charCodeAt(this.read + 1) << 16 ^ this.data.charCodeAt(this.read + 2) << 8 ^ this.data.charCodeAt(this.read + 3); - this.read += 4; - return rval; - }; - util.ByteStringBuffer.prototype.getInt16Le = function() { - var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8; - this.read += 2; - return rval; - }; - util.ByteStringBuffer.prototype.getInt24Le = function() { - var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16; - this.read += 3; - return rval; - }; - util.ByteStringBuffer.prototype.getInt32Le = function() { - var rval = this.data.charCodeAt(this.read) ^ this.data.charCodeAt(this.read + 1) << 8 ^ this.data.charCodeAt(this.read + 2) << 16 ^ this.data.charCodeAt(this.read + 3) << 24; - this.read += 4; - return rval; - }; - util.ByteStringBuffer.prototype.getInt = function(n) { - _checkBitsParam(n); - var rval = 0; - do { - rval = (rval << 8) + this.data.charCodeAt(this.read++); - n -= 8; - } while (n > 0); - return rval; - }; - util.ByteStringBuffer.prototype.getSignedInt = function(n) { - var x = this.getInt(n); - var max = 2 << n - 2; - if (x >= max) { - x -= max << 1; - } - return x; - }; - util.ByteStringBuffer.prototype.getBytes = function(count) { - var rval; - if (count) { - count = Math.min(this.length(), count); - rval = this.data.slice(this.read, this.read + count); - this.read += count; - } else if (count === 0) { - rval = ""; - } else { - rval = this.read === 0 ? this.data : this.data.slice(this.read); - this.clear(); - } - return rval; - }; - util.ByteStringBuffer.prototype.bytes = function(count) { - return typeof count === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count); - }; - util.ByteStringBuffer.prototype.at = function(i) { - return this.data.charCodeAt(this.read + i); - }; - util.ByteStringBuffer.prototype.setAt = function(i, b) { - this.data = this.data.substr(0, this.read + i) + String.fromCharCode(b) + this.data.substr(this.read + i + 1); - return this; - }; - util.ByteStringBuffer.prototype.last = function() { - return this.data.charCodeAt(this.data.length - 1); - }; - util.ByteStringBuffer.prototype.copy = function() { - var c = util.createBuffer(this.data); - c.read = this.read; - return c; - }; - util.ByteStringBuffer.prototype.compact = function() { - if (this.read > 0) { - this.data = this.data.slice(this.read); - this.read = 0; - } - return this; - }; - util.ByteStringBuffer.prototype.clear = function() { - this.data = ""; - this.read = 0; - return this; - }; - util.ByteStringBuffer.prototype.truncate = function(count) { - var len = Math.max(0, this.length() - count); - this.data = this.data.substr(this.read, len); - this.read = 0; - return this; - }; - util.ByteStringBuffer.prototype.toHex = function() { - var rval = ""; - for (var i = this.read; i < this.data.length; ++i) { - var b = this.data.charCodeAt(i); - if (b < 16) { - rval += "0"; - } - rval += b.toString(16); - } - return rval; - }; - util.ByteStringBuffer.prototype.toString = function() { - return util.decodeUtf8(this.bytes()); - }; - function DataBuffer(b, options) { - options = options || {}; - this.read = options.readOffset || 0; - this.growSize = options.growSize || 1024; - var isArrayBuffer = util.isArrayBuffer(b); - var isArrayBufferView = util.isArrayBufferView(b); - if (isArrayBuffer || isArrayBufferView) { - if (isArrayBuffer) { - this.data = new DataView(b); - } else { - this.data = new DataView(b.buffer, b.byteOffset, b.byteLength); - } - this.write = "writeOffset" in options ? options.writeOffset : this.data.byteLength; - return; - } - this.data = new DataView(new ArrayBuffer(0)); - this.write = 0; - if (b !== null && b !== void 0) { - this.putBytes(b); - } - if ("writeOffset" in options) { - this.write = options.writeOffset; - } - } - util.DataBuffer = DataBuffer; - util.DataBuffer.prototype.length = function() { - return this.write - this.read; - }; - util.DataBuffer.prototype.isEmpty = function() { - return this.length() <= 0; - }; - util.DataBuffer.prototype.accommodate = function(amount, growSize) { - if (this.length() >= amount) { - return this; - } - growSize = Math.max(growSize || this.growSize, amount); - var src = new Uint8Array( - this.data.buffer, - this.data.byteOffset, - this.data.byteLength - ); - var dst = new Uint8Array(this.length() + growSize); - dst.set(src); - this.data = new DataView(dst.buffer); - return this; - }; - util.DataBuffer.prototype.putByte = function(b) { - this.accommodate(1); - this.data.setUint8(this.write++, b); - return this; - }; - util.DataBuffer.prototype.fillWithByte = function(b, n) { - this.accommodate(n); - for (var i = 0; i < n; ++i) { - this.data.setUint8(b); - } - return this; - }; - util.DataBuffer.prototype.putBytes = function(bytes, encoding) { - if (util.isArrayBufferView(bytes)) { - var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); - var len = src.byteLength - src.byteOffset; - this.accommodate(len); - var dst = new Uint8Array(this.data.buffer, this.write); - dst.set(src); - this.write += len; - return this; - } - if (util.isArrayBuffer(bytes)) { - var src = new Uint8Array(bytes); - this.accommodate(src.byteLength); - var dst = new Uint8Array(this.data.buffer); - dst.set(src, this.write); - this.write += src.byteLength; - return this; - } - if (bytes instanceof util.DataBuffer || typeof bytes === "object" && typeof bytes.read === "number" && typeof bytes.write === "number" && util.isArrayBufferView(bytes.data)) { - var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); - this.accommodate(src.byteLength); - var dst = new Uint8Array(bytes.data.byteLength, this.write); - dst.set(src); - this.write += src.byteLength; - return this; - } - if (bytes instanceof util.ByteStringBuffer) { - bytes = bytes.data; - encoding = "binary"; - } - encoding = encoding || "binary"; - if (typeof bytes === "string") { - var view; - if (encoding === "hex") { - this.accommodate(Math.ceil(bytes.length / 2)); - view = new Uint8Array(this.data.buffer, this.write); - this.write += util.binary.hex.decode(bytes, view, this.write); - return this; - } - if (encoding === "base64") { - this.accommodate(Math.ceil(bytes.length / 4) * 3); - view = new Uint8Array(this.data.buffer, this.write); - this.write += util.binary.base64.decode(bytes, view, this.write); - return this; - } - if (encoding === "utf8") { - bytes = util.encodeUtf8(bytes); - encoding = "binary"; - } - if (encoding === "binary" || encoding === "raw") { - this.accommodate(bytes.length); - view = new Uint8Array(this.data.buffer, this.write); - this.write += util.binary.raw.decode(view); - return this; - } - if (encoding === "utf16") { - this.accommodate(bytes.length * 2); - view = new Uint16Array(this.data.buffer, this.write); - this.write += util.text.utf16.encode(view); - return this; - } - throw new Error("Invalid encoding: " + encoding); - } - throw Error("Invalid parameter: " + bytes); - }; - util.DataBuffer.prototype.putBuffer = function(buffer) { - this.putBytes(buffer); - buffer.clear(); - return this; - }; - util.DataBuffer.prototype.putString = function(str) { - return this.putBytes(str, "utf16"); - }; - util.DataBuffer.prototype.putInt16 = function(i) { - this.accommodate(2); - this.data.setInt16(this.write, i); - this.write += 2; - return this; - }; - util.DataBuffer.prototype.putInt24 = function(i) { - this.accommodate(3); - this.data.setInt16(this.write, i >> 8 & 65535); - this.data.setInt8(this.write, i >> 16 & 255); - this.write += 3; - return this; - }; - util.DataBuffer.prototype.putInt32 = function(i) { - this.accommodate(4); - this.data.setInt32(this.write, i); - this.write += 4; - return this; - }; - util.DataBuffer.prototype.putInt16Le = function(i) { - this.accommodate(2); - this.data.setInt16(this.write, i, true); - this.write += 2; - return this; - }; - util.DataBuffer.prototype.putInt24Le = function(i) { - this.accommodate(3); - this.data.setInt8(this.write, i >> 16 & 255); - this.data.setInt16(this.write, i >> 8 & 65535, true); - this.write += 3; - return this; - }; - util.DataBuffer.prototype.putInt32Le = function(i) { - this.accommodate(4); - this.data.setInt32(this.write, i, true); - this.write += 4; - return this; - }; - util.DataBuffer.prototype.putInt = function(i, n) { - _checkBitsParam(n); - this.accommodate(n / 8); - do { - n -= 8; - this.data.setInt8(this.write++, i >> n & 255); - } while (n > 0); - return this; - }; - util.DataBuffer.prototype.putSignedInt = function(i, n) { - _checkBitsParam(n); - this.accommodate(n / 8); - if (i < 0) { - i += 2 << n - 1; - } - return this.putInt(i, n); - }; - util.DataBuffer.prototype.getByte = function() { - return this.data.getInt8(this.read++); - }; - util.DataBuffer.prototype.getInt16 = function() { - var rval = this.data.getInt16(this.read); - this.read += 2; - return rval; - }; - util.DataBuffer.prototype.getInt24 = function() { - var rval = this.data.getInt16(this.read) << 8 ^ this.data.getInt8(this.read + 2); - this.read += 3; - return rval; - }; - util.DataBuffer.prototype.getInt32 = function() { - var rval = this.data.getInt32(this.read); - this.read += 4; - return rval; - }; - util.DataBuffer.prototype.getInt16Le = function() { - var rval = this.data.getInt16(this.read, true); - this.read += 2; - return rval; - }; - util.DataBuffer.prototype.getInt24Le = function() { - var rval = this.data.getInt8(this.read) ^ this.data.getInt16(this.read + 1, true) << 8; - this.read += 3; - return rval; - }; - util.DataBuffer.prototype.getInt32Le = function() { - var rval = this.data.getInt32(this.read, true); - this.read += 4; - return rval; - }; - util.DataBuffer.prototype.getInt = function(n) { - _checkBitsParam(n); - var rval = 0; - do { - rval = (rval << 8) + this.data.getInt8(this.read++); - n -= 8; - } while (n > 0); - return rval; - }; - util.DataBuffer.prototype.getSignedInt = function(n) { - var x = this.getInt(n); - var max = 2 << n - 2; - if (x >= max) { - x -= max << 1; - } - return x; - }; - util.DataBuffer.prototype.getBytes = function(count) { - var rval; - if (count) { - count = Math.min(this.length(), count); - rval = this.data.slice(this.read, this.read + count); - this.read += count; - } else if (count === 0) { - rval = ""; - } else { - rval = this.read === 0 ? this.data : this.data.slice(this.read); - this.clear(); - } - return rval; - }; - util.DataBuffer.prototype.bytes = function(count) { - return typeof count === "undefined" ? this.data.slice(this.read) : this.data.slice(this.read, this.read + count); - }; - util.DataBuffer.prototype.at = function(i) { - return this.data.getUint8(this.read + i); - }; - util.DataBuffer.prototype.setAt = function(i, b) { - this.data.setUint8(i, b); - return this; - }; - util.DataBuffer.prototype.last = function() { - return this.data.getUint8(this.write - 1); - }; - util.DataBuffer.prototype.copy = function() { - return new util.DataBuffer(this); - }; - util.DataBuffer.prototype.compact = function() { - if (this.read > 0) { - var src = new Uint8Array(this.data.buffer, this.read); - var dst = new Uint8Array(src.byteLength); - dst.set(src); - this.data = new DataView(dst); - this.write -= this.read; - this.read = 0; - } - return this; - }; - util.DataBuffer.prototype.clear = function() { - this.data = new DataView(new ArrayBuffer(0)); - this.read = this.write = 0; - return this; - }; - util.DataBuffer.prototype.truncate = function(count) { - this.write = Math.max(0, this.length() - count); - this.read = Math.min(this.read, this.write); - return this; - }; - util.DataBuffer.prototype.toHex = function() { - var rval = ""; - for (var i = this.read; i < this.data.byteLength; ++i) { - var b = this.data.getUint8(i); - if (b < 16) { - rval += "0"; - } - rval += b.toString(16); - } - return rval; - }; - util.DataBuffer.prototype.toString = function(encoding) { - var view = new Uint8Array(this.data, this.read, this.length()); - encoding = encoding || "utf8"; - if (encoding === "binary" || encoding === "raw") { - return util.binary.raw.encode(view); - } - if (encoding === "hex") { - return util.binary.hex.encode(view); - } - if (encoding === "base64") { - return util.binary.base64.encode(view); - } - if (encoding === "utf8") { - return util.text.utf8.decode(view); - } - if (encoding === "utf16") { - return util.text.utf16.decode(view); - } - throw new Error("Invalid encoding: " + encoding); - }; - util.createBuffer = function(input, encoding) { - encoding = encoding || "raw"; - if (input !== void 0 && encoding === "utf8") { - input = util.encodeUtf8(input); - } - return new util.ByteBuffer(input); - }; - util.fillString = function(c, n) { - var s = ""; - while (n > 0) { - if (n & 1) { - s += c; - } - n >>>= 1; - if (n > 0) { - c += c; - } - } - return s; - }; - util.xorBytes = function(s1, s2, n) { - var s3 = ""; - var b = ""; - var t = ""; - var i = 0; - var c = 0; - for (; n > 0; --n, ++i) { - b = s1.charCodeAt(i) ^ s2.charCodeAt(i); - if (c >= 10) { - s3 += t; - t = ""; - c = 0; - } - t += String.fromCharCode(b); - ++c; - } - s3 += t; - return s3; - }; - util.hexToBytes = function(hex) { - var rval = ""; - var i = 0; - if (hex.length & true) { - i = 1; - rval += String.fromCharCode(parseInt(hex[0], 16)); - } - for (; i < hex.length; i += 2) { - rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); - } - return rval; - }; - util.bytesToHex = function(bytes) { - return util.createBuffer(bytes).toHex(); - }; - util.int32ToBytes = function(i) { - return String.fromCharCode(i >> 24 & 255) + String.fromCharCode(i >> 16 & 255) + String.fromCharCode(i >> 8 & 255) + String.fromCharCode(i & 255); - }; - var _base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - var _base64Idx = [ - /*43 -43 = 0*/ - /*'+', 1, 2, 3,'/' */ - 62, - -1, - -1, - -1, - 63, - /*'0','1','2','3','4','5','6','7','8','9' */ - 52, - 53, - 54, - 55, - 56, - 57, - 58, - 59, - 60, - 61, - /*15, 16, 17,'=', 19, 20, 21 */ - -1, - -1, - -1, - 64, - -1, - -1, - -1, - /*65 - 43 = 22*/ - /*'A','B','C','D','E','F','G','H','I','J','K','L','M', */ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - /*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */ - 13, - 14, - 15, - 16, - 17, - 18, - 19, - 20, - 21, - 22, - 23, - 24, - 25, - /*91 - 43 = 48 */ - /*48, 49, 50, 51, 52, 53 */ - -1, - -1, - -1, - -1, - -1, - -1, - /*97 - 43 = 54*/ - /*'a','b','c','d','e','f','g','h','i','j','k','l','m' */ - 26, - 27, - 28, - 29, - 30, - 31, - 32, - 33, - 34, - 35, - 36, - 37, - 38, - /*'n','o','p','q','r','s','t','u','v','w','x','y','z' */ - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 46, - 47, - 48, - 49, - 50, - 51 - ]; - var _base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; - util.encode64 = function(input, maxline) { - var line = ""; - var output = ""; - var chr1, chr2, chr3; - var i = 0; - while (i < input.length) { - chr1 = input.charCodeAt(i++); - chr2 = input.charCodeAt(i++); - chr3 = input.charCodeAt(i++); - line += _base64.charAt(chr1 >> 2); - line += _base64.charAt((chr1 & 3) << 4 | chr2 >> 4); - if (isNaN(chr2)) { - line += "=="; - } else { - line += _base64.charAt((chr2 & 15) << 2 | chr3 >> 6); - line += isNaN(chr3) ? "=" : _base64.charAt(chr3 & 63); - } - if (maxline && line.length > maxline) { - output += line.substr(0, maxline) + "\r\n"; - line = line.substr(maxline); - } - } - output += line; - return output; - }; - util.decode64 = function(input) { - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); - var output = ""; - var enc1, enc2, enc3, enc4; - var i = 0; - while (i < input.length) { - enc1 = _base64Idx[input.charCodeAt(i++) - 43]; - enc2 = _base64Idx[input.charCodeAt(i++) - 43]; - enc3 = _base64Idx[input.charCodeAt(i++) - 43]; - enc4 = _base64Idx[input.charCodeAt(i++) - 43]; - output += String.fromCharCode(enc1 << 2 | enc2 >> 4); - if (enc3 !== 64) { - output += String.fromCharCode((enc2 & 15) << 4 | enc3 >> 2); - if (enc4 !== 64) { - output += String.fromCharCode((enc3 & 3) << 6 | enc4); - } - } - } - return output; - }; - util.encodeUtf8 = function(str) { - return unescape(encodeURIComponent(str)); - }; - util.decodeUtf8 = function(str) { - return decodeURIComponent(escape(str)); - }; - util.binary = { - raw: {}, - hex: {}, - base64: {}, - base58: {}, - baseN: { - encode: baseN.encode, - decode: baseN.decode - } - }; - util.binary.raw.encode = function(bytes) { - return String.fromCharCode.apply(null, bytes); - }; - util.binary.raw.decode = function(str, output, offset) { - var out = output; - if (!out) { - out = new Uint8Array(str.length); - } - offset = offset || 0; - var j = offset; - for (var i = 0; i < str.length; ++i) { - out[j++] = str.charCodeAt(i); - } - return output ? j - offset : out; - }; - util.binary.hex.encode = util.bytesToHex; - util.binary.hex.decode = function(hex, output, offset) { - var out = output; - if (!out) { - out = new Uint8Array(Math.ceil(hex.length / 2)); - } - offset = offset || 0; - var i = 0, j = offset; - if (hex.length & 1) { - i = 1; - out[j++] = parseInt(hex[0], 16); - } - for (; i < hex.length; i += 2) { - out[j++] = parseInt(hex.substr(i, 2), 16); - } - return output ? j - offset : out; - }; - util.binary.base64.encode = function(input, maxline) { - var line = ""; - var output = ""; - var chr1, chr2, chr3; - var i = 0; - while (i < input.byteLength) { - chr1 = input[i++]; - chr2 = input[i++]; - chr3 = input[i++]; - line += _base64.charAt(chr1 >> 2); - line += _base64.charAt((chr1 & 3) << 4 | chr2 >> 4); - if (isNaN(chr2)) { - line += "=="; - } else { - line += _base64.charAt((chr2 & 15) << 2 | chr3 >> 6); - line += isNaN(chr3) ? "=" : _base64.charAt(chr3 & 63); - } - if (maxline && line.length > maxline) { - output += line.substr(0, maxline) + "\r\n"; - line = line.substr(maxline); - } - } - output += line; - return output; - }; - util.binary.base64.decode = function(input, output, offset) { - var out = output; - if (!out) { - out = new Uint8Array(Math.ceil(input.length / 4) * 3); - } - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); - offset = offset || 0; - var enc1, enc2, enc3, enc4; - var i = 0, j = offset; - while (i < input.length) { - enc1 = _base64Idx[input.charCodeAt(i++) - 43]; - enc2 = _base64Idx[input.charCodeAt(i++) - 43]; - enc3 = _base64Idx[input.charCodeAt(i++) - 43]; - enc4 = _base64Idx[input.charCodeAt(i++) - 43]; - out[j++] = enc1 << 2 | enc2 >> 4; - if (enc3 !== 64) { - out[j++] = (enc2 & 15) << 4 | enc3 >> 2; - if (enc4 !== 64) { - out[j++] = (enc3 & 3) << 6 | enc4; - } - } - } - return output ? j - offset : out.subarray(0, j); - }; - util.binary.base58.encode = function(input, maxline) { - return util.binary.baseN.encode(input, _base58, maxline); - }; - util.binary.base58.decode = function(input, maxline) { - return util.binary.baseN.decode(input, _base58, maxline); - }; - util.text = { - utf8: {}, - utf16: {} - }; - util.text.utf8.encode = function(str, output, offset) { - str = util.encodeUtf8(str); - var out = output; - if (!out) { - out = new Uint8Array(str.length); - } - offset = offset || 0; - var j = offset; - for (var i = 0; i < str.length; ++i) { - out[j++] = str.charCodeAt(i); - } - return output ? j - offset : out; - }; - util.text.utf8.decode = function(bytes) { - return util.decodeUtf8(String.fromCharCode.apply(null, bytes)); - }; - util.text.utf16.encode = function(str, output, offset) { - var out = output; - if (!out) { - out = new Uint8Array(str.length * 2); - } - var view = new Uint16Array(out.buffer); - offset = offset || 0; - var j = offset; - var k = offset; - for (var i = 0; i < str.length; ++i) { - view[k++] = str.charCodeAt(i); - j += 2; - } - return output ? j - offset : out; - }; - util.text.utf16.decode = function(bytes) { - return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); - }; - util.deflate = function(api, bytes, raw) { - bytes = util.decode64(api.deflate(util.encode64(bytes)).rval); - if (raw) { - var start = 2; - var flg = bytes.charCodeAt(1); - if (flg & 32) { - start = 6; - } - bytes = bytes.substring(start, bytes.length - 4); - } - return bytes; - }; - util.inflate = function(api, bytes, raw) { - var rval = api.inflate(util.encode64(bytes)).rval; - return rval === null ? null : util.decode64(rval); - }; - var _setStorageObject = function(api, id, obj) { - if (!api) { - throw new Error("WebStorage not available."); - } - var rval; - if (obj === null) { - rval = api.removeItem(id); - } else { - obj = util.encode64(JSON.stringify(obj)); - rval = api.setItem(id, obj); - } - if (typeof rval !== "undefined" && rval.rval !== true) { - var error = new Error(rval.error.message); - error.id = rval.error.id; - error.name = rval.error.name; - throw error; - } - }; - var _getStorageObject = function(api, id) { - if (!api) { - throw new Error("WebStorage not available."); - } - var rval = api.getItem(id); - if (api.init) { - if (rval.rval === null) { - if (rval.error) { - var error = new Error(rval.error.message); - error.id = rval.error.id; - error.name = rval.error.name; - throw error; - } - rval = null; - } else { - rval = rval.rval; - } - } - if (rval !== null) { - rval = JSON.parse(util.decode64(rval)); - } - return rval; - }; - var _setItem = function(api, id, key, data) { - var obj = _getStorageObject(api, id); - if (obj === null) { - obj = {}; - } - obj[key] = data; - _setStorageObject(api, id, obj); - }; - var _getItem = function(api, id, key) { - var rval = _getStorageObject(api, id); - if (rval !== null) { - rval = key in rval ? rval[key] : null; - } - return rval; - }; - var _removeItem = function(api, id, key) { - var obj = _getStorageObject(api, id); - if (obj !== null && key in obj) { - delete obj[key]; - var empty = true; - for (var prop in obj) { - empty = false; - break; - } - if (empty) { - obj = null; - } - _setStorageObject(api, id, obj); - } - }; - var _clearItems = function(api, id) { - _setStorageObject(api, id, null); - }; - var _callStorageFunction = function(func, args, location) { - var rval = null; - if (typeof location === "undefined") { - location = ["web", "flash"]; - } - var type; - var done = false; - var exception = null; - for (var idx in location) { - type = location[idx]; - try { - if (type === "flash" || type === "both") { - if (args[0] === null) { - throw new Error("Flash local storage not available."); - } - rval = func.apply(this, args); - done = type === "flash"; - } - if (type === "web" || type === "both") { - args[0] = localStorage; - rval = func.apply(this, args); - done = true; - } - } catch (ex) { - exception = ex; - } - if (done) { - break; - } - } - if (!done) { - throw exception; - } - return rval; - }; - util.setItem = function(api, id, key, data, location) { - _callStorageFunction(_setItem, arguments, location); - }; - util.getItem = function(api, id, key, location) { - return _callStorageFunction(_getItem, arguments, location); - }; - util.removeItem = function(api, id, key, location) { - _callStorageFunction(_removeItem, arguments, location); - }; - util.clearItems = function(api, id, location) { - _callStorageFunction(_clearItems, arguments, location); - }; - util.isEmpty = function(obj) { - for (var prop in obj) { - if (obj.hasOwnProperty(prop)) { - return false; - } - } - return true; - }; - util.format = function(format) { - var re = /%./g; - var match; - var part; - var argi = 0; - var parts = []; - var last = 0; - while (match = re.exec(format)) { - part = format.substring(last, re.lastIndex - 2); - if (part.length > 0) { - parts.push(part); - } - last = re.lastIndex; - var code = match[0][1]; - switch (code) { - case "s": - case "o": - if (argi < arguments.length) { - parts.push(arguments[argi++ + 1]); - } else { - parts.push(""); - } - break; - case "%": - parts.push("%"); - break; - default: - parts.push("<%" + code + "?>"); - } - } - parts.push(format.substring(last)); - return parts.join(""); - }; - util.formatNumber = function(number, decimals, dec_point, thousands_sep) { - var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; - var d = dec_point === void 0 ? "," : dec_point; - var t = thousands_sep === void 0 ? "." : thousands_sep, s = n < 0 ? "-" : ""; - var i = parseInt(n = Math.abs(+n || 0).toFixed(c), 10) + ""; - var j = i.length > 3 ? i.length % 3 : 0; - return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); - }; - util.formatSize = function(size) { - if (size >= 1073741824) { - size = util.formatNumber(size / 1073741824, 2, ".", "") + " GiB"; - } else if (size >= 1048576) { - size = util.formatNumber(size / 1048576, 2, ".", "") + " MiB"; - } else if (size >= 1024) { - size = util.formatNumber(size / 1024, 0) + " KiB"; - } else { - size = util.formatNumber(size, 0) + " bytes"; - } - return size; - }; - util.bytesFromIP = function(ip) { - if (ip.indexOf(".") !== -1) { - return util.bytesFromIPv4(ip); - } - if (ip.indexOf(":") !== -1) { - return util.bytesFromIPv6(ip); - } - return null; - }; - util.bytesFromIPv4 = function(ip) { - ip = ip.split("."); - if (ip.length !== 4) { - return null; - } - var b = util.createBuffer(); - for (var i = 0; i < ip.length; ++i) { - var num = parseInt(ip[i], 10); - if (isNaN(num)) { - return null; - } - b.putByte(num); - } - return b.getBytes(); - }; - util.bytesFromIPv6 = function(ip) { - var blanks = 0; - ip = ip.split(":").filter(function(e) { - if (e.length === 0) ++blanks; - return true; - }); - var zeros = (8 - ip.length + blanks) * 2; - var b = util.createBuffer(); - for (var i = 0; i < 8; ++i) { - if (!ip[i] || ip[i].length === 0) { - b.fillWithByte(0, zeros); - zeros = 0; - continue; - } - var bytes = util.hexToBytes(ip[i]); - if (bytes.length < 2) { - b.putByte(0); - } - b.putBytes(bytes); - } - return b.getBytes(); - }; - util.bytesToIP = function(bytes) { - if (bytes.length === 4) { - return util.bytesToIPv4(bytes); - } - if (bytes.length === 16) { - return util.bytesToIPv6(bytes); - } - return null; - }; - util.bytesToIPv4 = function(bytes) { - if (bytes.length !== 4) { - return null; - } - var ip = []; - for (var i = 0; i < bytes.length; ++i) { - ip.push(bytes.charCodeAt(i)); - } - return ip.join("."); - }; - util.bytesToIPv6 = function(bytes) { - if (bytes.length !== 16) { - return null; - } - var ip = []; - var zeroGroups = []; - var zeroMaxGroup = 0; - for (var i = 0; i < bytes.length; i += 2) { - var hex = util.bytesToHex(bytes[i] + bytes[i + 1]); - while (hex[0] === "0" && hex !== "0") { - hex = hex.substr(1); - } - if (hex === "0") { - var last = zeroGroups[zeroGroups.length - 1]; - var idx = ip.length; - if (!last || idx !== last.end + 1) { - zeroGroups.push({ start: idx, end: idx }); - } else { - last.end = idx; - if (last.end - last.start > zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start) { - zeroMaxGroup = zeroGroups.length - 1; - } - } - } - ip.push(hex); - } - if (zeroGroups.length > 0) { - var group = zeroGroups[zeroMaxGroup]; - if (group.end - group.start > 0) { - ip.splice(group.start, group.end - group.start + 1, ""); - if (group.start === 0) { - ip.unshift(""); - } - if (group.end === 7) { - ip.push(""); - } - } - } - return ip.join(":"); - }; - util.estimateCores = function(options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; - } - options = options || {}; - if ("cores" in util && !options.update) { - return callback(null, util.cores); - } - if (typeof navigator !== "undefined" && "hardwareConcurrency" in navigator && navigator.hardwareConcurrency > 0) { - util.cores = navigator.hardwareConcurrency; - return callback(null, util.cores); - } - if (typeof Worker === "undefined") { - util.cores = 1; - return callback(null, util.cores); - } - if (typeof Blob === "undefined") { - util.cores = 2; - return callback(null, util.cores); - } - var blobUrl = URL.createObjectURL(new Blob([ - "(", - function() { - self.addEventListener("message", function(e) { - var st = Date.now(); - var et = st + 4; - while (Date.now() < et) ; - self.postMessage({ st, et }); - }); - }.toString(), - ")()" - ], { type: "application/javascript" })); - sample([], 5, 16); - function sample(max, samples, numWorkers) { - if (samples === 0) { - var avg = Math.floor(max.reduce(function(avg2, x) { - return avg2 + x; - }, 0) / max.length); - util.cores = Math.max(1, avg); - URL.revokeObjectURL(blobUrl); - return callback(null, util.cores); - } - map(numWorkers, function(err, results) { - max.push(reduce(numWorkers, results)); - sample(max, samples - 1, numWorkers); - }); - } - function map(numWorkers, callback2) { - var workers = []; - var results = []; - for (var i = 0; i < numWorkers; ++i) { - var worker = new Worker(blobUrl); - worker.addEventListener("message", function(e) { - results.push(e.data); - if (results.length === numWorkers) { - for (var i2 = 0; i2 < numWorkers; ++i2) { - workers[i2].terminate(); - } - callback2(null, results); - } - }); - workers.push(worker); - } - for (var i = 0; i < numWorkers; ++i) { - workers[i].postMessage(i); - } - } - function reduce(numWorkers, results) { - var overlaps = []; - for (var n = 0; n < numWorkers; ++n) { - var r1 = results[n]; - var overlap = overlaps[n] = []; - for (var i = 0; i < numWorkers; ++i) { - if (n === i) { - continue; - } - var r2 = results[i]; - if (r1.st > r2.st && r1.st < r2.et || r2.st > r1.st && r2.st < r1.et) { - overlap.push(i); - } - } - } - return overlaps.reduce(function(max, overlap2) { - return Math.max(max, overlap2.length); - }, 0); - } - }; - } -}); - -// node_modules/node-forge/lib/cipher.js -var require_cipher = __commonJS({ - "node_modules/node-forge/lib/cipher.js"(exports, module) { - var forge2 = require_forge(); - require_util(); - module.exports = forge2.cipher = forge2.cipher || {}; - forge2.cipher.algorithms = forge2.cipher.algorithms || {}; - forge2.cipher.createCipher = function(algorithm, key) { - var api = algorithm; - if (typeof api === "string") { - api = forge2.cipher.getAlgorithm(api); - if (api) { - api = api(); - } - } - if (!api) { - throw new Error("Unsupported algorithm: " + algorithm); - } - return new forge2.cipher.BlockCipher({ - algorithm: api, - key, - decrypt: false - }); - }; - forge2.cipher.createDecipher = function(algorithm, key) { - var api = algorithm; - if (typeof api === "string") { - api = forge2.cipher.getAlgorithm(api); - if (api) { - api = api(); - } - } - if (!api) { - throw new Error("Unsupported algorithm: " + algorithm); - } - return new forge2.cipher.BlockCipher({ - algorithm: api, - key, - decrypt: true - }); - }; - forge2.cipher.registerAlgorithm = function(name, algorithm) { - name = name.toUpperCase(); - forge2.cipher.algorithms[name] = algorithm; - }; - forge2.cipher.getAlgorithm = function(name) { - name = name.toUpperCase(); - if (name in forge2.cipher.algorithms) { - return forge2.cipher.algorithms[name]; - } - return null; - }; - var BlockCipher = forge2.cipher.BlockCipher = function(options) { - this.algorithm = options.algorithm; - this.mode = this.algorithm.mode; - this.blockSize = this.mode.blockSize; - this._finish = false; - this._input = null; - this.output = null; - this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt; - this._decrypt = options.decrypt; - this.algorithm.initialize(options); - }; - BlockCipher.prototype.start = function(options) { - options = options || {}; - var opts = {}; - for (var key in options) { - opts[key] = options[key]; - } - opts.decrypt = this._decrypt; - this._finish = false; - this._input = forge2.util.createBuffer(); - this.output = options.output || forge2.util.createBuffer(); - this.mode.start(opts); - }; - BlockCipher.prototype.update = function(input) { - if (input) { - this._input.putBuffer(input); - } - while (!this._op.call(this.mode, this._input, this.output, this._finish) && !this._finish) { - } - this._input.compact(); - }; - BlockCipher.prototype.finish = function(pad) { - if (pad && (this.mode.name === "ECB" || this.mode.name === "CBC")) { - this.mode.pad = function(input) { - return pad(this.blockSize, input, false); - }; - this.mode.unpad = function(output) { - return pad(this.blockSize, output, true); - }; - } - var options = {}; - options.decrypt = this._decrypt; - options.overflow = this._input.length() % this.blockSize; - if (!this._decrypt && this.mode.pad) { - if (!this.mode.pad(this._input, options)) { - return false; - } - } - this._finish = true; - this.update(); - if (this._decrypt && this.mode.unpad) { - if (!this.mode.unpad(this.output, options)) { - return false; - } - } - if (this.mode.afterFinish) { - if (!this.mode.afterFinish(this.output, options)) { - return false; - } - } - return true; - }; - } -}); - -// node_modules/node-forge/lib/cipherModes.js -var require_cipherModes = __commonJS({ - "node_modules/node-forge/lib/cipherModes.js"(exports, module) { - var forge2 = require_forge(); - require_util(); - forge2.cipher = forge2.cipher || {}; - var modes = module.exports = forge2.cipher.modes = forge2.cipher.modes || {}; - modes.ecb = function(options) { - options = options || {}; - this.name = "ECB"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); - }; - modes.ecb.prototype.start = function(options) { - }; - modes.ecb.prototype.encrypt = function(input, output, finish) { - if (input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } - this.cipher.encrypt(this._inBlock, this._outBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); - } - }; - modes.ecb.prototype.decrypt = function(input, output, finish) { - if (input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } - this.cipher.decrypt(this._inBlock, this._outBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); - } - }; - modes.ecb.prototype.pad = function(input, options) { - var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length(); - input.fillWithByte(padding, padding); - return true; - }; - modes.ecb.prototype.unpad = function(output, options) { - if (options.overflow > 0) { - return false; - } - var len = output.length(); - var count = output.at(len - 1); - if (count > this.blockSize << 2) { - return false; - } - output.truncate(count); - return true; - }; - modes.cbc = function(options) { - options = options || {}; - this.name = "CBC"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); - }; - modes.cbc.prototype.start = function(options) { - if (options.iv === null) { - if (!this._prev) { - throw new Error("Invalid IV parameter."); - } - this._iv = this._prev.slice(0); - } else if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } else { - this._iv = transformIV(options.iv, this.blockSize); - this._prev = this._iv.slice(0); - } - }; - modes.cbc.prototype.encrypt = function(input, output, finish) { - if (input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._prev[i] ^ input.getInt32(); - } - this.cipher.encrypt(this._inBlock, this._outBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i]); - } - this._prev = this._outBlock; - }; - modes.cbc.prototype.decrypt = function(input, output, finish) { - if (input.length() < this.blockSize && !(finish && input.length() > 0)) { - return true; - } - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - } - this.cipher.decrypt(this._inBlock, this._outBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._prev[i] ^ this._outBlock[i]); - } - this._prev = this._inBlock.slice(0); - }; - modes.cbc.prototype.pad = function(input, options) { - var padding = input.length() === this.blockSize ? this.blockSize : this.blockSize - input.length(); - input.fillWithByte(padding, padding); - return true; - }; - modes.cbc.prototype.unpad = function(output, options) { - if (options.overflow > 0) { - return false; - } - var len = output.length(); - var count = output.at(len - 1); - if (count > this.blockSize << 2) { - return false; - } - output.truncate(count); - return true; - }; - modes.cfb = function(options) { - options = options || {}; - this.name = "CFB"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialBlock = new Array(this._ints); - this._partialOutput = forge2.util.createBuffer(); - this._partialBytes = 0; - }; - modes.cfb.prototype.start = function(options) { - if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; - }; - modes.cfb.prototype.encrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32() ^ this._outBlock[i]; - output.putInt32(this._inBlock[i]); - } - return; - } - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialBlock[i] = input.getInt32() ^ this._outBlock[i]; - this._partialOutput.putInt32(this._partialBlock[i]); - } - if (partialBytes > 0) { - input.read -= this.blockSize; - } else { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._partialBlock[i]; - } - } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if (partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; - } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; - }; - modes.cfb.prototype.decrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = input.getInt32(); - output.putInt32(this._inBlock[i] ^ this._outBlock[i]); - } - return; - } - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialBlock[i] = input.getInt32(); - this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]); - } - if (partialBytes > 0) { - input.read -= this.blockSize; - } else { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._partialBlock[i]; - } - } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if (partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; - } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; - }; - modes.ofb = function(options) { - options = options || {}; - this.name = "OFB"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialOutput = forge2.util.createBuffer(); - this._partialBytes = 0; - }; - modes.ofb.prototype.start = function(options) { - if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; - }; - modes.ofb.prototype.encrypt = function(input, output, finish) { - var inputLength = input.length(); - if (input.length() === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - output.putInt32(input.getInt32() ^ this._outBlock[i]); - this._inBlock[i] = this._outBlock[i]; - } - return; - } - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); - } - if (partialBytes > 0) { - input.read -= this.blockSize; - } else { - for (var i = 0; i < this._ints; ++i) { - this._inBlock[i] = this._outBlock[i]; - } - } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if (partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; - } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; - }; - modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt; - modes.ctr = function(options) { - options = options || {}; - this.name = "CTR"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = null; - this._outBlock = new Array(this._ints); - this._partialOutput = forge2.util.createBuffer(); - this._partialBytes = 0; - }; - modes.ctr.prototype.start = function(options) { - if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } - this._iv = transformIV(options.iv, this.blockSize); - this._inBlock = this._iv.slice(0); - this._partialBytes = 0; - }; - modes.ctr.prototype.encrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - output.putInt32(input.getInt32() ^ this._outBlock[i]); - } - } else { - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); - } - if (partialBytes > 0) { - input.read -= this.blockSize; - } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if (partialBytes > 0 && !finish) { - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; - } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; - } - inc32(this._inBlock); - }; - modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt; - modes.gcm = function(options) { - options = options || {}; - this.name = "GCM"; - this.cipher = options.cipher; - this.blockSize = options.blockSize || 16; - this._ints = this.blockSize / 4; - this._inBlock = new Array(this._ints); - this._outBlock = new Array(this._ints); - this._partialOutput = forge2.util.createBuffer(); - this._partialBytes = 0; - this._R = 3774873600; - }; - modes.gcm.prototype.start = function(options) { - if (!("iv" in options)) { - throw new Error("Invalid IV parameter."); - } - var iv = forge2.util.createBuffer(options.iv); - this._cipherLength = 0; - var additionalData; - if ("additionalData" in options) { - additionalData = forge2.util.createBuffer(options.additionalData); - } else { - additionalData = forge2.util.createBuffer(); - } - if ("tagLength" in options) { - this._tagLength = options.tagLength; - } else { - this._tagLength = 128; - } - this._tag = null; - if (options.decrypt) { - this._tag = forge2.util.createBuffer(options.tag).getBytes(); - if (this._tag.length !== this._tagLength / 8) { - throw new Error("Authentication tag does not match tag length."); - } - } - this._hashBlock = new Array(this._ints); - this.tag = null; - this._hashSubkey = new Array(this._ints); - this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey); - this.componentBits = 4; - this._m = this.generateHashTable(this._hashSubkey, this.componentBits); - var ivLength = iv.length(); - if (ivLength === 12) { - this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1]; - } else { - this._j0 = [0, 0, 0, 0]; - while (iv.length() > 0) { - this._j0 = this.ghash( - this._hashSubkey, - this._j0, - [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()] - ); - } - this._j0 = this.ghash( - this._hashSubkey, - this._j0, - [0, 0].concat(from64To32(ivLength * 8)) - ); - } - this._inBlock = this._j0.slice(0); - inc32(this._inBlock); - this._partialBytes = 0; - additionalData = forge2.util.createBuffer(additionalData); - this._aDataLength = from64To32(additionalData.length() * 8); - var overflow = additionalData.length() % this.blockSize; - if (overflow) { - additionalData.fillWithByte(0, this.blockSize - overflow); - } - this._s = [0, 0, 0, 0]; - while (additionalData.length() > 0) { - this._s = this.ghash(this._hashSubkey, this._s, [ - additionalData.getInt32(), - additionalData.getInt32(), - additionalData.getInt32(), - additionalData.getInt32() - ]); - } - }; - modes.gcm.prototype.encrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength === 0) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - if (this._partialBytes === 0 && inputLength >= this.blockSize) { - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i] ^= input.getInt32()); - } - this._cipherLength += this.blockSize; - } else { - var partialBytes = (this.blockSize - inputLength) % this.blockSize; - if (partialBytes > 0) { - partialBytes = this.blockSize - partialBytes; - } - this._partialOutput.clear(); - for (var i = 0; i < this._ints; ++i) { - this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); - } - if (partialBytes <= 0 || finish) { - if (finish) { - var overflow = inputLength % this.blockSize; - this._cipherLength += overflow; - this._partialOutput.truncate(this.blockSize - overflow); - } else { - this._cipherLength += this.blockSize; - } - for (var i = 0; i < this._ints; ++i) { - this._outBlock[i] = this._partialOutput.getInt32(); - } - this._partialOutput.read -= this.blockSize; - } - if (this._partialBytes > 0) { - this._partialOutput.getBytes(this._partialBytes); - } - if (partialBytes > 0 && !finish) { - input.read -= this.blockSize; - output.putBytes(this._partialOutput.getBytes( - partialBytes - this._partialBytes - )); - this._partialBytes = partialBytes; - return true; - } - output.putBytes(this._partialOutput.getBytes( - inputLength - this._partialBytes - )); - this._partialBytes = 0; - } - this._s = this.ghash(this._hashSubkey, this._s, this._outBlock); - inc32(this._inBlock); - }; - modes.gcm.prototype.decrypt = function(input, output, finish) { - var inputLength = input.length(); - if (inputLength < this.blockSize && !(finish && inputLength > 0)) { - return true; - } - this.cipher.encrypt(this._inBlock, this._outBlock); - inc32(this._inBlock); - this._hashBlock[0] = input.getInt32(); - this._hashBlock[1] = input.getInt32(); - this._hashBlock[2] = input.getInt32(); - this._hashBlock[3] = input.getInt32(); - this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock); - for (var i = 0; i < this._ints; ++i) { - output.putInt32(this._outBlock[i] ^ this._hashBlock[i]); - } - if (inputLength < this.blockSize) { - this._cipherLength += inputLength % this.blockSize; - } else { - this._cipherLength += this.blockSize; - } - }; - modes.gcm.prototype.afterFinish = function(output, options) { - var rval = true; - if (options.decrypt && options.overflow) { - output.truncate(this.blockSize - options.overflow); - } - this.tag = forge2.util.createBuffer(); - var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8)); - this._s = this.ghash(this._hashSubkey, this._s, lengths); - var tag = []; - this.cipher.encrypt(this._j0, tag); - for (var i = 0; i < this._ints; ++i) { - this.tag.putInt32(this._s[i] ^ tag[i]); - } - this.tag.truncate(this.tag.length() % (this._tagLength / 8)); - if (options.decrypt && this.tag.bytes() !== this._tag) { - rval = false; - } - return rval; - }; - modes.gcm.prototype.multiply = function(x, y) { - var z_i = [0, 0, 0, 0]; - var v_i = y.slice(0); - for (var i = 0; i < 128; ++i) { - var x_i = x[i / 32 | 0] & 1 << 31 - i % 32; - if (x_i) { - z_i[0] ^= v_i[0]; - z_i[1] ^= v_i[1]; - z_i[2] ^= v_i[2]; - z_i[3] ^= v_i[3]; - } - this.pow(v_i, v_i); - } - return z_i; - }; - modes.gcm.prototype.pow = function(x, out) { - var lsb = x[3] & 1; - for (var i = 3; i > 0; --i) { - out[i] = x[i] >>> 1 | (x[i - 1] & 1) << 31; - } - out[0] = x[0] >>> 1; - if (lsb) { - out[0] ^= this._R; - } - }; - modes.gcm.prototype.tableMultiply = function(x) { - var z = [0, 0, 0, 0]; - for (var i = 0; i < 32; ++i) { - var idx = i / 8 | 0; - var x_i = x[idx] >>> (7 - i % 8) * 4 & 15; - var ah = this._m[i][x_i]; - z[0] ^= ah[0]; - z[1] ^= ah[1]; - z[2] ^= ah[2]; - z[3] ^= ah[3]; - } - return z; - }; - modes.gcm.prototype.ghash = function(h, y, x) { - y[0] ^= x[0]; - y[1] ^= x[1]; - y[2] ^= x[2]; - y[3] ^= x[3]; - return this.tableMultiply(y); - }; - modes.gcm.prototype.generateHashTable = function(h, bits) { - var multiplier = 8 / bits; - var perInt = 4 * multiplier; - var size = 16 * multiplier; - var m = new Array(size); - for (var i = 0; i < size; ++i) { - var tmp = [0, 0, 0, 0]; - var idx = i / perInt | 0; - var shft = (perInt - 1 - i % perInt) * bits; - tmp[idx] = 1 << bits - 1 << shft; - m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits); - } - return m; - }; - modes.gcm.prototype.generateSubHashTable = function(mid, bits) { - var size = 1 << bits; - var half = size >>> 1; - var m = new Array(size); - m[half] = mid.slice(0); - var i = half >>> 1; - while (i > 0) { - this.pow(m[2 * i], m[i] = []); - i >>= 1; - } - i = 2; - while (i < half) { - for (var j = 1; j < i; ++j) { - var m_i = m[i]; - var m_j = m[j]; - m[i + j] = [ - m_i[0] ^ m_j[0], - m_i[1] ^ m_j[1], - m_i[2] ^ m_j[2], - m_i[3] ^ m_j[3] - ]; - } - i *= 2; - } - m[0] = [0, 0, 0, 0]; - for (i = half + 1; i < size; ++i) { - var c = m[i ^ half]; - m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]]; - } - return m; - }; - function transformIV(iv, blockSize) { - if (typeof iv === "string") { - iv = forge2.util.createBuffer(iv); - } - if (forge2.util.isArray(iv) && iv.length > 4) { - var tmp = iv; - iv = forge2.util.createBuffer(); - for (var i = 0; i < tmp.length; ++i) { - iv.putByte(tmp[i]); - } - } - if (iv.length() < blockSize) { - throw new Error( - "Invalid IV length; got " + iv.length() + " bytes and expected " + blockSize + " bytes." - ); - } - if (!forge2.util.isArray(iv)) { - var ints = []; - var blocks = blockSize / 4; - for (var i = 0; i < blocks; ++i) { - ints.push(iv.getInt32()); - } - iv = ints; - } - return iv; - } - function inc32(block) { - block[block.length - 1] = block[block.length - 1] + 1 & 4294967295; - } - function from64To32(num) { - return [num / 4294967296 | 0, num & 4294967295]; - } - } -}); - -// node_modules/node-forge/lib/aes.js -var require_aes = __commonJS({ - "node_modules/node-forge/lib/aes.js"(exports, module) { - var forge2 = require_forge(); - require_cipher(); - require_cipherModes(); - require_util(); - module.exports = forge2.aes = forge2.aes || {}; - forge2.aes.startEncrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key, - output, - decrypt: false, - mode - }); - cipher.start(iv); - return cipher; - }; - forge2.aes.createEncryptionCipher = function(key, mode) { - return _createCipher({ - key, - output: null, - decrypt: false, - mode - }); - }; - forge2.aes.startDecrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key, - output, - decrypt: true, - mode - }); - cipher.start(iv); - return cipher; - }; - forge2.aes.createDecryptionCipher = function(key, mode) { - return _createCipher({ - key, - output: null, - decrypt: true, - mode - }); - }; - forge2.aes.Algorithm = function(name, mode) { - if (!init) { - initialize(); - } - var self2 = this; - self2.name = name; - self2.mode = new mode({ - blockSize: 16, - cipher: { - encrypt: function(inBlock, outBlock) { - return _updateBlock(self2._w, inBlock, outBlock, false); - }, - decrypt: function(inBlock, outBlock) { - return _updateBlock(self2._w, inBlock, outBlock, true); - } - } - }); - self2._init = false; - }; - forge2.aes.Algorithm.prototype.initialize = function(options) { - if (this._init) { - return; - } - var key = options.key; - var tmp; - if (typeof key === "string" && (key.length === 16 || key.length === 24 || key.length === 32)) { - key = forge2.util.createBuffer(key); - } else if (forge2.util.isArray(key) && (key.length === 16 || key.length === 24 || key.length === 32)) { - tmp = key; - key = forge2.util.createBuffer(); - for (var i = 0; i < tmp.length; ++i) { - key.putByte(tmp[i]); - } - } - if (!forge2.util.isArray(key)) { - tmp = key; - key = []; - var len = tmp.length(); - if (len === 16 || len === 24 || len === 32) { - len = len >>> 2; - for (var i = 0; i < len; ++i) { - key.push(tmp.getInt32()); - } - } - } - if (!forge2.util.isArray(key) || !(key.length === 4 || key.length === 6 || key.length === 8)) { - throw new Error("Invalid key parameter."); - } - var mode = this.mode.name; - var encryptOp = ["CFB", "OFB", "CTR", "GCM"].indexOf(mode) !== -1; - this._w = _expandKey(key, options.decrypt && !encryptOp); - this._init = true; - }; - forge2.aes._expandKey = function(key, decrypt) { - if (!init) { - initialize(); - } - return _expandKey(key, decrypt); - }; - forge2.aes._updateBlock = _updateBlock; - registerAlgorithm("AES-ECB", forge2.cipher.modes.ecb); - registerAlgorithm("AES-CBC", forge2.cipher.modes.cbc); - registerAlgorithm("AES-CFB", forge2.cipher.modes.cfb); - registerAlgorithm("AES-OFB", forge2.cipher.modes.ofb); - registerAlgorithm("AES-CTR", forge2.cipher.modes.ctr); - registerAlgorithm("AES-GCM", forge2.cipher.modes.gcm); - function registerAlgorithm(name, mode) { - var factory = function() { - return new forge2.aes.Algorithm(name, mode); - }; - forge2.cipher.registerAlgorithm(name, factory); - } - var init = false; - var Nb = 4; - var sbox; - var isbox; - var rcon; - var mix; - var imix; - function initialize() { - init = true; - rcon = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54]; - var xtime = new Array(256); - for (var i = 0; i < 128; ++i) { - xtime[i] = i << 1; - xtime[i + 128] = i + 128 << 1 ^ 283; - } - sbox = new Array(256); - isbox = new Array(256); - mix = new Array(4); - imix = new Array(4); - for (var i = 0; i < 4; ++i) { - mix[i] = new Array(256); - imix[i] = new Array(256); - } - var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime; - for (var i = 0; i < 256; ++i) { - sx = ei ^ ei << 1 ^ ei << 2 ^ ei << 3 ^ ei << 4; - sx = sx >> 8 ^ sx & 255 ^ 99; - sbox[e] = sx; - isbox[sx] = e; - sx2 = xtime[sx]; - e2 = xtime[e]; - e4 = xtime[e2]; - e8 = xtime[e4]; - me = sx2 << 24 ^ // 2 - sx << 16 ^ // 1 - sx << 8 ^ // 1 - (sx ^ sx2); - ime = (e2 ^ e4 ^ e8) << 24 ^ // E (14) - (e ^ e8) << 16 ^ // 9 - (e ^ e4 ^ e8) << 8 ^ // D (13) - (e ^ e2 ^ e8); - for (var n = 0; n < 4; ++n) { - mix[n][e] = me; - imix[n][sx] = ime; - me = me << 24 | me >>> 8; - ime = ime << 24 | ime >>> 8; - } - if (e === 0) { - e = ei = 1; - } else { - e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]]; - ei ^= xtime[xtime[ei]]; - } - } - } - function _expandKey(key, decrypt) { - var w = key.slice(0); - var temp, iNk = 1; - var Nk = w.length; - var Nr1 = Nk + 6 + 1; - var end = Nb * Nr1; - for (var i = Nk; i < end; ++i) { - temp = w[i - 1]; - if (i % Nk === 0) { - temp = sbox[temp >>> 16 & 255] << 24 ^ sbox[temp >>> 8 & 255] << 16 ^ sbox[temp & 255] << 8 ^ sbox[temp >>> 24] ^ rcon[iNk] << 24; - iNk++; - } else if (Nk > 6 && i % Nk === 4) { - temp = sbox[temp >>> 24] << 24 ^ sbox[temp >>> 16 & 255] << 16 ^ sbox[temp >>> 8 & 255] << 8 ^ sbox[temp & 255]; - } - w[i] = w[i - Nk] ^ temp; - } - if (decrypt) { - var tmp; - var m0 = imix[0]; - var m1 = imix[1]; - var m2 = imix[2]; - var m3 = imix[3]; - var wnew = w.slice(0); - end = w.length; - for (var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) { - if (i === 0 || i === end - Nb) { - wnew[i] = w[wi]; - wnew[i + 1] = w[wi + 3]; - wnew[i + 2] = w[wi + 2]; - wnew[i + 3] = w[wi + 1]; - } else { - for (var n = 0; n < Nb; ++n) { - tmp = w[wi + n]; - wnew[i + (3 & -n)] = m0[sbox[tmp >>> 24]] ^ m1[sbox[tmp >>> 16 & 255]] ^ m2[sbox[tmp >>> 8 & 255]] ^ m3[sbox[tmp & 255]]; - } - } - } - w = wnew; - } - return w; - } - function _updateBlock(w, input, output, decrypt) { - var Nr = w.length / 4 - 1; - var m0, m1, m2, m3, sub; - if (decrypt) { - m0 = imix[0]; - m1 = imix[1]; - m2 = imix[2]; - m3 = imix[3]; - sub = isbox; - } else { - m0 = mix[0]; - m1 = mix[1]; - m2 = mix[2]; - m3 = mix[3]; - sub = sbox; - } - var a, b, c, d, a2, b2, c2; - a = input[0] ^ w[0]; - b = input[decrypt ? 3 : 1] ^ w[1]; - c = input[2] ^ w[2]; - d = input[decrypt ? 1 : 3] ^ w[3]; - var i = 3; - for (var round = 1; round < Nr; ++round) { - a2 = m0[a >>> 24] ^ m1[b >>> 16 & 255] ^ m2[c >>> 8 & 255] ^ m3[d & 255] ^ w[++i]; - b2 = m0[b >>> 24] ^ m1[c >>> 16 & 255] ^ m2[d >>> 8 & 255] ^ m3[a & 255] ^ w[++i]; - c2 = m0[c >>> 24] ^ m1[d >>> 16 & 255] ^ m2[a >>> 8 & 255] ^ m3[b & 255] ^ w[++i]; - d = m0[d >>> 24] ^ m1[a >>> 16 & 255] ^ m2[b >>> 8 & 255] ^ m3[c & 255] ^ w[++i]; - a = a2; - b = b2; - c = c2; - } - output[0] = sub[a >>> 24] << 24 ^ sub[b >>> 16 & 255] << 16 ^ sub[c >>> 8 & 255] << 8 ^ sub[d & 255] ^ w[++i]; - output[decrypt ? 3 : 1] = sub[b >>> 24] << 24 ^ sub[c >>> 16 & 255] << 16 ^ sub[d >>> 8 & 255] << 8 ^ sub[a & 255] ^ w[++i]; - output[2] = sub[c >>> 24] << 24 ^ sub[d >>> 16 & 255] << 16 ^ sub[a >>> 8 & 255] << 8 ^ sub[b & 255] ^ w[++i]; - output[decrypt ? 1 : 3] = sub[d >>> 24] << 24 ^ sub[a >>> 16 & 255] << 16 ^ sub[b >>> 8 & 255] << 8 ^ sub[c & 255] ^ w[++i]; - } - function _createCipher(options) { - options = options || {}; - var mode = (options.mode || "CBC").toUpperCase(); - var algorithm = "AES-" + mode; - var cipher; - if (options.decrypt) { - cipher = forge2.cipher.createDecipher(algorithm, options.key); - } else { - cipher = forge2.cipher.createCipher(algorithm, options.key); - } - var start = cipher.start; - cipher.start = function(iv, options2) { - var output = null; - if (options2 instanceof forge2.util.ByteBuffer) { - output = options2; - options2 = {}; - } - options2 = options2 || {}; - options2.output = output; - options2.iv = iv; - start.call(cipher, options2); - }; - return cipher; - } - } -}); - -// node_modules/node-forge/lib/oids.js -var require_oids = __commonJS({ - "node_modules/node-forge/lib/oids.js"(exports, module) { - var forge2 = require_forge(); - forge2.pki = forge2.pki || {}; - var oids = module.exports = forge2.pki.oids = forge2.oids = forge2.oids || {}; - function _IN(id, name) { - oids[id] = name; - oids[name] = id; - } - function _I_(id, name) { - oids[id] = name; - } - _IN("1.2.840.113549.1.1.1", "rsaEncryption"); - _IN("1.2.840.113549.1.1.4", "md5WithRSAEncryption"); - _IN("1.2.840.113549.1.1.5", "sha1WithRSAEncryption"); - _IN("1.2.840.113549.1.1.7", "RSAES-OAEP"); - _IN("1.2.840.113549.1.1.8", "mgf1"); - _IN("1.2.840.113549.1.1.9", "pSpecified"); - _IN("1.2.840.113549.1.1.10", "RSASSA-PSS"); - _IN("1.2.840.113549.1.1.11", "sha256WithRSAEncryption"); - _IN("1.2.840.113549.1.1.12", "sha384WithRSAEncryption"); - _IN("1.2.840.113549.1.1.13", "sha512WithRSAEncryption"); - _IN("1.3.101.112", "EdDSA25519"); - _IN("1.2.840.10040.4.3", "dsa-with-sha1"); - _IN("1.3.14.3.2.7", "desCBC"); - _IN("1.3.14.3.2.26", "sha1"); - _IN("1.3.14.3.2.29", "sha1WithRSASignature"); - _IN("2.16.840.1.101.3.4.2.1", "sha256"); - _IN("2.16.840.1.101.3.4.2.2", "sha384"); - _IN("2.16.840.1.101.3.4.2.3", "sha512"); - _IN("2.16.840.1.101.3.4.2.4", "sha224"); - _IN("2.16.840.1.101.3.4.2.5", "sha512-224"); - _IN("2.16.840.1.101.3.4.2.6", "sha512-256"); - _IN("1.2.840.113549.2.2", "md2"); - _IN("1.2.840.113549.2.5", "md5"); - _IN("1.2.840.113549.1.7.1", "data"); - _IN("1.2.840.113549.1.7.2", "signedData"); - _IN("1.2.840.113549.1.7.3", "envelopedData"); - _IN("1.2.840.113549.1.7.4", "signedAndEnvelopedData"); - _IN("1.2.840.113549.1.7.5", "digestedData"); - _IN("1.2.840.113549.1.7.6", "encryptedData"); - _IN("1.2.840.113549.1.9.1", "emailAddress"); - _IN("1.2.840.113549.1.9.2", "unstructuredName"); - _IN("1.2.840.113549.1.9.3", "contentType"); - _IN("1.2.840.113549.1.9.4", "messageDigest"); - _IN("1.2.840.113549.1.9.5", "signingTime"); - _IN("1.2.840.113549.1.9.6", "counterSignature"); - _IN("1.2.840.113549.1.9.7", "challengePassword"); - _IN("1.2.840.113549.1.9.8", "unstructuredAddress"); - _IN("1.2.840.113549.1.9.14", "extensionRequest"); - _IN("1.2.840.113549.1.9.20", "friendlyName"); - _IN("1.2.840.113549.1.9.21", "localKeyId"); - _IN("1.2.840.113549.1.9.22.1", "x509Certificate"); - _IN("1.2.840.113549.1.12.10.1.1", "keyBag"); - _IN("1.2.840.113549.1.12.10.1.2", "pkcs8ShroudedKeyBag"); - _IN("1.2.840.113549.1.12.10.1.3", "certBag"); - _IN("1.2.840.113549.1.12.10.1.4", "crlBag"); - _IN("1.2.840.113549.1.12.10.1.5", "secretBag"); - _IN("1.2.840.113549.1.12.10.1.6", "safeContentsBag"); - _IN("1.2.840.113549.1.5.13", "pkcs5PBES2"); - _IN("1.2.840.113549.1.5.12", "pkcs5PBKDF2"); - _IN("1.2.840.113549.1.12.1.1", "pbeWithSHAAnd128BitRC4"); - _IN("1.2.840.113549.1.12.1.2", "pbeWithSHAAnd40BitRC4"); - _IN("1.2.840.113549.1.12.1.3", "pbeWithSHAAnd3-KeyTripleDES-CBC"); - _IN("1.2.840.113549.1.12.1.4", "pbeWithSHAAnd2-KeyTripleDES-CBC"); - _IN("1.2.840.113549.1.12.1.5", "pbeWithSHAAnd128BitRC2-CBC"); - _IN("1.2.840.113549.1.12.1.6", "pbewithSHAAnd40BitRC2-CBC"); - _IN("1.2.840.113549.2.7", "hmacWithSHA1"); - _IN("1.2.840.113549.2.8", "hmacWithSHA224"); - _IN("1.2.840.113549.2.9", "hmacWithSHA256"); - _IN("1.2.840.113549.2.10", "hmacWithSHA384"); - _IN("1.2.840.113549.2.11", "hmacWithSHA512"); - _IN("1.2.840.113549.3.7", "des-EDE3-CBC"); - _IN("2.16.840.1.101.3.4.1.2", "aes128-CBC"); - _IN("2.16.840.1.101.3.4.1.22", "aes192-CBC"); - _IN("2.16.840.1.101.3.4.1.42", "aes256-CBC"); - _IN("2.5.4.3", "commonName"); - _IN("2.5.4.4", "surname"); - _IN("2.5.4.5", "serialNumber"); - _IN("2.5.4.6", "countryName"); - _IN("2.5.4.7", "localityName"); - _IN("2.5.4.8", "stateOrProvinceName"); - _IN("2.5.4.9", "streetAddress"); - _IN("2.5.4.10", "organizationName"); - _IN("2.5.4.11", "organizationalUnitName"); - _IN("2.5.4.12", "title"); - _IN("2.5.4.13", "description"); - _IN("2.5.4.15", "businessCategory"); - _IN("2.5.4.17", "postalCode"); - _IN("2.5.4.42", "givenName"); - _IN("1.3.6.1.4.1.311.60.2.1.2", "jurisdictionOfIncorporationStateOrProvinceName"); - _IN("1.3.6.1.4.1.311.60.2.1.3", "jurisdictionOfIncorporationCountryName"); - _IN("2.16.840.1.113730.1.1", "nsCertType"); - _IN("2.16.840.1.113730.1.13", "nsComment"); - _I_("2.5.29.1", "authorityKeyIdentifier"); - _I_("2.5.29.2", "keyAttributes"); - _I_("2.5.29.3", "certificatePolicies"); - _I_("2.5.29.4", "keyUsageRestriction"); - _I_("2.5.29.5", "policyMapping"); - _I_("2.5.29.6", "subtreesConstraint"); - _I_("2.5.29.7", "subjectAltName"); - _I_("2.5.29.8", "issuerAltName"); - _I_("2.5.29.9", "subjectDirectoryAttributes"); - _I_("2.5.29.10", "basicConstraints"); - _I_("2.5.29.11", "nameConstraints"); - _I_("2.5.29.12", "policyConstraints"); - _I_("2.5.29.13", "basicConstraints"); - _IN("2.5.29.14", "subjectKeyIdentifier"); - _IN("2.5.29.15", "keyUsage"); - _I_("2.5.29.16", "privateKeyUsagePeriod"); - _IN("2.5.29.17", "subjectAltName"); - _IN("2.5.29.18", "issuerAltName"); - _IN("2.5.29.19", "basicConstraints"); - _I_("2.5.29.20", "cRLNumber"); - _I_("2.5.29.21", "cRLReason"); - _I_("2.5.29.22", "expirationDate"); - _I_("2.5.29.23", "instructionCode"); - _I_("2.5.29.24", "invalidityDate"); - _I_("2.5.29.25", "cRLDistributionPoints"); - _I_("2.5.29.26", "issuingDistributionPoint"); - _I_("2.5.29.27", "deltaCRLIndicator"); - _I_("2.5.29.28", "issuingDistributionPoint"); - _I_("2.5.29.29", "certificateIssuer"); - _I_("2.5.29.30", "nameConstraints"); - _IN("2.5.29.31", "cRLDistributionPoints"); - _IN("2.5.29.32", "certificatePolicies"); - _I_("2.5.29.33", "policyMappings"); - _I_("2.5.29.34", "policyConstraints"); - _IN("2.5.29.35", "authorityKeyIdentifier"); - _I_("2.5.29.36", "policyConstraints"); - _IN("2.5.29.37", "extKeyUsage"); - _I_("2.5.29.46", "freshestCRL"); - _I_("2.5.29.54", "inhibitAnyPolicy"); - _IN("1.3.6.1.4.1.11129.2.4.2", "timestampList"); - _IN("1.3.6.1.5.5.7.1.1", "authorityInfoAccess"); - _IN("1.3.6.1.5.5.7.3.1", "serverAuth"); - _IN("1.3.6.1.5.5.7.3.2", "clientAuth"); - _IN("1.3.6.1.5.5.7.3.3", "codeSigning"); - _IN("1.3.6.1.5.5.7.3.4", "emailProtection"); - _IN("1.3.6.1.5.5.7.3.8", "timeStamping"); - } -}); - -// node_modules/node-forge/lib/asn1.js -var require_asn1 = __commonJS({ - "node_modules/node-forge/lib/asn1.js"(exports, module) { - var forge2 = require_forge(); - require_util(); - require_oids(); - var asn1 = module.exports = forge2.asn1 = forge2.asn1 || {}; - asn1.Class = { - UNIVERSAL: 0, - APPLICATION: 64, - CONTEXT_SPECIFIC: 128, - PRIVATE: 192 - }; - asn1.Type = { - NONE: 0, - BOOLEAN: 1, - INTEGER: 2, - BITSTRING: 3, - OCTETSTRING: 4, - NULL: 5, - OID: 6, - ODESC: 7, - EXTERNAL: 8, - REAL: 9, - ENUMERATED: 10, - EMBEDDED: 11, - UTF8: 12, - ROID: 13, - SEQUENCE: 16, - SET: 17, - PRINTABLESTRING: 19, - IA5STRING: 22, - UTCTIME: 23, - GENERALIZEDTIME: 24, - BMPSTRING: 30 - }; - asn1.create = function(tagClass, type, constructed, value, options) { - if (forge2.util.isArray(value)) { - var tmp = []; - for (var i = 0; i < value.length; ++i) { - if (value[i] !== void 0) { - tmp.push(value[i]); - } - } - value = tmp; - } - var obj = { - tagClass, - type, - constructed, - composed: constructed || forge2.util.isArray(value), - value - }; - if (options && "bitStringContents" in options) { - obj.bitStringContents = options.bitStringContents; - obj.original = asn1.copy(obj); - } - return obj; - }; - asn1.copy = function(obj, options) { - var copy; - if (forge2.util.isArray(obj)) { - copy = []; - for (var i = 0; i < obj.length; ++i) { - copy.push(asn1.copy(obj[i], options)); - } - return copy; - } - if (typeof obj === "string") { - return obj; - } - copy = { - tagClass: obj.tagClass, - type: obj.type, - constructed: obj.constructed, - composed: obj.composed, - value: asn1.copy(obj.value, options) - }; - if (options && !options.excludeBitStringContents) { - copy.bitStringContents = obj.bitStringContents; - } - return copy; - }; - asn1.equals = function(obj1, obj2, options) { - if (forge2.util.isArray(obj1)) { - if (!forge2.util.isArray(obj2)) { - return false; - } - if (obj1.length !== obj2.length) { - return false; - } - for (var i = 0; i < obj1.length; ++i) { - if (!asn1.equals(obj1[i], obj2[i])) { - return false; - } - } - return true; - } - if (typeof obj1 !== typeof obj2) { - return false; - } - if (typeof obj1 === "string") { - return obj1 === obj2; - } - var equal = obj1.tagClass === obj2.tagClass && obj1.type === obj2.type && obj1.constructed === obj2.constructed && obj1.composed === obj2.composed && asn1.equals(obj1.value, obj2.value); - if (options && options.includeBitStringContents) { - equal = equal && obj1.bitStringContents === obj2.bitStringContents; - } - return equal; - }; - asn1.getBerValueLength = function(b) { - var b2 = b.getByte(); - if (b2 === 128) { - return void 0; - } - var length; - var longForm = b2 & 128; - if (!longForm) { - length = b2; - } else { - length = b.getInt((b2 & 127) << 3); - } - return length; - }; - function _checkBufferLength(bytes, remaining, n) { - if (n > remaining) { - var error = new Error("Too few bytes to parse DER."); - error.available = bytes.length(); - error.remaining = remaining; - error.requested = n; - throw error; - } - } - var _getValueLength = function(bytes, remaining) { - var b2 = bytes.getByte(); - remaining--; - if (b2 === 128) { - return void 0; - } - var length; - var longForm = b2 & 128; - if (!longForm) { - length = b2; - } else { - var longFormBytes = b2 & 127; - _checkBufferLength(bytes, remaining, longFormBytes); - length = bytes.getInt(longFormBytes << 3); - } - if (length < 0) { - throw new Error("Negative length: " + length); - } - return length; - }; - asn1.fromDer = function(bytes, options) { - if (options === void 0) { - options = { - strict: true, - parseAllBytes: true, - decodeBitStrings: true - }; - } - if (typeof options === "boolean") { - options = { - strict: options, - parseAllBytes: true, - decodeBitStrings: true - }; - } - if (!("strict" in options)) { - options.strict = true; - } - if (!("parseAllBytes" in options)) { - options.parseAllBytes = true; - } - if (!("decodeBitStrings" in options)) { - options.decodeBitStrings = true; - } - if (typeof bytes === "string") { - bytes = forge2.util.createBuffer(bytes); - } - var byteCount = bytes.length(); - var value = _fromDer(bytes, bytes.length(), 0, options); - if (options.parseAllBytes && bytes.length() !== 0) { - var error = new Error("Unparsed DER bytes remain after ASN.1 parsing."); - error.byteCount = byteCount; - error.remaining = bytes.length(); - throw error; - } - return value; - }; - function _fromDer(bytes, remaining, depth, options) { - var start; - _checkBufferLength(bytes, remaining, 2); - var b1 = bytes.getByte(); - remaining--; - var tagClass = b1 & 192; - var type = b1 & 31; - start = bytes.length(); - var length = _getValueLength(bytes, remaining); - remaining -= start - bytes.length(); - if (length !== void 0 && length > remaining) { - if (options.strict) { - var error = new Error("Too few bytes to read ASN.1 value."); - error.available = bytes.length(); - error.remaining = remaining; - error.requested = length; - throw error; - } - length = remaining; - } - var value; - var bitStringContents; - var constructed = (b1 & 32) === 32; - if (constructed) { - value = []; - if (length === void 0) { - for (; ; ) { - _checkBufferLength(bytes, remaining, 2); - if (bytes.bytes(2) === String.fromCharCode(0, 0)) { - bytes.getBytes(2); - remaining -= 2; - break; - } - start = bytes.length(); - value.push(_fromDer(bytes, remaining, depth + 1, options)); - remaining -= start - bytes.length(); - } - } else { - while (length > 0) { - start = bytes.length(); - value.push(_fromDer(bytes, length, depth + 1, options)); - remaining -= start - bytes.length(); - length -= start - bytes.length(); - } - } - } - if (value === void 0 && tagClass === asn1.Class.UNIVERSAL && type === asn1.Type.BITSTRING) { - bitStringContents = bytes.bytes(length); - } - if (value === void 0 && options.decodeBitStrings && tagClass === asn1.Class.UNIVERSAL && // FIXME: OCTET STRINGs not yet supported here - // .. other parts of forge expect to decode OCTET STRINGs manually - type === asn1.Type.BITSTRING && length > 1) { - var savedRead = bytes.read; - var savedRemaining = remaining; - var unused = 0; - if (type === asn1.Type.BITSTRING) { - _checkBufferLength(bytes, remaining, 1); - unused = bytes.getByte(); - remaining--; - } - if (unused === 0) { - try { - start = bytes.length(); - var subOptions = { - // enforce strict mode to avoid parsing ASN.1 from plain data - strict: true, - decodeBitStrings: true - }; - var composed = _fromDer(bytes, remaining, depth + 1, subOptions); - var used = start - bytes.length(); - remaining -= used; - if (type == asn1.Type.BITSTRING) { - used++; - } - var tc = composed.tagClass; - if (used === length && (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) { - value = [composed]; - } - } catch (ex) { - } - } - if (value === void 0) { - bytes.read = savedRead; - remaining = savedRemaining; - } - } - if (value === void 0) { - if (length === void 0) { - if (options.strict) { - throw new Error("Non-constructed ASN.1 object of indefinite length."); - } - length = remaining; - } - if (type === asn1.Type.BMPSTRING) { - value = ""; - for (; length > 0; length -= 2) { - _checkBufferLength(bytes, remaining, 2); - value += String.fromCharCode(bytes.getInt16()); - remaining -= 2; - } - } else { - value = bytes.getBytes(length); - remaining -= length; - } - } - var asn1Options = bitStringContents === void 0 ? null : { - bitStringContents - }; - return asn1.create(tagClass, type, constructed, value, asn1Options); - } - asn1.toDer = function(obj) { - var bytes = forge2.util.createBuffer(); - var b1 = obj.tagClass | obj.type; - var value = forge2.util.createBuffer(); - var useBitStringContents = false; - if ("bitStringContents" in obj) { - useBitStringContents = true; - if (obj.original) { - useBitStringContents = asn1.equals(obj, obj.original); - } - } - if (useBitStringContents) { - value.putBytes(obj.bitStringContents); - } else if (obj.composed) { - if (obj.constructed) { - b1 |= 32; - } else { - value.putByte(0); - } - for (var i = 0; i < obj.value.length; ++i) { - if (obj.value[i] !== void 0) { - value.putBuffer(asn1.toDer(obj.value[i])); - } - } - } else { - if (obj.type === asn1.Type.BMPSTRING) { - for (var i = 0; i < obj.value.length; ++i) { - value.putInt16(obj.value.charCodeAt(i)); - } - } else { - if (obj.type === asn1.Type.INTEGER && obj.value.length > 1 && // leading 0x00 for positive integer - (obj.value.charCodeAt(0) === 0 && (obj.value.charCodeAt(1) & 128) === 0 || // leading 0xFF for negative integer - obj.value.charCodeAt(0) === 255 && (obj.value.charCodeAt(1) & 128) === 128)) { - value.putBytes(obj.value.substr(1)); - } else { - value.putBytes(obj.value); - } - } - } - bytes.putByte(b1); - if (value.length() <= 127) { - bytes.putByte(value.length() & 127); - } else { - var len = value.length(); - var lenBytes = ""; - do { - lenBytes += String.fromCharCode(len & 255); - len = len >>> 8; - } while (len > 0); - bytes.putByte(lenBytes.length | 128); - for (var i = lenBytes.length - 1; i >= 0; --i) { - bytes.putByte(lenBytes.charCodeAt(i)); - } - } - bytes.putBuffer(value); - return bytes; - }; - asn1.oidToDer = function(oid) { - var values = oid.split("."); - var bytes = forge2.util.createBuffer(); - bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10)); - var last, valueBytes, value, b; - for (var i = 2; i < values.length; ++i) { - last = true; - valueBytes = []; - value = parseInt(values[i], 10); - do { - b = value & 127; - value = value >>> 7; - if (!last) { - b |= 128; - } - valueBytes.push(b); - last = false; - } while (value > 0); - for (var n = valueBytes.length - 1; n >= 0; --n) { - bytes.putByte(valueBytes[n]); - } - } - return bytes; - }; - asn1.derToOid = function(bytes) { - var oid; - if (typeof bytes === "string") { - bytes = forge2.util.createBuffer(bytes); - } - var b = bytes.getByte(); - oid = Math.floor(b / 40) + "." + b % 40; - var value = 0; - while (bytes.length() > 0) { - b = bytes.getByte(); - value = value << 7; - if (b & 128) { - value += b & 127; - } else { - oid += "." + (value + b); - value = 0; - } - } - return oid; - }; - asn1.utcTimeToDate = function(utc) { - var date = /* @__PURE__ */ new Date(); - var year = parseInt(utc.substr(0, 2), 10); - year = year >= 50 ? 1900 + year : 2e3 + year; - var MM = parseInt(utc.substr(2, 2), 10) - 1; - var DD = parseInt(utc.substr(4, 2), 10); - var hh = parseInt(utc.substr(6, 2), 10); - var mm = parseInt(utc.substr(8, 2), 10); - var ss = 0; - if (utc.length > 11) { - var c = utc.charAt(10); - var end = 10; - if (c !== "+" && c !== "-") { - ss = parseInt(utc.substr(10, 2), 10); - end += 2; - } - } - date.setUTCFullYear(year, MM, DD); - date.setUTCHours(hh, mm, ss, 0); - if (end) { - c = utc.charAt(end); - if (c === "+" || c === "-") { - var hhoffset = parseInt(utc.substr(end + 1, 2), 10); - var mmoffset = parseInt(utc.substr(end + 4, 2), 10); - var offset = hhoffset * 60 + mmoffset; - offset *= 6e4; - if (c === "+") { - date.setTime(+date - offset); - } else { - date.setTime(+date + offset); - } - } - } - return date; - }; - asn1.generalizedTimeToDate = function(gentime) { - var date = /* @__PURE__ */ new Date(); - var YYYY = parseInt(gentime.substr(0, 4), 10); - var MM = parseInt(gentime.substr(4, 2), 10) - 1; - var DD = parseInt(gentime.substr(6, 2), 10); - var hh = parseInt(gentime.substr(8, 2), 10); - var mm = parseInt(gentime.substr(10, 2), 10); - var ss = parseInt(gentime.substr(12, 2), 10); - var fff = 0; - var offset = 0; - var isUTC = false; - if (gentime.charAt(gentime.length - 1) === "Z") { - isUTC = true; - } - var end = gentime.length - 5, c = gentime.charAt(end); - if (c === "+" || c === "-") { - var hhoffset = parseInt(gentime.substr(end + 1, 2), 10); - var mmoffset = parseInt(gentime.substr(end + 4, 2), 10); - offset = hhoffset * 60 + mmoffset; - offset *= 6e4; - if (c === "+") { - offset *= -1; - } - isUTC = true; - } - if (gentime.charAt(14) === ".") { - fff = parseFloat(gentime.substr(14), 10) * 1e3; - } - if (isUTC) { - date.setUTCFullYear(YYYY, MM, DD); - date.setUTCHours(hh, mm, ss, fff); - date.setTime(+date + offset); - } else { - date.setFullYear(YYYY, MM, DD); - date.setHours(hh, mm, ss, fff); - } - return date; - }; - asn1.dateToUtcTime = function(date) { - if (typeof date === "string") { - return date; - } - var rval = ""; - var format = []; - format.push(("" + date.getUTCFullYear()).substr(2)); - format.push("" + (date.getUTCMonth() + 1)); - format.push("" + date.getUTCDate()); - format.push("" + date.getUTCHours()); - format.push("" + date.getUTCMinutes()); - format.push("" + date.getUTCSeconds()); - for (var i = 0; i < format.length; ++i) { - if (format[i].length < 2) { - rval += "0"; - } - rval += format[i]; - } - rval += "Z"; - return rval; - }; - asn1.dateToGeneralizedTime = function(date) { - if (typeof date === "string") { - return date; - } - var rval = ""; - var format = []; - format.push("" + date.getUTCFullYear()); - format.push("" + (date.getUTCMonth() + 1)); - format.push("" + date.getUTCDate()); - format.push("" + date.getUTCHours()); - format.push("" + date.getUTCMinutes()); - format.push("" + date.getUTCSeconds()); - for (var i = 0; i < format.length; ++i) { - if (format[i].length < 2) { - rval += "0"; - } - rval += format[i]; - } - rval += "Z"; - return rval; - }; - asn1.integerToDer = function(x) { - var rval = forge2.util.createBuffer(); - if (x >= -128 && x < 128) { - return rval.putSignedInt(x, 8); - } - if (x >= -32768 && x < 32768) { - return rval.putSignedInt(x, 16); - } - if (x >= -8388608 && x < 8388608) { - return rval.putSignedInt(x, 24); - } - if (x >= -2147483648 && x < 2147483648) { - return rval.putSignedInt(x, 32); - } - var error = new Error("Integer too large; max is 32-bits."); - error.integer = x; - throw error; - }; - asn1.derToInteger = function(bytes) { - if (typeof bytes === "string") { - bytes = forge2.util.createBuffer(bytes); - } - var n = bytes.length() * 8; - if (n > 32) { - throw new Error("Integer too large; max is 32-bits."); - } - return bytes.getSignedInt(n); - }; - asn1.validate = function(obj, v, capture, errors) { - var rval = false; - if ((obj.tagClass === v.tagClass || typeof v.tagClass === "undefined") && (obj.type === v.type || typeof v.type === "undefined")) { - if (obj.constructed === v.constructed || typeof v.constructed === "undefined") { - rval = true; - if (v.value && forge2.util.isArray(v.value)) { - var j = 0; - for (var i = 0; rval && i < v.value.length; ++i) { - rval = v.value[i].optional || false; - if (obj.value[j]) { - rval = asn1.validate(obj.value[j], v.value[i], capture, errors); - if (rval) { - ++j; - } else if (v.value[i].optional) { - rval = true; - } - } - if (!rval && errors) { - errors.push( - "[" + v.name + '] Tag class "' + v.tagClass + '", type "' + v.type + '" expected value length "' + v.value.length + '", got "' + obj.value.length + '"' - ); - } - } - } - if (rval && capture) { - if (v.capture) { - capture[v.capture] = obj.value; - } - if (v.captureAsn1) { - capture[v.captureAsn1] = obj; - } - if (v.captureBitStringContents && "bitStringContents" in obj) { - capture[v.captureBitStringContents] = obj.bitStringContents; - } - if (v.captureBitStringValue && "bitStringContents" in obj) { - var value; - if (obj.bitStringContents.length < 2) { - capture[v.captureBitStringValue] = ""; - } else { - var unused = obj.bitStringContents.charCodeAt(0); - if (unused !== 0) { - throw new Error( - "captureBitStringValue only supported for zero unused bits" - ); - } - capture[v.captureBitStringValue] = obj.bitStringContents.slice(1); - } - } - } - } else if (errors) { - errors.push( - "[" + v.name + '] Expected constructed "' + v.constructed + '", got "' + obj.constructed + '"' - ); - } - } else if (errors) { - if (obj.tagClass !== v.tagClass) { - errors.push( - "[" + v.name + '] Expected tag class "' + v.tagClass + '", got "' + obj.tagClass + '"' - ); - } - if (obj.type !== v.type) { - errors.push( - "[" + v.name + '] Expected type "' + v.type + '", got "' + obj.type + '"' - ); - } - } - return rval; - }; - var _nonLatinRegex = /[^\\u0000-\\u00ff]/; - asn1.prettyPrint = function(obj, level, indentation) { - var rval = ""; - level = level || 0; - indentation = indentation || 2; - if (level > 0) { - rval += "\n"; - } - var indent = ""; - for (var i = 0; i < level * indentation; ++i) { - indent += " "; - } - rval += indent + "Tag: "; - switch (obj.tagClass) { - case asn1.Class.UNIVERSAL: - rval += "Universal:"; - break; - case asn1.Class.APPLICATION: - rval += "Application:"; - break; - case asn1.Class.CONTEXT_SPECIFIC: - rval += "Context-Specific:"; - break; - case asn1.Class.PRIVATE: - rval += "Private:"; - break; - } - if (obj.tagClass === asn1.Class.UNIVERSAL) { - rval += obj.type; - switch (obj.type) { - case asn1.Type.NONE: - rval += " (None)"; - break; - case asn1.Type.BOOLEAN: - rval += " (Boolean)"; - break; - case asn1.Type.INTEGER: - rval += " (Integer)"; - break; - case asn1.Type.BITSTRING: - rval += " (Bit string)"; - break; - case asn1.Type.OCTETSTRING: - rval += " (Octet string)"; - break; - case asn1.Type.NULL: - rval += " (Null)"; - break; - case asn1.Type.OID: - rval += " (Object Identifier)"; - break; - case asn1.Type.ODESC: - rval += " (Object Descriptor)"; - break; - case asn1.Type.EXTERNAL: - rval += " (External or Instance of)"; - break; - case asn1.Type.REAL: - rval += " (Real)"; - break; - case asn1.Type.ENUMERATED: - rval += " (Enumerated)"; - break; - case asn1.Type.EMBEDDED: - rval += " (Embedded PDV)"; - break; - case asn1.Type.UTF8: - rval += " (UTF8)"; - break; - case asn1.Type.ROID: - rval += " (Relative Object Identifier)"; - break; - case asn1.Type.SEQUENCE: - rval += " (Sequence)"; - break; - case asn1.Type.SET: - rval += " (Set)"; - break; - case asn1.Type.PRINTABLESTRING: - rval += " (Printable String)"; - break; - case asn1.Type.IA5String: - rval += " (IA5String (ASCII))"; - break; - case asn1.Type.UTCTIME: - rval += " (UTC time)"; - break; - case asn1.Type.GENERALIZEDTIME: - rval += " (Generalized time)"; - break; - case asn1.Type.BMPSTRING: - rval += " (BMP String)"; - break; - } - } else { - rval += obj.type; - } - rval += "\n"; - rval += indent + "Constructed: " + obj.constructed + "\n"; - if (obj.composed) { - var subvalues = 0; - var sub = ""; - for (var i = 0; i < obj.value.length; ++i) { - if (obj.value[i] !== void 0) { - subvalues += 1; - sub += asn1.prettyPrint(obj.value[i], level + 1, indentation); - if (i + 1 < obj.value.length) { - sub += ","; - } - } - } - rval += indent + "Sub values: " + subvalues + sub; - } else { - rval += indent + "Value: "; - if (obj.type === asn1.Type.OID) { - var oid = asn1.derToOid(obj.value); - rval += oid; - if (forge2.pki && forge2.pki.oids) { - if (oid in forge2.pki.oids) { - rval += " (" + forge2.pki.oids[oid] + ") "; - } - } - } - if (obj.type === asn1.Type.INTEGER) { - try { - rval += asn1.derToInteger(obj.value); - } catch (ex) { - rval += "0x" + forge2.util.bytesToHex(obj.value); - } - } else if (obj.type === asn1.Type.BITSTRING) { - if (obj.value.length > 1) { - rval += "0x" + forge2.util.bytesToHex(obj.value.slice(1)); - } else { - rval += "(none)"; - } - if (obj.value.length > 0) { - var unused = obj.value.charCodeAt(0); - if (unused == 1) { - rval += " (1 unused bit shown)"; - } else if (unused > 1) { - rval += " (" + unused + " unused bits shown)"; - } - } - } else if (obj.type === asn1.Type.OCTETSTRING) { - if (!_nonLatinRegex.test(obj.value)) { - rval += "(" + obj.value + ") "; - } - rval += "0x" + forge2.util.bytesToHex(obj.value); - } else if (obj.type === asn1.Type.UTF8) { - try { - rval += forge2.util.decodeUtf8(obj.value); - } catch (e) { - if (e.message === "URI malformed") { - rval += "0x" + forge2.util.bytesToHex(obj.value) + " (malformed UTF8)"; - } else { - throw e; - } - } - } else if (obj.type === asn1.Type.PRINTABLESTRING || obj.type === asn1.Type.IA5String) { - rval += obj.value; - } else if (_nonLatinRegex.test(obj.value)) { - rval += "0x" + forge2.util.bytesToHex(obj.value); - } else if (obj.value.length === 0) { - rval += "[null]"; - } else { - rval += obj.value; - } - } - return rval; - }; - } -}); - -// node_modules/node-forge/lib/md.js -var require_md = __commonJS({ - "node_modules/node-forge/lib/md.js"(exports, module) { - var forge2 = require_forge(); - module.exports = forge2.md = forge2.md || {}; - forge2.md.algorithms = forge2.md.algorithms || {}; - } -}); - -// node_modules/node-forge/lib/hmac.js -var require_hmac = __commonJS({ - "node_modules/node-forge/lib/hmac.js"(exports, module) { - var forge2 = require_forge(); - require_md(); - require_util(); - var hmac = module.exports = forge2.hmac = forge2.hmac || {}; - hmac.create = function() { - var _key = null; - var _md = null; - var _ipadding = null; - var _opadding = null; - var ctx = {}; - ctx.start = function(md, key) { - if (md !== null) { - if (typeof md === "string") { - md = md.toLowerCase(); - if (md in forge2.md.algorithms) { - _md = forge2.md.algorithms[md].create(); - } else { - throw new Error('Unknown hash algorithm "' + md + '"'); - } - } else { - _md = md; - } - } - if (key === null) { - key = _key; - } else { - if (typeof key === "string") { - key = forge2.util.createBuffer(key); - } else if (forge2.util.isArray(key)) { - var tmp = key; - key = forge2.util.createBuffer(); - for (var i = 0; i < tmp.length; ++i) { - key.putByte(tmp[i]); - } - } - var keylen = key.length(); - if (keylen > _md.blockLength) { - _md.start(); - _md.update(key.bytes()); - key = _md.digest(); - } - _ipadding = forge2.util.createBuffer(); - _opadding = forge2.util.createBuffer(); - keylen = key.length(); - for (var i = 0; i < keylen; ++i) { - var tmp = key.at(i); - _ipadding.putByte(54 ^ tmp); - _opadding.putByte(92 ^ tmp); - } - if (keylen < _md.blockLength) { - var tmp = _md.blockLength - keylen; - for (var i = 0; i < tmp; ++i) { - _ipadding.putByte(54); - _opadding.putByte(92); - } - } - _key = key; - _ipadding = _ipadding.bytes(); - _opadding = _opadding.bytes(); - } - _md.start(); - _md.update(_ipadding); - }; - ctx.update = function(bytes) { - _md.update(bytes); - }; - ctx.getMac = function() { - var inner = _md.digest().bytes(); - _md.start(); - _md.update(_opadding); - _md.update(inner); - return _md.digest(); - }; - ctx.digest = ctx.getMac; - return ctx; - }; - } -}); - -// node_modules/node-forge/lib/md5.js -var require_md5 = __commonJS({ - "node_modules/node-forge/lib/md5.js"(exports, module) { - var forge2 = require_forge(); - require_md(); - require_util(); - var md5 = module.exports = forge2.md5 = forge2.md5 || {}; - forge2.md.md5 = forge2.md.algorithms.md5 = md5; - md5.create = function() { - if (!_initialized) { - _init(); - } - var _state = null; - var _input = forge2.util.createBuffer(); - var _w = new Array(16); - var md = { - algorithm: "md5", - blockLength: 64, - digestLength: 16, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; - md.start = function() { - md.messageLength = 0; - md.fullMessageLength = md.messageLength64 = []; - var int32s = md.messageLengthSize / 4; - for (var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); - } - _input = forge2.util.createBuffer(); - _state = { - h0: 1732584193, - h1: 4023233417, - h2: 2562383102, - h3: 271733878 - }; - return md; - }; - md.start(); - md.update = function(msg, encoding) { - if (encoding === "utf8") { - msg = forge2.util.encodeUtf8(msg); - } - var len = msg.length; - md.messageLength += len; - len = [len / 4294967296 >>> 0, len >>> 0]; - for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + (md.fullMessageLength[i] / 4294967296 >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = len[1] / 4294967296 >>> 0; - } - _input.putBytes(msg); - _update(_state, _w, _input); - if (_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - return md; - }; - md.digest = function() { - var finalBlock = forge2.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; - var overflow = remaining & md.blockLength - 1; - finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); - var bits, carry = 0; - for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { - bits = md.fullMessageLength[i] * 8 + carry; - carry = bits / 4294967296 >>> 0; - finalBlock.putInt32Le(bits >>> 0); - } - var s2 = { - h0: _state.h0, - h1: _state.h1, - h2: _state.h2, - h3: _state.h3 - }; - _update(s2, _w, finalBlock); - var rval = forge2.util.createBuffer(); - rval.putInt32Le(s2.h0); - rval.putInt32Le(s2.h1); - rval.putInt32Le(s2.h2); - rval.putInt32Le(s2.h3); - return rval; - }; - return md; - }; - var _padding = null; - var _g = null; - var _r = null; - var _k = null; - var _initialized = false; - function _init() { - _padding = String.fromCharCode(128); - _padding += forge2.util.fillString(String.fromCharCode(0), 64); - _g = [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 1, - 6, - 11, - 0, - 5, - 10, - 15, - 4, - 9, - 14, - 3, - 8, - 13, - 2, - 7, - 12, - 5, - 8, - 11, - 14, - 1, - 4, - 7, - 10, - 13, - 0, - 3, - 6, - 9, - 12, - 15, - 2, - 0, - 7, - 14, - 5, - 12, - 3, - 10, - 1, - 8, - 15, - 6, - 13, - 4, - 11, - 2, - 9 - ]; - _r = [ - 7, - 12, - 17, - 22, - 7, - 12, - 17, - 22, - 7, - 12, - 17, - 22, - 7, - 12, - 17, - 22, - 5, - 9, - 14, - 20, - 5, - 9, - 14, - 20, - 5, - 9, - 14, - 20, - 5, - 9, - 14, - 20, - 4, - 11, - 16, - 23, - 4, - 11, - 16, - 23, - 4, - 11, - 16, - 23, - 4, - 11, - 16, - 23, - 6, - 10, - 15, - 21, - 6, - 10, - 15, - 21, - 6, - 10, - 15, - 21, - 6, - 10, - 15, - 21 - ]; - _k = new Array(64); - for (var i = 0; i < 64; ++i) { - _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296); - } - _initialized = true; - } - function _update(s, w, bytes) { - var t, a, b, c, d, f, r, i; - var len = bytes.length(); - while (len >= 64) { - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; - for (i = 0; i < 16; ++i) { - w[i] = bytes.getInt32Le(); - f = d ^ b & (c ^ d); - t = a + f + _k[i] + w[i]; - r = _r[i]; - a = d; - d = c; - c = b; - b += t << r | t >>> 32 - r; - } - for (; i < 32; ++i) { - f = c ^ d & (b ^ c); - t = a + f + _k[i] + w[_g[i]]; - r = _r[i]; - a = d; - d = c; - c = b; - b += t << r | t >>> 32 - r; - } - for (; i < 48; ++i) { - f = b ^ c ^ d; - t = a + f + _k[i] + w[_g[i]]; - r = _r[i]; - a = d; - d = c; - c = b; - b += t << r | t >>> 32 - r; - } - for (; i < 64; ++i) { - f = c ^ (b | ~d); - t = a + f + _k[i] + w[_g[i]]; - r = _r[i]; - a = d; - d = c; - c = b; - b += t << r | t >>> 32 - r; - } - s.h0 = s.h0 + a | 0; - s.h1 = s.h1 + b | 0; - s.h2 = s.h2 + c | 0; - s.h3 = s.h3 + d | 0; - len -= 64; - } - } - } -}); - -// node_modules/node-forge/lib/pem.js -var require_pem = __commonJS({ - "node_modules/node-forge/lib/pem.js"(exports, module) { - var forge2 = require_forge(); - require_util(); - var pem = module.exports = forge2.pem = forge2.pem || {}; - pem.encode = function(msg, options) { - options = options || {}; - var rval = "-----BEGIN " + msg.type + "-----\r\n"; - var header; - if (msg.procType) { - header = { - name: "Proc-Type", - values: [String(msg.procType.version), msg.procType.type] - }; - rval += foldHeader(header); - } - if (msg.contentDomain) { - header = { name: "Content-Domain", values: [msg.contentDomain] }; - rval += foldHeader(header); - } - if (msg.dekInfo) { - header = { name: "DEK-Info", values: [msg.dekInfo.algorithm] }; - if (msg.dekInfo.parameters) { - header.values.push(msg.dekInfo.parameters); - } - rval += foldHeader(header); - } - if (msg.headers) { - for (var i = 0; i < msg.headers.length; ++i) { - rval += foldHeader(msg.headers[i]); - } - } - if (msg.procType) { - rval += "\r\n"; - } - rval += forge2.util.encode64(msg.body, options.maxline || 64) + "\r\n"; - rval += "-----END " + msg.type + "-----\r\n"; - return rval; - }; - pem.decode = function(str) { - var rval = []; - var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g; - var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/; - var rCRLF = /\r?\n/; - var match; - while (true) { - match = rMessage.exec(str); - if (!match) { - break; - } - var type = match[1]; - if (type === "NEW CERTIFICATE REQUEST") { - type = "CERTIFICATE REQUEST"; - } - var msg = { - type, - procType: null, - contentDomain: null, - dekInfo: null, - headers: [], - body: forge2.util.decode64(match[3]) - }; - rval.push(msg); - if (!match[2]) { - continue; - } - var lines = match[2].split(rCRLF); - var li = 0; - while (match && li < lines.length) { - var line = lines[li].replace(/\s+$/, ""); - for (var nl = li + 1; nl < lines.length; ++nl) { - var next = lines[nl]; - if (!/\s/.test(next[0])) { - break; - } - line += next; - li = nl; - } - match = line.match(rHeader); - if (match) { - var header = { name: match[1], values: [] }; - var values = match[2].split(","); - for (var vi = 0; vi < values.length; ++vi) { - header.values.push(ltrim(values[vi])); - } - if (!msg.procType) { - if (header.name !== "Proc-Type") { - throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".'); - } else if (header.values.length !== 2) { - throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.'); - } - msg.procType = { version: values[0], type: values[1] }; - } else if (!msg.contentDomain && header.name === "Content-Domain") { - msg.contentDomain = values[0] || ""; - } else if (!msg.dekInfo && header.name === "DEK-Info") { - if (header.values.length === 0) { - throw new Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.'); - } - msg.dekInfo = { algorithm: values[0], parameters: values[1] || null }; - } else { - msg.headers.push(header); - } - } - ++li; - } - if (msg.procType === "ENCRYPTED" && !msg.dekInfo) { - throw new Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".'); - } - } - if (rval.length === 0) { - throw new Error("Invalid PEM formatted message."); - } - return rval; - }; - function foldHeader(header) { - var rval = header.name + ": "; - var values = []; - var insertSpace = function(match, $1) { - return " " + $1; - }; - for (var i = 0; i < header.values.length; ++i) { - values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace)); - } - rval += values.join(",") + "\r\n"; - var length = 0; - var candidate = -1; - for (var i = 0; i < rval.length; ++i, ++length) { - if (length > 65 && candidate !== -1) { - var insert = rval[candidate]; - if (insert === ",") { - ++candidate; - rval = rval.substr(0, candidate) + "\r\n " + rval.substr(candidate); - } else { - rval = rval.substr(0, candidate) + "\r\n" + insert + rval.substr(candidate + 1); - } - length = i - candidate - 1; - candidate = -1; - ++i; - } else if (rval[i] === " " || rval[i] === " " || rval[i] === ",") { - candidate = i; - } - } - return rval; - } - function ltrim(str) { - return str.replace(/^\s+/, ""); - } - } -}); - -// node_modules/node-forge/lib/des.js -var require_des = __commonJS({ - "node_modules/node-forge/lib/des.js"(exports, module) { - var forge2 = require_forge(); - require_cipher(); - require_cipherModes(); - require_util(); - module.exports = forge2.des = forge2.des || {}; - forge2.des.startEncrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key, - output, - decrypt: false, - mode: mode || (iv === null ? "ECB" : "CBC") - }); - cipher.start(iv); - return cipher; - }; - forge2.des.createEncryptionCipher = function(key, mode) { - return _createCipher({ - key, - output: null, - decrypt: false, - mode - }); - }; - forge2.des.startDecrypting = function(key, iv, output, mode) { - var cipher = _createCipher({ - key, - output, - decrypt: true, - mode: mode || (iv === null ? "ECB" : "CBC") - }); - cipher.start(iv); - return cipher; - }; - forge2.des.createDecryptionCipher = function(key, mode) { - return _createCipher({ - key, - output: null, - decrypt: true, - mode - }); - }; - forge2.des.Algorithm = function(name, mode) { - var self2 = this; - self2.name = name; - self2.mode = new mode({ - blockSize: 8, - cipher: { - encrypt: function(inBlock, outBlock) { - return _updateBlock(self2._keys, inBlock, outBlock, false); - }, - decrypt: function(inBlock, outBlock) { - return _updateBlock(self2._keys, inBlock, outBlock, true); - } - } - }); - self2._init = false; - }; - forge2.des.Algorithm.prototype.initialize = function(options) { - if (this._init) { - return; - } - var key = forge2.util.createBuffer(options.key); - if (this.name.indexOf("3DES") === 0) { - if (key.length() !== 24) { - throw new Error("Invalid Triple-DES key size: " + key.length() * 8); - } - } - this._keys = _createKeys(key); - this._init = true; - }; - registerAlgorithm("DES-ECB", forge2.cipher.modes.ecb); - registerAlgorithm("DES-CBC", forge2.cipher.modes.cbc); - registerAlgorithm("DES-CFB", forge2.cipher.modes.cfb); - registerAlgorithm("DES-OFB", forge2.cipher.modes.ofb); - registerAlgorithm("DES-CTR", forge2.cipher.modes.ctr); - registerAlgorithm("3DES-ECB", forge2.cipher.modes.ecb); - registerAlgorithm("3DES-CBC", forge2.cipher.modes.cbc); - registerAlgorithm("3DES-CFB", forge2.cipher.modes.cfb); - registerAlgorithm("3DES-OFB", forge2.cipher.modes.ofb); - registerAlgorithm("3DES-CTR", forge2.cipher.modes.ctr); - function registerAlgorithm(name, mode) { - var factory = function() { - return new forge2.des.Algorithm(name, mode); - }; - forge2.cipher.registerAlgorithm(name, factory); - } - var spfunction1 = [16843776, 0, 65536, 16843780, 16842756, 66564, 4, 65536, 1024, 16843776, 16843780, 1024, 16778244, 16842756, 16777216, 4, 1028, 16778240, 16778240, 66560, 66560, 16842752, 16842752, 16778244, 65540, 16777220, 16777220, 65540, 0, 1028, 66564, 16777216, 65536, 16843780, 4, 16842752, 16843776, 16777216, 16777216, 1024, 16842756, 65536, 66560, 16777220, 1024, 4, 16778244, 66564, 16843780, 65540, 16842752, 16778244, 16777220, 1028, 66564, 16843776, 1028, 16778240, 16778240, 0, 65540, 66560, 0, 16842756]; - var spfunction2 = [-2146402272, -2147450880, 32768, 1081376, 1048576, 32, -2146435040, -2147450848, -2147483616, -2146402272, -2146402304, -2147483648, -2147450880, 1048576, 32, -2146435040, 1081344, 1048608, -2147450848, 0, -2147483648, 32768, 1081376, -2146435072, 1048608, -2147483616, 0, 1081344, 32800, -2146402304, -2146435072, 32800, 0, 1081376, -2146435040, 1048576, -2147450848, -2146435072, -2146402304, 32768, -2146435072, -2147450880, 32, -2146402272, 1081376, 32, 32768, -2147483648, 32800, -2146402304, 1048576, -2147483616, 1048608, -2147450848, -2147483616, 1048608, 1081344, 0, -2147450880, 32800, -2147483648, -2146435040, -2146402272, 1081344]; - var spfunction3 = [520, 134349312, 0, 134348808, 134218240, 0, 131592, 134218240, 131080, 134217736, 134217736, 131072, 134349320, 131080, 134348800, 520, 134217728, 8, 134349312, 512, 131584, 134348800, 134348808, 131592, 134218248, 131584, 131072, 134218248, 8, 134349320, 512, 134217728, 134349312, 134217728, 131080, 520, 131072, 134349312, 134218240, 0, 512, 131080, 134349320, 134218240, 134217736, 512, 0, 134348808, 134218248, 131072, 134217728, 134349320, 8, 131592, 131584, 134217736, 134348800, 134218248, 520, 134348800, 131592, 8, 134348808, 131584]; - var spfunction4 = [8396801, 8321, 8321, 128, 8396928, 8388737, 8388609, 8193, 0, 8396800, 8396800, 8396929, 129, 0, 8388736, 8388609, 1, 8192, 8388608, 8396801, 128, 8388608, 8193, 8320, 8388737, 1, 8320, 8388736, 8192, 8396928, 8396929, 129, 8388736, 8388609, 8396800, 8396929, 129, 0, 0, 8396800, 8320, 8388736, 8388737, 1, 8396801, 8321, 8321, 128, 8396929, 129, 1, 8192, 8388609, 8193, 8396928, 8388737, 8193, 8320, 8388608, 8396801, 128, 8388608, 8192, 8396928]; - var spfunction5 = [256, 34078976, 34078720, 1107296512, 524288, 256, 1073741824, 34078720, 1074266368, 524288, 33554688, 1074266368, 1107296512, 1107820544, 524544, 1073741824, 33554432, 1074266112, 1074266112, 0, 1073742080, 1107820800, 1107820800, 33554688, 1107820544, 1073742080, 0, 1107296256, 34078976, 33554432, 1107296256, 524544, 524288, 1107296512, 256, 33554432, 1073741824, 34078720, 1107296512, 1074266368, 33554688, 1073741824, 1107820544, 34078976, 1074266368, 256, 33554432, 1107820544, 1107820800, 524544, 1107296256, 1107820800, 34078720, 0, 1074266112, 1107296256, 524544, 33554688, 1073742080, 524288, 0, 1074266112, 34078976, 1073742080]; - var spfunction6 = [536870928, 541065216, 16384, 541081616, 541065216, 16, 541081616, 4194304, 536887296, 4210704, 4194304, 536870928, 4194320, 536887296, 536870912, 16400, 0, 4194320, 536887312, 16384, 4210688, 536887312, 16, 541065232, 541065232, 0, 4210704, 541081600, 16400, 4210688, 541081600, 536870912, 536887296, 16, 541065232, 4210688, 541081616, 4194304, 16400, 536870928, 4194304, 536887296, 536870912, 16400, 536870928, 541081616, 4210688, 541065216, 4210704, 541081600, 0, 541065232, 16, 16384, 541065216, 4210704, 16384, 4194320, 536887312, 0, 541081600, 536870912, 4194320, 536887312]; - var spfunction7 = [2097152, 69206018, 67110914, 0, 2048, 67110914, 2099202, 69208064, 69208066, 2097152, 0, 67108866, 2, 67108864, 69206018, 2050, 67110912, 2099202, 2097154, 67110912, 67108866, 69206016, 69208064, 2097154, 69206016, 2048, 2050, 69208066, 2099200, 2, 67108864, 2099200, 67108864, 2099200, 2097152, 67110914, 67110914, 69206018, 69206018, 2, 2097154, 67108864, 67110912, 2097152, 69208064, 2050, 2099202, 69208064, 2050, 67108866, 69208066, 69206016, 2099200, 0, 2, 69208066, 0, 2099202, 69206016, 2048, 67108866, 67110912, 2048, 2097154]; - var spfunction8 = [268439616, 4096, 262144, 268701760, 268435456, 268439616, 64, 268435456, 262208, 268697600, 268701760, 266240, 268701696, 266304, 4096, 64, 268697600, 268435520, 268439552, 4160, 266240, 262208, 268697664, 268701696, 4160, 0, 0, 268697664, 268435520, 268439552, 266304, 262144, 266304, 262144, 268701696, 4096, 64, 268697664, 4096, 266304, 268439552, 64, 268435520, 268697600, 268697664, 268435456, 262144, 268439616, 0, 268701760, 262208, 268435520, 268697600, 268439552, 268439616, 0, 268701760, 266240, 266240, 4160, 4160, 262208, 268435456, 268701696]; - function _createKeys(key) { - var pc2bytes0 = [0, 4, 536870912, 536870916, 65536, 65540, 536936448, 536936452, 512, 516, 536871424, 536871428, 66048, 66052, 536936960, 536936964], pc2bytes1 = [0, 1, 1048576, 1048577, 67108864, 67108865, 68157440, 68157441, 256, 257, 1048832, 1048833, 67109120, 67109121, 68157696, 68157697], pc2bytes2 = [0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272, 0, 8, 2048, 2056, 16777216, 16777224, 16779264, 16779272], pc2bytes3 = [0, 2097152, 134217728, 136314880, 8192, 2105344, 134225920, 136323072, 131072, 2228224, 134348800, 136445952, 139264, 2236416, 134356992, 136454144], pc2bytes4 = [0, 262144, 16, 262160, 0, 262144, 16, 262160, 4096, 266240, 4112, 266256, 4096, 266240, 4112, 266256], pc2bytes5 = [0, 1024, 32, 1056, 0, 1024, 32, 1056, 33554432, 33555456, 33554464, 33555488, 33554432, 33555456, 33554464, 33555488], pc2bytes6 = [0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746, 0, 268435456, 524288, 268959744, 2, 268435458, 524290, 268959746], pc2bytes7 = [0, 65536, 2048, 67584, 536870912, 536936448, 536872960, 536938496, 131072, 196608, 133120, 198656, 537001984, 537067520, 537004032, 537069568], pc2bytes8 = [0, 262144, 0, 262144, 2, 262146, 2, 262146, 33554432, 33816576, 33554432, 33816576, 33554434, 33816578, 33554434, 33816578], pc2bytes9 = [0, 268435456, 8, 268435464, 0, 268435456, 8, 268435464, 1024, 268436480, 1032, 268436488, 1024, 268436480, 1032, 268436488], pc2bytes10 = [0, 32, 0, 32, 1048576, 1048608, 1048576, 1048608, 8192, 8224, 8192, 8224, 1056768, 1056800, 1056768, 1056800], pc2bytes11 = [0, 16777216, 512, 16777728, 2097152, 18874368, 2097664, 18874880, 67108864, 83886080, 67109376, 83886592, 69206016, 85983232, 69206528, 85983744], pc2bytes12 = [0, 4096, 134217728, 134221824, 524288, 528384, 134742016, 134746112, 16, 4112, 134217744, 134221840, 524304, 528400, 134742032, 134746128], pc2bytes13 = [0, 4, 256, 260, 0, 4, 256, 260, 1, 5, 257, 261, 1, 5, 257, 261]; - var iterations = key.length() > 8 ? 3 : 1; - var keys = []; - var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; - var n = 0, tmp; - for (var j = 0; j < iterations; j++) { - var left = key.getInt32(); - var right = key.getInt32(); - tmp = (left >>> 4 ^ right) & 252645135; - right ^= tmp; - left ^= tmp << 4; - tmp = (right >>> -16 ^ left) & 65535; - left ^= tmp; - right ^= tmp << -16; - tmp = (left >>> 2 ^ right) & 858993459; - right ^= tmp; - left ^= tmp << 2; - tmp = (right >>> -16 ^ left) & 65535; - left ^= tmp; - right ^= tmp << -16; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - tmp = (right >>> 8 ^ left) & 16711935; - left ^= tmp; - right ^= tmp << 8; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - tmp = left << 8 | right >>> 20 & 240; - left = right << 24 | right << 8 & 16711680 | right >>> 8 & 65280 | right >>> 24 & 240; - right = tmp; - for (var i = 0; i < shifts.length; ++i) { - if (shifts[i]) { - left = left << 2 | left >>> 26; - right = right << 2 | right >>> 26; - } else { - left = left << 1 | left >>> 27; - right = right << 1 | right >>> 27; - } - left &= -15; - right &= -15; - var lefttmp = pc2bytes0[left >>> 28] | pc2bytes1[left >>> 24 & 15] | pc2bytes2[left >>> 20 & 15] | pc2bytes3[left >>> 16 & 15] | pc2bytes4[left >>> 12 & 15] | pc2bytes5[left >>> 8 & 15] | pc2bytes6[left >>> 4 & 15]; - var righttmp = pc2bytes7[right >>> 28] | pc2bytes8[right >>> 24 & 15] | pc2bytes9[right >>> 20 & 15] | pc2bytes10[right >>> 16 & 15] | pc2bytes11[right >>> 12 & 15] | pc2bytes12[right >>> 8 & 15] | pc2bytes13[right >>> 4 & 15]; - tmp = (righttmp >>> 16 ^ lefttmp) & 65535; - keys[n++] = lefttmp ^ tmp; - keys[n++] = righttmp ^ tmp << 16; - } - } - return keys; - } - function _updateBlock(keys, input, output, decrypt) { - var iterations = keys.length === 32 ? 3 : 9; - var looping; - if (iterations === 3) { - looping = decrypt ? [30, -2, -2] : [0, 32, 2]; - } else { - looping = decrypt ? [94, 62, -2, 32, 64, 2, 30, -2, -2] : [0, 32, 2, 62, 30, -2, 64, 96, 2]; - } - var tmp; - var left = input[0]; - var right = input[1]; - tmp = (left >>> 4 ^ right) & 252645135; - right ^= tmp; - left ^= tmp << 4; - tmp = (left >>> 16 ^ right) & 65535; - right ^= tmp; - left ^= tmp << 16; - tmp = (right >>> 2 ^ left) & 858993459; - left ^= tmp; - right ^= tmp << 2; - tmp = (right >>> 8 ^ left) & 16711935; - left ^= tmp; - right ^= tmp << 8; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - left = left << 1 | left >>> 31; - right = right << 1 | right >>> 31; - for (var j = 0; j < iterations; j += 3) { - var endloop = looping[j + 1]; - var loopinc = looping[j + 2]; - for (var i = looping[j]; i != endloop; i += loopinc) { - var right1 = right ^ keys[i]; - var right2 = (right >>> 4 | right << 28) ^ keys[i + 1]; - tmp = left; - left = right; - right = tmp ^ (spfunction2[right1 >>> 24 & 63] | spfunction4[right1 >>> 16 & 63] | spfunction6[right1 >>> 8 & 63] | spfunction8[right1 & 63] | spfunction1[right2 >>> 24 & 63] | spfunction3[right2 >>> 16 & 63] | spfunction5[right2 >>> 8 & 63] | spfunction7[right2 & 63]); - } - tmp = left; - left = right; - right = tmp; - } - left = left >>> 1 | left << 31; - right = right >>> 1 | right << 31; - tmp = (left >>> 1 ^ right) & 1431655765; - right ^= tmp; - left ^= tmp << 1; - tmp = (right >>> 8 ^ left) & 16711935; - left ^= tmp; - right ^= tmp << 8; - tmp = (right >>> 2 ^ left) & 858993459; - left ^= tmp; - right ^= tmp << 2; - tmp = (left >>> 16 ^ right) & 65535; - right ^= tmp; - left ^= tmp << 16; - tmp = (left >>> 4 ^ right) & 252645135; - right ^= tmp; - left ^= tmp << 4; - output[0] = left; - output[1] = right; - } - function _createCipher(options) { - options = options || {}; - var mode = (options.mode || "CBC").toUpperCase(); - var algorithm = "DES-" + mode; - var cipher; - if (options.decrypt) { - cipher = forge2.cipher.createDecipher(algorithm, options.key); - } else { - cipher = forge2.cipher.createCipher(algorithm, options.key); - } - var start = cipher.start; - cipher.start = function(iv, options2) { - var output = null; - if (options2 instanceof forge2.util.ByteBuffer) { - output = options2; - options2 = {}; - } - options2 = options2 || {}; - options2.output = output; - options2.iv = iv; - start.call(cipher, options2); - }; - return cipher; - } - } -}); - -// node_modules/node-forge/lib/pbkdf2.js -var require_pbkdf2 = __commonJS({ - "node_modules/node-forge/lib/pbkdf2.js"(exports, module) { - var forge2 = require_forge(); - require_hmac(); - require_md(); - require_util(); - var pkcs5 = forge2.pkcs5 = forge2.pkcs5 || {}; - var crypto; - if (forge2.util.isNodejs && !forge2.options.usePureJavaScript) { - crypto = __require("crypto"); - } - module.exports = forge2.pbkdf2 = pkcs5.pbkdf2 = function(p, s, c, dkLen, md, callback) { - if (typeof md === "function") { - callback = md; - md = null; - } - if (forge2.util.isNodejs && !forge2.options.usePureJavaScript && crypto.pbkdf2 && (md === null || typeof md !== "object") && (crypto.pbkdf2Sync.length > 4 || (!md || md === "sha1"))) { - if (typeof md !== "string") { - md = "sha1"; - } - p = Buffer.from(p, "binary"); - s = Buffer.from(s, "binary"); - if (!callback) { - if (crypto.pbkdf2Sync.length === 4) { - return crypto.pbkdf2Sync(p, s, c, dkLen).toString("binary"); - } - return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString("binary"); - } - if (crypto.pbkdf2Sync.length === 4) { - return crypto.pbkdf2(p, s, c, dkLen, function(err2, key) { - if (err2) { - return callback(err2); - } - callback(null, key.toString("binary")); - }); - } - return crypto.pbkdf2(p, s, c, dkLen, md, function(err2, key) { - if (err2) { - return callback(err2); - } - callback(null, key.toString("binary")); - }); - } - if (typeof md === "undefined" || md === null) { - md = "sha1"; - } - if (typeof md === "string") { - if (!(md in forge2.md.algorithms)) { - throw new Error("Unknown hash algorithm: " + md); - } - md = forge2.md[md].create(); - } - var hLen = md.digestLength; - if (dkLen > 4294967295 * hLen) { - var err = new Error("Derived key is too long."); - if (callback) { - return callback(err); - } - throw err; - } - var len = Math.ceil(dkLen / hLen); - var r = dkLen - (len - 1) * hLen; - var prf = forge2.hmac.create(); - prf.start(md, p); - var dk = ""; - var xor, u_c, u_c1; - if (!callback) { - for (var i = 1; i <= len; ++i) { - prf.start(null, null); - prf.update(s); - prf.update(forge2.util.int32ToBytes(i)); - xor = u_c1 = prf.digest().getBytes(); - for (var j = 2; j <= c; ++j) { - prf.start(null, null); - prf.update(u_c1); - u_c = prf.digest().getBytes(); - xor = forge2.util.xorBytes(xor, u_c, hLen); - u_c1 = u_c; - } - dk += i < len ? xor : xor.substr(0, r); - } - return dk; - } - var i = 1, j; - function outer() { - if (i > len) { - return callback(null, dk); - } - prf.start(null, null); - prf.update(s); - prf.update(forge2.util.int32ToBytes(i)); - xor = u_c1 = prf.digest().getBytes(); - j = 2; - inner(); - } - function inner() { - if (j <= c) { - prf.start(null, null); - prf.update(u_c1); - u_c = prf.digest().getBytes(); - xor = forge2.util.xorBytes(xor, u_c, hLen); - u_c1 = u_c; - ++j; - return forge2.util.setImmediate(inner); - } - dk += i < len ? xor : xor.substr(0, r); - ++i; - outer(); - } - outer(); - }; - } -}); - -// node_modules/node-forge/lib/sha256.js -var require_sha256 = __commonJS({ - "node_modules/node-forge/lib/sha256.js"(exports, module) { - var forge2 = require_forge(); - require_md(); - require_util(); - var sha256 = module.exports = forge2.sha256 = forge2.sha256 || {}; - forge2.md.sha256 = forge2.md.algorithms.sha256 = sha256; - sha256.create = function() { - if (!_initialized) { - _init(); - } - var _state = null; - var _input = forge2.util.createBuffer(); - var _w = new Array(64); - var md = { - algorithm: "sha256", - blockLength: 64, - digestLength: 32, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; - md.start = function() { - md.messageLength = 0; - md.fullMessageLength = md.messageLength64 = []; - var int32s = md.messageLengthSize / 4; - for (var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); - } - _input = forge2.util.createBuffer(); - _state = { - h0: 1779033703, - h1: 3144134277, - h2: 1013904242, - h3: 2773480762, - h4: 1359893119, - h5: 2600822924, - h6: 528734635, - h7: 1541459225 - }; - return md; - }; - md.start(); - md.update = function(msg, encoding) { - if (encoding === "utf8") { - msg = forge2.util.encodeUtf8(msg); - } - var len = msg.length; - md.messageLength += len; - len = [len / 4294967296 >>> 0, len >>> 0]; - for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + (md.fullMessageLength[i] / 4294967296 >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = len[1] / 4294967296 >>> 0; - } - _input.putBytes(msg); - _update(_state, _w, _input); - if (_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - return md; - }; - md.digest = function() { - var finalBlock = forge2.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; - var overflow = remaining & md.blockLength - 1; - finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); - var next, carry; - var bits = md.fullMessageLength[0] * 8; - for (var i = 0; i < md.fullMessageLength.length - 1; ++i) { - next = md.fullMessageLength[i + 1] * 8; - carry = next / 4294967296 >>> 0; - bits += carry; - finalBlock.putInt32(bits >>> 0); - bits = next >>> 0; - } - finalBlock.putInt32(bits); - var s2 = { - h0: _state.h0, - h1: _state.h1, - h2: _state.h2, - h3: _state.h3, - h4: _state.h4, - h5: _state.h5, - h6: _state.h6, - h7: _state.h7 - }; - _update(s2, _w, finalBlock); - var rval = forge2.util.createBuffer(); - rval.putInt32(s2.h0); - rval.putInt32(s2.h1); - rval.putInt32(s2.h2); - rval.putInt32(s2.h3); - rval.putInt32(s2.h4); - rval.putInt32(s2.h5); - rval.putInt32(s2.h6); - rval.putInt32(s2.h7); - return rval; - }; - return md; - }; - var _padding = null; - var _initialized = false; - var _k = null; - function _init() { - _padding = String.fromCharCode(128); - _padding += forge2.util.fillString(String.fromCharCode(0), 64); - _k = [ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 - ]; - _initialized = true; - } - function _update(s, w, bytes) { - var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h; - var len = bytes.length(); - while (len >= 64) { - for (i = 0; i < 16; ++i) { - w[i] = bytes.getInt32(); - } - for (; i < 64; ++i) { - t1 = w[i - 2]; - t1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10; - t2 = w[i - 15]; - t2 = (t2 >>> 7 | t2 << 25) ^ (t2 >>> 18 | t2 << 14) ^ t2 >>> 3; - w[i] = t1 + w[i - 7] + t2 + w[i - 16] | 0; - } - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; - e = s.h4; - f = s.h5; - g = s.h6; - h = s.h7; - for (i = 0; i < 64; ++i) { - s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7); - ch = g ^ e & (f ^ g); - s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); - maj = a & b | c & (a ^ b); - t1 = h + s1 + ch + _k[i] + w[i]; - t2 = s0 + maj; - h = g; - g = f; - f = e; - e = d + t1 >>> 0; - d = c; - c = b; - b = a; - a = t1 + t2 >>> 0; - } - s.h0 = s.h0 + a | 0; - s.h1 = s.h1 + b | 0; - s.h2 = s.h2 + c | 0; - s.h3 = s.h3 + d | 0; - s.h4 = s.h4 + e | 0; - s.h5 = s.h5 + f | 0; - s.h6 = s.h6 + g | 0; - s.h7 = s.h7 + h | 0; - len -= 64; - } - } - } -}); - -// node_modules/node-forge/lib/prng.js -var require_prng = __commonJS({ - "node_modules/node-forge/lib/prng.js"(exports, module) { - var forge2 = require_forge(); - require_util(); - var _crypto = null; - if (forge2.util.isNodejs && !forge2.options.usePureJavaScript && !process.versions["node-webkit"]) { - _crypto = __require("crypto"); - } - var prng = module.exports = forge2.prng = forge2.prng || {}; - prng.create = function(plugin) { - var ctx = { - plugin, - key: null, - seed: null, - time: null, - // number of reseeds so far - reseeds: 0, - // amount of data generated so far - generated: 0, - // no initial key bytes - keyBytes: "" - }; - var md = plugin.md; - var pools = new Array(32); - for (var i = 0; i < 32; ++i) { - pools[i] = md.create(); - } - ctx.pools = pools; - ctx.pool = 0; - ctx.generate = function(count, callback) { - if (!callback) { - return ctx.generateSync(count); - } - var cipher = ctx.plugin.cipher; - var increment = ctx.plugin.increment; - var formatKey = ctx.plugin.formatKey; - var formatSeed = ctx.plugin.formatSeed; - var b = forge2.util.createBuffer(); - ctx.key = null; - generate(); - function generate(err) { - if (err) { - return callback(err); - } - if (b.length() >= count) { - return callback(null, b.getBytes(count)); - } - if (ctx.generated > 1048575) { - ctx.key = null; - } - if (ctx.key === null) { - return forge2.util.nextTick(function() { - _reseed(generate); - }); - } - var bytes = cipher(ctx.key, ctx.seed); - ctx.generated += bytes.length; - b.putBytes(bytes); - ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); - ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); - forge2.util.setImmediate(generate); - } - }; - ctx.generateSync = function(count) { - var cipher = ctx.plugin.cipher; - var increment = ctx.plugin.increment; - var formatKey = ctx.plugin.formatKey; - var formatSeed = ctx.plugin.formatSeed; - ctx.key = null; - var b = forge2.util.createBuffer(); - while (b.length() < count) { - if (ctx.generated > 1048575) { - ctx.key = null; - } - if (ctx.key === null) { - _reseedSync(); - } - var bytes = cipher(ctx.key, ctx.seed); - ctx.generated += bytes.length; - b.putBytes(bytes); - ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); - ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); - } - return b.getBytes(count); - }; - function _reseed(callback) { - if (ctx.pools[0].messageLength >= 32) { - _seed(); - return callback(); - } - var needed = 32 - ctx.pools[0].messageLength << 5; - ctx.seedFile(needed, function(err, bytes) { - if (err) { - return callback(err); - } - ctx.collect(bytes); - _seed(); - callback(); - }); - } - function _reseedSync() { - if (ctx.pools[0].messageLength >= 32) { - return _seed(); - } - var needed = 32 - ctx.pools[0].messageLength << 5; - ctx.collect(ctx.seedFileSync(needed)); - _seed(); - } - function _seed() { - ctx.reseeds = ctx.reseeds === 4294967295 ? 0 : ctx.reseeds + 1; - var md2 = ctx.plugin.md.create(); - md2.update(ctx.keyBytes); - var _2powK = 1; - for (var k = 0; k < 32; ++k) { - if (ctx.reseeds % _2powK === 0) { - md2.update(ctx.pools[k].digest().getBytes()); - ctx.pools[k].start(); - } - _2powK = _2powK << 1; - } - ctx.keyBytes = md2.digest().getBytes(); - md2.start(); - md2.update(ctx.keyBytes); - var seedBytes = md2.digest().getBytes(); - ctx.key = ctx.plugin.formatKey(ctx.keyBytes); - ctx.seed = ctx.plugin.formatSeed(seedBytes); - ctx.generated = 0; - } - function defaultSeedFile(needed) { - var getRandomValues = null; - var globalScope = forge2.util.globalScope; - var _crypto2 = globalScope.crypto || globalScope.msCrypto; - if (_crypto2 && _crypto2.getRandomValues) { - getRandomValues = function(arr) { - return _crypto2.getRandomValues(arr); - }; - } - var b = forge2.util.createBuffer(); - if (getRandomValues) { - while (b.length() < needed) { - var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4); - var entropy = new Uint32Array(Math.floor(count)); - try { - getRandomValues(entropy); - for (var i2 = 0; i2 < entropy.length; ++i2) { - b.putInt32(entropy[i2]); - } - } catch (e) { - if (!(typeof QuotaExceededError !== "undefined" && e instanceof QuotaExceededError)) { - throw e; - } - } - } - } - if (b.length() < needed) { - var hi, lo, next; - var seed = Math.floor(Math.random() * 65536); - while (b.length() < needed) { - lo = 16807 * (seed & 65535); - hi = 16807 * (seed >> 16); - lo += (hi & 32767) << 16; - lo += hi >> 15; - lo = (lo & 2147483647) + (lo >> 31); - seed = lo & 4294967295; - for (var i2 = 0; i2 < 3; ++i2) { - next = seed >>> (i2 << 3); - next ^= Math.floor(Math.random() * 256); - b.putByte(next & 255); - } - } - } - return b.getBytes(needed); - } - if (_crypto) { - ctx.seedFile = function(needed, callback) { - _crypto.randomBytes(needed, function(err, bytes) { - if (err) { - return callback(err); - } - callback(null, bytes.toString()); - }); - }; - ctx.seedFileSync = function(needed) { - return _crypto.randomBytes(needed).toString(); - }; - } else { - ctx.seedFile = function(needed, callback) { - try { - callback(null, defaultSeedFile(needed)); - } catch (e) { - callback(e); - } - }; - ctx.seedFileSync = defaultSeedFile; - } - ctx.collect = function(bytes) { - var count = bytes.length; - for (var i2 = 0; i2 < count; ++i2) { - ctx.pools[ctx.pool].update(bytes.substr(i2, 1)); - ctx.pool = ctx.pool === 31 ? 0 : ctx.pool + 1; - } - }; - ctx.collectInt = function(i2, n) { - var bytes = ""; - for (var x = 0; x < n; x += 8) { - bytes += String.fromCharCode(i2 >> x & 255); - } - ctx.collect(bytes); - }; - ctx.registerWorker = function(worker) { - if (worker === self) { - ctx.seedFile = function(needed, callback) { - function listener2(e) { - var data = e.data; - if (data.forge && data.forge.prng) { - self.removeEventListener("message", listener2); - callback(data.forge.prng.err, data.forge.prng.bytes); - } - } - self.addEventListener("message", listener2); - self.postMessage({ forge: { prng: { needed } } }); - }; - } else { - var listener = function(e) { - var data = e.data; - if (data.forge && data.forge.prng) { - ctx.seedFile(data.forge.prng.needed, function(err, bytes) { - worker.postMessage({ forge: { prng: { err, bytes } } }); - }); - } - }; - worker.addEventListener("message", listener); - } - }; - return ctx; - }; - } -}); - -// node_modules/node-forge/lib/random.js -var require_random = __commonJS({ - "node_modules/node-forge/lib/random.js"(exports, module) { - var forge2 = require_forge(); - require_aes(); - require_sha256(); - require_prng(); - require_util(); - (function() { - if (forge2.random && forge2.random.getBytes) { - module.exports = forge2.random; - return; - } - (function(jQuery2) { - var prng_aes = {}; - var _prng_aes_output = new Array(4); - var _prng_aes_buffer = forge2.util.createBuffer(); - prng_aes.formatKey = function(key2) { - var tmp = forge2.util.createBuffer(key2); - key2 = new Array(4); - key2[0] = tmp.getInt32(); - key2[1] = tmp.getInt32(); - key2[2] = tmp.getInt32(); - key2[3] = tmp.getInt32(); - return forge2.aes._expandKey(key2, false); - }; - prng_aes.formatSeed = function(seed) { - var tmp = forge2.util.createBuffer(seed); - seed = new Array(4); - seed[0] = tmp.getInt32(); - seed[1] = tmp.getInt32(); - seed[2] = tmp.getInt32(); - seed[3] = tmp.getInt32(); - return seed; - }; - prng_aes.cipher = function(key2, seed) { - forge2.aes._updateBlock(key2, seed, _prng_aes_output, false); - _prng_aes_buffer.putInt32(_prng_aes_output[0]); - _prng_aes_buffer.putInt32(_prng_aes_output[1]); - _prng_aes_buffer.putInt32(_prng_aes_output[2]); - _prng_aes_buffer.putInt32(_prng_aes_output[3]); - return _prng_aes_buffer.getBytes(); - }; - prng_aes.increment = function(seed) { - ++seed[3]; - return seed; - }; - prng_aes.md = forge2.md.sha256; - function spawnPrng() { - var ctx = forge2.prng.create(prng_aes); - ctx.getBytes = function(count, callback) { - return ctx.generate(count, callback); - }; - ctx.getBytesSync = function(count) { - return ctx.generate(count); - }; - return ctx; - } - var _ctx = spawnPrng(); - var getRandomValues = null; - var globalScope = forge2.util.globalScope; - var _crypto = globalScope.crypto || globalScope.msCrypto; - if (_crypto && _crypto.getRandomValues) { - getRandomValues = function(arr) { - return _crypto.getRandomValues(arr); - }; - } - if (forge2.options.usePureJavaScript || !forge2.util.isNodejs && !getRandomValues) { - if (typeof window === "undefined" || window.document === void 0) { - } - _ctx.collectInt(+/* @__PURE__ */ new Date(), 32); - if (typeof navigator !== "undefined") { - var _navBytes = ""; - for (var key in navigator) { - try { - if (typeof navigator[key] == "string") { - _navBytes += navigator[key]; - } - } catch (e) { - } - } - _ctx.collect(_navBytes); - _navBytes = null; - } - if (jQuery2) { - jQuery2().mousemove(function(e) { - _ctx.collectInt(e.clientX, 16); - _ctx.collectInt(e.clientY, 16); - }); - jQuery2().keypress(function(e) { - _ctx.collectInt(e.charCode, 8); - }); - } - } - if (!forge2.random) { - forge2.random = _ctx; - } else { - for (var key in _ctx) { - forge2.random[key] = _ctx[key]; - } - } - forge2.random.createInstance = spawnPrng; - module.exports = forge2.random; - })(typeof jQuery !== "undefined" ? jQuery : null); - })(); - } -}); - -// node_modules/node-forge/lib/rc2.js -var require_rc2 = __commonJS({ - "node_modules/node-forge/lib/rc2.js"(exports, module) { - var forge2 = require_forge(); - require_util(); - var piTable = [ - 217, - 120, - 249, - 196, - 25, - 221, - 181, - 237, - 40, - 233, - 253, - 121, - 74, - 160, - 216, - 157, - 198, - 126, - 55, - 131, - 43, - 118, - 83, - 142, - 98, - 76, - 100, - 136, - 68, - 139, - 251, - 162, - 23, - 154, - 89, - 245, - 135, - 179, - 79, - 19, - 97, - 69, - 109, - 141, - 9, - 129, - 125, - 50, - 189, - 143, - 64, - 235, - 134, - 183, - 123, - 11, - 240, - 149, - 33, - 34, - 92, - 107, - 78, - 130, - 84, - 214, - 101, - 147, - 206, - 96, - 178, - 28, - 115, - 86, - 192, - 20, - 167, - 140, - 241, - 220, - 18, - 117, - 202, - 31, - 59, - 190, - 228, - 209, - 66, - 61, - 212, - 48, - 163, - 60, - 182, - 38, - 111, - 191, - 14, - 218, - 70, - 105, - 7, - 87, - 39, - 242, - 29, - 155, - 188, - 148, - 67, - 3, - 248, - 17, - 199, - 246, - 144, - 239, - 62, - 231, - 6, - 195, - 213, - 47, - 200, - 102, - 30, - 215, - 8, - 232, - 234, - 222, - 128, - 82, - 238, - 247, - 132, - 170, - 114, - 172, - 53, - 77, - 106, - 42, - 150, - 26, - 210, - 113, - 90, - 21, - 73, - 116, - 75, - 159, - 208, - 94, - 4, - 24, - 164, - 236, - 194, - 224, - 65, - 110, - 15, - 81, - 203, - 204, - 36, - 145, - 175, - 80, - 161, - 244, - 112, - 57, - 153, - 124, - 58, - 133, - 35, - 184, - 180, - 122, - 252, - 2, - 54, - 91, - 37, - 85, - 151, - 49, - 45, - 93, - 250, - 152, - 227, - 138, - 146, - 174, - 5, - 223, - 41, - 16, - 103, - 108, - 186, - 201, - 211, - 0, - 230, - 207, - 225, - 158, - 168, - 44, - 99, - 22, - 1, - 63, - 88, - 226, - 137, - 169, - 13, - 56, - 52, - 27, - 171, - 51, - 255, - 176, - 187, - 72, - 12, - 95, - 185, - 177, - 205, - 46, - 197, - 243, - 219, - 71, - 229, - 165, - 156, - 119, - 10, - 166, - 32, - 104, - 254, - 127, - 193, - 173 - ]; - var s = [1, 2, 3, 5]; - var rol = function(word, bits) { - return word << bits & 65535 | (word & 65535) >> 16 - bits; - }; - var ror = function(word, bits) { - return (word & 65535) >> bits | word << 16 - bits & 65535; - }; - module.exports = forge2.rc2 = forge2.rc2 || {}; - forge2.rc2.expandKey = function(key, effKeyBits) { - if (typeof key === "string") { - key = forge2.util.createBuffer(key); - } - effKeyBits = effKeyBits || 128; - var L = key; - var T = key.length(); - var T1 = effKeyBits; - var T8 = Math.ceil(T1 / 8); - var TM = 255 >> (T1 & 7); - var i; - for (i = T; i < 128; i++) { - L.putByte(piTable[L.at(i - 1) + L.at(i - T) & 255]); - } - L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]); - for (i = 127 - T8; i >= 0; i--) { - L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]); - } - return L; - }; - var createCipher = function(key, bits, encrypt) { - var _finish = false, _input = null, _output = null, _iv = null; - var mixRound, mashRound; - var i, j, K = []; - key = forge2.rc2.expandKey(key, bits); - for (i = 0; i < 64; i++) { - K.push(key.getInt16Le()); - } - if (encrypt) { - mixRound = function(R) { - for (i = 0; i < 4; i++) { - R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + (~R[(i + 3) % 4] & R[(i + 1) % 4]); - R[i] = rol(R[i], s[i]); - j++; - } - }; - mashRound = function(R) { - for (i = 0; i < 4; i++) { - R[i] += K[R[(i + 3) % 4] & 63]; - } - }; - } else { - mixRound = function(R) { - for (i = 3; i >= 0; i--) { - R[i] = ror(R[i], s[i]); - R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + (~R[(i + 3) % 4] & R[(i + 1) % 4]); - j--; - } - }; - mashRound = function(R) { - for (i = 3; i >= 0; i--) { - R[i] -= K[R[(i + 3) % 4] & 63]; - } - }; - } - var runPlan = function(plan) { - var R = []; - for (i = 0; i < 4; i++) { - var val = _input.getInt16Le(); - if (_iv !== null) { - if (encrypt) { - val ^= _iv.getInt16Le(); - } else { - _iv.putInt16Le(val); - } - } - R.push(val & 65535); - } - j = encrypt ? 0 : 63; - for (var ptr = 0; ptr < plan.length; ptr++) { - for (var ctr = 0; ctr < plan[ptr][0]; ctr++) { - plan[ptr][1](R); - } - } - for (i = 0; i < 4; i++) { - if (_iv !== null) { - if (encrypt) { - _iv.putInt16Le(R[i]); - } else { - R[i] ^= _iv.getInt16Le(); - } - } - _output.putInt16Le(R[i]); - } - }; - var cipher = null; - cipher = { - /** - * Starts or restarts the encryption or decryption process, whichever - * was previously configured. - * - * To use the cipher in CBC mode, iv may be given either as a string - * of bytes, or as a byte buffer. For ECB mode, give null as iv. - * - * @param iv the initialization vector to use, null for ECB mode. - * @param output the output the buffer to write to, null to create one. - */ - start: function(iv, output) { - if (iv) { - if (typeof iv === "string") { - iv = forge2.util.createBuffer(iv); - } - } - _finish = false; - _input = forge2.util.createBuffer(); - _output = output || new forge2.util.createBuffer(); - _iv = iv; - cipher.output = _output; - }, - /** - * Updates the next block. - * - * @param input the buffer to read from. - */ - update: function(input) { - if (!_finish) { - _input.putBuffer(input); - } - while (_input.length() >= 8) { - runPlan([ - [5, mixRound], - [1, mashRound], - [6, mixRound], - [1, mashRound], - [5, mixRound] - ]); - } - }, - /** - * Finishes encrypting or decrypting. - * - * @param pad a padding function to use, null for PKCS#7 padding, - * signature(blockSize, buffer, decrypt). - * - * @return true if successful, false on error. - */ - finish: function(pad) { - var rval = true; - if (encrypt) { - if (pad) { - rval = pad(8, _input, !encrypt); - } else { - var padding = _input.length() === 8 ? 8 : 8 - _input.length(); - _input.fillWithByte(padding, padding); - } - } - if (rval) { - _finish = true; - cipher.update(); - } - if (!encrypt) { - rval = _input.length() === 0; - if (rval) { - if (pad) { - rval = pad(8, _output, !encrypt); - } else { - var len = _output.length(); - var count = _output.at(len - 1); - if (count > len) { - rval = false; - } else { - _output.truncate(count); - } - } - } - } - return rval; - } - }; - return cipher; - }; - forge2.rc2.startEncrypting = function(key, iv, output) { - var cipher = forge2.rc2.createEncryptionCipher(key, 128); - cipher.start(iv, output); - return cipher; - }; - forge2.rc2.createEncryptionCipher = function(key, bits) { - return createCipher(key, bits, true); - }; - forge2.rc2.startDecrypting = function(key, iv, output) { - var cipher = forge2.rc2.createDecryptionCipher(key, 128); - cipher.start(iv, output); - return cipher; - }; - forge2.rc2.createDecryptionCipher = function(key, bits) { - return createCipher(key, bits, false); - }; - } -}); - -// node_modules/node-forge/lib/jsbn.js -var require_jsbn = __commonJS({ - "node_modules/node-forge/lib/jsbn.js"(exports, module) { - var forge2 = require_forge(); - module.exports = forge2.jsbn = forge2.jsbn || {}; - var dbits; - var canary = 244837814094590; - var j_lm = (canary & 16777215) == 15715070; - function BigInteger2(a, b, c) { - this.data = []; - if (a != null) - if ("number" == typeof a) this.fromNumber(a, b, c); - else if (b == null && "string" != typeof a) this.fromString(a, 256); - else this.fromString(a, b); - } - forge2.jsbn.BigInteger = BigInteger2; - function nbi() { - return new BigInteger2(null); - } - function am1(i, x, w, j, c, n) { - while (--n >= 0) { - var v = x * this.data[i++] + w.data[j] + c; - c = Math.floor(v / 67108864); - w.data[j++] = v & 67108863; - } - return c; - } - function am2(i, x, w, j, c, n) { - var xl = x & 32767, xh = x >> 15; - while (--n >= 0) { - var l = this.data[i] & 32767; - var h = this.data[i++] >> 15; - var m = xh * l + h * xl; - l = xl * l + ((m & 32767) << 15) + w.data[j] + (c & 1073741823); - c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); - w.data[j++] = l & 1073741823; - } - return c; - } - function am3(i, x, w, j, c, n) { - var xl = x & 16383, xh = x >> 14; - while (--n >= 0) { - var l = this.data[i] & 16383; - var h = this.data[i++] >> 14; - var m = xh * l + h * xl; - l = xl * l + ((m & 16383) << 14) + w.data[j] + c; - c = (l >> 28) + (m >> 14) + xh * h; - w.data[j++] = l & 268435455; - } - return c; - } - if (typeof navigator === "undefined") { - BigInteger2.prototype.am = am3; - dbits = 28; - } else if (j_lm && navigator.appName == "Microsoft Internet Explorer") { - BigInteger2.prototype.am = am2; - dbits = 30; - } else if (j_lm && navigator.appName != "Netscape") { - BigInteger2.prototype.am = am1; - dbits = 26; - } else { - BigInteger2.prototype.am = am3; - dbits = 28; - } - BigInteger2.prototype.DB = dbits; - BigInteger2.prototype.DM = (1 << dbits) - 1; - BigInteger2.prototype.DV = 1 << dbits; - var BI_FP = 52; - BigInteger2.prototype.FV = Math.pow(2, BI_FP); - BigInteger2.prototype.F1 = BI_FP - dbits; - BigInteger2.prototype.F2 = 2 * dbits - BI_FP; - var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; - var BI_RC = new Array(); - var rr; - var vv; - rr = "0".charCodeAt(0); - for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv; - rr = "a".charCodeAt(0); - for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - rr = "A".charCodeAt(0); - for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv; - function int2char(n) { - return BI_RM.charAt(n); - } - function intAt(s, i) { - var c = BI_RC[s.charCodeAt(i)]; - return c == null ? -1 : c; - } - function bnpCopyTo(r) { - for (var i = this.t - 1; i >= 0; --i) r.data[i] = this.data[i]; - r.t = this.t; - r.s = this.s; - } - function bnpFromInt(x) { - this.t = 1; - this.s = x < 0 ? -1 : 0; - if (x > 0) this.data[0] = x; - else if (x < -1) this.data[0] = x + this.DV; - else this.t = 0; - } - function nbv(i) { - var r = nbi(); - r.fromInt(i); - return r; - } - function bnpFromString(s, b) { - var k; - if (b == 16) k = 4; - else if (b == 8) k = 3; - else if (b == 256) k = 8; - else if (b == 2) k = 1; - else if (b == 32) k = 5; - else if (b == 4) k = 2; - else { - this.fromRadix(s, b); - return; - } - this.t = 0; - this.s = 0; - var i = s.length, mi = false, sh = 0; - while (--i >= 0) { - var x = k == 8 ? s[i] & 255 : intAt(s, i); - if (x < 0) { - if (s.charAt(i) == "-") mi = true; - continue; - } - mi = false; - if (sh == 0) - this.data[this.t++] = x; - else if (sh + k > this.DB) { - this.data[this.t - 1] |= (x & (1 << this.DB - sh) - 1) << sh; - this.data[this.t++] = x >> this.DB - sh; - } else - this.data[this.t - 1] |= x << sh; - sh += k; - if (sh >= this.DB) sh -= this.DB; - } - if (k == 8 && (s[0] & 128) != 0) { - this.s = -1; - if (sh > 0) this.data[this.t - 1] |= (1 << this.DB - sh) - 1 << sh; - } - this.clamp(); - if (mi) BigInteger2.ZERO.subTo(this, this); - } - function bnpClamp() { - var c = this.s & this.DM; - while (this.t > 0 && this.data[this.t - 1] == c) --this.t; - } - function bnToString(b) { - if (this.s < 0) return "-" + this.negate().toString(b); - var k; - if (b == 16) k = 4; - else if (b == 8) k = 3; - else if (b == 2) k = 1; - else if (b == 32) k = 5; - else if (b == 4) k = 2; - else return this.toRadix(b); - var km = (1 << k) - 1, d, m = false, r = "", i = this.t; - var p = this.DB - i * this.DB % k; - if (i-- > 0) { - if (p < this.DB && (d = this.data[i] >> p) > 0) { - m = true; - r = int2char(d); - } - while (i >= 0) { - if (p < k) { - d = (this.data[i] & (1 << p) - 1) << k - p; - d |= this.data[--i] >> (p += this.DB - k); - } else { - d = this.data[i] >> (p -= k) & km; - if (p <= 0) { - p += this.DB; - --i; - } - } - if (d > 0) m = true; - if (m) r += int2char(d); - } - } - return m ? r : "0"; - } - function bnNegate() { - var r = nbi(); - BigInteger2.ZERO.subTo(this, r); - return r; - } - function bnAbs() { - return this.s < 0 ? this.negate() : this; - } - function bnCompareTo(a) { - var r = this.s - a.s; - if (r != 0) return r; - var i = this.t; - r = i - a.t; - if (r != 0) return this.s < 0 ? -r : r; - while (--i >= 0) if ((r = this.data[i] - a.data[i]) != 0) return r; - return 0; - } - function nbits(x) { - var r = 1, t; - if ((t = x >>> 16) != 0) { - x = t; - r += 16; - } - if ((t = x >> 8) != 0) { - x = t; - r += 8; - } - if ((t = x >> 4) != 0) { - x = t; - r += 4; - } - if ((t = x >> 2) != 0) { - x = t; - r += 2; - } - if ((t = x >> 1) != 0) { - x = t; - r += 1; - } - return r; - } - function bnBitLength() { - if (this.t <= 0) return 0; - return this.DB * (this.t - 1) + nbits(this.data[this.t - 1] ^ this.s & this.DM); - } - function bnpDLShiftTo(n, r) { - var i; - for (i = this.t - 1; i >= 0; --i) r.data[i + n] = this.data[i]; - for (i = n - 1; i >= 0; --i) r.data[i] = 0; - r.t = this.t + n; - r.s = this.s; - } - function bnpDRShiftTo(n, r) { - for (var i = n; i < this.t; ++i) r.data[i - n] = this.data[i]; - r.t = Math.max(this.t - n, 0); - r.s = this.s; - } - function bnpLShiftTo(n, r) { - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << cbs) - 1; - var ds = Math.floor(n / this.DB), c = this.s << bs & this.DM, i; - for (i = this.t - 1; i >= 0; --i) { - r.data[i + ds + 1] = this.data[i] >> cbs | c; - c = (this.data[i] & bm) << bs; - } - for (i = ds - 1; i >= 0; --i) r.data[i] = 0; - r.data[ds] = c; - r.t = this.t + ds + 1; - r.s = this.s; - r.clamp(); - } - function bnpRShiftTo(n, r) { - r.s = this.s; - var ds = Math.floor(n / this.DB); - if (ds >= this.t) { - r.t = 0; - return; - } - var bs = n % this.DB; - var cbs = this.DB - bs; - var bm = (1 << bs) - 1; - r.data[0] = this.data[ds] >> bs; - for (var i = ds + 1; i < this.t; ++i) { - r.data[i - ds - 1] |= (this.data[i] & bm) << cbs; - r.data[i - ds] = this.data[i] >> bs; - } - if (bs > 0) r.data[this.t - ds - 1] |= (this.s & bm) << cbs; - r.t = this.t - ds; - r.clamp(); - } - function bnpSubTo(a, r) { - var i = 0, c = 0, m = Math.min(a.t, this.t); - while (i < m) { - c += this.data[i] - a.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - if (a.t < this.t) { - c -= a.s; - while (i < this.t) { - c += this.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c -= a.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - c -= a.s; - } - r.s = c < 0 ? -1 : 0; - if (c < -1) r.data[i++] = this.DV + c; - else if (c > 0) r.data[i++] = c; - r.t = i; - r.clamp(); - } - function bnpMultiplyTo(a, r) { - var x = this.abs(), y = a.abs(); - var i = x.t; - r.t = i + y.t; - while (--i >= 0) r.data[i] = 0; - for (i = 0; i < y.t; ++i) r.data[i + x.t] = x.am(0, y.data[i], r, i, 0, x.t); - r.s = 0; - r.clamp(); - if (this.s != a.s) BigInteger2.ZERO.subTo(r, r); - } - function bnpSquareTo(r) { - var x = this.abs(); - var i = r.t = 2 * x.t; - while (--i >= 0) r.data[i] = 0; - for (i = 0; i < x.t - 1; ++i) { - var c = x.am(i, x.data[i], r, 2 * i, 0, 1); - if ((r.data[i + x.t] += x.am(i + 1, 2 * x.data[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { - r.data[i + x.t] -= x.DV; - r.data[i + x.t + 1] = 1; - } - } - if (r.t > 0) r.data[r.t - 1] += x.am(i, x.data[i], r, 2 * i, 0, 1); - r.s = 0; - r.clamp(); - } - function bnpDivRemTo(m, q, r) { - var pm = m.abs(); - if (pm.t <= 0) return; - var pt = this.abs(); - if (pt.t < pm.t) { - if (q != null) q.fromInt(0); - if (r != null) this.copyTo(r); - return; - } - if (r == null) r = nbi(); - var y = nbi(), ts = this.s, ms = m.s; - var nsh = this.DB - nbits(pm.data[pm.t - 1]); - if (nsh > 0) { - pm.lShiftTo(nsh, y); - pt.lShiftTo(nsh, r); - } else { - pm.copyTo(y); - pt.copyTo(r); - } - var ys = y.t; - var y0 = y.data[ys - 1]; - if (y0 == 0) return; - var yt = y0 * (1 << this.F1) + (ys > 1 ? y.data[ys - 2] >> this.F2 : 0); - var d1 = this.FV / yt, d2 = (1 << this.F1) / yt, e = 1 << this.F2; - var i = r.t, j = i - ys, t = q == null ? nbi() : q; - y.dlShiftTo(j, t); - if (r.compareTo(t) >= 0) { - r.data[r.t++] = 1; - r.subTo(t, r); - } - BigInteger2.ONE.dlShiftTo(ys, t); - t.subTo(y, y); - while (y.t < ys) y.data[y.t++] = 0; - while (--j >= 0) { - var qd = r.data[--i] == y0 ? this.DM : Math.floor(r.data[i] * d1 + (r.data[i - 1] + e) * d2); - if ((r.data[i] += y.am(0, qd, r, j, 0, ys)) < qd) { - y.dlShiftTo(j, t); - r.subTo(t, r); - while (r.data[i] < --qd) r.subTo(t, r); - } - } - if (q != null) { - r.drShiftTo(ys, q); - if (ts != ms) BigInteger2.ZERO.subTo(q, q); - } - r.t = ys; - r.clamp(); - if (nsh > 0) r.rShiftTo(nsh, r); - if (ts < 0) BigInteger2.ZERO.subTo(r, r); - } - function bnMod(a) { - var r = nbi(); - this.abs().divRemTo(a, null, r); - if (this.s < 0 && r.compareTo(BigInteger2.ZERO) > 0) a.subTo(r, r); - return r; - } - function Classic(m) { - this.m = m; - } - function cConvert(x) { - if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); - else return x; - } - function cRevert(x) { - return x; - } - function cReduce(x) { - x.divRemTo(this.m, null, x); - } - function cMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - function cSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - Classic.prototype.convert = cConvert; - Classic.prototype.revert = cRevert; - Classic.prototype.reduce = cReduce; - Classic.prototype.mulTo = cMulTo; - Classic.prototype.sqrTo = cSqrTo; - function bnpInvDigit() { - if (this.t < 1) return 0; - var x = this.data[0]; - if ((x & 1) == 0) return 0; - var y = x & 3; - y = y * (2 - (x & 15) * y) & 15; - y = y * (2 - (x & 255) * y) & 255; - y = y * (2 - ((x & 65535) * y & 65535)) & 65535; - y = y * (2 - x * y % this.DV) % this.DV; - return y > 0 ? this.DV - y : -y; - } - function Montgomery(m) { - this.m = m; - this.mp = m.invDigit(); - this.mpl = this.mp & 32767; - this.mph = this.mp >> 15; - this.um = (1 << m.DB - 15) - 1; - this.mt2 = 2 * m.t; - } - function montConvert(x) { - var r = nbi(); - x.abs().dlShiftTo(this.m.t, r); - r.divRemTo(this.m, null, r); - if (x.s < 0 && r.compareTo(BigInteger2.ZERO) > 0) this.m.subTo(r, r); - return r; - } - function montRevert(x) { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } - function montReduce(x) { - while (x.t <= this.mt2) - x.data[x.t++] = 0; - for (var i = 0; i < this.m.t; ++i) { - var j = x.data[i] & 32767; - var u0 = j * this.mpl + ((j * this.mph + (x.data[i] >> 15) * this.mpl & this.um) << 15) & x.DM; - j = i + this.m.t; - x.data[j] += this.m.am(0, u0, x, i, 0, this.m.t); - while (x.data[j] >= x.DV) { - x.data[j] -= x.DV; - x.data[++j]++; - } - } - x.clamp(); - x.drShiftTo(this.m.t, x); - if (x.compareTo(this.m) >= 0) x.subTo(this.m, x); - } - function montSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - function montMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - Montgomery.prototype.convert = montConvert; - Montgomery.prototype.revert = montRevert; - Montgomery.prototype.reduce = montReduce; - Montgomery.prototype.mulTo = montMulTo; - Montgomery.prototype.sqrTo = montSqrTo; - function bnpIsEven() { - return (this.t > 0 ? this.data[0] & 1 : this.s) == 0; - } - function bnpExp(e, z) { - if (e > 4294967295 || e < 1) return BigInteger2.ONE; - var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e) - 1; - g.copyTo(r); - while (--i >= 0) { - z.sqrTo(r, r2); - if ((e & 1 << i) > 0) z.mulTo(r2, g, r); - else { - var t = r; - r = r2; - r2 = t; - } - } - return z.revert(r); - } - function bnModPowInt(e, m) { - var z; - if (e < 256 || m.isEven()) z = new Classic(m); - else z = new Montgomery(m); - return this.exp(e, z); - } - BigInteger2.prototype.copyTo = bnpCopyTo; - BigInteger2.prototype.fromInt = bnpFromInt; - BigInteger2.prototype.fromString = bnpFromString; - BigInteger2.prototype.clamp = bnpClamp; - BigInteger2.prototype.dlShiftTo = bnpDLShiftTo; - BigInteger2.prototype.drShiftTo = bnpDRShiftTo; - BigInteger2.prototype.lShiftTo = bnpLShiftTo; - BigInteger2.prototype.rShiftTo = bnpRShiftTo; - BigInteger2.prototype.subTo = bnpSubTo; - BigInteger2.prototype.multiplyTo = bnpMultiplyTo; - BigInteger2.prototype.squareTo = bnpSquareTo; - BigInteger2.prototype.divRemTo = bnpDivRemTo; - BigInteger2.prototype.invDigit = bnpInvDigit; - BigInteger2.prototype.isEven = bnpIsEven; - BigInteger2.prototype.exp = bnpExp; - BigInteger2.prototype.toString = bnToString; - BigInteger2.prototype.negate = bnNegate; - BigInteger2.prototype.abs = bnAbs; - BigInteger2.prototype.compareTo = bnCompareTo; - BigInteger2.prototype.bitLength = bnBitLength; - BigInteger2.prototype.mod = bnMod; - BigInteger2.prototype.modPowInt = bnModPowInt; - BigInteger2.ZERO = nbv(0); - BigInteger2.ONE = nbv(1); - function bnClone() { - var r = nbi(); - this.copyTo(r); - return r; - } - function bnIntValue() { - if (this.s < 0) { - if (this.t == 1) return this.data[0] - this.DV; - else if (this.t == 0) return -1; - } else if (this.t == 1) return this.data[0]; - else if (this.t == 0) return 0; - return (this.data[1] & (1 << 32 - this.DB) - 1) << this.DB | this.data[0]; - } - function bnByteValue() { - return this.t == 0 ? this.s : this.data[0] << 24 >> 24; - } - function bnShortValue() { - return this.t == 0 ? this.s : this.data[0] << 16 >> 16; - } - function bnpChunkSize(r) { - return Math.floor(Math.LN2 * this.DB / Math.log(r)); - } - function bnSigNum() { - if (this.s < 0) return -1; - else if (this.t <= 0 || this.t == 1 && this.data[0] <= 0) return 0; - else return 1; - } - function bnpToRadix(b) { - if (b == null) b = 10; - if (this.signum() == 0 || b < 2 || b > 36) return "0"; - var cs = this.chunkSize(b); - var a = Math.pow(b, cs); - var d = nbv(a), y = nbi(), z = nbi(), r = ""; - this.divRemTo(d, y, z); - while (y.signum() > 0) { - r = (a + z.intValue()).toString(b).substr(1) + r; - y.divRemTo(d, y, z); - } - return z.intValue().toString(b) + r; - } - function bnpFromRadix(s, b) { - this.fromInt(0); - if (b == null) b = 10; - var cs = this.chunkSize(b); - var d = Math.pow(b, cs), mi = false, j = 0, w = 0; - for (var i = 0; i < s.length; ++i) { - var x = intAt(s, i); - if (x < 0) { - if (s.charAt(i) == "-" && this.signum() == 0) mi = true; - continue; - } - w = b * w + x; - if (++j >= cs) { - this.dMultiply(d); - this.dAddOffset(w, 0); - j = 0; - w = 0; - } - } - if (j > 0) { - this.dMultiply(Math.pow(b, j)); - this.dAddOffset(w, 0); - } - if (mi) BigInteger2.ZERO.subTo(this, this); - } - function bnpFromNumber(a, b, c) { - if ("number" == typeof b) { - if (a < 2) this.fromInt(1); - else { - this.fromNumber(a, c); - if (!this.testBit(a - 1)) - this.bitwiseTo(BigInteger2.ONE.shiftLeft(a - 1), op_or, this); - if (this.isEven()) this.dAddOffset(1, 0); - while (!this.isProbablePrime(b)) { - this.dAddOffset(2, 0); - if (this.bitLength() > a) this.subTo(BigInteger2.ONE.shiftLeft(a - 1), this); - } - } - } else { - var x = new Array(), t = a & 7; - x.length = (a >> 3) + 1; - b.nextBytes(x); - if (t > 0) x[0] &= (1 << t) - 1; - else x[0] = 0; - this.fromString(x, 256); - } - } - function bnToByteArray() { - var i = this.t, r = new Array(); - r[0] = this.s; - var p = this.DB - i * this.DB % 8, d, k = 0; - if (i-- > 0) { - if (p < this.DB && (d = this.data[i] >> p) != (this.s & this.DM) >> p) - r[k++] = d | this.s << this.DB - p; - while (i >= 0) { - if (p < 8) { - d = (this.data[i] & (1 << p) - 1) << 8 - p; - d |= this.data[--i] >> (p += this.DB - 8); - } else { - d = this.data[i] >> (p -= 8) & 255; - if (p <= 0) { - p += this.DB; - --i; - } - } - if ((d & 128) != 0) d |= -256; - if (k == 0 && (this.s & 128) != (d & 128)) ++k; - if (k > 0 || d != this.s) r[k++] = d; - } - } - return r; - } - function bnEquals(a) { - return this.compareTo(a) == 0; - } - function bnMin(a) { - return this.compareTo(a) < 0 ? this : a; - } - function bnMax(a) { - return this.compareTo(a) > 0 ? this : a; - } - function bnpBitwiseTo(a, op, r) { - var i, f, m = Math.min(a.t, this.t); - for (i = 0; i < m; ++i) r.data[i] = op(this.data[i], a.data[i]); - if (a.t < this.t) { - f = a.s & this.DM; - for (i = m; i < this.t; ++i) r.data[i] = op(this.data[i], f); - r.t = this.t; - } else { - f = this.s & this.DM; - for (i = m; i < a.t; ++i) r.data[i] = op(f, a.data[i]); - r.t = a.t; - } - r.s = op(this.s, a.s); - r.clamp(); - } - function op_and(x, y) { - return x & y; - } - function bnAnd(a) { - var r = nbi(); - this.bitwiseTo(a, op_and, r); - return r; - } - function op_or(x, y) { - return x | y; - } - function bnOr(a) { - var r = nbi(); - this.bitwiseTo(a, op_or, r); - return r; - } - function op_xor(x, y) { - return x ^ y; - } - function bnXor(a) { - var r = nbi(); - this.bitwiseTo(a, op_xor, r); - return r; - } - function op_andnot(x, y) { - return x & ~y; - } - function bnAndNot(a) { - var r = nbi(); - this.bitwiseTo(a, op_andnot, r); - return r; - } - function bnNot() { - var r = nbi(); - for (var i = 0; i < this.t; ++i) r.data[i] = this.DM & ~this.data[i]; - r.t = this.t; - r.s = ~this.s; - return r; - } - function bnShiftLeft(n) { - var r = nbi(); - if (n < 0) this.rShiftTo(-n, r); - else this.lShiftTo(n, r); - return r; - } - function bnShiftRight(n) { - var r = nbi(); - if (n < 0) this.lShiftTo(-n, r); - else this.rShiftTo(n, r); - return r; - } - function lbit(x) { - if (x == 0) return -1; - var r = 0; - if ((x & 65535) == 0) { - x >>= 16; - r += 16; - } - if ((x & 255) == 0) { - x >>= 8; - r += 8; - } - if ((x & 15) == 0) { - x >>= 4; - r += 4; - } - if ((x & 3) == 0) { - x >>= 2; - r += 2; - } - if ((x & 1) == 0) ++r; - return r; - } - function bnGetLowestSetBit() { - for (var i = 0; i < this.t; ++i) - if (this.data[i] != 0) return i * this.DB + lbit(this.data[i]); - if (this.s < 0) return this.t * this.DB; - return -1; - } - function cbit(x) { - var r = 0; - while (x != 0) { - x &= x - 1; - ++r; - } - return r; - } - function bnBitCount() { - var r = 0, x = this.s & this.DM; - for (var i = 0; i < this.t; ++i) r += cbit(this.data[i] ^ x); - return r; - } - function bnTestBit(n) { - var j = Math.floor(n / this.DB); - if (j >= this.t) return this.s != 0; - return (this.data[j] & 1 << n % this.DB) != 0; - } - function bnpChangeBit(n, op) { - var r = BigInteger2.ONE.shiftLeft(n); - this.bitwiseTo(r, op, r); - return r; - } - function bnSetBit(n) { - return this.changeBit(n, op_or); - } - function bnClearBit(n) { - return this.changeBit(n, op_andnot); - } - function bnFlipBit(n) { - return this.changeBit(n, op_xor); - } - function bnpAddTo(a, r) { - var i = 0, c = 0, m = Math.min(a.t, this.t); - while (i < m) { - c += this.data[i] + a.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - if (a.t < this.t) { - c += a.s; - while (i < this.t) { - c += this.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - c += this.s; - } else { - c += this.s; - while (i < a.t) { - c += a.data[i]; - r.data[i++] = c & this.DM; - c >>= this.DB; - } - c += a.s; - } - r.s = c < 0 ? -1 : 0; - if (c > 0) r.data[i++] = c; - else if (c < -1) r.data[i++] = this.DV + c; - r.t = i; - r.clamp(); - } - function bnAdd(a) { - var r = nbi(); - this.addTo(a, r); - return r; - } - function bnSubtract(a) { - var r = nbi(); - this.subTo(a, r); - return r; - } - function bnMultiply(a) { - var r = nbi(); - this.multiplyTo(a, r); - return r; - } - function bnDivide(a) { - var r = nbi(); - this.divRemTo(a, r, null); - return r; - } - function bnRemainder(a) { - var r = nbi(); - this.divRemTo(a, null, r); - return r; - } - function bnDivideAndRemainder(a) { - var q = nbi(), r = nbi(); - this.divRemTo(a, q, r); - return new Array(q, r); - } - function bnpDMultiply(n) { - this.data[this.t] = this.am(0, n - 1, this, 0, 0, this.t); - ++this.t; - this.clamp(); - } - function bnpDAddOffset(n, w) { - if (n == 0) return; - while (this.t <= w) this.data[this.t++] = 0; - this.data[w] += n; - while (this.data[w] >= this.DV) { - this.data[w] -= this.DV; - if (++w >= this.t) this.data[this.t++] = 0; - ++this.data[w]; - } - } - function NullExp() { - } - function nNop(x) { - return x; - } - function nMulTo(x, y, r) { - x.multiplyTo(y, r); - } - function nSqrTo(x, r) { - x.squareTo(r); - } - NullExp.prototype.convert = nNop; - NullExp.prototype.revert = nNop; - NullExp.prototype.mulTo = nMulTo; - NullExp.prototype.sqrTo = nSqrTo; - function bnPow(e) { - return this.exp(e, new NullExp()); - } - function bnpMultiplyLowerTo(a, n, r) { - var i = Math.min(this.t + a.t, n); - r.s = 0; - r.t = i; - while (i > 0) r.data[--i] = 0; - var j; - for (j = r.t - this.t; i < j; ++i) r.data[i + this.t] = this.am(0, a.data[i], r, i, 0, this.t); - for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a.data[i], r, i, 0, n - i); - r.clamp(); - } - function bnpMultiplyUpperTo(a, n, r) { - --n; - var i = r.t = this.t + a.t - n; - r.s = 0; - while (--i >= 0) r.data[i] = 0; - for (i = Math.max(n - this.t, 0); i < a.t; ++i) - r.data[this.t + i - n] = this.am(n - i, a.data[i], r, 0, 0, this.t + i - n); - r.clamp(); - r.drShiftTo(1, r); - } - function Barrett(m) { - this.r2 = nbi(); - this.q3 = nbi(); - BigInteger2.ONE.dlShiftTo(2 * m.t, this.r2); - this.mu = this.r2.divide(m); - this.m = m; - } - function barrettConvert(x) { - if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m); - else if (x.compareTo(this.m) < 0) return x; - else { - var r = nbi(); - x.copyTo(r); - this.reduce(r); - return r; - } - } - function barrettRevert(x) { - return x; - } - function barrettReduce(x) { - x.drShiftTo(this.m.t - 1, this.r2); - if (x.t > this.m.t + 1) { - x.t = this.m.t + 1; - x.clamp(); - } - this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); - this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); - while (x.compareTo(this.r2) < 0) x.dAddOffset(1, this.m.t + 1); - x.subTo(this.r2, x); - while (x.compareTo(this.m) >= 0) x.subTo(this.m, x); - } - function barrettSqrTo(x, r) { - x.squareTo(r); - this.reduce(r); - } - function barrettMulTo(x, y, r) { - x.multiplyTo(y, r); - this.reduce(r); - } - Barrett.prototype.convert = barrettConvert; - Barrett.prototype.revert = barrettRevert; - Barrett.prototype.reduce = barrettReduce; - Barrett.prototype.mulTo = barrettMulTo; - Barrett.prototype.sqrTo = barrettSqrTo; - function bnModPow(e, m) { - var i = e.bitLength(), k, r = nbv(1), z; - if (i <= 0) return r; - else if (i < 18) k = 1; - else if (i < 48) k = 3; - else if (i < 144) k = 4; - else if (i < 768) k = 5; - else k = 6; - if (i < 8) - z = new Classic(m); - else if (m.isEven()) - z = new Barrett(m); - else - z = new Montgomery(m); - var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1; - g[1] = z.convert(this); - if (k > 1) { - var g2 = nbi(); - z.sqrTo(g[1], g2); - while (n <= km) { - g[n] = nbi(); - z.mulTo(g2, g[n - 2], g[n]); - n += 2; - } - } - var j = e.t - 1, w, is1 = true, r2 = nbi(), t; - i = nbits(e.data[j]) - 1; - while (j >= 0) { - if (i >= k1) w = e.data[j] >> i - k1 & km; - else { - w = (e.data[j] & (1 << i + 1) - 1) << k1 - i; - if (j > 0) w |= e.data[j - 1] >> this.DB + i - k1; - } - n = k; - while ((w & 1) == 0) { - w >>= 1; - --n; - } - if ((i -= n) < 0) { - i += this.DB; - --j; - } - if (is1) { - g[w].copyTo(r); - is1 = false; - } else { - while (n > 1) { - z.sqrTo(r, r2); - z.sqrTo(r2, r); - n -= 2; - } - if (n > 0) z.sqrTo(r, r2); - else { - t = r; - r = r2; - r2 = t; - } - z.mulTo(r2, g[w], r); - } - while (j >= 0 && (e.data[j] & 1 << i) == 0) { - z.sqrTo(r, r2); - t = r; - r = r2; - r2 = t; - if (--i < 0) { - i = this.DB - 1; - --j; - } - } - } - return z.revert(r); - } - function bnGCD(a) { - var x = this.s < 0 ? this.negate() : this.clone(); - var y = a.s < 0 ? a.negate() : a.clone(); - if (x.compareTo(y) < 0) { - var t = x; - x = y; - y = t; - } - var i = x.getLowestSetBit(), g = y.getLowestSetBit(); - if (g < 0) return x; - if (i < g) g = i; - if (g > 0) { - x.rShiftTo(g, x); - y.rShiftTo(g, y); - } - while (x.signum() > 0) { - if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x); - if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y); - if (x.compareTo(y) >= 0) { - x.subTo(y, x); - x.rShiftTo(1, x); - } else { - y.subTo(x, y); - y.rShiftTo(1, y); - } - } - if (g > 0) y.lShiftTo(g, y); - return y; - } - function bnpModInt(n) { - if (n <= 0) return 0; - var d = this.DV % n, r = this.s < 0 ? n - 1 : 0; - if (this.t > 0) - if (d == 0) r = this.data[0] % n; - else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this.data[i]) % n; - return r; - } - function bnModInverse(m) { - var ac = m.isEven(); - if (this.isEven() && ac || m.signum() == 0) return BigInteger2.ZERO; - var u = m.clone(), v = this.clone(); - var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); - while (u.signum() != 0) { - while (u.isEven()) { - u.rShiftTo(1, u); - if (ac) { - if (!a.isEven() || !b.isEven()) { - a.addTo(this, a); - b.subTo(m, b); - } - a.rShiftTo(1, a); - } else if (!b.isEven()) b.subTo(m, b); - b.rShiftTo(1, b); - } - while (v.isEven()) { - v.rShiftTo(1, v); - if (ac) { - if (!c.isEven() || !d.isEven()) { - c.addTo(this, c); - d.subTo(m, d); - } - c.rShiftTo(1, c); - } else if (!d.isEven()) d.subTo(m, d); - d.rShiftTo(1, d); - } - if (u.compareTo(v) >= 0) { - u.subTo(v, u); - if (ac) a.subTo(c, a); - b.subTo(d, b); - } else { - v.subTo(u, v); - if (ac) c.subTo(a, c); - d.subTo(b, d); - } - } - if (v.compareTo(BigInteger2.ONE) != 0) return BigInteger2.ZERO; - if (d.compareTo(m) >= 0) return d.subtract(m); - if (d.signum() < 0) d.addTo(m, d); - else return d; - if (d.signum() < 0) return d.add(m); - else return d; - } - var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509]; - var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; - function bnIsProbablePrime(t) { - var i, x = this.abs(); - if (x.t == 1 && x.data[0] <= lowprimes[lowprimes.length - 1]) { - for (i = 0; i < lowprimes.length; ++i) - if (x.data[0] == lowprimes[i]) return true; - return false; - } - if (x.isEven()) return false; - i = 1; - while (i < lowprimes.length) { - var m = lowprimes[i], j = i + 1; - while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]; - m = x.modInt(m); - while (i < j) if (m % lowprimes[i++] == 0) return false; - } - return x.millerRabin(t); - } - function bnpMillerRabin(t) { - var n1 = this.subtract(BigInteger2.ONE); - var k = n1.getLowestSetBit(); - if (k <= 0) return false; - var r = n1.shiftRight(k); - var prng = bnGetPrng(); - var a; - for (var i = 0; i < t; ++i) { - do { - a = new BigInteger2(this.bitLength(), prng); - } while (a.compareTo(BigInteger2.ONE) <= 0 || a.compareTo(n1) >= 0); - var y = a.modPow(r, this); - if (y.compareTo(BigInteger2.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1; - while (j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2, this); - if (y.compareTo(BigInteger2.ONE) == 0) return false; - } - if (y.compareTo(n1) != 0) return false; - } - } - return true; - } - function bnGetPrng() { - return { - // x is an array to fill with bytes - nextBytes: function(x) { - for (var i = 0; i < x.length; ++i) { - x[i] = Math.floor(Math.random() * 256); - } - } - }; - } - BigInteger2.prototype.chunkSize = bnpChunkSize; - BigInteger2.prototype.toRadix = bnpToRadix; - BigInteger2.prototype.fromRadix = bnpFromRadix; - BigInteger2.prototype.fromNumber = bnpFromNumber; - BigInteger2.prototype.bitwiseTo = bnpBitwiseTo; - BigInteger2.prototype.changeBit = bnpChangeBit; - BigInteger2.prototype.addTo = bnpAddTo; - BigInteger2.prototype.dMultiply = bnpDMultiply; - BigInteger2.prototype.dAddOffset = bnpDAddOffset; - BigInteger2.prototype.multiplyLowerTo = bnpMultiplyLowerTo; - BigInteger2.prototype.multiplyUpperTo = bnpMultiplyUpperTo; - BigInteger2.prototype.modInt = bnpModInt; - BigInteger2.prototype.millerRabin = bnpMillerRabin; - BigInteger2.prototype.clone = bnClone; - BigInteger2.prototype.intValue = bnIntValue; - BigInteger2.prototype.byteValue = bnByteValue; - BigInteger2.prototype.shortValue = bnShortValue; - BigInteger2.prototype.signum = bnSigNum; - BigInteger2.prototype.toByteArray = bnToByteArray; - BigInteger2.prototype.equals = bnEquals; - BigInteger2.prototype.min = bnMin; - BigInteger2.prototype.max = bnMax; - BigInteger2.prototype.and = bnAnd; - BigInteger2.prototype.or = bnOr; - BigInteger2.prototype.xor = bnXor; - BigInteger2.prototype.andNot = bnAndNot; - BigInteger2.prototype.not = bnNot; - BigInteger2.prototype.shiftLeft = bnShiftLeft; - BigInteger2.prototype.shiftRight = bnShiftRight; - BigInteger2.prototype.getLowestSetBit = bnGetLowestSetBit; - BigInteger2.prototype.bitCount = bnBitCount; - BigInteger2.prototype.testBit = bnTestBit; - BigInteger2.prototype.setBit = bnSetBit; - BigInteger2.prototype.clearBit = bnClearBit; - BigInteger2.prototype.flipBit = bnFlipBit; - BigInteger2.prototype.add = bnAdd; - BigInteger2.prototype.subtract = bnSubtract; - BigInteger2.prototype.multiply = bnMultiply; - BigInteger2.prototype.divide = bnDivide; - BigInteger2.prototype.remainder = bnRemainder; - BigInteger2.prototype.divideAndRemainder = bnDivideAndRemainder; - BigInteger2.prototype.modPow = bnModPow; - BigInteger2.prototype.modInverse = bnModInverse; - BigInteger2.prototype.pow = bnPow; - BigInteger2.prototype.gcd = bnGCD; - BigInteger2.prototype.isProbablePrime = bnIsProbablePrime; - } -}); - -// node_modules/node-forge/lib/sha1.js -var require_sha1 = __commonJS({ - "node_modules/node-forge/lib/sha1.js"(exports, module) { - var forge2 = require_forge(); - require_md(); - require_util(); - var sha1 = module.exports = forge2.sha1 = forge2.sha1 || {}; - forge2.md.sha1 = forge2.md.algorithms.sha1 = sha1; - sha1.create = function() { - if (!_initialized) { - _init(); - } - var _state = null; - var _input = forge2.util.createBuffer(); - var _w = new Array(80); - var md = { - algorithm: "sha1", - blockLength: 64, - digestLength: 20, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 8 - }; - md.start = function() { - md.messageLength = 0; - md.fullMessageLength = md.messageLength64 = []; - var int32s = md.messageLengthSize / 4; - for (var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); - } - _input = forge2.util.createBuffer(); - _state = { - h0: 1732584193, - h1: 4023233417, - h2: 2562383102, - h3: 271733878, - h4: 3285377520 - }; - return md; - }; - md.start(); - md.update = function(msg, encoding) { - if (encoding === "utf8") { - msg = forge2.util.encodeUtf8(msg); - } - var len = msg.length; - md.messageLength += len; - len = [len / 4294967296 >>> 0, len >>> 0]; - for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + (md.fullMessageLength[i] / 4294967296 >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = len[1] / 4294967296 >>> 0; - } - _input.putBytes(msg); - _update(_state, _w, _input); - if (_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - return md; - }; - md.digest = function() { - var finalBlock = forge2.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; - var overflow = remaining & md.blockLength - 1; - finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); - var next, carry; - var bits = md.fullMessageLength[0] * 8; - for (var i = 0; i < md.fullMessageLength.length - 1; ++i) { - next = md.fullMessageLength[i + 1] * 8; - carry = next / 4294967296 >>> 0; - bits += carry; - finalBlock.putInt32(bits >>> 0); - bits = next >>> 0; - } - finalBlock.putInt32(bits); - var s2 = { - h0: _state.h0, - h1: _state.h1, - h2: _state.h2, - h3: _state.h3, - h4: _state.h4 - }; - _update(s2, _w, finalBlock); - var rval = forge2.util.createBuffer(); - rval.putInt32(s2.h0); - rval.putInt32(s2.h1); - rval.putInt32(s2.h2); - rval.putInt32(s2.h3); - rval.putInt32(s2.h4); - return rval; - }; - return md; - }; - var _padding = null; - var _initialized = false; - function _init() { - _padding = String.fromCharCode(128); - _padding += forge2.util.fillString(String.fromCharCode(0), 64); - _initialized = true; - } - function _update(s, w, bytes) { - var t, a, b, c, d, e, f, i; - var len = bytes.length(); - while (len >= 64) { - a = s.h0; - b = s.h1; - c = s.h2; - d = s.h3; - e = s.h4; - for (i = 0; i < 16; ++i) { - t = bytes.getInt32(); - w[i] = t; - f = d ^ b & (c ^ d); - t = (a << 5 | a >>> 27) + f + e + 1518500249 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 20; ++i) { - t = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; - t = t << 1 | t >>> 31; - w[i] = t; - f = d ^ b & (c ^ d); - t = (a << 5 | a >>> 27) + f + e + 1518500249 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 32; ++i) { - t = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; - t = t << 1 | t >>> 31; - w[i] = t; - f = b ^ c ^ d; - t = (a << 5 | a >>> 27) + f + e + 1859775393 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 40; ++i) { - t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; - t = t << 2 | t >>> 30; - w[i] = t; - f = b ^ c ^ d; - t = (a << 5 | a >>> 27) + f + e + 1859775393 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 60; ++i) { - t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; - t = t << 2 | t >>> 30; - w[i] = t; - f = b & c | d & (b ^ c); - t = (a << 5 | a >>> 27) + f + e + 2400959708 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - for (; i < 80; ++i) { - t = w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]; - t = t << 2 | t >>> 30; - w[i] = t; - f = b ^ c ^ d; - t = (a << 5 | a >>> 27) + f + e + 3395469782 + t; - e = d; - d = c; - c = (b << 30 | b >>> 2) >>> 0; - b = a; - a = t; - } - s.h0 = s.h0 + a | 0; - s.h1 = s.h1 + b | 0; - s.h2 = s.h2 + c | 0; - s.h3 = s.h3 + d | 0; - s.h4 = s.h4 + e | 0; - len -= 64; - } - } - } -}); - -// node_modules/node-forge/lib/pkcs1.js -var require_pkcs1 = __commonJS({ - "node_modules/node-forge/lib/pkcs1.js"(exports, module) { - var forge2 = require_forge(); - require_util(); - require_random(); - require_sha1(); - var pkcs1 = module.exports = forge2.pkcs1 = forge2.pkcs1 || {}; - pkcs1.encode_rsa_oaep = function(key, message, options) { - var label; - var seed; - var md; - var mgf1Md; - if (typeof options === "string") { - label = options; - seed = arguments[3] || void 0; - md = arguments[4] || void 0; - } else if (options) { - label = options.label || void 0; - seed = options.seed || void 0; - md = options.md || void 0; - if (options.mgf1 && options.mgf1.md) { - mgf1Md = options.mgf1.md; - } - } - if (!md) { - md = forge2.md.sha1.create(); - } else { - md.start(); - } - if (!mgf1Md) { - mgf1Md = md; - } - var keyLength = Math.ceil(key.n.bitLength() / 8); - var maxLength = keyLength - 2 * md.digestLength - 2; - if (message.length > maxLength) { - var error = new Error("RSAES-OAEP input message length is too long."); - error.length = message.length; - error.maxLength = maxLength; - throw error; - } - if (!label) { - label = ""; - } - md.update(label, "raw"); - var lHash = md.digest(); - var PS = ""; - var PS_length = maxLength - message.length; - for (var i = 0; i < PS_length; i++) { - PS += "\0"; - } - var DB = lHash.getBytes() + PS + "" + message; - if (!seed) { - seed = forge2.random.getBytes(md.digestLength); - } else if (seed.length !== md.digestLength) { - var error = new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length."); - error.seedLength = seed.length; - error.digestLength = md.digestLength; - throw error; - } - var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); - var maskedDB = forge2.util.xorBytes(DB, dbMask, DB.length); - var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); - var maskedSeed = forge2.util.xorBytes(seed, seedMask, seed.length); - return "\0" + maskedSeed + maskedDB; - }; - pkcs1.decode_rsa_oaep = function(key, em, options) { - var label; - var md; - var mgf1Md; - if (typeof options === "string") { - label = options; - md = arguments[3] || void 0; - } else if (options) { - label = options.label || void 0; - md = options.md || void 0; - if (options.mgf1 && options.mgf1.md) { - mgf1Md = options.mgf1.md; - } - } - var keyLength = Math.ceil(key.n.bitLength() / 8); - if (em.length !== keyLength) { - var error = new Error("RSAES-OAEP encoded message length is invalid."); - error.length = em.length; - error.expectedLength = keyLength; - throw error; - } - if (md === void 0) { - md = forge2.md.sha1.create(); - } else { - md.start(); - } - if (!mgf1Md) { - mgf1Md = md; - } - if (keyLength < 2 * md.digestLength + 2) { - throw new Error("RSAES-OAEP key is too short for the hash function."); - } - if (!label) { - label = ""; - } - md.update(label, "raw"); - var lHash = md.digest().getBytes(); - var y = em.charAt(0); - var maskedSeed = em.substring(1, md.digestLength + 1); - var maskedDB = em.substring(1 + md.digestLength); - var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); - var seed = forge2.util.xorBytes(maskedSeed, seedMask, maskedSeed.length); - var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); - var db2 = forge2.util.xorBytes(maskedDB, dbMask, maskedDB.length); - var lHashPrime = db2.substring(0, md.digestLength); - var error = y !== "\0"; - for (var i = 0; i < md.digestLength; ++i) { - error |= lHash.charAt(i) !== lHashPrime.charAt(i); - } - var in_ps = 1; - var index = md.digestLength; - for (var j = md.digestLength; j < db2.length; j++) { - var code = db2.charCodeAt(j); - var is_0 = code & 1 ^ 1; - var error_mask = in_ps ? 65534 : 0; - error |= code & error_mask; - in_ps = in_ps & is_0; - index += in_ps; - } - if (error || db2.charCodeAt(index) !== 1) { - throw new Error("Invalid RSAES-OAEP padding."); - } - return db2.substring(index + 1); - }; - function rsa_mgf1(seed, maskLength, hash) { - if (!hash) { - hash = forge2.md.sha1.create(); - } - var t = ""; - var count = Math.ceil(maskLength / hash.digestLength); - for (var i = 0; i < count; ++i) { - var c = String.fromCharCode( - i >> 24 & 255, - i >> 16 & 255, - i >> 8 & 255, - i & 255 - ); - hash.start(); - hash.update(seed + c); - t += hash.digest().getBytes(); - } - return t.substring(0, maskLength); - } - } -}); - -// node_modules/node-forge/lib/prime.js -var require_prime = __commonJS({ - "node_modules/node-forge/lib/prime.js"(exports, module) { - var forge2 = require_forge(); - require_util(); - require_jsbn(); - require_random(); - (function() { - if (forge2.prime) { - module.exports = forge2.prime; - return; - } - var prime = module.exports = forge2.prime = forge2.prime || {}; - var BigInteger2 = forge2.jsbn.BigInteger; - var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; - var THIRTY = new BigInteger2(null); - THIRTY.fromInt(30); - var op_or = function(x, y) { - return x | y; - }; - prime.generateProbablePrime = function(bits, options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; - } - options = options || {}; - var algorithm = options.algorithm || "PRIMEINC"; - if (typeof algorithm === "string") { - algorithm = { name: algorithm }; - } - algorithm.options = algorithm.options || {}; - var prng = options.prng || forge2.random; - var rng = { - // x is an array to fill with bytes - nextBytes: function(x) { - var b = prng.getBytesSync(x.length); - for (var i = 0; i < x.length; ++i) { - x[i] = b.charCodeAt(i); - } - } - }; - if (algorithm.name === "PRIMEINC") { - return primeincFindPrime(bits, rng, algorithm.options, callback); - } - throw new Error("Invalid prime generation algorithm: " + algorithm.name); - }; - function primeincFindPrime(bits, rng, options, callback) { - if ("workers" in options) { - return primeincFindPrimeWithWorkers(bits, rng, options, callback); - } - return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); - } - function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) { - var num = generateRandom(bits, rng); - var deltaIdx = 0; - var mrTests = getMillerRabinTests(num.bitLength()); - if ("millerRabinTests" in options) { - mrTests = options.millerRabinTests; - } - var maxBlockTime = 10; - if ("maxBlockTime" in options) { - maxBlockTime = options.maxBlockTime; - } - _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); - } - function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) { - var start = +/* @__PURE__ */ new Date(); - do { - if (num.bitLength() > bits) { - num = generateRandom(bits, rng); - } - if (num.isProbablePrime(mrTests)) { - return callback(null, num); - } - num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); - } while (maxBlockTime < 0 || +/* @__PURE__ */ new Date() - start < maxBlockTime); - forge2.util.setImmediate(function() { - _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); - }); - } - function primeincFindPrimeWithWorkers(bits, rng, options, callback) { - if (typeof Worker === "undefined") { - return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); - } - var num = generateRandom(bits, rng); - var numWorkers = options.workers; - var workLoad = options.workLoad || 100; - var range = workLoad * 30 / 8; - var workerScript = options.workerScript || "forge/prime.worker.js"; - if (numWorkers === -1) { - return forge2.util.estimateCores(function(err, cores) { - if (err) { - cores = 2; - } - numWorkers = cores - 1; - generate(); - }); - } - generate(); - function generate() { - numWorkers = Math.max(1, numWorkers); - var workers = []; - for (var i = 0; i < numWorkers; ++i) { - workers[i] = new Worker(workerScript); - } - var running = numWorkers; - for (var i = 0; i < numWorkers; ++i) { - workers[i].addEventListener("message", workerMessage); - } - var found = false; - function workerMessage(e) { - if (found) { - return; - } - --running; - var data = e.data; - if (data.found) { - for (var i2 = 0; i2 < workers.length; ++i2) { - workers[i2].terminate(); - } - found = true; - return callback(null, new BigInteger2(data.prime, 16)); - } - if (num.bitLength() > bits) { - num = generateRandom(bits, rng); - } - var hex = num.toString(16); - e.target.postMessage({ - hex, - workLoad - }); - num.dAddOffset(range, 0); - } - } - } - function generateRandom(bits, rng) { - var num = new BigInteger2(bits, rng); - var bits1 = bits - 1; - if (!num.testBit(bits1)) { - num.bitwiseTo(BigInteger2.ONE.shiftLeft(bits1), op_or, num); - } - num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0); - return num; - } - function getMillerRabinTests(bits) { - if (bits <= 100) return 27; - if (bits <= 150) return 18; - if (bits <= 200) return 15; - if (bits <= 250) return 12; - if (bits <= 300) return 9; - if (bits <= 350) return 8; - if (bits <= 400) return 7; - if (bits <= 500) return 6; - if (bits <= 600) return 5; - if (bits <= 800) return 4; - if (bits <= 1250) return 3; - return 2; - } - })(); - } -}); - -// node_modules/node-forge/lib/rsa.js -var require_rsa = __commonJS({ - "node_modules/node-forge/lib/rsa.js"(exports, module) { - var forge2 = require_forge(); - require_asn1(); - require_jsbn(); - require_oids(); - require_pkcs1(); - require_prime(); - require_random(); - require_util(); - if (typeof BigInteger2 === "undefined") { - BigInteger2 = forge2.jsbn.BigInteger; - } - var BigInteger2; - var _crypto = forge2.util.isNodejs ? __require("crypto") : null; - var asn1 = forge2.asn1; - var util = forge2.util; - forge2.pki = forge2.pki || {}; - module.exports = forge2.pki.rsa = forge2.rsa = forge2.rsa || {}; - var pki = forge2.pki; - var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; - var privateKeyValidator = { - // PrivateKeyInfo - name: "PrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: "PrivateKeyInfo.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyVersion" - }, { - // privateKeyAlgorithm - name: "PrivateKeyInfo.privateKeyAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "privateKeyOid" - }] - }, { - // PrivateKey - name: "PrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "privateKey" - }] - }; - var rsaPrivateKeyValidator = { - // RSAPrivateKey - name: "RSAPrivateKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: "RSAPrivateKey.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyVersion" - }, { - // modulus (n) - name: "RSAPrivateKey.modulus", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyModulus" - }, { - // publicExponent (e) - name: "RSAPrivateKey.publicExponent", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyPublicExponent" - }, { - // privateExponent (d) - name: "RSAPrivateKey.privateExponent", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyPrivateExponent" - }, { - // prime1 (p) - name: "RSAPrivateKey.prime1", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyPrime1" - }, { - // prime2 (q) - name: "RSAPrivateKey.prime2", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyPrime2" - }, { - // exponent1 (d mod (p-1)) - name: "RSAPrivateKey.exponent1", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyExponent1" - }, { - // exponent2 (d mod (q-1)) - name: "RSAPrivateKey.exponent2", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyExponent2" - }, { - // coefficient ((inverse of q) mod p) - name: "RSAPrivateKey.coefficient", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyCoefficient" - }] - }; - var rsaPublicKeyValidator = { - // RSAPublicKey - name: "RSAPublicKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // modulus (n) - name: "RSAPublicKey.modulus", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "publicKeyModulus" - }, { - // publicExponent (e) - name: "RSAPublicKey.exponent", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "publicKeyExponent" - }] - }; - var publicKeyValidator = forge2.pki.rsa.publicKeyValidator = { - name: "SubjectPublicKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "subjectPublicKeyInfo", - value: [{ - name: "SubjectPublicKeyInfo.AlgorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "publicKeyOid" - }] - }, { - // subjectPublicKey - name: "SubjectPublicKeyInfo.subjectPublicKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - value: [{ - // RSAPublicKey - name: "SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: "rsaPublicKey" - }] - }] - }; - var digestInfoValidator = { - name: "DigestInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "DigestInfo.DigestAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "DigestInfo.DigestAlgorithm.algorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "algorithmIdentifier" - }, { - // NULL paramters - name: "DigestInfo.DigestAlgorithm.parameters", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.NULL, - // captured only to check existence for md2 and md5 - capture: "parameters", - optional: true, - constructed: false - }] - }, { - // digest - name: "DigestInfo.digest", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "digest" - }] - }; - var emsaPkcs1v15encode = function(md) { - var oid; - if (md.algorithm in pki.oids) { - oid = pki.oids[md.algorithm]; - } else { - var error = new Error("Unknown message digest algorithm."); - error.algorithm = md.algorithm; - throw error; - } - var oidBytes = asn1.oidToDer(oid).getBytes(); - var digestInfo = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - var digestAlgorithm = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - digestAlgorithm.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - oidBytes - )); - digestAlgorithm.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.NULL, - false, - "" - )); - var digest = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - md.digest().getBytes() - ); - digestInfo.value.push(digestAlgorithm); - digestInfo.value.push(digest); - return asn1.toDer(digestInfo).getBytes(); - }; - var _modPow = function(x, key, pub) { - if (pub) { - return x.modPow(key.e, key.n); - } - if (!key.p || !key.q) { - return x.modPow(key.d, key.n); - } - if (!key.dP) { - key.dP = key.d.mod(key.p.subtract(BigInteger2.ONE)); - } - if (!key.dQ) { - key.dQ = key.d.mod(key.q.subtract(BigInteger2.ONE)); - } - if (!key.qInv) { - key.qInv = key.q.modInverse(key.p); - } - var r; - do { - r = new BigInteger2( - forge2.util.bytesToHex(forge2.random.getBytes(key.n.bitLength() / 8)), - 16 - ); - } while (r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger2.ONE)); - x = x.multiply(r.modPow(key.e, key.n)).mod(key.n); - var xp = x.mod(key.p).modPow(key.dP, key.p); - var xq = x.mod(key.q).modPow(key.dQ, key.q); - while (xp.compareTo(xq) < 0) { - xp = xp.add(key.p); - } - var y = xp.subtract(xq).multiply(key.qInv).mod(key.p).multiply(key.q).add(xq); - y = y.multiply(r.modInverse(key.n)).mod(key.n); - return y; - }; - pki.rsa.encrypt = function(m, key, bt) { - var pub = bt; - var eb; - var k = Math.ceil(key.n.bitLength() / 8); - if (bt !== false && bt !== true) { - pub = bt === 2; - eb = _encodePkcs1_v1_5(m, key, bt); - } else { - eb = forge2.util.createBuffer(); - eb.putBytes(m); - } - var x = new BigInteger2(eb.toHex(), 16); - var y = _modPow(x, key, pub); - var yhex = y.toString(16); - var ed = forge2.util.createBuffer(); - var zeros = k - Math.ceil(yhex.length / 2); - while (zeros > 0) { - ed.putByte(0); - --zeros; - } - ed.putBytes(forge2.util.hexToBytes(yhex)); - return ed.getBytes(); - }; - pki.rsa.decrypt = function(ed, key, pub, ml) { - var k = Math.ceil(key.n.bitLength() / 8); - if (ed.length !== k) { - var error = new Error("Encrypted message length is invalid."); - error.length = ed.length; - error.expected = k; - throw error; - } - var y = new BigInteger2(forge2.util.createBuffer(ed).toHex(), 16); - if (y.compareTo(key.n) >= 0) { - throw new Error("Encrypted message is invalid."); - } - var x = _modPow(y, key, pub); - var xhex = x.toString(16); - var eb = forge2.util.createBuffer(); - var zeros = k - Math.ceil(xhex.length / 2); - while (zeros > 0) { - eb.putByte(0); - --zeros; - } - eb.putBytes(forge2.util.hexToBytes(xhex)); - if (ml !== false) { - return _decodePkcs1_v1_5(eb.getBytes(), key, pub); - } - return eb.getBytes(); - }; - pki.rsa.createKeyPairGenerationState = function(bits, e, options) { - if (typeof bits === "string") { - bits = parseInt(bits, 10); - } - bits = bits || 2048; - options = options || {}; - var prng = options.prng || forge2.random; - var rng = { - // x is an array to fill with bytes - nextBytes: function(x) { - var b = prng.getBytesSync(x.length); - for (var i = 0; i < x.length; ++i) { - x[i] = b.charCodeAt(i); - } - } - }; - var algorithm = options.algorithm || "PRIMEINC"; - var rval; - if (algorithm === "PRIMEINC") { - rval = { - algorithm, - state: 0, - bits, - rng, - eInt: e || 65537, - e: new BigInteger2(null), - p: null, - q: null, - qBits: bits >> 1, - pBits: bits - (bits >> 1), - pqState: 0, - num: null, - keys: null - }; - rval.e.fromInt(rval.eInt); - } else { - throw new Error("Invalid key generation algorithm: " + algorithm); - } - return rval; - }; - pki.rsa.stepKeyPairGenerationState = function(state, n) { - if (!("algorithm" in state)) { - state.algorithm = "PRIMEINC"; - } - var THIRTY = new BigInteger2(null); - THIRTY.fromInt(30); - var deltaIdx = 0; - var op_or = function(x, y) { - return x | y; - }; - var t1 = +/* @__PURE__ */ new Date(); - var t2; - var total = 0; - while (state.keys === null && (n <= 0 || total < n)) { - if (state.state === 0) { - var bits = state.p === null ? state.pBits : state.qBits; - var bits1 = bits - 1; - if (state.pqState === 0) { - state.num = new BigInteger2(bits, state.rng); - if (!state.num.testBit(bits1)) { - state.num.bitwiseTo( - BigInteger2.ONE.shiftLeft(bits1), - op_or, - state.num - ); - } - state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0); - deltaIdx = 0; - ++state.pqState; - } else if (state.pqState === 1) { - if (state.num.bitLength() > bits) { - state.pqState = 0; - } else if (state.num.isProbablePrime( - _getMillerRabinTests(state.num.bitLength()) - )) { - ++state.pqState; - } else { - state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); - } - } else if (state.pqState === 2) { - state.pqState = state.num.subtract(BigInteger2.ONE).gcd(state.e).compareTo(BigInteger2.ONE) === 0 ? 3 : 0; - } else if (state.pqState === 3) { - state.pqState = 0; - if (state.p === null) { - state.p = state.num; - } else { - state.q = state.num; - } - if (state.p !== null && state.q !== null) { - ++state.state; - } - state.num = null; - } - } else if (state.state === 1) { - if (state.p.compareTo(state.q) < 0) { - state.num = state.p; - state.p = state.q; - state.q = state.num; - } - ++state.state; - } else if (state.state === 2) { - state.p1 = state.p.subtract(BigInteger2.ONE); - state.q1 = state.q.subtract(BigInteger2.ONE); - state.phi = state.p1.multiply(state.q1); - ++state.state; - } else if (state.state === 3) { - if (state.phi.gcd(state.e).compareTo(BigInteger2.ONE) === 0) { - ++state.state; - } else { - state.p = null; - state.q = null; - state.state = 0; - } - } else if (state.state === 4) { - state.n = state.p.multiply(state.q); - if (state.n.bitLength() === state.bits) { - ++state.state; - } else { - state.q = null; - state.state = 0; - } - } else if (state.state === 5) { - var d = state.e.modInverse(state.phi); - state.keys = { - privateKey: pki.rsa.setPrivateKey( - state.n, - state.e, - d, - state.p, - state.q, - d.mod(state.p1), - d.mod(state.q1), - state.q.modInverse(state.p) - ), - publicKey: pki.rsa.setPublicKey(state.n, state.e) - }; - } - t2 = +/* @__PURE__ */ new Date(); - total += t2 - t1; - t1 = t2; - } - return state.keys !== null; - }; - pki.rsa.generateKeyPair = function(bits, e, options, callback) { - if (arguments.length === 1) { - if (typeof bits === "object") { - options = bits; - bits = void 0; - } else if (typeof bits === "function") { - callback = bits; - bits = void 0; - } - } else if (arguments.length === 2) { - if (typeof bits === "number") { - if (typeof e === "function") { - callback = e; - e = void 0; - } else if (typeof e !== "number") { - options = e; - e = void 0; - } - } else { - options = bits; - callback = e; - bits = void 0; - e = void 0; - } - } else if (arguments.length === 3) { - if (typeof e === "number") { - if (typeof options === "function") { - callback = options; - options = void 0; - } - } else { - callback = options; - options = e; - e = void 0; - } - } - options = options || {}; - if (bits === void 0) { - bits = options.bits || 2048; - } - if (e === void 0) { - e = options.e || 65537; - } - if (!forge2.options.usePureJavaScript && !options.prng && bits >= 256 && bits <= 16384 && (e === 65537 || e === 3)) { - if (callback) { - if (_detectNodeCrypto("generateKeyPair")) { - return _crypto.generateKeyPair("rsa", { - modulusLength: bits, - publicExponent: e, - publicKeyEncoding: { - type: "spki", - format: "pem" - }, - privateKeyEncoding: { - type: "pkcs8", - format: "pem" - } - }, function(err, pub, priv) { - if (err) { - return callback(err); - } - callback(null, { - privateKey: pki.privateKeyFromPem(priv), - publicKey: pki.publicKeyFromPem(pub) - }); - }); - } - if (_detectSubtleCrypto("generateKey") && _detectSubtleCrypto("exportKey")) { - return util.globalScope.crypto.subtle.generateKey({ - name: "RSASSA-PKCS1-v1_5", - modulusLength: bits, - publicExponent: _intToUint8Array(e), - hash: { name: "SHA-256" } - }, true, ["sign", "verify"]).then(function(pair) { - return util.globalScope.crypto.subtle.exportKey( - "pkcs8", - pair.privateKey - ); - }).then(void 0, function(err) { - callback(err); - }).then(function(pkcs8) { - if (pkcs8) { - var privateKey = pki.privateKeyFromAsn1( - asn1.fromDer(forge2.util.createBuffer(pkcs8)) - ); - callback(null, { - privateKey, - publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) - }); - } - }); - } - if (_detectSubtleMsCrypto("generateKey") && _detectSubtleMsCrypto("exportKey")) { - var genOp = util.globalScope.msCrypto.subtle.generateKey({ - name: "RSASSA-PKCS1-v1_5", - modulusLength: bits, - publicExponent: _intToUint8Array(e), - hash: { name: "SHA-256" } - }, true, ["sign", "verify"]); - genOp.oncomplete = function(e2) { - var pair = e2.target.result; - var exportOp = util.globalScope.msCrypto.subtle.exportKey( - "pkcs8", - pair.privateKey - ); - exportOp.oncomplete = function(e3) { - var pkcs8 = e3.target.result; - var privateKey = pki.privateKeyFromAsn1( - asn1.fromDer(forge2.util.createBuffer(pkcs8)) - ); - callback(null, { - privateKey, - publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) - }); - }; - exportOp.onerror = function(err) { - callback(err); - }; - }; - genOp.onerror = function(err) { - callback(err); - }; - return; - } - } else { - if (_detectNodeCrypto("generateKeyPairSync")) { - var keypair = _crypto.generateKeyPairSync("rsa", { - modulusLength: bits, - publicExponent: e, - publicKeyEncoding: { - type: "spki", - format: "pem" - }, - privateKeyEncoding: { - type: "pkcs8", - format: "pem" - } - }); - return { - privateKey: pki.privateKeyFromPem(keypair.privateKey), - publicKey: pki.publicKeyFromPem(keypair.publicKey) - }; - } - } - } - var state = pki.rsa.createKeyPairGenerationState(bits, e, options); - if (!callback) { - pki.rsa.stepKeyPairGenerationState(state, 0); - return state.keys; - } - _generateKeyPair(state, options, callback); - }; - pki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) { - var key = { - n, - e - }; - key.encrypt = function(data, scheme, schemeOptions) { - if (typeof scheme === "string") { - scheme = scheme.toUpperCase(); - } else if (scheme === void 0) { - scheme = "RSAES-PKCS1-V1_5"; - } - if (scheme === "RSAES-PKCS1-V1_5") { - scheme = { - encode: function(m, key2, pub) { - return _encodePkcs1_v1_5(m, key2, 2).getBytes(); - } - }; - } else if (scheme === "RSA-OAEP" || scheme === "RSAES-OAEP") { - scheme = { - encode: function(m, key2) { - return forge2.pkcs1.encode_rsa_oaep(key2, m, schemeOptions); - } - }; - } else if (["RAW", "NONE", "NULL", null].indexOf(scheme) !== -1) { - scheme = { encode: function(e3) { - return e3; - } }; - } else if (typeof scheme === "string") { - throw new Error('Unsupported encryption scheme: "' + scheme + '".'); - } - var e2 = scheme.encode(data, key, true); - return pki.rsa.encrypt(e2, key, true); - }; - key.verify = function(digest, signature, scheme, options) { - if (typeof scheme === "string") { - scheme = scheme.toUpperCase(); - } else if (scheme === void 0) { - scheme = "RSASSA-PKCS1-V1_5"; - } - if (options === void 0) { - options = { - _parseAllDigestBytes: true - }; - } - if (!("_parseAllDigestBytes" in options)) { - options._parseAllDigestBytes = true; - } - if (scheme === "RSASSA-PKCS1-V1_5") { - scheme = { - verify: function(digest2, d2) { - d2 = _decodePkcs1_v1_5(d2, key, true); - var obj = asn1.fromDer(d2, { - parseAllBytes: options._parseAllDigestBytes - }); - var capture = {}; - var errors = []; - if (!asn1.validate(obj, digestInfoValidator, capture, errors)) { - var error = new Error( - "ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value." - ); - error.errors = errors; - throw error; - } - var oid = asn1.derToOid(capture.algorithmIdentifier); - if (!(oid === forge2.oids.md2 || oid === forge2.oids.md5 || oid === forge2.oids.sha1 || oid === forge2.oids.sha224 || oid === forge2.oids.sha256 || oid === forge2.oids.sha384 || oid === forge2.oids.sha512 || oid === forge2.oids["sha512-224"] || oid === forge2.oids["sha512-256"])) { - var error = new Error( - "Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier." - ); - error.oid = oid; - throw error; - } - if (oid === forge2.oids.md2 || oid === forge2.oids.md5) { - if (!("parameters" in capture)) { - throw new Error( - "ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters." - ); - } - } - return digest2 === capture.digest; - } - }; - } else if (scheme === "NONE" || scheme === "NULL" || scheme === null) { - scheme = { - verify: function(digest2, d2) { - d2 = _decodePkcs1_v1_5(d2, key, true); - return digest2 === d2; - } - }; - } - var d = pki.rsa.decrypt(signature, key, true, false); - return scheme.verify(digest, d, key.n.bitLength()); - }; - return key; - }; - pki.setRsaPrivateKey = pki.rsa.setPrivateKey = function(n, e, d, p, q, dP, dQ, qInv) { - var key = { - n, - e, - d, - p, - q, - dP, - dQ, - qInv - }; - key.decrypt = function(data, scheme, schemeOptions) { - if (typeof scheme === "string") { - scheme = scheme.toUpperCase(); - } else if (scheme === void 0) { - scheme = "RSAES-PKCS1-V1_5"; - } - var d2 = pki.rsa.decrypt(data, key, false, false); - if (scheme === "RSAES-PKCS1-V1_5") { - scheme = { decode: _decodePkcs1_v1_5 }; - } else if (scheme === "RSA-OAEP" || scheme === "RSAES-OAEP") { - scheme = { - decode: function(d3, key2) { - return forge2.pkcs1.decode_rsa_oaep(key2, d3, schemeOptions); - } - }; - } else if (["RAW", "NONE", "NULL", null].indexOf(scheme) !== -1) { - scheme = { decode: function(d3) { - return d3; - } }; - } else { - throw new Error('Unsupported encryption scheme: "' + scheme + '".'); - } - return scheme.decode(d2, key, false); - }; - key.sign = function(md, scheme) { - var bt = false; - if (typeof scheme === "string") { - scheme = scheme.toUpperCase(); - } - if (scheme === void 0 || scheme === "RSASSA-PKCS1-V1_5") { - scheme = { encode: emsaPkcs1v15encode }; - bt = 1; - } else if (scheme === "NONE" || scheme === "NULL" || scheme === null) { - scheme = { encode: function() { - return md; - } }; - bt = 1; - } - var d2 = scheme.encode(md, key.n.bitLength()); - return pki.rsa.encrypt(d2, key, bt); - }; - return key; - }; - pki.wrapRsaPrivateKey = function(rsaKey) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version (0) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(0).getBytes() - ), - // privateKeyAlgorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.rsaEncryption).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]), - // PrivateKey - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(rsaKey).getBytes() - ) - ]); - }; - pki.privateKeyFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - if (asn1.validate(obj, privateKeyValidator, capture, errors)) { - obj = asn1.fromDer(forge2.util.createBuffer(capture.privateKey)); - } - capture = {}; - errors = []; - if (!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) { - var error = new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey."); - error.errors = errors; - throw error; - } - var n, e, d, p, q, dP, dQ, qInv; - n = forge2.util.createBuffer(capture.privateKeyModulus).toHex(); - e = forge2.util.createBuffer(capture.privateKeyPublicExponent).toHex(); - d = forge2.util.createBuffer(capture.privateKeyPrivateExponent).toHex(); - p = forge2.util.createBuffer(capture.privateKeyPrime1).toHex(); - q = forge2.util.createBuffer(capture.privateKeyPrime2).toHex(); - dP = forge2.util.createBuffer(capture.privateKeyExponent1).toHex(); - dQ = forge2.util.createBuffer(capture.privateKeyExponent2).toHex(); - qInv = forge2.util.createBuffer(capture.privateKeyCoefficient).toHex(); - return pki.setRsaPrivateKey( - new BigInteger2(n, 16), - new BigInteger2(e, 16), - new BigInteger2(d, 16), - new BigInteger2(p, 16), - new BigInteger2(q, 16), - new BigInteger2(dP, 16), - new BigInteger2(dQ, 16), - new BigInteger2(qInv, 16) - ); - }; - pki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version (0 = only 2 primes, 1 multiple primes) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(0).getBytes() - ), - // modulus (n) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.n) - ), - // publicExponent (e) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.e) - ), - // privateExponent (d) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.d) - ), - // privateKeyPrime1 (p) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.p) - ), - // privateKeyPrime2 (q) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.q) - ), - // privateKeyExponent1 (dP) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.dP) - ), - // privateKeyExponent2 (dQ) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.dQ) - ), - // coefficient (qInv) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.qInv) - ) - ]); - }; - pki.publicKeyFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - if (asn1.validate(obj, publicKeyValidator, capture, errors)) { - var oid = asn1.derToOid(capture.publicKeyOid); - if (oid !== pki.oids.rsaEncryption) { - var error = new Error("Cannot read public key. Unknown OID."); - error.oid = oid; - throw error; - } - obj = capture.rsaPublicKey; - } - errors = []; - if (!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) { - var error = new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey."); - error.errors = errors; - throw error; - } - var n = forge2.util.createBuffer(capture.publicKeyModulus).toHex(); - var e = forge2.util.createBuffer(capture.publicKeyExponent).toHex(); - return pki.setRsaPublicKey( - new BigInteger2(n, 16), - new BigInteger2(e, 16) - ); - }; - pki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.rsaEncryption).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]), - // subjectPublicKey - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [ - pki.publicKeyToRSAPublicKey(key) - ]) - ]); - }; - pki.publicKeyToRSAPublicKey = function(key) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // modulus (n) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.n) - ), - // publicExponent (e) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - _bnToBytes(key.e) - ) - ]); - }; - function _encodePkcs1_v1_5(m, key, bt) { - var eb = forge2.util.createBuffer(); - var k = Math.ceil(key.n.bitLength() / 8); - if (m.length > k - 11) { - var error = new Error("Message is too long for PKCS#1 v1.5 padding."); - error.length = m.length; - error.max = k - 11; - throw error; - } - eb.putByte(0); - eb.putByte(bt); - var padNum = k - 3 - m.length; - var padByte; - if (bt === 0 || bt === 1) { - padByte = bt === 0 ? 0 : 255; - for (var i = 0; i < padNum; ++i) { - eb.putByte(padByte); - } - } else { - while (padNum > 0) { - var numZeros = 0; - var padBytes = forge2.random.getBytes(padNum); - for (var i = 0; i < padNum; ++i) { - padByte = padBytes.charCodeAt(i); - if (padByte === 0) { - ++numZeros; - } else { - eb.putByte(padByte); - } - } - padNum = numZeros; - } - } - eb.putByte(0); - eb.putBytes(m); - return eb; - } - function _decodePkcs1_v1_5(em, key, pub, ml) { - var k = Math.ceil(key.n.bitLength() / 8); - var eb = forge2.util.createBuffer(em); - var first = eb.getByte(); - var bt = eb.getByte(); - if (first !== 0 || pub && bt !== 0 && bt !== 1 || !pub && bt != 2 || pub && bt === 0 && typeof ml === "undefined") { - throw new Error("Encryption block is invalid."); - } - var padNum = 0; - if (bt === 0) { - padNum = k - 3 - ml; - for (var i = 0; i < padNum; ++i) { - if (eb.getByte() !== 0) { - throw new Error("Encryption block is invalid."); - } - } - } else if (bt === 1) { - padNum = 0; - while (eb.length() > 1) { - if (eb.getByte() !== 255) { - --eb.read; - break; - } - ++padNum; - } - } else if (bt === 2) { - padNum = 0; - while (eb.length() > 1) { - if (eb.getByte() === 0) { - --eb.read; - break; - } - ++padNum; - } - } - var zero = eb.getByte(); - if (zero !== 0 || padNum !== k - 3 - eb.length()) { - throw new Error("Encryption block is invalid."); - } - return eb.getBytes(); - } - function _generateKeyPair(state, options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; - } - options = options || {}; - var opts = { - algorithm: { - name: options.algorithm || "PRIMEINC", - options: { - workers: options.workers || 2, - workLoad: options.workLoad || 100, - workerScript: options.workerScript - } - } - }; - if ("prng" in options) { - opts.prng = options.prng; - } - generate(); - function generate() { - getPrime(state.pBits, function(err, num) { - if (err) { - return callback(err); - } - state.p = num; - if (state.q !== null) { - return finish(err, state.q); - } - getPrime(state.qBits, finish); - }); - } - function getPrime(bits, callback2) { - forge2.prime.generateProbablePrime(bits, opts, callback2); - } - function finish(err, num) { - if (err) { - return callback(err); - } - state.q = num; - if (state.p.compareTo(state.q) < 0) { - var tmp = state.p; - state.p = state.q; - state.q = tmp; - } - if (state.p.subtract(BigInteger2.ONE).gcd(state.e).compareTo(BigInteger2.ONE) !== 0) { - state.p = null; - generate(); - return; - } - if (state.q.subtract(BigInteger2.ONE).gcd(state.e).compareTo(BigInteger2.ONE) !== 0) { - state.q = null; - getPrime(state.qBits, finish); - return; - } - state.p1 = state.p.subtract(BigInteger2.ONE); - state.q1 = state.q.subtract(BigInteger2.ONE); - state.phi = state.p1.multiply(state.q1); - if (state.phi.gcd(state.e).compareTo(BigInteger2.ONE) !== 0) { - state.p = state.q = null; - generate(); - return; - } - state.n = state.p.multiply(state.q); - if (state.n.bitLength() !== state.bits) { - state.q = null; - getPrime(state.qBits, finish); - return; - } - var d = state.e.modInverse(state.phi); - state.keys = { - privateKey: pki.rsa.setPrivateKey( - state.n, - state.e, - d, - state.p, - state.q, - d.mod(state.p1), - d.mod(state.q1), - state.q.modInverse(state.p) - ), - publicKey: pki.rsa.setPublicKey(state.n, state.e) - }; - callback(null, state.keys); - } - } - function _bnToBytes(b) { - var hex = b.toString(16); - if (hex[0] >= "8") { - hex = "00" + hex; - } - var bytes = forge2.util.hexToBytes(hex); - if (bytes.length > 1 && // leading 0x00 for positive integer - (bytes.charCodeAt(0) === 0 && (bytes.charCodeAt(1) & 128) === 0 || // leading 0xFF for negative integer - bytes.charCodeAt(0) === 255 && (bytes.charCodeAt(1) & 128) === 128)) { - return bytes.substr(1); - } - return bytes; - } - function _getMillerRabinTests(bits) { - if (bits <= 100) return 27; - if (bits <= 150) return 18; - if (bits <= 200) return 15; - if (bits <= 250) return 12; - if (bits <= 300) return 9; - if (bits <= 350) return 8; - if (bits <= 400) return 7; - if (bits <= 500) return 6; - if (bits <= 600) return 5; - if (bits <= 800) return 4; - if (bits <= 1250) return 3; - return 2; - } - function _detectNodeCrypto(fn) { - return forge2.util.isNodejs && typeof _crypto[fn] === "function"; - } - function _detectSubtleCrypto(fn) { - return typeof util.globalScope !== "undefined" && typeof util.globalScope.crypto === "object" && typeof util.globalScope.crypto.subtle === "object" && typeof util.globalScope.crypto.subtle[fn] === "function"; - } - function _detectSubtleMsCrypto(fn) { - return typeof util.globalScope !== "undefined" && typeof util.globalScope.msCrypto === "object" && typeof util.globalScope.msCrypto.subtle === "object" && typeof util.globalScope.msCrypto.subtle[fn] === "function"; - } - function _intToUint8Array(x) { - var bytes = forge2.util.hexToBytes(x.toString(16)); - var buffer = new Uint8Array(bytes.length); - for (var i = 0; i < bytes.length; ++i) { - buffer[i] = bytes.charCodeAt(i); - } - return buffer; - } - } -}); - -// node_modules/node-forge/lib/pbe.js -var require_pbe = __commonJS({ - "node_modules/node-forge/lib/pbe.js"(exports, module) { - var forge2 = require_forge(); - require_aes(); - require_asn1(); - require_des(); - require_md(); - require_oids(); - require_pbkdf2(); - require_pem(); - require_random(); - require_rc2(); - require_rsa(); - require_util(); - if (typeof BigInteger2 === "undefined") { - BigInteger2 = forge2.jsbn.BigInteger; - } - var BigInteger2; - var asn1 = forge2.asn1; - var pki = forge2.pki = forge2.pki || {}; - module.exports = pki.pbe = forge2.pbe = forge2.pbe || {}; - var oids = pki.oids; - var encryptedPrivateKeyValidator = { - name: "EncryptedPrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EncryptedPrivateKeyInfo.encryptionAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "encryptionOid" - }, { - name: "AlgorithmIdentifier.parameters", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "encryptionParams" - }] - }, { - // encryptedData - name: "EncryptedPrivateKeyInfo.encryptedData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "encryptedData" - }] - }; - var PBES2AlgorithmsValidator = { - name: "PBES2Algorithms", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "PBES2Algorithms.keyDerivationFunc", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "PBES2Algorithms.keyDerivationFunc.oid", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "kdfOid" - }, { - name: "PBES2Algorithms.params", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "PBES2Algorithms.params.salt", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "kdfSalt" - }, { - name: "PBES2Algorithms.params.iterationCount", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "kdfIterationCount" - }, { - name: "PBES2Algorithms.params.keyLength", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - optional: true, - capture: "keyLength" - }, { - // prf - name: "PBES2Algorithms.params.prf", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: "PBES2Algorithms.params.prf.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "prfOid" - }] - }] - }] - }, { - name: "PBES2Algorithms.encryptionScheme", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "PBES2Algorithms.encryptionScheme.oid", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "encOid" - }, { - name: "PBES2Algorithms.encryptionScheme.iv", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "encIv" - }] - }] - }; - var pkcs12PbeParamsValidator = { - name: "pkcs-12PbeParams", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "pkcs-12PbeParams.salt", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "salt" - }, { - name: "pkcs-12PbeParams.iterations", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "iterations" - }] - }; - pki.encryptPrivateKeyInfo = function(obj, password, options) { - options = options || {}; - options.saltSize = options.saltSize || 8; - options.count = options.count || 2048; - options.algorithm = options.algorithm || "aes128"; - options.prfAlgorithm = options.prfAlgorithm || "sha1"; - var salt = forge2.random.getBytesSync(options.saltSize); - var count = options.count; - var countBytes = asn1.integerToDer(count); - var dkLen; - var encryptionAlgorithm; - var encryptedData; - if (options.algorithm.indexOf("aes") === 0 || options.algorithm === "des") { - var ivLen, encOid, cipherFn; - switch (options.algorithm) { - case "aes128": - dkLen = 16; - ivLen = 16; - encOid = oids["aes128-CBC"]; - cipherFn = forge2.aes.createEncryptionCipher; - break; - case "aes192": - dkLen = 24; - ivLen = 16; - encOid = oids["aes192-CBC"]; - cipherFn = forge2.aes.createEncryptionCipher; - break; - case "aes256": - dkLen = 32; - ivLen = 16; - encOid = oids["aes256-CBC"]; - cipherFn = forge2.aes.createEncryptionCipher; - break; - case "des": - dkLen = 8; - ivLen = 8; - encOid = oids["desCBC"]; - cipherFn = forge2.des.createEncryptionCipher; - break; - default: - var error = new Error("Cannot encrypt private key. Unknown encryption algorithm."); - error.algorithm = options.algorithm; - throw error; - } - var prfAlgorithm = "hmacWith" + options.prfAlgorithm.toUpperCase(); - var md = prfAlgorithmToMessageDigest(prfAlgorithm); - var dk = forge2.pkcs5.pbkdf2(password, salt, count, dkLen, md); - var iv = forge2.random.getBytesSync(ivLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(asn1.toDer(obj)); - cipher.finish(); - encryptedData = cipher.output.getBytes(); - var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm); - encryptionAlgorithm = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oids["pkcs5PBES2"]).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // keyDerivationFunc - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oids["pkcs5PBKDF2"]).getBytes() - ), - // PBKDF2-params - params - ]), - // encryptionScheme - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(encOid).getBytes() - ), - // iv - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - iv - ) - ]) - ]) - ] - ); - } else if (options.algorithm === "3des") { - dkLen = 24; - var saltBytes = new forge2.util.ByteBuffer(salt); - var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen); - var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen); - var cipher = forge2.des.createEncryptionCipher(dk); - cipher.start(iv); - cipher.update(asn1.toDer(obj)); - cipher.finish(); - encryptedData = cipher.output.getBytes(); - encryptionAlgorithm = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes() - ), - // pkcs-12PbeParams - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // salt - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), - // iteration count - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - countBytes.getBytes() - ) - ]) - ] - ); - } else { - var error = new Error("Cannot encrypt private key. Unknown encryption algorithm."); - error.algorithm = options.algorithm; - throw error; - } - var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // encryptionAlgorithm - encryptionAlgorithm, - // encryptedData - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - encryptedData - ) - ]); - return rval; - }; - pki.decryptPrivateKeyInfo = function(obj, password) { - var rval = null; - var capture = {}; - var errors = []; - if (!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) { - var error = new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); - error.errors = errors; - throw error; - } - var oid = asn1.derToOid(capture.encryptionOid); - var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password); - var encrypted = forge2.util.createBuffer(capture.encryptedData); - cipher.update(encrypted); - if (cipher.finish()) { - rval = asn1.fromDer(cipher.output); - } - return rval; - }; - pki.encryptedPrivateKeyToPem = function(epki, maxline) { - var msg = { - type: "ENCRYPTED PRIVATE KEY", - body: asn1.toDer(epki).getBytes() - }; - return forge2.pem.encode(msg, { maxline }); - }; - pki.encryptedPrivateKeyFromPem = function(pem) { - var msg = forge2.pem.decode(pem)[0]; - if (msg.type !== "ENCRYPTED PRIVATE KEY") { - var error = new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".'); - error.headerType = msg.type; - throw error; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted."); - } - return asn1.fromDer(msg.body); - }; - pki.encryptRsaPrivateKey = function(rsaKey, password, options) { - options = options || {}; - if (!options.legacy) { - var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey)); - rval = pki.encryptPrivateKeyInfo(rval, password, options); - return pki.encryptedPrivateKeyToPem(rval); - } - var algorithm; - var iv; - var dkLen; - var cipherFn; - switch (options.algorithm) { - case "aes128": - algorithm = "AES-128-CBC"; - dkLen = 16; - iv = forge2.random.getBytesSync(16); - cipherFn = forge2.aes.createEncryptionCipher; - break; - case "aes192": - algorithm = "AES-192-CBC"; - dkLen = 24; - iv = forge2.random.getBytesSync(16); - cipherFn = forge2.aes.createEncryptionCipher; - break; - case "aes256": - algorithm = "AES-256-CBC"; - dkLen = 32; - iv = forge2.random.getBytesSync(16); - cipherFn = forge2.aes.createEncryptionCipher; - break; - case "3des": - algorithm = "DES-EDE3-CBC"; - dkLen = 24; - iv = forge2.random.getBytesSync(8); - cipherFn = forge2.des.createEncryptionCipher; - break; - case "des": - algorithm = "DES-CBC"; - dkLen = 8; - iv = forge2.random.getBytesSync(8); - cipherFn = forge2.des.createEncryptionCipher; - break; - default: - var error = new Error('Could not encrypt RSA private key; unsupported encryption algorithm "' + options.algorithm + '".'); - error.algorithm = options.algorithm; - throw error; - } - var dk = forge2.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey))); - cipher.finish(); - var msg = { - type: "RSA PRIVATE KEY", - procType: { - version: "4", - type: "ENCRYPTED" - }, - dekInfo: { - algorithm, - parameters: forge2.util.bytesToHex(iv).toUpperCase() - }, - body: cipher.output.getBytes() - }; - return forge2.pem.encode(msg); - }; - pki.decryptRsaPrivateKey = function(pem, password) { - var rval = null; - var msg = forge2.pem.decode(pem)[0]; - if (msg.type !== "ENCRYPTED PRIVATE KEY" && msg.type !== "PRIVATE KEY" && msg.type !== "RSA PRIVATE KEY") { - var error = new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".'); - error.headerType = error; - throw error; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - var dkLen; - var cipherFn; - switch (msg.dekInfo.algorithm) { - case "DES-CBC": - dkLen = 8; - cipherFn = forge2.des.createDecryptionCipher; - break; - case "DES-EDE3-CBC": - dkLen = 24; - cipherFn = forge2.des.createDecryptionCipher; - break; - case "AES-128-CBC": - dkLen = 16; - cipherFn = forge2.aes.createDecryptionCipher; - break; - case "AES-192-CBC": - dkLen = 24; - cipherFn = forge2.aes.createDecryptionCipher; - break; - case "AES-256-CBC": - dkLen = 32; - cipherFn = forge2.aes.createDecryptionCipher; - break; - case "RC2-40-CBC": - dkLen = 5; - cipherFn = function(key) { - return forge2.rc2.createDecryptionCipher(key, 40); - }; - break; - case "RC2-64-CBC": - dkLen = 8; - cipherFn = function(key) { - return forge2.rc2.createDecryptionCipher(key, 64); - }; - break; - case "RC2-128-CBC": - dkLen = 16; - cipherFn = function(key) { - return forge2.rc2.createDecryptionCipher(key, 128); - }; - break; - default: - var error = new Error('Could not decrypt private key; unsupported encryption algorithm "' + msg.dekInfo.algorithm + '".'); - error.algorithm = msg.dekInfo.algorithm; - throw error; - } - var iv = forge2.util.hexToBytes(msg.dekInfo.parameters); - var dk = forge2.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); - var cipher = cipherFn(dk); - cipher.start(iv); - cipher.update(forge2.util.createBuffer(msg.body)); - if (cipher.finish()) { - rval = cipher.output.getBytes(); - } else { - return rval; - } - } else { - rval = msg.body; - } - if (msg.type === "ENCRYPTED PRIVATE KEY") { - rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password); - } else { - rval = asn1.fromDer(rval); - } - if (rval !== null) { - rval = pki.privateKeyFromAsn1(rval); - } - return rval; - }; - pki.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) { - var j, l; - if (typeof md === "undefined" || md === null) { - if (!("sha1" in forge2.md)) { - throw new Error('"sha1" hash algorithm unavailable.'); - } - md = forge2.md.sha1.create(); - } - var u = md.digestLength; - var v = md.blockLength; - var result = new forge2.util.ByteBuffer(); - var passBuf = new forge2.util.ByteBuffer(); - if (password !== null && password !== void 0) { - for (l = 0; l < password.length; l++) { - passBuf.putInt16(password.charCodeAt(l)); - } - passBuf.putInt16(0); - } - var p = passBuf.length(); - var s = salt.length(); - var D = new forge2.util.ByteBuffer(); - D.fillWithByte(id, v); - var Slen = v * Math.ceil(s / v); - var S = new forge2.util.ByteBuffer(); - for (l = 0; l < Slen; l++) { - S.putByte(salt.at(l % s)); - } - var Plen = v * Math.ceil(p / v); - var P = new forge2.util.ByteBuffer(); - for (l = 0; l < Plen; l++) { - P.putByte(passBuf.at(l % p)); - } - var I = S; - I.putBuffer(P); - var c = Math.ceil(n / u); - for (var i = 1; i <= c; i++) { - var buf = new forge2.util.ByteBuffer(); - buf.putBytes(D.bytes()); - buf.putBytes(I.bytes()); - for (var round = 0; round < iter; round++) { - md.start(); - md.update(buf.getBytes()); - buf = md.digest(); - } - var B = new forge2.util.ByteBuffer(); - for (l = 0; l < v; l++) { - B.putByte(buf.at(l % u)); - } - var k = Math.ceil(s / v) + Math.ceil(p / v); - var Inew = new forge2.util.ByteBuffer(); - for (j = 0; j < k; j++) { - var chunk = new forge2.util.ByteBuffer(I.getBytes(v)); - var x = 511; - for (l = B.length() - 1; l >= 0; l--) { - x = x >> 8; - x += B.at(l) + chunk.at(l); - chunk.setAt(l, x & 255); - } - Inew.putBuffer(chunk); - } - I = Inew; - result.putBuffer(buf); - } - result.truncate(result.length() - n); - return result; - }; - pki.pbe.getCipher = function(oid, params, password) { - switch (oid) { - case pki.oids["pkcs5PBES2"]: - return pki.pbe.getCipherForPBES2(oid, params, password); - case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]: - case pki.oids["pbewithSHAAnd40BitRC2-CBC"]: - return pki.pbe.getCipherForPKCS12PBE(oid, params, password); - default: - var error = new Error("Cannot read encrypted PBE data block. Unsupported OID."); - error.oid = oid; - error.supportedOids = [ - "pkcs5PBES2", - "pbeWithSHAAnd3-KeyTripleDES-CBC", - "pbewithSHAAnd40BitRC2-CBC" - ]; - throw error; - } - }; - pki.pbe.getCipherForPBES2 = function(oid, params, password) { - var capture = {}; - var errors = []; - if (!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) { - var error = new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); - error.errors = errors; - throw error; - } - oid = asn1.derToOid(capture.kdfOid); - if (oid !== pki.oids["pkcs5PBKDF2"]) { - var error = new Error("Cannot read encrypted private key. Unsupported key derivation function OID."); - error.oid = oid; - error.supportedOids = ["pkcs5PBKDF2"]; - throw error; - } - oid = asn1.derToOid(capture.encOid); - if (oid !== pki.oids["aes128-CBC"] && oid !== pki.oids["aes192-CBC"] && oid !== pki.oids["aes256-CBC"] && oid !== pki.oids["des-EDE3-CBC"] && oid !== pki.oids["desCBC"]) { - var error = new Error("Cannot read encrypted private key. Unsupported encryption scheme OID."); - error.oid = oid; - error.supportedOids = [ - "aes128-CBC", - "aes192-CBC", - "aes256-CBC", - "des-EDE3-CBC", - "desCBC" - ]; - throw error; - } - var salt = capture.kdfSalt; - var count = forge2.util.createBuffer(capture.kdfIterationCount); - count = count.getInt(count.length() << 3); - var dkLen; - var cipherFn; - switch (pki.oids[oid]) { - case "aes128-CBC": - dkLen = 16; - cipherFn = forge2.aes.createDecryptionCipher; - break; - case "aes192-CBC": - dkLen = 24; - cipherFn = forge2.aes.createDecryptionCipher; - break; - case "aes256-CBC": - dkLen = 32; - cipherFn = forge2.aes.createDecryptionCipher; - break; - case "des-EDE3-CBC": - dkLen = 24; - cipherFn = forge2.des.createDecryptionCipher; - break; - case "desCBC": - dkLen = 8; - cipherFn = forge2.des.createDecryptionCipher; - break; - } - var md = prfOidToMessageDigest(capture.prfOid); - var dk = forge2.pkcs5.pbkdf2(password, salt, count, dkLen, md); - var iv = capture.encIv; - var cipher = cipherFn(dk); - cipher.start(iv); - return cipher; - }; - pki.pbe.getCipherForPKCS12PBE = function(oid, params, password) { - var capture = {}; - var errors = []; - if (!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) { - var error = new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo."); - error.errors = errors; - throw error; - } - var salt = forge2.util.createBuffer(capture.salt); - var count = forge2.util.createBuffer(capture.iterations); - count = count.getInt(count.length() << 3); - var dkLen, dIvLen, cipherFn; - switch (oid) { - case pki.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]: - dkLen = 24; - dIvLen = 8; - cipherFn = forge2.des.startDecrypting; - break; - case pki.oids["pbewithSHAAnd40BitRC2-CBC"]: - dkLen = 5; - dIvLen = 8; - cipherFn = function(key2, iv2) { - var cipher = forge2.rc2.createDecryptionCipher(key2, 40); - cipher.start(iv2, null); - return cipher; - }; - break; - default: - var error = new Error("Cannot read PKCS #12 PBE data block. Unsupported OID."); - error.oid = oid; - throw error; - } - var md = prfOidToMessageDigest(capture.prfOid); - var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md); - md.start(); - var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md); - return cipherFn(key, iv); - }; - pki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) { - if (typeof md === "undefined" || md === null) { - if (!("md5" in forge2.md)) { - throw new Error('"md5" hash algorithm unavailable.'); - } - md = forge2.md.md5.create(); - } - if (salt === null) { - salt = ""; - } - var digests = [hash(md, password + salt)]; - for (var length = 16, i = 1; length < dkLen; ++i, length += 16) { - digests.push(hash(md, digests[i - 1] + password + salt)); - } - return digests.join("").substr(0, dkLen); - }; - function hash(md, bytes) { - return md.start().update(bytes).digest().getBytes(); - } - function prfOidToMessageDigest(prfOid) { - var prfAlgorithm; - if (!prfOid) { - prfAlgorithm = "hmacWithSHA1"; - } else { - prfAlgorithm = pki.oids[asn1.derToOid(prfOid)]; - if (!prfAlgorithm) { - var error = new Error("Unsupported PRF OID."); - error.oid = prfOid; - error.supported = [ - "hmacWithSHA1", - "hmacWithSHA224", - "hmacWithSHA256", - "hmacWithSHA384", - "hmacWithSHA512" - ]; - throw error; - } - } - return prfAlgorithmToMessageDigest(prfAlgorithm); - } - function prfAlgorithmToMessageDigest(prfAlgorithm) { - var factory = forge2.md; - switch (prfAlgorithm) { - case "hmacWithSHA224": - factory = forge2.md.sha512; - case "hmacWithSHA1": - case "hmacWithSHA256": - case "hmacWithSHA384": - case "hmacWithSHA512": - prfAlgorithm = prfAlgorithm.substr(8).toLowerCase(); - break; - default: - var error = new Error("Unsupported PRF algorithm."); - error.algorithm = prfAlgorithm; - error.supported = [ - "hmacWithSHA1", - "hmacWithSHA224", - "hmacWithSHA256", - "hmacWithSHA384", - "hmacWithSHA512" - ]; - throw error; - } - if (!factory || !(prfAlgorithm in factory)) { - throw new Error("Unknown hash algorithm: " + prfAlgorithm); - } - return factory[prfAlgorithm].create(); - } - function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) { - var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // salt - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - salt - ), - // iteration count - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - countBytes.getBytes() - ) - ]); - if (prfAlgorithm !== "hmacWithSHA1") { - params.value.push( - // key length - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - forge2.util.hexToBytes(dkLen.toString(16)) - ), - // AlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ); - } - return params; - } - } -}); - -// node_modules/node-forge/lib/pkcs7asn1.js -var require_pkcs7asn1 = __commonJS({ - "node_modules/node-forge/lib/pkcs7asn1.js"(exports, module) { - var forge2 = require_forge(); - require_asn1(); - require_util(); - var asn1 = forge2.asn1; - var p7v = module.exports = forge2.pkcs7asn1 = forge2.pkcs7asn1 || {}; - forge2.pkcs7 = forge2.pkcs7 || {}; - forge2.pkcs7.asn1 = p7v; - var contentInfoValidator = { - name: "ContentInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "ContentInfo.ContentType", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "contentType" - }, { - name: "ContentInfo.content", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - captureAsn1: "content" - }] - }; - p7v.contentInfoValidator = contentInfoValidator; - var encryptedContentInfoValidator = { - name: "EncryptedContentInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EncryptedContentInfo.contentType", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "contentType" - }, { - name: "EncryptedContentInfo.contentEncryptionAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EncryptedContentInfo.contentEncryptionAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "encAlgorithm" - }, { - name: "EncryptedContentInfo.contentEncryptionAlgorithm.parameter", - tagClass: asn1.Class.UNIVERSAL, - captureAsn1: "encParameter" - }] - }, { - name: "EncryptedContentInfo.encryptedContent", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - /* The PKCS#7 structure output by OpenSSL somewhat differs from what - * other implementations do generate. - * - * OpenSSL generates a structure like this: - * SEQUENCE { - * ... - * [0] - * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 - * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 - * ... - * } - * - * Whereas other implementations (and this PKCS#7 module) generate: - * SEQUENCE { - * ... - * [0] { - * OCTET STRING - * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 - * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 - * ... - * } - * } - * - * In order to support both, we just capture the context specific - * field here. The OCTET STRING bit is removed below. - */ - capture: "encryptedContent", - captureAsn1: "encryptedContentAsn1" - }] - }; - p7v.envelopedDataValidator = { - name: "EnvelopedData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EnvelopedData.Version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }, { - name: "EnvelopedData.RecipientInfos", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - captureAsn1: "recipientInfos" - }].concat(encryptedContentInfoValidator) - }; - p7v.encryptedDataValidator = { - name: "EncryptedData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "EncryptedData.Version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }].concat(encryptedContentInfoValidator) - }; - var signerValidator = { - name: "SignerInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "SignerInfo.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false - }, { - name: "SignerInfo.issuerAndSerialNumber", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "SignerInfo.issuerAndSerialNumber.issuer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "issuer" - }, { - name: "SignerInfo.issuerAndSerialNumber.serialNumber", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "serial" - }] - }, { - name: "SignerInfo.digestAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "SignerInfo.digestAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "digestAlgorithm" - }, { - name: "SignerInfo.digestAlgorithm.parameter", - tagClass: asn1.Class.UNIVERSAL, - constructed: false, - captureAsn1: "digestParameter", - optional: true - }] - }, { - name: "SignerInfo.authenticatedAttributes", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - capture: "authenticatedAttributes" - }, { - name: "SignerInfo.digestEncryptionAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - capture: "signatureAlgorithm" - }, { - name: "SignerInfo.encryptedDigest", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "signature" - }, { - name: "SignerInfo.unauthenticatedAttributes", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - optional: true, - capture: "unauthenticatedAttributes" - }] - }; - p7v.signedDataValidator = { - name: "SignedData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [ - { - name: "SignedData.Version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }, - { - name: "SignedData.DigestAlgorithms", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - captureAsn1: "digestAlgorithms" - }, - contentInfoValidator, - { - name: "SignedData.Certificates", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - optional: true, - captureAsn1: "certificates" - }, - { - name: "SignedData.CertificateRevocationLists", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - optional: true, - captureAsn1: "crls" - }, - { - name: "SignedData.SignerInfos", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - capture: "signerInfos", - optional: true, - value: [signerValidator] - } - ] - }; - p7v.recipientInfoValidator = { - name: "RecipientInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "RecipientInfo.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }, { - name: "RecipientInfo.issuerAndSerial", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "RecipientInfo.issuerAndSerial.issuer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "issuer" - }, { - name: "RecipientInfo.issuerAndSerial.serialNumber", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "serial" - }] - }, { - name: "RecipientInfo.keyEncryptionAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "RecipientInfo.keyEncryptionAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "encAlgorithm" - }, { - name: "RecipientInfo.keyEncryptionAlgorithm.parameter", - tagClass: asn1.Class.UNIVERSAL, - constructed: false, - captureAsn1: "encParameter", - optional: true - }] - }, { - name: "RecipientInfo.encryptedKey", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "encKey" - }] - }; - } -}); - -// node_modules/node-forge/lib/mgf1.js -var require_mgf1 = __commonJS({ - "node_modules/node-forge/lib/mgf1.js"(exports, module) { - var forge2 = require_forge(); - require_util(); - forge2.mgf = forge2.mgf || {}; - var mgf1 = module.exports = forge2.mgf.mgf1 = forge2.mgf1 = forge2.mgf1 || {}; - mgf1.create = function(md) { - var mgf = { - /** - * Generate mask of specified length. - * - * @param {String} seed The seed for mask generation. - * @param maskLen Number of bytes to generate. - * @return {String} The generated mask. - */ - generate: function(seed, maskLen) { - var t = new forge2.util.ByteBuffer(); - var len = Math.ceil(maskLen / md.digestLength); - for (var i = 0; i < len; i++) { - var c = new forge2.util.ByteBuffer(); - c.putInt32(i); - md.start(); - md.update(seed + c.getBytes()); - t.putBuffer(md.digest()); - } - t.truncate(t.length() - maskLen); - return t.getBytes(); - } - }; - return mgf; - }; - } -}); - -// node_modules/node-forge/lib/mgf.js -var require_mgf = __commonJS({ - "node_modules/node-forge/lib/mgf.js"(exports, module) { - var forge2 = require_forge(); - require_mgf1(); - module.exports = forge2.mgf = forge2.mgf || {}; - forge2.mgf.mgf1 = forge2.mgf1; - } -}); - -// node_modules/node-forge/lib/pss.js -var require_pss = __commonJS({ - "node_modules/node-forge/lib/pss.js"(exports, module) { - var forge2 = require_forge(); - require_random(); - require_util(); - var pss = module.exports = forge2.pss = forge2.pss || {}; - pss.create = function(options) { - if (arguments.length === 3) { - options = { - md: arguments[0], - mgf: arguments[1], - saltLength: arguments[2] - }; - } - var hash = options.md; - var mgf = options.mgf; - var hLen = hash.digestLength; - var salt_ = options.salt || null; - if (typeof salt_ === "string") { - salt_ = forge2.util.createBuffer(salt_); - } - var sLen; - if ("saltLength" in options) { - sLen = options.saltLength; - } else if (salt_ !== null) { - sLen = salt_.length(); - } else { - throw new Error("Salt length not specified or specific salt not given."); - } - if (salt_ !== null && salt_.length() !== sLen) { - throw new Error("Given salt length does not match length of given salt."); - } - var prng = options.prng || forge2.random; - var pssobj = {}; - pssobj.encode = function(md, modBits) { - var i; - var emBits = modBits - 1; - var emLen = Math.ceil(emBits / 8); - var mHash = md.digest().getBytes(); - if (emLen < hLen + sLen + 2) { - throw new Error("Message is too long to encrypt."); - } - var salt; - if (salt_ === null) { - salt = prng.getBytesSync(sLen); - } else { - salt = salt_.bytes(); - } - var m_ = new forge2.util.ByteBuffer(); - m_.fillWithByte(0, 8); - m_.putBytes(mHash); - m_.putBytes(salt); - hash.start(); - hash.update(m_.getBytes()); - var h = hash.digest().getBytes(); - var ps = new forge2.util.ByteBuffer(); - ps.fillWithByte(0, emLen - sLen - hLen - 2); - ps.putByte(1); - ps.putBytes(salt); - var db2 = ps.getBytes(); - var maskLen = emLen - hLen - 1; - var dbMask = mgf.generate(h, maskLen); - var maskedDB = ""; - for (i = 0; i < maskLen; i++) { - maskedDB += String.fromCharCode(db2.charCodeAt(i) ^ dbMask.charCodeAt(i)); - } - var mask = 65280 >> 8 * emLen - emBits & 255; - maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + maskedDB.substr(1); - return maskedDB + h + String.fromCharCode(188); - }; - pssobj.verify = function(mHash, em, modBits) { - var i; - var emBits = modBits - 1; - var emLen = Math.ceil(emBits / 8); - em = em.substr(-emLen); - if (emLen < hLen + sLen + 2) { - throw new Error("Inconsistent parameters to PSS signature verification."); - } - if (em.charCodeAt(emLen - 1) !== 188) { - throw new Error("Encoded message does not end in 0xBC."); - } - var maskLen = emLen - hLen - 1; - var maskedDB = em.substr(0, maskLen); - var h = em.substr(maskLen, hLen); - var mask = 65280 >> 8 * emLen - emBits & 255; - if ((maskedDB.charCodeAt(0) & mask) !== 0) { - throw new Error("Bits beyond keysize not zero as expected."); - } - var dbMask = mgf.generate(h, maskLen); - var db2 = ""; - for (i = 0; i < maskLen; i++) { - db2 += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i)); - } - db2 = String.fromCharCode(db2.charCodeAt(0) & ~mask) + db2.substr(1); - var checkLen = emLen - hLen - sLen - 2; - for (i = 0; i < checkLen; i++) { - if (db2.charCodeAt(i) !== 0) { - throw new Error("Leftmost octets not zero as expected"); - } - } - if (db2.charCodeAt(checkLen) !== 1) { - throw new Error("Inconsistent PSS signature, 0x01 marker not found"); - } - var salt = db2.substr(-sLen); - var m_ = new forge2.util.ByteBuffer(); - m_.fillWithByte(0, 8); - m_.putBytes(mHash); - m_.putBytes(salt); - hash.start(); - hash.update(m_.getBytes()); - var h_ = hash.digest().getBytes(); - return h === h_; - }; - return pssobj; - }; - } -}); - -// node_modules/node-forge/lib/x509.js -var require_x509 = __commonJS({ - "node_modules/node-forge/lib/x509.js"(exports, module) { - var forge2 = require_forge(); - require_aes(); - require_asn1(); - require_des(); - require_md(); - require_mgf(); - require_oids(); - require_pem(); - require_pss(); - require_rsa(); - require_util(); - var asn1 = forge2.asn1; - var pki = module.exports = forge2.pki = forge2.pki || {}; - var oids = pki.oids; - var _shortNames = {}; - _shortNames["CN"] = oids["commonName"]; - _shortNames["commonName"] = "CN"; - _shortNames["C"] = oids["countryName"]; - _shortNames["countryName"] = "C"; - _shortNames["L"] = oids["localityName"]; - _shortNames["localityName"] = "L"; - _shortNames["ST"] = oids["stateOrProvinceName"]; - _shortNames["stateOrProvinceName"] = "ST"; - _shortNames["O"] = oids["organizationName"]; - _shortNames["organizationName"] = "O"; - _shortNames["OU"] = oids["organizationalUnitName"]; - _shortNames["organizationalUnitName"] = "OU"; - _shortNames["E"] = oids["emailAddress"]; - _shortNames["emailAddress"] = "E"; - var publicKeyValidator = forge2.pki.rsa.publicKeyValidator; - var x509CertificateValidator = { - name: "Certificate", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "Certificate.TBSCertificate", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "tbsCertificate", - value: [ - { - name: "Certificate.TBSCertificate.version", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - value: [{ - name: "Certificate.TBSCertificate.version.integer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "certVersion" - }] - }, - { - name: "Certificate.TBSCertificate.serialNumber", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "certSerialNumber" - }, - { - name: "Certificate.TBSCertificate.signature", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "Certificate.TBSCertificate.signature.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "certinfoSignatureOid" - }, { - name: "Certificate.TBSCertificate.signature.parameters", - tagClass: asn1.Class.UNIVERSAL, - optional: true, - captureAsn1: "certinfoSignatureParams" - }] - }, - { - name: "Certificate.TBSCertificate.issuer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "certIssuer" - }, - { - name: "Certificate.TBSCertificate.validity", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - // Note: UTC and generalized times may both appear so the capture - // names are based on their detected order, the names used below - // are only for the common case, which validity time really means - // "notBefore" and which means "notAfter" will be determined by order - value: [{ - // notBefore (Time) (UTC time case) - name: "Certificate.TBSCertificate.validity.notBefore (utc)", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.UTCTIME, - constructed: false, - optional: true, - capture: "certValidity1UTCTime" - }, { - // notBefore (Time) (generalized time case) - name: "Certificate.TBSCertificate.validity.notBefore (generalized)", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.GENERALIZEDTIME, - constructed: false, - optional: true, - capture: "certValidity2GeneralizedTime" - }, { - // notAfter (Time) (only UTC time is supported) - name: "Certificate.TBSCertificate.validity.notAfter (utc)", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.UTCTIME, - constructed: false, - optional: true, - capture: "certValidity3UTCTime" - }, { - // notAfter (Time) (only UTC time is supported) - name: "Certificate.TBSCertificate.validity.notAfter (generalized)", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.GENERALIZEDTIME, - constructed: false, - optional: true, - capture: "certValidity4GeneralizedTime" - }] - }, - { - // Name (subject) (RDNSequence) - name: "Certificate.TBSCertificate.subject", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "certSubject" - }, - // SubjectPublicKeyInfo - publicKeyValidator, - { - // issuerUniqueID (optional) - name: "Certificate.TBSCertificate.issuerUniqueID", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - optional: true, - value: [{ - name: "Certificate.TBSCertificate.issuerUniqueID.id", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - // TODO: support arbitrary bit length ids - captureBitStringValue: "certIssuerUniqueId" - }] - }, - { - // subjectUniqueID (optional) - name: "Certificate.TBSCertificate.subjectUniqueID", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 2, - constructed: true, - optional: true, - value: [{ - name: "Certificate.TBSCertificate.subjectUniqueID.id", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - // TODO: support arbitrary bit length ids - captureBitStringValue: "certSubjectUniqueId" - }] - }, - { - // Extensions (optional) - name: "Certificate.TBSCertificate.extensions", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 3, - constructed: true, - captureAsn1: "certExtensions", - optional: true - } - ] - }, { - // AlgorithmIdentifier (signature algorithm) - name: "Certificate.signatureAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // algorithm - name: "Certificate.signatureAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "certSignatureOid" - }, { - name: "Certificate.TBSCertificate.signature.parameters", - tagClass: asn1.Class.UNIVERSAL, - optional: true, - captureAsn1: "certSignatureParams" - }] - }, { - // SignatureValue - name: "Certificate.signatureValue", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - captureBitStringValue: "certSignature" - }] - }; - var rsassaPssParameterValidator = { - name: "rsapss", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "rsapss.hashAlgorithm", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - value: [{ - name: "rsapss.hashAlgorithm.AlgorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: "rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "hashOid" - /* parameter block omitted, for SHA1 NULL anyhow. */ - }] - }] - }, { - name: "rsapss.maskGenAlgorithm", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 1, - constructed: true, - value: [{ - name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.SEQUENCE, - constructed: true, - optional: true, - value: [{ - name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "maskGenOid" - }, { - name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.params", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "maskGenHashOid" - /* parameter block omitted, for SHA1 NULL anyhow. */ - }] - }] - }] - }, { - name: "rsapss.saltLength", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 2, - optional: true, - value: [{ - name: "rsapss.saltLength.saltLength", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.INTEGER, - constructed: false, - capture: "saltLength" - }] - }, { - name: "rsapss.trailerField", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 3, - optional: true, - value: [{ - name: "rsapss.trailer.trailer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.INTEGER, - constructed: false, - capture: "trailer" - }] - }] - }; - var certificationRequestInfoValidator = { - name: "CertificationRequestInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "certificationRequestInfo", - value: [ - { - name: "CertificationRequestInfo.integer", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "certificationRequestInfoVersion" - }, - { - // Name (subject) (RDNSequence) - name: "CertificationRequestInfo.subject", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "certificationRequestInfoSubject" - }, - // SubjectPublicKeyInfo - publicKeyValidator, - { - name: "CertificationRequestInfo.attributes", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - type: 0, - constructed: true, - optional: true, - capture: "certificationRequestInfoAttributes", - value: [{ - name: "CertificationRequestInfo.attributes", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "CertificationRequestInfo.attributes.type", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false - }, { - name: "CertificationRequestInfo.attributes.value", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true - }] - }] - } - ] - }; - var certificationRequestValidator = { - name: "CertificationRequest", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "csr", - value: [ - certificationRequestInfoValidator, - { - // AlgorithmIdentifier (signature algorithm) - name: "CertificationRequest.signatureAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // algorithm - name: "CertificationRequest.signatureAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "csrSignatureOid" - }, { - name: "CertificationRequest.signatureAlgorithm.parameters", - tagClass: asn1.Class.UNIVERSAL, - optional: true, - captureAsn1: "csrSignatureParams" - }] - }, - { - // signature - name: "CertificationRequest.signature", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - captureBitStringValue: "csrSignature" - } - ] - }; - pki.RDNAttributesAsArray = function(rdn, md) { - var rval = []; - var set, attr, obj; - for (var si = 0; si < rdn.value.length; ++si) { - set = rdn.value[si]; - for (var i = 0; i < set.value.length; ++i) { - obj = {}; - attr = set.value[i]; - obj.type = asn1.derToOid(attr.value[0].value); - obj.value = attr.value[1].value; - obj.valueTagClass = attr.value[1].type; - if (obj.type in oids) { - obj.name = oids[obj.type]; - if (obj.name in _shortNames) { - obj.shortName = _shortNames[obj.name]; - } - } - if (md) { - md.update(obj.type); - md.update(obj.value); - } - rval.push(obj); - } - } - return rval; - }; - pki.CRIAttributesAsArray = function(attributes) { - var rval = []; - for (var si = 0; si < attributes.length; ++si) { - var seq = attributes[si]; - var type = asn1.derToOid(seq.value[0].value); - var values = seq.value[1].value; - for (var vi = 0; vi < values.length; ++vi) { - var obj = {}; - obj.type = type; - obj.value = values[vi].value; - obj.valueTagClass = values[vi].type; - if (obj.type in oids) { - obj.name = oids[obj.type]; - if (obj.name in _shortNames) { - obj.shortName = _shortNames[obj.name]; - } - } - if (obj.type === oids.extensionRequest) { - obj.extensions = []; - for (var ei = 0; ei < obj.value.length; ++ei) { - obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei])); - } - } - rval.push(obj); - } - } - return rval; - }; - function _getAttribute(obj, options) { - if (typeof options === "string") { - options = { shortName: options }; - } - var rval = null; - var attr; - for (var i = 0; rval === null && i < obj.attributes.length; ++i) { - attr = obj.attributes[i]; - if (options.type && options.type === attr.type) { - rval = attr; - } else if (options.name && options.name === attr.name) { - rval = attr; - } else if (options.shortName && options.shortName === attr.shortName) { - rval = attr; - } - } - return rval; - } - var _readSignatureParameters = function(oid, obj, fillDefaults) { - var params = {}; - if (oid !== oids["RSASSA-PSS"]) { - return params; - } - if (fillDefaults) { - params = { - hash: { - algorithmOid: oids["sha1"] - }, - mgf: { - algorithmOid: oids["mgf1"], - hash: { - algorithmOid: oids["sha1"] - } - }, - saltLength: 20 - }; - } - var capture = {}; - var errors = []; - if (!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) { - var error = new Error("Cannot read RSASSA-PSS parameter block."); - error.errors = errors; - throw error; - } - if (capture.hashOid !== void 0) { - params.hash = params.hash || {}; - params.hash.algorithmOid = asn1.derToOid(capture.hashOid); - } - if (capture.maskGenOid !== void 0) { - params.mgf = params.mgf || {}; - params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid); - params.mgf.hash = params.mgf.hash || {}; - params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid); - } - if (capture.saltLength !== void 0) { - params.saltLength = capture.saltLength.charCodeAt(0); - } - return params; - }; - var _createSignatureDigest = function(options) { - switch (oids[options.signatureOid]) { - case "sha1WithRSAEncryption": - case "sha1WithRSASignature": - return forge2.md.sha1.create(); - case "md5WithRSAEncryption": - return forge2.md.md5.create(); - case "sha256WithRSAEncryption": - return forge2.md.sha256.create(); - case "sha384WithRSAEncryption": - return forge2.md.sha384.create(); - case "sha512WithRSAEncryption": - return forge2.md.sha512.create(); - case "RSASSA-PSS": - return forge2.md.sha256.create(); - default: - var error = new Error( - "Could not compute " + options.type + " digest. Unknown signature OID." - ); - error.signatureOid = options.signatureOid; - throw error; - } - }; - var _verifySignature = function(options) { - var cert = options.certificate; - var scheme; - switch (cert.signatureOid) { - case oids.sha1WithRSAEncryption: - case oids.sha1WithRSASignature: - break; - case oids["RSASSA-PSS"]: - var hash, mgf; - hash = oids[cert.signatureParameters.mgf.hash.algorithmOid]; - if (hash === void 0 || forge2.md[hash] === void 0) { - var error = new Error("Unsupported MGF hash function."); - error.oid = cert.signatureParameters.mgf.hash.algorithmOid; - error.name = hash; - throw error; - } - mgf = oids[cert.signatureParameters.mgf.algorithmOid]; - if (mgf === void 0 || forge2.mgf[mgf] === void 0) { - var error = new Error("Unsupported MGF function."); - error.oid = cert.signatureParameters.mgf.algorithmOid; - error.name = mgf; - throw error; - } - mgf = forge2.mgf[mgf].create(forge2.md[hash].create()); - hash = oids[cert.signatureParameters.hash.algorithmOid]; - if (hash === void 0 || forge2.md[hash] === void 0) { - var error = new Error("Unsupported RSASSA-PSS hash function."); - error.oid = cert.signatureParameters.hash.algorithmOid; - error.name = hash; - throw error; - } - scheme = forge2.pss.create( - forge2.md[hash].create(), - mgf, - cert.signatureParameters.saltLength - ); - break; - } - return cert.publicKey.verify( - options.md.digest().getBytes(), - options.signature, - scheme - ); - }; - pki.certificateFromPem = function(pem, computeHash, strict) { - var msg = forge2.pem.decode(pem)[0]; - if (msg.type !== "CERTIFICATE" && msg.type !== "X509 CERTIFICATE" && msg.type !== "TRUSTED CERTIFICATE") { - var error = new Error( - 'Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".' - ); - error.headerType = msg.type; - throw error; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error( - "Could not convert certificate from PEM; PEM is encrypted." - ); - } - var obj = asn1.fromDer(msg.body, strict); - return pki.certificateFromAsn1(obj, computeHash); - }; - pki.certificateToPem = function(cert, maxline) { - var msg = { - type: "CERTIFICATE", - body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes() - }; - return forge2.pem.encode(msg, { maxline }); - }; - pki.publicKeyFromPem = function(pem) { - var msg = forge2.pem.decode(pem)[0]; - if (msg.type !== "PUBLIC KEY" && msg.type !== "RSA PUBLIC KEY") { - var error = new Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".'); - error.headerType = msg.type; - throw error; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert public key from PEM; PEM is encrypted."); - } - var obj = asn1.fromDer(msg.body); - return pki.publicKeyFromAsn1(obj); - }; - pki.publicKeyToPem = function(key, maxline) { - var msg = { - type: "PUBLIC KEY", - body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes() - }; - return forge2.pem.encode(msg, { maxline }); - }; - pki.publicKeyToRSAPublicKeyPem = function(key, maxline) { - var msg = { - type: "RSA PUBLIC KEY", - body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes() - }; - return forge2.pem.encode(msg, { maxline }); - }; - pki.getPublicKeyFingerprint = function(key, options) { - options = options || {}; - var md = options.md || forge2.md.sha1.create(); - var type = options.type || "RSAPublicKey"; - var bytes; - switch (type) { - case "RSAPublicKey": - bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes(); - break; - case "SubjectPublicKeyInfo": - bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes(); - break; - default: - throw new Error('Unknown fingerprint type "' + options.type + '".'); - } - md.start(); - md.update(bytes); - var digest = md.digest(); - if (options.encoding === "hex") { - var hex = digest.toHex(); - if (options.delimiter) { - return hex.match(/.{2}/g).join(options.delimiter); - } - return hex; - } else if (options.encoding === "binary") { - return digest.getBytes(); - } else if (options.encoding) { - throw new Error('Unknown encoding "' + options.encoding + '".'); - } - return digest; - }; - pki.certificationRequestFromPem = function(pem, computeHash, strict) { - var msg = forge2.pem.decode(pem)[0]; - if (msg.type !== "CERTIFICATE REQUEST") { - var error = new Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".'); - error.headerType = msg.type; - throw error; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert certification request from PEM; PEM is encrypted."); - } - var obj = asn1.fromDer(msg.body, strict); - return pki.certificationRequestFromAsn1(obj, computeHash); - }; - pki.certificationRequestToPem = function(csr, maxline) { - var msg = { - type: "CERTIFICATE REQUEST", - body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes() - }; - return forge2.pem.encode(msg, { maxline }); - }; - pki.createCertificate = function() { - var cert = {}; - cert.version = 2; - cert.serialNumber = "00"; - cert.signatureOid = null; - cert.signature = null; - cert.siginfo = {}; - cert.siginfo.algorithmOid = null; - cert.validity = {}; - cert.validity.notBefore = /* @__PURE__ */ new Date(); - cert.validity.notAfter = /* @__PURE__ */ new Date(); - cert.issuer = {}; - cert.issuer.getField = function(sn) { - return _getAttribute(cert.issuer, sn); - }; - cert.issuer.addField = function(attr) { - _fillMissingFields([attr]); - cert.issuer.attributes.push(attr); - }; - cert.issuer.attributes = []; - cert.issuer.hash = null; - cert.subject = {}; - cert.subject.getField = function(sn) { - return _getAttribute(cert.subject, sn); - }; - cert.subject.addField = function(attr) { - _fillMissingFields([attr]); - cert.subject.attributes.push(attr); - }; - cert.subject.attributes = []; - cert.subject.hash = null; - cert.extensions = []; - cert.publicKey = null; - cert.md = null; - cert.setSubject = function(attrs, uniqueId) { - _fillMissingFields(attrs); - cert.subject.attributes = attrs; - delete cert.subject.uniqueId; - if (uniqueId) { - cert.subject.uniqueId = uniqueId; - } - cert.subject.hash = null; - }; - cert.setIssuer = function(attrs, uniqueId) { - _fillMissingFields(attrs); - cert.issuer.attributes = attrs; - delete cert.issuer.uniqueId; - if (uniqueId) { - cert.issuer.uniqueId = uniqueId; - } - cert.issuer.hash = null; - }; - cert.setExtensions = function(exts) { - for (var i = 0; i < exts.length; ++i) { - _fillMissingExtensionFields(exts[i], { cert }); - } - cert.extensions = exts; - }; - cert.getExtension = function(options) { - if (typeof options === "string") { - options = { name: options }; - } - var rval = null; - var ext; - for (var i = 0; rval === null && i < cert.extensions.length; ++i) { - ext = cert.extensions[i]; - if (options.id && ext.id === options.id) { - rval = ext; - } else if (options.name && ext.name === options.name) { - rval = ext; - } - } - return rval; - }; - cert.sign = function(key, md) { - cert.md = md || forge2.md.sha1.create(); - var algorithmOid = oids[cert.md.algorithm + "WithRSAEncryption"]; - if (!algorithmOid) { - var error = new Error("Could not compute certificate digest. Unknown message digest algorithm OID."); - error.algorithm = cert.md.algorithm; - throw error; - } - cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid; - cert.tbsCertificate = pki.getTBSCertificate(cert); - var bytes = asn1.toDer(cert.tbsCertificate); - cert.md.update(bytes.getBytes()); - cert.signature = key.sign(cert.md); - }; - cert.verify = function(child) { - var rval = false; - if (!cert.issued(child)) { - var issuer = child.issuer; - var subject = cert.subject; - var error = new Error( - "The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject." - ); - error.expectedIssuer = subject.attributes; - error.actualIssuer = issuer.attributes; - throw error; - } - var md = child.md; - if (md === null) { - md = _createSignatureDigest({ - signatureOid: child.signatureOid, - type: "certificate" - }); - var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child); - var bytes = asn1.toDer(tbsCertificate); - md.update(bytes.getBytes()); - } - if (md !== null) { - rval = _verifySignature({ - certificate: cert, - md, - signature: child.signature - }); - } - return rval; - }; - cert.isIssuer = function(parent) { - var rval = false; - var i = cert.issuer; - var s = parent.subject; - if (i.hash && s.hash) { - rval = i.hash === s.hash; - } else if (i.attributes.length === s.attributes.length) { - rval = true; - var iattr, sattr; - for (var n = 0; rval && n < i.attributes.length; ++n) { - iattr = i.attributes[n]; - sattr = s.attributes[n]; - if (iattr.type !== sattr.type || iattr.value !== sattr.value) { - rval = false; - } - } - } - return rval; - }; - cert.issued = function(child) { - return child.isIssuer(cert); - }; - cert.generateSubjectKeyIdentifier = function() { - return pki.getPublicKeyFingerprint(cert.publicKey, { type: "RSAPublicKey" }); - }; - cert.verifySubjectKeyIdentifier = function() { - var oid = oids["subjectKeyIdentifier"]; - for (var i = 0; i < cert.extensions.length; ++i) { - var ext = cert.extensions[i]; - if (ext.id === oid) { - var ski = cert.generateSubjectKeyIdentifier().getBytes(); - return forge2.util.hexToBytes(ext.subjectKeyIdentifier) === ski; - } - } - return false; - }; - return cert; - }; - pki.certificateFromAsn1 = function(obj, computeHash) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, x509CertificateValidator, capture, errors)) { - var error = new Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate."); - error.errors = errors; - throw error; - } - var oid = asn1.derToOid(capture.publicKeyOid); - if (oid !== pki.oids.rsaEncryption) { - throw new Error("Cannot read public key. OID is not RSA."); - } - var cert = pki.createCertificate(); - cert.version = capture.certVersion ? capture.certVersion.charCodeAt(0) : 0; - var serial = forge2.util.createBuffer(capture.certSerialNumber); - cert.serialNumber = serial.toHex(); - cert.signatureOid = forge2.asn1.derToOid(capture.certSignatureOid); - cert.signatureParameters = _readSignatureParameters( - cert.signatureOid, - capture.certSignatureParams, - true - ); - cert.siginfo.algorithmOid = forge2.asn1.derToOid(capture.certinfoSignatureOid); - cert.siginfo.parameters = _readSignatureParameters( - cert.siginfo.algorithmOid, - capture.certinfoSignatureParams, - false - ); - cert.signature = capture.certSignature; - var validity = []; - if (capture.certValidity1UTCTime !== void 0) { - validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime)); - } - if (capture.certValidity2GeneralizedTime !== void 0) { - validity.push(asn1.generalizedTimeToDate( - capture.certValidity2GeneralizedTime - )); - } - if (capture.certValidity3UTCTime !== void 0) { - validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime)); - } - if (capture.certValidity4GeneralizedTime !== void 0) { - validity.push(asn1.generalizedTimeToDate( - capture.certValidity4GeneralizedTime - )); - } - if (validity.length > 2) { - throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate."); - } - if (validity.length < 2) { - throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime."); - } - cert.validity.notBefore = validity[0]; - cert.validity.notAfter = validity[1]; - cert.tbsCertificate = capture.tbsCertificate; - if (computeHash) { - cert.md = _createSignatureDigest({ - signatureOid: cert.signatureOid, - type: "certificate" - }); - var bytes = asn1.toDer(cert.tbsCertificate); - cert.md.update(bytes.getBytes()); - } - var imd = forge2.md.sha1.create(); - var ibytes = asn1.toDer(capture.certIssuer); - imd.update(ibytes.getBytes()); - cert.issuer.getField = function(sn) { - return _getAttribute(cert.issuer, sn); - }; - cert.issuer.addField = function(attr) { - _fillMissingFields([attr]); - cert.issuer.attributes.push(attr); - }; - cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer); - if (capture.certIssuerUniqueId) { - cert.issuer.uniqueId = capture.certIssuerUniqueId; - } - cert.issuer.hash = imd.digest().toHex(); - var smd = forge2.md.sha1.create(); - var sbytes = asn1.toDer(capture.certSubject); - smd.update(sbytes.getBytes()); - cert.subject.getField = function(sn) { - return _getAttribute(cert.subject, sn); - }; - cert.subject.addField = function(attr) { - _fillMissingFields([attr]); - cert.subject.attributes.push(attr); - }; - cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject); - if (capture.certSubjectUniqueId) { - cert.subject.uniqueId = capture.certSubjectUniqueId; - } - cert.subject.hash = smd.digest().toHex(); - if (capture.certExtensions) { - cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions); - } else { - cert.extensions = []; - } - cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo); - return cert; - }; - pki.certificateExtensionsFromAsn1 = function(exts) { - var rval = []; - for (var i = 0; i < exts.value.length; ++i) { - var extseq = exts.value[i]; - for (var ei = 0; ei < extseq.value.length; ++ei) { - rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei])); - } - } - return rval; - }; - pki.certificateExtensionFromAsn1 = function(ext) { - var e = {}; - e.id = asn1.derToOid(ext.value[0].value); - e.critical = false; - if (ext.value[1].type === asn1.Type.BOOLEAN) { - e.critical = ext.value[1].value.charCodeAt(0) !== 0; - e.value = ext.value[2].value; - } else { - e.value = ext.value[1].value; - } - if (e.id in oids) { - e.name = oids[e.id]; - if (e.name === "keyUsage") { - var ev = asn1.fromDer(e.value); - var b2 = 0; - var b3 = 0; - if (ev.value.length > 1) { - b2 = ev.value.charCodeAt(1); - b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0; - } - e.digitalSignature = (b2 & 128) === 128; - e.nonRepudiation = (b2 & 64) === 64; - e.keyEncipherment = (b2 & 32) === 32; - e.dataEncipherment = (b2 & 16) === 16; - e.keyAgreement = (b2 & 8) === 8; - e.keyCertSign = (b2 & 4) === 4; - e.cRLSign = (b2 & 2) === 2; - e.encipherOnly = (b2 & 1) === 1; - e.decipherOnly = (b3 & 128) === 128; - } else if (e.name === "basicConstraints") { - var ev = asn1.fromDer(e.value); - if (ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) { - e.cA = ev.value[0].value.charCodeAt(0) !== 0; - } else { - e.cA = false; - } - var value = null; - if (ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) { - value = ev.value[0].value; - } else if (ev.value.length > 1) { - value = ev.value[1].value; - } - if (value !== null) { - e.pathLenConstraint = asn1.derToInteger(value); - } - } else if (e.name === "extKeyUsage") { - var ev = asn1.fromDer(e.value); - for (var vi = 0; vi < ev.value.length; ++vi) { - var oid = asn1.derToOid(ev.value[vi].value); - if (oid in oids) { - e[oids[oid]] = true; - } else { - e[oid] = true; - } - } - } else if (e.name === "nsCertType") { - var ev = asn1.fromDer(e.value); - var b2 = 0; - if (ev.value.length > 1) { - b2 = ev.value.charCodeAt(1); - } - e.client = (b2 & 128) === 128; - e.server = (b2 & 64) === 64; - e.email = (b2 & 32) === 32; - e.objsign = (b2 & 16) === 16; - e.reserved = (b2 & 8) === 8; - e.sslCA = (b2 & 4) === 4; - e.emailCA = (b2 & 2) === 2; - e.objCA = (b2 & 1) === 1; - } else if (e.name === "subjectAltName" || e.name === "issuerAltName") { - e.altNames = []; - var gn; - var ev = asn1.fromDer(e.value); - for (var n = 0; n < ev.value.length; ++n) { - gn = ev.value[n]; - var altName = { - type: gn.type, - value: gn.value - }; - e.altNames.push(altName); - switch (gn.type) { - case 1: - case 2: - case 6: - break; - case 7: - altName.ip = forge2.util.bytesToIP(gn.value); - break; - case 8: - altName.oid = asn1.derToOid(gn.value); - break; - default: - } - } - } else if (e.name === "subjectKeyIdentifier") { - var ev = asn1.fromDer(e.value); - e.subjectKeyIdentifier = forge2.util.bytesToHex(ev.value); - } - } - return e; - }; - pki.certificationRequestFromAsn1 = function(obj, computeHash) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, certificationRequestValidator, capture, errors)) { - var error = new Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest."); - error.errors = errors; - throw error; - } - var oid = asn1.derToOid(capture.publicKeyOid); - if (oid !== pki.oids.rsaEncryption) { - throw new Error("Cannot read public key. OID is not RSA."); - } - var csr = pki.createCertificationRequest(); - csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0; - csr.signatureOid = forge2.asn1.derToOid(capture.csrSignatureOid); - csr.signatureParameters = _readSignatureParameters( - csr.signatureOid, - capture.csrSignatureParams, - true - ); - csr.siginfo.algorithmOid = forge2.asn1.derToOid(capture.csrSignatureOid); - csr.siginfo.parameters = _readSignatureParameters( - csr.siginfo.algorithmOid, - capture.csrSignatureParams, - false - ); - csr.signature = capture.csrSignature; - csr.certificationRequestInfo = capture.certificationRequestInfo; - if (computeHash) { - csr.md = _createSignatureDigest({ - signatureOid: csr.signatureOid, - type: "certification request" - }); - var bytes = asn1.toDer(csr.certificationRequestInfo); - csr.md.update(bytes.getBytes()); - } - var smd = forge2.md.sha1.create(); - csr.subject.getField = function(sn) { - return _getAttribute(csr.subject, sn); - }; - csr.subject.addField = function(attr) { - _fillMissingFields([attr]); - csr.subject.attributes.push(attr); - }; - csr.subject.attributes = pki.RDNAttributesAsArray( - capture.certificationRequestInfoSubject, - smd - ); - csr.subject.hash = smd.digest().toHex(); - csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo); - csr.getAttribute = function(sn) { - return _getAttribute(csr, sn); - }; - csr.addAttribute = function(attr) { - _fillMissingFields([attr]); - csr.attributes.push(attr); - }; - csr.attributes = pki.CRIAttributesAsArray( - capture.certificationRequestInfoAttributes || [] - ); - return csr; - }; - pki.createCertificationRequest = function() { - var csr = {}; - csr.version = 0; - csr.signatureOid = null; - csr.signature = null; - csr.siginfo = {}; - csr.siginfo.algorithmOid = null; - csr.subject = {}; - csr.subject.getField = function(sn) { - return _getAttribute(csr.subject, sn); - }; - csr.subject.addField = function(attr) { - _fillMissingFields([attr]); - csr.subject.attributes.push(attr); - }; - csr.subject.attributes = []; - csr.subject.hash = null; - csr.publicKey = null; - csr.attributes = []; - csr.getAttribute = function(sn) { - return _getAttribute(csr, sn); - }; - csr.addAttribute = function(attr) { - _fillMissingFields([attr]); - csr.attributes.push(attr); - }; - csr.md = null; - csr.setSubject = function(attrs) { - _fillMissingFields(attrs); - csr.subject.attributes = attrs; - csr.subject.hash = null; - }; - csr.setAttributes = function(attrs) { - _fillMissingFields(attrs); - csr.attributes = attrs; - }; - csr.sign = function(key, md) { - csr.md = md || forge2.md.sha1.create(); - var algorithmOid = oids[csr.md.algorithm + "WithRSAEncryption"]; - if (!algorithmOid) { - var error = new Error("Could not compute certification request digest. Unknown message digest algorithm OID."); - error.algorithm = csr.md.algorithm; - throw error; - } - csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid; - csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr); - var bytes = asn1.toDer(csr.certificationRequestInfo); - csr.md.update(bytes.getBytes()); - csr.signature = key.sign(csr.md); - }; - csr.verify = function() { - var rval = false; - var md = csr.md; - if (md === null) { - md = _createSignatureDigest({ - signatureOid: csr.signatureOid, - type: "certification request" - }); - var cri = csr.certificationRequestInfo || pki.getCertificationRequestInfo(csr); - var bytes = asn1.toDer(cri); - md.update(bytes.getBytes()); - } - if (md !== null) { - rval = _verifySignature({ - certificate: csr, - md, - signature: csr.signature - }); - } - return rval; - }; - return csr; - }; - function _dnToAsn1(obj) { - var rval = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - var attr, set; - var attrs = obj.attributes; - for (var i = 0; i < attrs.length; ++i) { - attr = attrs[i]; - var value = attr.value; - var valueTagClass = asn1.Type.PRINTABLESTRING; - if ("valueTagClass" in attr) { - valueTagClass = attr.valueTagClass; - if (valueTagClass === asn1.Type.UTF8) { - value = forge2.util.encodeUtf8(value); - } - } - set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AttributeType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(attr.type).getBytes() - ), - // AttributeValue - asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value) - ]) - ]); - rval.value.push(set); - } - return rval; - } - function _fillMissingFields(attrs) { - var attr; - for (var i = 0; i < attrs.length; ++i) { - attr = attrs[i]; - if (typeof attr.name === "undefined") { - if (attr.type && attr.type in pki.oids) { - attr.name = pki.oids[attr.type]; - } else if (attr.shortName && attr.shortName in _shortNames) { - attr.name = pki.oids[_shortNames[attr.shortName]]; - } - } - if (typeof attr.type === "undefined") { - if (attr.name && attr.name in pki.oids) { - attr.type = pki.oids[attr.name]; - } else { - var error = new Error("Attribute type not specified."); - error.attribute = attr; - throw error; - } - } - if (typeof attr.shortName === "undefined") { - if (attr.name && attr.name in _shortNames) { - attr.shortName = _shortNames[attr.name]; - } - } - if (attr.type === oids.extensionRequest) { - attr.valueConstructed = true; - attr.valueTagClass = asn1.Type.SEQUENCE; - if (!attr.value && attr.extensions) { - attr.value = []; - for (var ei = 0; ei < attr.extensions.length; ++ei) { - attr.value.push(pki.certificateExtensionToAsn1( - _fillMissingExtensionFields(attr.extensions[ei]) - )); - } - } - } - if (typeof attr.value === "undefined") { - var error = new Error("Attribute value not specified."); - error.attribute = attr; - throw error; - } - } - } - function _fillMissingExtensionFields(e, options) { - options = options || {}; - if (typeof e.name === "undefined") { - if (e.id && e.id in pki.oids) { - e.name = pki.oids[e.id]; - } - } - if (typeof e.id === "undefined") { - if (e.name && e.name in pki.oids) { - e.id = pki.oids[e.name]; - } else { - var error = new Error("Extension ID not specified."); - error.extension = e; - throw error; - } - } - if (typeof e.value !== "undefined") { - return e; - } - if (e.name === "keyUsage") { - var unused = 0; - var b2 = 0; - var b3 = 0; - if (e.digitalSignature) { - b2 |= 128; - unused = 7; - } - if (e.nonRepudiation) { - b2 |= 64; - unused = 6; - } - if (e.keyEncipherment) { - b2 |= 32; - unused = 5; - } - if (e.dataEncipherment) { - b2 |= 16; - unused = 4; - } - if (e.keyAgreement) { - b2 |= 8; - unused = 3; - } - if (e.keyCertSign) { - b2 |= 4; - unused = 2; - } - if (e.cRLSign) { - b2 |= 2; - unused = 1; - } - if (e.encipherOnly) { - b2 |= 1; - unused = 0; - } - if (e.decipherOnly) { - b3 |= 128; - unused = 7; - } - var value = String.fromCharCode(unused); - if (b3 !== 0) { - value += String.fromCharCode(b2) + String.fromCharCode(b3); - } else if (b2 !== 0) { - value += String.fromCharCode(b2); - } - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - value - ); - } else if (e.name === "basicConstraints") { - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - if (e.cA) { - e.value.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BOOLEAN, - false, - String.fromCharCode(255) - )); - } - if ("pathLenConstraint" in e) { - e.value.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(e.pathLenConstraint).getBytes() - )); - } - } else if (e.name === "extKeyUsage") { - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - var seq = e.value.value; - for (var key in e) { - if (e[key] !== true) { - continue; - } - if (key in oids) { - seq.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oids[key]).getBytes() - )); - } else if (key.indexOf(".") !== -1) { - seq.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(key).getBytes() - )); - } - } - } else if (e.name === "nsCertType") { - var unused = 0; - var b2 = 0; - if (e.client) { - b2 |= 128; - unused = 7; - } - if (e.server) { - b2 |= 64; - unused = 6; - } - if (e.email) { - b2 |= 32; - unused = 5; - } - if (e.objsign) { - b2 |= 16; - unused = 4; - } - if (e.reserved) { - b2 |= 8; - unused = 3; - } - if (e.sslCA) { - b2 |= 4; - unused = 2; - } - if (e.emailCA) { - b2 |= 2; - unused = 1; - } - if (e.objCA) { - b2 |= 1; - unused = 0; - } - var value = String.fromCharCode(unused); - if (b2 !== 0) { - value += String.fromCharCode(b2); - } - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - value - ); - } else if (e.name === "subjectAltName" || e.name === "issuerAltName") { - e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - var altName; - for (var n = 0; n < e.altNames.length; ++n) { - altName = e.altNames[n]; - var value = altName.value; - if (altName.type === 7 && altName.ip) { - value = forge2.util.bytesFromIP(altName.ip); - if (value === null) { - var error = new Error( - 'Extension "ip" value is not a valid IPv4 or IPv6 address.' - ); - error.extension = e; - throw error; - } - } else if (altName.type === 8) { - if (altName.oid) { - value = asn1.oidToDer(asn1.oidToDer(altName.oid)); - } else { - value = asn1.oidToDer(value); - } - } - e.value.value.push(asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - altName.type, - false, - value - )); - } - } else if (e.name === "nsComment" && options.cert) { - if (!/^[\x00-\x7F]*$/.test(e.comment) || e.comment.length < 1 || e.comment.length > 128) { - throw new Error('Invalid "nsComment" content.'); - } - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.IA5STRING, - false, - e.comment - ); - } else if (e.name === "subjectKeyIdentifier" && options.cert) { - var ski = options.cert.generateSubjectKeyIdentifier(); - e.subjectKeyIdentifier = ski.toHex(); - e.value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - ski.getBytes() - ); - } else if (e.name === "authorityKeyIdentifier" && options.cert) { - e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - var seq = e.value.value; - if (e.keyIdentifier) { - var keyIdentifier = e.keyIdentifier === true ? options.cert.generateSubjectKeyIdentifier().getBytes() : e.keyIdentifier; - seq.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier) - ); - } - if (e.authorityCertIssuer) { - var authorityCertIssuer = [ - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [ - _dnToAsn1(e.authorityCertIssuer === true ? options.cert.issuer : e.authorityCertIssuer) - ]) - ]; - seq.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer) - ); - } - if (e.serialNumber) { - var serialNumber = forge2.util.hexToBytes(e.serialNumber === true ? options.cert.serialNumber : e.serialNumber); - seq.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber) - ); - } - } else if (e.name === "cRLDistributionPoints") { - e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - var seq = e.value.value; - var subSeq = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [] - ); - var fullNameGeneralNames = asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - 0, - true, - [] - ); - var altName; - for (var n = 0; n < e.altNames.length; ++n) { - altName = e.altNames[n]; - var value = altName.value; - if (altName.type === 7 && altName.ip) { - value = forge2.util.bytesFromIP(altName.ip); - if (value === null) { - var error = new Error( - 'Extension "ip" value is not a valid IPv4 or IPv6 address.' - ); - error.extension = e; - throw error; - } - } else if (altName.type === 8) { - if (altName.oid) { - value = asn1.oidToDer(asn1.oidToDer(altName.oid)); - } else { - value = asn1.oidToDer(value); - } - } - fullNameGeneralNames.value.push(asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - altName.type, - false, - value - )); - } - subSeq.value.push(asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - 0, - true, - [fullNameGeneralNames] - )); - seq.push(subSeq); - } - if (typeof e.value === "undefined") { - var error = new Error("Extension value not specified."); - error.extension = e; - throw error; - } - return e; - } - function _signatureParametersToAsn1(oid, params) { - switch (oid) { - case oids["RSASSA-PSS"]: - var parts = []; - if (params.hash.algorithmOid !== void 0) { - parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(params.hash.algorithmOid).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ])); - } - if (params.mgf.algorithmOid !== void 0) { - parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(params.mgf.algorithmOid).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ]) - ])); - } - if (params.saltLength !== void 0) { - parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(params.saltLength).getBytes() - ) - ])); - } - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts); - default: - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ""); - } - } - function _CRIAttributesToAsn1(csr) { - var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []); - if (csr.attributes.length === 0) { - return rval; - } - var attrs = csr.attributes; - for (var i = 0; i < attrs.length; ++i) { - var attr = attrs[i]; - var value = attr.value; - var valueTagClass = asn1.Type.UTF8; - if ("valueTagClass" in attr) { - valueTagClass = attr.valueTagClass; - } - if (valueTagClass === asn1.Type.UTF8) { - value = forge2.util.encodeUtf8(value); - } - var valueConstructed = false; - if ("valueConstructed" in attr) { - valueConstructed = attr.valueConstructed; - } - var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AttributeType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(attr.type).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - // AttributeValue - asn1.create( - asn1.Class.UNIVERSAL, - valueTagClass, - valueConstructed, - value - ) - ]) - ]); - rval.value.push(seq); - } - return rval; - } - var jan_1_1950 = /* @__PURE__ */ new Date("1950-01-01T00:00:00Z"); - var jan_1_2050 = /* @__PURE__ */ new Date("2050-01-01T00:00:00Z"); - function _dateToAsn1(date) { - if (date >= jan_1_1950 && date < jan_1_2050) { - return asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.UTCTIME, - false, - asn1.dateToUtcTime(date) - ); - } else { - return asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.GENERALIZEDTIME, - false, - asn1.dateToGeneralizedTime(date) - ); - } - } - pki.getTBSCertificate = function(cert) { - var notBefore = _dateToAsn1(cert.validity.notBefore); - var notAfter = _dateToAsn1(cert.validity.notAfter); - var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // integer - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(cert.version).getBytes() - ) - ]), - // serialNumber - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - forge2.util.hexToBytes(cert.serialNumber) - ), - // signature - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(cert.siginfo.algorithmOid).getBytes() - ), - // parameters - _signatureParametersToAsn1( - cert.siginfo.algorithmOid, - cert.siginfo.parameters - ) - ]), - // issuer - _dnToAsn1(cert.issuer), - // validity - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - notBefore, - notAfter - ]), - // subject - _dnToAsn1(cert.subject), - // SubjectPublicKeyInfo - pki.publicKeyToAsn1(cert.publicKey) - ]); - if (cert.issuer.uniqueId) { - tbs.value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - // TODO: support arbitrary bit length ids - String.fromCharCode(0) + cert.issuer.uniqueId - ) - ]) - ); - } - if (cert.subject.uniqueId) { - tbs.value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - // TODO: support arbitrary bit length ids - String.fromCharCode(0) + cert.subject.uniqueId - ) - ]) - ); - } - if (cert.extensions.length > 0) { - tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions)); - } - return tbs; - }; - pki.getCertificationRequestInfo = function(csr) { - var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(csr.version).getBytes() - ), - // subject - _dnToAsn1(csr.subject), - // SubjectPublicKeyInfo - pki.publicKeyToAsn1(csr.publicKey), - // attributes - _CRIAttributesToAsn1(csr) - ]); - return cri; - }; - pki.distinguishedNameToAsn1 = function(dn) { - return _dnToAsn1(dn); - }; - pki.certificateToAsn1 = function(cert) { - var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert); - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // TBSCertificate - tbsCertificate, - // AlgorithmIdentifier (signature algorithm) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(cert.signatureOid).getBytes() - ), - // parameters - _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters) - ]), - // SignatureValue - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - String.fromCharCode(0) + cert.signature - ) - ]); - }; - pki.certificateExtensionsToAsn1 = function(exts) { - var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []); - var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - rval.value.push(seq); - for (var i = 0; i < exts.length; ++i) { - seq.value.push(pki.certificateExtensionToAsn1(exts[i])); - } - return rval; - }; - pki.certificateExtensionToAsn1 = function(ext) { - var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); - extseq.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(ext.id).getBytes() - )); - if (ext.critical) { - extseq.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BOOLEAN, - false, - String.fromCharCode(255) - )); - } - var value = ext.value; - if (typeof ext.value !== "string") { - value = asn1.toDer(value).getBytes(); - } - extseq.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - value - )); - return extseq; - }; - pki.certificationRequestToAsn1 = function(csr) { - var cri = csr.certificationRequestInfo || pki.getCertificationRequestInfo(csr); - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // CertificationRequestInfo - cri, - // AlgorithmIdentifier (signature algorithm) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(csr.signatureOid).getBytes() - ), - // parameters - _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters) - ]), - // signature - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BITSTRING, - false, - String.fromCharCode(0) + csr.signature - ) - ]); - }; - pki.createCaStore = function(certs) { - var caStore = { - // stored certificates - certs: {} - }; - caStore.getIssuer = function(cert2) { - var rval = getBySubject(cert2.issuer); - return rval; - }; - caStore.addCertificate = function(cert2) { - if (typeof cert2 === "string") { - cert2 = forge2.pki.certificateFromPem(cert2); - } - ensureSubjectHasHash(cert2.subject); - if (!caStore.hasCertificate(cert2)) { - if (cert2.subject.hash in caStore.certs) { - var tmp = caStore.certs[cert2.subject.hash]; - if (!forge2.util.isArray(tmp)) { - tmp = [tmp]; - } - tmp.push(cert2); - caStore.certs[cert2.subject.hash] = tmp; - } else { - caStore.certs[cert2.subject.hash] = cert2; - } - } - }; - caStore.hasCertificate = function(cert2) { - if (typeof cert2 === "string") { - cert2 = forge2.pki.certificateFromPem(cert2); - } - var match = getBySubject(cert2.subject); - if (!match) { - return false; - } - if (!forge2.util.isArray(match)) { - match = [match]; - } - var der1 = asn1.toDer(pki.certificateToAsn1(cert2)).getBytes(); - for (var i2 = 0; i2 < match.length; ++i2) { - var der2 = asn1.toDer(pki.certificateToAsn1(match[i2])).getBytes(); - if (der1 === der2) { - return true; - } - } - return false; - }; - caStore.listAllCertificates = function() { - var certList = []; - for (var hash in caStore.certs) { - if (caStore.certs.hasOwnProperty(hash)) { - var value = caStore.certs[hash]; - if (!forge2.util.isArray(value)) { - certList.push(value); - } else { - for (var i2 = 0; i2 < value.length; ++i2) { - certList.push(value[i2]); - } - } - } - } - return certList; - }; - caStore.removeCertificate = function(cert2) { - var result; - if (typeof cert2 === "string") { - cert2 = forge2.pki.certificateFromPem(cert2); - } - ensureSubjectHasHash(cert2.subject); - if (!caStore.hasCertificate(cert2)) { - return null; - } - var match = getBySubject(cert2.subject); - if (!forge2.util.isArray(match)) { - result = caStore.certs[cert2.subject.hash]; - delete caStore.certs[cert2.subject.hash]; - return result; - } - var der1 = asn1.toDer(pki.certificateToAsn1(cert2)).getBytes(); - for (var i2 = 0; i2 < match.length; ++i2) { - var der2 = asn1.toDer(pki.certificateToAsn1(match[i2])).getBytes(); - if (der1 === der2) { - result = match[i2]; - match.splice(i2, 1); - } - } - if (match.length === 0) { - delete caStore.certs[cert2.subject.hash]; - } - return result; - }; - function getBySubject(subject) { - ensureSubjectHasHash(subject); - return caStore.certs[subject.hash] || null; - } - function ensureSubjectHasHash(subject) { - if (!subject.hash) { - var md = forge2.md.sha1.create(); - subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md); - subject.hash = md.digest().toHex(); - } - } - if (certs) { - for (var i = 0; i < certs.length; ++i) { - var cert = certs[i]; - caStore.addCertificate(cert); - } - } - return caStore; - }; - pki.certificateError = { - bad_certificate: "forge.pki.BadCertificate", - unsupported_certificate: "forge.pki.UnsupportedCertificate", - certificate_revoked: "forge.pki.CertificateRevoked", - certificate_expired: "forge.pki.CertificateExpired", - certificate_unknown: "forge.pki.CertificateUnknown", - unknown_ca: "forge.pki.UnknownCertificateAuthority" - }; - pki.verifyCertificateChain = function(caStore, chain, options) { - if (typeof options === "function") { - options = { verify: options }; - } - options = options || {}; - chain = chain.slice(0); - var certs = chain.slice(0); - var validityCheckDate = options.validityCheckDate; - if (typeof validityCheckDate === "undefined") { - validityCheckDate = /* @__PURE__ */ new Date(); - } - var first = true; - var error = null; - var depth = 0; - do { - var cert = chain.shift(); - var parent = null; - var selfSigned = false; - if (validityCheckDate) { - if (validityCheckDate < cert.validity.notBefore || validityCheckDate > cert.validity.notAfter) { - error = { - message: "Certificate is not valid yet or has expired.", - error: pki.certificateError.certificate_expired, - notBefore: cert.validity.notBefore, - notAfter: cert.validity.notAfter, - // TODO: we might want to reconsider renaming 'now' to - // 'validityCheckDate' should this API be changed in the future. - now: validityCheckDate - }; - } - } - if (error === null) { - parent = chain[0] || caStore.getIssuer(cert); - if (parent === null) { - if (cert.isIssuer(cert)) { - selfSigned = true; - parent = cert; - } - } - if (parent) { - var parents = parent; - if (!forge2.util.isArray(parents)) { - parents = [parents]; - } - var verified = false; - while (!verified && parents.length > 0) { - parent = parents.shift(); - try { - verified = parent.verify(cert); - } catch (ex) { - } - } - if (!verified) { - error = { - message: "Certificate signature is invalid.", - error: pki.certificateError.bad_certificate - }; - } - } - if (error === null && (!parent || selfSigned) && !caStore.hasCertificate(cert)) { - error = { - message: "Certificate is not trusted.", - error: pki.certificateError.unknown_ca - }; - } - } - if (error === null && parent && !cert.isIssuer(parent)) { - error = { - message: "Certificate issuer is invalid.", - error: pki.certificateError.bad_certificate - }; - } - if (error === null) { - var se = { - keyUsage: true, - basicConstraints: true - }; - for (var i = 0; error === null && i < cert.extensions.length; ++i) { - var ext = cert.extensions[i]; - if (ext.critical && !(ext.name in se)) { - error = { - message: "Certificate has an unsupported critical extension.", - error: pki.certificateError.unsupported_certificate - }; - } - } - } - if (error === null && (!first || chain.length === 0 && (!parent || selfSigned))) { - var bcExt = cert.getExtension("basicConstraints"); - var keyUsageExt = cert.getExtension("keyUsage"); - if (keyUsageExt !== null) { - if (!keyUsageExt.keyCertSign || bcExt === null) { - error = { - message: "Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.", - error: pki.certificateError.bad_certificate - }; - } - } - if (error === null && bcExt !== null && !bcExt.cA) { - error = { - message: "Certificate basicConstraints indicates the certificate is not a CA.", - error: pki.certificateError.bad_certificate - }; - } - if (error === null && keyUsageExt !== null && "pathLenConstraint" in bcExt) { - var pathLen = depth - 1; - if (pathLen > bcExt.pathLenConstraint) { - error = { - message: "Certificate basicConstraints pathLenConstraint violated.", - error: pki.certificateError.bad_certificate - }; - } - } - } - var vfd = error === null ? true : error.error; - var ret = options.verify ? options.verify(vfd, depth, certs) : vfd; - if (ret === true) { - error = null; - } else { - if (vfd === true) { - error = { - message: "The application rejected the certificate.", - error: pki.certificateError.bad_certificate - }; - } - if (ret || ret === 0) { - if (typeof ret === "object" && !forge2.util.isArray(ret)) { - if (ret.message) { - error.message = ret.message; - } - if (ret.error) { - error.error = ret.error; - } - } else if (typeof ret === "string") { - error.error = ret; - } - } - throw error; - } - first = false; - ++depth; - } while (chain.length > 0); - return true; - }; - } -}); - -// node_modules/node-forge/lib/pkcs12.js -var require_pkcs12 = __commonJS({ - "node_modules/node-forge/lib/pkcs12.js"(exports, module) { - var forge2 = require_forge(); - require_asn1(); - require_hmac(); - require_oids(); - require_pkcs7asn1(); - require_pbe(); - require_random(); - require_rsa(); - require_sha1(); - require_util(); - require_x509(); - var asn1 = forge2.asn1; - var pki = forge2.pki; - var p12 = module.exports = forge2.pkcs12 = forge2.pkcs12 || {}; - var contentInfoValidator = { - name: "ContentInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - // a ContentInfo - constructed: true, - value: [{ - name: "ContentInfo.contentType", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "contentType" - }, { - name: "ContentInfo.content", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - constructed: true, - captureAsn1: "content" - }] - }; - var pfxValidator = { - name: "PFX", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [ - { - name: "PFX.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "version" - }, - contentInfoValidator, - { - name: "PFX.macData", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: "mac", - value: [{ - name: "PFX.macData.mac", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - // DigestInfo - constructed: true, - value: [{ - name: "PFX.macData.mac.digestAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - // DigestAlgorithmIdentifier - constructed: true, - value: [{ - name: "PFX.macData.mac.digestAlgorithm.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "macAlgorithm" - }, { - name: "PFX.macData.mac.digestAlgorithm.parameters", - tagClass: asn1.Class.UNIVERSAL, - captureAsn1: "macAlgorithmParameters" - }] - }, { - name: "PFX.macData.mac.digest", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "macDigest" - }] - }, { - name: "PFX.macData.macSalt", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "macSalt" - }, { - name: "PFX.macData.iterations", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - optional: true, - capture: "macIterations" - }] - } - ] - }; - var safeBagValidator = { - name: "SafeBag", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "SafeBag.bagId", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "bagId" - }, { - name: "SafeBag.bagValue", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - constructed: true, - captureAsn1: "bagValue" - }, { - name: "SafeBag.bagAttributes", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - optional: true, - capture: "bagAttributes" - }] - }; - var attributeValidator = { - name: "Attribute", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "Attribute.attrId", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "oid" - }, { - name: "Attribute.attrValues", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SET, - constructed: true, - capture: "values" - }] - }; - var certBagValidator = { - name: "CertBag", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "CertBag.certId", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "certId" - }, { - name: "CertBag.certValue", - tagClass: asn1.Class.CONTEXT_SPECIFIC, - constructed: true, - /* So far we only support X.509 certificates (which are wrapped in - an OCTET STRING, hence hard code that here). */ - value: [{ - name: "CertBag.certValue[0]", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Class.OCTETSTRING, - constructed: false, - capture: "cert" - }] - }] - }; - function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) { - var result = []; - for (var i = 0; i < safeContents.length; i++) { - for (var j = 0; j < safeContents[i].safeBags.length; j++) { - var bag = safeContents[i].safeBags[j]; - if (bagType !== void 0 && bag.type !== bagType) { - continue; - } - if (attrName === null) { - result.push(bag); - continue; - } - if (bag.attributes[attrName] !== void 0 && bag.attributes[attrName].indexOf(attrValue) >= 0) { - result.push(bag); - } - } - } - return result; - } - p12.pkcs12FromAsn1 = function(obj, strict, password) { - if (typeof strict === "string") { - password = strict; - strict = true; - } else if (strict === void 0) { - strict = true; - } - var capture = {}; - var errors = []; - if (!asn1.validate(obj, pfxValidator, capture, errors)) { - var error = new Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX."); - error.errors = error; - throw error; - } - var pfx = { - version: capture.version.charCodeAt(0), - safeContents: [], - /** - * Gets bags with matching attributes. - * - * @param filter the attributes to filter by: - * [localKeyId] the localKeyId to search for. - * [localKeyIdHex] the localKeyId in hex to search for. - * [friendlyName] the friendly name to search for. - * [bagType] bag type to narrow each attribute search by. - * - * @return a map of attribute type to an array of matching bags or, if no - * attribute was given but a bag type, the map key will be the - * bag type. - */ - getBags: function(filter) { - var rval = {}; - var localKeyId; - if ("localKeyId" in filter) { - localKeyId = filter.localKeyId; - } else if ("localKeyIdHex" in filter) { - localKeyId = forge2.util.hexToBytes(filter.localKeyIdHex); - } - if (localKeyId === void 0 && !("friendlyName" in filter) && "bagType" in filter) { - rval[filter.bagType] = _getBagsByAttribute( - pfx.safeContents, - null, - null, - filter.bagType - ); - } - if (localKeyId !== void 0) { - rval.localKeyId = _getBagsByAttribute( - pfx.safeContents, - "localKeyId", - localKeyId, - filter.bagType - ); - } - if ("friendlyName" in filter) { - rval.friendlyName = _getBagsByAttribute( - pfx.safeContents, - "friendlyName", - filter.friendlyName, - filter.bagType - ); - } - return rval; - }, - /** - * DEPRECATED: use getBags() instead. - * - * Get bags with matching friendlyName attribute. - * - * @param friendlyName the friendly name to search for. - * @param [bagType] bag type to narrow search by. - * - * @return an array of bags with matching friendlyName attribute. - */ - getBagsByFriendlyName: function(friendlyName, bagType) { - return _getBagsByAttribute( - pfx.safeContents, - "friendlyName", - friendlyName, - bagType - ); - }, - /** - * DEPRECATED: use getBags() instead. - * - * Get bags with matching localKeyId attribute. - * - * @param localKeyId the localKeyId to search for. - * @param [bagType] bag type to narrow search by. - * - * @return an array of bags with matching localKeyId attribute. - */ - getBagsByLocalKeyId: function(localKeyId, bagType) { - return _getBagsByAttribute( - pfx.safeContents, - "localKeyId", - localKeyId, - bagType - ); - } - }; - if (capture.version.charCodeAt(0) !== 3) { - var error = new Error("PKCS#12 PFX of version other than 3 not supported."); - error.version = capture.version.charCodeAt(0); - throw error; - } - if (asn1.derToOid(capture.contentType) !== pki.oids.data) { - var error = new Error("Only PKCS#12 PFX in password integrity mode supported."); - error.oid = asn1.derToOid(capture.contentType); - throw error; - } - var data = capture.content.value[0]; - if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) { - throw new Error("PKCS#12 authSafe content data is not an OCTET STRING."); - } - data = _decodePkcs7Data(data); - if (capture.mac) { - var md = null; - var macKeyBytes = 0; - var macAlgorithm = asn1.derToOid(capture.macAlgorithm); - switch (macAlgorithm) { - case pki.oids.sha1: - md = forge2.md.sha1.create(); - macKeyBytes = 20; - break; - case pki.oids.sha256: - md = forge2.md.sha256.create(); - macKeyBytes = 32; - break; - case pki.oids.sha384: - md = forge2.md.sha384.create(); - macKeyBytes = 48; - break; - case pki.oids.sha512: - md = forge2.md.sha512.create(); - macKeyBytes = 64; - break; - case pki.oids.md5: - md = forge2.md.md5.create(); - macKeyBytes = 16; - break; - } - if (md === null) { - throw new Error("PKCS#12 uses unsupported MAC algorithm: " + macAlgorithm); - } - var macSalt = new forge2.util.ByteBuffer(capture.macSalt); - var macIterations = "macIterations" in capture ? parseInt(forge2.util.bytesToHex(capture.macIterations), 16) : 1; - var macKey = p12.generateKey( - password, - macSalt, - 3, - macIterations, - macKeyBytes, - md - ); - var mac = forge2.hmac.create(); - mac.start(md, macKey); - mac.update(data.value); - var macValue = mac.getMac(); - if (macValue.getBytes() !== capture.macDigest) { - throw new Error("PKCS#12 MAC could not be verified. Invalid password?"); - } - } - _decodeAuthenticatedSafe(pfx, data.value, strict, password); - return pfx; - }; - function _decodePkcs7Data(data) { - if (data.composed || data.constructed) { - var value = forge2.util.createBuffer(); - for (var i = 0; i < data.value.length; ++i) { - value.putBytes(data.value[i].value); - } - data.composed = data.constructed = false; - data.value = value.getBytes(); - } - return data; - } - function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) { - authSafe = asn1.fromDer(authSafe, strict); - if (authSafe.tagClass !== asn1.Class.UNIVERSAL || authSafe.type !== asn1.Type.SEQUENCE || authSafe.constructed !== true) { - throw new Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo"); - } - for (var i = 0; i < authSafe.value.length; i++) { - var contentInfo = authSafe.value[i]; - var capture = {}; - var errors = []; - if (!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) { - var error = new Error("Cannot read ContentInfo."); - error.errors = errors; - throw error; - } - var obj = { - encrypted: false - }; - var safeContents = null; - var data = capture.content.value[0]; - switch (asn1.derToOid(capture.contentType)) { - case pki.oids.data: - if (data.tagClass !== asn1.Class.UNIVERSAL || data.type !== asn1.Type.OCTETSTRING) { - throw new Error("PKCS#12 SafeContents Data is not an OCTET STRING."); - } - safeContents = _decodePkcs7Data(data).value; - break; - case pki.oids.encryptedData: - safeContents = _decryptSafeContents(data, password); - obj.encrypted = true; - break; - default: - var error = new Error("Unsupported PKCS#12 contentType."); - error.contentType = asn1.derToOid(capture.contentType); - throw error; - } - obj.safeBags = _decodeSafeContents(safeContents, strict, password); - pfx.safeContents.push(obj); - } - } - function _decryptSafeContents(data, password) { - var capture = {}; - var errors = []; - if (!asn1.validate( - data, - forge2.pkcs7.asn1.encryptedDataValidator, - capture, - errors - )) { - var error = new Error("Cannot read EncryptedContentInfo."); - error.errors = errors; - throw error; - } - var oid = asn1.derToOid(capture.contentType); - if (oid !== pki.oids.data) { - var error = new Error( - "PKCS#12 EncryptedContentInfo ContentType is not Data." - ); - error.oid = oid; - throw error; - } - oid = asn1.derToOid(capture.encAlgorithm); - var cipher = pki.pbe.getCipher(oid, capture.encParameter, password); - var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1); - var encrypted = forge2.util.createBuffer(encryptedContentAsn1.value); - cipher.update(encrypted); - if (!cipher.finish()) { - throw new Error("Failed to decrypt PKCS#12 SafeContents."); - } - return cipher.output.getBytes(); - } - function _decodeSafeContents(safeContents, strict, password) { - if (!strict && safeContents.length === 0) { - return []; - } - safeContents = asn1.fromDer(safeContents, strict); - if (safeContents.tagClass !== asn1.Class.UNIVERSAL || safeContents.type !== asn1.Type.SEQUENCE || safeContents.constructed !== true) { - throw new Error( - "PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag." - ); - } - var res = []; - for (var i = 0; i < safeContents.value.length; i++) { - var safeBag = safeContents.value[i]; - var capture = {}; - var errors = []; - if (!asn1.validate(safeBag, safeBagValidator, capture, errors)) { - var error = new Error("Cannot read SafeBag."); - error.errors = errors; - throw error; - } - var bag = { - type: asn1.derToOid(capture.bagId), - attributes: _decodeBagAttributes(capture.bagAttributes) - }; - res.push(bag); - var validator, decoder; - var bagAsn1 = capture.bagValue.value[0]; - switch (bag.type) { - case pki.oids.pkcs8ShroudedKeyBag: - bagAsn1 = pki.decryptPrivateKeyInfo(bagAsn1, password); - if (bagAsn1 === null) { - throw new Error( - "Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?" - ); - } - case pki.oids.keyBag: - try { - bag.key = pki.privateKeyFromAsn1(bagAsn1); - } catch (e) { - bag.key = null; - bag.asn1 = bagAsn1; - } - continue; - case pki.oids.certBag: - validator = certBagValidator; - decoder = function() { - if (asn1.derToOid(capture.certId) !== pki.oids.x509Certificate) { - var error2 = new Error( - "Unsupported certificate type, only X.509 supported." - ); - error2.oid = asn1.derToOid(capture.certId); - throw error2; - } - var certAsn1 = asn1.fromDer(capture.cert, strict); - try { - bag.cert = pki.certificateFromAsn1(certAsn1, true); - } catch (e) { - bag.cert = null; - bag.asn1 = certAsn1; - } - }; - break; - default: - var error = new Error("Unsupported PKCS#12 SafeBag type."); - error.oid = bag.type; - throw error; - } - if (validator !== void 0 && !asn1.validate(bagAsn1, validator, capture, errors)) { - var error = new Error("Cannot read PKCS#12 " + validator.name); - error.errors = errors; - throw error; - } - decoder(); - } - return res; - } - function _decodeBagAttributes(attributes) { - var decodedAttrs = {}; - if (attributes !== void 0) { - for (var i = 0; i < attributes.length; ++i) { - var capture = {}; - var errors = []; - if (!asn1.validate(attributes[i], attributeValidator, capture, errors)) { - var error = new Error("Cannot read PKCS#12 BagAttribute."); - error.errors = errors; - throw error; - } - var oid = asn1.derToOid(capture.oid); - if (pki.oids[oid] === void 0) { - continue; - } - decodedAttrs[pki.oids[oid]] = []; - for (var j = 0; j < capture.values.length; ++j) { - decodedAttrs[pki.oids[oid]].push(capture.values[j].value); - } - } - } - return decodedAttrs; - } - p12.toPkcs12Asn1 = function(key, cert, password, options) { - options = options || {}; - options.saltSize = options.saltSize || 8; - options.count = options.count || 2048; - options.algorithm = options.algorithm || options.encAlgorithm || "aes128"; - if (!("useMac" in options)) { - options.useMac = true; - } - if (!("localKeyId" in options)) { - options.localKeyId = null; - } - if (!("generateLocalKeyId" in options)) { - options.generateLocalKeyId = true; - } - var localKeyId = options.localKeyId; - var bagAttrs; - if (localKeyId !== null) { - localKeyId = forge2.util.hexToBytes(localKeyId); - } else if (options.generateLocalKeyId) { - if (cert) { - var pairedCert = forge2.util.isArray(cert) ? cert[0] : cert; - if (typeof pairedCert === "string") { - pairedCert = pki.certificateFromPem(pairedCert); - } - var sha1 = forge2.md.sha1.create(); - sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes()); - localKeyId = sha1.digest().getBytes(); - } else { - localKeyId = forge2.random.getBytes(20); - } - } - var attrs = []; - if (localKeyId !== null) { - attrs.push( - // localKeyID - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // attrId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.localKeyId).getBytes() - ), - // attrValues - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - localKeyId - ) - ]) - ]) - ); - } - if ("friendlyName" in options) { - attrs.push( - // friendlyName - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // attrId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.friendlyName).getBytes() - ), - // attrValues - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.BMPSTRING, - false, - options.friendlyName - ) - ]) - ]) - ); - } - if (attrs.length > 0) { - bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs); - } - var contents = []; - var chain = []; - if (cert !== null) { - if (forge2.util.isArray(cert)) { - chain = cert; - } else { - chain = [cert]; - } - } - var certSafeBags = []; - for (var i = 0; i < chain.length; ++i) { - cert = chain[i]; - if (typeof cert === "string") { - cert = pki.certificateFromPem(cert); - } - var certBagAttrs = i === 0 ? bagAttrs : void 0; - var certAsn1 = pki.certificateToAsn1(cert); - var certSafeBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // bagId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.certBag).getBytes() - ), - // bagValue - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // CertBag - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // certId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.x509Certificate).getBytes() - ), - // certValue (x509Certificate) - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(certAsn1).getBytes() - ) - ]) - ]) - ]), - // bagAttributes (OPTIONAL) - certBagAttrs - ]); - certSafeBags.push(certSafeBag); - } - if (certSafeBags.length > 0) { - var certSafeContents = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - certSafeBags - ); - var certCI = ( - // PKCS#7 ContentInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // contentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - // OID for the content type is 'data' - asn1.oidToDer(pki.oids.data).getBytes() - ), - // content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(certSafeContents).getBytes() - ) - ]) - ]) - ); - contents.push(certCI); - } - var keyBag = null; - if (key !== null) { - var pkAsn1 = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key)); - if (password === null) { - keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // bagId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.keyBag).getBytes() - ), - // bagValue - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // PrivateKeyInfo - pkAsn1 - ]), - // bagAttributes (OPTIONAL) - bagAttrs - ]); - } else { - keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // bagId - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes() - ), - // bagValue - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - // EncryptedPrivateKeyInfo - pki.encryptPrivateKeyInfo(pkAsn1, password, options) - ]), - // bagAttributes (OPTIONAL) - bagAttrs - ]); - } - var keySafeContents = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]); - var keyCI = ( - // PKCS#7 ContentInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // contentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - // OID for the content type is 'data' - asn1.oidToDer(pki.oids.data).getBytes() - ), - // content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(keySafeContents).getBytes() - ) - ]) - ]) - ); - contents.push(keyCI); - } - var safe = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - contents - ); - var macData; - if (options.useMac) { - var sha1 = forge2.md.sha1.create(); - var macSalt = new forge2.util.ByteBuffer( - forge2.random.getBytes(options.saltSize) - ); - var count = options.count; - var key = p12.generateKey(password, macSalt, 3, count, 20); - var mac = forge2.hmac.create(); - mac.start(sha1, key); - mac.update(asn1.toDer(safe).getBytes()); - var macValue = mac.getMac(); - macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // mac DigestInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // digestAlgorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm = SHA-1 - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(pki.oids.sha1).getBytes() - ), - // parameters = Null - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]), - // digest - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - macValue.getBytes() - ) - ]), - // macSalt OCTET STRING - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - macSalt.getBytes() - ), - // iterations INTEGER (XXX: Only support count < 65536) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(count).getBytes() - ) - ]); - } - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version (3) - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(3).getBytes() - ), - // PKCS#7 ContentInfo - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // contentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - // OID for the content type is 'data' - asn1.oidToDer(pki.oids.data).getBytes() - ), - // content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - asn1.toDer(safe).getBytes() - ) - ]) - ]), - macData - ]); - }; - p12.generateKey = forge2.pbe.generatePkcs12Key; - } -}); - -// node_modules/node-forge/lib/pki.js -var require_pki = __commonJS({ - "node_modules/node-forge/lib/pki.js"(exports, module) { - var forge2 = require_forge(); - require_asn1(); - require_oids(); - require_pbe(); - require_pem(); - require_pbkdf2(); - require_pkcs12(); - require_pss(); - require_rsa(); - require_util(); - require_x509(); - var asn1 = forge2.asn1; - var pki = module.exports = forge2.pki = forge2.pki || {}; - pki.pemToDer = function(pem) { - var msg = forge2.pem.decode(pem)[0]; - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert PEM to DER; PEM is encrypted."); - } - return forge2.util.createBuffer(msg.body); - }; - pki.privateKeyFromPem = function(pem) { - var msg = forge2.pem.decode(pem)[0]; - if (msg.type !== "PRIVATE KEY" && msg.type !== "RSA PRIVATE KEY") { - var error = new Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".'); - error.headerType = msg.type; - throw error; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert private key from PEM; PEM is encrypted."); - } - var obj = asn1.fromDer(msg.body); - return pki.privateKeyFromAsn1(obj); - }; - pki.privateKeyToPem = function(key, maxline) { - var msg = { - type: "RSA PRIVATE KEY", - body: asn1.toDer(pki.privateKeyToAsn1(key)).getBytes() - }; - return forge2.pem.encode(msg, { maxline }); - }; - pki.privateKeyInfoToPem = function(pki2, maxline) { - var msg = { - type: "PRIVATE KEY", - body: asn1.toDer(pki2).getBytes() - }; - return forge2.pem.encode(msg, { maxline }); - }; - } -}); - -// node_modules/node-forge/lib/tls.js -var require_tls = __commonJS({ - "node_modules/node-forge/lib/tls.js"(exports, module) { - var forge2 = require_forge(); - require_asn1(); - require_hmac(); - require_md5(); - require_pem(); - require_pki(); - require_random(); - require_sha1(); - require_util(); - var prf_TLS1 = function(secret, label, seed, length) { - var rval = forge2.util.createBuffer(); - var idx = secret.length >> 1; - var slen = idx + (secret.length & 1); - var s1 = secret.substr(0, slen); - var s2 = secret.substr(idx, slen); - var ai = forge2.util.createBuffer(); - var hmac = forge2.hmac.create(); - seed = label + seed; - var md5itr = Math.ceil(length / 16); - var sha1itr = Math.ceil(length / 20); - hmac.start("MD5", s1); - var md5bytes = forge2.util.createBuffer(); - ai.putBytes(seed); - for (var i = 0; i < md5itr; ++i) { - hmac.start(null, null); - hmac.update(ai.getBytes()); - ai.putBuffer(hmac.digest()); - hmac.start(null, null); - hmac.update(ai.bytes() + seed); - md5bytes.putBuffer(hmac.digest()); - } - hmac.start("SHA1", s2); - var sha1bytes = forge2.util.createBuffer(); - ai.clear(); - ai.putBytes(seed); - for (var i = 0; i < sha1itr; ++i) { - hmac.start(null, null); - hmac.update(ai.getBytes()); - ai.putBuffer(hmac.digest()); - hmac.start(null, null); - hmac.update(ai.bytes() + seed); - sha1bytes.putBuffer(hmac.digest()); - } - rval.putBytes(forge2.util.xorBytes( - md5bytes.getBytes(), - sha1bytes.getBytes(), - length - )); - return rval; - }; - var hmac_sha1 = function(key2, seqNum, record) { - var hmac = forge2.hmac.create(); - hmac.start("SHA1", key2); - var b = forge2.util.createBuffer(); - b.putInt32(seqNum[0]); - b.putInt32(seqNum[1]); - b.putByte(record.type); - b.putByte(record.version.major); - b.putByte(record.version.minor); - b.putInt16(record.length); - b.putBytes(record.fragment.bytes()); - hmac.update(b.getBytes()); - return hmac.digest().getBytes(); - }; - var deflate = function(c, record, s) { - var rval = false; - try { - var bytes = c.deflate(record.fragment.getBytes()); - record.fragment = forge2.util.createBuffer(bytes); - record.length = bytes.length; - rval = true; - } catch (ex) { - } - return rval; - }; - var inflate = function(c, record, s) { - var rval = false; - try { - var bytes = c.inflate(record.fragment.getBytes()); - record.fragment = forge2.util.createBuffer(bytes); - record.length = bytes.length; - rval = true; - } catch (ex) { - } - return rval; - }; - var readVector = function(b, lenBytes) { - var len = 0; - switch (lenBytes) { - case 1: - len = b.getByte(); - break; - case 2: - len = b.getInt16(); - break; - case 3: - len = b.getInt24(); - break; - case 4: - len = b.getInt32(); - break; - } - return forge2.util.createBuffer(b.getBytes(len)); - }; - var writeVector = function(b, lenBytes, v) { - b.putInt(v.length(), lenBytes << 3); - b.putBuffer(v); - }; - var tls = {}; - tls.Versions = { - TLS_1_0: { major: 3, minor: 1 }, - TLS_1_1: { major: 3, minor: 2 }, - TLS_1_2: { major: 3, minor: 3 } - }; - tls.SupportedVersions = [ - tls.Versions.TLS_1_1, - tls.Versions.TLS_1_0 - ]; - tls.Version = tls.SupportedVersions[0]; - tls.MaxFragment = 16384 - 1024; - tls.ConnectionEnd = { - server: 0, - client: 1 - }; - tls.PRFAlgorithm = { - tls_prf_sha256: 0 - }; - tls.BulkCipherAlgorithm = { - none: null, - rc4: 0, - des3: 1, - aes: 2 - }; - tls.CipherType = { - stream: 0, - block: 1, - aead: 2 - }; - tls.MACAlgorithm = { - none: null, - hmac_md5: 0, - hmac_sha1: 1, - hmac_sha256: 2, - hmac_sha384: 3, - hmac_sha512: 4 - }; - tls.CompressionMethod = { - none: 0, - deflate: 1 - }; - tls.ContentType = { - change_cipher_spec: 20, - alert: 21, - handshake: 22, - application_data: 23, - heartbeat: 24 - }; - tls.HandshakeType = { - hello_request: 0, - client_hello: 1, - server_hello: 2, - certificate: 11, - server_key_exchange: 12, - certificate_request: 13, - server_hello_done: 14, - certificate_verify: 15, - client_key_exchange: 16, - finished: 20 - }; - tls.Alert = {}; - tls.Alert.Level = { - warning: 1, - fatal: 2 - }; - tls.Alert.Description = { - close_notify: 0, - unexpected_message: 10, - bad_record_mac: 20, - decryption_failed: 21, - record_overflow: 22, - decompression_failure: 30, - handshake_failure: 40, - bad_certificate: 42, - unsupported_certificate: 43, - certificate_revoked: 44, - certificate_expired: 45, - certificate_unknown: 46, - illegal_parameter: 47, - unknown_ca: 48, - access_denied: 49, - decode_error: 50, - decrypt_error: 51, - export_restriction: 60, - protocol_version: 70, - insufficient_security: 71, - internal_error: 80, - user_canceled: 90, - no_renegotiation: 100 - }; - tls.HeartbeatMessageType = { - heartbeat_request: 1, - heartbeat_response: 2 - }; - tls.CipherSuites = {}; - tls.getCipherSuite = function(twoBytes) { - var rval = null; - for (var key2 in tls.CipherSuites) { - var cs = tls.CipherSuites[key2]; - if (cs.id[0] === twoBytes.charCodeAt(0) && cs.id[1] === twoBytes.charCodeAt(1)) { - rval = cs; - break; - } - } - return rval; - }; - tls.handleUnexpected = function(c, record) { - var ignore = !c.open && c.entity === tls.ConnectionEnd.client; - if (!ignore) { - c.error(c, { - message: "Unexpected message. Received TLS record out of order.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unexpected_message - } - }); - } - }; - tls.handleHelloRequest = function(c, record, length) { - if (!c.handshaking && c.handshakes > 0) { - tls.queue(c, tls.createAlert(c, { - level: tls.Alert.Level.warning, - description: tls.Alert.Description.no_renegotiation - })); - tls.flush(c); - } - c.process(); - }; - tls.parseHelloMessage = function(c, record, length) { - var msg = null; - var client = c.entity === tls.ConnectionEnd.client; - if (length < 38) { - c.error(c, { - message: client ? "Invalid ServerHello message. Message too short." : "Invalid ClientHello message. Message too short.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } else { - var b = record.fragment; - var remaining = b.length(); - msg = { - version: { - major: b.getByte(), - minor: b.getByte() - }, - random: forge2.util.createBuffer(b.getBytes(32)), - session_id: readVector(b, 1), - extensions: [] - }; - if (client) { - msg.cipher_suite = b.getBytes(2); - msg.compression_method = b.getByte(); - } else { - msg.cipher_suites = readVector(b, 2); - msg.compression_methods = readVector(b, 1); - } - remaining = length - (remaining - b.length()); - if (remaining > 0) { - var exts = readVector(b, 2); - while (exts.length() > 0) { - msg.extensions.push({ - type: [exts.getByte(), exts.getByte()], - data: readVector(exts, 2) - }); - } - if (!client) { - for (var i = 0; i < msg.extensions.length; ++i) { - var ext = msg.extensions[i]; - if (ext.type[0] === 0 && ext.type[1] === 0) { - var snl = readVector(ext.data, 2); - while (snl.length() > 0) { - var snType = snl.getByte(); - if (snType !== 0) { - break; - } - c.session.extensions.server_name.serverNameList.push( - readVector(snl, 2).getBytes() - ); - } - } - } - } - } - if (c.session.version) { - if (msg.version.major !== c.session.version.major || msg.version.minor !== c.session.version.minor) { - return c.error(c, { - message: "TLS version change is disallowed during renegotiation.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.protocol_version - } - }); - } - } - if (client) { - c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite); - } else { - var tmp = forge2.util.createBuffer(msg.cipher_suites.bytes()); - while (tmp.length() > 0) { - c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2)); - if (c.session.cipherSuite !== null) { - break; - } - } - } - if (c.session.cipherSuite === null) { - return c.error(c, { - message: "No cipher suites in common.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.handshake_failure - }, - cipherSuite: forge2.util.bytesToHex(msg.cipher_suite) - }); - } - if (client) { - c.session.compressionMethod = msg.compression_method; - } else { - c.session.compressionMethod = tls.CompressionMethod.none; - } - } - return msg; - }; - tls.createSecurityParameters = function(c, msg) { - var client = c.entity === tls.ConnectionEnd.client; - var msgRandom = msg.random.bytes(); - var cRandom = client ? c.session.sp.client_random : msgRandom; - var sRandom = client ? msgRandom : tls.createRandom().getBytes(); - c.session.sp = { - entity: c.entity, - prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256, - bulk_cipher_algorithm: null, - cipher_type: null, - enc_key_length: null, - block_length: null, - fixed_iv_length: null, - record_iv_length: null, - mac_algorithm: null, - mac_length: null, - mac_key_length: null, - compression_algorithm: c.session.compressionMethod, - pre_master_secret: null, - master_secret: null, - client_random: cRandom, - server_random: sRandom - }; - }; - tls.handleServerHello = function(c, record, length) { - var msg = tls.parseHelloMessage(c, record, length); - if (c.fail) { - return; - } - if (msg.version.minor <= c.version.minor) { - c.version.minor = msg.version.minor; - } else { - return c.error(c, { - message: "Incompatible TLS version.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.protocol_version - } - }); - } - c.session.version = c.version; - var sessionId = msg.session_id.bytes(); - if (sessionId.length > 0 && sessionId === c.session.id) { - c.expect = SCC; - c.session.resuming = true; - c.session.sp.server_random = msg.random.bytes(); - } else { - c.expect = SCE; - c.session.resuming = false; - tls.createSecurityParameters(c, msg); - } - c.session.id = sessionId; - c.process(); - }; - tls.handleClientHello = function(c, record, length) { - var msg = tls.parseHelloMessage(c, record, length); - if (c.fail) { - return; - } - var sessionId = msg.session_id.bytes(); - var session = null; - if (c.sessionCache) { - session = c.sessionCache.getSession(sessionId); - if (session === null) { - sessionId = ""; - } else if (session.version.major !== msg.version.major || session.version.minor > msg.version.minor) { - session = null; - sessionId = ""; - } - } - if (sessionId.length === 0) { - sessionId = forge2.random.getBytes(32); - } - c.session.id = sessionId; - c.session.clientHelloVersion = msg.version; - c.session.sp = {}; - if (session) { - c.version = c.session.version = session.version; - c.session.sp = session.sp; - } else { - var version; - for (var i = 1; i < tls.SupportedVersions.length; ++i) { - version = tls.SupportedVersions[i]; - if (version.minor <= msg.version.minor) { - break; - } - } - c.version = { major: version.major, minor: version.minor }; - c.session.version = c.version; - } - if (session !== null) { - c.expect = CCC; - c.session.resuming = true; - c.session.sp.client_random = msg.random.bytes(); - } else { - c.expect = c.verifyClient !== false ? CCE : CKE; - c.session.resuming = false; - tls.createSecurityParameters(c, msg); - } - c.open = true; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createServerHello(c) - })); - if (c.session.resuming) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.change_cipher_spec, - data: tls.createChangeCipherSpec() - })); - c.state.pending = tls.createConnectionState(c); - c.state.current.write = c.state.pending.write; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createFinished(c) - })); - } else { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createCertificate(c) - })); - if (!c.fail) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createServerKeyExchange(c) - })); - if (c.verifyClient !== false) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createCertificateRequest(c) - })); - } - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createServerHelloDone(c) - })); - } - } - tls.flush(c); - c.process(); - }; - tls.handleCertificate = function(c, record, length) { - if (length < 3) { - return c.error(c, { - message: "Invalid Certificate message. Message too short.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } - var b = record.fragment; - var msg = { - certificate_list: readVector(b, 3) - }; - var cert, asn1; - var certs = []; - try { - while (msg.certificate_list.length() > 0) { - cert = readVector(msg.certificate_list, 3); - asn1 = forge2.asn1.fromDer(cert); - cert = forge2.pki.certificateFromAsn1(asn1, true); - certs.push(cert); - } - } catch (ex) { - return c.error(c, { - message: "Could not parse certificate list.", - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.bad_certificate - } - }); - } - var client = c.entity === tls.ConnectionEnd.client; - if ((client || c.verifyClient === true) && certs.length === 0) { - c.error(c, { - message: client ? "No server certificate provided." : "No client certificate provided.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } else if (certs.length === 0) { - c.expect = client ? SKE : CKE; - } else { - if (client) { - c.session.serverCertificate = certs[0]; - } else { - c.session.clientCertificate = certs[0]; - } - if (tls.verifyCertificateChain(c, certs)) { - c.expect = client ? SKE : CKE; - } - } - c.process(); - }; - tls.handleServerKeyExchange = function(c, record, length) { - if (length > 0) { - return c.error(c, { - message: "Invalid key parameters. Only RSA is supported.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unsupported_certificate - } - }); - } - c.expect = SCR; - c.process(); - }; - tls.handleClientKeyExchange = function(c, record, length) { - if (length < 48) { - return c.error(c, { - message: "Invalid key parameters. Only RSA is supported.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unsupported_certificate - } - }); - } - var b = record.fragment; - var msg = { - enc_pre_master_secret: readVector(b, 2).getBytes() - }; - var privateKey = null; - if (c.getPrivateKey) { - try { - privateKey = c.getPrivateKey(c, c.session.serverCertificate); - privateKey = forge2.pki.privateKeyFromPem(privateKey); - } catch (ex) { - c.error(c, { - message: "Could not get private key.", - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } - } - if (privateKey === null) { - return c.error(c, { - message: "No private key set.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } - try { - var sp = c.session.sp; - sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret); - var version = c.session.clientHelloVersion; - if (version.major !== sp.pre_master_secret.charCodeAt(0) || version.minor !== sp.pre_master_secret.charCodeAt(1)) { - throw new Error("TLS version rollback attack detected."); - } - } catch (ex) { - sp.pre_master_secret = forge2.random.getBytes(48); - } - c.expect = CCC; - if (c.session.clientCertificate !== null) { - c.expect = CCV; - } - c.process(); - }; - tls.handleCertificateRequest = function(c, record, length) { - if (length < 3) { - return c.error(c, { - message: "Invalid CertificateRequest. Message too short.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } - var b = record.fragment; - var msg = { - certificate_types: readVector(b, 1), - certificate_authorities: readVector(b, 2) - }; - c.session.certificateRequest = msg; - c.expect = SHD; - c.process(); - }; - tls.handleCertificateVerify = function(c, record, length) { - if (length < 2) { - return c.error(c, { - message: "Invalid CertificateVerify. Message too short.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } - var b = record.fragment; - b.read -= 4; - var msgBytes = b.bytes(); - b.read += 4; - var msg = { - signature: readVector(b, 2).getBytes() - }; - var verify = forge2.util.createBuffer(); - verify.putBuffer(c.session.md5.digest()); - verify.putBuffer(c.session.sha1.digest()); - verify = verify.getBytes(); - try { - var cert = c.session.clientCertificate; - if (!cert.publicKey.verify(verify, msg.signature, "NONE")) { - throw new Error("CertificateVerify signature does not match."); - } - c.session.md5.update(msgBytes); - c.session.sha1.update(msgBytes); - } catch (ex) { - return c.error(c, { - message: "Bad signature in CertificateVerify.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.handshake_failure - } - }); - } - c.expect = CCC; - c.process(); - }; - tls.handleServerHelloDone = function(c, record, length) { - if (length > 0) { - return c.error(c, { - message: "Invalid ServerHelloDone message. Invalid length.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.record_overflow - } - }); - } - if (c.serverCertificate === null) { - var error = { - message: "No server certificate provided. Not enough security.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.insufficient_security - } - }; - var depth = 0; - var ret = c.verify(c, error.alert.description, depth, []); - if (ret !== true) { - if (ret || ret === 0) { - if (typeof ret === "object" && !forge2.util.isArray(ret)) { - if (ret.message) { - error.message = ret.message; - } - if (ret.alert) { - error.alert.description = ret.alert; - } - } else if (typeof ret === "number") { - error.alert.description = ret; - } - } - return c.error(c, error); - } - } - if (c.session.certificateRequest !== null) { - record = tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createCertificate(c) - }); - tls.queue(c, record); - } - record = tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createClientKeyExchange(c) - }); - tls.queue(c, record); - c.expect = SER; - var callback = function(c2, signature) { - if (c2.session.certificateRequest !== null && c2.session.clientCertificate !== null) { - tls.queue(c2, tls.createRecord(c2, { - type: tls.ContentType.handshake, - data: tls.createCertificateVerify(c2, signature) - })); - } - tls.queue(c2, tls.createRecord(c2, { - type: tls.ContentType.change_cipher_spec, - data: tls.createChangeCipherSpec() - })); - c2.state.pending = tls.createConnectionState(c2); - c2.state.current.write = c2.state.pending.write; - tls.queue(c2, tls.createRecord(c2, { - type: tls.ContentType.handshake, - data: tls.createFinished(c2) - })); - c2.expect = SCC; - tls.flush(c2); - c2.process(); - }; - if (c.session.certificateRequest === null || c.session.clientCertificate === null) { - return callback(c, null); - } - tls.getClientSignature(c, callback); - }; - tls.handleChangeCipherSpec = function(c, record) { - if (record.fragment.getByte() !== 1) { - return c.error(c, { - message: "Invalid ChangeCipherSpec message received.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.illegal_parameter - } - }); - } - var client = c.entity === tls.ConnectionEnd.client; - if (c.session.resuming && client || !c.session.resuming && !client) { - c.state.pending = tls.createConnectionState(c); - } - c.state.current.read = c.state.pending.read; - if (!c.session.resuming && client || c.session.resuming && !client) { - c.state.pending = null; - } - c.expect = client ? SFI : CFI; - c.process(); - }; - tls.handleFinished = function(c, record, length) { - var b = record.fragment; - b.read -= 4; - var msgBytes = b.bytes(); - b.read += 4; - var vd = record.fragment.getBytes(); - b = forge2.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); - var client = c.entity === tls.ConnectionEnd.client; - var label = client ? "server finished" : "client finished"; - var sp = c.session.sp; - var vdl = 12; - var prf = prf_TLS1; - b = prf(sp.master_secret, label, b.getBytes(), vdl); - if (b.getBytes() !== vd) { - return c.error(c, { - message: "Invalid verify_data in Finished message.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.decrypt_error - } - }); - } - c.session.md5.update(msgBytes); - c.session.sha1.update(msgBytes); - if (c.session.resuming && client || !c.session.resuming && !client) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.change_cipher_spec, - data: tls.createChangeCipherSpec() - })); - c.state.current.write = c.state.pending.write; - c.state.pending = null; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createFinished(c) - })); - } - c.expect = client ? SAD : CAD; - c.handshaking = false; - ++c.handshakes; - c.peerCertificate = client ? c.session.serverCertificate : c.session.clientCertificate; - tls.flush(c); - c.isConnected = true; - c.connected(c); - c.process(); - }; - tls.handleAlert = function(c, record) { - var b = record.fragment; - var alert = { - level: b.getByte(), - description: b.getByte() - }; - var msg; - switch (alert.description) { - case tls.Alert.Description.close_notify: - msg = "Connection closed."; - break; - case tls.Alert.Description.unexpected_message: - msg = "Unexpected message."; - break; - case tls.Alert.Description.bad_record_mac: - msg = "Bad record MAC."; - break; - case tls.Alert.Description.decryption_failed: - msg = "Decryption failed."; - break; - case tls.Alert.Description.record_overflow: - msg = "Record overflow."; - break; - case tls.Alert.Description.decompression_failure: - msg = "Decompression failed."; - break; - case tls.Alert.Description.handshake_failure: - msg = "Handshake failure."; - break; - case tls.Alert.Description.bad_certificate: - msg = "Bad certificate."; - break; - case tls.Alert.Description.unsupported_certificate: - msg = "Unsupported certificate."; - break; - case tls.Alert.Description.certificate_revoked: - msg = "Certificate revoked."; - break; - case tls.Alert.Description.certificate_expired: - msg = "Certificate expired."; - break; - case tls.Alert.Description.certificate_unknown: - msg = "Certificate unknown."; - break; - case tls.Alert.Description.illegal_parameter: - msg = "Illegal parameter."; - break; - case tls.Alert.Description.unknown_ca: - msg = "Unknown certificate authority."; - break; - case tls.Alert.Description.access_denied: - msg = "Access denied."; - break; - case tls.Alert.Description.decode_error: - msg = "Decode error."; - break; - case tls.Alert.Description.decrypt_error: - msg = "Decrypt error."; - break; - case tls.Alert.Description.export_restriction: - msg = "Export restriction."; - break; - case tls.Alert.Description.protocol_version: - msg = "Unsupported protocol version."; - break; - case tls.Alert.Description.insufficient_security: - msg = "Insufficient security."; - break; - case tls.Alert.Description.internal_error: - msg = "Internal error."; - break; - case tls.Alert.Description.user_canceled: - msg = "User canceled."; - break; - case tls.Alert.Description.no_renegotiation: - msg = "Renegotiation not supported."; - break; - default: - msg = "Unknown error."; - break; - } - if (alert.description === tls.Alert.Description.close_notify) { - return c.close(); - } - c.error(c, { - message: msg, - send: false, - // origin is the opposite end - origin: c.entity === tls.ConnectionEnd.client ? "server" : "client", - alert - }); - c.process(); - }; - tls.handleHandshake = function(c, record) { - var b = record.fragment; - var type = b.getByte(); - var length = b.getInt24(); - if (length > b.length()) { - c.fragmented = record; - record.fragment = forge2.util.createBuffer(); - b.read -= 4; - return c.process(); - } - c.fragmented = null; - b.read -= 4; - var bytes = b.bytes(length + 4); - b.read += 4; - if (type in hsTable[c.entity][c.expect]) { - if (c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) { - c.handshaking = true; - c.session = { - version: null, - extensions: { - server_name: { - serverNameList: [] - } - }, - cipherSuite: null, - compressionMethod: null, - serverCertificate: null, - clientCertificate: null, - md5: forge2.md.md5.create(), - sha1: forge2.md.sha1.create() - }; - } - if (type !== tls.HandshakeType.hello_request && type !== tls.HandshakeType.certificate_verify && type !== tls.HandshakeType.finished) { - c.session.md5.update(bytes); - c.session.sha1.update(bytes); - } - hsTable[c.entity][c.expect][type](c, record, length); - } else { - tls.handleUnexpected(c, record); - } - }; - tls.handleApplicationData = function(c, record) { - c.data.putBuffer(record.fragment); - c.dataReady(c); - c.process(); - }; - tls.handleHeartbeat = function(c, record) { - var b = record.fragment; - var type = b.getByte(); - var length = b.getInt16(); - var payload = b.getBytes(length); - if (type === tls.HeartbeatMessageType.heartbeat_request) { - if (c.handshaking || length > payload.length) { - return c.process(); - } - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.heartbeat, - data: tls.createHeartbeat( - tls.HeartbeatMessageType.heartbeat_response, - payload - ) - })); - tls.flush(c); - } else if (type === tls.HeartbeatMessageType.heartbeat_response) { - if (payload !== c.expectedHeartbeatPayload) { - return c.process(); - } - if (c.heartbeatReceived) { - c.heartbeatReceived(c, forge2.util.createBuffer(payload)); - } - } - c.process(); - }; - var SHE = 0; - var SCE = 1; - var SKE = 2; - var SCR = 3; - var SHD = 4; - var SCC = 5; - var SFI = 6; - var SAD = 7; - var SER = 8; - var CHE = 0; - var CCE = 1; - var CKE = 2; - var CCV = 3; - var CCC = 4; - var CFI = 5; - var CAD = 6; - var __ = tls.handleUnexpected; - var R0 = tls.handleChangeCipherSpec; - var R1 = tls.handleAlert; - var R2 = tls.handleHandshake; - var R3 = tls.handleApplicationData; - var R4 = tls.handleHeartbeat; - var ctTable = []; - ctTable[tls.ConnectionEnd.client] = [ - // CC,AL,HS,AD,HB - /*SHE*/ - [__, R1, R2, __, R4], - /*SCE*/ - [__, R1, R2, __, R4], - /*SKE*/ - [__, R1, R2, __, R4], - /*SCR*/ - [__, R1, R2, __, R4], - /*SHD*/ - [__, R1, R2, __, R4], - /*SCC*/ - [R0, R1, __, __, R4], - /*SFI*/ - [__, R1, R2, __, R4], - /*SAD*/ - [__, R1, R2, R3, R4], - /*SER*/ - [__, R1, R2, __, R4] - ]; - ctTable[tls.ConnectionEnd.server] = [ - // CC,AL,HS,AD - /*CHE*/ - [__, R1, R2, __, R4], - /*CCE*/ - [__, R1, R2, __, R4], - /*CKE*/ - [__, R1, R2, __, R4], - /*CCV*/ - [__, R1, R2, __, R4], - /*CCC*/ - [R0, R1, __, __, R4], - /*CFI*/ - [__, R1, R2, __, R4], - /*CAD*/ - [__, R1, R2, R3, R4], - /*CER*/ - [__, R1, R2, __, R4] - ]; - var H0 = tls.handleHelloRequest; - var H1 = tls.handleServerHello; - var H2 = tls.handleCertificate; - var H3 = tls.handleServerKeyExchange; - var H4 = tls.handleCertificateRequest; - var H5 = tls.handleServerHelloDone; - var H6 = tls.handleFinished; - var hsTable = []; - hsTable[tls.ConnectionEnd.client] = [ - // HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI - /*SHE*/ - [__, __, H1, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*SCE*/ - [H0, __, __, __, __, __, __, __, __, __, __, H2, H3, H4, H5, __, __, __, __, __, __], - /*SKE*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, H3, H4, H5, __, __, __, __, __, __], - /*SCR*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, H4, H5, __, __, __, __, __, __], - /*SHD*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, H5, __, __, __, __, __, __], - /*SCC*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*SFI*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6], - /*SAD*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*SER*/ - [H0, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] - ]; - var H7 = tls.handleClientHello; - var H8 = tls.handleClientKeyExchange; - var H9 = tls.handleCertificateVerify; - hsTable[tls.ConnectionEnd.server] = [ - // 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI - /*CHE*/ - [__, H7, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*CCE*/ - [__, __, __, __, __, __, __, __, __, __, __, H2, __, __, __, __, __, __, __, __, __], - /*CKE*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H8, __, __, __, __], - /*CCV*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H9, __, __, __, __, __], - /*CCC*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*CFI*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, H6], - /*CAD*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __], - /*CER*/ - [__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __] - ]; - tls.generateKeys = function(c, sp) { - var prf = prf_TLS1; - var random = sp.client_random + sp.server_random; - if (!c.session.resuming) { - sp.master_secret = prf( - sp.pre_master_secret, - "master secret", - random, - 48 - ).bytes(); - sp.pre_master_secret = null; - } - random = sp.server_random + sp.client_random; - var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length; - var tls10 = c.version.major === tls.Versions.TLS_1_0.major && c.version.minor === tls.Versions.TLS_1_0.minor; - if (tls10) { - length += 2 * sp.fixed_iv_length; - } - var km = prf(sp.master_secret, "key expansion", random, length); - var rval = { - client_write_MAC_key: km.getBytes(sp.mac_key_length), - server_write_MAC_key: km.getBytes(sp.mac_key_length), - client_write_key: km.getBytes(sp.enc_key_length), - server_write_key: km.getBytes(sp.enc_key_length) - }; - if (tls10) { - rval.client_write_IV = km.getBytes(sp.fixed_iv_length); - rval.server_write_IV = km.getBytes(sp.fixed_iv_length); - } - return rval; - }; - tls.createConnectionState = function(c) { - var client = c.entity === tls.ConnectionEnd.client; - var createMode = function() { - var mode = { - // two 32-bit numbers, first is most significant - sequenceNumber: [0, 0], - macKey: null, - macLength: 0, - macFunction: null, - cipherState: null, - cipherFunction: function(record) { - return true; - }, - compressionState: null, - compressFunction: function(record) { - return true; - }, - updateSequenceNumber: function() { - if (mode.sequenceNumber[1] === 4294967295) { - mode.sequenceNumber[1] = 0; - ++mode.sequenceNumber[0]; - } else { - ++mode.sequenceNumber[1]; - } - } - }; - return mode; - }; - var state = { - read: createMode(), - write: createMode() - }; - state.read.update = function(c2, record) { - if (!state.read.cipherFunction(record, state.read)) { - c2.error(c2, { - message: "Could not decrypt record or bad MAC.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - // doesn't matter if decryption failed or MAC was - // invalid, return the same error so as not to reveal - // which one occurred - description: tls.Alert.Description.bad_record_mac - } - }); - } else if (!state.read.compressFunction(c2, record, state.read)) { - c2.error(c2, { - message: "Could not decompress record.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.decompression_failure - } - }); - } - return !c2.fail; - }; - state.write.update = function(c2, record) { - if (!state.write.compressFunction(c2, record, state.write)) { - c2.error(c2, { - message: "Could not compress record.", - send: false, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } else if (!state.write.cipherFunction(record, state.write)) { - c2.error(c2, { - message: "Could not encrypt record.", - send: false, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } - return !c2.fail; - }; - if (c.session) { - var sp = c.session.sp; - c.session.cipherSuite.initSecurityParameters(sp); - sp.keys = tls.generateKeys(c, sp); - state.read.macKey = client ? sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key; - state.write.macKey = client ? sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key; - c.session.cipherSuite.initConnectionState(state, c, sp); - switch (sp.compression_algorithm) { - case tls.CompressionMethod.none: - break; - case tls.CompressionMethod.deflate: - state.read.compressFunction = inflate; - state.write.compressFunction = deflate; - break; - default: - throw new Error("Unsupported compression algorithm."); - } - } - return state; - }; - tls.createRandom = function() { - var d = /* @__PURE__ */ new Date(); - var utc = +d + d.getTimezoneOffset() * 6e4; - var rval = forge2.util.createBuffer(); - rval.putInt32(utc); - rval.putBytes(forge2.random.getBytes(28)); - return rval; - }; - tls.createRecord = function(c, options) { - if (!options.data) { - return null; - } - var record = { - type: options.type, - version: { - major: c.version.major, - minor: c.version.minor - }, - length: options.data.length(), - fragment: options.data - }; - return record; - }; - tls.createAlert = function(c, alert) { - var b = forge2.util.createBuffer(); - b.putByte(alert.level); - b.putByte(alert.description); - return tls.createRecord(c, { - type: tls.ContentType.alert, - data: b - }); - }; - tls.createClientHello = function(c) { - c.session.clientHelloVersion = { - major: c.version.major, - minor: c.version.minor - }; - var cipherSuites = forge2.util.createBuffer(); - for (var i = 0; i < c.cipherSuites.length; ++i) { - var cs = c.cipherSuites[i]; - cipherSuites.putByte(cs.id[0]); - cipherSuites.putByte(cs.id[1]); - } - var cSuites = cipherSuites.length(); - var compressionMethods = forge2.util.createBuffer(); - compressionMethods.putByte(tls.CompressionMethod.none); - var cMethods = compressionMethods.length(); - var extensions = forge2.util.createBuffer(); - if (c.virtualHost) { - var ext = forge2.util.createBuffer(); - ext.putByte(0); - ext.putByte(0); - var serverName = forge2.util.createBuffer(); - serverName.putByte(0); - writeVector(serverName, 2, forge2.util.createBuffer(c.virtualHost)); - var snList = forge2.util.createBuffer(); - writeVector(snList, 2, serverName); - writeVector(ext, 2, snList); - extensions.putBuffer(ext); - } - var extLength = extensions.length(); - if (extLength > 0) { - extLength += 2; - } - var sessionId = c.session.id; - var length = sessionId.length + 1 + // session ID vector - 2 + // version (major + minor) - 4 + 28 + // random time and random bytes - 2 + cSuites + // cipher suites vector - 1 + cMethods + // compression methods vector - extLength; - var rval = forge2.util.createBuffer(); - rval.putByte(tls.HandshakeType.client_hello); - rval.putInt24(length); - rval.putByte(c.version.major); - rval.putByte(c.version.minor); - rval.putBytes(c.session.sp.client_random); - writeVector(rval, 1, forge2.util.createBuffer(sessionId)); - writeVector(rval, 2, cipherSuites); - writeVector(rval, 1, compressionMethods); - if (extLength > 0) { - writeVector(rval, 2, extensions); - } - return rval; - }; - tls.createServerHello = function(c) { - var sessionId = c.session.id; - var length = sessionId.length + 1 + // session ID vector - 2 + // version (major + minor) - 4 + 28 + // random time and random bytes - 2 + // chosen cipher suite - 1; - var rval = forge2.util.createBuffer(); - rval.putByte(tls.HandshakeType.server_hello); - rval.putInt24(length); - rval.putByte(c.version.major); - rval.putByte(c.version.minor); - rval.putBytes(c.session.sp.server_random); - writeVector(rval, 1, forge2.util.createBuffer(sessionId)); - rval.putByte(c.session.cipherSuite.id[0]); - rval.putByte(c.session.cipherSuite.id[1]); - rval.putByte(c.session.compressionMethod); - return rval; - }; - tls.createCertificate = function(c) { - var client = c.entity === tls.ConnectionEnd.client; - var cert = null; - if (c.getCertificate) { - var hint; - if (client) { - hint = c.session.certificateRequest; - } else { - hint = c.session.extensions.server_name.serverNameList; - } - cert = c.getCertificate(c, hint); - } - var certList = forge2.util.createBuffer(); - if (cert !== null) { - try { - if (!forge2.util.isArray(cert)) { - cert = [cert]; - } - var asn1 = null; - for (var i = 0; i < cert.length; ++i) { - var msg = forge2.pem.decode(cert[i])[0]; - if (msg.type !== "CERTIFICATE" && msg.type !== "X509 CERTIFICATE" && msg.type !== "TRUSTED CERTIFICATE") { - var error = new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".'); - error.headerType = msg.type; - throw error; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert certificate from PEM; PEM is encrypted."); - } - var der = forge2.util.createBuffer(msg.body); - if (asn1 === null) { - asn1 = forge2.asn1.fromDer(der.bytes(), false); - } - var certBuffer = forge2.util.createBuffer(); - writeVector(certBuffer, 3, der); - certList.putBuffer(certBuffer); - } - cert = forge2.pki.certificateFromAsn1(asn1); - if (client) { - c.session.clientCertificate = cert; - } else { - c.session.serverCertificate = cert; - } - } catch (ex) { - return c.error(c, { - message: "Could not send certificate list.", - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.bad_certificate - } - }); - } - } - var length = 3 + certList.length(); - var rval = forge2.util.createBuffer(); - rval.putByte(tls.HandshakeType.certificate); - rval.putInt24(length); - writeVector(rval, 3, certList); - return rval; - }; - tls.createClientKeyExchange = function(c) { - var b = forge2.util.createBuffer(); - b.putByte(c.session.clientHelloVersion.major); - b.putByte(c.session.clientHelloVersion.minor); - b.putBytes(forge2.random.getBytes(46)); - var sp = c.session.sp; - sp.pre_master_secret = b.getBytes(); - var key2 = c.session.serverCertificate.publicKey; - b = key2.encrypt(sp.pre_master_secret); - var length = b.length + 2; - var rval = forge2.util.createBuffer(); - rval.putByte(tls.HandshakeType.client_key_exchange); - rval.putInt24(length); - rval.putInt16(b.length); - rval.putBytes(b); - return rval; - }; - tls.createServerKeyExchange = function(c) { - var length = 0; - var rval = forge2.util.createBuffer(); - if (length > 0) { - rval.putByte(tls.HandshakeType.server_key_exchange); - rval.putInt24(length); - } - return rval; - }; - tls.getClientSignature = function(c, callback) { - var b = forge2.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); - b = b.getBytes(); - c.getSignature = c.getSignature || function(c2, b2, callback2) { - var privateKey = null; - if (c2.getPrivateKey) { - try { - privateKey = c2.getPrivateKey(c2, c2.session.clientCertificate); - privateKey = forge2.pki.privateKeyFromPem(privateKey); - } catch (ex) { - c2.error(c2, { - message: "Could not get private key.", - cause: ex, - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } - } - if (privateKey === null) { - c2.error(c2, { - message: "No private key set.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.internal_error - } - }); - } else { - b2 = privateKey.sign(b2, null); - } - callback2(c2, b2); - }; - c.getSignature(c, b, callback); - }; - tls.createCertificateVerify = function(c, signature) { - var length = signature.length + 2; - var rval = forge2.util.createBuffer(); - rval.putByte(tls.HandshakeType.certificate_verify); - rval.putInt24(length); - rval.putInt16(signature.length); - rval.putBytes(signature); - return rval; - }; - tls.createCertificateRequest = function(c) { - var certTypes = forge2.util.createBuffer(); - certTypes.putByte(1); - var cAs = forge2.util.createBuffer(); - for (var key2 in c.caStore.certs) { - var cert = c.caStore.certs[key2]; - var dn = forge2.pki.distinguishedNameToAsn1(cert.subject); - var byteBuffer = forge2.asn1.toDer(dn); - cAs.putInt16(byteBuffer.length()); - cAs.putBuffer(byteBuffer); - } - var length = 1 + certTypes.length() + 2 + cAs.length(); - var rval = forge2.util.createBuffer(); - rval.putByte(tls.HandshakeType.certificate_request); - rval.putInt24(length); - writeVector(rval, 1, certTypes); - writeVector(rval, 2, cAs); - return rval; - }; - tls.createServerHelloDone = function(c) { - var rval = forge2.util.createBuffer(); - rval.putByte(tls.HandshakeType.server_hello_done); - rval.putInt24(0); - return rval; - }; - tls.createChangeCipherSpec = function() { - var rval = forge2.util.createBuffer(); - rval.putByte(1); - return rval; - }; - tls.createFinished = function(c) { - var b = forge2.util.createBuffer(); - b.putBuffer(c.session.md5.digest()); - b.putBuffer(c.session.sha1.digest()); - var client = c.entity === tls.ConnectionEnd.client; - var sp = c.session.sp; - var vdl = 12; - var prf = prf_TLS1; - var label = client ? "client finished" : "server finished"; - b = prf(sp.master_secret, label, b.getBytes(), vdl); - var rval = forge2.util.createBuffer(); - rval.putByte(tls.HandshakeType.finished); - rval.putInt24(b.length()); - rval.putBuffer(b); - return rval; - }; - tls.createHeartbeat = function(type, payload, payloadLength) { - if (typeof payloadLength === "undefined") { - payloadLength = payload.length; - } - var rval = forge2.util.createBuffer(); - rval.putByte(type); - rval.putInt16(payloadLength); - rval.putBytes(payload); - var plaintextLength = rval.length(); - var paddingLength = Math.max(16, plaintextLength - payloadLength - 3); - rval.putBytes(forge2.random.getBytes(paddingLength)); - return rval; - }; - tls.queue = function(c, record) { - if (!record) { - return; - } - if (record.fragment.length() === 0) { - if (record.type === tls.ContentType.handshake || record.type === tls.ContentType.alert || record.type === tls.ContentType.change_cipher_spec) { - return; - } - } - if (record.type === tls.ContentType.handshake) { - var bytes = record.fragment.bytes(); - c.session.md5.update(bytes); - c.session.sha1.update(bytes); - bytes = null; - } - var records; - if (record.fragment.length() <= tls.MaxFragment) { - records = [record]; - } else { - records = []; - var data = record.fragment.bytes(); - while (data.length > tls.MaxFragment) { - records.push(tls.createRecord(c, { - type: record.type, - data: forge2.util.createBuffer(data.slice(0, tls.MaxFragment)) - })); - data = data.slice(tls.MaxFragment); - } - if (data.length > 0) { - records.push(tls.createRecord(c, { - type: record.type, - data: forge2.util.createBuffer(data) - })); - } - } - for (var i = 0; i < records.length && !c.fail; ++i) { - var rec = records[i]; - var s = c.state.current.write; - if (s.update(c, rec)) { - c.records.push(rec); - } - } - }; - tls.flush = function(c) { - for (var i = 0; i < c.records.length; ++i) { - var record = c.records[i]; - c.tlsData.putByte(record.type); - c.tlsData.putByte(record.version.major); - c.tlsData.putByte(record.version.minor); - c.tlsData.putInt16(record.fragment.length()); - c.tlsData.putBuffer(c.records[i].fragment); - } - c.records = []; - return c.tlsDataReady(c); - }; - var _certErrorToAlertDesc = function(error) { - switch (error) { - case true: - return true; - case forge2.pki.certificateError.bad_certificate: - return tls.Alert.Description.bad_certificate; - case forge2.pki.certificateError.unsupported_certificate: - return tls.Alert.Description.unsupported_certificate; - case forge2.pki.certificateError.certificate_revoked: - return tls.Alert.Description.certificate_revoked; - case forge2.pki.certificateError.certificate_expired: - return tls.Alert.Description.certificate_expired; - case forge2.pki.certificateError.certificate_unknown: - return tls.Alert.Description.certificate_unknown; - case forge2.pki.certificateError.unknown_ca: - return tls.Alert.Description.unknown_ca; - default: - return tls.Alert.Description.bad_certificate; - } - }; - var _alertDescToCertError = function(desc) { - switch (desc) { - case true: - return true; - case tls.Alert.Description.bad_certificate: - return forge2.pki.certificateError.bad_certificate; - case tls.Alert.Description.unsupported_certificate: - return forge2.pki.certificateError.unsupported_certificate; - case tls.Alert.Description.certificate_revoked: - return forge2.pki.certificateError.certificate_revoked; - case tls.Alert.Description.certificate_expired: - return forge2.pki.certificateError.certificate_expired; - case tls.Alert.Description.certificate_unknown: - return forge2.pki.certificateError.certificate_unknown; - case tls.Alert.Description.unknown_ca: - return forge2.pki.certificateError.unknown_ca; - default: - return forge2.pki.certificateError.bad_certificate; - } - }; - tls.verifyCertificateChain = function(c, chain) { - try { - var options = {}; - for (var key2 in c.verifyOptions) { - options[key2] = c.verifyOptions[key2]; - } - options.verify = function(vfd, depth, chain2) { - var desc = _certErrorToAlertDesc(vfd); - var ret = c.verify(c, vfd, depth, chain2); - if (ret !== true) { - if (typeof ret === "object" && !forge2.util.isArray(ret)) { - var error = new Error("The application rejected the certificate."); - error.send = true; - error.alert = { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.bad_certificate - }; - if (ret.message) { - error.message = ret.message; - } - if (ret.alert) { - error.alert.description = ret.alert; - } - throw error; - } - if (ret !== vfd) { - ret = _alertDescToCertError(ret); - } - } - return ret; - }; - forge2.pki.verifyCertificateChain(c.caStore, chain, options); - } catch (ex) { - var err = ex; - if (typeof err !== "object" || forge2.util.isArray(err)) { - err = { - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: _certErrorToAlertDesc(ex) - } - }; - } - if (!("send" in err)) { - err.send = true; - } - if (!("alert" in err)) { - err.alert = { - level: tls.Alert.Level.fatal, - description: _certErrorToAlertDesc(err.error) - }; - } - c.error(c, err); - } - return !c.fail; - }; - tls.createSessionCache = function(cache, capacity) { - var rval = null; - if (cache && cache.getSession && cache.setSession && cache.order) { - rval = cache; - } else { - rval = {}; - rval.cache = cache || {}; - rval.capacity = Math.max(capacity || 100, 1); - rval.order = []; - for (var key2 in cache) { - if (rval.order.length <= capacity) { - rval.order.push(key2); - } else { - delete cache[key2]; - } - } - rval.getSession = function(sessionId) { - var session = null; - var key3 = null; - if (sessionId) { - key3 = forge2.util.bytesToHex(sessionId); - } else if (rval.order.length > 0) { - key3 = rval.order[0]; - } - if (key3 !== null && key3 in rval.cache) { - session = rval.cache[key3]; - delete rval.cache[key3]; - for (var i in rval.order) { - if (rval.order[i] === key3) { - rval.order.splice(i, 1); - break; - } - } - } - return session; - }; - rval.setSession = function(sessionId, session) { - if (rval.order.length === rval.capacity) { - var key3 = rval.order.shift(); - delete rval.cache[key3]; - } - var key3 = forge2.util.bytesToHex(sessionId); - rval.order.push(key3); - rval.cache[key3] = session; - }; - } - return rval; - }; - tls.createConnection = function(options) { - var caStore = null; - if (options.caStore) { - if (forge2.util.isArray(options.caStore)) { - caStore = forge2.pki.createCaStore(options.caStore); - } else { - caStore = options.caStore; - } - } else { - caStore = forge2.pki.createCaStore(); - } - var cipherSuites = options.cipherSuites || null; - if (cipherSuites === null) { - cipherSuites = []; - for (var key2 in tls.CipherSuites) { - cipherSuites.push(tls.CipherSuites[key2]); - } - } - var entity = options.server || false ? tls.ConnectionEnd.server : tls.ConnectionEnd.client; - var sessionCache = options.sessionCache ? tls.createSessionCache(options.sessionCache) : null; - var c = { - version: { major: tls.Version.major, minor: tls.Version.minor }, - entity, - sessionId: options.sessionId, - caStore, - sessionCache, - cipherSuites, - connected: options.connected, - virtualHost: options.virtualHost || null, - verifyClient: options.verifyClient || false, - verify: options.verify || function(cn, vfd, dpth, cts) { - return vfd; - }, - verifyOptions: options.verifyOptions || {}, - getCertificate: options.getCertificate || null, - getPrivateKey: options.getPrivateKey || null, - getSignature: options.getSignature || null, - input: forge2.util.createBuffer(), - tlsData: forge2.util.createBuffer(), - data: forge2.util.createBuffer(), - tlsDataReady: options.tlsDataReady, - dataReady: options.dataReady, - heartbeatReceived: options.heartbeatReceived, - closed: options.closed, - error: function(c2, ex) { - ex.origin = ex.origin || (c2.entity === tls.ConnectionEnd.client ? "client" : "server"); - if (ex.send) { - tls.queue(c2, tls.createAlert(c2, ex.alert)); - tls.flush(c2); - } - var fatal = ex.fatal !== false; - if (fatal) { - c2.fail = true; - } - options.error(c2, ex); - if (fatal) { - c2.close(false); - } - }, - deflate: options.deflate || null, - inflate: options.inflate || null - }; - c.reset = function(clearFail) { - c.version = { major: tls.Version.major, minor: tls.Version.minor }; - c.record = null; - c.session = null; - c.peerCertificate = null; - c.state = { - pending: null, - current: null - }; - c.expect = c.entity === tls.ConnectionEnd.client ? SHE : CHE; - c.fragmented = null; - c.records = []; - c.open = false; - c.handshakes = 0; - c.handshaking = false; - c.isConnected = false; - c.fail = !(clearFail || typeof clearFail === "undefined"); - c.input.clear(); - c.tlsData.clear(); - c.data.clear(); - c.state.current = tls.createConnectionState(c); - }; - c.reset(); - var _update = function(c2, record) { - var aligned = record.type - tls.ContentType.change_cipher_spec; - var handlers = ctTable[c2.entity][c2.expect]; - if (aligned in handlers) { - handlers[aligned](c2, record); - } else { - tls.handleUnexpected(c2, record); - } - }; - var _readRecordHeader = function(c2) { - var rval = 0; - var b = c2.input; - var len = b.length(); - if (len < 5) { - rval = 5 - len; - } else { - c2.record = { - type: b.getByte(), - version: { - major: b.getByte(), - minor: b.getByte() - }, - length: b.getInt16(), - fragment: forge2.util.createBuffer(), - ready: false - }; - var compatibleVersion = c2.record.version.major === c2.version.major; - if (compatibleVersion && c2.session && c2.session.version) { - compatibleVersion = c2.record.version.minor === c2.version.minor; - } - if (!compatibleVersion) { - c2.error(c2, { - message: "Incompatible TLS version.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.protocol_version - } - }); - } - } - return rval; - }; - var _readRecord = function(c2) { - var rval = 0; - var b = c2.input; - var len = b.length(); - if (len < c2.record.length) { - rval = c2.record.length - len; - } else { - c2.record.fragment.putBytes(b.getBytes(c2.record.length)); - b.compact(); - var s = c2.state.current.read; - if (s.update(c2, c2.record)) { - if (c2.fragmented !== null) { - if (c2.fragmented.type === c2.record.type) { - c2.fragmented.fragment.putBuffer(c2.record.fragment); - c2.record = c2.fragmented; - } else { - c2.error(c2, { - message: "Invalid fragmented record.", - send: true, - alert: { - level: tls.Alert.Level.fatal, - description: tls.Alert.Description.unexpected_message - } - }); - } - } - c2.record.ready = true; - } - } - return rval; - }; - c.handshake = function(sessionId) { - if (c.entity !== tls.ConnectionEnd.client) { - c.error(c, { - message: "Cannot initiate handshake as a server.", - fatal: false - }); - } else if (c.handshaking) { - c.error(c, { - message: "Handshake already in progress.", - fatal: false - }); - } else { - if (c.fail && !c.open && c.handshakes === 0) { - c.fail = false; - } - c.handshaking = true; - sessionId = sessionId || ""; - var session = null; - if (sessionId.length > 0) { - if (c.sessionCache) { - session = c.sessionCache.getSession(sessionId); - } - if (session === null) { - sessionId = ""; - } - } - if (sessionId.length === 0 && c.sessionCache) { - session = c.sessionCache.getSession(); - if (session !== null) { - sessionId = session.id; - } - } - c.session = { - id: sessionId, - version: null, - cipherSuite: null, - compressionMethod: null, - serverCertificate: null, - certificateRequest: null, - clientCertificate: null, - sp: {}, - md5: forge2.md.md5.create(), - sha1: forge2.md.sha1.create() - }; - if (session) { - c.version = session.version; - c.session.sp = session.sp; - } - c.session.sp.client_random = tls.createRandom().getBytes(); - c.open = true; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.handshake, - data: tls.createClientHello(c) - })); - tls.flush(c); - } - }; - c.process = function(data) { - var rval = 0; - if (data) { - c.input.putBytes(data); - } - if (!c.fail) { - if (c.record !== null && c.record.ready && c.record.fragment.isEmpty()) { - c.record = null; - } - if (c.record === null) { - rval = _readRecordHeader(c); - } - if (!c.fail && c.record !== null && !c.record.ready) { - rval = _readRecord(c); - } - if (!c.fail && c.record !== null && c.record.ready) { - _update(c, c.record); - } - } - return rval; - }; - c.prepare = function(data) { - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.application_data, - data: forge2.util.createBuffer(data) - })); - return tls.flush(c); - }; - c.prepareHeartbeatRequest = function(payload, payloadLength) { - if (payload instanceof forge2.util.ByteBuffer) { - payload = payload.bytes(); - } - if (typeof payloadLength === "undefined") { - payloadLength = payload.length; - } - c.expectedHeartbeatPayload = payload; - tls.queue(c, tls.createRecord(c, { - type: tls.ContentType.heartbeat, - data: tls.createHeartbeat( - tls.HeartbeatMessageType.heartbeat_request, - payload, - payloadLength - ) - })); - return tls.flush(c); - }; - c.close = function(clearFail) { - if (!c.fail && c.sessionCache && c.session) { - var session = { - id: c.session.id, - version: c.session.version, - sp: c.session.sp - }; - session.sp.keys = null; - c.sessionCache.setSession(session.id, session); - } - if (c.open) { - c.open = false; - c.input.clear(); - if (c.isConnected || c.handshaking) { - c.isConnected = c.handshaking = false; - tls.queue(c, tls.createAlert(c, { - level: tls.Alert.Level.warning, - description: tls.Alert.Description.close_notify - })); - tls.flush(c); - } - c.closed(c); - } - c.reset(clearFail); - }; - return c; - }; - module.exports = forge2.tls = forge2.tls || {}; - for (key in tls) { - if (typeof tls[key] !== "function") { - forge2.tls[key] = tls[key]; - } - } - var key; - forge2.tls.prf_tls1 = prf_TLS1; - forge2.tls.hmac_sha1 = hmac_sha1; - forge2.tls.createSessionCache = tls.createSessionCache; - forge2.tls.createConnection = tls.createConnection; - } -}); - -// node_modules/node-forge/lib/aesCipherSuites.js -var require_aesCipherSuites = __commonJS({ - "node_modules/node-forge/lib/aesCipherSuites.js"(exports, module) { - var forge2 = require_forge(); - require_aes(); - require_tls(); - var tls = module.exports = forge2.tls; - tls.CipherSuites["TLS_RSA_WITH_AES_128_CBC_SHA"] = { - id: [0, 47], - name: "TLS_RSA_WITH_AES_128_CBC_SHA", - initSecurityParameters: function(sp) { - sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; - sp.cipher_type = tls.CipherType.block; - sp.enc_key_length = 16; - sp.block_length = 16; - sp.fixed_iv_length = 16; - sp.record_iv_length = 16; - sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; - sp.mac_length = 20; - sp.mac_key_length = 20; - }, - initConnectionState - }; - tls.CipherSuites["TLS_RSA_WITH_AES_256_CBC_SHA"] = { - id: [0, 53], - name: "TLS_RSA_WITH_AES_256_CBC_SHA", - initSecurityParameters: function(sp) { - sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; - sp.cipher_type = tls.CipherType.block; - sp.enc_key_length = 32; - sp.block_length = 16; - sp.fixed_iv_length = 16; - sp.record_iv_length = 16; - sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; - sp.mac_length = 20; - sp.mac_key_length = 20; - }, - initConnectionState - }; - function initConnectionState(state, c, sp) { - var client = c.entity === forge2.tls.ConnectionEnd.client; - state.read.cipherState = { - init: false, - cipher: forge2.cipher.createDecipher("AES-CBC", client ? sp.keys.server_write_key : sp.keys.client_write_key), - iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV - }; - state.write.cipherState = { - init: false, - cipher: forge2.cipher.createCipher("AES-CBC", client ? sp.keys.client_write_key : sp.keys.server_write_key), - iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV - }; - state.read.cipherFunction = decrypt_aes_cbc_sha1; - state.write.cipherFunction = encrypt_aes_cbc_sha1; - state.read.macLength = state.write.macLength = sp.mac_length; - state.read.macFunction = state.write.macFunction = tls.hmac_sha1; - } - function encrypt_aes_cbc_sha1(record, s) { - var rval = false; - var mac = s.macFunction(s.macKey, s.sequenceNumber, record); - record.fragment.putBytes(mac); - s.updateSequenceNumber(); - var iv; - if (record.version.minor === tls.Versions.TLS_1_0.minor) { - iv = s.cipherState.init ? null : s.cipherState.iv; - } else { - iv = forge2.random.getBytesSync(16); - } - s.cipherState.init = true; - var cipher = s.cipherState.cipher; - cipher.start({ iv }); - if (record.version.minor >= tls.Versions.TLS_1_1.minor) { - cipher.output.putBytes(iv); - } - cipher.update(record.fragment); - if (cipher.finish(encrypt_aes_cbc_sha1_padding)) { - record.fragment = cipher.output; - record.length = record.fragment.length(); - rval = true; - } - return rval; - } - function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) { - if (!decrypt) { - var padding = blockSize - input.length() % blockSize; - input.fillWithByte(padding - 1, padding); - } - return true; - } - function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) { - var rval = true; - if (decrypt) { - var len = output.length(); - var paddingLength = output.last(); - for (var i = len - 1 - paddingLength; i < len - 1; ++i) { - rval = rval && output.at(i) == paddingLength; - } - if (rval) { - output.truncate(paddingLength + 1); - } - } - return rval; - } - function decrypt_aes_cbc_sha1(record, s) { - var rval = false; - var iv; - if (record.version.minor === tls.Versions.TLS_1_0.minor) { - iv = s.cipherState.init ? null : s.cipherState.iv; - } else { - iv = record.fragment.getBytes(16); - } - s.cipherState.init = true; - var cipher = s.cipherState.cipher; - cipher.start({ iv }); - cipher.update(record.fragment); - rval = cipher.finish(decrypt_aes_cbc_sha1_padding); - var macLen = s.macLength; - var mac = forge2.random.getBytesSync(macLen); - var len = cipher.output.length(); - if (len >= macLen) { - record.fragment = cipher.output.getBytes(len - macLen); - mac = cipher.output.getBytes(macLen); - } else { - record.fragment = cipher.output.getBytes(); - } - record.fragment = forge2.util.createBuffer(record.fragment); - record.length = record.fragment.length(); - var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record); - s.updateSequenceNumber(); - rval = compareMacs(s.macKey, mac, mac2) && rval; - return rval; - } - function compareMacs(key, mac1, mac2) { - var hmac = forge2.hmac.create(); - hmac.start("SHA1", key); - hmac.update(mac1); - mac1 = hmac.digest().getBytes(); - hmac.start(null, null); - hmac.update(mac2); - mac2 = hmac.digest().getBytes(); - return mac1 === mac2; - } - } -}); - -// node_modules/node-forge/lib/sha512.js -var require_sha512 = __commonJS({ - "node_modules/node-forge/lib/sha512.js"(exports, module) { - var forge2 = require_forge(); - require_md(); - require_util(); - var sha512 = module.exports = forge2.sha512 = forge2.sha512 || {}; - forge2.md.sha512 = forge2.md.algorithms.sha512 = sha512; - var sha384 = forge2.sha384 = forge2.sha512.sha384 = forge2.sha512.sha384 || {}; - sha384.create = function() { - return sha512.create("SHA-384"); - }; - forge2.md.sha384 = forge2.md.algorithms.sha384 = sha384; - forge2.sha512.sha256 = forge2.sha512.sha256 || { - create: function() { - return sha512.create("SHA-512/256"); - } - }; - forge2.md["sha512/256"] = forge2.md.algorithms["sha512/256"] = forge2.sha512.sha256; - forge2.sha512.sha224 = forge2.sha512.sha224 || { - create: function() { - return sha512.create("SHA-512/224"); - } - }; - forge2.md["sha512/224"] = forge2.md.algorithms["sha512/224"] = forge2.sha512.sha224; - sha512.create = function(algorithm) { - if (!_initialized) { - _init(); - } - if (typeof algorithm === "undefined") { - algorithm = "SHA-512"; - } - if (!(algorithm in _states)) { - throw new Error("Invalid SHA-512 algorithm: " + algorithm); - } - var _state = _states[algorithm]; - var _h = null; - var _input = forge2.util.createBuffer(); - var _w = new Array(80); - for (var wi = 0; wi < 80; ++wi) { - _w[wi] = new Array(2); - } - var digestLength = 64; - switch (algorithm) { - case "SHA-384": - digestLength = 48; - break; - case "SHA-512/256": - digestLength = 32; - break; - case "SHA-512/224": - digestLength = 28; - break; - } - var md = { - // SHA-512 => sha512 - algorithm: algorithm.replace("-", "").toLowerCase(), - blockLength: 128, - digestLength, - // 56-bit length of message so far (does not including padding) - messageLength: 0, - // true message length - fullMessageLength: null, - // size of message length in bytes - messageLengthSize: 16 - }; - md.start = function() { - md.messageLength = 0; - md.fullMessageLength = md.messageLength128 = []; - var int32s = md.messageLengthSize / 4; - for (var i = 0; i < int32s; ++i) { - md.fullMessageLength.push(0); - } - _input = forge2.util.createBuffer(); - _h = new Array(_state.length); - for (var i = 0; i < _state.length; ++i) { - _h[i] = _state[i].slice(0); - } - return md; - }; - md.start(); - md.update = function(msg, encoding) { - if (encoding === "utf8") { - msg = forge2.util.encodeUtf8(msg); - } - var len = msg.length; - md.messageLength += len; - len = [len / 4294967296 >>> 0, len >>> 0]; - for (var i = md.fullMessageLength.length - 1; i >= 0; --i) { - md.fullMessageLength[i] += len[1]; - len[1] = len[0] + (md.fullMessageLength[i] / 4294967296 >>> 0); - md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; - len[0] = len[1] / 4294967296 >>> 0; - } - _input.putBytes(msg); - _update(_h, _w, _input); - if (_input.read > 2048 || _input.length() === 0) { - _input.compact(); - } - return md; - }; - md.digest = function() { - var finalBlock = forge2.util.createBuffer(); - finalBlock.putBytes(_input.bytes()); - var remaining = md.fullMessageLength[md.fullMessageLength.length - 1] + md.messageLengthSize; - var overflow = remaining & md.blockLength - 1; - finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); - var next, carry; - var bits = md.fullMessageLength[0] * 8; - for (var i = 0; i < md.fullMessageLength.length - 1; ++i) { - next = md.fullMessageLength[i + 1] * 8; - carry = next / 4294967296 >>> 0; - bits += carry; - finalBlock.putInt32(bits >>> 0); - bits = next >>> 0; - } - finalBlock.putInt32(bits); - var h = new Array(_h.length); - for (var i = 0; i < _h.length; ++i) { - h[i] = _h[i].slice(0); - } - _update(h, _w, finalBlock); - var rval = forge2.util.createBuffer(); - var hlen; - if (algorithm === "SHA-512") { - hlen = h.length; - } else if (algorithm === "SHA-384") { - hlen = h.length - 2; - } else { - hlen = h.length - 4; - } - for (var i = 0; i < hlen; ++i) { - rval.putInt32(h[i][0]); - if (i !== hlen - 1 || algorithm !== "SHA-512/224") { - rval.putInt32(h[i][1]); - } - } - return rval; - }; - return md; - }; - var _padding = null; - var _initialized = false; - var _k = null; - var _states = null; - function _init() { - _padding = String.fromCharCode(128); - _padding += forge2.util.fillString(String.fromCharCode(0), 128); - _k = [ - [1116352408, 3609767458], - [1899447441, 602891725], - [3049323471, 3964484399], - [3921009573, 2173295548], - [961987163, 4081628472], - [1508970993, 3053834265], - [2453635748, 2937671579], - [2870763221, 3664609560], - [3624381080, 2734883394], - [310598401, 1164996542], - [607225278, 1323610764], - [1426881987, 3590304994], - [1925078388, 4068182383], - [2162078206, 991336113], - [2614888103, 633803317], - [3248222580, 3479774868], - [3835390401, 2666613458], - [4022224774, 944711139], - [264347078, 2341262773], - [604807628, 2007800933], - [770255983, 1495990901], - [1249150122, 1856431235], - [1555081692, 3175218132], - [1996064986, 2198950837], - [2554220882, 3999719339], - [2821834349, 766784016], - [2952996808, 2566594879], - [3210313671, 3203337956], - [3336571891, 1034457026], - [3584528711, 2466948901], - [113926993, 3758326383], - [338241895, 168717936], - [666307205, 1188179964], - [773529912, 1546045734], - [1294757372, 1522805485], - [1396182291, 2643833823], - [1695183700, 2343527390], - [1986661051, 1014477480], - [2177026350, 1206759142], - [2456956037, 344077627], - [2730485921, 1290863460], - [2820302411, 3158454273], - [3259730800, 3505952657], - [3345764771, 106217008], - [3516065817, 3606008344], - [3600352804, 1432725776], - [4094571909, 1467031594], - [275423344, 851169720], - [430227734, 3100823752], - [506948616, 1363258195], - [659060556, 3750685593], - [883997877, 3785050280], - [958139571, 3318307427], - [1322822218, 3812723403], - [1537002063, 2003034995], - [1747873779, 3602036899], - [1955562222, 1575990012], - [2024104815, 1125592928], - [2227730452, 2716904306], - [2361852424, 442776044], - [2428436474, 593698344], - [2756734187, 3733110249], - [3204031479, 2999351573], - [3329325298, 3815920427], - [3391569614, 3928383900], - [3515267271, 566280711], - [3940187606, 3454069534], - [4118630271, 4000239992], - [116418474, 1914138554], - [174292421, 2731055270], - [289380356, 3203993006], - [460393269, 320620315], - [685471733, 587496836], - [852142971, 1086792851], - [1017036298, 365543100], - [1126000580, 2618297676], - [1288033470, 3409855158], - [1501505948, 4234509866], - [1607167915, 987167468], - [1816402316, 1246189591] - ]; - _states = {}; - _states["SHA-512"] = [ - [1779033703, 4089235720], - [3144134277, 2227873595], - [1013904242, 4271175723], - [2773480762, 1595750129], - [1359893119, 2917565137], - [2600822924, 725511199], - [528734635, 4215389547], - [1541459225, 327033209] - ]; - _states["SHA-384"] = [ - [3418070365, 3238371032], - [1654270250, 914150663], - [2438529370, 812702999], - [355462360, 4144912697], - [1731405415, 4290775857], - [2394180231, 1750603025], - [3675008525, 1694076839], - [1203062813, 3204075428] - ]; - _states["SHA-512/256"] = [ - [573645204, 4230739756], - [2673172387, 3360449730], - [596883563, 1867755857], - [2520282905, 1497426621], - [2519219938, 2827943907], - [3193839141, 1401305490], - [721525244, 746961066], - [246885852, 2177182882] - ]; - _states["SHA-512/224"] = [ - [2352822216, 424955298], - [1944164710, 2312950998], - [502970286, 855612546], - [1738396948, 1479516111], - [258812777, 2077511080], - [2011393907, 79989058], - [1067287976, 1780299464], - [286451373, 2446758561] - ]; - _initialized = true; - } - function _update(s, w, bytes) { - var t1_hi, t1_lo; - var t2_hi, t2_lo; - var s0_hi, s0_lo; - var s1_hi, s1_lo; - var ch_hi, ch_lo; - var maj_hi, maj_lo; - var a_hi, a_lo; - var b_hi, b_lo; - var c_hi, c_lo; - var d_hi, d_lo; - var e_hi, e_lo; - var f_hi, f_lo; - var g_hi, g_lo; - var h_hi, h_lo; - var i, hi, lo, w2, w7, w15, w16; - var len = bytes.length(); - while (len >= 128) { - for (i = 0; i < 16; ++i) { - w[i][0] = bytes.getInt32() >>> 0; - w[i][1] = bytes.getInt32() >>> 0; - } - for (; i < 80; ++i) { - w2 = w[i - 2]; - hi = w2[0]; - lo = w2[1]; - t1_hi = ((hi >>> 19 | lo << 13) ^ // ROTR 19 - (lo >>> 29 | hi << 3) ^ // ROTR 61/(swap + ROTR 29) - hi >>> 6) >>> 0; - t1_lo = ((hi << 13 | lo >>> 19) ^ // ROTR 19 - (lo << 3 | hi >>> 29) ^ // ROTR 61/(swap + ROTR 29) - (hi << 26 | lo >>> 6)) >>> 0; - w15 = w[i - 15]; - hi = w15[0]; - lo = w15[1]; - t2_hi = ((hi >>> 1 | lo << 31) ^ // ROTR 1 - (hi >>> 8 | lo << 24) ^ // ROTR 8 - hi >>> 7) >>> 0; - t2_lo = ((hi << 31 | lo >>> 1) ^ // ROTR 1 - (hi << 24 | lo >>> 8) ^ // ROTR 8 - (hi << 25 | lo >>> 7)) >>> 0; - w7 = w[i - 7]; - w16 = w[i - 16]; - lo = t1_lo + w7[1] + t2_lo + w16[1]; - w[i][0] = t1_hi + w7[0] + t2_hi + w16[0] + (lo / 4294967296 >>> 0) >>> 0; - w[i][1] = lo >>> 0; - } - a_hi = s[0][0]; - a_lo = s[0][1]; - b_hi = s[1][0]; - b_lo = s[1][1]; - c_hi = s[2][0]; - c_lo = s[2][1]; - d_hi = s[3][0]; - d_lo = s[3][1]; - e_hi = s[4][0]; - e_lo = s[4][1]; - f_hi = s[5][0]; - f_lo = s[5][1]; - g_hi = s[6][0]; - g_lo = s[6][1]; - h_hi = s[7][0]; - h_lo = s[7][1]; - for (i = 0; i < 80; ++i) { - s1_hi = ((e_hi >>> 14 | e_lo << 18) ^ // ROTR 14 - (e_hi >>> 18 | e_lo << 14) ^ // ROTR 18 - (e_lo >>> 9 | e_hi << 23)) >>> 0; - s1_lo = ((e_hi << 18 | e_lo >>> 14) ^ // ROTR 14 - (e_hi << 14 | e_lo >>> 18) ^ // ROTR 18 - (e_lo << 23 | e_hi >>> 9)) >>> 0; - ch_hi = (g_hi ^ e_hi & (f_hi ^ g_hi)) >>> 0; - ch_lo = (g_lo ^ e_lo & (f_lo ^ g_lo)) >>> 0; - s0_hi = ((a_hi >>> 28 | a_lo << 4) ^ // ROTR 28 - (a_lo >>> 2 | a_hi << 30) ^ // ROTR 34/(swap + ROTR 2) - (a_lo >>> 7 | a_hi << 25)) >>> 0; - s0_lo = ((a_hi << 4 | a_lo >>> 28) ^ // ROTR 28 - (a_lo << 30 | a_hi >>> 2) ^ // ROTR 34/(swap + ROTR 2) - (a_lo << 25 | a_hi >>> 7)) >>> 0; - maj_hi = (a_hi & b_hi | c_hi & (a_hi ^ b_hi)) >>> 0; - maj_lo = (a_lo & b_lo | c_lo & (a_lo ^ b_lo)) >>> 0; - lo = h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]; - t1_hi = h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] + (lo / 4294967296 >>> 0) >>> 0; - t1_lo = lo >>> 0; - lo = s0_lo + maj_lo; - t2_hi = s0_hi + maj_hi + (lo / 4294967296 >>> 0) >>> 0; - t2_lo = lo >>> 0; - h_hi = g_hi; - h_lo = g_lo; - g_hi = f_hi; - g_lo = f_lo; - f_hi = e_hi; - f_lo = e_lo; - lo = d_lo + t1_lo; - e_hi = d_hi + t1_hi + (lo / 4294967296 >>> 0) >>> 0; - e_lo = lo >>> 0; - d_hi = c_hi; - d_lo = c_lo; - c_hi = b_hi; - c_lo = b_lo; - b_hi = a_hi; - b_lo = a_lo; - lo = t1_lo + t2_lo; - a_hi = t1_hi + t2_hi + (lo / 4294967296 >>> 0) >>> 0; - a_lo = lo >>> 0; - } - lo = s[0][1] + a_lo; - s[0][0] = s[0][0] + a_hi + (lo / 4294967296 >>> 0) >>> 0; - s[0][1] = lo >>> 0; - lo = s[1][1] + b_lo; - s[1][0] = s[1][0] + b_hi + (lo / 4294967296 >>> 0) >>> 0; - s[1][1] = lo >>> 0; - lo = s[2][1] + c_lo; - s[2][0] = s[2][0] + c_hi + (lo / 4294967296 >>> 0) >>> 0; - s[2][1] = lo >>> 0; - lo = s[3][1] + d_lo; - s[3][0] = s[3][0] + d_hi + (lo / 4294967296 >>> 0) >>> 0; - s[3][1] = lo >>> 0; - lo = s[4][1] + e_lo; - s[4][0] = s[4][0] + e_hi + (lo / 4294967296 >>> 0) >>> 0; - s[4][1] = lo >>> 0; - lo = s[5][1] + f_lo; - s[5][0] = s[5][0] + f_hi + (lo / 4294967296 >>> 0) >>> 0; - s[5][1] = lo >>> 0; - lo = s[6][1] + g_lo; - s[6][0] = s[6][0] + g_hi + (lo / 4294967296 >>> 0) >>> 0; - s[6][1] = lo >>> 0; - lo = s[7][1] + h_lo; - s[7][0] = s[7][0] + h_hi + (lo / 4294967296 >>> 0) >>> 0; - s[7][1] = lo >>> 0; - len -= 128; - } - } - } -}); - -// node_modules/node-forge/lib/asn1-validator.js -var require_asn1_validator = __commonJS({ - "node_modules/node-forge/lib/asn1-validator.js"(exports) { - var forge2 = require_forge(); - require_asn1(); - var asn1 = forge2.asn1; - exports.privateKeyValidator = { - // PrivateKeyInfo - name: "PrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - // Version (INTEGER) - name: "PrivateKeyInfo.version", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.INTEGER, - constructed: false, - capture: "privateKeyVersion" - }, { - // privateKeyAlgorithm - name: "PrivateKeyInfo.privateKeyAlgorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "privateKeyOid" - }] - }, { - // PrivateKey - name: "PrivateKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OCTETSTRING, - constructed: false, - capture: "privateKey" - }] - }; - exports.publicKeyValidator = { - name: "SubjectPublicKeyInfo", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - captureAsn1: "subjectPublicKeyInfo", - value: [ - { - name: "SubjectPublicKeyInfo.AlgorithmIdentifier", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - value: [{ - name: "AlgorithmIdentifier.algorithm", - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.OID, - constructed: false, - capture: "publicKeyOid" - }] - }, - // capture group for ed25519PublicKey - { - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - composed: true, - captureBitStringValue: "ed25519PublicKey" - } - // FIXME: this is capture group for rsaPublicKey, use it in this API or - // discard? - /* { - // subjectPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.BITSTRING, - constructed: false, - value: [{ - // RSAPublicKey - name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', - tagClass: asn1.Class.UNIVERSAL, - type: asn1.Type.SEQUENCE, - constructed: true, - optional: true, - captureAsn1: 'rsaPublicKey' - }] - } */ - ] - }; - } -}); - -// node_modules/node-forge/lib/ed25519.js -var require_ed25519 = __commonJS({ - "node_modules/node-forge/lib/ed25519.js"(exports, module) { - var forge2 = require_forge(); - require_jsbn(); - require_random(); - require_sha512(); - require_util(); - var asn1Validator = require_asn1_validator(); - var publicKeyValidator = asn1Validator.publicKeyValidator; - var privateKeyValidator = asn1Validator.privateKeyValidator; - if (typeof BigInteger2 === "undefined") { - BigInteger2 = forge2.jsbn.BigInteger; - } - var BigInteger2; - var ByteBuffer = forge2.util.ByteBuffer; - var NativeBuffer = typeof Buffer === "undefined" ? Uint8Array : Buffer; - forge2.pki = forge2.pki || {}; - module.exports = forge2.pki.ed25519 = forge2.ed25519 = forge2.ed25519 || {}; - var ed25519 = forge2.ed25519; - ed25519.constants = {}; - ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32; - ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64; - ed25519.constants.SEED_BYTE_LENGTH = 32; - ed25519.constants.SIGN_BYTE_LENGTH = 64; - ed25519.constants.HASH_BYTE_LENGTH = 64; - ed25519.generateKeyPair = function(options) { - options = options || {}; - var seed = options.seed; - if (seed === void 0) { - seed = forge2.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH); - } else if (typeof seed === "string") { - if (seed.length !== ed25519.constants.SEED_BYTE_LENGTH) { - throw new TypeError( - '"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH + " bytes in length." - ); - } - } else if (!(seed instanceof Uint8Array)) { - throw new TypeError( - '"seed" must be a node.js Buffer, Uint8Array, or a binary string.' - ); - } - seed = messageToNativeBuffer({ message: seed, encoding: "binary" }); - var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); - var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); - for (var i = 0; i < 32; ++i) { - sk[i] = seed[i]; - } - crypto_sign_keypair(pk, sk); - return { publicKey: pk, privateKey: sk }; - }; - ed25519.privateKeyFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - var valid = forge2.asn1.validate(obj, privateKeyValidator, capture, errors); - if (!valid) { - var error = new Error("Invalid Key."); - error.errors = errors; - throw error; - } - var oid = forge2.asn1.derToOid(capture.privateKeyOid); - var ed25519Oid = forge2.oids.EdDSA25519; - if (oid !== ed25519Oid) { - throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".'); - } - var privateKey = capture.privateKey; - var privateKeyBytes = messageToNativeBuffer({ - message: forge2.asn1.fromDer(privateKey).value, - encoding: "binary" - }); - return { privateKeyBytes }; - }; - ed25519.publicKeyFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - var valid = forge2.asn1.validate(obj, publicKeyValidator, capture, errors); - if (!valid) { - var error = new Error("Invalid Key."); - error.errors = errors; - throw error; - } - var oid = forge2.asn1.derToOid(capture.publicKeyOid); - var ed25519Oid = forge2.oids.EdDSA25519; - if (oid !== ed25519Oid) { - throw new Error('Invalid OID "' + oid + '"; OID must be "' + ed25519Oid + '".'); - } - var publicKeyBytes = capture.ed25519PublicKey; - if (publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { - throw new Error("Key length is invalid."); - } - return messageToNativeBuffer({ - message: publicKeyBytes, - encoding: "binary" - }); - }; - ed25519.publicKeyFromPrivateKey = function(options) { - options = options || {}; - var privateKey = messageToNativeBuffer({ - message: options.privateKey, - encoding: "binary" - }); - if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.privateKey" must have a byte length of ' + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH - ); - } - var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); - for (var i = 0; i < pk.length; ++i) { - pk[i] = privateKey[32 + i]; - } - return pk; - }; - ed25519.sign = function(options) { - options = options || {}; - var msg = messageToNativeBuffer(options); - var privateKey = messageToNativeBuffer({ - message: options.privateKey, - encoding: "binary" - }); - if (privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) { - var keyPair = ed25519.generateKeyPair({ seed: privateKey }); - privateKey = keyPair.privateKey; - } else if (privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.privateKey" must have a byte length of ' + ed25519.constants.SEED_BYTE_LENGTH + " or " + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH - ); - } - var signedMsg = new NativeBuffer( - ed25519.constants.SIGN_BYTE_LENGTH + msg.length - ); - crypto_sign(signedMsg, msg, msg.length, privateKey); - var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH); - for (var i = 0; i < sig.length; ++i) { - sig[i] = signedMsg[i]; - } - return sig; - }; - ed25519.verify = function(options) { - options = options || {}; - var msg = messageToNativeBuffer(options); - if (options.signature === void 0) { - throw new TypeError( - '"options.signature" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a binary string.' - ); - } - var sig = messageToNativeBuffer({ - message: options.signature, - encoding: "binary" - }); - if (sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) { - throw new TypeError( - '"options.signature" must have a byte length of ' + ed25519.constants.SIGN_BYTE_LENGTH - ); - } - var publicKey = messageToNativeBuffer({ - message: options.publicKey, - encoding: "binary" - }); - if (publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { - throw new TypeError( - '"options.publicKey" must have a byte length of ' + ed25519.constants.PUBLIC_KEY_BYTE_LENGTH - ); - } - var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); - var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); - var i; - for (i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) { - sm[i] = sig[i]; - } - for (i = 0; i < msg.length; ++i) { - sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i]; - } - return crypto_sign_open(m, sm, sm.length, publicKey) >= 0; - }; - function messageToNativeBuffer(options) { - var message = options.message; - if (message instanceof Uint8Array || message instanceof NativeBuffer) { - return message; - } - var encoding = options.encoding; - if (message === void 0) { - if (options.md) { - message = options.md.digest().getBytes(); - encoding = "binary"; - } else { - throw new TypeError('"options.message" or "options.md" not specified.'); - } - } - if (typeof message === "string" && !encoding) { - throw new TypeError('"options.encoding" must be "binary" or "utf8".'); - } - if (typeof message === "string") { - if (typeof Buffer !== "undefined") { - return Buffer.from(message, encoding); - } - message = new ByteBuffer(message, encoding); - } else if (!(message instanceof ByteBuffer)) { - throw new TypeError( - '"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.' - ); - } - var buffer = new NativeBuffer(message.length()); - for (var i = 0; i < buffer.length; ++i) { - buffer[i] = message.at(i); - } - return buffer; - } - var gf0 = gf(); - var gf1 = gf([1]); - var D = gf([ - 30883, - 4953, - 19914, - 30187, - 55467, - 16705, - 2637, - 112, - 59544, - 30585, - 16505, - 36039, - 65139, - 11119, - 27886, - 20995 - ]); - var D2 = gf([ - 61785, - 9906, - 39828, - 60374, - 45398, - 33411, - 5274, - 224, - 53552, - 61171, - 33010, - 6542, - 64743, - 22239, - 55772, - 9222 - ]); - var X = gf([ - 54554, - 36645, - 11616, - 51542, - 42930, - 38181, - 51040, - 26924, - 56412, - 64982, - 57905, - 49316, - 21502, - 52590, - 14035, - 8553 - ]); - var Y = gf([ - 26200, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214, - 26214 - ]); - var L = new Float64Array([ - 237, - 211, - 245, - 92, - 26, - 99, - 18, - 88, - 214, - 156, - 247, - 162, - 222, - 249, - 222, - 20, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 16 - ]); - var I = gf([ - 41136, - 18958, - 6951, - 50414, - 58488, - 44335, - 6150, - 12099, - 55207, - 15867, - 153, - 11085, - 57099, - 20417, - 9344, - 11139 - ]); - function sha512(msg, msgLen) { - var md = forge2.md.sha512.create(); - var buffer = new ByteBuffer(msg); - md.update(buffer.getBytes(msgLen), "binary"); - var hash = md.digest().getBytes(); - if (typeof Buffer !== "undefined") { - return Buffer.from(hash, "binary"); - } - var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH); - for (var i = 0; i < 64; ++i) { - out[i] = hash.charCodeAt(i); - } - return out; - } - function crypto_sign_keypair(pk, sk) { - var p = [gf(), gf(), gf(), gf()]; - var i; - var d = sha512(sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - scalarbase(p, d); - pack(pk, p); - for (i = 0; i < 32; ++i) { - sk[i + 32] = pk[i]; - } - return 0; - } - function crypto_sign(sm, m, n, sk) { - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; - var d = sha512(sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; - var smlen = n + 64; - for (i = 0; i < n; ++i) { - sm[64 + i] = m[i]; - } - for (i = 0; i < 32; ++i) { - sm[32 + i] = d[32 + i]; - } - var r = sha512(sm.subarray(32), n + 32); - reduce(r); - scalarbase(p, r); - pack(sm, p); - for (i = 32; i < 64; ++i) { - sm[i] = sk[i]; - } - var h = sha512(sm, n + 64); - reduce(h); - for (i = 32; i < 64; ++i) { - x[i] = 0; - } - for (i = 0; i < 32; ++i) { - x[i] = r[i]; - } - for (i = 0; i < 32; ++i) { - for (j = 0; j < 32; j++) { - x[i + j] += h[i] * d[j]; - } - } - modL(sm.subarray(32), x); - return smlen; - } - function crypto_sign_open(m, sm, n, pk) { - var i, mlen; - var t = new NativeBuffer(32); - var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; - mlen = -1; - if (n < 64) { - return -1; - } - if (unpackneg(q, pk)) { - return -1; - } - for (i = 0; i < n; ++i) { - m[i] = sm[i]; - } - for (i = 0; i < 32; ++i) { - m[i + 32] = pk[i]; - } - var h = sha512(m, n); - reduce(h); - scalarmult(p, q, h); - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; ++i) { - m[i] = 0; - } - return -1; - } - for (i = 0; i < n; ++i) { - m[i] = sm[i + 64]; - } - mlen = n; - return mlen; - } - function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = x[j] + 128 >> 8; - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; ++j) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; ++j) { - x[j] -= carry * L[j]; - } - for (i = 0; i < 32; ++i) { - x[i + 1] += x[i] >> 8; - r[i] = x[i] & 255; - } - } - function reduce(r) { - var x = new Float64Array(64); - for (var i = 0; i < 64; ++i) { - x[i] = r[i]; - r[i] = 0; - } - modL(r, x); - } - function add(p, q) { - var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf(); - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); - } - function cswap(p, q, b) { - for (var i = 0; i < 4; ++i) { - sel25519(p[i], q[i], b); - } - } - function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; - } - function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; ++i) { - t[i] = n[i]; - } - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; ++j) { - m[0] = t[0] - 65517; - for (i = 1; i < 15; ++i) { - m[i] = t[i] - 65535 - (m[i - 1] >> 16 & 1); - m[i - 1] &= 65535; - } - m[15] = t[15] - 32767 - (m[14] >> 16 & 1); - b = m[15] >> 16 & 1; - m[14] &= 65535; - sel25519(t, m, 1 - b); - } - for (i = 0; i < 16; i++) { - o[2 * i] = t[i] & 255; - o[2 * i + 1] = t[i] >> 8; - } - } - function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) { - M(r[0], r[0], I); - } - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) { - return -1; - } - if (par25519(r[0]) === p[31] >> 7) { - Z(r[0], gf0, r[0]); - } - M(r[3], r[0], r[1]); - return 0; - } - function unpack25519(o, n) { - var i; - for (i = 0; i < 16; ++i) { - o[i] = n[2 * i] + (n[2 * i + 1] << 8); - } - o[15] &= 32767; - } - function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; ++a) { - c[a] = i[a]; - } - for (a = 250; a >= 0; --a) { - S(c, c); - if (a !== 1) { - M(c, c, i); - } - } - for (a = 0; a < 16; ++a) { - o[a] = c[a]; - } - } - function neq25519(a, b) { - var c = new NativeBuffer(32); - var d = new NativeBuffer(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); - } - function crypto_verify_32(x, xi, y, yi) { - return vn(x, xi, y, yi, 32); - } - function vn(x, xi, y, yi, n) { - var i, d = 0; - for (i = 0; i < n; ++i) { - d |= x[xi + i] ^ y[yi + i]; - } - return (1 & d - 1 >>> 8) - 1; - } - function par25519(a) { - var d = new NativeBuffer(32); - pack25519(d, a); - return d[0] & 1; - } - function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = s[i / 8 | 0] >> (i & 7) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); - } - } - function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); - } - function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) { - r[i] = a[i] | 0; - } - } - function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; ++a) { - c[a] = i[a]; - } - for (a = 253; a >= 0; --a) { - S(c, c); - if (a !== 2 && a !== 4) { - M(c, c, i); - } - } - for (a = 0; a < 16; ++a) { - o[a] = c[a]; - } - } - function car25519(o) { - var i, v, c = 1; - for (i = 0; i < 16; ++i) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; - } - o[0] += c - 1 + 37 * (c - 1); - } - function sel25519(p, q, b) { - var t, c = ~(b - 1); - for (var i = 0; i < 16; ++i) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; - } - } - function gf(init) { - var i, r = new Float64Array(16); - if (init) { - for (i = 0; i < init.length; ++i) { - r[i] = init[i]; - } - } - return r; - } - function A(o, a, b) { - for (var i = 0; i < 16; ++i) { - o[i] = a[i] + b[i]; - } - } - function Z(o, a, b) { - for (var i = 0; i < 16; ++i) { - o[i] = a[i] - b[i]; - } - } - function S(o, a) { - M(o, a, a); - } - function M(o, a, b) { - var v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15]; - v = a[0]; - t0 += v * b0; - t1 += v * b1; - t2 += v * b2; - t3 += v * b3; - t4 += v * b4; - t5 += v * b5; - t6 += v * b6; - t7 += v * b7; - t8 += v * b8; - t9 += v * b9; - t10 += v * b10; - t11 += v * b11; - t12 += v * b12; - t13 += v * b13; - t14 += v * b14; - t15 += v * b15; - v = a[1]; - t1 += v * b0; - t2 += v * b1; - t3 += v * b2; - t4 += v * b3; - t5 += v * b4; - t6 += v * b5; - t7 += v * b6; - t8 += v * b7; - t9 += v * b8; - t10 += v * b9; - t11 += v * b10; - t12 += v * b11; - t13 += v * b12; - t14 += v * b13; - t15 += v * b14; - t16 += v * b15; - v = a[2]; - t2 += v * b0; - t3 += v * b1; - t4 += v * b2; - t5 += v * b3; - t6 += v * b4; - t7 += v * b5; - t8 += v * b6; - t9 += v * b7; - t10 += v * b8; - t11 += v * b9; - t12 += v * b10; - t13 += v * b11; - t14 += v * b12; - t15 += v * b13; - t16 += v * b14; - t17 += v * b15; - v = a[3]; - t3 += v * b0; - t4 += v * b1; - t5 += v * b2; - t6 += v * b3; - t7 += v * b4; - t8 += v * b5; - t9 += v * b6; - t10 += v * b7; - t11 += v * b8; - t12 += v * b9; - t13 += v * b10; - t14 += v * b11; - t15 += v * b12; - t16 += v * b13; - t17 += v * b14; - t18 += v * b15; - v = a[4]; - t4 += v * b0; - t5 += v * b1; - t6 += v * b2; - t7 += v * b3; - t8 += v * b4; - t9 += v * b5; - t10 += v * b6; - t11 += v * b7; - t12 += v * b8; - t13 += v * b9; - t14 += v * b10; - t15 += v * b11; - t16 += v * b12; - t17 += v * b13; - t18 += v * b14; - t19 += v * b15; - v = a[5]; - t5 += v * b0; - t6 += v * b1; - t7 += v * b2; - t8 += v * b3; - t9 += v * b4; - t10 += v * b5; - t11 += v * b6; - t12 += v * b7; - t13 += v * b8; - t14 += v * b9; - t15 += v * b10; - t16 += v * b11; - t17 += v * b12; - t18 += v * b13; - t19 += v * b14; - t20 += v * b15; - v = a[6]; - t6 += v * b0; - t7 += v * b1; - t8 += v * b2; - t9 += v * b3; - t10 += v * b4; - t11 += v * b5; - t12 += v * b6; - t13 += v * b7; - t14 += v * b8; - t15 += v * b9; - t16 += v * b10; - t17 += v * b11; - t18 += v * b12; - t19 += v * b13; - t20 += v * b14; - t21 += v * b15; - v = a[7]; - t7 += v * b0; - t8 += v * b1; - t9 += v * b2; - t10 += v * b3; - t11 += v * b4; - t12 += v * b5; - t13 += v * b6; - t14 += v * b7; - t15 += v * b8; - t16 += v * b9; - t17 += v * b10; - t18 += v * b11; - t19 += v * b12; - t20 += v * b13; - t21 += v * b14; - t22 += v * b15; - v = a[8]; - t8 += v * b0; - t9 += v * b1; - t10 += v * b2; - t11 += v * b3; - t12 += v * b4; - t13 += v * b5; - t14 += v * b6; - t15 += v * b7; - t16 += v * b8; - t17 += v * b9; - t18 += v * b10; - t19 += v * b11; - t20 += v * b12; - t21 += v * b13; - t22 += v * b14; - t23 += v * b15; - v = a[9]; - t9 += v * b0; - t10 += v * b1; - t11 += v * b2; - t12 += v * b3; - t13 += v * b4; - t14 += v * b5; - t15 += v * b6; - t16 += v * b7; - t17 += v * b8; - t18 += v * b9; - t19 += v * b10; - t20 += v * b11; - t21 += v * b12; - t22 += v * b13; - t23 += v * b14; - t24 += v * b15; - v = a[10]; - t10 += v * b0; - t11 += v * b1; - t12 += v * b2; - t13 += v * b3; - t14 += v * b4; - t15 += v * b5; - t16 += v * b6; - t17 += v * b7; - t18 += v * b8; - t19 += v * b9; - t20 += v * b10; - t21 += v * b11; - t22 += v * b12; - t23 += v * b13; - t24 += v * b14; - t25 += v * b15; - v = a[11]; - t11 += v * b0; - t12 += v * b1; - t13 += v * b2; - t14 += v * b3; - t15 += v * b4; - t16 += v * b5; - t17 += v * b6; - t18 += v * b7; - t19 += v * b8; - t20 += v * b9; - t21 += v * b10; - t22 += v * b11; - t23 += v * b12; - t24 += v * b13; - t25 += v * b14; - t26 += v * b15; - v = a[12]; - t12 += v * b0; - t13 += v * b1; - t14 += v * b2; - t15 += v * b3; - t16 += v * b4; - t17 += v * b5; - t18 += v * b6; - t19 += v * b7; - t20 += v * b8; - t21 += v * b9; - t22 += v * b10; - t23 += v * b11; - t24 += v * b12; - t25 += v * b13; - t26 += v * b14; - t27 += v * b15; - v = a[13]; - t13 += v * b0; - t14 += v * b1; - t15 += v * b2; - t16 += v * b3; - t17 += v * b4; - t18 += v * b5; - t19 += v * b6; - t20 += v * b7; - t21 += v * b8; - t22 += v * b9; - t23 += v * b10; - t24 += v * b11; - t25 += v * b12; - t26 += v * b13; - t27 += v * b14; - t28 += v * b15; - v = a[14]; - t14 += v * b0; - t15 += v * b1; - t16 += v * b2; - t17 += v * b3; - t18 += v * b4; - t19 += v * b5; - t20 += v * b6; - t21 += v * b7; - t22 += v * b8; - t23 += v * b9; - t24 += v * b10; - t25 += v * b11; - t26 += v * b12; - t27 += v * b13; - t28 += v * b14; - t29 += v * b15; - v = a[15]; - t15 += v * b0; - t16 += v * b1; - t17 += v * b2; - t18 += v * b3; - t19 += v * b4; - t20 += v * b5; - t21 += v * b6; - t22 += v * b7; - t23 += v * b8; - t24 += v * b9; - t25 += v * b10; - t26 += v * b11; - t27 += v * b12; - t28 += v * b13; - t29 += v * b14; - t30 += v * b15; - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - c = 1; - v = t0 + c + 65535; - c = Math.floor(v / 65536); - t0 = v - c * 65536; - v = t1 + c + 65535; - c = Math.floor(v / 65536); - t1 = v - c * 65536; - v = t2 + c + 65535; - c = Math.floor(v / 65536); - t2 = v - c * 65536; - v = t3 + c + 65535; - c = Math.floor(v / 65536); - t3 = v - c * 65536; - v = t4 + c + 65535; - c = Math.floor(v / 65536); - t4 = v - c * 65536; - v = t5 + c + 65535; - c = Math.floor(v / 65536); - t5 = v - c * 65536; - v = t6 + c + 65535; - c = Math.floor(v / 65536); - t6 = v - c * 65536; - v = t7 + c + 65535; - c = Math.floor(v / 65536); - t7 = v - c * 65536; - v = t8 + c + 65535; - c = Math.floor(v / 65536); - t8 = v - c * 65536; - v = t9 + c + 65535; - c = Math.floor(v / 65536); - t9 = v - c * 65536; - v = t10 + c + 65535; - c = Math.floor(v / 65536); - t10 = v - c * 65536; - v = t11 + c + 65535; - c = Math.floor(v / 65536); - t11 = v - c * 65536; - v = t12 + c + 65535; - c = Math.floor(v / 65536); - t12 = v - c * 65536; - v = t13 + c + 65535; - c = Math.floor(v / 65536); - t13 = v - c * 65536; - v = t14 + c + 65535; - c = Math.floor(v / 65536); - t14 = v - c * 65536; - v = t15 + c + 65535; - c = Math.floor(v / 65536); - t15 = v - c * 65536; - t0 += c - 1 + 37 * (c - 1); - c = 1; - v = t0 + c + 65535; - c = Math.floor(v / 65536); - t0 = v - c * 65536; - v = t1 + c + 65535; - c = Math.floor(v / 65536); - t1 = v - c * 65536; - v = t2 + c + 65535; - c = Math.floor(v / 65536); - t2 = v - c * 65536; - v = t3 + c + 65535; - c = Math.floor(v / 65536); - t3 = v - c * 65536; - v = t4 + c + 65535; - c = Math.floor(v / 65536); - t4 = v - c * 65536; - v = t5 + c + 65535; - c = Math.floor(v / 65536); - t5 = v - c * 65536; - v = t6 + c + 65535; - c = Math.floor(v / 65536); - t6 = v - c * 65536; - v = t7 + c + 65535; - c = Math.floor(v / 65536); - t7 = v - c * 65536; - v = t8 + c + 65535; - c = Math.floor(v / 65536); - t8 = v - c * 65536; - v = t9 + c + 65535; - c = Math.floor(v / 65536); - t9 = v - c * 65536; - v = t10 + c + 65535; - c = Math.floor(v / 65536); - t10 = v - c * 65536; - v = t11 + c + 65535; - c = Math.floor(v / 65536); - t11 = v - c * 65536; - v = t12 + c + 65535; - c = Math.floor(v / 65536); - t12 = v - c * 65536; - v = t13 + c + 65535; - c = Math.floor(v / 65536); - t13 = v - c * 65536; - v = t14 + c + 65535; - c = Math.floor(v / 65536); - t14 = v - c * 65536; - v = t15 + c + 65535; - c = Math.floor(v / 65536); - t15 = v - c * 65536; - t0 += c - 1 + 37 * (c - 1); - o[0] = t0; - o[1] = t1; - o[2] = t2; - o[3] = t3; - o[4] = t4; - o[5] = t5; - o[6] = t6; - o[7] = t7; - o[8] = t8; - o[9] = t9; - o[10] = t10; - o[11] = t11; - o[12] = t12; - o[13] = t13; - o[14] = t14; - o[15] = t15; - } - } -}); - -// node_modules/node-forge/lib/kem.js -var require_kem = __commonJS({ - "node_modules/node-forge/lib/kem.js"(exports, module) { - var forge2 = require_forge(); - require_util(); - require_random(); - require_jsbn(); - module.exports = forge2.kem = forge2.kem || {}; - var BigInteger2 = forge2.jsbn.BigInteger; - forge2.kem.rsa = {}; - forge2.kem.rsa.create = function(kdf, options) { - options = options || {}; - var prng = options.prng || forge2.random; - var kem = {}; - kem.encrypt = function(publicKey, keyLength) { - var byteLength = Math.ceil(publicKey.n.bitLength() / 8); - var r; - do { - r = new BigInteger2( - forge2.util.bytesToHex(prng.getBytesSync(byteLength)), - 16 - ).mod(publicKey.n); - } while (r.compareTo(BigInteger2.ONE) <= 0); - r = forge2.util.hexToBytes(r.toString(16)); - var zeros = byteLength - r.length; - if (zeros > 0) { - r = forge2.util.fillString(String.fromCharCode(0), zeros) + r; - } - var encapsulation = publicKey.encrypt(r, "NONE"); - var key = kdf.generate(r, keyLength); - return { encapsulation, key }; - }; - kem.decrypt = function(privateKey, encapsulation, keyLength) { - var r = privateKey.decrypt(encapsulation, "NONE"); - return kdf.generate(r, keyLength); - }; - return kem; - }; - forge2.kem.kdf1 = function(md, digestLength) { - _createKDF(this, md, 0, digestLength || md.digestLength); - }; - forge2.kem.kdf2 = function(md, digestLength) { - _createKDF(this, md, 1, digestLength || md.digestLength); - }; - function _createKDF(kdf, md, counterStart, digestLength) { - kdf.generate = function(x, length) { - var key = new forge2.util.ByteBuffer(); - var k = Math.ceil(length / digestLength) + counterStart; - var c = new forge2.util.ByteBuffer(); - for (var i = counterStart; i < k; ++i) { - c.putInt32(i); - md.start(); - md.update(x + c.getBytes()); - var hash = md.digest(); - key.putBytes(hash.getBytes(digestLength)); - } - key.truncate(key.length() - length); - return key.getBytes(); - }; - } - } -}); - -// node_modules/node-forge/lib/log.js -var require_log = __commonJS({ - "node_modules/node-forge/lib/log.js"(exports, module) { - var forge2 = require_forge(); - require_util(); - module.exports = forge2.log = forge2.log || {}; - forge2.log.levels = [ - "none", - "error", - "warning", - "info", - "debug", - "verbose", - "max" - ]; - var sLevelInfo = {}; - var sLoggers = []; - var sConsoleLogger = null; - forge2.log.LEVEL_LOCKED = 1 << 1; - forge2.log.NO_LEVEL_CHECK = 1 << 2; - forge2.log.INTERPOLATE = 1 << 3; - for (i = 0; i < forge2.log.levels.length; ++i) { - level = forge2.log.levels[i]; - sLevelInfo[level] = { - index: i, - name: level.toUpperCase() - }; - } - var level; - var i; - forge2.log.logMessage = function(message) { - var messageLevelIndex = sLevelInfo[message.level].index; - for (var i2 = 0; i2 < sLoggers.length; ++i2) { - var logger2 = sLoggers[i2]; - if (logger2.flags & forge2.log.NO_LEVEL_CHECK) { - logger2.f(message); - } else { - var loggerLevelIndex = sLevelInfo[logger2.level].index; - if (messageLevelIndex <= loggerLevelIndex) { - logger2.f(logger2, message); - } - } - } - }; - forge2.log.prepareStandard = function(message) { - if (!("standard" in message)) { - message.standard = sLevelInfo[message.level].name + //' ' + +message.timestamp + - " [" + message.category + "] " + message.message; - } - }; - forge2.log.prepareFull = function(message) { - if (!("full" in message)) { - var args = [message.message]; - args = args.concat([]); - message.full = forge2.util.format.apply(this, args); - } - }; - forge2.log.prepareStandardFull = function(message) { - if (!("standardFull" in message)) { - forge2.log.prepareStandard(message); - message.standardFull = message.standard; - } - }; - if (true) { - levels = ["error", "warning", "info", "debug", "verbose"]; - for (i = 0; i < levels.length; ++i) { - (function(level2) { - forge2.log[level2] = function(category, message) { - var args = Array.prototype.slice.call(arguments).slice(2); - var msg = { - timestamp: /* @__PURE__ */ new Date(), - level: level2, - category, - message, - "arguments": args - /*standard*/ - /*full*/ - /*fullMessage*/ - }; - forge2.log.logMessage(msg); - }; - })(levels[i]); - } - } - var levels; - var i; - forge2.log.makeLogger = function(logFunction) { - var logger2 = { - flags: 0, - f: logFunction - }; - forge2.log.setLevel(logger2, "none"); - return logger2; - }; - forge2.log.setLevel = function(logger2, level2) { - var rval = false; - if (logger2 && !(logger2.flags & forge2.log.LEVEL_LOCKED)) { - for (var i2 = 0; i2 < forge2.log.levels.length; ++i2) { - var aValidLevel = forge2.log.levels[i2]; - if (level2 == aValidLevel) { - logger2.level = level2; - rval = true; - break; - } - } - } - return rval; - }; - forge2.log.lock = function(logger2, lock2) { - if (typeof lock2 === "undefined" || lock2) { - logger2.flags |= forge2.log.LEVEL_LOCKED; - } else { - logger2.flags &= ~forge2.log.LEVEL_LOCKED; - } - }; - forge2.log.addLogger = function(logger2) { - sLoggers.push(logger2); - }; - if (typeof console !== "undefined" && "log" in console) { - if (console.error && console.warn && console.info && console.debug) { - levelHandlers = { - error: console.error, - warning: console.warn, - info: console.info, - debug: console.debug, - verbose: console.debug - }; - f = function(logger2, message) { - forge2.log.prepareStandard(message); - var handler = levelHandlers[message.level]; - var args = [message.standard]; - args = args.concat(message["arguments"].slice()); - handler.apply(console, args); - }; - logger = forge2.log.makeLogger(f); - } else { - f = function(logger2, message) { - forge2.log.prepareStandardFull(message); - console.log(message.standardFull); - }; - logger = forge2.log.makeLogger(f); - } - forge2.log.setLevel(logger, "debug"); - forge2.log.addLogger(logger); - sConsoleLogger = logger; - } else { - console = { - log: function() { - } - }; - } - var logger; - var levelHandlers; - var f; - if (sConsoleLogger !== null && typeof window !== "undefined" && window.location) { - query = new URL(window.location.href).searchParams; - if (query.has("console.level")) { - forge2.log.setLevel( - sConsoleLogger, - query.get("console.level").slice(-1)[0] - ); - } - if (query.has("console.lock")) { - lock = query.get("console.lock").slice(-1)[0]; - if (lock == "true") { - forge2.log.lock(sConsoleLogger); - } - } - } - var query; - var lock; - forge2.log.consoleLogger = sConsoleLogger; - } -}); - -// node_modules/node-forge/lib/md.all.js -var require_md_all = __commonJS({ - "node_modules/node-forge/lib/md.all.js"(exports, module) { - module.exports = require_md(); - require_md5(); - require_sha1(); - require_sha256(); - require_sha512(); - } -}); - -// node_modules/node-forge/lib/pkcs7.js -var require_pkcs7 = __commonJS({ - "node_modules/node-forge/lib/pkcs7.js"(exports, module) { - var forge2 = require_forge(); - require_aes(); - require_asn1(); - require_des(); - require_oids(); - require_pem(); - require_pkcs7asn1(); - require_random(); - require_util(); - require_x509(); - var asn1 = forge2.asn1; - var p7 = module.exports = forge2.pkcs7 = forge2.pkcs7 || {}; - p7.messageFromPem = function(pem) { - var msg = forge2.pem.decode(pem)[0]; - if (msg.type !== "PKCS7") { - var error = new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".'); - error.headerType = msg.type; - throw error; - } - if (msg.procType && msg.procType.type === "ENCRYPTED") { - throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted."); - } - var obj = asn1.fromDer(msg.body); - return p7.messageFromAsn1(obj); - }; - p7.messageToPem = function(msg, maxline) { - var pemObj = { - type: "PKCS7", - body: asn1.toDer(msg.toAsn1()).getBytes() - }; - return forge2.pem.encode(pemObj, { maxline }); - }; - p7.messageFromAsn1 = function(obj) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) { - var error = new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo."); - error.errors = errors; - throw error; - } - var contentType = asn1.derToOid(capture.contentType); - var msg; - switch (contentType) { - case forge2.pki.oids.envelopedData: - msg = p7.createEnvelopedData(); - break; - case forge2.pki.oids.encryptedData: - msg = p7.createEncryptedData(); - break; - case forge2.pki.oids.signedData: - msg = p7.createSignedData(); - break; - default: - throw new Error("Cannot read PKCS#7 message. ContentType with OID " + contentType + " is not (yet) supported."); - } - msg.fromAsn1(capture.content.value[0]); - return msg; - }; - p7.createSignedData = function() { - var msg = null; - msg = { - type: forge2.pki.oids.signedData, - version: 1, - certificates: [], - crls: [], - // TODO: add json-formatted signer stuff here? - signers: [], - // populated during sign() - digestAlgorithmIdentifiers: [], - contentInfo: null, - signerInfos: [], - fromAsn1: function(obj) { - _fromAsn1(msg, obj, p7.asn1.signedDataValidator); - msg.certificates = []; - msg.crls = []; - msg.digestAlgorithmIdentifiers = []; - msg.contentInfo = null; - msg.signerInfos = []; - if (msg.rawCapture.certificates) { - var certs = msg.rawCapture.certificates.value; - for (var i = 0; i < certs.length; ++i) { - msg.certificates.push(forge2.pki.certificateFromAsn1(certs[i])); - } - } - }, - toAsn1: function() { - if (!msg.contentInfo) { - msg.sign(); - } - var certs = []; - for (var i = 0; i < msg.certificates.length; ++i) { - certs.push(forge2.pki.certificateToAsn1(msg.certificates[i])); - } - var crls = []; - var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(msg.version).getBytes() - ), - // DigestAlgorithmIdentifiers - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SET, - true, - msg.digestAlgorithmIdentifiers - ), - // ContentInfo - msg.contentInfo - ]) - ]); - if (certs.length > 0) { - signedData.value[0].value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs) - ); - } - if (crls.length > 0) { - signedData.value[0].value.push( - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls) - ); - } - signedData.value[0].value.push( - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SET, - true, - msg.signerInfos - ) - ); - return asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [ - // ContentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(msg.type).getBytes() - ), - // [0] SignedData - signedData - ] - ); - }, - /** - * Add (another) entity to list of signers. - * - * Note: If authenticatedAttributes are provided, then, per RFC 2315, - * they must include at least two attributes: content type and - * message digest. The message digest attribute value will be - * auto-calculated during signing and will be ignored if provided. - * - * Here's an example of providing these two attributes: - * - * forge.pkcs7.createSignedData(); - * p7.addSigner({ - * issuer: cert.issuer.attributes, - * serialNumber: cert.serialNumber, - * key: privateKey, - * digestAlgorithm: forge.pki.oids.sha1, - * authenticatedAttributes: [{ - * type: forge.pki.oids.contentType, - * value: forge.pki.oids.data - * }, { - * type: forge.pki.oids.messageDigest - * }] - * }); - * - * TODO: Support [subjectKeyIdentifier] as signer's ID. - * - * @param signer the signer information: - * key the signer's private key. - * [certificate] a certificate containing the public key - * associated with the signer's private key; use this option as - * an alternative to specifying signer.issuer and - * signer.serialNumber. - * [issuer] the issuer attributes (eg: cert.issuer.attributes). - * [serialNumber] the signer's certificate's serial number in - * hexadecimal (eg: cert.serialNumber). - * [digestAlgorithm] the message digest OID, as a string, to use - * (eg: forge.pki.oids.sha1). - * [authenticatedAttributes] an optional array of attributes - * to also sign along with the content. - */ - addSigner: function(signer) { - var issuer = signer.issuer; - var serialNumber = signer.serialNumber; - if (signer.certificate) { - var cert = signer.certificate; - if (typeof cert === "string") { - cert = forge2.pki.certificateFromPem(cert); - } - issuer = cert.issuer.attributes; - serialNumber = cert.serialNumber; - } - var key = signer.key; - if (!key) { - throw new Error( - "Could not add PKCS#7 signer; no private key specified." - ); - } - if (typeof key === "string") { - key = forge2.pki.privateKeyFromPem(key); - } - var digestAlgorithm = signer.digestAlgorithm || forge2.pki.oids.sha1; - switch (digestAlgorithm) { - case forge2.pki.oids.sha1: - case forge2.pki.oids.sha256: - case forge2.pki.oids.sha384: - case forge2.pki.oids.sha512: - case forge2.pki.oids.md5: - break; - default: - throw new Error( - "Could not add PKCS#7 signer; unknown message digest algorithm: " + digestAlgorithm - ); - } - var authenticatedAttributes = signer.authenticatedAttributes || []; - if (authenticatedAttributes.length > 0) { - var contentType = false; - var messageDigest = false; - for (var i = 0; i < authenticatedAttributes.length; ++i) { - var attr = authenticatedAttributes[i]; - if (!contentType && attr.type === forge2.pki.oids.contentType) { - contentType = true; - if (messageDigest) { - break; - } - continue; - } - if (!messageDigest && attr.type === forge2.pki.oids.messageDigest) { - messageDigest = true; - if (contentType) { - break; - } - continue; - } - } - if (!contentType || !messageDigest) { - throw new Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest."); - } - } - msg.signers.push({ - key, - version: 1, - issuer, - serialNumber, - digestAlgorithm, - signatureAlgorithm: forge2.pki.oids.rsaEncryption, - signature: null, - authenticatedAttributes, - unauthenticatedAttributes: [] - }); - }, - /** - * Signs the content. - * @param options Options to apply when signing: - * [detached] boolean. If signing should be done in detached mode. Defaults to false. - */ - sign: function(options) { - options = options || {}; - if (typeof msg.content !== "object" || msg.contentInfo === null) { - msg.contentInfo = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - [ - // ContentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(forge2.pki.oids.data).getBytes() - ) - ] - ); - if ("content" in msg) { - var content; - if (msg.content instanceof forge2.util.ByteBuffer) { - content = msg.content.bytes(); - } else if (typeof msg.content === "string") { - content = forge2.util.encodeUtf8(msg.content); - } - if (options.detached) { - msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content); - } else { - msg.contentInfo.value.push( - // [0] EXPLICIT content - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - content - ) - ]) - ); - } - } - } - if (msg.signers.length === 0) { - return; - } - var mds = addDigestAlgorithmIds(); - addSignerInfos(mds); - }, - verify: function() { - throw new Error("PKCS#7 signature verification not yet implemented."); - }, - /** - * Add a certificate. - * - * @param cert the certificate to add. - */ - addCertificate: function(cert) { - if (typeof cert === "string") { - cert = forge2.pki.certificateFromPem(cert); - } - msg.certificates.push(cert); - }, - /** - * Add a certificate revokation list. - * - * @param crl the certificate revokation list to add. - */ - addCertificateRevokationList: function(crl) { - throw new Error("PKCS#7 CRL support not yet implemented."); - } - }; - return msg; - function addDigestAlgorithmIds() { - var mds = {}; - for (var i = 0; i < msg.signers.length; ++i) { - var signer = msg.signers[i]; - var oid = signer.digestAlgorithm; - if (!(oid in mds)) { - mds[oid] = forge2.md[forge2.pki.oids[oid]].create(); - } - if (signer.authenticatedAttributes.length === 0) { - signer.md = mds[oid]; - } else { - signer.md = forge2.md[forge2.pki.oids[oid]].create(); - } - } - msg.digestAlgorithmIdentifiers = []; - for (var oid in mds) { - msg.digestAlgorithmIdentifiers.push( - // AlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(oid).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ); - } - return mds; - } - function addSignerInfos(mds) { - var content; - if (msg.detachedContent) { - content = msg.detachedContent; - } else { - content = msg.contentInfo.value[1]; - content = content.value[0]; - } - if (!content) { - throw new Error( - "Could not sign PKCS#7 message; there is no content to sign." - ); - } - var contentType = asn1.derToOid(msg.contentInfo.value[0].value); - var bytes = asn1.toDer(content); - bytes.getByte(); - asn1.getBerValueLength(bytes); - bytes = bytes.getBytes(); - for (var oid in mds) { - mds[oid].start().update(bytes); - } - var signingTime = /* @__PURE__ */ new Date(); - for (var i = 0; i < msg.signers.length; ++i) { - var signer = msg.signers[i]; - if (signer.authenticatedAttributes.length === 0) { - if (contentType !== forge2.pki.oids.data) { - throw new Error( - "Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data." - ); - } - } else { - signer.authenticatedAttributesAsn1 = asn1.create( - asn1.Class.CONTEXT_SPECIFIC, - 0, - true, - [] - ); - var attrsAsn1 = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SET, - true, - [] - ); - for (var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) { - var attr = signer.authenticatedAttributes[ai]; - if (attr.type === forge2.pki.oids.messageDigest) { - attr.value = mds[signer.digestAlgorithm].digest(); - } else if (attr.type === forge2.pki.oids.signingTime) { - if (!attr.value) { - attr.value = signingTime; - } - } - attrsAsn1.value.push(_attributeToAsn1(attr)); - signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr)); - } - bytes = asn1.toDer(attrsAsn1).getBytes(); - signer.md.start().update(bytes); - } - signer.signature = signer.key.sign(signer.md, "RSASSA-PKCS1-V1_5"); - } - msg.signerInfos = _signersToAsn1(msg.signers); - } - }; - p7.createEncryptedData = function() { - var msg = null; - msg = { - type: forge2.pki.oids.encryptedData, - version: 0, - encryptedContent: { - algorithm: forge2.pki.oids["aes256-CBC"] - }, - /** - * Reads an EncryptedData content block (in ASN.1 format) - * - * @param obj The ASN.1 representation of the EncryptedData content block - */ - fromAsn1: function(obj) { - _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator); - }, - /** - * Decrypt encrypted content - * - * @param key The (symmetric) key as a byte buffer - */ - decrypt: function(key) { - if (key !== void 0) { - msg.encryptedContent.key = key; - } - _decryptContent(msg); - } - }; - return msg; - }; - p7.createEnvelopedData = function() { - var msg = null; - msg = { - type: forge2.pki.oids.envelopedData, - version: 0, - recipients: [], - encryptedContent: { - algorithm: forge2.pki.oids["aes256-CBC"] - }, - /** - * Reads an EnvelopedData content block (in ASN.1 format) - * - * @param obj the ASN.1 representation of the EnvelopedData content block. - */ - fromAsn1: function(obj) { - var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator); - msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value); - }, - toAsn1: function() { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // ContentType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(msg.type).getBytes() - ), - // [0] EnvelopedData - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(msg.version).getBytes() - ), - // RecipientInfos - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SET, - true, - _recipientsToAsn1(msg.recipients) - ), - // EncryptedContentInfo - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.SEQUENCE, - true, - _encryptedContentToAsn1(msg.encryptedContent) - ) - ]) - ]) - ]); - }, - /** - * Find recipient by X.509 certificate's issuer. - * - * @param cert the certificate with the issuer to look for. - * - * @return the recipient object. - */ - findRecipient: function(cert) { - var sAttr = cert.issuer.attributes; - for (var i = 0; i < msg.recipients.length; ++i) { - var r = msg.recipients[i]; - var rAttr = r.issuer; - if (r.serialNumber !== cert.serialNumber) { - continue; - } - if (rAttr.length !== sAttr.length) { - continue; - } - var match = true; - for (var j = 0; j < sAttr.length; ++j) { - if (rAttr[j].type !== sAttr[j].type || rAttr[j].value !== sAttr[j].value) { - match = false; - break; - } - } - if (match) { - return r; - } - } - return null; - }, - /** - * Decrypt enveloped content - * - * @param recipient The recipient object related to the private key - * @param privKey The (RSA) private key object - */ - decrypt: function(recipient, privKey) { - if (msg.encryptedContent.key === void 0 && recipient !== void 0 && privKey !== void 0) { - switch (recipient.encryptedContent.algorithm) { - case forge2.pki.oids.rsaEncryption: - case forge2.pki.oids.desCBC: - var key = privKey.decrypt(recipient.encryptedContent.content); - msg.encryptedContent.key = forge2.util.createBuffer(key); - break; - default: - throw new Error("Unsupported asymmetric cipher, OID " + recipient.encryptedContent.algorithm); - } - } - _decryptContent(msg); - }, - /** - * Add (another) entity to list of recipients. - * - * @param cert The certificate of the entity to add. - */ - addRecipient: function(cert) { - msg.recipients.push({ - version: 0, - issuer: cert.issuer.attributes, - serialNumber: cert.serialNumber, - encryptedContent: { - // We simply assume rsaEncryption here, since forge.pki only - // supports RSA so far. If the PKI module supports other - // ciphers one day, we need to modify this one as well. - algorithm: forge2.pki.oids.rsaEncryption, - key: cert.publicKey - } - }); - }, - /** - * Encrypt enveloped content. - * - * This function supports two optional arguments, cipher and key, which - * can be used to influence symmetric encryption. Unless cipher is - * provided, the cipher specified in encryptedContent.algorithm is used - * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key - * is (re-)used. If that one's not set, a random key will be generated - * automatically. - * - * @param [key] The key to be used for symmetric encryption. - * @param [cipher] The OID of the symmetric cipher to use. - */ - encrypt: function(key, cipher) { - if (msg.encryptedContent.content === void 0) { - cipher = cipher || msg.encryptedContent.algorithm; - key = key || msg.encryptedContent.key; - var keyLen, ivLen, ciphFn; - switch (cipher) { - case forge2.pki.oids["aes128-CBC"]: - keyLen = 16; - ivLen = 16; - ciphFn = forge2.aes.createEncryptionCipher; - break; - case forge2.pki.oids["aes192-CBC"]: - keyLen = 24; - ivLen = 16; - ciphFn = forge2.aes.createEncryptionCipher; - break; - case forge2.pki.oids["aes256-CBC"]: - keyLen = 32; - ivLen = 16; - ciphFn = forge2.aes.createEncryptionCipher; - break; - case forge2.pki.oids["des-EDE3-CBC"]: - keyLen = 24; - ivLen = 8; - ciphFn = forge2.des.createEncryptionCipher; - break; - default: - throw new Error("Unsupported symmetric cipher, OID " + cipher); - } - if (key === void 0) { - key = forge2.util.createBuffer(forge2.random.getBytes(keyLen)); - } else if (key.length() != keyLen) { - throw new Error("Symmetric key has wrong length; got " + key.length() + " bytes, expected " + keyLen + "."); - } - msg.encryptedContent.algorithm = cipher; - msg.encryptedContent.key = key; - msg.encryptedContent.parameter = forge2.util.createBuffer( - forge2.random.getBytes(ivLen) - ); - var ciph = ciphFn(key); - ciph.start(msg.encryptedContent.parameter.copy()); - ciph.update(msg.content); - if (!ciph.finish()) { - throw new Error("Symmetric encryption failed."); - } - msg.encryptedContent.content = ciph.output; - } - for (var i = 0; i < msg.recipients.length; ++i) { - var recipient = msg.recipients[i]; - if (recipient.encryptedContent.content !== void 0) { - continue; - } - switch (recipient.encryptedContent.algorithm) { - case forge2.pki.oids.rsaEncryption: - recipient.encryptedContent.content = recipient.encryptedContent.key.encrypt( - msg.encryptedContent.key.data - ); - break; - default: - throw new Error("Unsupported asymmetric cipher, OID " + recipient.encryptedContent.algorithm); - } - } - } - }; - return msg; - }; - function _recipientFromAsn1(obj) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) { - var error = new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo."); - error.errors = errors; - throw error; - } - return { - version: capture.version.charCodeAt(0), - issuer: forge2.pki.RDNAttributesAsArray(capture.issuer), - serialNumber: forge2.util.createBuffer(capture.serial).toHex(), - encryptedContent: { - algorithm: asn1.derToOid(capture.encAlgorithm), - parameter: capture.encParameter ? capture.encParameter.value : void 0, - content: capture.encKey - } - }; - } - function _recipientToAsn1(obj) { - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(obj.version).getBytes() - ), - // IssuerAndSerialNumber - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Name - forge2.pki.distinguishedNameToAsn1({ attributes: obj.issuer }), - // Serial - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - forge2.util.hexToBytes(obj.serialNumber) - ) - ]), - // KeyEncryptionAlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(obj.encryptedContent.algorithm).getBytes() - ), - // Parameter, force NULL, only RSA supported for now. - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]), - // EncryptedKey - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - obj.encryptedContent.content - ) - ]); - } - function _recipientsFromAsn1(infos) { - var ret = []; - for (var i = 0; i < infos.length; ++i) { - ret.push(_recipientFromAsn1(infos[i])); - } - return ret; - } - function _recipientsToAsn1(recipients) { - var ret = []; - for (var i = 0; i < recipients.length; ++i) { - ret.push(_recipientToAsn1(recipients[i])); - } - return ret; - } - function _signerToAsn1(obj) { - var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // version - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - asn1.integerToDer(obj.version).getBytes() - ), - // issuerAndSerialNumber - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // name - forge2.pki.distinguishedNameToAsn1({ attributes: obj.issuer }), - // serial - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.INTEGER, - false, - forge2.util.hexToBytes(obj.serialNumber) - ) - ]), - // digestAlgorithm - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(obj.digestAlgorithm).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ]) - ]); - if (obj.authenticatedAttributesAsn1) { - rval.value.push(obj.authenticatedAttributesAsn1); - } - rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(obj.signatureAlgorithm).getBytes() - ), - // parameters (null) - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, "") - ])); - rval.value.push(asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - obj.signature - )); - if (obj.unauthenticatedAttributes.length > 0) { - var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []); - for (var i = 0; i < obj.unauthenticatedAttributes.length; ++i) { - var attr = obj.unauthenticatedAttributes[i]; - attrsAsn1.values.push(_attributeToAsn1(attr)); - } - rval.value.push(attrsAsn1); - } - return rval; - } - function _signersToAsn1(signers) { - var ret = []; - for (var i = 0; i < signers.length; ++i) { - ret.push(_signerToAsn1(signers[i])); - } - return ret; - } - function _attributeToAsn1(attr) { - var value; - if (attr.type === forge2.pki.oids.contentType) { - value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(attr.value).getBytes() - ); - } else if (attr.type === forge2.pki.oids.messageDigest) { - value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - attr.value.bytes() - ); - } else if (attr.type === forge2.pki.oids.signingTime) { - var jan_1_1950 = /* @__PURE__ */ new Date("1950-01-01T00:00:00Z"); - var jan_1_2050 = /* @__PURE__ */ new Date("2050-01-01T00:00:00Z"); - var date = attr.value; - if (typeof date === "string") { - var timestamp = Date.parse(date); - if (!isNaN(timestamp)) { - date = new Date(timestamp); - } else if (date.length === 13) { - date = asn1.utcTimeToDate(date); - } else { - date = asn1.generalizedTimeToDate(date); - } - } - if (date >= jan_1_1950 && date < jan_1_2050) { - value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.UTCTIME, - false, - asn1.dateToUtcTime(date) - ); - } else { - value = asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.GENERALIZEDTIME, - false, - asn1.dateToGeneralizedTime(date) - ); - } - } - return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // AttributeType - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(attr.type).getBytes() - ), - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ - // AttributeValue - value - ]) - ]); - } - function _encryptedContentToAsn1(ec) { - return [ - // ContentType, always Data for the moment - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(forge2.pki.oids.data).getBytes() - ), - // ContentEncryptionAlgorithmIdentifier - asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ - // Algorithm - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OID, - false, - asn1.oidToDer(ec.algorithm).getBytes() - ), - // Parameters (IV) - !ec.parameter ? void 0 : asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - ec.parameter.getBytes() - ) - ]), - // [0] EncryptedContent - asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ - asn1.create( - asn1.Class.UNIVERSAL, - asn1.Type.OCTETSTRING, - false, - ec.content.getBytes() - ) - ]) - ]; - } - function _fromAsn1(msg, obj, validator) { - var capture = {}; - var errors = []; - if (!asn1.validate(obj, validator, capture, errors)) { - var error = new Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message."); - error.errors = error; - throw error; - } - var contentType = asn1.derToOid(capture.contentType); - if (contentType !== forge2.pki.oids.data) { - throw new Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported."); - } - if (capture.encryptedContent) { - var content = ""; - if (forge2.util.isArray(capture.encryptedContent)) { - for (var i = 0; i < capture.encryptedContent.length; ++i) { - if (capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) { - throw new Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects."); - } - content += capture.encryptedContent[i].value; - } - } else { - content = capture.encryptedContent; - } - msg.encryptedContent = { - algorithm: asn1.derToOid(capture.encAlgorithm), - parameter: forge2.util.createBuffer(capture.encParameter.value), - content: forge2.util.createBuffer(content) - }; - } - if (capture.content) { - var content = ""; - if (forge2.util.isArray(capture.content)) { - for (var i = 0; i < capture.content.length; ++i) { - if (capture.content[i].type !== asn1.Type.OCTETSTRING) { - throw new Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects."); - } - content += capture.content[i].value; - } - } else { - content = capture.content; - } - msg.content = forge2.util.createBuffer(content); - } - msg.version = capture.version.charCodeAt(0); - msg.rawCapture = capture; - return capture; - } - function _decryptContent(msg) { - if (msg.encryptedContent.key === void 0) { - throw new Error("Symmetric key not available."); - } - if (msg.content === void 0) { - var ciph; - switch (msg.encryptedContent.algorithm) { - case forge2.pki.oids["aes128-CBC"]: - case forge2.pki.oids["aes192-CBC"]: - case forge2.pki.oids["aes256-CBC"]: - ciph = forge2.aes.createDecryptionCipher(msg.encryptedContent.key); - break; - case forge2.pki.oids["desCBC"]: - case forge2.pki.oids["des-EDE3-CBC"]: - ciph = forge2.des.createDecryptionCipher(msg.encryptedContent.key); - break; - default: - throw new Error("Unsupported symmetric cipher, OID " + msg.encryptedContent.algorithm); - } - ciph.start(msg.encryptedContent.parameter); - ciph.update(msg.encryptedContent.content); - if (!ciph.finish()) { - throw new Error("Symmetric decryption failed."); - } - msg.content = ciph.output; - } - } - } -}); - -// node_modules/node-forge/lib/ssh.js -var require_ssh = __commonJS({ - "node_modules/node-forge/lib/ssh.js"(exports, module) { - var forge2 = require_forge(); - require_aes(); - require_hmac(); - require_md5(); - require_sha1(); - require_util(); - var ssh = module.exports = forge2.ssh = forge2.ssh || {}; - ssh.privateKeyToPutty = function(privateKey, passphrase, comment) { - comment = comment || ""; - passphrase = passphrase || ""; - var algorithm = "ssh-rsa"; - var encryptionAlgorithm = passphrase === "" ? "none" : "aes256-cbc"; - var ppk = "PuTTY-User-Key-File-2: " + algorithm + "\r\n"; - ppk += "Encryption: " + encryptionAlgorithm + "\r\n"; - ppk += "Comment: " + comment + "\r\n"; - var pubbuffer = forge2.util.createBuffer(); - _addStringToBuffer(pubbuffer, algorithm); - _addBigIntegerToBuffer(pubbuffer, privateKey.e); - _addBigIntegerToBuffer(pubbuffer, privateKey.n); - var pub = forge2.util.encode64(pubbuffer.bytes(), 64); - var length = Math.floor(pub.length / 66) + 1; - ppk += "Public-Lines: " + length + "\r\n"; - ppk += pub; - var privbuffer = forge2.util.createBuffer(); - _addBigIntegerToBuffer(privbuffer, privateKey.d); - _addBigIntegerToBuffer(privbuffer, privateKey.p); - _addBigIntegerToBuffer(privbuffer, privateKey.q); - _addBigIntegerToBuffer(privbuffer, privateKey.qInv); - var priv; - if (!passphrase) { - priv = forge2.util.encode64(privbuffer.bytes(), 64); - } else { - var encLen = privbuffer.length() + 16 - 1; - encLen -= encLen % 16; - var padding = _sha1(privbuffer.bytes()); - padding.truncate(padding.length() - encLen + privbuffer.length()); - privbuffer.putBuffer(padding); - var aeskey = forge2.util.createBuffer(); - aeskey.putBuffer(_sha1("\0\0\0\0", passphrase)); - aeskey.putBuffer(_sha1("\0\0\0", passphrase)); - var cipher = forge2.aes.createEncryptionCipher(aeskey.truncate(8), "CBC"); - cipher.start(forge2.util.createBuffer().fillWithByte(0, 16)); - cipher.update(privbuffer.copy()); - cipher.finish(); - var encrypted = cipher.output; - encrypted.truncate(16); - priv = forge2.util.encode64(encrypted.bytes(), 64); - } - length = Math.floor(priv.length / 66) + 1; - ppk += "\r\nPrivate-Lines: " + length + "\r\n"; - ppk += priv; - var mackey = _sha1("putty-private-key-file-mac-key", passphrase); - var macbuffer = forge2.util.createBuffer(); - _addStringToBuffer(macbuffer, algorithm); - _addStringToBuffer(macbuffer, encryptionAlgorithm); - _addStringToBuffer(macbuffer, comment); - macbuffer.putInt32(pubbuffer.length()); - macbuffer.putBuffer(pubbuffer); - macbuffer.putInt32(privbuffer.length()); - macbuffer.putBuffer(privbuffer); - var hmac = forge2.hmac.create(); - hmac.start("sha1", mackey); - hmac.update(macbuffer.bytes()); - ppk += "\r\nPrivate-MAC: " + hmac.digest().toHex() + "\r\n"; - return ppk; - }; - ssh.publicKeyToOpenSSH = function(key, comment) { - var type = "ssh-rsa"; - comment = comment || ""; - var buffer = forge2.util.createBuffer(); - _addStringToBuffer(buffer, type); - _addBigIntegerToBuffer(buffer, key.e); - _addBigIntegerToBuffer(buffer, key.n); - return type + " " + forge2.util.encode64(buffer.bytes()) + " " + comment; - }; - ssh.privateKeyToOpenSSH = function(privateKey, passphrase) { - if (!passphrase) { - return forge2.pki.privateKeyToPem(privateKey); - } - return forge2.pki.encryptRsaPrivateKey( - privateKey, - passphrase, - { legacy: true, algorithm: "aes128" } - ); - }; - ssh.getPublicKeyFingerprint = function(key, options) { - options = options || {}; - var md = options.md || forge2.md.md5.create(); - var type = "ssh-rsa"; - var buffer = forge2.util.createBuffer(); - _addStringToBuffer(buffer, type); - _addBigIntegerToBuffer(buffer, key.e); - _addBigIntegerToBuffer(buffer, key.n); - md.start(); - md.update(buffer.getBytes()); - var digest = md.digest(); - if (options.encoding === "hex") { - var hex = digest.toHex(); - if (options.delimiter) { - return hex.match(/.{2}/g).join(options.delimiter); - } - return hex; - } else if (options.encoding === "binary") { - return digest.getBytes(); - } else if (options.encoding) { - throw new Error('Unknown encoding "' + options.encoding + '".'); - } - return digest; - }; - function _addBigIntegerToBuffer(buffer, val) { - var hexVal = val.toString(16); - if (hexVal[0] >= "8") { - hexVal = "00" + hexVal; - } - var bytes = forge2.util.hexToBytes(hexVal); - buffer.putInt32(bytes.length); - buffer.putBytes(bytes); - } - function _addStringToBuffer(buffer, val) { - buffer.putInt32(val.length); - buffer.putString(val); - } - function _sha1() { - var sha = forge2.md.sha1.create(); - var num = arguments.length; - for (var i = 0; i < num; ++i) { - sha.update(arguments[i]); - } - return sha.digest(); - } - } -}); - -// node_modules/node-forge/lib/index.js -var require_lib = __commonJS({ - "node_modules/node-forge/lib/index.js"(exports, module) { - module.exports = require_forge(); - require_aes(); - require_aesCipherSuites(); - require_asn1(); - require_cipher(); - require_des(); - require_ed25519(); - require_hmac(); - require_kem(); - require_log(); - require_md_all(); - require_mgf1(); - require_pbkdf2(); - require_pem(); - require_pkcs1(); - require_pkcs12(); - require_pkcs7(); - require_pki(); - require_prime(); - require_prng(); - require_pss(); - require_random(); - require_rc2(); - require_ssh(); - require_tls(); - require_util(); - } -}); - -// src/lostcity/server/PreloadedDirs.ts -var PreloadedDirs_exports = {}; -__export(PreloadedDirs_exports, { - jingles: () => jingles, - maps: () => maps, - serverMaps: () => serverMaps, - songs: () => songs -}); -var maps, songs, jingles, serverMaps; -var init_PreloadedDirs = __esm({ - "src/lostcity/server/PreloadedDirs.ts"() { - "use strict"; - maps = ["l29_75", "l30_75", "l31_75", "l32_70", "l32_71", "l32_72", "l32_73", "l32_74", "l32_75", "l33_70", "l33_71", "l33_72", "l33_73", "l33_74", "l33_75", "l33_76", "l34_70", "l34_71", "l34_72", "l34_73", "l34_74", "l34_75", "l34_76", "l35_20", "l35_75", "l35_76", "l36_146", "l36_147", "l36_148", "l36_149", "l36_150", "l36_153", "l36_154", "l36_52", "l36_53", "l36_54", "l36_72", "l36_73", "l36_74", "l36_75", "l36_76", "l37_146", "l37_147", "l37_148", "l37_149", "l37_150", "l37_151", "l37_152", "l37_153", "l37_154", "l37_48", "l37_49", "l37_50", "l37_51", "l37_52", "l37_53", "l37_54", "l37_55", "l37_72", "l37_73", "l37_74", "l37_75", "l38_146", "l38_147", "l38_148", "l38_149", "l38_150", "l38_151", "l38_152", "l38_153", "l38_154", "l38_155", "l38_45", "l38_46", "l38_47", "l38_48", "l38_49", "l38_50", "l38_51", "l38_52", "l38_53", "l38_54", "l38_55", "l38_72", "l38_73", "l38_74", "l39_147", "l39_148", "l39_149", "l39_150", "l39_151", "l39_152", "l39_153", "l39_154", "l39_155", "l39_45", "l39_46", "l39_47", "l39_48", "l39_49", "l39_50", "l39_51", "l39_52", "l39_53", "l39_54", "l39_55", "l39_72", "l39_73", "l39_74", "l39_75", "l39_76", "l40_147", "l40_148", "l40_149", "l40_150", "l40_151", "l40_152", "l40_153", "l40_154", "l40_45", "l40_46", "l40_47", "l40_48", "l40_49", "l40_50", "l40_51", "l40_52", "l40_53", "l40_54", "l40_55", "l40_72", "l40_73", "l40_74", "l40_75", "l40_76", "l41_146", "l41_149", "l41_151", "l41_152", "l41_153", "l41_154", "l41_45", "l41_46", "l41_47", "l41_48", "l41_49", "l41_50", "l41_51", "l41_52", "l41_53", "l41_54", "l41_55", "l41_56", "l41_72", "l41_73", "l41_74", "l41_75", "l42_144", "l42_145", "l42_146", "l42_151", "l42_152", "l42_153", "l42_49", "l42_50", "l42_51", "l42_52", "l42_53", "l42_54", "l42_55", "l42_56", "l42_72", "l42_73", "l42_74", "l42_75", "l43_144", "l43_145", "l43_146", "l43_153", "l43_154", "l43_45", "l43_46", "l43_47", "l43_48", "l43_49", "l43_50", "l43_51", "l43_52", "l43_53", "l43_54", "l43_55", "l43_56", "l43_72", "l43_73", "l43_74", "l43_75", "l44_144", "l44_145", "l44_146", "l44_148", "l44_149", "l44_150", "l44_151", "l44_152", "l44_153", "l44_154", "l44_155", "l44_45", "l44_46", "l44_47", "l44_48", "l44_49", "l44_50", "l44_51", "l44_52", "l44_53", "l44_54", "l44_55", "l44_72", "l44_73", "l44_74", "l44_75", "l45_145", "l45_146", "l45_148", "l45_150", "l45_151", "l45_152", "l45_153", "l45_154", "l45_155", "l45_45", "l45_46", "l45_47", "l45_48", "l45_49", "l45_50", "l45_51", "l45_52", "l45_53", "l45_54", "l45_55", "l45_56", "l45_57", "l45_58", "l45_59", "l45_60", "l45_61", "l45_62", "l45_73", "l45_74", "l45_75", "l45_76", "l46_149", "l46_150", "l46_152", "l46_153", "l46_154", "l46_161", "l46_45", "l46_46", "l46_47", "l46_48", "l46_49", "l46_50", "l46_51", "l46_52", "l46_53", "l46_54", "l46_55", "l46_56", "l46_57", "l46_58", "l46_59", "l46_60", "l46_61", "l46_62", "l46_75", "l47_148", "l47_149", "l47_150", "l47_152", "l47_153", "l47_160", "l47_161", "l47_47", "l47_48", "l47_49", "l47_50", "l47_51", "l47_52", "l47_53", "l47_54", "l47_55", "l47_56", "l47_57", "l47_58", "l47_59", "l47_60", "l47_61", "l47_62", "l47_75", "l48_148", "l48_149", "l48_152", "l48_153", "l48_154", "l48_155", "l48_156", "l48_47", "l48_48", "l48_49", "l48_50", "l48_51", "l48_52", "l48_53", "l48_54", "l48_55", "l48_56", "l48_57", "l48_58", "l48_59", "l48_60", "l48_61", "l48_62", "l49_148", "l49_149", "l49_153", "l49_154", "l49_155", "l49_156", "l49_46", "l49_47", "l49_48", "l49_49", "l49_50", "l49_51", "l49_52", "l49_53", "l49_54", "l49_55", "l49_56", "l49_57", "l49_58", "l49_59", "l49_60", "l49_61", "l49_62", "l50_149", "l50_150", "l50_152", "l50_153", "l50_154", "l50_46", "l50_47", "l50_48", "l50_49", "l50_50", "l50_51", "l50_52", "l50_53", "l50_54", "l50_55", "l50_56", "l50_57", "l50_58", "l50_59", "l50_60", "l50_61", "l50_62", "l51_147", "l51_154", "l51_46", "l51_47", "l51_48", "l51_49", "l51_50", "l51_51", "l51_52", "l51_53", "l51_54", "l51_55", "l51_56", "l51_57", "l51_58", "l51_59", "l51_60", "l51_61", "l51_62", "l52_152", "l52_153", "l52_154", "l52_46", "l52_47", "l52_48", "l52_49", "l52_50", "l52_51", "l52_52", "l52_53", "l52_54", "l52_55", "l52_56", "l52_57", "l52_58", "l52_59", "l52_60", "l52_61", "l52_62", "l53_49", "l53_50", "l53_51", "l53_52", "l53_53", "m29_75", "m30_75", "m31_75", "m32_70", "m32_71", "m32_72", "m32_73", "m32_74", "m32_75", "m33_70", "m33_71", "m33_72", "m33_73", "m33_74", "m33_75", "m33_76", "m34_70", "m34_71", "m34_72", "m34_73", "m34_74", "m34_75", "m34_76", "m35_20", "m35_75", "m35_76", "m36_146", "m36_147", "m36_148", "m36_149", "m36_150", "m36_153", "m36_154", "m36_52", "m36_53", "m36_54", "m36_72", "m36_73", "m36_74", "m36_75", "m36_76", "m37_146", "m37_147", "m37_148", "m37_149", "m37_150", "m37_151", "m37_152", "m37_153", "m37_154", "m37_48", "m37_49", "m37_50", "m37_51", "m37_52", "m37_53", "m37_54", "m37_55", "m37_72", "m37_73", "m37_74", "m37_75", "m38_146", "m38_147", "m38_148", "m38_149", "m38_150", "m38_151", "m38_152", "m38_153", "m38_154", "m38_155", "m38_45", "m38_46", "m38_47", "m38_48", "m38_49", "m38_50", "m38_51", "m38_52", "m38_53", "m38_54", "m38_55", "m38_72", "m38_73", "m38_74", "m39_147", "m39_148", "m39_149", "m39_150", "m39_151", "m39_152", "m39_153", "m39_154", "m39_155", "m39_45", "m39_46", "m39_47", "m39_48", "m39_49", "m39_50", "m39_51", "m39_52", "m39_53", "m39_54", "m39_55", "m39_72", "m39_73", "m39_74", "m39_75", "m39_76", "m40_147", "m40_148", "m40_149", "m40_150", "m40_151", "m40_152", "m40_153", "m40_154", "m40_45", "m40_46", "m40_47", "m40_48", "m40_49", "m40_50", "m40_51", "m40_52", "m40_53", "m40_54", "m40_55", "m40_72", "m40_73", "m40_74", "m40_75", "m40_76", "m41_146", "m41_149", "m41_151", "m41_152", "m41_153", "m41_154", "m41_45", "m41_46", "m41_47", "m41_48", "m41_49", "m41_50", "m41_51", "m41_52", "m41_53", "m41_54", "m41_55", "m41_56", "m41_72", "m41_73", "m41_74", "m41_75", "m42_144", "m42_145", "m42_146", "m42_151", "m42_152", "m42_153", "m42_49", "m42_50", "m42_51", "m42_52", "m42_53", "m42_54", "m42_55", "m42_56", "m42_72", "m42_73", "m42_74", "m42_75", "m43_144", "m43_145", "m43_146", "m43_153", "m43_154", "m43_45", "m43_46", "m43_47", "m43_48", "m43_49", "m43_50", "m43_51", "m43_52", "m43_53", "m43_54", "m43_55", "m43_56", "m43_72", "m43_73", "m43_74", "m43_75", "m44_144", "m44_145", "m44_146", "m44_148", "m44_149", "m44_150", "m44_151", "m44_152", "m44_153", "m44_154", "m44_155", "m44_45", "m44_46", "m44_47", "m44_48", "m44_49", "m44_50", "m44_51", "m44_52", "m44_53", "m44_54", "m44_55", "m44_72", "m44_73", "m44_74", "m44_75", "m45_145", "m45_146", "m45_148", "m45_150", "m45_151", "m45_152", "m45_153", "m45_154", "m45_155", "m45_45", "m45_46", "m45_47", "m45_48", "m45_49", "m45_50", "m45_51", "m45_52", "m45_53", "m45_54", "m45_55", "m45_56", "m45_57", "m45_58", "m45_59", "m45_60", "m45_61", "m45_62", "m45_73", "m45_74", "m45_75", "m45_76", "m46_149", "m46_150", "m46_152", "m46_153", "m46_154", "m46_161", "m46_45", "m46_46", "m46_47", "m46_48", "m46_49", "m46_50", "m46_51", "m46_52", "m46_53", "m46_54", "m46_55", "m46_56", "m46_57", "m46_58", "m46_59", "m46_60", "m46_61", "m46_62", "m46_75", "m47_148", "m47_149", "m47_150", "m47_152", "m47_153", "m47_160", "m47_161", "m47_47", "m47_48", "m47_49", "m47_50", "m47_51", "m47_52", "m47_53", "m47_54", "m47_55", "m47_56", "m47_57", "m47_58", "m47_59", "m47_60", "m47_61", "m47_62", "m47_75", "m48_148", "m48_149", "m48_152", "m48_153", "m48_154", "m48_155", "m48_156", "m48_47", "m48_48", "m48_49", "m48_50", "m48_51", "m48_52", "m48_53", "m48_54", "m48_55", "m48_56", "m48_57", "m48_58", "m48_59", "m48_60", "m48_61", "m48_62", "m49_148", "m49_149", "m49_153", "m49_154", "m49_155", "m49_156", "m49_46", "m49_47", "m49_48", "m49_49", "m49_50", "m49_51", "m49_52", "m49_53", "m49_54", "m49_55", "m49_56", "m49_57", "m49_58", "m49_59", "m49_60", "m49_61", "m49_62", "m50_149", "m50_150", "m50_152", "m50_153", "m50_154", "m50_46", "m50_47", "m50_48", "m50_49", "m50_50", "m50_51", "m50_52", "m50_53", "m50_54", "m50_55", "m50_56", "m50_57", "m50_58", "m50_59", "m50_60", "m50_61", "m50_62", "m51_147", "m51_154", "m51_46", "m51_47", "m51_48", "m51_49", "m51_50", "m51_51", "m51_52", "m51_53", "m51_54", "m51_55", "m51_56", "m51_57", "m51_58", "m51_59", "m51_60", "m51_61", "m51_62", "m52_152", "m52_153", "m52_154", "m52_46", "m52_47", "m52_48", "m52_49", "m52_50", "m52_51", "m52_52", "m52_53", "m52_54", "m52_55", "m52_56", "m52_57", "m52_58", "m52_59", "m52_60", "m52_61", "m52_62", "m53_49", "m53_50", "m53_51", "m53_52", "m53_53"]; - songs = ["adventure.mid", "al_kharid.mid", "alone.mid", "ambience_2.mid", "ambience_3.mid", "ambience_4.mid", "ambient_jungle.mid", "arabian.mid", "arabian2.mid", "arabian3.mid", "arabique.mid", "army_of_darkness.mid", "arrival.mid", "attack1.mid", "attack2.mid", "attack3.mid", "attack4.mid", "attack5.mid", "attack6.mid", "attention.mid", "autumn_voyage.mid", "background2.mid", "ballad_of_enchantment.mid", "baroque.mid", "beyond.mid", "big_chords.mid", "book_of_spells.mid", "camelot.mid", "cave_background1.mid", "cavern.mid", "cellar_song1.mid", "chain_of_command.mid", "chompy_hunt.mid", "close_quarters.mid", "crystal_cave.mid", "crystal_sword.mid", "cursed.mid", "dangerous.mid", "dark2.mid", "deep_wildy.mid", "desert_voyage.mid", "doorways.mid", "dream1.mid", "duel_arena.mid", "dunjun.mid", "egypt.mid", "emotion.mid", "emperor.mid", "escape.mid", "expanse.mid", "expecting.mid", "expedition.mid", "fade_test.mid", "faerie.mid", "fanfare.mid", "fanfare2.mid", "fanfare3.mid", "fishing.mid", "flute_salad.mid", "forbidden.mid", "forever.mid", "game_intro_1.mid", "gaol.mid", "garden.mid", "gnome.mid", "gnome_king.mid", "gnome_theme.mid", "gnome_village.mid", "gnome_village2.mid", "gnomeball.mid", "greatness.mid", "grumpy.mid", "harmony.mid", "harmony2.mid", "heart_and_mind.mid", "high_seas.mid", "horizon.mid", "iban.mid", "ice_melody.mid", "in_the_manor.mid", "inspiration.mid", "intrepid.mid", "jolly-r.mid", "jungle_island.mid", "jungly1.mid", "jungly2.mid", "jungly3.mid", "knightly.mid", "landlubber.mid", "lasting.mid", "legion.mid", "lightness.mid", "lightwalk.mid", "lonesome.mid", "long_ago.mid", "long_way_home.mid", "lullaby.mid", "mage_arena.mid", "magic_dance.mid", "magical_journey.mid", "march2.mid", "medieval.mid", "mellow.mid", "miles_away.mid", "miracle_dance.mid", "monarch_waltz.mid", "moody.mid", "neverland.mid", "newbie_melody.mid", "nightfall.mid", "nomad.mid", "null.mid", "organ_music_1.mid", "organ_music_2.mid", "oriental.mid", "overture.mid", "parade.mid", "quest.mid", "regal2.mid", "reggae.mid", "reggae2.mid", "riverside.mid", "royale.mid", "rune_essence.mid", "sad_meadow.mid", "scape_cave.mid", "scape_main.mid", "scape_sad1.mid", "scape_soft.mid", "scape_wild1.mid", "sea_shanty.mid", "sea_shanty2.mid", "serenade.mid", "serene.mid", "shine.mid", "shining.mid", "silence.mid", "soundscape.mid", "spirit.mid", "splendour.mid", "spooky2.mid", "spooky_jungle.mid", "starlight.mid", "start.mid", "still_night.mid", "talking_forest.mid", "the_desert.mid", "the_shadow.mid", "the_tower.mid", "theme.mid", "tomorrow.mid", "trawler.mid", "trawler_minor.mid", "tree_spirits.mid", "tribal.mid", "tribal2.mid", "tribal_background.mid", "trinity.mid", "troubled.mid", "undercurrent.mid", "underground.mid", "understanding.mid", "unknown_land.mid", "upass1.mid", "upcoming.mid", "venture.mid", "venture2.mid", "vision.mid", "voodoo_cult.mid", "voyage.mid", "wander.mid", "waterfall.mid", "wilderness2.mid", "wilderness3.mid", "wilderness4.mid", "witching.mid", "wolf_mountain.mid", "wonder.mid", "wonderous.mid", "workshop.mid", "yesteryear.mid", "zealot.mid"]; - jingles = ["advance agility.mid", "advance attack.mid", "advance attack2.mid", "advance cooking.mid", "advance cooking2.mid", "advance crafting.mid", "advance crafting2.mid", "advance defense.mid", "advance defense2.mid", "advance firemarking.mid", "advance firemarking2.mid", "advance fishing.mid", "advance fishing2.mid", "advance fletching.mid", "advance fletching2.mid", "advance herblaw.mid", "advance herblaw2.mid", "advance hitpoints.mid", "advance hitpoints2.mid", "advance magic.mid", "advance magic2.mid", "advance mining.mid", "advance mining2.mid", "advance prayer.mid", "advance prayer2.mid", "advance ranged.mid", "advance ranged2.mid", "advance runecraft.mid", "advance runecraft2.mid", "advance smithing.mid", "advance smithing2.mid", "advance strength.mid", "advance strength2.mid", "advance thieving.mid", "advance thieving2.mid", "advance woodcutting.mid", "advance woodcutting2.mid", "death.mid", "death2.mid", "dice lose.mid", "dice win.mid", "duel start.mid", "duel win2.mid", "quest complete 1.mid", "quest complete 2.mid", "quest complete 3.mid", "sailing journey.mid", "treasure hunt win.mid"]; - serverMaps = ["m29_75", "m30_75", "m31_75", "m32_70", "m32_71", "m32_72", "m32_73", "m32_74", "m32_75", "m33_70", "m33_71", "m33_72", "m33_73", "m33_74", "m33_75", "m33_76", "m34_70", "m34_71", "m34_72", "m34_73", "m34_74", "m34_75", "m34_76", "m35_20", "m35_75", "m35_76", "m36_146", "m36_147", "m36_148", "m36_149", "m36_150", "m36_153", "m36_154", "m36_52", "m36_53", "m36_54", "m36_72", "m36_73", "m36_74", "m36_75", "m36_76", "m37_146", "m37_147", "m37_148", "m37_149", "m37_150", "m37_151", "m37_152", "m37_153", "m37_154", "m37_48", "m37_49", "m37_50", "m37_51", "m37_52", "m37_53", "m37_54", "m37_55", "m37_72", "m37_73", "m37_74", "m37_75", "m38_146", "m38_147", "m38_148", "m38_149", "m38_150", "m38_151", "m38_152", "m38_153", "m38_154", "m38_155", "m38_45", "m38_46", "m38_47", "m38_48", "m38_49", "m38_50", "m38_51", "m38_52", "m38_53", "m38_54", "m38_55", "m38_72", "m38_73", "m38_74", "m39_147", "m39_148", "m39_149", "m39_150", "m39_151", "m39_152", "m39_153", "m39_154", "m39_155", "m39_45", "m39_46", "m39_47", "m39_48", "m39_49", "m39_50", "m39_51", "m39_52", "m39_53", "m39_54", "m39_55", "m39_72", "m39_73", "m39_74", "m39_75", "m39_76", "m40_147", "m40_148", "m40_149", "m40_150", "m40_151", "m40_152", "m40_153", "m40_154", "m40_45", "m40_46", "m40_47", "m40_48", "m40_49", "m40_50", "m40_51", "m40_52", "m40_53", "m40_54", "m40_55", "m40_72", "m40_73", "m40_74", "m40_75", "m40_76", "m41_146", "m41_149", "m41_151", "m41_152", "m41_153", "m41_154", "m41_45", "m41_46", "m41_47", "m41_48", "m41_49", "m41_50", "m41_51", "m41_52", "m41_53", "m41_54", "m41_55", "m41_56", "m41_72", "m41_73", "m41_74", "m41_75", "m42_144", "m42_145", "m42_146", "m42_151", "m42_152", "m42_153", "m42_49", "m42_50", "m42_51", "m42_52", "m42_53", "m42_54", "m42_55", "m42_56", "m42_72", "m42_73", "m42_74", "m42_75", "m43_144", "m43_145", "m43_146", "m43_153", "m43_154", "m43_45", "m43_46", "m43_47", "m43_48", "m43_49", "m43_50", "m43_51", "m43_52", "m43_53", "m43_54", "m43_55", "m43_56", "m43_72", "m43_73", "m43_74", "m43_75", "m44_144", "m44_145", "m44_146", "m44_148", "m44_149", "m44_150", "m44_151", "m44_152", "m44_153", "m44_154", "m44_155", "m44_45", "m44_46", "m44_47", "m44_48", "m44_49", "m44_50", "m44_51", "m44_52", "m44_53", "m44_54", "m44_55", "m44_72", "m44_73", "m44_74", "m44_75", "m45_145", "m45_146", "m45_148", "m45_150", "m45_151", "m45_152", "m45_153", "m45_154", "m45_155", "m45_45", "m45_46", "m45_47", "m45_48", "m45_49", "m45_50", "m45_51", "m45_52", "m45_53", "m45_54", "m45_55", "m45_56", "m45_57", "m45_58", "m45_59", "m45_60", "m45_61", "m45_62", "m45_73", "m45_74", "m45_75", "m45_76", "m46_149", "m46_150", "m46_152", "m46_153", "m46_154", "m46_161", "m46_45", "m46_46", "m46_47", "m46_48", "m46_49", "m46_50", "m46_51", "m46_52", "m46_53", "m46_54", "m46_55", "m46_56", "m46_57", "m46_58", "m46_59", "m46_60", "m46_61", "m46_62", "m46_75", "m47_148", "m47_149", "m47_150", "m47_152", "m47_153", "m47_160", "m47_161", "m47_47", "m47_48", "m47_49", "m47_50", "m47_51", "m47_52", "m47_53", "m47_54", "m47_55", "m47_56", "m47_57", "m47_58", "m47_59", "m47_60", "m47_61", "m47_62", "m47_75", "m48_148", "m48_149", "m48_152", "m48_153", "m48_154", "m48_155", "m48_156", "m48_47", "m48_48", "m48_49", "m48_50", "m48_51", "m48_52", "m48_53", "m48_54", "m48_55", "m48_56", "m48_57", "m48_58", "m48_59", "m48_60", "m48_61", "m48_62", "m49_148", "m49_149", "m49_153", "m49_154", "m49_155", "m49_156", "m49_46", "m49_47", "m49_48", "m49_49", "m49_50", "m49_51", "m49_52", "m49_53", "m49_54", "m49_55", "m49_56", "m49_57", "m49_58", "m49_59", "m49_60", "m49_61", "m49_62", "m50_149", "m50_150", "m50_152", "m50_153", "m50_154", "m50_46", "m50_47", "m50_48", "m50_49", "m50_50", "m50_51", "m50_52", "m50_53", "m50_54", "m50_55", "m50_56", "m50_57", "m50_58", "m50_59", "m50_60", "m50_61", "m50_62", "m51_147", "m51_154", "m51_46", "m51_47", "m51_48", "m51_49", "m51_50", "m51_51", "m51_52", "m51_53", "m51_54", "m51_55", "m51_56", "m51_57", "m51_58", "m51_59", "m51_60", "m51_61", "m51_62", "m52_152", "m52_153", "m52_154", "m52_46", "m52_47", "m52_48", "m52_49", "m52_50", "m52_51", "m52_52", "m52_53", "m52_54", "m52_55", "m52_56", "m52_57", "m52_58", "m52_59", "m52_60", "m52_61", "m52_62", "m53_49", "m53_50", "m53_51", "m53_52", "m53_53"]; - } -}); - -// src/lostcity/engine/World.ts - -// src/jagex2/jstring/JString.ts -function toBase37(string) { - string = string.trim(); - let l = 0n; - for (let i = 0; i < string.length && i < 12; i++) { - const c = string.charCodeAt(i); - l *= 37n; - if (c >= 65 && c <= 90) { - l += BigInt(c + 1 - 65); - } else if (c >= 97 && c <= 122) { - l += BigInt(c + 1 - 97); - } else if (c >= 48 && c <= 57) { - l += BigInt(c + 27 - 48); - } - } - return l; -} -var BASE37_LOOKUP = [ - "_", - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9" -]; -function fromBase37(value) { - if (value < 0n || value >= 6582952005840035281n) { - return "invalid_name"; - } - if (value % 37n === 0n) { - return "invalid_name"; - } - let len = 0; - const chars = Array(12); - while (value !== 0n) { - const l1 = value; - value /= 37n; - chars[11 - len++] = BASE37_LOOKUP[Number(l1 - value * 37n)]; - } - return chars.slice(12 - len).join(""); -} -function toTitleCase(str) { - return str.replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()); -} -function toSafeName(name) { - return fromBase37(toBase37(name)); -} -function toDisplayName(name) { - return toTitleCase(toSafeName(name).replaceAll("_", " ")); -} - -// src/lostcity/cache/config/CategoryType.ts - -// src/jagex2/io/Packet.ts -var import_node_forge = __toESM(require_lib(), 1); - -// src/jagex2/datastruct/Linkable.ts -var Linkable = class { - key; - next; - prev; - constructor() { - this.key = 0n; - this.next = this; - this.prev = this; - } - unlink() { - if (!this.prev || !this.next) { - return; - } - this.prev.next = this.next; - this.next.prev = this.prev; - this.next = null; - this.prev = null; - } -}; - -// src/jagex2/datastruct/LinkList.ts -var LinkList = class { - sentinel; - cursor = null; - constructor() { - const head = new Linkable(); - head.next = head; - head.prev = head; - this.sentinel = head; - } - addTail(node) { - if (node.prev) { - node.unlink(); - } - node.prev = this.sentinel.prev; - node.next = this.sentinel; - if (node.prev) { - node.prev.next = node; - } - node.next.prev = node; - } - addHead(node) { - if (node.prev) { - node.unlink(); - } - node.prev = this.sentinel; - node.next = this.sentinel.next; - node.prev.next = node; - if (node.next) { - node.next.prev = node; - } - } - removeHead() { - const node = this.sentinel.next; - if (node === this.sentinel) { - return null; - } - node?.unlink(); - return node; - } - head() { - const node = this.sentinel.next; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.next || null; - return node; - } - tail() { - const node = this.sentinel.prev; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.prev || null; - return node; - } - next() { - const node = this.cursor; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.next || null; - return node; - } - prev() { - const node = this.cursor; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.prev || null; - return node; - } - clear() { - while (true) { - const node = this.sentinel.next; - if (node === this.sentinel) { - return; - } - node?.unlink(); - } - } -}; - -// src/jagex2/datastruct/Hashable.ts -var Hashable = class extends Linkable { - nextHashable; - prevHashable; - constructor() { - super(); - this.nextHashable = this; - this.prevHashable = this; - } - uncache() { - if (!this.prevHashable || !this.nextHashable) { - return; - } - this.prevHashable.nextHashable = this.nextHashable; - this.nextHashable.prevHashable = this.prevHashable; - this.nextHashable = null; - this.prevHashable = null; - } -}; - -// src/jagex2/io/Packet.ts -var BigInteger = import_node_forge.default.jsbn.BigInteger; -var Packet = class _Packet extends Hashable { - static crctable = new Int32Array(256); - static bitmask = new Uint32Array(33); - /** - * Reversed CRC-32 polynomial for Cyclic Redundancy Check (CRC). - * This is sometimes referred to as CRC32B. - */ - static crc32b = 3988292384; - static { - for (let i = 0; i < 32; i++) { - this.bitmask[i] = (1 << i) - 1; - } - this.bitmask[32] = 4294967295; - for (let b = 0; b < 256; b++) { - let remainder = b; - for (let bit = 0; bit < 8; bit++) { - if ((remainder & 1) == 1) { - remainder = remainder >>> 1 ^ this.crc32b; - } else { - remainder >>>= 1; - } - } - this.crctable[b] = remainder; - } - } - static getcrc(src, offset, length) { - let crc = 4294967295; - for (let i = offset; i < length; i++) { - crc = crc >>> 8 ^ this.crctable[(crc ^ src[i]) & 255]; - } - return ~crc; - } - static checkcrc(src, offset, length, expected = 0) { - const checksum = _Packet.getcrc(src, offset, length); - return checksum == expected; - } - static alloc(type) { - let packet = null; - if (type === 0 && this.cacheMinCount > 0) { - packet = this.cacheMin.removeHead(); - this.cacheMinCount--; - } else if (type === 1 && this.cacheMidCount > 0) { - packet = this.cacheMid.removeHead(); - this.cacheMidCount--; - } else if (type === 2 && this.cacheMaxCount > 0) { - packet = this.cacheMax.removeHead(); - this.cacheMaxCount--; - } else if (type === 3 && this.cacheBigCount > 0) { - packet = this.cacheBig.removeHead(); - this.cacheBigCount--; - } else if (type === 4 && this.cacheHugeCount > 0) { - packet = this.cacheHuge.removeHead(); - this.cacheHugeCount--; - } else if (type === 5 && this.cacheUnimaginableCount > 0) { - packet = this.cacheUnimaginable.removeHead(); - this.cacheUnimaginableCount--; - } - if (packet !== null) { - packet.pos = 0; - packet.bitPos = 0; - return packet; - } - if (type === 0) { - return new _Packet(new Uint8Array(100)); - } else if (type === 1) { - return new _Packet(new Uint8Array(5e3)); - } else if (type === 2) { - return new _Packet(new Uint8Array(3e4)); - } else if (type === 3) { - return new _Packet(new Uint8Array(1e5)); - } else if (type === 4) { - return new _Packet(new Uint8Array(5e5)); - } else if (type === 5) { - return new _Packet(new Uint8Array(2e6)); - } else { - return new _Packet(new Uint8Array(type)); - } - } - static load(path4, seekToEnd = false) { - const packet = new _Packet(new Uint8Array(fs.readFileSync(path4))); - if (seekToEnd) { - packet.pos = packet.data.length; - } - return packet; - } - static async loadAsync(path4, seekToEnd = false) { - const packet = new _Packet(new Uint8Array(await (await fetch(path4)).arrayBuffer())); - if (seekToEnd) { - packet.pos = packet.data.length; - } - return packet; - } - static cacheMinCount = 0; - static cacheMidCount = 0; - static cacheMaxCount = 0; - static cacheBigCount = 0; - static cacheHugeCount = 0; - static cacheUnimaginableCount = 0; - static cacheMin = new LinkList(); - static cacheMid = new LinkList(); - static cacheMax = new LinkList(); - static cacheBig = new LinkList(); - static cacheHuge = new LinkList(); - static cacheUnimaginable = new LinkList(); - data; - #view; - pos; - bitPos; - constructor(src) { - super(); - this.data = src; - this.#view = new DataView(this.data.buffer); - this.pos = 0; - this.bitPos = 0; - } - get available() { - return this.data.length - this.pos; - } - get length() { - return this.data.length; - } - release() { - this.pos = 0; - this.bitPos = 0; - if (this.data.length === 100 && _Packet.cacheMinCount < 1e3) { - _Packet.cacheMin.addTail(this); - _Packet.cacheMinCount++; - } else if (this.data.length === 5e3 && _Packet.cacheMidCount < 250) { - _Packet.cacheMid.addTail(this); - _Packet.cacheMidCount++; - } else if (this.data.length === 3e4 && _Packet.cacheMaxCount < 50) { - _Packet.cacheMax.addTail(this); - _Packet.cacheMaxCount++; - } else if (this.data.length === 1e5 && _Packet.cacheBigCount < 10) { - _Packet.cacheBig.addTail(this); - _Packet.cacheBigCount++; - } else if (this.data.length === 5e5 && _Packet.cacheHugeCount < 5) { - _Packet.cacheHuge.addTail(this); - _Packet.cacheHugeCount++; - } else if (this.data.length === 2e6 && _Packet.cacheUnimaginableCount < 2) { - _Packet.cacheUnimaginable.addTail(this); - _Packet.cacheUnimaginableCount++; - } - } - save(filePath, length = this.pos, start = 0) { - if (typeof self === "undefined") { - const dir = path.dirname(filePath); - if (!fs.existsSync(dir)) { - fs.mkdirSync(dir, { recursive: true }); - } - fs.writeFileSync(filePath, this.data.subarray(start, start + length)); - } else { - const blob = new Blob([this.data.subarray(start, start + length)], { type: "application/octet-stream" }); - const url = URL.createObjectURL(blob); - self.postMessage({ type: "save", value: url, path: filePath }); - } - } - p1(value) { - this.#view.setUint8(this.pos++, value); - } - p2(value) { - this.#view.setUint16(this.pos, value); - this.pos += 2; - } - ip2(value) { - this.#view.setUint16(this.pos, value, true); - this.pos += 2; - } - p3(value) { - this.#view.setUint8(this.pos++, value >> 16); - this.#view.setUint16(this.pos, value); - this.pos += 2; - } - p4(value) { - this.#view.setInt32(this.pos, value); - this.pos += 4; - } - ip4(value) { - this.#view.setInt32(this.pos, value, true); - this.pos += 4; - } - p8(value) { - this.#view.setBigInt64(this.pos, value); - this.pos += 8; - } - pbool(value) { - this.p1(value ? 1 : 0); - } - pjstr(str, terminator = 10) { - const length = str.length; - for (let i = 0; i < length; i++) { - this.#view.setUint8(this.pos++, str.charCodeAt(i)); - } - this.#view.setUint8(this.pos++, terminator); - } - pdata(src, offset, length) { - this.data.set(src.subarray(offset, offset + length), this.pos); - this.pos += length - offset; - } - psize4(size) { - this.#view.setUint32(this.pos - size - 4, size); - } - psize2(size) { - this.#view.setUint16(this.pos - size - 2, size); - } - psize1(size) { - this.#view.setUint8(this.pos - size - 1, size); - } - psmarts(value) { - if (value < 64 && value >= 64) { - this.p1(value + 64); - } else if (value < 16384 && value >= -16384) { - this.p2(value + 49152); - } else { - throw new Error("Error psmarts out of range: " + value); - } - } - psmart(value) { - if (value >= 0 && value < 128) { - this.p1(value); - } else if (value >= 0 && value < 32768) { - this.p2(value + 32768); - } else { - throw new Error("Error psmart out of range: " + value); - } - } - // ---- - g1() { - return this.#view.getUint8(this.pos++); - } - g1b() { - return this.#view.getInt8(this.pos++); - } - g2() { - this.pos += 2; - return this.#view.getUint16(this.pos - 2); - } - g2s() { - this.pos += 2; - return this.#view.getInt16(this.pos - 2); - } - ig2() { - this.pos += 2; - return this.#view.getUint16(this.pos - 2, true); - } - g3() { - const result = this.#view.getUint8(this.pos++) << 16 | this.#view.getUint16(this.pos); - this.pos += 2; - return result; - } - g4() { - this.pos += 4; - return this.#view.getInt32(this.pos - 4); - } - ig4() { - this.pos += 4; - return this.#view.getInt32(this.pos - 4, true); - } - g8() { - this.pos += 8; - return this.#view.getBigInt64(this.pos - 8); - } - gbool() { - return this.g1() === 1; - } - gjstr(terminator = 10) { - const length = this.data.length; - let str = ""; - let b; - while ((b = this.#view.getUint8(this.pos++)) !== terminator && this.pos < length) { - str += String.fromCharCode(b); - } - return str; - } - gdata(dest, offset, length) { - dest.set(this.data.subarray(this.pos, this.pos + length), offset); - this.pos += length; - } - gsmarts() { - return this.#view.getUint8(this.pos) < 128 ? this.g1() - 64 : this.g2() - 49152; - } - gsmart() { - return this.#view.getUint8(this.pos) < 128 ? this.g1() : this.g2() - 32768; - } - bits() { - this.bitPos = this.pos << 3; - } - bytes() { - this.pos = this.bitPos + 7 >>> 3; - } - gBit(n) { - let bytePos = this.bitPos >>> 3; - let remaining = 8 - (this.bitPos & 7); - let value = 0; - this.bitPos += n; - for (; n > remaining; remaining = 8) { - value += (this.#view.getUint8(bytePos++) & _Packet.bitmask[remaining]) << n - remaining; - n -= remaining; - } - if (n == remaining) { - value += this.#view.getUint8(bytePos) & _Packet.bitmask[remaining]; - } else { - value += this.#view.getUint8(bytePos) >>> remaining - n & _Packet.bitmask[n]; - } - return value; - } - pBit(n, value) { - const pos = this.bitPos; - this.bitPos += n; - let bytePos = pos >>> 3; - let remaining = 8 - (pos & 7); - const view = this.#view; - for (; n > remaining; remaining = 8) { - const shift2 = (1 << remaining) - 1; - const byte2 = view.getUint8(bytePos); - view.setUint8(bytePos++, byte2 & ~shift2 | value >>> n - remaining & shift2); - n -= remaining; - } - const r = remaining - n; - const shift = (1 << n) - 1; - const byte = view.getUint8(bytePos); - view.setUint8(bytePos, byte & ~shift << r | (value & shift) << r); - } - rsaenc(pem) { - const length = this.pos; - this.pos = 0; - const dec = new Uint8Array(length); - this.gdata(dec, 0, dec.length); - const bigRaw = new BigInteger(Array.from(dec)); - const rawEnc = Uint8Array.from(bigRaw.modPow(pem.e, pem.n).toByteArray()); - this.pos = 0; - this.p1(rawEnc.length); - this.pdata(rawEnc, 0, rawEnc.length); - } - rsadec(pem) { - const p = pem.p; - const q = pem.q; - const dP = pem.dP; - const dQ = pem.dQ; - const qInv = pem.qInv; - const enc = new Uint8Array(this.g1()); - this.gdata(enc, 0, enc.length); - const bigRaw = new BigInteger(Array.from(enc)); - const m1 = bigRaw.mod(p).modPow(dP, p); - const m2 = bigRaw.mod(q).modPow(dQ, q); - const h = qInv.multiply(m1.subtract(m2)).mod(p); - const rawDec = new Uint8Array(m2.add(h.multiply(q)).toByteArray()); - this.pos = 0; - this.pdata(rawDec, 0, rawDec.length); - this.pos = 0; - } - // later revs have tinyenc/tinydec methods - // later revs have alt methods for packet obfuscation -}; - -// src/lostcity/cache/config/ConfigType.ts -var ConfigType = class { - id; - debugname = null; - constructor(id) { - this.id = id; - } - decodeType(dat) { - while (dat.available > 0) { - const code = dat.g1(); - if (code === 0) { - break; - } - this.decode(code, dat); - } - } -}; - -// src/lostcity/cache/config/CategoryType.ts -var CategoryType = class _CategoryType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static load(dir) { - if (!fs2.existsSync(`${dir}/server/category.dat`)) { - console.log("Warning: No category.dat found."); - return; - } - const dat = Packet.load(`${dir}/server/category.dat`); - this.parse(dat); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/category.dat`); - if (!file.ok) { - console.log("Warning: No category.dat found."); - return; - } - const dat = new Packet(new Uint8Array(await file.arrayBuffer())); - this.parse(dat); - } - static parse(dat) { - _CategoryType.configNames = /* @__PURE__ */ new Map(); - _CategoryType.configs = []; - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new _CategoryType(id); - config.decodeType(dat); - _CategoryType.configs[id] = config; - if (config.debugname) { - _CategoryType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return _CategoryType.configs[id]; - } - static getId(name) { - return _CategoryType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - // ---- - decode(code, dat) { - this.debugname = dat.gjstr(); - } - toString() { - return this.debugname ?? `category_${this.id}`; - } -}; - -// src/lostcity/cache/config/DbRowType.ts - -// src/lostcity/cache/config/DbTableType.ts - -// src/lostcity/cache/config/ScriptVarType.ts -var ScriptVarType = class _ScriptVarType { - static INT = 105; - // i - static AUTOINT = 255; - // ÿ - virtual type used for enum keys - static STRING = 115; - // s - static ENUM = 103; - // g - static OBJ = 111; - // o - static LOC = 108; - // l - static COMPONENT = 73; - // I - static NAMEDOBJ = 79; - // O - static STRUCT = 74; - // J - static BOOLEAN = 49; - // 1 - static COORD = 99; - // c - static CATEGORY = 121; - // y - static SPOTANIM = 116; - // t - static NPC = 110; - // n - static INV = 118; - // v - static SYNTH = 80; - // P - static SEQ = 65; - // A - static STAT = 83; - // S - static VARP = 86; - // V - static PLAYER_UID = 112; - // p - static NPC_UID = 78; - // N - static INTERFACE = 97; - // a - static NPC_STAT = 254; - // þ - static IDKIT = 75; - // K - static getType(type) { - switch (type) { - case _ScriptVarType.INT: - return "int"; - case _ScriptVarType.STRING: - return "string"; - case _ScriptVarType.ENUM: - return "enum"; - case _ScriptVarType.OBJ: - return "obj"; - case _ScriptVarType.LOC: - return "loc"; - case _ScriptVarType.COMPONENT: - return "component"; - case _ScriptVarType.NAMEDOBJ: - return "namedobj"; - case _ScriptVarType.STRUCT: - return "struct"; - case _ScriptVarType.BOOLEAN: - return "boolean"; - case _ScriptVarType.COORD: - return "coord"; - case _ScriptVarType.CATEGORY: - return "category"; - case _ScriptVarType.SPOTANIM: - return "spotanim"; - case _ScriptVarType.NPC: - return "npc"; - case _ScriptVarType.INV: - return "inv"; - case _ScriptVarType.SYNTH: - return "synth"; - case _ScriptVarType.SEQ: - return "seq"; - case _ScriptVarType.STAT: - return "stat"; - case _ScriptVarType.AUTOINT: - return "autoint"; - case _ScriptVarType.VARP: - return "varp"; - case _ScriptVarType.PLAYER_UID: - return "player_uid"; - case _ScriptVarType.NPC_UID: - return "npc_uid"; - case _ScriptVarType.INTERFACE: - return "interface"; - case _ScriptVarType.NPC_STAT: - return "npc_stat"; - case _ScriptVarType.IDKIT: - return "idkit"; - default: - return "unknown"; - } - } - static getTypeChar(type) { - let char = "i"; - switch (type) { - case "int": - char = "i"; - break; - case "autoint": - char = "\xFF"; - break; - case "string": - char = "s"; - break; - case "enum": - char = "g"; - break; - case "obj": - char = "o"; - break; - case "loc": - char = "l"; - break; - case "component": - char = "I"; - break; - case "namedobj": - char = "O"; - break; - case "struct": - char = "J"; - break; - case "boolean": - char = "1"; - break; - case "coord": - char = "c"; - break; - case "category": - char = "y"; - break; - case "spotanim": - char = "t"; - break; - case "npc": - char = "n"; - break; - case "inv": - char = "v"; - break; - case "synth": - char = "P"; - break; - case "seq": - char = "A"; - break; - case "stat": - char = "S"; - break; - case "varp": - char = "V"; - break; - case "player_uid": - char = "p"; - break; - case "npc_uid": - char = "N"; - break; - case "interface": - char = "a"; - break; - case "npc_stat": - char = "\xFE"; - break; - case "idkit": - char = "K"; - break; - default: - return null; - } - return char.charCodeAt(0); - } - static getDefault(type) { - if (type === _ScriptVarType.STRING) { - return ""; - } else if (type === _ScriptVarType.BOOLEAN) { - return 0; - } else { - return -1; - } - } -}; - -// src/lostcity/cache/config/DbTableType.ts -var DbTableType = class _DbTableType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static load(dir) { - if (!fs3.existsSync(`${dir}/server/dbtable.dat`)) { - console.log("Warning: No dbtable.dat found."); - return; - } - const dat = Packet.load(`${dir}/server/dbtable.dat`); - this.parse(dat); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/dbtable.dat`); - if (!file.ok) { - console.log("Warning: No dbtable.dat found."); - return; - } - const dat = new Packet(new Uint8Array(await file.arrayBuffer())); - this.parse(dat); - } - static parse(dat) { - _DbTableType.configNames = /* @__PURE__ */ new Map(); - _DbTableType.configs = []; - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new _DbTableType(id); - config.decodeType(dat); - _DbTableType.configs[id] = config; - if (config.debugname) { - _DbTableType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return _DbTableType.configs[id]; - } - static getId(name) { - return _DbTableType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - // ---- - types = []; - defaultValues = []; - columnNames = []; - decode(code, dat) { - if (code === 1) { - this.types = new Array(dat.g1()); - for (let setting = dat.g1(); setting != 255; setting = dat.g1()) { - const column = setting & 127; - const hasDefault = (setting & 128) !== 0; - const columnTypes = new Array(dat.g1()); - for (let i = 0; i < columnTypes.length; i++) { - columnTypes[i] = dat.g1(); - } - this.types[column] = columnTypes; - if (hasDefault) { - if (!this.defaultValues) { - this.defaultValues = new Array(this.types.length); - } - this.defaultValues[column] = this.decodeValues(dat, column); - } - } - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else if (code === 251) { - this.columnNames = new Array(dat.g1()); - for (let i = 0; i < this.columnNames.length; i++) { - this.columnNames[i] = dat.gjstr(); - } - } else { - throw new Error(`Unrecognized dbtable config code: ${code}`); - } - } - getDefault(column) { - if (!this.defaultValues[column]) { - const defaults = []; - for (let i = 0; i < this.types[column].length; i++) { - defaults[i] = ScriptVarType.getDefault(this.types[column][i]); - } - return defaults; - } - return this.defaultValues[column]; - } - decodeValues(dat, column) { - const types = this.types[column]; - const fieldCount = dat.g1(); - const values = new Array(fieldCount * types.length); - for (let fieldId = 0; fieldId < fieldCount; fieldId++) { - for (let typeId = 0; typeId < types.length; typeId++) { - const type = types[typeId]; - const index = typeId + fieldId * types.length; - if (type === ScriptVarType.STRING) { - values[index] = dat.gjstr(); - } else { - values[index] = dat.g4(); - } - } - } - return values; - } -}; - -// src/lostcity/cache/config/DbRowType.ts -var DbRowType = class _DbRowType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static load(dir) { - if (!fs4.existsSync(`${dir}/server/dbrow.dat`)) { - console.log("Warning: No dbrow.dat found."); - return; - } - const dat = Packet.load(`${dir}/server/dbrow.dat`); - this.parse(dat); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/dbrow.dat`); - if (!file.ok) { - console.log("Warning: No dbrow.dat found."); - return; - } - const dat = new Packet(new Uint8Array(await file.arrayBuffer())); - this.parse(dat); - } - static parse(dat) { - _DbRowType.configNames = /* @__PURE__ */ new Map(); - _DbRowType.configs = []; - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new _DbRowType(id); - config.decodeType(dat); - _DbRowType.configs[id] = config; - if (config.debugname) { - _DbRowType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return _DbRowType.configs[id]; - } - static getId(name) { - return _DbRowType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - static getInTable(tableId) { - return _DbRowType.configs.filter((config) => config.tableId === tableId); - } - // ---- - tableId = 0; - types = []; - columnValues = []; - decode(code, dat) { - if (code === 3) { - const numColumns = dat.g1(); - this.types = new Array(numColumns); - this.columnValues = new Array(numColumns); - for (let columnId = dat.g1(); columnId != 255; columnId = dat.g1()) { - const columnTypes = new Array(dat.g1()); - for (let i = 0; i < columnTypes.length; i++) { - columnTypes[i] = dat.g1(); - } - this.types[columnId] = columnTypes; - this.columnValues[columnId] = this.decodeValues(dat, columnId); - } - } else if (code === 4) { - this.tableId = dat.g2(); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized dbtable config code: ${code}`); - } - } - getValue(column, listIndex) { - const value = this.columnValues[column].slice(listIndex * this.types[column].length, (listIndex + 1) * this.types[column].length); - if (!value.length) { - return DbTableType.get(this.tableId).getDefault(column); - } - return value; - } - decodeValues(dat, column) { - const types = this.types[column]; - const fieldCount = dat.g1(); - const values = new Array(fieldCount * types.length); - for (let fieldId = 0; fieldId < fieldCount; fieldId++) { - for (let typeId = 0; typeId < types.length; typeId++) { - const type = types[typeId]; - const index = typeId + fieldId * types.length; - if (type === ScriptVarType.STRING) { - values[index] = dat.gjstr(); - } else { - values[index] = dat.g4(); - } - } - } - return values; - } -}; - -// src/lostcity/cache/config/EnumType.ts -var EnumType = class _EnumType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static load(dir) { - if (!fs5.existsSync(`${dir}/server/enum.dat`)) { - console.log("Warning: No enum.dat found."); - return; - } - const dat = Packet.load(`${dir}/server/enum.dat`); - this.parse(dat); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/enum.dat`); - if (!file.ok) { - console.log("Warning: No enum.dat found."); - return; - } - const dat = new Packet(new Uint8Array(await file.arrayBuffer())); - this.parse(dat); - } - static parse(dat) { - _EnumType.configNames = /* @__PURE__ */ new Map(); - _EnumType.configs = []; - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new _EnumType(id); - config.decodeType(dat); - _EnumType.configs[id] = config; - if (config.debugname) { - _EnumType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return _EnumType.configs[id]; - } - static getId(name) { - return _EnumType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - // ---- - // server-side - inputtype = ScriptVarType.INT; - outputtype = ScriptVarType.INT; - defaultInt = 0; - defaultString = "null"; - values = /* @__PURE__ */ new Map(); - decode(code, dat) { - if (code === 1) { - this.inputtype = dat.g1(); - } else if (code === 2) { - this.outputtype = dat.g1(); - } else if (code === 3) { - this.defaultString = dat.gjstr(); - } else if (code === 4) { - this.defaultInt = dat.g4(); - } else if (code === 5) { - const count = dat.g2(); - for (let i = 0; i < count; i++) { - this.values.set(dat.g4(), dat.gjstr()); - } - } else if (code === 6) { - const count = dat.g2(); - for (let i = 0; i < count; i++) { - this.values.set(dat.g4(), dat.g4()); - } - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized enum config code: ${code}`); - } - } -}; - -// src/3rdparty/bzip2-wasm/bzip2-1.0.8/bzip2.mjs -var loadBZip2WASM = (() => { - var _scriptName = import.meta.url; - return async function(moduleArg = {}) { - var moduleRtn; - var Module = Object.assign({}, moduleArg); - var readyPromiseResolve, readyPromiseReject; - var readyPromise = new Promise((resolve, reject) => { - readyPromiseResolve = resolve; - readyPromiseReject = reject; - }); - ["_BZ2_bzBuffToBuffDecompress", "_BZ2_bzBuffToBuffCompress", "_malloc", "_free", "_memory", "___indirect_function_table", "onRuntimeInitialized"].forEach((prop) => { - if (!Object.getOwnPropertyDescriptor(readyPromise, prop)) { - Object.defineProperty(readyPromise, prop, { - get: () => abort("You are getting " + prop + " on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js"), - set: () => abort("You are setting " + prop + " on the Promise object, instead of the instance. Use .then() to get called back with the instance, see the MODULARIZE docs in src/settings.js") - }); - } - }); - var ENVIRONMENT_IS_WEB = typeof window == "object"; - var ENVIRONMENT_IS_WORKER = typeof importScripts == "function"; - var ENVIRONMENT_IS_NODE = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string"; - var ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER; - if (Module["ENVIRONMENT"]) { - throw new Error("Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)"); - } - if (ENVIRONMENT_IS_NODE) { - const { createRequire } = await import("module"); - var require2 = createRequire(import.meta.url); - } - var moduleOverrides = Object.assign({}, Module); - var arguments_ = []; - var thisProgram = "./this.program"; - var quit_ = (status, toThrow) => { - throw toThrow; - }; - var scriptDirectory = ""; - function locateFile(path4) { - if (Module["locateFile"]) { - return Module["locateFile"](path4, scriptDirectory); - } - return scriptDirectory + path4; - } - var read_, readAsync, readBinary; - if (ENVIRONMENT_IS_NODE) { - if (typeof process == "undefined" || !process.release || process.release.name !== "node") throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)"); - var nodeVersion = process.versions.node; - var numericVersion = nodeVersion.split(".").slice(0, 3); - numericVersion = numericVersion[0] * 1e4 + numericVersion[1] * 100 + numericVersion[2].split("-")[0] * 1; - var minVersion = 16e4; - if (numericVersion < 16e4) { - throw new Error("This emscripten-generated code requires node v16.0.0 (detected v" + nodeVersion + ")"); - } - var fs30 = require2("fs"); - var nodePath = require2("path"); - scriptDirectory = require2("url").fileURLToPath(new URL("./", import.meta.url)); - read_ = (filename, binary) => { - filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename); - return fs30.readFileSync(filename, binary ? void 0 : "utf8"); - }; - readBinary = (filename) => { - var ret = read_(filename, true); - if (!ret.buffer) { - ret = new Uint8Array(ret); - } - assert(ret.buffer); - return ret; - }; - readAsync = (filename, onload, onerror, binary = true) => { - filename = isFileURI(filename) ? new URL(filename) : nodePath.normalize(filename); - fs30.readFile(filename, binary ? void 0 : "utf8", (err2, data) => { - if (err2) onerror(err2); - else onload(binary ? data.buffer : data); - }); - }; - if (!Module["thisProgram"] && process.argv.length > 1) { - thisProgram = process.argv[1].replace(/\\/g, "/"); - } - arguments_ = process.argv.slice(2); - quit_ = (status, toThrow) => { - process.exitCode = status; - throw toThrow; - }; - } else if (ENVIRONMENT_IS_SHELL) { - if (typeof process == "object" && typeof require2 === "function" || typeof window == "object" || typeof importScripts == "function") throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)"); - } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { - if (ENVIRONMENT_IS_WORKER) { - scriptDirectory = self.location.href; - } else if (typeof document != "undefined" && document.currentScript) { - scriptDirectory = document.currentScript.src; - } - if (_scriptName) { - scriptDirectory = _scriptName; - } - if (scriptDirectory.startsWith("blob:")) { - scriptDirectory = ""; - } else { - scriptDirectory = scriptDirectory.substr(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1); - } - if (!(typeof window == "object" || typeof importScripts == "function")) throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)"); - { - read_ = (url) => { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, false); - xhr.send(null); - return xhr.responseText; - }; - if (ENVIRONMENT_IS_WORKER) { - readBinary = (url) => { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, false); - xhr.responseType = "arraybuffer"; - xhr.send(null); - return new Uint8Array( - /** @type{!ArrayBuffer} */ - xhr.response - ); - }; - } - readAsync = (url, onload, onerror) => { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, true); - xhr.responseType = "arraybuffer"; - xhr.onload = () => { - if (xhr.status == 200 || xhr.status == 0 && xhr.response) { - onload(xhr.response); - return; - } - onerror(); - }; - xhr.onerror = onerror; - xhr.send(null); - }; - } - } else { - throw new Error("environment detection error"); - } - var out = Module["print"] || console.log.bind(console); - var err = Module["printErr"] || console.error.bind(console); - Object.assign(Module, moduleOverrides); - moduleOverrides = null; - checkIncomingModuleAPI(); - if (Module["arguments"]) arguments_ = Module["arguments"]; - legacyModuleProp("arguments", "arguments_"); - if (Module["thisProgram"]) thisProgram = Module["thisProgram"]; - legacyModuleProp("thisProgram", "thisProgram"); - if (Module["quit"]) quit_ = Module["quit"]; - legacyModuleProp("quit", "quit_"); - assert(typeof Module["memoryInitializerPrefixURL"] == "undefined", "Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead"); - assert(typeof Module["pthreadMainPrefixURL"] == "undefined", "Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead"); - assert(typeof Module["cdInitializerPrefixURL"] == "undefined", "Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead"); - assert(typeof Module["filePackagePrefixURL"] == "undefined", "Module.filePackagePrefixURL option was removed, use Module.locateFile instead"); - assert(typeof Module["read"] == "undefined", "Module.read option was removed (modify read_ in JS)"); - assert(typeof Module["readAsync"] == "undefined", "Module.readAsync option was removed (modify readAsync in JS)"); - assert(typeof Module["readBinary"] == "undefined", "Module.readBinary option was removed (modify readBinary in JS)"); - assert(typeof Module["setWindowTitle"] == "undefined", "Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)"); - assert(typeof Module["TOTAL_MEMORY"] == "undefined", "Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY"); - legacyModuleProp("asm", "wasmExports"); - legacyModuleProp("read", "read_"); - legacyModuleProp("readAsync", "readAsync"); - legacyModuleProp("readBinary", "readBinary"); - legacyModuleProp("setWindowTitle", "setWindowTitle"); - var IDBFS = "IDBFS is no longer included by default; build with -lidbfs.js"; - var PROXYFS = "PROXYFS is no longer included by default; build with -lproxyfs.js"; - var WORKERFS = "WORKERFS is no longer included by default; build with -lworkerfs.js"; - var FETCHFS = "FETCHFS is no longer included by default; build with -lfetchfs.js"; - var ICASEFS = "ICASEFS is no longer included by default; build with -licasefs.js"; - var JSFILEFS = "JSFILEFS is no longer included by default; build with -ljsfilefs.js"; - var OPFS = "OPFS is no longer included by default; build with -lopfs.js"; - var NODEFS = "NODEFS is no longer included by default; build with -lnodefs.js"; - assert(!ENVIRONMENT_IS_SHELL, "shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable."); - var wasmBinary; - if (Module["wasmBinary"]) wasmBinary = Module["wasmBinary"]; - legacyModuleProp("wasmBinary", "wasmBinary"); - if (typeof WebAssembly != "object") { - err("no native wasm support detected"); - } - var wasmMemory; - var ABORT = false; - var EXITSTATUS; - function assert(condition, text) { - if (!condition) { - abort("Assertion failed" + (text ? ": " + text : "")); - } - } - var HEAP, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64; - function updateMemoryViews() { - var b = wasmMemory.buffer; - Module["HEAP8"] = HEAP8 = new Int8Array(b); - Module["HEAP16"] = HEAP16 = new Int16Array(b); - Module["HEAPU8"] = HEAPU8 = new Uint8Array(b); - Module["HEAPU16"] = HEAPU16 = new Uint16Array(b); - Module["HEAP32"] = HEAP32 = new Int32Array(b); - Module["HEAPU32"] = HEAPU32 = new Uint32Array(b); - Module["HEAPF32"] = HEAPF32 = new Float32Array(b); - Module["HEAPF64"] = HEAPF64 = new Float64Array(b); - } - assert(!Module["STACK_SIZE"], "STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time"); - assert( - typeof Int32Array != "undefined" && typeof Float64Array !== "undefined" && Int32Array.prototype.subarray != void 0 && Int32Array.prototype.set != void 0, - "JS engine does not provide full typed array support" - ); - assert(!Module["wasmMemory"], "Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally"); - assert(!Module["INITIAL_MEMORY"], "Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically"); - function writeStackCookie() { - var max = _emscripten_stack_get_end(); - assert((max & 3) == 0); - if (max == 0) { - max += 4; - } - HEAPU32[max >> 2] = 34821223; - HEAPU32[max + 4 >> 2] = 2310721022; - HEAPU32[0 >> 2] = 1668509029; - } - function checkStackCookie() { - if (ABORT) return; - var max = _emscripten_stack_get_end(); - if (max == 0) { - max += 4; - } - var cookie1 = HEAPU32[max >> 2]; - var cookie2 = HEAPU32[max + 4 >> 2]; - if (cookie1 != 34821223 || cookie2 != 2310721022) { - abort(`Stack overflow! Stack cookie has been overwritten at ${ptrToString(max)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${ptrToString(cookie2)} ${ptrToString(cookie1)}`); - } - if (HEAPU32[0 >> 2] != 1668509029) { - abort("Runtime error: The application has corrupted its heap memory area (address zero)!"); - } - } - (function() { - var h16 = new Int16Array(1); - var h8 = new Int8Array(h16.buffer); - h16[0] = 25459; - if (h8[0] !== 115 || h8[1] !== 99) throw "Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)"; - })(); - var __ATPRERUN__ = []; - var __ATINIT__ = []; - var __ATEXIT__ = []; - var __ATPOSTRUN__ = []; - var runtimeInitialized = false; - function preRun() { - if (Module["preRun"]) { - if (typeof Module["preRun"] == "function") Module["preRun"] = [Module["preRun"]]; - while (Module["preRun"].length) { - addOnPreRun(Module["preRun"].shift()); - } - } - callRuntimeCallbacks(__ATPRERUN__); - } - function initRuntime() { - assert(!runtimeInitialized); - runtimeInitialized = true; - checkStackCookie(); - callRuntimeCallbacks(__ATINIT__); - } - function postRun() { - checkStackCookie(); - if (Module["postRun"]) { - if (typeof Module["postRun"] == "function") Module["postRun"] = [Module["postRun"]]; - while (Module["postRun"].length) { - addOnPostRun(Module["postRun"].shift()); - } - } - callRuntimeCallbacks(__ATPOSTRUN__); - } - function addOnPreRun(cb) { - __ATPRERUN__.unshift(cb); - } - function addOnInit(cb) { - __ATINIT__.unshift(cb); - } - function addOnExit(cb) { - } - function addOnPostRun(cb) { - __ATPOSTRUN__.unshift(cb); - } - assert(Math.imul, "This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"); - assert(Math.fround, "This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"); - assert(Math.clz32, "This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"); - assert(Math.trunc, "This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill"); - var runDependencies = 0; - var runDependencyWatcher = null; - var dependenciesFulfilled = null; - var runDependencyTracking = {}; - function getUniqueRunDependency(id) { - var orig = id; - while (1) { - if (!runDependencyTracking[id]) return id; - id = orig + Math.random(); - } - } - function addRunDependency(id) { - runDependencies++; - Module["monitorRunDependencies"]?.(runDependencies); - if (id) { - assert(!runDependencyTracking[id]); - runDependencyTracking[id] = 1; - if (runDependencyWatcher === null && typeof setInterval != "undefined") { - runDependencyWatcher = setInterval(() => { - if (ABORT) { - clearInterval(runDependencyWatcher); - runDependencyWatcher = null; - return; - } - var shown = false; - for (var dep in runDependencyTracking) { - if (!shown) { - shown = true; - err("still waiting on run dependencies:"); - } - err(`dependency: ${dep}`); - } - if (shown) { - err("(end of list)"); - } - }, 1e4); - } - } else { - err("warning: run dependency added without ID"); - } - } - function removeRunDependency(id) { - runDependencies--; - Module["monitorRunDependencies"]?.(runDependencies); - if (id) { - assert(runDependencyTracking[id]); - delete runDependencyTracking[id]; - } else { - err("warning: run dependency removed without ID"); - } - if (runDependencies == 0) { - if (runDependencyWatcher !== null) { - clearInterval(runDependencyWatcher); - runDependencyWatcher = null; - } - if (dependenciesFulfilled) { - var callback = dependenciesFulfilled; - dependenciesFulfilled = null; - callback(); - } - } - } - function abort(what) { - Module["onAbort"]?.(what); - what = "Aborted(" + what + ")"; - err(what); - ABORT = true; - EXITSTATUS = 1; - var e = new WebAssembly.RuntimeError(what); - readyPromiseReject(e); - throw e; - } - var FS = { - error() { - abort("Filesystem support (FS) was not included. The problem is that you are using files from JS, but files were not used from C/C++, so filesystem support was not auto-included. You can force-include filesystem support with -sFORCE_FILESYSTEM"); - }, - init() { - FS.error(); - }, - createDataFile() { - FS.error(); - }, - createPreloadedFile() { - FS.error(); - }, - createLazyFile() { - FS.error(); - }, - open() { - FS.error(); - }, - mkdev() { - FS.error(); - }, - registerDevice() { - FS.error(); - }, - analyzePath() { - FS.error(); - }, - ErrnoError() { - FS.error(); - } - }; - Module["FS_createDataFile"] = FS.createDataFile; - Module["FS_createPreloadedFile"] = FS.createPreloadedFile; - var dataURIPrefix = "data:application/octet-stream;base64,"; - var isDataURI = (filename) => filename.startsWith(dataURIPrefix); - var isFileURI = (filename) => filename.startsWith("file://"); - function createExportWrapper(name, nargs) { - return (...args) => { - assert(runtimeInitialized, `native function \`${name}\` called before runtime initialization`); - var f = wasmExports[name]; - assert(f, `exported native function \`${name}\` not found`); - assert(args.length <= nargs, `native function \`${name}\` called with ${args.length} args but expects ${nargs}`); - return f(...args); - }; - } - function findWasmBinary() { - if (Module["locateFile"]) { - var f = "bzip2.wasm"; - if (!isDataURI(f)) { - return locateFile(f); - } - return f; - } - return new URL("bzip2.wasm", import.meta.url).href; - } - var wasmBinaryFile; - function getBinarySync(file) { - if (file == wasmBinaryFile && wasmBinary) { - return new Uint8Array(wasmBinary); - } - if (readBinary) { - return readBinary(file); - } - throw "both async and sync fetching of the wasm failed"; - } - function getBinaryPromise(binaryFile) { - if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) { - if (typeof fetch == "function" && !isFileURI(binaryFile)) { - return fetch(binaryFile, { credentials: "same-origin" }).then((response) => { - if (!response["ok"]) { - throw `failed to load wasm binary file at '${binaryFile}'`; - } - return response["arrayBuffer"](); - }).catch(() => getBinarySync(binaryFile)); - } else if (readAsync) { - return new Promise((resolve, reject) => { - readAsync(binaryFile, (response) => resolve(new Uint8Array( - /** @type{!ArrayBuffer} */ - response - )), reject); - }); - } - } - return Promise.resolve().then(() => getBinarySync(binaryFile)); - } - function instantiateArrayBuffer(binaryFile, imports, receiver) { - return getBinaryPromise(binaryFile).then((binary) => { - return WebAssembly.instantiate(binary, imports); - }).then(receiver, (reason) => { - err(`failed to asynchronously prepare wasm: ${reason}`); - if (isFileURI(wasmBinaryFile)) { - err(`warning: Loading from a file URI (${wasmBinaryFile}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing`); - } - abort(reason); - }); - } - function instantiateAsync(binary, binaryFile, imports, callback) { - if (!binary && typeof WebAssembly.instantiateStreaming == "function" && !isDataURI(binaryFile) && // Don't use streaming for file:// delivered objects in a webview, fetch them synchronously. - !isFileURI(binaryFile) && // Avoid instantiateStreaming() on Node.js environment for now, as while - // Node.js v18.1.0 implements it, it does not have a full fetch() - // implementation yet. - // - // Reference: - // https://github.com/emscripten-core/emscripten/pull/16917 - !ENVIRONMENT_IS_NODE && typeof fetch == "function") { - return fetch(binaryFile, { credentials: "same-origin" }).then((response) => { - var result = WebAssembly.instantiateStreaming(response, imports); - return result.then( - callback, - function(reason) { - err(`wasm streaming compile failed: ${reason}`); - err("falling back to ArrayBuffer instantiation"); - return instantiateArrayBuffer(binaryFile, imports, callback); - } - ); - }); - } - return instantiateArrayBuffer(binaryFile, imports, callback); - } - function getWasmImports() { - return { - "env": wasmImports, - "wasi_snapshot_preview1": wasmImports - }; - } - function createWasm() { - var info = getWasmImports(); - function receiveInstance(instance, module) { - wasmExports = instance.exports; - wasmMemory = wasmExports["memory"]; - assert(wasmMemory, "memory not found in wasm exports"); - updateMemoryViews(); - addOnInit(wasmExports["__wasm_call_ctors"]); - removeRunDependency("wasm-instantiate"); - return wasmExports; - } - addRunDependency("wasm-instantiate"); - var trueModule = Module; - function receiveInstantiationResult(result) { - assert(Module === trueModule, "the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?"); - trueModule = null; - receiveInstance(result["instance"]); - } - if (Module["instantiateWasm"]) { - try { - return Module["instantiateWasm"](info, receiveInstance); - } catch (e) { - err(`Module.instantiateWasm callback failed with error: ${e}`); - readyPromiseReject(e); - } - } - if (!wasmBinaryFile) wasmBinaryFile = findWasmBinary(); - instantiateAsync(wasmBinary, wasmBinaryFile, info, receiveInstantiationResult).catch(readyPromiseReject); - return {}; - } - var tempDouble; - var tempI64; - function legacyModuleProp(prop, newName, incoming = true) { - if (!Object.getOwnPropertyDescriptor(Module, prop)) { - Object.defineProperty(Module, prop, { - configurable: true, - get() { - let extra = incoming ? " (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)" : ""; - abort(`\`Module.${prop}\` has been replaced by \`${newName}\`` + extra); - } - }); - } - } - function ignoredModuleProp(prop) { - if (Object.getOwnPropertyDescriptor(Module, prop)) { - abort(`\`Module.${prop}\` was supplied but \`${prop}\` not included in INCOMING_MODULE_JS_API`); - } - } - function isExportedByForceFilesystem(name) { - return name === "FS_createPath" || name === "FS_createDataFile" || name === "FS_createPreloadedFile" || name === "FS_unlink" || name === "addRunDependency" || // The old FS has some functionality that WasmFS lacks. - name === "FS_createLazyFile" || name === "FS_createDevice" || name === "removeRunDependency"; - } - function missingGlobal(sym, msg) { - if (typeof globalThis != "undefined") { - Object.defineProperty(globalThis, sym, { - configurable: true, - get() { - warnOnce(`\`${sym}\` is not longer defined by emscripten. ${msg}`); - return void 0; - } - }); - } - } - missingGlobal("buffer", "Please use HEAP8.buffer or wasmMemory.buffer"); - missingGlobal("asm", "Please use wasmExports instead"); - function missingLibrarySymbol(sym) { - if (typeof globalThis != "undefined" && !Object.getOwnPropertyDescriptor(globalThis, sym)) { - Object.defineProperty(globalThis, sym, { - configurable: true, - get() { - var msg = `\`${sym}\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`; - var librarySymbol = sym; - if (!librarySymbol.startsWith("_")) { - librarySymbol = "$" + sym; - } - msg += ` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${librarySymbol}')`; - if (isExportedByForceFilesystem(sym)) { - msg += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"; - } - warnOnce(msg); - return void 0; - } - }); - } - unexportedRuntimeSymbol(sym); - } - function unexportedRuntimeSymbol(sym) { - if (!Object.getOwnPropertyDescriptor(Module, sym)) { - Object.defineProperty(Module, sym, { - configurable: true, - get() { - var msg = `'${sym}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`; - if (isExportedByForceFilesystem(sym)) { - msg += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"; - } - abort(msg); - } - }); - } - } - function dbg(...args) { - console.warn(...args); - } - function ExitStatus(status) { - this.name = "ExitStatus"; - this.message = `Program terminated with exit(${status})`; - this.status = status; - } - var callRuntimeCallbacks = (callbacks) => { - while (callbacks.length > 0) { - callbacks.shift()(Module); - } - }; - function getValue(ptr, type = "i8") { - if (type.endsWith("*")) type = "*"; - switch (type) { - case "i1": - return HEAP8[ptr]; - case "i8": - return HEAP8[ptr]; - case "i16": - return HEAP16[ptr >> 1]; - case "i32": - return HEAP32[ptr >> 2]; - case "i64": - abort("to do getValue(i64) use WASM_BIGINT"); - case "float": - return HEAPF32[ptr >> 2]; - case "double": - return HEAPF64[ptr >> 3]; - case "*": - return HEAPU32[ptr >> 2]; - default: - abort(`invalid type for getValue: ${type}`); - } - } - var noExitRuntime = Module["noExitRuntime"] || true; - var ptrToString = (ptr) => { - assert(typeof ptr === "number"); - ptr >>>= 0; - return "0x" + ptr.toString(16).padStart(8, "0"); - }; - function setValue(ptr, value, type = "i8") { - if (type.endsWith("*")) type = "*"; - switch (type) { - case "i1": - HEAP8[ptr] = value; - break; - case "i8": - HEAP8[ptr] = value; - break; - case "i16": - HEAP16[ptr >> 1] = value; - break; - case "i32": - HEAP32[ptr >> 2] = value; - break; - case "i64": - abort("to do setValue(i64) use WASM_BIGINT"); - case "float": - HEAPF32[ptr >> 2] = value; - break; - case "double": - HEAPF64[ptr >> 3] = value; - break; - case "*": - HEAPU32[ptr >> 2] = value; - break; - default: - abort(`invalid type for setValue: ${type}`); - } - } - var stackRestore = (val) => __emscripten_stack_restore(val); - var stackSave = () => _emscripten_stack_get_current(); - var warnOnce = (text) => { - warnOnce.shown ||= {}; - if (!warnOnce.shown[text]) { - warnOnce.shown[text] = 1; - if (ENVIRONMENT_IS_NODE) text = "warning: " + text; - err(text); - } - }; - var __emscripten_memcpy_js = (dest, src, num) => HEAPU8.copyWithin(dest, src, src + num); - var getHeapMax = () => ( - // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate - // full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side - // for any code that deals with heap sizes, which would require special - // casing all heap size related code to treat 0 specially. - 2147483648 - ); - var growMemory = (size) => { - var b = wasmMemory.buffer; - var pages = (size - b.byteLength + 65535) / 65536; - try { - wasmMemory.grow(pages); - updateMemoryViews(); - return 1; - } catch (e) { - err(`growMemory: Attempted to grow heap from ${b.byteLength} bytes to ${size} bytes, but got error: ${e}`); - } - }; - var _emscripten_resize_heap = (requestedSize) => { - var oldSize = HEAPU8.length; - requestedSize >>>= 0; - assert(requestedSize > oldSize); - var maxHeapSize = getHeapMax(); - if (requestedSize > maxHeapSize) { - err(`Cannot enlarge memory, requested ${requestedSize} bytes, but the limit is ${maxHeapSize} bytes!`); - return false; - } - var alignUp = (x, multiple) => x + (multiple - x % multiple) % multiple; - for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { - var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); - overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296); - var newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), 65536)); - var replacement = growMemory(newSize); - if (replacement) { - return true; - } - } - err(`Failed to grow the heap from ${oldSize} bytes to ${newSize} bytes, not enough memory!`); - return false; - }; - var runtimeKeepaliveCounter = 0; - var keepRuntimeAlive = () => noExitRuntime || runtimeKeepaliveCounter > 0; - var _proc_exit = (code) => { - EXITSTATUS = code; - if (!keepRuntimeAlive()) { - Module["onExit"]?.(code); - ABORT = true; - } - quit_(code, new ExitStatus(code)); - }; - var exitJS = (status, implicit) => { - EXITSTATUS = status; - checkUnflushedContent(); - if (keepRuntimeAlive() && !implicit) { - var msg = `program exited (with status: ${status}), but keepRuntimeAlive() is set (counter=${runtimeKeepaliveCounter}) due to an async operation, so halting execution but not exiting the runtime or preventing further async execution (you can use emscripten_force_exit, if you want to force a true shutdown)`; - readyPromiseReject(msg); - err(msg); - } - _proc_exit(status); - }; - var _exit = exitJS; - var UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder("utf8") : void 0; - var UTF8ArrayToString = (heapOrArray, idx, maxBytesToRead) => { - var endIdx = idx + maxBytesToRead; - var endPtr = idx; - while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr; - if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) { - return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr)); - } - var str = ""; - while (idx < endPtr) { - var u0 = heapOrArray[idx++]; - if (!(u0 & 128)) { - str += String.fromCharCode(u0); - continue; - } - var u1 = heapOrArray[idx++] & 63; - if ((u0 & 224) == 192) { - str += String.fromCharCode((u0 & 31) << 6 | u1); - continue; - } - var u2 = heapOrArray[idx++] & 63; - if ((u0 & 240) == 224) { - u0 = (u0 & 15) << 12 | u1 << 6 | u2; - } else { - if ((u0 & 248) != 240) warnOnce("Invalid UTF-8 leading byte " + ptrToString(u0) + " encountered when deserializing a UTF-8 string in wasm memory to a JS string!"); - u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63; - } - if (u0 < 65536) { - str += String.fromCharCode(u0); - } else { - var ch = u0 - 65536; - str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023); - } - } - return str; - }; - var UTF8ToString = (ptr, maxBytesToRead) => { - assert(typeof ptr == "number", `UTF8ToString expects a number (got ${typeof ptr})`); - return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : ""; - }; - var SYSCALLS = { - varargs: void 0, - getStr(ptr) { - var ret = UTF8ToString(ptr); - return ret; - } - }; - var _fd_close = (fd) => { - abort("fd_close called without SYSCALLS_REQUIRE_FILESYSTEM"); - }; - var convertI32PairToI53Checked = (lo, hi) => { - assert(lo == lo >>> 0 || lo == (lo | 0)); - assert(hi === (hi | 0)); - return hi + 2097152 >>> 0 < 4194305 - !!lo ? (lo >>> 0) + hi * 4294967296 : NaN; - }; - function _fd_seek(fd, offset_low, offset_high, whence, newOffset) { - var offset = convertI32PairToI53Checked(offset_low, offset_high); - return 70; - ; - } - var printCharBuffers = [null, [], []]; - var printChar = (stream, curr) => { - var buffer = printCharBuffers[stream]; - assert(buffer); - if (curr === 0 || curr === 10) { - (stream === 1 ? out : err)(UTF8ArrayToString(buffer, 0)); - buffer.length = 0; - } else { - buffer.push(curr); - } - }; - var flush_NO_FILESYSTEM = () => { - _fflush(0); - if (printCharBuffers[1].length) printChar(1, 10); - if (printCharBuffers[2].length) printChar(2, 10); - }; - var _fd_write = (fd, iov, iovcnt, pnum) => { - var num = 0; - for (var i = 0; i < iovcnt; i++) { - var ptr = HEAPU32[iov >> 2]; - var len = HEAPU32[iov + 4 >> 2]; - iov += 8; - for (var j = 0; j < len; j++) { - printChar(fd, HEAPU8[ptr + j]); - } - num += len; - } - HEAPU32[pnum >> 2] = num; - return 0; - }; - function checkIncomingModuleAPI() { - ignoredModuleProp("fetchSettings"); - } - var wasmImports = { - /** @export */ - _emscripten_memcpy_js: __emscripten_memcpy_js, - /** @export */ - emscripten_resize_heap: _emscripten_resize_heap, - /** @export */ - exit: _exit, - /** @export */ - fd_close: _fd_close, - /** @export */ - fd_seek: _fd_seek, - /** @export */ - fd_write: _fd_write - }; - var wasmExports = createWasm(); - var ___wasm_call_ctors = createExportWrapper("__wasm_call_ctors", 0); - var _malloc = Module["_malloc"] = createExportWrapper("malloc", 1); - var _free = Module["_free"] = createExportWrapper("free", 1); - var _fflush = createExportWrapper("fflush", 1); - var _BZ2_bzBuffToBuffCompress = Module["_BZ2_bzBuffToBuffCompress"] = createExportWrapper("BZ2_bzBuffToBuffCompress", 7); - var _BZ2_bzBuffToBuffDecompress = Module["_BZ2_bzBuffToBuffDecompress"] = createExportWrapper("BZ2_bzBuffToBuffDecompress", 6); - var _emscripten_stack_init = () => (_emscripten_stack_init = wasmExports["emscripten_stack_init"])(); - var _emscripten_stack_get_free = () => (_emscripten_stack_get_free = wasmExports["emscripten_stack_get_free"])(); - var _emscripten_stack_get_base = () => (_emscripten_stack_get_base = wasmExports["emscripten_stack_get_base"])(); - var _emscripten_stack_get_end = () => (_emscripten_stack_get_end = wasmExports["emscripten_stack_get_end"])(); - var __emscripten_stack_restore = (a0) => (__emscripten_stack_restore = wasmExports["_emscripten_stack_restore"])(a0); - var __emscripten_stack_alloc = (a0) => (__emscripten_stack_alloc = wasmExports["_emscripten_stack_alloc"])(a0); - var _emscripten_stack_get_current = () => (_emscripten_stack_get_current = wasmExports["emscripten_stack_get_current"])(); - var dynCall_jiji = Module["dynCall_jiji"] = createExportWrapper("dynCall_jiji", 5); - Module["setValue"] = setValue; - Module["getValue"] = getValue; - var missingLibrarySymbols = [ - "writeI53ToI64", - "writeI53ToI64Clamped", - "writeI53ToI64Signaling", - "writeI53ToU64Clamped", - "writeI53ToU64Signaling", - "readI53FromI64", - "readI53FromU64", - "convertI32PairToI53", - "convertU32PairToI53", - "stackAlloc", - "getTempRet0", - "setTempRet0", - "zeroMemory", - "isLeapYear", - "ydayFromDate", - "arraySum", - "addDays", - "inetPton4", - "inetNtop4", - "inetPton6", - "inetNtop6", - "readSockaddr", - "writeSockaddr", - "initRandomFill", - "randomFill", - "emscriptenLog", - "readEmAsmArgs", - "jstoi_q", - "getExecutableName", - "listenOnce", - "autoResumeAudioContext", - "dynCallLegacy", - "getDynCaller", - "dynCall", - "handleException", - "runtimeKeepalivePush", - "runtimeKeepalivePop", - "callUserCallback", - "maybeExit", - "asmjsMangle", - "asyncLoad", - "alignMemory", - "mmapAlloc", - "HandleAllocator", - "getNativeTypeSize", - "STACK_SIZE", - "STACK_ALIGN", - "POINTER_SIZE", - "ASSERTIONS", - "getCFunc", - "ccall", - "cwrap", - "uleb128Encode", - "sigToWasmTypes", - "generateFuncType", - "convertJsFunctionToWasm", - "getEmptyTableSlot", - "updateTableMap", - "getFunctionAddress", - "addFunction", - "removeFunction", - "reallyNegative", - "unSign", - "strLen", - "reSign", - "formatString", - "stringToUTF8Array", - "stringToUTF8", - "lengthBytesUTF8", - "intArrayFromString", - "intArrayToString", - "AsciiToString", - "stringToAscii", - "UTF16ToString", - "stringToUTF16", - "lengthBytesUTF16", - "UTF32ToString", - "stringToUTF32", - "lengthBytesUTF32", - "stringToNewUTF8", - "stringToUTF8OnStack", - "writeArrayToMemory", - "registerKeyEventCallback", - "maybeCStringToJsString", - "findEventTarget", - "getBoundingClientRect", - "fillMouseEventData", - "registerMouseEventCallback", - "registerWheelEventCallback", - "registerUiEventCallback", - "registerFocusEventCallback", - "fillDeviceOrientationEventData", - "registerDeviceOrientationEventCallback", - "fillDeviceMotionEventData", - "registerDeviceMotionEventCallback", - "screenOrientation", - "fillOrientationChangeEventData", - "registerOrientationChangeEventCallback", - "fillFullscreenChangeEventData", - "registerFullscreenChangeEventCallback", - "JSEvents_requestFullscreen", - "JSEvents_resizeCanvasForFullscreen", - "registerRestoreOldStyle", - "hideEverythingExceptGivenElement", - "restoreHiddenElements", - "setLetterbox", - "softFullscreenResizeWebGLRenderTarget", - "doRequestFullscreen", - "fillPointerlockChangeEventData", - "registerPointerlockChangeEventCallback", - "registerPointerlockErrorEventCallback", - "requestPointerLock", - "fillVisibilityChangeEventData", - "registerVisibilityChangeEventCallback", - "registerTouchEventCallback", - "fillGamepadEventData", - "registerGamepadEventCallback", - "registerBeforeUnloadEventCallback", - "fillBatteryEventData", - "battery", - "registerBatteryEventCallback", - "setCanvasElementSize", - "getCanvasElementSize", - "jsStackTrace", - "getCallstack", - "convertPCtoSourceLocation", - "getEnvStrings", - "checkWasiClock", - "wasiRightsToMuslOFlags", - "wasiOFlagsToMuslOFlags", - "createDyncallWrapper", - "safeSetTimeout", - "setImmediateWrapped", - "clearImmediateWrapped", - "polyfillSetImmediate", - "getPromise", - "makePromise", - "idsToPromises", - "makePromiseCallback", - "ExceptionInfo", - "findMatchingCatch", - "Browser_asyncPrepareDataCounter", - "setMainLoop", - "getSocketFromFD", - "getSocketAddress", - "FS_createPreloadedFile", - "FS_modeStringToFlags", - "FS_getMode", - "FS_stdin_getChar", - "FS_createDataFile", - "FS_unlink", - "FS_mkdirTree", - "_setNetworkCallback", - "heapObjectForWebGLType", - "toTypedArrayIndex", - "webgl_enable_ANGLE_instanced_arrays", - "webgl_enable_OES_vertex_array_object", - "webgl_enable_WEBGL_draw_buffers", - "webgl_enable_WEBGL_multi_draw", - "emscriptenWebGLGet", - "computeUnpackAlignedImageSize", - "colorChannelsInGlTextureFormat", - "emscriptenWebGLGetTexPixelData", - "emscriptenWebGLGetUniform", - "webglGetUniformLocation", - "webglPrepareUniformLocationsBeforeFirstUse", - "webglGetLeftBracePos", - "emscriptenWebGLGetVertexAttrib", - "__glGetActiveAttribOrUniform", - "writeGLArray", - "registerWebGlEventCallback", - "runAndAbortIfError", - "ALLOC_NORMAL", - "ALLOC_STACK", - "allocate", - "writeStringToMemory", - "writeAsciiToMemory", - "setErrNo", - "demangle", - "stackTrace" - ]; - missingLibrarySymbols.forEach(missingLibrarySymbol); - var unexportedSymbols = [ - "run", - "addOnPreRun", - "addOnInit", - "addOnPreMain", - "addOnExit", - "addOnPostRun", - "addRunDependency", - "removeRunDependency", - "FS_createFolder", - "FS_createPath", - "FS_createLazyFile", - "FS_createLink", - "FS_createDevice", - "FS_readFile", - "out", - "err", - "callMain", - "abort", - "wasmMemory", - "wasmExports", - "writeStackCookie", - "checkStackCookie", - "convertI32PairToI53Checked", - "stackSave", - "stackRestore", - "ptrToString", - "exitJS", - "getHeapMax", - "growMemory", - "ENV", - "MONTH_DAYS_REGULAR", - "MONTH_DAYS_LEAP", - "MONTH_DAYS_REGULAR_CUMULATIVE", - "MONTH_DAYS_LEAP_CUMULATIVE", - "ERRNO_CODES", - "ERRNO_MESSAGES", - "DNS", - "Protocols", - "Sockets", - "timers", - "warnOnce", - "readEmAsmArgsArray", - "jstoi_s", - "keepRuntimeAlive", - "wasmTable", - "noExitRuntime", - "freeTableIndexes", - "functionsInTableMap", - "PATH", - "PATH_FS", - "UTF8Decoder", - "UTF8ArrayToString", - "UTF8ToString", - "UTF16Decoder", - "JSEvents", - "specialHTMLTargets", - "findCanvasEventTarget", - "currentFullscreenStrategy", - "restoreOldWindowedStyle", - "UNWIND_CACHE", - "ExitStatus", - "flush_NO_FILESYSTEM", - "promiseMap", - "uncaughtExceptionCount", - "exceptionLast", - "exceptionCaught", - "Browser", - "getPreloadedImageData__data", - "wget", - "SYSCALLS", - "preloadPlugins", - "FS_stdin_getChar_buffer", - "FS", - "MEMFS", - "TTY", - "PIPEFS", - "SOCKFS", - "tempFixedLengthArray", - "miniTempWebGLFloatBuffers", - "miniTempWebGLIntBuffers", - "GL", - "AL", - "GLUT", - "EGL", - "GLEW", - "IDBStore", - "SDL", - "SDL_gfx", - "allocateUTF8", - "allocateUTF8OnStack" - ]; - unexportedSymbols.forEach(unexportedRuntimeSymbol); - var calledRun; - dependenciesFulfilled = function runCaller() { - if (!calledRun) run(); - if (!calledRun) dependenciesFulfilled = runCaller; - }; - function stackCheckInit() { - _emscripten_stack_init(); - writeStackCookie(); - } - function run() { - if (runDependencies > 0) { - return; - } - stackCheckInit(); - preRun(); - if (runDependencies > 0) { - return; - } - function doRun() { - if (calledRun) return; - calledRun = true; - Module["calledRun"] = true; - if (ABORT) return; - initRuntime(); - readyPromiseResolve(Module); - if (Module["onRuntimeInitialized"]) Module["onRuntimeInitialized"](); - assert(!Module["_main"], 'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]'); - postRun(); - } - if (Module["setStatus"]) { - Module["setStatus"]("Running..."); - setTimeout(function() { - setTimeout(function() { - Module["setStatus"](""); - }, 1); - doRun(); - }, 1); - } else { - doRun(); - } - checkStackCookie(); - } - function checkUnflushedContent() { - var oldOut = out; - var oldErr = err; - var has = false; - out = err = (x) => { - has = true; - }; - try { - flush_NO_FILESYSTEM(); - } catch (e) { - } - out = oldOut; - err = oldErr; - if (has) { - warnOnce("stdio streams had content in them that was not flushed. you should set EXIT_RUNTIME to 1 (see the Emscripten FAQ), or make sure to emit a newline when you printf etc."); - warnOnce("(this may also be due to not including full filesystem support - try building with -sFORCE_FILESYSTEM)"); - } - } - if (Module["preInit"]) { - if (typeof Module["preInit"] == "function") Module["preInit"] = [Module["preInit"]]; - while (Module["preInit"].length > 0) { - Module["preInit"].pop()(); - } - } - run(); - moduleRtn = readyPromise; - for (const prop of Object.keys(Module)) { - if (!(prop in moduleArg)) { - Object.defineProperty(moduleArg, prop, { - configurable: true, - get() { - abort(`Access to module property ('${prop}') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.`); - } - }); - } - } - return moduleRtn; - }; -})(); -var bzip2_default = loadBZip2WASM; - -// src/3rdparty/bzip2-wasm/bzip2-wasm.js -var ERROR_MESSAGES = { - "-2": "BZ_PARAM_ERROR: incorrect parameters", - "-3": "BZ_MEM_ERROR: couldn't allocate enough memory", - "-4": "BZ_DATA_ERROR: data integrity error when decompressing", - "-5": "BZ_DATA_ERROR_MAGIC: compressed data has incorrect header", - "-7": "BZ_UNEXPECTED_EOF: compressed data ends too early", - "-8": "BZ_OUTBUFF_FULL: destination buffer is full" -}; -var BZip2 = class { - constructor() { - this.wasmModule = void 0; - } - // fetch the wasm and initialize it - async init() { - if (this.wasmModule) { - return; - } - if (typeof process !== "undefined") { - const { dirname } = await import("path"); - const { createRequire } = await import( - /* webpackIgnore: true */ - "module" - ); - globalThis.__dirname = dirname(import.meta.url); - globalThis.require = createRequire(import.meta.url); - } - this.wasmModule = await bzip2_default(); - } - ensureInitialized() { - if (!this.wasmModule) { - throw new Error( - `${this.constructor.name} not initalized. call .init()` - ); - } - } - // turn bzip's integer return values into an error message and throw it. - // also free the destination pointers - handleError(returnValue, destPtr, destLengthPtr) { - if (returnValue === 0) { - return; - } - this.wasmModule._free(destPtr); - this.wasmModule._free(destLengthPtr); - const errorMessage = ERROR_MESSAGES[returnValue]; - if (errorMessage) { - throw new Error(errorMessage); - } - throw new Error(`error code: ${returnValue}`); - } - // create source, destination and length buffers - createWASMBuffers(source, destLength) { - const { _malloc, setValue, HEAPU8 } = this.wasmModule; - const sourcePtr = _malloc(source.length); - HEAPU8.set(source, sourcePtr); - const destPtr = _malloc(destLength); - const destLengthPtr = _malloc(destLength); - setValue(destLengthPtr, destLength, "i32"); - return { sourcePtr, destPtr, destLengthPtr }; - } - // read the length returned by bzip, create a new Uint8Array of that size - // and copy the decompressed/compressed data into it - createBuffer(destPtr, destLengthPtr) { - const { _free, getValue, HEAPU8 } = this.wasmModule; - const destLength = getValue(destLengthPtr, "i32"); - const dest = new Uint8Array(destLength); - dest.set(HEAPU8.subarray(destPtr, destPtr + destLength)); - _free(destPtr); - _free(destLengthPtr); - return dest; - } - decompress(compressed, decompressedLength, prependHeader = false, containsDecompressedLength = false) { - if (containsDecompressedLength) { - decompressedLength = compressed[0] << 24 | compressed[1] << 16 | compressed[2] << 8 | compressed[3]; - compressed[0] = "B".charCodeAt(0); - compressed[1] = "Z".charCodeAt(0); - compressed[2] = "h".charCodeAt(0); - compressed[3] = "1".charCodeAt(0); - prependHeader = false; - } - if (prependHeader) { - const temp = new Uint8Array(compressed.length + 4); - temp[0] = "B".charCodeAt(0); - temp[1] = "Z".charCodeAt(0); - temp[2] = "h".charCodeAt(0); - temp[3] = "1".charCodeAt(0); - temp.set(compressed, 4); - compressed = temp; - } - this.ensureInitialized(); - const { - sourcePtr: compressedPtr, - destPtr: decompressedPtr, - destLengthPtr: decompressedLengthPtr - } = this.createWASMBuffers(compressed, decompressedLength); - const returnValue = this.wasmModule._BZ2_bzBuffToBuffDecompress( - decompressedPtr, - decompressedLengthPtr, - compressedPtr, - compressed.length, - 0, - 0 - ); - this.wasmModule._free(compressedPtr); - this.handleError(returnValue, decompressedPtr, decompressedLengthPtr); - return this.createBuffer(decompressedPtr, decompressedLengthPtr); - } - compress(decompressed, prefixLength = false, removeHeader = false, blockSize = 1, compressedLength = 0) { - this.ensureInitialized(); - if (!compressedLength) { - compressedLength = decompressed.length + 1024; - } - if (compressedLength < 128) { - compressedLength = 128; - } - if (blockSize <= 0 || blockSize > 9) { - throw new RangeError("blockSize should be between 1-9"); - } - const { - sourcePtr: decompressedPtr, - destPtr: compressedPtr, - destLengthPtr: compressedLengthPtr - } = this.createWASMBuffers(decompressed, compressedLength); - const returnValue = this.wasmModule._BZ2_bzBuffToBuffCompress( - compressedPtr, - compressedLengthPtr, - decompressedPtr, - decompressed.length, - blockSize, - 0, - 30 - ); - this.wasmModule._free(decompressedPtr); - this.handleError(returnValue, compressedPtr, compressedLengthPtr); - const buf = this.createBuffer(compressedPtr, compressedLengthPtr); - if (prefixLength) { - buf[0] = decompressed.length >> 24 & 255; - buf[1] = decompressed.length >> 16 & 255; - buf[2] = decompressed.length >> 8 & 255; - buf[3] = decompressed.length & 255; - } - if (removeHeader) { - return buf.subarray(4); - } - return buf; - } -}; -var bzip2_wasm_default = BZip2; - -// src/jagex2/io/BZip2.ts -var bzip2 = new bzip2_wasm_default(); -await bzip2.init(); -var BZip2_default = bzip2; - -// src/jagex2/io/Jagfile.ts -function genHash(name) { - let hash = 0; - name = name.toUpperCase(); - for (let i = 0; i < name.length; i++) { - hash = hash * 61 + name.charCodeAt(i) - 32 | 0; - } - return hash; -} -var Jagfile = class _Jagfile { - data = null; - fileCount = 0; - fileHash = []; - fileName = []; - fileUnpackedSize = []; - filePackedSize = []; - filePos = []; - unpacked = false; - fileQueue = []; - fileWrite = []; - static load(path4) { - return new _Jagfile(Packet.load(path4)); - } - static async loadAsync(path4) { - return new _Jagfile(await Packet.loadAsync(path4)); - } - constructor(src) { - if (!src) { - return; - } - const unpackedSize = src.g3(); - const packedSize = src.g3(); - if (unpackedSize === packedSize) { - this.data = new Uint8Array(src.data); - this.unpacked = false; - } else { - this.data = BZip2_default.decompress(src.data, unpackedSize, true); - src = new Packet(this.data); - this.unpacked = true; - } - this.fileCount = src.g2(); - let pos = src.pos + this.fileCount * 10; - for (let i = 0; i < this.fileCount; i++) { - this.fileHash[i] = src.g4(); - const hashMatch = KNOWN_HASHES.findIndex((x) => x === this.fileHash[i]); - if (hashMatch !== -1) { - this.fileName[i] = KNOWN_NAMES[hashMatch]; - } - this.fileUnpackedSize[i] = src.g3(); - this.filePackedSize[i] = src.g3(); - this.filePos[i] = pos; - pos += this.filePackedSize[i]; - } - } - get(index) { - if (index < 0 || index >= this.fileCount) { - return null; - } - if (this.data === null) { - throw new Error("Jagfile data is not loaded"); - } - const src = this.data.subarray(this.filePos[index], this.filePos[index] + this.filePackedSize[index]); - if (this.unpacked) { - return new Packet(src); - } else { - return new Packet(BZip2_default.decompress(src, this.fileUnpackedSize[index], true)); - } - } - read(name) { - const hash = genHash(name); - for (let i = 0; i < this.fileCount; i++) { - if (this.fileHash[i] === hash) { - return this.get(i); - } - } - return null; - } - write(name, data) { - const hash = genHash(name); - this.fileQueue.push({ hash, name, write: true, data: data.data.subarray(0, data.pos) }); - } - delete(name) { - const hash = genHash(name); - this.fileQueue.push({ hash, name, delete: true }); - } - rename(oldName, newName) { - const oldHash = genHash(oldName); - const newHash = genHash(newName); - this.fileQueue.push({ - hash: oldHash, - name: oldName, - rename: true, - newName, - newHash - }); - } - save(path4, doNotCompressWhole = false) { - let buf = Packet.alloc(5); - for (let i = 0; i < this.fileQueue.length; i++) { - const queued = this.fileQueue[i]; - let index = this.fileHash.findIndex((x) => x === queued.hash); - if (queued.write) { - if (index === -1) { - index = this.fileCount++; - this.fileHash[index] = queued.hash; - this.fileName[index] = queued.name; - } - if (!queued.data) { - throw new Error("Cannot write without data"); - } - this.fileUnpackedSize[index] = queued.data.length; - this.filePackedSize[index] = queued.data.length; - this.filePos[index] = -1; - this.fileWrite[index] = queued.data; - } - if (queued.delete && index !== -1) { - this.fileHash.splice(index, 1); - this.fileName.splice(index, 1); - this.fileUnpackedSize.splice(index, 1); - this.filePackedSize.splice(index, 1); - this.filePos.splice(index, 1); - this.fileCount--; - } - if (queued.rename && index !== -1) { - if (!queued.newHash) { - throw new Error("Cannot rename without newHash"); - } - if (!queued.newName) { - throw new Error("Cannot rename without newName"); - } - this.fileHash[index] = queued.newHash; - this.fileName[index] = queued.newName; - } - this.fileQueue.splice(i, 1); - i--; - } - let compressWhole = this.fileCount === 1; - if (doNotCompressWhole && compressWhole) { - compressWhole = false; - } - buf.p2(this.fileCount); - for (let i = 0; i < this.fileCount; i++) { - buf.p4(this.fileHash[i]); - buf.p3(this.fileUnpackedSize[i]); - if (this.fileWrite[i] && !compressWhole) { - this.fileWrite[i] = BZip2_default.compress(this.fileWrite[i], false, true); - this.filePackedSize[i] = this.fileWrite[i].length; - } - buf.p3(this.filePackedSize[i]); - } - for (let i = 0; i < this.fileCount; i++) { - const data = this.fileWrite[i]; - buf.pdata(data, 0, data.length); - } - const jag = Packet.alloc(5); - jag.p3(buf.pos); - if (compressWhole) { - buf = new Packet(BZip2_default.compress(buf.data, false, true)); - } - if (compressWhole) { - jag.p3(buf.data.length); - jag.pdata(buf.data, 0, buf.data.length); - } else { - jag.p3(buf.pos); - jag.pdata(buf.data, 0, buf.pos); - } - jag.save(path4); - buf.release(); - jag.release(); - } - deconstruct(name) { - const dat = this.read(name + ".dat"); - const idx = this.read(name + ".idx"); - if (dat === null || idx === null) { - throw new Error("Failed to read dat or idx"); - } - const count = idx.g2(); - const sizes = new Array(count); - const offsets = new Array(count); - let offset = 2; - for (let i = 0; i < count; i++) { - sizes[i] = idx.g2(); - offsets[i] = offset; - offset += sizes[i]; - } - const checksums = new Array(count); - for (let i = 0; i < count; i++) { - dat.pos = offsets[i]; - checksums[i] = Packet.getcrc(dat.data, offset, sizes[i]); - } - return { count, sizes, offsets, checksums }; - } -}; -var KNOWN_NAMES = [ - // title - "index.dat", - "logo.dat", - "p11.dat", - "p12.dat", - "b12.dat", - "q8.dat", - "runes.dat", - "title.dat", - "titlebox.dat", - "titlebutton.dat", - // seen in 274 - "p11_full.dat", - "p12_full.dat", - "b12_full.dat", - "q8_full.dat", - // config - "flo.dat", - "flo.idx", - "idk.dat", - "idk.idx", - "loc.dat", - "loc.idx", - "npc.dat", - "npc.idx", - "obj.dat", - "obj.idx", - "seq.dat", - "seq.idx", - "spotanim.dat", - "spotanim.idx", - "varp.dat", - "varp.idx", - // seen in 254 - "varbit.dat", - "varbit.idx", - // seen in 274 - "mesanim.dat", - "mesanim.idx", - "mes.dat", - "mes.idx", - "param.dat", - "param.idx", - "hunt.dat", - "hunt.idx", - // interface - "data", - // media - "backbase1.dat", - "backbase2.dat", - "backhmid1.dat", - "backhmid2.dat", - "backleft1.dat", - "backleft2.dat", - "backright1.dat", - "backright2.dat", - "backtop1.dat", - "backtop2.dat", - "backvmid1.dat", - "backvmid2.dat", - "backvmid3.dat", - "chatback.dat", - "combatboxes.dat", - "combaticons.dat", - "combaticons2.dat", - "combaticons3.dat", - "compass.dat", - "cross.dat", - "gnomeball_buttons.dat", - "headicons.dat", - "hitmarks.dat", - // index.dat - "invback.dat", - "leftarrow.dat", - "magicoff.dat", - "magicoff2.dat", - "magicon.dat", - "magicon2.dat", - "mapback.dat", - "mapdots.dat", - "mapflag.dat", - "mapfunction.dat", - "mapscene.dat", - "miscgraphics.dat", - "miscgraphics2.dat", - "miscgraphics3.dat", - "prayerglow.dat", - "prayeroff.dat", - "prayeron.dat", - "redstone1.dat", - "redstone2.dat", - "redstone3.dat", - "rightarrow.dat", - "scrollbar.dat", - "sideicons.dat", - "staticons.dat", - "staticons2.dat", - "steelborder.dat", - "steelborder2.dat", - "sworddecor.dat", - "tradebacking.dat", - "wornicons.dat", - // seen in 254 - "mapmarker.dat", - "mod_icons.dat", - "mapedge.dat", - // seen in 336 - "blackmark.dat", - "button_brown.dat", - "button_brown_big.dat", - "button_red.dat", - "chest.dat", - "coins.dat", - "headicons_hint.dat", - "headicons_pk.dat", - "headicons_prayer.dat", - "key.dat", - "keys.dat", - "leftarrow_small.dat", - "letter.dat", - "number_button.dat", - "overlay_duel.dat", - "overlay_multiway.dat", - "pen.dat", - "rightarrow_small.dat", - "startgame.dat", - "tex_brown.dat", - "tex_red.dat", - "titlescroll.dat", - // models (225 and before) - "base_head.dat", - "base_label.dat", - "base_type.dat", - "frame_del.dat", - "frame_head.dat", - "frame_tran1.dat", - "frame_tran2.dat", - "ob_axis.dat", - "ob_face1.dat", - "ob_face2.dat", - "ob_face3.dat", - "ob_face4.dat", - "ob_face5.dat", - "ob_head.dat", - "ob_point1.dat", - "ob_point2.dat", - "ob_point3.dat", - "ob_point4.dat", - "ob_point5.dat", - "ob_vertex1.dat", - "ob_vertex2.dat", - // versionlist (introduced in 234) - "anim_crc", - "anim_index", - "anim_version", - "map_crc", - "map_index", - "map_version", - "midi_crc", - "midi_index", - "midi_version", - "model_crc", - "model_index", - "model_version", - // textures - // index.dat - "0.dat", - "1.dat", - "2.dat", - "3.dat", - "4.dat", - "5.dat", - "6.dat", - "7.dat", - "8.dat", - "9.dat", - "10.dat", - "11.dat", - "12.dat", - "13.dat", - "14.dat", - "15.dat", - "16.dat", - "17.dat", - "18.dat", - "19.dat", - "20.dat", - "21.dat", - "22.dat", - "23.dat", - "24.dat", - "25.dat", - "26.dat", - "27.dat", - "28.dat", - "29.dat", - "30.dat", - "31.dat", - "32.dat", - "33.dat", - "34.dat", - "35.dat", - "36.dat", - "37.dat", - "38.dat", - "39.dat", - "40.dat", - "41.dat", - "42.dat", - "43.dat", - "44.dat", - "45.dat", - "46.dat", - "47.dat", - "48.dat", - "49.dat", - // wordenc - "badenc.txt", - "domainenc.txt", - "fragmentsenc.txt", - "tldlist.txt", - // sounds - "sounds.dat", - // worldmap - "labels.dat", - "floorcol.dat", - "underlay.dat", - "overlay.dat", - "size.dat" - // added later -]; -var KNOWN_HASHES = []; -for (let i = 0; i < KNOWN_NAMES.length; i++) { - KNOWN_HASHES[i] = genHash(KNOWN_NAMES[i]); -} - -// src/lostcity/cache/config/FontType.ts -var FontType = class _FontType { - static CHAR_LOOKUP = []; - static instances = []; - static { - const charset = `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!"\xA3$%^&*()-_=+[{]};:'@#~,<.>/?\\| `; - for (let i = 0; i < 256; i++) { - let c = charset.indexOf(String.fromCharCode(i)); - if (c == -1) { - c = 74; - } - _FontType.CHAR_LOOKUP[i] = c; - } - } - static load(dir) { - const title = Jagfile.load(`${dir}/client/title`); - _FontType.instances[0] = new _FontType(title, "p11"); - _FontType.instances[1] = new _FontType(title, "p12"); - _FontType.instances[2] = new _FontType(title, "b12"); - _FontType.instances[3] = new _FontType(title, "q8"); - } - static async loadAsync(dir) { - const title = await Jagfile.loadAsync(`${dir}/client/title`); - _FontType.instances[0] = new _FontType(title, "p11"); - _FontType.instances[1] = new _FontType(title, "p12"); - _FontType.instances[2] = new _FontType(title, "b12"); - _FontType.instances[3] = new _FontType(title, "q8"); - } - static get(id) { - return _FontType.instances[id]; - } - static get count() { - return this.instances.length; - } - // ---- - charMask = new Array(94); - charMaskWidth = new Uint8Array(94); - charMaskHeight = new Uint8Array(94); - charOffsetX = new Uint8Array(94); - charOffsetY = new Uint8Array(94); - charAdvance = new Uint8Array(95); - drawWidth = new Uint8Array(256); - height = 0; - constructor(title, font) { - const dat = title.read(`${font}.dat`); - const idx = title.read("index.dat"); - if (!dat || !idx) { - return; - } - idx.pos = dat.g2() + 4; - const off = idx.g1(); - if (off > 0) { - idx.pos += (off - 1) * 3; - } - for (let i = 0; i < 94; i++) { - this.charOffsetX[i] = idx.g1(); - this.charOffsetY[i] = idx.g1(); - const w = this.charMaskWidth[i] = idx.g2(); - const h = this.charMaskHeight[i] = idx.g2(); - const type = idx.g1(); - const len = w * h; - this.charMask[i] = new Uint8Array(len); - if (type == 0) { - for (let j = 0; j < len; j++) { - this.charMask[i][j] = dat.g1(); - } - } else if (type == 1) { - for (let x = 0; x < w; x++) { - for (let y = 0; y < h; y++) { - this.charMask[i][x + y * w] = dat.g1(); - } - } - } - if (h > this.height) { - this.height = h; - } - this.charOffsetX[i] = 1; - this.charAdvance[i] = w + 2; - let space = 0; - for (let y = Math.floor(h / 7); y < h; y++) { - space += this.charMask[i][y * w]; - } - if (space <= Math.floor(h / 7)) { - this.charAdvance[i]--; - this.charOffsetX[i] = 0; - } - space = 0; - for (let y = Math.floor(h / 7); y < h; y++) { - space += this.charMask[i][w + y * w - 1]; - } - if (space <= Math.floor(h / 7)) { - this.charAdvance[i]--; - } - } - this.charAdvance[94] = this.charAdvance[8]; - for (let c = 0; c < 256; c++) { - this.drawWidth[c] = this.charAdvance[_FontType.CHAR_LOOKUP[c]]; - } - } - stringWidth(str) { - if (str == null) { - return 0; - } - let size = 0; - for (let c = 0; c < str.length; c++) { - if (str.charAt(c) == "@" && c + 4 < str.length && str.charAt(c + 4) == "@") { - c += 4; - } else { - size += this.drawWidth[str.charCodeAt(c)]; - } - } - return size; - } - split(str, maxWidth) { - if (str.length === 0) { - return [str]; - } - const lines = []; - while (str.length > 0) { - const width = this.stringWidth(str); - if (width <= maxWidth && str.indexOf("|") === -1) { - lines.push(str); - break; - } - let splitIndex = str.length; - for (let i = 0; i < str.length; i++) { - if (str[i] === " ") { - const w = this.stringWidth(str.substring(0, i)); - if (w > maxWidth) { - break; - } - splitIndex = i; - } else if (str[i] === "|") { - splitIndex = i; - break; - } - } - lines.push(str.substring(0, splitIndex)); - str = str.substring(splitIndex + 1); - } - return lines; - } -}; - -// src/lostcity/cache/config/HuntType.ts - -// src/lostcity/entity/hunt/HuntCheckNotTooStrong.ts -var HuntCheckNotTooStrong = /* @__PURE__ */ ((HuntCheckNotTooStrong2) => { - HuntCheckNotTooStrong2[HuntCheckNotTooStrong2["OFF"] = 0] = "OFF"; - HuntCheckNotTooStrong2[HuntCheckNotTooStrong2["OUTSIDE_WILDERNESS"] = 1] = "OUTSIDE_WILDERNESS"; - return HuntCheckNotTooStrong2; -})(HuntCheckNotTooStrong || {}); -var HuntCheckNotTooStrong_default = HuntCheckNotTooStrong; - -// src/lostcity/entity/hunt/HuntModeType.ts -var HuntModeType = /* @__PURE__ */ ((HuntModeType2) => { - HuntModeType2[HuntModeType2["OFF"] = 0] = "OFF"; - HuntModeType2[HuntModeType2["PLAYER"] = 1] = "PLAYER"; - HuntModeType2[HuntModeType2["NPC"] = 2] = "NPC"; - HuntModeType2[HuntModeType2["OBJ"] = 3] = "OBJ"; - HuntModeType2[HuntModeType2["SCENERY"] = 4] = "SCENERY"; - return HuntModeType2; -})(HuntModeType || {}); -var HuntModeType_default = HuntModeType; - -// src/lostcity/entity/hunt/HuntNobodyNear.ts -var HuntNobodyNear = /* @__PURE__ */ ((HuntNobodyNear2) => { - HuntNobodyNear2[HuntNobodyNear2["KEEPHUNTING"] = 0] = "KEEPHUNTING"; - HuntNobodyNear2[HuntNobodyNear2["PAUSEHUNT"] = 1] = "PAUSEHUNT"; - return HuntNobodyNear2; -})(HuntNobodyNear || {}); -var HuntNobodyNear_default = HuntNobodyNear; - -// src/lostcity/entity/hunt/HuntVis.ts -var HuntVis = /* @__PURE__ */ ((HuntVis2) => { - HuntVis2[HuntVis2["OFF"] = 0] = "OFF"; - HuntVis2[HuntVis2["LINEOFSIGHT"] = 1] = "LINEOFSIGHT"; - HuntVis2[HuntVis2["LINEOFWALK"] = 2] = "LINEOFWALK"; - return HuntVis2; -})(HuntVis || {}); -var HuntVis_default = HuntVis; - -// src/lostcity/entity/NpcMode.ts -var NpcMode = /* @__PURE__ */ ((NpcMode2) => { - NpcMode2[NpcMode2["NULL"] = -1] = "NULL"; - NpcMode2[NpcMode2["NONE"] = 0] = "NONE"; - NpcMode2[NpcMode2["WANDER"] = 1] = "WANDER"; - NpcMode2[NpcMode2["PATROL"] = 2] = "PATROL"; - NpcMode2[NpcMode2["PLAYERESCAPE"] = 3] = "PLAYERESCAPE"; - NpcMode2[NpcMode2["PLAYERFOLLOW"] = 4] = "PLAYERFOLLOW"; - NpcMode2[NpcMode2["PLAYERFACE"] = 5] = "PLAYERFACE"; - NpcMode2[NpcMode2["PLAYERFACECLOSE"] = 6] = "PLAYERFACECLOSE"; - NpcMode2[NpcMode2["OPPLAYER1"] = 7] = "OPPLAYER1"; - NpcMode2[NpcMode2["OPPLAYER2"] = 8] = "OPPLAYER2"; - NpcMode2[NpcMode2["OPPLAYER3"] = 9] = "OPPLAYER3"; - NpcMode2[NpcMode2["OPPLAYER4"] = 10] = "OPPLAYER4"; - NpcMode2[NpcMode2["OPPLAYER5"] = 11] = "OPPLAYER5"; - NpcMode2[NpcMode2["APPLAYER1"] = 12] = "APPLAYER1"; - NpcMode2[NpcMode2["APPLAYER2"] = 13] = "APPLAYER2"; - NpcMode2[NpcMode2["APPLAYER3"] = 14] = "APPLAYER3"; - NpcMode2[NpcMode2["APPLAYER4"] = 15] = "APPLAYER4"; - NpcMode2[NpcMode2["APPLAYER5"] = 16] = "APPLAYER5"; - NpcMode2[NpcMode2["OPLOC1"] = 17] = "OPLOC1"; - NpcMode2[NpcMode2["OPLOC2"] = 18] = "OPLOC2"; - NpcMode2[NpcMode2["OPLOC3"] = 19] = "OPLOC3"; - NpcMode2[NpcMode2["OPLOC4"] = 20] = "OPLOC4"; - NpcMode2[NpcMode2["OPLOC5"] = 21] = "OPLOC5"; - NpcMode2[NpcMode2["APLOC1"] = 22] = "APLOC1"; - NpcMode2[NpcMode2["APLOC2"] = 23] = "APLOC2"; - NpcMode2[NpcMode2["APLOC3"] = 24] = "APLOC3"; - NpcMode2[NpcMode2["APLOC4"] = 25] = "APLOC4"; - NpcMode2[NpcMode2["APLOC5"] = 26] = "APLOC5"; - NpcMode2[NpcMode2["OPOBJ1"] = 27] = "OPOBJ1"; - NpcMode2[NpcMode2["OPOBJ2"] = 28] = "OPOBJ2"; - NpcMode2[NpcMode2["OPOBJ3"] = 29] = "OPOBJ3"; - NpcMode2[NpcMode2["OPOBJ4"] = 30] = "OPOBJ4"; - NpcMode2[NpcMode2["OPOBJ5"] = 31] = "OPOBJ5"; - NpcMode2[NpcMode2["APOBJ1"] = 32] = "APOBJ1"; - NpcMode2[NpcMode2["APOBJ2"] = 33] = "APOBJ2"; - NpcMode2[NpcMode2["APOBJ3"] = 34] = "APOBJ3"; - NpcMode2[NpcMode2["APOBJ4"] = 35] = "APOBJ4"; - NpcMode2[NpcMode2["APOBJ5"] = 36] = "APOBJ5"; - NpcMode2[NpcMode2["OPNPC1"] = 37] = "OPNPC1"; - NpcMode2[NpcMode2["OPNPC2"] = 38] = "OPNPC2"; - NpcMode2[NpcMode2["OPNPC3"] = 39] = "OPNPC3"; - NpcMode2[NpcMode2["OPNPC4"] = 40] = "OPNPC4"; - NpcMode2[NpcMode2["OPNPC5"] = 41] = "OPNPC5"; - NpcMode2[NpcMode2["APNPC1"] = 42] = "APNPC1"; - NpcMode2[NpcMode2["APNPC2"] = 43] = "APNPC2"; - NpcMode2[NpcMode2["APNPC3"] = 44] = "APNPC3"; - NpcMode2[NpcMode2["APNPC4"] = 45] = "APNPC4"; - NpcMode2[NpcMode2["APNPC5"] = 46] = "APNPC5"; - NpcMode2[NpcMode2["QUEUE1"] = 47] = "QUEUE1"; - NpcMode2[NpcMode2["QUEUE2"] = 48] = "QUEUE2"; - NpcMode2[NpcMode2["QUEUE3"] = 49] = "QUEUE3"; - NpcMode2[NpcMode2["QUEUE4"] = 50] = "QUEUE4"; - NpcMode2[NpcMode2["QUEUE5"] = 51] = "QUEUE5"; - NpcMode2[NpcMode2["QUEUE6"] = 52] = "QUEUE6"; - NpcMode2[NpcMode2["QUEUE7"] = 53] = "QUEUE7"; - NpcMode2[NpcMode2["QUEUE8"] = 54] = "QUEUE8"; - NpcMode2[NpcMode2["QUEUE9"] = 55] = "QUEUE9"; - NpcMode2[NpcMode2["QUEUE10"] = 56] = "QUEUE10"; - NpcMode2[NpcMode2["QUEUE11"] = 57] = "QUEUE11"; - NpcMode2[NpcMode2["QUEUE12"] = 58] = "QUEUE12"; - NpcMode2[NpcMode2["QUEUE13"] = 59] = "QUEUE13"; - NpcMode2[NpcMode2["QUEUE14"] = 60] = "QUEUE14"; - NpcMode2[NpcMode2["QUEUE15"] = 61] = "QUEUE15"; - NpcMode2[NpcMode2["QUEUE16"] = 62] = "QUEUE16"; - NpcMode2[NpcMode2["QUEUE17"] = 63] = "QUEUE17"; - NpcMode2[NpcMode2["QUEUE18"] = 64] = "QUEUE18"; - NpcMode2[NpcMode2["QUEUE19"] = 65] = "QUEUE19"; - NpcMode2[NpcMode2["QUEUE20"] = 66] = "QUEUE20"; - return NpcMode2; -})(NpcMode || {}); -var NpcMode_default = NpcMode; - -// src/lostcity/cache/config/HuntType.ts -var HuntType = class _HuntType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static load(dir) { - if (!fs6.existsSync(`${dir}/server/hunt.dat`)) { - console.log("Warning: No hunt.dat found."); - return; - } - const dat = Packet.load(`${dir}/server/hunt.dat`); - this.parse(dat); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/hunt.dat`); - if (!file.ok) { - console.log("Warning: No hunt.dat found."); - return; - } - const dat = new Packet(new Uint8Array(await file.arrayBuffer())); - this.parse(dat); - } - static parse(dat) { - _HuntType.configNames = /* @__PURE__ */ new Map(); - _HuntType.configs = []; - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new _HuntType(id); - config.decodeType(dat); - _HuntType.configs[id] = config; - if (config.debugname) { - _HuntType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return _HuntType.configs[id]; - } - static getId(name) { - return _HuntType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - // ---- - type = HuntModeType_default.OFF; - checkVis = HuntVis_default.OFF; - checkNotTooStrong = HuntCheckNotTooStrong_default.OFF; - checkNotBusy = false; - findKeepHunting = false; - findNewMode = NpcMode_default.NONE; - nobodyNear = HuntNobodyNear_default.PAUSEHUNT; - checkNotCombat = -1; - checkNotCombatSelf = -1; - checkAfk = true; - rate = 1; - checkCategory = -1; - checkNpc = -1; - checkObj = -1; - checkLoc = -1; - checkInv = -1; - checkObjParam = -1; - checkInvMinQuantity = -1; - checkInvMaxQuantity = -1; - decode(code, dat) { - if (code === 1) { - this.type = dat.g1(); - } else if (code == 2) { - this.checkVis = dat.g1(); - } else if (code == 3) { - this.checkNotTooStrong = dat.g1(); - } else if (code == 4) { - this.checkNotBusy = true; - } else if (code == 5) { - this.findKeepHunting = true; - } else if (code == 6) { - this.findNewMode = dat.g1(); - } else if (code == 7) { - this.nobodyNear = dat.g1(); - } else if (code === 8) { - this.checkNotCombat = dat.g2(); - } else if (code === 9) { - this.checkNotCombatSelf = dat.g2(); - } else if (code === 10) { - this.checkAfk = false; - } else if (code === 11) { - this.rate = dat.g2(); - } else if (code === 12) { - this.checkCategory = dat.g2(); - } else if (code === 13) { - this.checkNpc = dat.g2(); - } else if (code === 14) { - this.checkObj = dat.g2(); - } else if (code === 15) { - this.checkLoc = dat.g2(); - } else if (code === 16) { - this.checkInv = dat.g2(); - this.checkObj = dat.g2(); - this.checkInvMinQuantity = dat.g4(); - this.checkInvMaxQuantity = dat.g4(); - } else if (code === 17) { - this.checkInv = dat.g2(); - this.checkObjParam = dat.g2(); - this.checkInvMinQuantity = dat.g4(); - this.checkInvMaxQuantity = dat.g4(); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized hunt config code: ${code}`); - } - } -}; - -// src/lostcity/cache/config/IdkType.ts -var IdkType = class _IdkType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static load(dir) { - if (!fs7.existsSync(`${dir}/server/idk.dat`)) { - console.log("Warning: No idk.dat found."); - return; - } - const server = Packet.load(`${dir}/server/idk.dat`); - const jag = Jagfile.load(`${dir}/client/config`); - this.parse(server, jag); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/idk.dat`); - if (!file.ok) { - console.log("Warning: No idk.dat found."); - return; - } - const [server, jag] = await Promise.all([file.arrayBuffer(), Jagfile.loadAsync(`${dir}/client/config`)]); - this.parse(new Packet(new Uint8Array(server)), jag); - } - static parse(server, jag) { - _IdkType.configNames = /* @__PURE__ */ new Map(); - _IdkType.configs = []; - const count = server.g2(); - const client = jag.read("idk.dat"); - client.pos = 2; - for (let id = 0; id < count; id++) { - const config = new _IdkType(id); - config.decodeType(server); - config.decodeType(client); - _IdkType.configs[id] = config; - if (config.debugname) { - _IdkType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return _IdkType.configs[id]; - } - static getId(name) { - return _IdkType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - // ---- - type = -1; - models = null; - heads = new Uint16Array(5).fill(-1); - recol_s = new Uint16Array(6).fill(0); - recol_d = new Uint16Array(6).fill(0); - disable = false; - decode(code, dat) { - if (code === 1) { - this.type = dat.g1(); - } else if (code === 2) { - const count = dat.g1(); - this.models = new Uint16Array(count); - for (let i = 0; i < count; i++) { - this.models[i] = dat.g2(); - } - } else if (code === 3) { - this.disable = true; - } else if (code >= 40 && code < 50) { - this.recol_s[code - 40] = dat.g2(); - } else if (code >= 50 && code < 60) { - this.recol_d[code - 50] = dat.g2(); - } else if (code >= 60 && code < 70) { - this.heads[code - 60] = dat.g2(); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized idk config code: ${code}`); - } - } -}; - -// src/lostcity/cache/config/Component.ts -var Component = class _Component { - static TYPE_LAYER = 0; - static TYPE_UNUSED = 1; - static TYPE_INVENTORY = 2; - static TYPE_RECT = 3; - static TYPE_TEXT = 4; - static TYPE_SPRITE = 5; - static TYPE_MODEL = 6; - static TYPE_INVENTORY_TEXT = 7; - static NO_BUTTON = 0; - static BUTTON = 1; - static TARGET_BUTTON = 2; - static CLOSE_BUTTON = 3; - static TOGGLE_BUTTON = 4; - static SELECT_BUTTON = 5; - static PAUSE_BUTTON = 6; - static componentNames = /* @__PURE__ */ new Map(); - static components = []; - static load(dir) { - if (!fs8.existsSync(`${dir}/server/interface.dat`)) { - console.log("Warning: No interface.dat found."); - return; - } - const dat = Packet.load(`${dir}/server/interface.dat`); - this.parse(dat); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/interface.dat`); - if (!file.ok) { - console.log("Warning: No interface.dat found."); - return; - } - const dat = new Packet(new Uint8Array(await file.arrayBuffer())); - this.parse(dat); - } - static parse(dat) { - this.componentNames = /* @__PURE__ */ new Map(); - this.components = []; - dat.g2(); - let rootLayer = -1; - while (dat.available > 0) { - let id = dat.g2(); - if (id === 65535) { - rootLayer = dat.g2(); - id = dat.g2(); - } - const com = new _Component(); - com.id = id; - com.rootLayer = rootLayer; - com.comName = dat.gjstr(); - com.overlay = dat.gbool(); - com.type = dat.g1(); - com.buttonType = dat.g1(); - com.clientCode = dat.g2(); - com.width = dat.g2(); - com.height = dat.g2(); - com.overLayer = dat.g1(); - if (com.overLayer == 0) { - com.overLayer = -1; - } else { - com.overLayer = (com.overLayer - 1 << 8) + dat.g1(); - } - const comparatorCount = dat.g1(); - if (comparatorCount > 0) { - com.scriptComparator = new Uint8Array(comparatorCount).fill(0); - com.scriptOperand = new Uint16Array(comparatorCount).fill(0); - for (let i = 0; i < comparatorCount; i++) { - com.scriptComparator[i] = dat.g1(); - com.scriptOperand[i] = dat.g2(); - } - } - const scriptCount = dat.g1(); - if (scriptCount > 0) { - com.scripts = new Array(scriptCount).fill(null); - for (let i = 0; i < scriptCount; i++) { - const opcodeCount = dat.g2(); - com.scripts[i] = new Uint16Array(opcodeCount).fill(0); - for (let j = 0; j < opcodeCount; j++) { - com.scripts[i][j] = dat.g2(); - } - } - } - switch (com.type) { - case _Component.TYPE_LAYER: { - com.scroll = dat.g2(); - com.hide = dat.gbool(); - const childCount = dat.g1(); - com.childId = new Uint16Array(childCount).fill(0); - com.childX = new Uint16Array(childCount).fill(0); - com.childY = new Uint16Array(childCount).fill(0); - for (let i = 0; i < childCount; i++) { - com.childId[i] = dat.g2(); - com.childX[i] = dat.g2s(); - com.childY[i] = dat.g2s(); - } - break; - } - case _Component.TYPE_UNUSED: - dat.pos += 10; - break; - case _Component.TYPE_INVENTORY: { - com.draggable = dat.gbool(); - com.interactable = dat.gbool(); - com.usable = dat.gbool(); - com.marginX = dat.g1(); - com.marginY = dat.g1(); - com.inventorySlotOffsetX = new Uint16Array(20).fill(0); - com.inventorySlotOffsetY = new Uint16Array(20).fill(0); - com.inventorySlotGraphic = new Array(20).fill(null); - for (let i = 0; i < 20; i++) { - if (dat.gbool()) { - com.inventorySlotOffsetX[i] = dat.g2s(); - com.inventorySlotOffsetY[i] = dat.g2s(); - com.inventorySlotGraphic[i] = dat.gjstr(); - } - } - com.inventoryOptions = new Array(5).fill(null); - for (let i = 0; i < 5; i++) { - com.inventoryOptions[i] = dat.gjstr(); - } - com.actionVerb = dat.gjstr(); - com.action = dat.gjstr(); - com.actionTarget = dat.g2(); - break; - } - case _Component.TYPE_RECT: - com.fill = dat.gbool(); - com.colour = dat.g4(); - com.activeColour = dat.g4(); - com.overColour = dat.g4(); - break; - case _Component.TYPE_TEXT: - com.center = dat.gbool(); - com.font = dat.g1(); - com.shadowed = dat.gbool(); - com.text = dat.gjstr(); - com.activeText = dat.gjstr(); - com.colour = dat.g4(); - com.activeColour = dat.g4(); - com.overColour = dat.g4(); - break; - case _Component.TYPE_SPRITE: - com.graphic = dat.gjstr(); - com.activeGraphic = dat.gjstr(); - break; - case _Component.TYPE_MODEL: { - com.model = dat.g1(); - if (com.model != 0) { - com.model = (com.model - 1 << 8) + dat.g1(); - } - com.activeModel = dat.g1(); - if (com.activeModel != 0) { - com.activeModel = (com.activeModel - 1 << 8) + dat.g1(); - } - com.anim = dat.g1(); - if (com.anim == 0) { - com.anim = -1; - } else { - com.anim = (com.anim - 1 << 8) + dat.g1(); - } - com.activeAnim = dat.g1(); - if (com.activeAnim == 0) { - com.activeAnim = -1; - } else { - com.activeAnim = (com.activeAnim - 1 << 8) + dat.g1(); - } - com.zoom = dat.g2(); - com.xan = dat.g2(); - com.yan = dat.g2(); - break; - } - case _Component.TYPE_INVENTORY_TEXT: { - com.center = dat.gbool(); - com.font = dat.g1(); - com.shadowed = dat.gbool(); - com.colour = dat.g4(); - com.marginX = dat.g2s(); - com.marginY = dat.g2s(); - com.interactable = dat.gbool(); - com.inventoryOptions = new Array(5).fill(null); - for (let i = 0; i < 5; i++) { - com.inventoryOptions[i] = dat.gjstr(); - } - break; - } - } - switch (com.buttonType) { - case _Component.NO_BUTTON: - break; - case _Component.TARGET_BUTTON: - com.actionVerb = dat.gjstr(); - com.action = dat.gjstr(); - com.actionTarget = dat.g2(); - break; - case _Component.BUTTON: - case _Component.TOGGLE_BUTTON: - case _Component.SELECT_BUTTON: - case _Component.PAUSE_BUTTON: - com.option = dat.gjstr(); - break; - } - _Component.components[id] = com; - if (com.comName) { - _Component.componentNames.set(com.comName, id); - } - } - } - static get(id) { - return _Component.components[id]; - } - static getId(name) { - return _Component.componentNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - // ---- - id = -1; - rootLayer = -1; - comName = null; - overlay = false; - type = -1; - buttonType = -1; - clientCode = 0; - width = 0; - height = 0; - overLayer = -1; - scriptComparator = null; - scriptOperand = null; - scripts = null; - scroll = 0; - hide = false; - draggable = false; - interactable = false; - usable = false; - marginX = 0; - marginY = 0; - inventorySlotOffsetX = null; - inventorySlotOffsetY = null; - inventorySlotGraphic = null; - inventoryOptions = null; - fill = false; - center = false; - font = 0; - shadowed = false; - text = null; - activeText = null; - colour = 0; - activeColour = 0; - overColour = 0; - graphic = null; - activeGraphic = null; - model = -1; - activeModel = -1; - anim = -1; - activeAnim = -1; - zoom = 0; - xan = 0; - yan = 0; - actionVerb = null; - action = null; - actionTarget = -1; - option = null; - childId = null; - childX = null; - childY = null; -}; - -// src/lostcity/cache/config/InvType.ts -var InvType = class _InvType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static SCOPE_TEMP = 0; - static SCOPE_PERM = 1; - static SCOPE_SHARED = 2; - // commonly referenced in-engine - static INV = -1; - static WORN = -1; - static load(dir) { - if (!fs9.existsSync(`${dir}/server/inv.dat`)) { - console.log("Warning: No inv.dat found."); - return; - } - const dat = Packet.load(`${dir}/server/inv.dat`); - this.parse(dat); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/inv.dat`); - if (!file.ok) { - console.log("Warning: No inv.dat found."); - return; - } - const dat = new Packet(new Uint8Array(await file.arrayBuffer())); - this.parse(dat); - } - static parse(dat) { - _InvType.configNames = /* @__PURE__ */ new Map(); - _InvType.configs = []; - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new _InvType(id); - config.decodeType(dat); - _InvType.configs[id] = config; - if (config.debugname) { - _InvType.configNames.set(config.debugname, id); - } - } - _InvType.INV = _InvType.getId("inv"); - _InvType.WORN = _InvType.getId("worn"); - } - static get(id) { - return _InvType.configs[id]; - } - static getId(name) { - return _InvType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - // ---- - scope = 0; - size = 1; - stackall = false; - restock = false; - allstock = false; - stockobj = null; - stockcount = null; - stockrate = null; - protect = true; - runweight = false; - // inv contributes to weight - dummyinv = false; - // inv only accepts objs with dummyitem=inv_only - decode(code, dat) { - if (code === 1) { - this.scope = dat.g1(); - } else if (code === 2) { - this.size = dat.g2(); - } else if (code === 3) { - this.stackall = true; - } else if (code === 4) { - const count = dat.g1(); - this.stockobj = new Uint16Array(count); - this.stockcount = new Uint16Array(count); - this.stockrate = new Int32Array(count); - for (let j = 0; j < count; j++) { - this.stockobj[j] = dat.g2(); - this.stockcount[j] = dat.g2(); - this.stockrate[j] = dat.g4(); - } - } else if (code === 5) { - this.restock = true; - } else if (code === 6) { - this.allstock = true; - } else if (code === 7) { - this.protect = false; - } else if (code === 8) { - this.runweight = true; - } else if (code === 9) { - this.dummyinv = true; - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized inv config code: ${code}`); - } - } -}; - -// src/lostcity/cache/config/LocType.ts - -// src/lostcity/cache/config/ParamHelper.ts -var ParamHelper = { - getStringParam: function(id, holder, defaultValue) { - const value = holder.params?.get(id); - if (typeof value !== "string") { - return defaultValue ?? "null"; - } - return value; - }, - getIntParam: function(id, holder, defaultValue) { - const value = holder.params?.get(id); - if (typeof value !== "number") { - return defaultValue; - } - return value; - }, - decodeParams: function(dat) { - const count = dat.g1(); - const params = /* @__PURE__ */ new Map(); - for (let i = 0; i < count; i++) { - const key = dat.g3(); - const isString = dat.gbool(); - if (isString) { - params.set(key, dat.gjstr()); - } else { - params.set(key, dat.g4()); - } - } - return params; - } -}; - -// src/lostcity/cache/config/LocType.ts -var LocType = class _LocType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static load(dir) { - if (!fs10.existsSync(`${dir}/server/loc.dat`)) { - console.log("Warning: No loc.dat found."); - return; - } - const server = Packet.load(`${dir}/server/loc.dat`); - const jag = Jagfile.load(`${dir}/client/config`); - this.parse(server, jag); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/loc.dat`); - if (!file.ok) { - console.log("Warning: No loc.dat found."); - return; - } - const [server, jag] = await Promise.all([file.arrayBuffer(), Jagfile.loadAsync(`${dir}/client/config`)]); - this.parse(new Packet(new Uint8Array(server)), jag); - } - static parse(server, jag) { - _LocType.configNames = /* @__PURE__ */ new Map(); - _LocType.configs = []; - const count = server.g2(); - const client = jag.read("loc.dat"); - client.pos = 2; - for (let id = 0; id < count; id++) { - const config = new _LocType(id); - config.active = -1; - config.decodeType(server); - config.decodeType(client); - if (config.active === -1 && config.shapes) { - config.active = config.shapes.length > 0 && config.shapes[0] === 10 ? 1 : 0; - if (config.op && config.op.length > 0) { - config.active = 1; - } - } - _LocType.configs[id] = config; - if (config.debugname) { - _LocType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return _LocType.configs[id]; - } - static getId(name) { - return _LocType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === void 0 || id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - // ---- - models = null; - shapes = null; - name = null; - desc = null; - recol_s = null; - recol_d = null; - width = 1; - length = 1; - blockwalk = true; - blockrange = true; - active = 0; - // not -1 here just in case an new LocType is created, we want to default to "false" - hillskew = false; - sharelight = false; - occlude = false; - anim = -1; - hasalpha = false; - wallwidth = 16; - ambient = 0; - contrast = 0; - op = null; - mapfunction = -1; - mapscene = -1; - mirror = false; - shadow = true; - resizex = 128; - resizey = 128; - resizez = 128; - forceapproach = 0; - xoff = 0; - yoff = 0; - zoff = 0; - forcedecor = false; - // server-side - category = -1; - params = /* @__PURE__ */ new Map(); - decode(code, dat) { - if (code === 1) { - const count = dat.g1(); - this.models = new Uint16Array(count); - this.shapes = new Uint8Array(count); - for (let i = 0; i < count; i++) { - this.models[i] = dat.g2(); - this.shapes[i] = dat.g1(); - } - } else if (code === 2) { - this.name = dat.gjstr(); - } else if (code === 3) { - this.desc = dat.gjstr(); - } else if (code === 14) { - this.width = dat.g1(); - } else if (code === 15) { - this.length = dat.g1(); - } else if (code === 17) { - this.blockwalk = false; - } else if (code === 18) { - this.blockrange = false; - } else if (code === 19) { - this.active = dat.g1(); - } else if (code === 21) { - this.hillskew = true; - } else if (code === 22) { - this.sharelight = true; - } else if (code === 23) { - this.occlude = true; - } else if (code === 24) { - this.anim = dat.g2(); - if (this.anim == 65535) { - this.anim = -1; - } - } else if (code === 25) { - this.hasalpha = true; - } else if (code === 28) { - this.wallwidth = dat.g1(); - } else if (code === 29) { - this.ambient = dat.g1b(); - } else if (code === 39) { - this.contrast = dat.g1b(); - } else if (code >= 30 && code < 35) { - if (!this.op) { - this.op = new Array(5).fill(null); - } - this.op[code - 30] = dat.gjstr(); - if (this.op[code - 30] === "hidden") { - this.op[code - 30] = null; - } - } else if (code === 40) { - const count = dat.g1(); - this.recol_s = new Uint16Array(count); - this.recol_d = new Uint16Array(count); - for (let i = 0; i < count; i++) { - this.recol_s[i] = dat.g2(); - this.recol_d[i] = dat.g2(); - } - } else if (code === 60) { - this.mapfunction = dat.g2(); - } else if (code === 62) { - this.mirror = true; - } else if (code === 64) { - this.shadow = false; - } else if (code === 65) { - this.resizex = dat.g2(); - } else if (code === 66) { - this.resizey = dat.g2(); - } else if (code === 67) { - this.resizez = dat.g2(); - } else if (code === 68) { - this.mapscene = dat.g2(); - } else if (code === 69) { - this.forceapproach = dat.g1(); - } else if (code === 70) { - this.xoff = dat.g2s(); - } else if (code === 71) { - this.yoff = dat.g2s(); - } else if (code === 72) { - this.zoff = dat.g2s(); - } else if (code === 73) { - this.forcedecor = true; - } else if (code === 200) { - this.category = dat.g2(); - } else if (code === 249) { - this.params = ParamHelper.decodeParams(dat); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized loc config code: ${code}`); - } - } -}; - -// src/lostcity/cache/config/MesanimType.ts -var MesanimType = class _MesanimType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static load(dir) { - if (!fs11.existsSync(`${dir}/server/mesanim.dat`)) { - console.log("Warning: No mesanim.dat found."); - return; - } - const dat = Packet.load(`${dir}/server/mesanim.dat`); - this.parse(dat); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/mesanim.dat`); - if (!file.ok) { - console.log("Warning: No mesanim.dat found."); - return; - } - const dat = new Packet(new Uint8Array(await file.arrayBuffer())); - this.parse(dat); - } - static parse(dat) { - _MesanimType.configNames = /* @__PURE__ */ new Map(); - _MesanimType.configs = []; - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new _MesanimType(id); - config.decodeType(dat); - _MesanimType.configs[id] = config; - if (config.debugname) { - _MesanimType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return _MesanimType.configs[id]; - } - static getId(name) { - return _MesanimType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - // ---- - len = new Array(4).fill(-1); - decode(code, dat) { - if (code >= 1 && code < 5) { - this.len[code - 1] = dat.g2(); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized mesanim config code: ${code}`); - } - } -}; - -// src/lostcity/cache/config/NpcType.ts - -// src/lostcity/entity/BlockWalk.ts -var BlockWalk = /* @__PURE__ */ ((BlockWalk2) => { - BlockWalk2[BlockWalk2["NONE"] = 0] = "NONE"; - BlockWalk2[BlockWalk2["NPC"] = 1] = "NPC"; - BlockWalk2[BlockWalk2["ALL"] = 2] = "ALL"; - return BlockWalk2; -})(BlockWalk || {}); -var BlockWalk_default = BlockWalk; - -// src/lostcity/entity/MoveRestrict.ts -var MoveRestrict = /* @__PURE__ */ ((MoveRestrict2) => { - MoveRestrict2[MoveRestrict2["NORMAL"] = 0] = "NORMAL"; - MoveRestrict2[MoveRestrict2["BLOCKED"] = 1] = "BLOCKED"; - MoveRestrict2[MoveRestrict2["BLOCKED_NORMAL"] = 2] = "BLOCKED_NORMAL"; - MoveRestrict2[MoveRestrict2["INDOORS"] = 3] = "INDOORS"; - MoveRestrict2[MoveRestrict2["OUTDOORS"] = 4] = "OUTDOORS"; - MoveRestrict2[MoveRestrict2["NOMOVE"] = 5] = "NOMOVE"; - MoveRestrict2[MoveRestrict2["PASSTHRU"] = 6] = "PASSTHRU"; - return MoveRestrict2; -})(MoveRestrict || {}); -var MoveRestrict_default = MoveRestrict; - -// src/lostcity/entity/NpcStat.ts -var NpcStat = /* @__PURE__ */ ((NpcStat2) => { - NpcStat2[NpcStat2["ATTACK"] = 0] = "ATTACK"; - NpcStat2[NpcStat2["DEFENCE"] = 1] = "DEFENCE"; - NpcStat2[NpcStat2["STRENGTH"] = 2] = "STRENGTH"; - NpcStat2[NpcStat2["HITPOINTS"] = 3] = "HITPOINTS"; - NpcStat2[NpcStat2["RANGED"] = 4] = "RANGED"; - NpcStat2[NpcStat2["MAGIC"] = 5] = "MAGIC"; - return NpcStat2; -})(NpcStat || {}); -var NpcStat_default = NpcStat; - -// src/lostcity/cache/config/NpcType.ts -var NpcType = class _NpcType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static load(dir) { - if (!fs12.existsSync(`${dir}/server/npc.dat`)) { - console.log("Warning: No npc.dat found."); - return; - } - const server = Packet.load(`${dir}/server/npc.dat`); - const jag = Jagfile.load(`${dir}/client/config`); - this.parse(server, jag); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/npc.dat`); - if (!file.ok) { - console.log("Warning: No npc.dat found."); - return; - } - const [server, jag] = await Promise.all([file.arrayBuffer(), Jagfile.loadAsync(`${dir}/client/config`)]); - this.parse(new Packet(new Uint8Array(server)), jag); - } - static parse(server, jag) { - _NpcType.configNames = /* @__PURE__ */ new Map(); - _NpcType.configs = []; - const count = server.g2(); - const client = jag.read("npc.dat"); - client.pos = 2; - for (let id = 0; id < count; id++) { - const config = new _NpcType(id); - config.decodeType(server); - config.decodeType(client); - _NpcType.configs[id] = config; - if (config.debugname) { - _NpcType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return _NpcType.configs[id]; - } - static getId(name) { - return _NpcType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - // ---- - name = null; - desc = null; - size = 1; - models = null; - heads = null; - hasanim = false; - readyanim = -1; - walkanim = -1; - walkanim_b = -1; - walkanim_r = -1; - walkanim_l = -1; - hasalpha = false; - recol_s = null; - recol_d = null; - op = null; - resizex = -1; - resizey = -1; - resizez = -1; - minimap = true; - vislevel = -1; - resizeh = 128; - resizev = 128; - // server-side - category = -1; - wanderrange = 5; - maxrange = 7; - huntrange = 5; - timer = -1; - respawnrate = 100; - // default to 1-minute - stats = [1, 1, 1, 1, 1, 1]; - moverestrict = MoveRestrict_default.NORMAL; - attackrange = 1; - huntmode = -1; - defaultmode = NpcMode_default.WANDER; - members = false; - blockwalk = BlockWalk_default.NPC; - params = /* @__PURE__ */ new Map(); - patrolCoord = []; - patrolDelay = []; - givechase = true; - decode(code, dat) { - if (code === 1) { - const count = dat.g1(); - this.models = new Uint16Array(count); - for (let i = 0; i < count; i++) { - this.models[i] = dat.g2(); - } - } else if (code === 2) { - this.name = dat.gjstr(); - } else if (code === 3) { - this.desc = dat.gjstr(); - } else if (code === 12) { - this.size = dat.g1(); - } else if (code === 13) { - this.readyanim = dat.g2(); - } else if (code === 14) { - this.walkanim = dat.g2(); - } else if (code === 16) { - this.hasanim = true; - } else if (code === 17) { - this.walkanim = dat.g2(); - this.walkanim_b = dat.g2(); - this.walkanim_r = dat.g2(); - this.walkanim_l = dat.g2(); - } else if (code === 18) { - this.category = dat.g2(); - } else if (code >= 30 && code < 40) { - if (!this.op) { - this.op = new Array(5).fill(null); - } - this.op[code - 30] = dat.gjstr(); - if (this.op[code - 30] === "hidden") { - this.op[code - 30] = null; - } - } else if (code === 40) { - const count = dat.g1(); - this.recol_s = new Uint16Array(count); - this.recol_d = new Uint16Array(count); - for (let i = 0; i < count; i++) { - this.recol_s[i] = dat.g2(); - this.recol_d[i] = dat.g2(); - } - } else if (code === 60) { - const count = dat.g1(); - this.heads = new Uint16Array(count); - for (let i = 0; i < count; i++) { - this.heads[i] = dat.g2(); - } - } else if (code === 74) { - this.stats[NpcStat_default.ATTACK] = dat.g2(); - } else if (code === 75) { - this.stats[NpcStat_default.DEFENCE] = dat.g2(); - } else if (code === 76) { - this.stats[NpcStat_default.STRENGTH] = dat.g2(); - } else if (code === 77) { - this.stats[NpcStat_default.HITPOINTS] = dat.g2(); - } else if (code === 78) { - this.stats[NpcStat_default.RANGED] = dat.g2(); - } else if (code === 79) { - this.stats[NpcStat_default.MAGIC] = dat.g2(); - } else if (code === 90) { - this.resizex = dat.g2(); - } else if (code === 91) { - this.resizey = dat.g2(); - } else if (code === 92) { - this.resizez = dat.g2(); - } else if (code === 93) { - this.minimap = false; - } else if (code === 95) { - this.vislevel = dat.g2(); - } else if (code === 97) { - this.resizeh = dat.g2(); - } else if (code === 98) { - this.resizev = dat.g2(); - } else if (code === 200) { - this.wanderrange = dat.g1(); - } else if (code === 201) { - this.maxrange = dat.g1(); - } else if (code === 202) { - this.huntrange = dat.g1(); - } else if (code === 203) { - this.timer = dat.g2(); - } else if (code === 204) { - this.respawnrate = dat.g2(); - } else if (code === 206) { - this.moverestrict = dat.g1(); - } else if (code == 207) { - this.attackrange = dat.g1(); - } else if (code === 208) { - this.blockwalk = dat.g1(); - } else if (code === 209) { - this.huntmode = dat.g1(); - } else if (code === 210) { - this.defaultmode = dat.g1(); - } else if (code === 211) { - this.members = true; - } else if (code === 212) { - const count = dat.g1(); - this.patrolCoord = new Array(count); - this.patrolDelay = new Array(count); - for (let j = 0; j < count; j++) { - this.patrolCoord[j] = dat.g4(); - this.patrolDelay[j] = dat.g1(); - } - } else if (code === 213) { - this.givechase = false; - } else if (code === 249) { - this.params = ParamHelper.decodeParams(dat); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - console.error("Unrecognized npc config code: " + code); - console.error("Try `npm run build` and report an issue if this still happens."); - process.exit(1); - } - } -}; - -// src/lostcity/cache/config/ObjType.ts - -// src/lostcity/cache/config/ParamType.ts -var ParamType = class _ParamType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static load(dir) { - if (!fs13.existsSync(`${dir}/server/param.dat`)) { - console.log("Warning: No param.dat found."); - return; - } - const dat = Packet.load(`${dir}/server/param.dat`); - this.parse(dat); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/param.dat`); - if (!file.ok) { - console.log("Warning: No param.dat found."); - return; - } - const dat = new Packet(new Uint8Array(await file.arrayBuffer())); - this.parse(dat); - } - static parse(dat) { - _ParamType.configNames = /* @__PURE__ */ new Map(); - _ParamType.configs = []; - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new _ParamType(id); - config.decodeType(dat); - _ParamType.configs[id] = config; - if (config.debugname) { - _ParamType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return _ParamType.configs[id]; - } - static getId(name) { - return _ParamType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - // ---- - type = ScriptVarType.INT; - defaultInt = -1; - defaultString = null; - autodisable = true; - decode(code, dat) { - if (code === 1) { - this.type = dat.g1(); - } else if (code === 2) { - this.defaultInt = dat.g4(); - } else if (code === 4) { - this.autodisable = false; - } else if (code === 5) { - this.defaultString = dat.gjstr(); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized param config code: ${code}`); - } - } - getType() { - switch (this.type) { - case ScriptVarType.INT: - return "int"; - case ScriptVarType.STRING: - return "string"; - case ScriptVarType.ENUM: - return "enum"; - case ScriptVarType.OBJ: - return "obj"; - case ScriptVarType.LOC: - return "loc"; - case ScriptVarType.COMPONENT: - return "component"; - case ScriptVarType.NAMEDOBJ: - return "namedobj"; - case ScriptVarType.STRUCT: - return "struct"; - case ScriptVarType.BOOLEAN: - return "boolean"; - case ScriptVarType.COORD: - return "coord"; - case ScriptVarType.CATEGORY: - return "category"; - case ScriptVarType.SPOTANIM: - return "spotanim"; - case ScriptVarType.NPC: - return "npc"; - case ScriptVarType.INV: - return "inv"; - case ScriptVarType.SYNTH: - return "synth"; - case ScriptVarType.SEQ: - return "seq"; - case ScriptVarType.STAT: - return "stat"; - case ScriptVarType.INTERFACE: - return "interface"; - default: - return "unknown"; - } - } - isString() { - return this.type === ScriptVarType.STRING; - } - get default() { - return this.isString() ? this.defaultString : this.defaultInt; - } -}; - -// src/lostcity/util/Environment.ts - -// src/lostcity/util/TryParse.ts -function tryParseBoolean(value, defaultValue) { - if (value === "true" || value === true) { - return true; - } else if (value === "false" || value === false) { - return false; - } else { - return defaultValue; - } -} -function tryParseInt(value, defaultValue) { - if (typeof value === "number") { - return value; - } - if (typeof value !== "string" && typeof value !== "number") { - return defaultValue; - } - const intValue = parseInt(value); - if (!isNaN(intValue)) { - return intValue; - } - return defaultValue; -} -function tryParseString(value, defaultValue) { - if (typeof value !== "string") { - return defaultValue; - } - return value; -} -function tryParseArray(value, defaultValue) { - if (!Array.isArray(value)) { - return defaultValue; - } - return value; -} - -// src/lostcity/util/Environment.ts -var Environment_default = { - /// web server - WEB_PORT: tryParseInt(void 0, false ? 80 : 8888), - WEB_CORS: tryParseBoolean(void 0, true), - /// game server - // world id - offset by 9, so 1 = 10, 2 = 11, etc - NODE_ID: tryParseInt(void 0, 10), - NODE_PORT: tryParseInt(void 0, 43594), - // members content - NODE_MEMBERS: tryParseBoolean(void 0, true), - // addxp multiplier - NODE_XPRATE: tryParseInt(void 0, 1), - // production mode! - NODE_PRODUCTION: tryParseBoolean(void 0, false), - // automatic shutdown time for production mode on sigint - NODE_KILLTIMER: tryParseInt(void 0, 50), - NODE_ALLOW_CHEATS: tryParseBoolean(void 0, true), - // development mode! - NODE_DEBUG: tryParseBoolean(void 0, true), - // measuring script execution - NODE_DEBUG_PROFILE: tryParseBoolean(void 0, false), - // *only* if no login server is running to authenticate accounts, this provides admin accs by username :) - NODE_STAFF: tryParseArray(void 0, ["pazaz"]), - // todo: add staffmodlevel to database - // no server routefinding until 2009 - NODE_CLIENT_ROUTEFINDER: tryParseBoolean(void 0, true), - // controllable for bot testing - NODE_SOCKET_TIMEOUT: tryParseBoolean(void 0, true), - /// login server - LOGIN_HOST: tryParseString(void 0, "localhost"), - LOGIN_PORT: tryParseInt(void 0, 43500), - LOGIN_KEY: tryParseString(void 0, ""), - /// database - DB_HOST: tryParseString(void 0, "localhost"), - DB_USER: tryParseString(void 0, "root"), - DB_PASS: tryParseString(void 0, "password"), - DB_NAME: tryParseString(void 0, "lostcity"), - /// development - // some users may not be able to change their system PATH for this project - BUILD_JAVA_PATH: tryParseString(void 0, "java"), - // auto-build on startup - BUILD_STARTUP: tryParseBoolean(void 0, true), - // auto-update compiler on startup - BUILD_STARTUP_UPDATE: tryParseBoolean(void 0, true), - // used to check if we're producing the original cache without edits - BUILD_VERIFY: tryParseBoolean(void 0, true), - // used to keep some semblance of sanity in our folder structure - BUILD_VERIFY_FOLDER: tryParseBoolean(void 0, true), - // used for unpacking/custom development - BUILD_VERIFY_PACK: tryParseBoolean(void 0, true), - // used for unpacking/custom development - BUILD_SRC_DIR: tryParseString(void 0, "data/src") -}; - -// src/lostcity/cache/config/ObjType.ts -var ObjType = class _ObjType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static load(dir) { - if (!fs14.existsSync(`${dir}/server/obj.dat`)) { - console.log("Warning: No obj.dat found."); - return; - } - const server = Packet.load(`${dir}/server/obj.dat`); - const jag = Jagfile.load(`${dir}/client/config`); - this.parse(server, jag); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/obj.dat`); - if (!file.ok) { - console.log("Warning: No obj.dat found."); - return; - } - const [server, jag] = await Promise.all([file.arrayBuffer(), Jagfile.loadAsync(`${dir}/client/config`)]); - this.parse(new Packet(new Uint8Array(server)), jag); - } - static parse(server, jag) { - _ObjType.configNames = /* @__PURE__ */ new Map(); - _ObjType.configs = []; - const count = server.g2(); - const client = jag.read("obj.dat"); - client.pos = 2; - for (let id = 0; id < count; id++) { - const config = new _ObjType(id); - config.decodeType(server); - config.decodeType(client); - _ObjType.configs[id] = config; - if (config.debugname) { - _ObjType.configNames.set(config.debugname, id); - } - } - for (let id = 0; id < count; id++) { - const config = _ObjType.configs[id]; - if (config.certtemplate != -1) { - config.toCertificate(); - } - if (!Environment_default.NODE_MEMBERS && config.members) { - config.tradeable = false; - config.op = null; - config.iop = null; - config.params.forEach((_, key) => { - if (ParamType.get(key)?.autodisable) { - config.params.delete(key); - } - }); - } - } - } - static get(id) { - return _ObjType.configs[id]; - } - static getId(name) { - return _ObjType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - static getWearPosId(name) { - switch (name) { - case "hat": - return 0; - case "back": - return 1; - case "front": - return 2; - case "righthand": - return 3; - case "torso": - return 4; - case "lefthand": - return 5; - case "arms": - return 6; - case "legs": - return 7; - case "head": - return 8; - case "hands": - return 9; - case "feet": - return 10; - case "jaw": - return 11; - case "ring": - return 12; - case "quiver": - return 13; - default: - return -1; - } - } - // ---- - model = 0; - name = null; - desc = null; - recol_s = null; - recol_d = null; - zoom2d = 2e3; - xan2d = 0; - yan2d = 0; - zan2d = 0; - xof2d = 0; - yof2d = 0; - code9 = false; - code10 = -1; - stackable = false; - cost = 1; - members = false; - op = null; - iop = null; - manwear = -1; - manwear2 = -1; - manwearOffsetY = 0; - womanwear = -1; - womanwear2 = -1; - womanwearOffsetY = 0; - manwear3 = -1; - womanwear3 = -1; - manhead = -1; - manhead2 = -1; - womanhead = -1; - womanhead2 = -1; - countobj = null; - countco = null; - certlink = -1; - certtemplate = -1; - // server-side - wearpos = -1; - wearpos2 = -1; - wearpos3 = -1; - weight = 0; - // in grams - category = -1; - dummyitem = 0; - tradeable = false; - respawnrate = 100; - // default to 1-minute - params = /* @__PURE__ */ new Map(); - decode(code, dat) { - if (code === 1) { - this.model = dat.g2(); - } else if (code === 2) { - this.name = dat.gjstr(); - } else if (code === 3) { - this.desc = dat.gjstr(); - } else if (code === 4) { - this.zoom2d = dat.g2(); - } else if (code === 5) { - this.xan2d = dat.g2(); - } else if (code === 6) { - this.yan2d = dat.g2(); - } else if (code === 7) { - this.xof2d = dat.g2s(); - } else if (code === 8) { - this.yof2d = dat.g2s(); - } else if (code === 9) { - this.code9 = true; - } else if (code === 10) { - this.code10 = dat.g2(); - } else if (code === 11) { - this.stackable = true; - } else if (code === 12) { - this.cost = dat.g4(); - } else if (code === 13) { - this.wearpos = dat.g1(); - } else if (code === 14) { - this.wearpos2 = dat.g1(); - } else if (code === 16) { - this.members = true; - } else if (code === 23) { - this.manwear = dat.g2(); - this.manwearOffsetY = dat.g1b(); - } else if (code === 24) { - this.manwear2 = dat.g2(); - } else if (code === 25) { - this.womanwear = dat.g2(); - this.womanwearOffsetY = dat.g1b(); - } else if (code === 26) { - this.womanwear2 = dat.g2(); - } else if (code === 27) { - this.wearpos3 = dat.g1(); - } else if (code >= 30 && code < 35) { - if (!this.op) { - this.op = new Array(5).fill(null); - } - this.op[code - 30] = dat.gjstr(); - } else if (code >= 35 && code < 40) { - if (!this.iop) { - this.iop = new Array(5).fill(null); - } - this.iop[code - 35] = dat.gjstr(); - } else if (code === 40) { - const count = dat.g1(); - this.recol_s = new Uint16Array(count); - this.recol_d = new Uint16Array(count); - for (let i = 0; i < count; i++) { - this.recol_s[i] = dat.g2(); - this.recol_d[i] = dat.g2(); - } - } else if (code === 75) { - this.weight = dat.g2s(); - } else if (code === 78) { - this.manwear3 = dat.g2(); - } else if (code === 79) { - this.womanwear3 = dat.g2(); - } else if (code === 90) { - this.manhead = dat.g2(); - } else if (code === 91) { - this.womanhead = dat.g2(); - } else if (code === 92) { - this.manhead2 = dat.g2(); - } else if (code === 93) { - this.womanhead2 = dat.g2(); - } else if (code === 94) { - this.category = dat.g2(); - } else if (code === 95) { - this.zan2d = dat.g2(); - } else if (code === 96) { - this.dummyitem = dat.g1(); - } else if (code === 97) { - this.certlink = dat.g2(); - } else if (code === 98) { - this.certtemplate = dat.g2(); - } else if (code >= 100 && code < 110) { - if (!this.countobj || !this.countco) { - this.countobj = new Uint16Array(10); - this.countco = new Uint16Array(10); - } - this.countobj[code - 100] = dat.g2(); - this.countco[code - 100] = dat.g2(); - } else if (code === 200) { - this.tradeable = true; - } else if (code === 201) { - this.respawnrate = dat.g2(); - } else if (code === 249) { - this.params = ParamHelper.decodeParams(dat); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized obj config code: ${code}`); - } - } - toCertificate() { - const template = _ObjType.get(this.certtemplate); - this.model = template.model; - this.zoom2d = template.zoom2d; - this.xan2d = template.xan2d; - this.yan2d = template.yan2d; - this.zan2d = template.zan2d; - this.xof2d = template.xof2d; - this.yof2d = template.yof2d; - this.recol_s = template.recol_s; - this.recol_d = template.recol_d; - const link = _ObjType.get(this.certlink); - this.name = link.name; - this.members = link.members; - this.cost = link.cost; - this.tradeable = link.tradeable; - let article = "a"; - const c = (link.name || "").toLowerCase().charAt(0); - if (c === "a" || c === "e" || c === "i" || c === "o" || c === "u") { - article = "an"; - } - this.desc = `Swap this note at any bank for ${article} ${link.name}.`; - this.stackable = true; - } -}; - -// src/lostcity/cache/config/SeqFrame.ts -var SeqFrame = class _SeqFrame { - static instances = []; - static load(dir) { - if (!fs15.existsSync(`${dir}/server/frame_del.dat`)) { - console.log("Warning: No frame_del.dat found."); - return; - } - const dat = Packet.load(`${dir}/server/frame_del.dat`); - this.parse(dat); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/frame_del.dat`); - if (!file.ok) { - console.log("Warning: No frame_del.dat found."); - return; - } - const dat = new Packet(new Uint8Array(await file.arrayBuffer())); - this.parse(dat); - } - static parse(dat) { - _SeqFrame.instances = []; - for (let i = 0; i < dat.data.length; i++) { - const frame = new _SeqFrame(); - frame.delay = dat.g1(); - _SeqFrame.instances[i] = frame; - } - } - // ---- - delay = 0; -}; - -// src/lostcity/cache/config/SeqType.ts -var SeqType = class _SeqType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static load(dir) { - if (!fs16.existsSync(`${dir}/server/seq.dat`)) { - console.log("Warning: No seq.dat found."); - return; - } - const server = Packet.load(`${dir}/server/seq.dat`); - const jag = Jagfile.load(`${dir}/client/config`); - this.parse(server, jag); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/seq.dat`); - if (!file.ok) { - console.log("Warning: No seq.dat found."); - return; - } - const [server, jag] = await Promise.all([file.arrayBuffer(), Jagfile.loadAsync(`${dir}/client/config`)]); - this.parse(new Packet(new Uint8Array(server)), jag); - } - static parse(server, jag) { - _SeqType.configNames = /* @__PURE__ */ new Map(); - _SeqType.configs = []; - const count = server.g2(); - const client = jag.read("seq.dat"); - client.pos = 2; - for (let id = 0; id < count; id++) { - const config = new _SeqType(id); - config.decodeType(server); - config.decodeType(client); - _SeqType.configs[id] = config; - if (config.debugname) { - _SeqType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return _SeqType.configs[id]; - } - static getId(name) { - return _SeqType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return _SeqType.configs.length; - } - // ---- - frames = null; - iframes = null; - delay = null; - replayoff = -1; - walkmerge = null; - stretches = false; - priority = 5; - mainhand = -1; - offhand = -1; - replaycount = 99; - duration = 0; - decode(code, dat) { - if (code === 1) { - const count = dat.g1(); - this.frames = new Int32Array(count); - this.iframes = new Int32Array(count); - this.delay = new Int32Array(count); - for (let i = 0; i < count; i++) { - this.frames[i] = dat.g2(); - this.iframes[i] = dat.g2(); - if (this.iframes[i] === 65535) { - this.iframes[i] = -1; - } - this.delay[i] = dat.g2(); - if (this.delay[i] === 0) { - this.delay[i] = SeqFrame.instances[this.frames[i]].delay; - } - if (this.delay[i] === 0) { - this.delay[i] = 1; - } - this.duration += this.delay[i]; - } - } else if (code === 2) { - this.replayoff = dat.g2(); - } else if (code === 3) { - const count = dat.g1(); - this.walkmerge = new Int32Array(count + 1); - for (let i = 0; i < count; i++) { - this.walkmerge[i] = dat.g1(); - } - this.walkmerge[count] = 9999999; - } else if (code === 4) { - this.stretches = true; - } else if (code === 5) { - this.priority = dat.g1(); - } else if (code === 6) { - this.mainhand = dat.g2(); - } else if (code === 7) { - this.offhand = dat.g2(); - } else if (code === 8) { - this.replaycount = dat.g1(); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized seq config code: ${code}`); - } - } -}; - -// src/lostcity/cache/config/StructType.ts -var StructType = class _StructType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static load(dir) { - if (!fs17.existsSync(`${dir}/server/struct.dat`)) { - console.log("Warning: No struct.dat found."); - return; - } - const dat = Packet.load(`${dir}/server/struct.dat`); - this.parse(dat); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/struct.dat`); - if (!file.ok) { - console.log("Warning: No struct.dat found."); - return; - } - const dat = new Packet(new Uint8Array(await file.arrayBuffer())); - this.parse(dat); - } - static parse(dat) { - _StructType.configNames = /* @__PURE__ */ new Map(); - _StructType.configs = []; - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new _StructType(id); - config.decodeType(dat); - _StructType.configs[id] = config; - if (config.debugname) { - _StructType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return _StructType.configs[id]; - } - static getId(name) { - return _StructType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - // ---- - params = null; - decode(code, dat) { - if (code === 249) { - this.params = ParamHelper.decodeParams(dat); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized struct config code: ${code}`); - } - } -}; - -// src/lostcity/cache/config/VarNpcType.ts -var VarNpcType = class _VarNpcType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static load(dir) { - if (!fs18.existsSync(`${dir}/server/varn.dat`)) { - console.log("Warning: No varn.dat found."); - return; - } - const dat = Packet.load(`${dir}/server/varn.dat`); - this.parse(dat); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/varn.dat`); - if (!file.ok) { - console.log("Warning: No varn.dat found."); - return; - } - const dat = new Packet(new Uint8Array(await file.arrayBuffer())); - this.parse(dat); - } - static parse(dat) { - _VarNpcType.configNames = /* @__PURE__ */ new Map(); - _VarNpcType.configs = []; - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new _VarNpcType(id); - config.decodeType(dat); - _VarNpcType.configs[id] = config; - if (config.debugname) { - _VarNpcType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return _VarNpcType.configs[id]; - } - static getId(name) { - return _VarNpcType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - // ---- - type = ScriptVarType.INT; - decode(code, dat) { - if (code === 1) { - this.type = dat.g1(); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - console.error(`Unrecognized varn config code: ${code}`); - } - } -}; - -// src/lostcity/cache/config/VarPlayerType.ts -var VarPlayerType = class _VarPlayerType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static SCOPE_TEMP = 0; - static SCOPE_PERM = 1; - // commonly referenced in-engine - static PLAYER_RUN = -1; - static TEMP_RUN = -1; - static LASTCOMBAT = -1; - static load(dir) { - if (!fs19.existsSync(`${dir}/server/varp.dat`)) { - console.log("Warning: No varp.dat found."); - return; - } - const server = Packet.load(`${dir}/server/varp.dat`); - const jag = Jagfile.load(`${dir}/client/config`); - this.parse(server, jag); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/varp.dat`); - if (!file.ok) { - console.log("Warning: No varp.dat found."); - return; - } - const [server, jag] = await Promise.all([file.arrayBuffer(), Jagfile.loadAsync(`${dir}/client/config`)]); - this.parse(new Packet(new Uint8Array(server)), jag); - } - static parse(server, jag) { - _VarPlayerType.configNames = /* @__PURE__ */ new Map(); - _VarPlayerType.configs = []; - const count = server.g2(); - const client = jag.read("varp.dat"); - client.pos = 2; - for (let id = 0; id < count; id++) { - const config = new _VarPlayerType(id); - config.decodeType(server); - config.decodeType(client); - _VarPlayerType.configs[id] = config; - if (config.debugname) { - _VarPlayerType.configNames.set(config.debugname, id); - } - } - _VarPlayerType.PLAYER_RUN = _VarPlayerType.getId("player_run"); - _VarPlayerType.TEMP_RUN = _VarPlayerType.getId("temp_run"); - _VarPlayerType.LASTCOMBAT = _VarPlayerType.getId("lastcombat"); - } - static get(id) { - return _VarPlayerType.configs[id]; - } - static getId(name) { - return _VarPlayerType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - // ---- - clientcode = 0; - // server-side - scope = _VarPlayerType.SCOPE_TEMP; - type = ScriptVarType.INT; - protect = true; - transmit = false; - decode(code, dat) { - if (code === 1) { - this.scope = dat.g1(); - } else if (code === 2) { - this.type = dat.g1(); - } else if (code === 4) { - this.protect = false; - } else if (code === 5) { - this.clientcode = dat.g2(); - } else if (code === 6) { - this.transmit = true; - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - console.error(`Unrecognized varp config code: ${code}`); - } - } -}; - -// src/lostcity/cache/config/VarSharedType.ts -var VarSharedType = class _VarSharedType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static load(dir) { - if (!fs20.existsSync(`${dir}/server/vars.dat`)) { - console.log("Warning: No vars.dat found."); - return; - } - const dat = Packet.load(`${dir}/server/vars.dat`); - this.parse(dat); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/vars.dat`); - if (!file.ok) { - console.log("Warning: No vars.dat found."); - return; - } - const dat = new Packet(new Uint8Array(await file.arrayBuffer())); - this.parse(dat); - } - static parse(dat) { - _VarSharedType.configNames = /* @__PURE__ */ new Map(); - _VarSharedType.configs = []; - const count = dat.g2(); - for (let id = 0; id < count; id++) { - const config = new _VarSharedType(id); - config.decodeType(dat); - _VarSharedType.configs[id] = config; - if (config.debugname) { - _VarSharedType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return _VarSharedType.configs[id]; - } - static getId(name) { - return _VarSharedType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - // ---- - type = ScriptVarType.INT; - decode(code, dat) { - switch (code) { - case 1: - this.type = dat.g1(); - break; - case 250: - this.debugname = dat.gjstr(); - break; - default: - console.error(`Unrecognized vars config code: ${code}`); - break; - } - } -}; - -// src/lostcity/cache/wordenc/WordEnc.ts - -// src/lostcity/cache/wordenc/WordEncFragments.ts -var WordEncFragments = class { - fragments = []; - filter(chars) { - for (let currentIndex = 0; currentIndex < chars.length; ) { - const numberIndex = this.indexOfNumber(chars, currentIndex); - if (numberIndex === -1) { - return; - } - let isSymbolOrNotLowercaseAlpha = false; - for (let index = currentIndex; index >= 0 && index < numberIndex && !isSymbolOrNotLowercaseAlpha; index++) { - if (!WordEnc.isSymbol(chars[index]) && !WordEnc.isNotLowercaseAlpha(chars[index])) { - isSymbolOrNotLowercaseAlpha = true; - } - } - let startIndex = 0; - if (isSymbolOrNotLowercaseAlpha) { - startIndex = 0; - } - if (startIndex === 0) { - startIndex = 1; - currentIndex = numberIndex; - } - let value = 0; - for (let index = numberIndex; index < chars.length && index < currentIndex; index++) { - value = value * 10 + chars[index].charCodeAt(0) - 48; - } - if (value <= 255 && currentIndex - numberIndex <= 8) { - startIndex++; - } else { - startIndex = 0; - } - if (startIndex === 4) { - WordEnc.maskChars(numberIndex, currentIndex, chars); - startIndex = 0; - } - currentIndex = this.indexOfNonNumber(currentIndex, chars); - } - } - isBadFragment(chars) { - if (WordEnc.isNumericalChars(chars)) { - return true; - } - const value = this.getInteger(chars); - const fragments = this.fragments; - const fragmentsLength = fragments.length; - if (value === fragments[0] || value === fragments[fragmentsLength - 1]) { - return true; - } - let start = 0; - let end = fragmentsLength - 1; - while (start <= end) { - const mid = (start + end) / 2 | 0; - if (value === fragments[mid]) { - return true; - } else if (value < fragments[mid]) { - end = mid - 1; - } else { - start = mid + 1; - } - } - return false; - } - getInteger(chars) { - if (chars.length > 6) { - return 0; - } - let value = 0; - for (let index = 0; index < chars.length; index++) { - const char = chars[chars.length - index - 1]; - if (WordEnc.isLowercaseAlpha(char)) { - value = value * 38 + char.charCodeAt(0) + 1 - "a".charCodeAt(0); - } else if (char == "'") { - value = value * 38 + 27; - } else if (WordEnc.isNumerical(char)) { - value = value * 38 + char.charCodeAt(0) + 28 - "0".charCodeAt(0); - } else if (char != "\0") { - return 0; - } - } - return value; - } - indexOfNumber(chars, offset) { - for (let index = offset; index < chars.length && index >= 0; index++) { - if (WordEnc.isNumerical(chars[index])) { - return index; - } - } - return -1; - } - indexOfNonNumber(offset, chars) { - for (let index = offset; index < chars.length && index >= 0; index++) { - if (!WordEnc.isNumerical(chars[index])) { - return index; - } - } - return chars.length; - } -}; - -// src/lostcity/cache/wordenc/WordEncBadWords.ts -var WordEncBadWords = class { - wordEncFragments; - bads = []; - badCombinations = []; - constructor(wordEncFragments) { - this.wordEncFragments = wordEncFragments; - } - filter(chars) { - for (let comboIndex = 0; comboIndex < 2; comboIndex++) { - for (let index = this.bads.length - 1; index >= 0; index--) { - this.filterBadCombinations(this.badCombinations[index], chars, this.bads[index]); - } - } - } - filterBadCombinations(combos, chars, bads) { - if (bads.length > chars.length) { - return; - } - for (let startIndex = 0; startIndex <= chars.length - bads.length; startIndex++) { - let currentIndex = startIndex; - const { currentIndex: updatedCurrentIndex, badIndex, hasSymbol, hasNumber, hasDigit } = this.processBadCharacters(chars, bads, currentIndex); - currentIndex = updatedCurrentIndex; - let currentChar = chars[currentIndex]; - let nextChar = currentIndex + 1 < chars.length ? chars[currentIndex + 1] : "\0"; - if (!(badIndex >= bads.length && (!hasNumber || !hasDigit))) { - continue; - } - let shouldFilter = true; - let localIndex; - if (hasSymbol) { - let isBeforeSymbol = false; - let isAfterSymbol = false; - if (startIndex - 1 < 0 || WordEnc.isSymbol(chars[startIndex - 1]) && chars[startIndex - 1] != "'") { - isBeforeSymbol = true; - } - if (currentIndex >= chars.length || WordEnc.isSymbol(chars[currentIndex]) && chars[currentIndex] != "'") { - isAfterSymbol = true; - } - if (!isBeforeSymbol || !isAfterSymbol) { - let isSubstringValid = false; - localIndex = startIndex - 2; - if (isBeforeSymbol) { - localIndex = startIndex; - } - while (!isSubstringValid && localIndex < currentIndex) { - if (localIndex >= 0 && (!WordEnc.isSymbol(chars[localIndex]) || chars[localIndex] == "'")) { - const localSubString = []; - let localSubStringIndex; - for (localSubStringIndex = 0; localSubStringIndex < 3 && localIndex + localSubStringIndex < chars.length && (!WordEnc.isSymbol(chars[localIndex + localSubStringIndex]) || chars[localIndex + localSubStringIndex] == "'"); localSubStringIndex++) { - localSubString[localSubStringIndex] = chars[localIndex + localSubStringIndex]; - } - let isSubStringValidCondition = true; - if (localSubStringIndex == 0) { - isSubStringValidCondition = false; - } - if (localSubStringIndex < 3 && localIndex - 1 >= 0 && (!WordEnc.isSymbol(chars[localIndex - 1]) || chars[localIndex - 1] == "'")) { - isSubStringValidCondition = false; - } - if (isSubStringValidCondition && !this.wordEncFragments.isBadFragment(localSubString)) { - isSubstringValid = true; - } - } - localIndex++; - } - if (!isSubstringValid) { - shouldFilter = false; - } - } - } else { - currentChar = " "; - if (startIndex - 1 >= 0) { - currentChar = chars[startIndex - 1]; - } - nextChar = " "; - if (currentIndex < chars.length) { - nextChar = chars[currentIndex]; - } - const current = this.getIndex(currentChar); - const next = this.getIndex(nextChar); - if (combos != null && this.comboMatches(current, combos, next)) { - shouldFilter = false; - } - } - if (!shouldFilter) { - continue; - } - let numeralCount = 0; - let alphaCount = 0; - for (let index = startIndex; index < currentIndex; index++) { - if (WordEnc.isNumerical(chars[index])) { - numeralCount++; - } else if (WordEnc.isAlpha(chars[index])) { - alphaCount++; - } - } - if (numeralCount <= alphaCount) { - WordEnc.maskChars(startIndex, currentIndex, chars); - } - } - } - processBadCharacters(chars, bads, startIndex) { - let index = startIndex; - let badIndex = 0; - let count = 0; - let hasSymbol = false; - let hasNumber = false; - let hasDigit = false; - for (; index < chars.length && !(hasNumber && hasDigit); ) { - if (index >= chars.length || hasNumber && hasDigit) { - break; - } - const currentChar = chars[index]; - const nextChar = index + 1 < chars.length ? chars[index + 1] : "\0"; - let currentLength; - if (badIndex < bads.length && (currentLength = this.getEmulatedBadCharLen(nextChar, String.fromCharCode(bads[badIndex]), currentChar)) > 0) { - if (currentLength === 1 && WordEnc.isNumerical(currentChar)) { - hasNumber = true; - } - if (currentLength === 2 && (WordEnc.isNumerical(currentChar) || WordEnc.isNumerical(nextChar))) { - hasNumber = true; - } - index += currentLength; - badIndex++; - } else { - if (badIndex === 0) { - break; - } - let previousLength; - if ((previousLength = this.getEmulatedBadCharLen(nextChar, String.fromCharCode(bads[badIndex - 1]), currentChar)) > 0) { - index += previousLength; - } else { - if (badIndex >= bads.length || !WordEnc.isNotLowercaseAlpha(currentChar)) { - break; - } - if (WordEnc.isSymbol(currentChar) && currentChar !== "'") { - hasSymbol = true; - } - if (WordEnc.isNumerical(currentChar)) { - hasDigit = true; - } - index++; - count++; - if ((count * 100 / (index - startIndex) | 0) > 90) { - break; - } - } - } - } - return { - currentIndex: index, - badIndex, - hasSymbol, - hasNumber, - hasDigit - }; - } - getEmulatedBadCharLen(nextChar, badChar, currentChar) { - if (badChar == currentChar) { - return 1; - } - if (badChar >= "a" && badChar <= "m") { - if (badChar == "a") { - if (currentChar != "4" && currentChar != "@" && currentChar != "^") { - if (currentChar == "/" && nextChar == "\\") { - return 2; - } - return 0; - } - return 1; - } - if (badChar == "b") { - if (currentChar != "6" && currentChar != "8") { - if (currentChar == "1" && nextChar == "3") { - return 2; - } - return 0; - } - return 1; - } - if (badChar == "c") { - if (currentChar != "(" && currentChar != "<" && currentChar != "{" && currentChar != "[") { - return 0; - } - return 1; - } - if (badChar == "d") { - if (currentChar == "[" && nextChar == ")") { - return 2; - } - return 0; - } - if (badChar == "e") { - if (currentChar != "3" && currentChar != "\u20AC") { - return 0; - } - return 1; - } - if (badChar == "f") { - if (currentChar == "p" && nextChar == "h") { - return 2; - } - if (currentChar == "\xA3") { - return 1; - } - return 0; - } - if (badChar == "g") { - if (currentChar != "9" && currentChar != "6") { - return 0; - } - return 1; - } - if (badChar == "h") { - if (currentChar == "#") { - return 1; - } - return 0; - } - if (badChar == "i") { - if (currentChar != "y" && currentChar != "l" && currentChar != "j" && currentChar != "1" && currentChar != "!" && currentChar != ":" && currentChar != ";" && currentChar != "|") { - return 0; - } - return 1; - } - if (badChar == "j") { - return 0; - } - if (badChar == "k") { - return 0; - } - if (badChar == "l") { - if (currentChar != "1" && currentChar != "|" && currentChar != "i") { - return 0; - } - return 1; - } - if (badChar == "m") { - return 0; - } - } - if (badChar >= "n" && badChar <= "z") { - if (badChar == "n") { - return 0; - } - if (badChar == "o") { - if (currentChar != "0" && currentChar != "*") { - if ((currentChar != "(" || nextChar != ")") && (currentChar != "[" || nextChar != "]") && (currentChar != "{" || nextChar != "}") && (currentChar != "<" || nextChar != ">")) { - return 0; - } - return 2; - } - return 1; - } - if (badChar == "p") { - return 0; - } - if (badChar == "q") { - return 0; - } - if (badChar == "r") { - return 0; - } - if (badChar == "s") { - if (currentChar != "5" && currentChar != "z" && currentChar != "$" && currentChar != "2") { - return 0; - } - return 1; - } - if (badChar == "t") { - if (currentChar != "7" && currentChar != "+") { - return 0; - } - return 1; - } - if (badChar == "u") { - if (currentChar == "v") { - return 1; - } - if ((currentChar != "\\" || nextChar != "/") && (currentChar != "\\" || nextChar != "|") && (currentChar != "|" || nextChar != "/")) { - return 0; - } - return 2; - } - if (badChar == "v") { - if ((currentChar != "\\" || nextChar != "/") && (currentChar != "\\" || nextChar != "|") && (currentChar != "|" || nextChar != "/")) { - return 0; - } - return 2; - } - if (badChar == "w") { - if (currentChar == "v" && nextChar == "v") { - return 2; - } - return 0; - } - if (badChar == "x") { - if ((currentChar != ")" || nextChar != "(") && (currentChar != "}" || nextChar != "{") && (currentChar != "]" || nextChar != "[") && (currentChar != ">" || nextChar != "<")) { - return 0; - } - return 2; - } - if (badChar == "y") { - return 0; - } - if (badChar == "z") { - return 0; - } - } - if (badChar >= "0" && badChar <= "9") { - if (badChar == "0") { - if (currentChar == "o" || currentChar == "O") { - return 1; - } else if ((currentChar != "(" || nextChar != ")") && (currentChar != "{" || nextChar != "}") && (currentChar != "[" || nextChar != "]")) { - return 0; - } else { - return 2; - } - } else if (badChar == "1") { - return currentChar == "l" ? 1 : 0; - } else { - return 0; - } - } else if (badChar == ",") { - return currentChar == "." ? 1 : 0; - } else if (badChar == ".") { - return currentChar == "," ? 1 : 0; - } else if (badChar == "!") { - return currentChar == "i" ? 1 : 0; - } - return 0; - } - comboMatches(currentIndex, combos, nextIndex) { - let start = 0; - let end = combos.length - 1; - while (start <= end) { - const mid = (start + end) / 2 | 0; - if (combos[mid][0] === currentIndex && combos[mid][1] === nextIndex) { - return true; - } else if (currentIndex < combos[mid][0] || currentIndex === combos[mid][0] && nextIndex < combos[mid][1]) { - end = mid - 1; - } else { - start = mid + 1; - } - } - return false; - } - getIndex(char) { - if (WordEnc.isLowercaseAlpha(char)) { - return char.charCodeAt(0) + 1 - "a".charCodeAt(0); - } else if (char == "'") { - return 28; - } else if (WordEnc.isNumerical(char)) { - return char.charCodeAt(0) + 29 - "0".charCodeAt(0); - } - return 27; - } -}; - -// src/lostcity/cache/wordenc/WordEncDomains.ts -var WordEncDomains = class { - wordEncBadWords; - domains = []; - constructor(wordEncBadWords) { - this.wordEncBadWords = wordEncBadWords; - } - filter(chars) { - const ampersat = [...chars]; - const period = [...chars]; - this.wordEncBadWords.filterBadCombinations(null, ampersat, WordEnc.AMPERSAT); - this.wordEncBadWords.filterBadCombinations(null, period, WordEnc.PERIOD); - for (let index = this.domains.length - 1; index >= 0; index--) { - this.filterDomain(period, ampersat, this.domains[index], chars); - } - } - getEmulatedDomainCharLen(nextChar, domainChar, currentChar) { - if (domainChar == currentChar) { - return 1; - } else if (domainChar == "o" && currentChar == "0") { - return 1; - } else if (domainChar == "o" && currentChar == "(" && nextChar == ")") { - return 2; - } else if (domainChar == "c" && (currentChar == "(" || currentChar == "<" || currentChar == "[")) { - return 1; - } else if (domainChar == "e" && currentChar == "\u20AC") { - return 1; - } else if (domainChar == "s" && currentChar == "$") { - return 1; - } else if (domainChar == "l" && currentChar == "i") { - return 1; - } - return 0; - } - filterDomain(period, ampersat, domain, chars) { - const domainLength = domain.length; - const charsLength = chars.length; - for (let index = 0; index <= charsLength - domainLength; index++) { - const { matched, currentIndex } = this.findMatchingDomain(index, domain, chars); - if (!matched) { - continue; - } - const ampersatStatus = WordEnc.prefixSymbolStatus(index, chars, 3, ampersat, ["@"]); - const periodStatus = WordEnc.suffixSymbolStatus(currentIndex - 1, chars, 3, period, [".", ","]); - const shouldFilter = ampersatStatus > 2 || periodStatus > 2; - if (!shouldFilter) { - continue; - } - WordEnc.maskChars(index, currentIndex, chars); - } - } - findMatchingDomain(startIndex, domain, chars) { - const domainLength = domain.length; - let currentIndex = startIndex; - let domainIndex = 0; - while (currentIndex < chars.length && domainIndex < domainLength) { - const currentChar = chars[currentIndex]; - const nextChar = currentIndex + 1 < chars.length ? chars[currentIndex + 1] : "\0"; - const currentLength = this.getEmulatedDomainCharLen(nextChar, String.fromCharCode(domain[domainIndex]), currentChar); - if (currentLength > 0) { - currentIndex += currentLength; - domainIndex++; - } else { - if (domainIndex === 0) break; - const previousLength = this.getEmulatedDomainCharLen(nextChar, String.fromCharCode(domain[domainIndex - 1]), currentChar); - if (previousLength > 0) { - currentIndex += previousLength; - if (domainIndex === 1) startIndex++; - } else { - if (domainIndex >= domainLength || !WordEnc.isSymbol(currentChar)) break; - currentIndex++; - } - } - } - return { matched: domainIndex >= domainLength, currentIndex }; - } -}; - -// src/lostcity/cache/wordenc/WordEncTlds.ts -var WordEncTlds = class { - wordEncBadWords; - wordEncDomains; - tlds = []; - tldTypes = []; - constructor(wordEncBadWords, wordEncDomains) { - this.wordEncBadWords = wordEncBadWords; - this.wordEncDomains = wordEncDomains; - } - filter(chars) { - const period = [...chars]; - const slash = [...chars]; - this.wordEncBadWords.filterBadCombinations(null, period, WordEnc.PERIOD); - this.wordEncBadWords.filterBadCombinations(null, slash, WordEnc.SLASH); - for (let index = 0; index < this.tlds.length; index++) { - this.filterTld(slash, this.tldTypes[index], chars, this.tlds[index], period); - } - } - filterTld(slash, tldType, chars, tld, period) { - if (tld.length > chars.length) { - return; - } - for (let index = 0; index <= chars.length - tld.length; index++) { - const { currentIndex, tldIndex } = this.processTlds(chars, tld, index); - if (tldIndex < tld.length) { - continue; - } - let shouldFilter = false; - const periodFilterStatus = WordEnc.prefixSymbolStatus(index, chars, 3, period, [",", "."]); - const slashFilterStatus = WordEnc.suffixSymbolStatus(currentIndex - 1, chars, 5, slash, ["\\", "/"]); - if (tldType == 1 && periodFilterStatus > 0 && slashFilterStatus > 0) { - shouldFilter = true; - } - if (tldType == 2 && (periodFilterStatus > 2 && slashFilterStatus > 0 || periodFilterStatus > 0 && slashFilterStatus > 2)) { - shouldFilter = true; - } - if (tldType == 3 && periodFilterStatus > 0 && slashFilterStatus > 2) { - shouldFilter = true; - } - if (!shouldFilter) { - continue; - } - let startFilterIndex = index; - let endFilterIndex = currentIndex - 1; - let foundPeriod = false; - let periodIndex; - if (periodFilterStatus > 2) { - if (periodFilterStatus == 4) { - foundPeriod = false; - for (periodIndex = index - 1; periodIndex >= 0; periodIndex--) { - if (foundPeriod) { - if (period[periodIndex] != "*") { - break; - } - startFilterIndex = periodIndex; - } else if (period[periodIndex] == "*") { - startFilterIndex = periodIndex; - foundPeriod = true; - } - } - } - foundPeriod = false; - for (periodIndex = startFilterIndex - 1; periodIndex >= 0; periodIndex--) { - if (foundPeriod) { - if (WordEnc.isSymbol(chars[periodIndex])) { - break; - } - startFilterIndex = periodIndex; - } else if (!WordEnc.isSymbol(chars[periodIndex])) { - foundPeriod = true; - startFilterIndex = periodIndex; - } - } - } - if (slashFilterStatus > 2) { - if (slashFilterStatus == 4) { - foundPeriod = false; - for (periodIndex = endFilterIndex + 1; periodIndex < chars.length; periodIndex++) { - if (foundPeriod) { - if (slash[periodIndex] != "*") { - break; - } - endFilterIndex = periodIndex; - } else if (slash[periodIndex] == "*") { - endFilterIndex = periodIndex; - foundPeriod = true; - } - } - } - foundPeriod = false; - for (periodIndex = endFilterIndex + 1; periodIndex < chars.length; periodIndex++) { - if (foundPeriod) { - if (WordEnc.isSymbol(chars[periodIndex])) { - break; - } - endFilterIndex = periodIndex; - } else if (!WordEnc.isSymbol(chars[periodIndex])) { - foundPeriod = true; - endFilterIndex = periodIndex; - } - } - } - WordEnc.maskChars(startFilterIndex, endFilterIndex + 1, chars); - } - } - processTlds(chars, tld, currentIndex) { - let tldIndex = 0; - while (currentIndex < chars.length && tldIndex < tld.length) { - const currentChar = chars[currentIndex]; - const nextChar = currentIndex + 1 < chars.length ? chars[currentIndex + 1] : "\0"; - let currentLength; - if ((currentLength = this.wordEncDomains.getEmulatedDomainCharLen(nextChar, String.fromCharCode(tld[tldIndex]), currentChar)) > 0) { - currentIndex += currentLength; - tldIndex++; - } else { - if (tldIndex === 0) { - break; - } - let previousLength; - if ((previousLength = this.wordEncDomains.getEmulatedDomainCharLen(nextChar, String.fromCharCode(tld[tldIndex - 1]), currentChar)) > 0) { - currentIndex += previousLength; - } else { - if (!WordEnc.isSymbol(currentChar)) { - break; - } - currentIndex++; - } - } - } - return { currentIndex, tldIndex }; - } -}; - -// src/lostcity/cache/wordenc/WordEnc.ts -var WordEnc = class _WordEnc { - static PERIOD = new Uint16Array( - ["d", "o", "t"].join("").split("").map((char) => char.charCodeAt(0)) - ); - static AMPERSAT = new Uint16Array( - ["(", "a", ")"].join("").split("").map((char) => char.charCodeAt(0)) - ); - static SLASH = new Uint16Array( - ["s", "l", "a", "s", "h"].join("").split("").map((char) => char.charCodeAt(0)) - ); - static wordEncFragments = new WordEncFragments(); - static wordEncBadWords = new WordEncBadWords(this.wordEncFragments); - static wordEncDomains = new WordEncDomains(this.wordEncBadWords); - static wordEncTlds = new WordEncTlds(this.wordEncBadWords, this.wordEncDomains); - static whitelist = ["cook", "cook's", "cooks", "seeks", "sheet"]; - static async load(dir) { - if (!fs21.existsSync(`${dir}/client/wordenc`)) { - console.log("Warning: No wordenc found."); - return; - } - const wordenc = Jagfile.load(`${dir}/client/wordenc`); - this.readAll(wordenc); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/client/wordenc`); - if (!file.ok) { - console.log("Warning: No wordenc.dat found."); - return; - } - const wordenc = new Jagfile(new Packet(new Uint8Array(await file.arrayBuffer()))); - this.readAll(wordenc); - } - static readAll(wordenc) { - const fragmentsenc = wordenc.read("fragmentsenc.txt"); - if (!fragmentsenc) { - console.log("Warning: No fragmentsenc found."); - return; - } - const badenc = wordenc.read("badenc.txt"); - if (!badenc) { - console.log("Warning: No badenc found."); - return; - } - const domainenc = wordenc.read("domainenc.txt"); - if (!domainenc) { - console.log("Warning: No domainenc found."); - return; - } - const tldlist = wordenc.read("tldlist.txt"); - if (!tldlist) { - console.log("Warning: No tldlist found."); - return; - } - this.decodeBadEnc(badenc); - this.decodeDomainEnc(domainenc); - this.decodeFragmentsEnc(fragmentsenc); - this.decodeTldList(tldlist); - } - static filter(input) { - const characters = [...input]; - this.format(characters); - const trimmed = characters.join("").trim(); - const lowercase = trimmed.toLowerCase(); - const filtered = [...lowercase]; - this.wordEncTlds.filter(filtered); - this.wordEncBadWords.filter(filtered); - this.wordEncDomains.filter(filtered); - this.wordEncFragments.filter(filtered); - for (let index = 0; index < this.whitelist.length; index++) { - let offset = -1; - while ((offset = lowercase.indexOf(this.whitelist[index], offset + 1)) !== -1) { - const whitelisted = [...this.whitelist[index]]; - for (let charIndex = 0; charIndex < whitelisted.length; charIndex++) { - filtered[charIndex + offset] = whitelisted[charIndex]; - } - } - } - this.replaceUppercases(filtered, [...trimmed]); - this.formatUppercases(filtered); - return filtered.join("").trim(); - } - static isSymbol(char) { - return !this.isAlpha(char) && !this.isNumerical(char); - } - static isNotLowercaseAlpha(char) { - return this.isLowercaseAlpha(char) ? char == "v" || char == "x" || char == "j" || char == "q" || char == "z" : true; - } - static isAlpha(char) { - return this.isLowercaseAlpha(char) || this.isUppercaseAlpha(char); - } - static isNumerical(char) { - return char >= "0" && char <= "9"; - } - static isLowercaseAlpha(char) { - return char >= "a" && char <= "z"; - } - static isUppercaseAlpha(char) { - return char >= "A" && char <= "Z"; - } - static isNumericalChars(chars) { - for (let index = 0; index < chars.length; index++) { - if (!this.isNumerical(chars[index]) && chars[index] !== "\0") { - return false; - } - } - return true; - } - static maskChars(offset, length, chars) { - for (let index = offset; index < length; index++) { - chars[index] = "*"; - } - } - static maskedCountBackwards(chars, offset) { - let count = 0; - for (let index = offset - 1; index >= 0 && _WordEnc.isSymbol(chars[index]); index--) { - if (chars[index] === "*") { - count++; - } - } - return count; - } - static maskedCountForwards(chars, offset) { - let count = 0; - for (let index = offset + 1; index < chars.length && this.isSymbol(chars[index]); index++) { - if (chars[index] === "*") { - count++; - } - } - return count; - } - static maskedCharsStatus(chars, filtered, offset, length, prefix) { - const count = prefix ? this.maskedCountBackwards(filtered, offset) : this.maskedCountForwards(filtered, offset); - if (count >= length) { - return 4; - } else if (this.isSymbol(prefix ? chars[offset - 1] : chars[offset + 1])) { - return 1; - } - return 0; - } - static prefixSymbolStatus(offset, chars, length, symbolChars, symbols) { - if (offset === 0) { - return 2; - } - for (let index = offset - 1; index >= 0 && _WordEnc.isSymbol(chars[index]); index--) { - if (symbols.includes(chars[index])) { - return 3; - } - } - return _WordEnc.maskedCharsStatus(chars, symbolChars, offset, length, true); - } - static suffixSymbolStatus(offset, chars, length, symbolChars, symbols) { - if (offset + 1 === chars.length) { - return 2; - } - for (let index = offset + 1; index < chars.length && _WordEnc.isSymbol(chars[index]); index++) { - if (symbols.includes(chars[index])) { - return 3; - } - } - return _WordEnc.maskedCharsStatus(chars, symbolChars, offset, length, false); - } - static decodeTldList(packet) { - const count = packet.g4(); - for (let index = 0; index < count; index++) { - this.wordEncTlds.tldTypes[index] = packet.g1(); - this.wordEncTlds.tlds[index] = new Uint16Array(packet.g1()).map(() => packet.g1()); - } - } - static decodeBadEnc(packet) { - const count = packet.g4(); - for (let index = 0; index < count; index++) { - this.wordEncBadWords.bads[index] = new Uint16Array(packet.g1()).map(() => packet.g1()); - const combos = new Array(packet.g1()).fill([]).map(() => [packet.g1b(), packet.g1b()]); - if (combos.length > 0) { - this.wordEncBadWords.badCombinations[index] = combos; - } - } - } - static decodeDomainEnc(packet) { - const count = packet.g4(); - for (let index = 0; index < count; index++) { - this.wordEncDomains.domains[index] = new Uint16Array(packet.g1()).map(() => packet.g1()); - } - } - static decodeFragmentsEnc(packet) { - const count = packet.g4(); - for (let index = 0; index < count; index++) { - this.wordEncFragments.fragments[index] = packet.g2(); - } - } - static format(chars) { - let pos = 0; - for (let index = 0; index < chars.length; index++) { - if (this.isCharacterAllowed(chars[index])) { - chars[pos] = chars[index]; - } else { - chars[pos] = " "; - } - if (pos === 0 || chars[pos] !== " " || chars[pos - 1] !== " ") { - pos++; - } - } - for (let index = pos; index < chars.length; index++) { - chars[index] = " "; - } - } - static isCharacterAllowed(char) { - return char >= " " && char <= "\x7F" || char == " " || char == "\n" || char == " " || char == "\xA3" || char == "\u20AC"; - } - static replaceUppercases(chars, comparison) { - for (let index = 0; index < comparison.length; index++) { - if (chars[index] !== "*" && this.isUppercaseAlpha(comparison[index])) { - chars[index] = comparison[index]; - } - } - } - static formatUppercases(chars) { - let flagged = true; - for (let index = 0; index < chars.length; index++) { - const char = chars[index]; - if (!this.isAlpha(char)) { - flagged = true; - } else if (flagged) { - if (this.isLowercaseAlpha(char)) { - flagged = false; - } - } else if (this.isUppercaseAlpha(char)) { - chars[index] = String.fromCharCode(char.charCodeAt(0) + "a".charCodeAt(0) - 65); - } - } - } -}; - -// src/lostcity/cache/config/SpotanimType.ts -var SpotanimType = class _SpotanimType extends ConfigType { - static configNames = /* @__PURE__ */ new Map(); - static configs = []; - static load(dir) { - if (!fs22.existsSync(`${dir}/server/spotanim.dat`)) { - console.log("Warning: No spotanim.dat found."); - return; - } - const server = Packet.load(`${dir}/server/spotanim.dat`); - const jag = Jagfile.load(`${dir}/client/config`); - this.parse(server, jag); - } - static async loadAsync(dir) { - const file = await fetch(`${dir}/server/spotanim.dat`); - if (!file.ok) { - console.log("Warning: No spotanim.dat found."); - return; - } - const [server, jag] = await Promise.all([file.arrayBuffer(), Jagfile.loadAsync(`${dir}/client/config`)]); - this.parse(new Packet(new Uint8Array(server)), jag); - } - static parse(server, jag) { - _SpotanimType.configNames = /* @__PURE__ */ new Map(); - _SpotanimType.configs = []; - const count = server.g2(); - const client = jag.read("spotanim.dat"); - client.pos = 2; - for (let id = 0; id < count; id++) { - const config = new _SpotanimType(id); - config.decodeType(server); - config.decodeType(client); - _SpotanimType.configs[id] = config; - if (config.debugname) { - _SpotanimType.configNames.set(config.debugname, id); - } - } - } - static get(id) { - return _SpotanimType.configs[id]; - } - static getId(name) { - return _SpotanimType.configNames.get(name) ?? -1; - } - static getByName(name) { - const id = this.getId(name); - if (id === -1) { - return null; - } - return this.get(id); - } - static get count() { - return this.configs.length; - } - // ---- - model = 0; - anim = -1; - hasalpha = false; - recol_s = new Uint16Array(6); - recol_d = new Uint16Array(6); - resizeh = 128; - resizev = 128; - orientation = 0; - ambient = 0; - contrast = 0; - decode(code, dat) { - if (code === 1) { - this.model = dat.g2(); - } else if (code === 2) { - this.anim = dat.g2(); - } else if (code === 3) { - this.hasalpha = true; - } else if (code === 4) { - this.resizeh = dat.g2(); - } else if (code === 5) { - this.resizev = dat.g2(); - } else if (code === 6) { - this.orientation = dat.g2(); - } else if (code === 7) { - this.ambient = dat.g1(); - } else if (code === 8) { - this.contrast = dat.g1(); - } else if (code >= 40 && code < 50) { - this.recol_s[code - 40] = dat.g2(); - } else if (code >= 50 && code < 60) { - this.recol_d[code - 50] = dat.g2(); - } else if (code === 250) { - this.debugname = dat.gjstr(); - } else { - throw new Error(`Unrecognized spotanim config code: ${code}`); - } - } -}; - -// src/lostcity/engine/GameMap.ts - -// src/lostcity/engine/script/ScriptPointer.ts -var ScriptPointer = /* @__PURE__ */ ((ScriptPointer2) => { - ScriptPointer2[ScriptPointer2["ActivePlayer"] = 0] = "ActivePlayer"; - ScriptPointer2[ScriptPointer2["ActivePlayer2"] = 1] = "ActivePlayer2"; - ScriptPointer2[ScriptPointer2["ProtectedActivePlayer"] = 2] = "ProtectedActivePlayer"; - ScriptPointer2[ScriptPointer2["ProtectedActivePlayer2"] = 3] = "ProtectedActivePlayer2"; - ScriptPointer2[ScriptPointer2["ActiveNpc"] = 4] = "ActiveNpc"; - ScriptPointer2[ScriptPointer2["ActiveNpc2"] = 5] = "ActiveNpc2"; - ScriptPointer2[ScriptPointer2["ActiveLoc"] = 6] = "ActiveLoc"; - ScriptPointer2[ScriptPointer2["ActiveLoc2"] = 7] = "ActiveLoc2"; - ScriptPointer2[ScriptPointer2["ActiveObj"] = 8] = "ActiveObj"; - ScriptPointer2[ScriptPointer2["ActiveObj2"] = 9] = "ActiveObj2"; - ScriptPointer2[ScriptPointer2["_LAST"] = 10] = "_LAST"; - return ScriptPointer2; -})(ScriptPointer || {}); -var ActiveNpc = [4 /* ActiveNpc */, 5 /* ActiveNpc2 */]; -var ActiveLoc = [6 /* ActiveLoc */, 7 /* ActiveLoc2 */]; -var ActiveObj = [8 /* ActiveObj */, 9 /* ActiveObj2 */]; -var ActivePlayer = [0 /* ActivePlayer */, 1 /* ActivePlayer2 */]; -var ProtectedActivePlayer = [2 /* ProtectedActivePlayer */, 3 /* ProtectedActivePlayer2 */]; -function checkedHandler(pointer, handler) { - return function(state) { - if (typeof pointer === "number") { - state.pointerCheck(pointer); - } else { - state.pointerCheck(pointer[state.intOperand]); - } - handler(state); - }; -} -var ScriptPointer_default = ScriptPointer; - -// src/lostcity/engine/script/ScriptFile.ts - -// src/lostcity/engine/script/ScriptOpcode.ts -var ScriptOpcode = /* @__PURE__ */ ((ScriptOpcode2) => { - ScriptOpcode2[ScriptOpcode2["PUSH_CONSTANT_INT"] = 0] = "PUSH_CONSTANT_INT"; - ScriptOpcode2[ScriptOpcode2["PUSH_VARP"] = 1] = "PUSH_VARP"; - ScriptOpcode2[ScriptOpcode2["POP_VARP"] = 2] = "POP_VARP"; - ScriptOpcode2[ScriptOpcode2["PUSH_CONSTANT_STRING"] = 3] = "PUSH_CONSTANT_STRING"; - ScriptOpcode2[ScriptOpcode2["PUSH_VARN"] = 4] = "PUSH_VARN"; - ScriptOpcode2[ScriptOpcode2["POP_VARN"] = 5] = "POP_VARN"; - ScriptOpcode2[ScriptOpcode2["BRANCH"] = 6] = "BRANCH"; - ScriptOpcode2[ScriptOpcode2["BRANCH_NOT"] = 7] = "BRANCH_NOT"; - ScriptOpcode2[ScriptOpcode2["BRANCH_EQUALS"] = 8] = "BRANCH_EQUALS"; - ScriptOpcode2[ScriptOpcode2["BRANCH_LESS_THAN"] = 9] = "BRANCH_LESS_THAN"; - ScriptOpcode2[ScriptOpcode2["BRANCH_GREATER_THAN"] = 10] = "BRANCH_GREATER_THAN"; - ScriptOpcode2[ScriptOpcode2["PUSH_VARS"] = 11] = "PUSH_VARS"; - ScriptOpcode2[ScriptOpcode2["POP_VARS"] = 12] = "POP_VARS"; - ScriptOpcode2[ScriptOpcode2["RETURN"] = 21] = "RETURN"; - ScriptOpcode2[ScriptOpcode2["GOSUB"] = 22] = "GOSUB"; - ScriptOpcode2[ScriptOpcode2["JUMP"] = 23] = "JUMP"; - ScriptOpcode2[ScriptOpcode2["SWITCH"] = 24] = "SWITCH"; - ScriptOpcode2[ScriptOpcode2["BRANCH_LESS_THAN_OR_EQUALS"] = 31] = "BRANCH_LESS_THAN_OR_EQUALS"; - ScriptOpcode2[ScriptOpcode2["BRANCH_GREATER_THAN_OR_EQUALS"] = 32] = "BRANCH_GREATER_THAN_OR_EQUALS"; - ScriptOpcode2[ScriptOpcode2["PUSH_INT_LOCAL"] = 33] = "PUSH_INT_LOCAL"; - ScriptOpcode2[ScriptOpcode2["POP_INT_LOCAL"] = 34] = "POP_INT_LOCAL"; - ScriptOpcode2[ScriptOpcode2["PUSH_STRING_LOCAL"] = 35] = "PUSH_STRING_LOCAL"; - ScriptOpcode2[ScriptOpcode2["POP_STRING_LOCAL"] = 36] = "POP_STRING_LOCAL"; - ScriptOpcode2[ScriptOpcode2["JOIN_STRING"] = 37] = "JOIN_STRING"; - ScriptOpcode2[ScriptOpcode2["POP_INT_DISCARD"] = 38] = "POP_INT_DISCARD"; - ScriptOpcode2[ScriptOpcode2["POP_STRING_DISCARD"] = 39] = "POP_STRING_DISCARD"; - ScriptOpcode2[ScriptOpcode2["GOSUB_WITH_PARAMS"] = 40] = "GOSUB_WITH_PARAMS"; - ScriptOpcode2[ScriptOpcode2["JUMP_WITH_PARAMS"] = 41] = "JUMP_WITH_PARAMS"; - ScriptOpcode2[ScriptOpcode2["DEFINE_ARRAY"] = 44] = "DEFINE_ARRAY"; - ScriptOpcode2[ScriptOpcode2["PUSH_ARRAY_INT"] = 45] = "PUSH_ARRAY_INT"; - ScriptOpcode2[ScriptOpcode2["POP_ARRAY_INT"] = 46] = "POP_ARRAY_INT"; - ScriptOpcode2[ScriptOpcode2["COORDX"] = 1e3] = "COORDX"; - ScriptOpcode2[ScriptOpcode2["COORDY"] = 1001] = "COORDY"; - ScriptOpcode2[ScriptOpcode2["COORDZ"] = 1002] = "COORDZ"; - ScriptOpcode2[ScriptOpcode2["DISTANCE"] = 1003] = "DISTANCE"; - ScriptOpcode2[ScriptOpcode2["HUNTALL"] = 1004] = "HUNTALL"; - ScriptOpcode2[ScriptOpcode2["HUNTNEXT"] = 1005] = "HUNTNEXT"; - ScriptOpcode2[ScriptOpcode2["INZONE"] = 1006] = "INZONE"; - ScriptOpcode2[ScriptOpcode2["LINEOFSIGHT"] = 1007] = "LINEOFSIGHT"; - ScriptOpcode2[ScriptOpcode2["LINEOFWALK"] = 1008] = "LINEOFWALK"; - ScriptOpcode2[ScriptOpcode2["MAP_BLOCKED"] = 1009] = "MAP_BLOCKED"; - ScriptOpcode2[ScriptOpcode2["MAP_INDOORS"] = 1010] = "MAP_INDOORS"; - ScriptOpcode2[ScriptOpcode2["MAP_CLOCK"] = 1011] = "MAP_CLOCK"; - ScriptOpcode2[ScriptOpcode2["MAP_LOCADDUNSAFE"] = 1012] = "MAP_LOCADDUNSAFE"; - ScriptOpcode2[ScriptOpcode2["MAP_MEMBERS"] = 1013] = "MAP_MEMBERS"; - ScriptOpcode2[ScriptOpcode2["MAP_PLAYERCOUNT"] = 1014] = "MAP_PLAYERCOUNT"; - ScriptOpcode2[ScriptOpcode2["MAP_FINDSQUARE"] = 1015] = "MAP_FINDSQUARE"; - ScriptOpcode2[ScriptOpcode2["MOVECOORD"] = 1016] = "MOVECOORD"; - ScriptOpcode2[ScriptOpcode2["PLAYERCOUNT"] = 1017] = "PLAYERCOUNT"; - ScriptOpcode2[ScriptOpcode2["PROJANIM_MAP"] = 1018] = "PROJANIM_MAP"; - ScriptOpcode2[ScriptOpcode2["PROJANIM_NPC"] = 1019] = "PROJANIM_NPC"; - ScriptOpcode2[ScriptOpcode2["PROJANIM_PL"] = 1020] = "PROJANIM_PL"; - ScriptOpcode2[ScriptOpcode2["SEQLENGTH"] = 1021] = "SEQLENGTH"; - ScriptOpcode2[ScriptOpcode2["SPLIT_GET"] = 1022] = "SPLIT_GET"; - ScriptOpcode2[ScriptOpcode2["SPLIT_GETANIM"] = 1023] = "SPLIT_GETANIM"; - ScriptOpcode2[ScriptOpcode2["SPLIT_INIT"] = 1024] = "SPLIT_INIT"; - ScriptOpcode2[ScriptOpcode2["SPLIT_LINECOUNT"] = 1025] = "SPLIT_LINECOUNT"; - ScriptOpcode2[ScriptOpcode2["SPLIT_PAGECOUNT"] = 1026] = "SPLIT_PAGECOUNT"; - ScriptOpcode2[ScriptOpcode2["SPOTANIM_MAP"] = 1027] = "SPOTANIM_MAP"; - ScriptOpcode2[ScriptOpcode2["STAT_RANDOM"] = 1028] = "STAT_RANDOM"; - ScriptOpcode2[ScriptOpcode2["STRUCT_PARAM"] = 1029] = "STRUCT_PARAM"; - ScriptOpcode2[ScriptOpcode2["WORLD_DELAY"] = 1030] = "WORLD_DELAY"; - ScriptOpcode2[ScriptOpcode2["NPCCOUNT"] = 1031] = "NPCCOUNT"; - ScriptOpcode2[ScriptOpcode2["ZONECOUNT"] = 1032] = "ZONECOUNT"; - ScriptOpcode2[ScriptOpcode2["LOCCOUNT"] = 1033] = "LOCCOUNT"; - ScriptOpcode2[ScriptOpcode2["OBJCOUNT"] = 1034] = "OBJCOUNT"; - ScriptOpcode2[ScriptOpcode2["ALLOWDESIGN"] = 2e3] = "ALLOWDESIGN"; - ScriptOpcode2[ScriptOpcode2["ANIM"] = 2001] = "ANIM"; - ScriptOpcode2[ScriptOpcode2["BAS_READYANIM"] = 2002] = "BAS_READYANIM"; - ScriptOpcode2[ScriptOpcode2["BAS_RUNNING"] = 2003] = "BAS_RUNNING"; - ScriptOpcode2[ScriptOpcode2["BAS_TURNONSPOT"] = 2004] = "BAS_TURNONSPOT"; - ScriptOpcode2[ScriptOpcode2["BAS_WALK_B"] = 2005] = "BAS_WALK_B"; - ScriptOpcode2[ScriptOpcode2["BAS_WALK_F"] = 2006] = "BAS_WALK_F"; - ScriptOpcode2[ScriptOpcode2["BAS_WALK_L"] = 2007] = "BAS_WALK_L"; - ScriptOpcode2[ScriptOpcode2["BAS_WALK_R"] = 2008] = "BAS_WALK_R"; - ScriptOpcode2[ScriptOpcode2["BUFFER_FULL"] = 2009] = "BUFFER_FULL"; - ScriptOpcode2[ScriptOpcode2["BUILDAPPEARANCE"] = 2010] = "BUILDAPPEARANCE"; - ScriptOpcode2[ScriptOpcode2["BUSY"] = 2011] = "BUSY"; - ScriptOpcode2[ScriptOpcode2["CAM_LOOKAT"] = 2012] = "CAM_LOOKAT"; - ScriptOpcode2[ScriptOpcode2["CAM_MOVETO"] = 2013] = "CAM_MOVETO"; - ScriptOpcode2[ScriptOpcode2["CAM_RESET"] = 2014] = "CAM_RESET"; - ScriptOpcode2[ScriptOpcode2["CAM_SHAKE"] = 2015] = "CAM_SHAKE"; - ScriptOpcode2[ScriptOpcode2["CLEARQUEUE"] = 2016] = "CLEARQUEUE"; - ScriptOpcode2[ScriptOpcode2["CLEARSOFTTIMER"] = 2017] = "CLEARSOFTTIMER"; - ScriptOpcode2[ScriptOpcode2["CLEARTIMER"] = 2018] = "CLEARTIMER"; - ScriptOpcode2[ScriptOpcode2["COORD"] = 2019] = "COORD"; - ScriptOpcode2[ScriptOpcode2["DAMAGE"] = 2020] = "DAMAGE"; - ScriptOpcode2[ScriptOpcode2["DISPLAYNAME"] = 2021] = "DISPLAYNAME"; - ScriptOpcode2[ScriptOpcode2["FACESQUARE"] = 2022] = "FACESQUARE"; - ScriptOpcode2[ScriptOpcode2["FINDUID"] = 2023] = "FINDUID"; - ScriptOpcode2[ScriptOpcode2["GENDER"] = 2024] = "GENDER"; - ScriptOpcode2[ScriptOpcode2["GETQUEUE"] = 2025] = "GETQUEUE"; - ScriptOpcode2[ScriptOpcode2["STAT_ADVANCE"] = 2026] = "STAT_ADVANCE"; - ScriptOpcode2[ScriptOpcode2["HEADICONS_GET"] = 2027] = "HEADICONS_GET"; - ScriptOpcode2[ScriptOpcode2["HEADICONS_SET"] = 2028] = "HEADICONS_SET"; - ScriptOpcode2[ScriptOpcode2["HEALENERGY"] = 2029] = "HEALENERGY"; - ScriptOpcode2[ScriptOpcode2["HINT_COORD"] = 2030] = "HINT_COORD"; - ScriptOpcode2[ScriptOpcode2["HINT_NPC"] = 2031] = "HINT_NPC"; - ScriptOpcode2[ScriptOpcode2["HINT_PLAYER"] = 2032] = "HINT_PLAYER"; - ScriptOpcode2[ScriptOpcode2["HINT_STOP"] = 2033] = "HINT_STOP"; - ScriptOpcode2[ScriptOpcode2["IF_CLOSE"] = 2034] = "IF_CLOSE"; - ScriptOpcode2[ScriptOpcode2["IF_CLOSESTICKY"] = 2035] = "IF_CLOSESTICKY"; - ScriptOpcode2[ScriptOpcode2["IF_MULTIZONE"] = 2036] = "IF_MULTIZONE"; - ScriptOpcode2[ScriptOpcode2["IF_OPENCHAT"] = 2037] = "IF_OPENCHAT"; - ScriptOpcode2[ScriptOpcode2["IF_OPENCHATSTICKY"] = 2038] = "IF_OPENCHATSTICKY"; - ScriptOpcode2[ScriptOpcode2["IF_OPENMAINMODAL"] = 2039] = "IF_OPENMAINMODAL"; - ScriptOpcode2[ScriptOpcode2["IF_OPENMAINMODALSIDEOVERLAY"] = 2040] = "IF_OPENMAINMODALSIDEOVERLAY"; - ScriptOpcode2[ScriptOpcode2["IF_OPENSIDEOVERLAY"] = 2041] = "IF_OPENSIDEOVERLAY"; - ScriptOpcode2[ScriptOpcode2["IF_SETANIM"] = 2042] = "IF_SETANIM"; - ScriptOpcode2[ScriptOpcode2["IF_SETCOLOUR"] = 2043] = "IF_SETCOLOUR"; - ScriptOpcode2[ScriptOpcode2["IF_SETHIDE"] = 2044] = "IF_SETHIDE"; - ScriptOpcode2[ScriptOpcode2["IF_SETMODEL"] = 2045] = "IF_SETMODEL"; - ScriptOpcode2[ScriptOpcode2["IF_SETRECOL"] = 2046] = "IF_SETRECOL"; - ScriptOpcode2[ScriptOpcode2["IF_SETNPCHEAD"] = 2047] = "IF_SETNPCHEAD"; - ScriptOpcode2[ScriptOpcode2["IF_SETOBJECT"] = 2048] = "IF_SETOBJECT"; - ScriptOpcode2[ScriptOpcode2["IF_SETPLAYERHEAD"] = 2049] = "IF_SETPLAYERHEAD"; - ScriptOpcode2[ScriptOpcode2["IF_SETPOSITION"] = 2050] = "IF_SETPOSITION"; - ScriptOpcode2[ScriptOpcode2["IF_SETRESUMEBUTTONS"] = 2051] = "IF_SETRESUMEBUTTONS"; - ScriptOpcode2[ScriptOpcode2["IF_SETTAB"] = 2052] = "IF_SETTAB"; - ScriptOpcode2[ScriptOpcode2["IF_SETTABACTIVE"] = 2053] = "IF_SETTABACTIVE"; - ScriptOpcode2[ScriptOpcode2["IF_SETTABFLASH"] = 2054] = "IF_SETTABFLASH"; - ScriptOpcode2[ScriptOpcode2["IF_SETTEXT"] = 2055] = "IF_SETTEXT"; - ScriptOpcode2[ScriptOpcode2["LAST_LOGIN_INFO"] = 2056] = "LAST_LOGIN_INFO"; - ScriptOpcode2[ScriptOpcode2["LAST_COM"] = 2057] = "LAST_COM"; - ScriptOpcode2[ScriptOpcode2["LAST_INT"] = 2058] = "LAST_INT"; - ScriptOpcode2[ScriptOpcode2["LAST_ITEM"] = 2059] = "LAST_ITEM"; - ScriptOpcode2[ScriptOpcode2["LAST_SLOT"] = 2060] = "LAST_SLOT"; - ScriptOpcode2[ScriptOpcode2["LAST_TARGETSLOT"] = 2061] = "LAST_TARGETSLOT"; - ScriptOpcode2[ScriptOpcode2["LAST_USEITEM"] = 2062] = "LAST_USEITEM"; - ScriptOpcode2[ScriptOpcode2["LAST_USESLOT"] = 2063] = "LAST_USESLOT"; - ScriptOpcode2[ScriptOpcode2["LONGQUEUE"] = 2064] = "LONGQUEUE"; - ScriptOpcode2[ScriptOpcode2["MES"] = 2065] = "MES"; - ScriptOpcode2[ScriptOpcode2["MIDI_JINGLE"] = 2066] = "MIDI_JINGLE"; - ScriptOpcode2[ScriptOpcode2["MIDI_SONG"] = 2067] = "MIDI_SONG"; - ScriptOpcode2[ScriptOpcode2["NAME"] = 2068] = "NAME"; - ScriptOpcode2[ScriptOpcode2["P_APRANGE"] = 2069] = "P_APRANGE"; - ScriptOpcode2[ScriptOpcode2["P_ARRIVEDELAY"] = 2070] = "P_ARRIVEDELAY"; - ScriptOpcode2[ScriptOpcode2["P_COUNTDIALOG"] = 2071] = "P_COUNTDIALOG"; - ScriptOpcode2[ScriptOpcode2["P_DELAY"] = 2072] = "P_DELAY"; - ScriptOpcode2[ScriptOpcode2["P_EXACTMOVE"] = 2073] = "P_EXACTMOVE"; - ScriptOpcode2[ScriptOpcode2["P_FINDUID"] = 2074] = "P_FINDUID"; - ScriptOpcode2[ScriptOpcode2["P_LOCMERGE"] = 2075] = "P_LOCMERGE"; - ScriptOpcode2[ScriptOpcode2["P_LOGOUT"] = 2076] = "P_LOGOUT"; - ScriptOpcode2[ScriptOpcode2["P_OPHELD"] = 2077] = "P_OPHELD"; - ScriptOpcode2[ScriptOpcode2["P_OPLOC"] = 2078] = "P_OPLOC"; - ScriptOpcode2[ScriptOpcode2["P_OPNPC"] = 2079] = "P_OPNPC"; - ScriptOpcode2[ScriptOpcode2["P_OPNPCT"] = 2080] = "P_OPNPCT"; - ScriptOpcode2[ScriptOpcode2["P_OPOBJ"] = 2081] = "P_OPOBJ"; - ScriptOpcode2[ScriptOpcode2["P_OPPLAYER"] = 2082] = "P_OPPLAYER"; - ScriptOpcode2[ScriptOpcode2["P_OPPLAYERT"] = 2083] = "P_OPPLAYERT"; - ScriptOpcode2[ScriptOpcode2["P_PAUSEBUTTON"] = 2084] = "P_PAUSEBUTTON"; - ScriptOpcode2[ScriptOpcode2["P_STOPACTION"] = 2085] = "P_STOPACTION"; - ScriptOpcode2[ScriptOpcode2["P_TELEJUMP"] = 2086] = "P_TELEJUMP"; - ScriptOpcode2[ScriptOpcode2["P_TELEPORT"] = 2087] = "P_TELEPORT"; - ScriptOpcode2[ScriptOpcode2["P_WALK"] = 2088] = "P_WALK"; - ScriptOpcode2[ScriptOpcode2["PLAYER_FINDALLZONE"] = 2089] = "PLAYER_FINDALLZONE"; - ScriptOpcode2[ScriptOpcode2["PLAYER_FINDNEXT"] = 2090] = "PLAYER_FINDNEXT"; - ScriptOpcode2[ScriptOpcode2["QUEUE"] = 2091] = "QUEUE"; - ScriptOpcode2[ScriptOpcode2["SAY"] = 2092] = "SAY"; - ScriptOpcode2[ScriptOpcode2["WALKTRIGGER"] = 2093] = "WALKTRIGGER"; - ScriptOpcode2[ScriptOpcode2["SETTIMER"] = 2094] = "SETTIMER"; - ScriptOpcode2[ScriptOpcode2["SOFTTIMER"] = 2095] = "SOFTTIMER"; - ScriptOpcode2[ScriptOpcode2["SOUND_SYNTH"] = 2096] = "SOUND_SYNTH"; - ScriptOpcode2[ScriptOpcode2["SPOTANIM_PL"] = 2097] = "SPOTANIM_PL"; - ScriptOpcode2[ScriptOpcode2["STAFFMODLEVEL"] = 2098] = "STAFFMODLEVEL"; - ScriptOpcode2[ScriptOpcode2["STAT"] = 2099] = "STAT"; - ScriptOpcode2[ScriptOpcode2["STAT_ADD"] = 2100] = "STAT_ADD"; - ScriptOpcode2[ScriptOpcode2["STAT_BASE"] = 2101] = "STAT_BASE"; - ScriptOpcode2[ScriptOpcode2["STAT_HEAL"] = 2102] = "STAT_HEAL"; - ScriptOpcode2[ScriptOpcode2["STAT_SUB"] = 2103] = "STAT_SUB"; - ScriptOpcode2[ScriptOpcode2["STRONGQUEUE"] = 2104] = "STRONGQUEUE"; - ScriptOpcode2[ScriptOpcode2["UID"] = 2105] = "UID"; - ScriptOpcode2[ScriptOpcode2["WEAKQUEUE"] = 2106] = "WEAKQUEUE"; - ScriptOpcode2[ScriptOpcode2["IF_OPENMAINOVERLAY"] = 2107] = "IF_OPENMAINOVERLAY"; - ScriptOpcode2[ScriptOpcode2["AFK_EVENT"] = 2108] = "AFK_EVENT"; - ScriptOpcode2[ScriptOpcode2["LOWMEMORY"] = 2109] = "LOWMEMORY"; - ScriptOpcode2[ScriptOpcode2["SETIDKIT"] = 2110] = "SETIDKIT"; - ScriptOpcode2[ScriptOpcode2["P_CLEARPENDINGACTION"] = 2111] = "P_CLEARPENDINGACTION"; - ScriptOpcode2[ScriptOpcode2["GETWALKTRIGGER"] = 2112] = "GETWALKTRIGGER"; - ScriptOpcode2[ScriptOpcode2["BUSY2"] = 2113] = "BUSY2"; - ScriptOpcode2[ScriptOpcode2["FINDHERO"] = 2114] = "FINDHERO"; - ScriptOpcode2[ScriptOpcode2["BOTH_HEROPOINTS"] = 2115] = "BOTH_HEROPOINTS"; - ScriptOpcode2[ScriptOpcode2["SETGENDER"] = 2116] = "SETGENDER"; - ScriptOpcode2[ScriptOpcode2["SETSKINCOLOUR"] = 2117] = "SETSKINCOLOUR"; - ScriptOpcode2[ScriptOpcode2["P_ANIMPROTECT"] = 2118] = "P_ANIMPROTECT"; - ScriptOpcode2[ScriptOpcode2["RUNENERGY"] = 2119] = "RUNENERGY"; - ScriptOpcode2[ScriptOpcode2["WEIGHT"] = 2120] = "WEIGHT"; - ScriptOpcode2[ScriptOpcode2["LAST_COORD"] = 2121] = "LAST_COORD"; - ScriptOpcode2[ScriptOpcode2["NPC_ADD"] = 2500] = "NPC_ADD"; - ScriptOpcode2[ScriptOpcode2["NPC_ANIM"] = 2501] = "NPC_ANIM"; - ScriptOpcode2[ScriptOpcode2["NPC_BASESTAT"] = 2502] = "NPC_BASESTAT"; - ScriptOpcode2[ScriptOpcode2["NPC_CATEGORY"] = 2503] = "NPC_CATEGORY"; - ScriptOpcode2[ScriptOpcode2["NPC_CHANGETYPE"] = 2504] = "NPC_CHANGETYPE"; - ScriptOpcode2[ScriptOpcode2["NPC_COORD"] = 2505] = "NPC_COORD"; - ScriptOpcode2[ScriptOpcode2["NPC_DAMAGE"] = 2506] = "NPC_DAMAGE"; - ScriptOpcode2[ScriptOpcode2["NPC_DEL"] = 2507] = "NPC_DEL"; - ScriptOpcode2[ScriptOpcode2["NPC_DELAY"] = 2508] = "NPC_DELAY"; - ScriptOpcode2[ScriptOpcode2["NPC_FACESQUARE"] = 2509] = "NPC_FACESQUARE"; - ScriptOpcode2[ScriptOpcode2["NPC_FIND"] = 2510] = "NPC_FIND"; - ScriptOpcode2[ScriptOpcode2["NPC_FINDALLANY"] = 2511] = "NPC_FINDALLANY"; - ScriptOpcode2[ScriptOpcode2["NPC_FINDEXACT"] = 2512] = "NPC_FINDEXACT"; - ScriptOpcode2[ScriptOpcode2["NPC_FINDHERO"] = 2513] = "NPC_FINDHERO"; - ScriptOpcode2[ScriptOpcode2["NPC_FINDALLZONE"] = 2514] = "NPC_FINDALLZONE"; - ScriptOpcode2[ScriptOpcode2["NPC_FINDNEXT"] = 2515] = "NPC_FINDNEXT"; - ScriptOpcode2[ScriptOpcode2["NPC_FINDUID"] = 2516] = "NPC_FINDUID"; - ScriptOpcode2[ScriptOpcode2["NPC_GETMODE"] = 2517] = "NPC_GETMODE"; - ScriptOpcode2[ScriptOpcode2["NPC_HEROPOINTS"] = 2518] = "NPC_HEROPOINTS"; - ScriptOpcode2[ScriptOpcode2["NPC_NAME"] = 2519] = "NPC_NAME"; - ScriptOpcode2[ScriptOpcode2["NPC_PARAM"] = 2520] = "NPC_PARAM"; - ScriptOpcode2[ScriptOpcode2["NPC_QUEUE"] = 2521] = "NPC_QUEUE"; - ScriptOpcode2[ScriptOpcode2["NPC_RANGE"] = 2522] = "NPC_RANGE"; - ScriptOpcode2[ScriptOpcode2["NPC_SAY"] = 2523] = "NPC_SAY"; - ScriptOpcode2[ScriptOpcode2["NPC_HUNTALL"] = 2524] = "NPC_HUNTALL"; - ScriptOpcode2[ScriptOpcode2["NPC_HUNTNEXT"] = 2525] = "NPC_HUNTNEXT"; - ScriptOpcode2[ScriptOpcode2["NPC_SETHUNT"] = 2526] = "NPC_SETHUNT"; - ScriptOpcode2[ScriptOpcode2["NPC_SETHUNTMODE"] = 2527] = "NPC_SETHUNTMODE"; - ScriptOpcode2[ScriptOpcode2["NPC_SETMODE"] = 2528] = "NPC_SETMODE"; - ScriptOpcode2[ScriptOpcode2["NPC_WALKTRIGGER"] = 2529] = "NPC_WALKTRIGGER"; - ScriptOpcode2[ScriptOpcode2["NPC_SETTIMER"] = 2530] = "NPC_SETTIMER"; - ScriptOpcode2[ScriptOpcode2["NPC_STAT"] = 2531] = "NPC_STAT"; - ScriptOpcode2[ScriptOpcode2["NPC_STATADD"] = 2532] = "NPC_STATADD"; - ScriptOpcode2[ScriptOpcode2["NPC_STATHEAL"] = 2533] = "NPC_STATHEAL"; - ScriptOpcode2[ScriptOpcode2["NPC_STATSUB"] = 2534] = "NPC_STATSUB"; - ScriptOpcode2[ScriptOpcode2["NPC_TELE"] = 2535] = "NPC_TELE"; - ScriptOpcode2[ScriptOpcode2["NPC_TYPE"] = 2536] = "NPC_TYPE"; - ScriptOpcode2[ScriptOpcode2["NPC_UID"] = 2537] = "NPC_UID"; - ScriptOpcode2[ScriptOpcode2["SPOTANIM_NPC"] = 2538] = "SPOTANIM_NPC"; - ScriptOpcode2[ScriptOpcode2["NPC_WALK"] = 2539] = "NPC_WALK"; - ScriptOpcode2[ScriptOpcode2["NPC_ATTACKRANGE"] = 2540] = "NPC_ATTACKRANGE"; - ScriptOpcode2[ScriptOpcode2["LOC_ADD"] = 3e3] = "LOC_ADD"; - ScriptOpcode2[ScriptOpcode2["LOC_ANGLE"] = 3001] = "LOC_ANGLE"; - ScriptOpcode2[ScriptOpcode2["LOC_ANIM"] = 3002] = "LOC_ANIM"; - ScriptOpcode2[ScriptOpcode2["LOC_CATEGORY"] = 3003] = "LOC_CATEGORY"; - ScriptOpcode2[ScriptOpcode2["LOC_CHANGE"] = 3004] = "LOC_CHANGE"; - ScriptOpcode2[ScriptOpcode2["LOC_COORD"] = 3005] = "LOC_COORD"; - ScriptOpcode2[ScriptOpcode2["LOC_DEL"] = 3006] = "LOC_DEL"; - ScriptOpcode2[ScriptOpcode2["LOC_FIND"] = 3007] = "LOC_FIND"; - ScriptOpcode2[ScriptOpcode2["LOC_FINDALLZONE"] = 3008] = "LOC_FINDALLZONE"; - ScriptOpcode2[ScriptOpcode2["LOC_FINDNEXT"] = 3009] = "LOC_FINDNEXT"; - ScriptOpcode2[ScriptOpcode2["LOC_NAME"] = 3010] = "LOC_NAME"; - ScriptOpcode2[ScriptOpcode2["LOC_PARAM"] = 3011] = "LOC_PARAM"; - ScriptOpcode2[ScriptOpcode2["LOC_SHAPE"] = 3012] = "LOC_SHAPE"; - ScriptOpcode2[ScriptOpcode2["LOC_TYPE"] = 3013] = "LOC_TYPE"; - ScriptOpcode2[ScriptOpcode2["OBJ_ADD"] = 3500] = "OBJ_ADD"; - ScriptOpcode2[ScriptOpcode2["OBJ_ADDALL"] = 3501] = "OBJ_ADDALL"; - ScriptOpcode2[ScriptOpcode2["OBJ_COORD"] = 3502] = "OBJ_COORD"; - ScriptOpcode2[ScriptOpcode2["OBJ_COUNT"] = 3503] = "OBJ_COUNT"; - ScriptOpcode2[ScriptOpcode2["OBJ_DEL"] = 3504] = "OBJ_DEL"; - ScriptOpcode2[ScriptOpcode2["OBJ_NAME"] = 3505] = "OBJ_NAME"; - ScriptOpcode2[ScriptOpcode2["OBJ_PARAM"] = 3506] = "OBJ_PARAM"; - ScriptOpcode2[ScriptOpcode2["OBJ_TAKEITEM"] = 3507] = "OBJ_TAKEITEM"; - ScriptOpcode2[ScriptOpcode2["OBJ_TYPE"] = 3508] = "OBJ_TYPE"; - ScriptOpcode2[ScriptOpcode2["NC_CATEGORY"] = 4e3] = "NC_CATEGORY"; - ScriptOpcode2[ScriptOpcode2["NC_DEBUGNAME"] = 4001] = "NC_DEBUGNAME"; - ScriptOpcode2[ScriptOpcode2["NC_DESC"] = 4002] = "NC_DESC"; - ScriptOpcode2[ScriptOpcode2["NC_NAME"] = 4003] = "NC_NAME"; - ScriptOpcode2[ScriptOpcode2["NC_OP"] = 4004] = "NC_OP"; - ScriptOpcode2[ScriptOpcode2["NC_PARAM"] = 4005] = "NC_PARAM"; - ScriptOpcode2[ScriptOpcode2["LC_CATEGORY"] = 4100] = "LC_CATEGORY"; - ScriptOpcode2[ScriptOpcode2["LC_DEBUGNAME"] = 4101] = "LC_DEBUGNAME"; - ScriptOpcode2[ScriptOpcode2["LC_DESC"] = 4102] = "LC_DESC"; - ScriptOpcode2[ScriptOpcode2["LC_NAME"] = 4103] = "LC_NAME"; - ScriptOpcode2[ScriptOpcode2["LC_OP"] = 4104] = "LC_OP"; - ScriptOpcode2[ScriptOpcode2["LC_PARAM"] = 4105] = "LC_PARAM"; - ScriptOpcode2[ScriptOpcode2["LC_WIDTH"] = 4106] = "LC_WIDTH"; - ScriptOpcode2[ScriptOpcode2["LC_LENGTH"] = 4107] = "LC_LENGTH"; - ScriptOpcode2[ScriptOpcode2["OC_CATEGORY"] = 4200] = "OC_CATEGORY"; - ScriptOpcode2[ScriptOpcode2["OC_CERT"] = 4201] = "OC_CERT"; - ScriptOpcode2[ScriptOpcode2["OC_COST"] = 4202] = "OC_COST"; - ScriptOpcode2[ScriptOpcode2["OC_DEBUGNAME"] = 4203] = "OC_DEBUGNAME"; - ScriptOpcode2[ScriptOpcode2["OC_DESC"] = 4204] = "OC_DESC"; - ScriptOpcode2[ScriptOpcode2["OC_IOP"] = 4205] = "OC_IOP"; - ScriptOpcode2[ScriptOpcode2["OC_MEMBERS"] = 4206] = "OC_MEMBERS"; - ScriptOpcode2[ScriptOpcode2["OC_NAME"] = 4207] = "OC_NAME"; - ScriptOpcode2[ScriptOpcode2["OC_OP"] = 4208] = "OC_OP"; - ScriptOpcode2[ScriptOpcode2["OC_PARAM"] = 4209] = "OC_PARAM"; - ScriptOpcode2[ScriptOpcode2["OC_STACKABLE"] = 4210] = "OC_STACKABLE"; - ScriptOpcode2[ScriptOpcode2["OC_TRADEABLE"] = 4211] = "OC_TRADEABLE"; - ScriptOpcode2[ScriptOpcode2["OC_UNCERT"] = 4212] = "OC_UNCERT"; - ScriptOpcode2[ScriptOpcode2["OC_WEARPOS2"] = 4213] = "OC_WEARPOS2"; - ScriptOpcode2[ScriptOpcode2["OC_WEARPOS3"] = 4214] = "OC_WEARPOS3"; - ScriptOpcode2[ScriptOpcode2["OC_WEARPOS"] = 4215] = "OC_WEARPOS"; - ScriptOpcode2[ScriptOpcode2["OC_WEIGHT"] = 4216] = "OC_WEIGHT"; - ScriptOpcode2[ScriptOpcode2["INV_ALLSTOCK"] = 4300] = "INV_ALLSTOCK"; - ScriptOpcode2[ScriptOpcode2["INV_SIZE"] = 4301] = "INV_SIZE"; - ScriptOpcode2[ScriptOpcode2["INV_STOCKBASE"] = 4302] = "INV_STOCKBASE"; - ScriptOpcode2[ScriptOpcode2["INV_ADD"] = 4303] = "INV_ADD"; - ScriptOpcode2[ScriptOpcode2["INV_CHANGESLOT"] = 4304] = "INV_CHANGESLOT"; - ScriptOpcode2[ScriptOpcode2["INV_CLEAR"] = 4305] = "INV_CLEAR"; - ScriptOpcode2[ScriptOpcode2["INV_DEL"] = 4306] = "INV_DEL"; - ScriptOpcode2[ScriptOpcode2["INV_DELSLOT"] = 4307] = "INV_DELSLOT"; - ScriptOpcode2[ScriptOpcode2["INV_DROPITEM"] = 4308] = "INV_DROPITEM"; - ScriptOpcode2[ScriptOpcode2["INV_DROPSLOT"] = 4309] = "INV_DROPSLOT"; - ScriptOpcode2[ScriptOpcode2["INV_FREESPACE"] = 4310] = "INV_FREESPACE"; - ScriptOpcode2[ScriptOpcode2["INV_GETNUM"] = 4311] = "INV_GETNUM"; - ScriptOpcode2[ScriptOpcode2["INV_GETOBJ"] = 4312] = "INV_GETOBJ"; - ScriptOpcode2[ScriptOpcode2["INV_ITEMSPACE"] = 4313] = "INV_ITEMSPACE"; - ScriptOpcode2[ScriptOpcode2["INV_ITEMSPACE2"] = 4314] = "INV_ITEMSPACE2"; - ScriptOpcode2[ScriptOpcode2["INV_MOVEFROMSLOT"] = 4315] = "INV_MOVEFROMSLOT"; - ScriptOpcode2[ScriptOpcode2["INV_MOVETOSLOT"] = 4316] = "INV_MOVETOSLOT"; - ScriptOpcode2[ScriptOpcode2["BOTH_MOVEINV"] = 4317] = "BOTH_MOVEINV"; - ScriptOpcode2[ScriptOpcode2["INV_MOVEITEM"] = 4318] = "INV_MOVEITEM"; - ScriptOpcode2[ScriptOpcode2["INV_MOVEITEM_CERT"] = 4319] = "INV_MOVEITEM_CERT"; - ScriptOpcode2[ScriptOpcode2["INV_MOVEITEM_UNCERT"] = 4320] = "INV_MOVEITEM_UNCERT"; - ScriptOpcode2[ScriptOpcode2["INV_SETSLOT"] = 4321] = "INV_SETSLOT"; - ScriptOpcode2[ScriptOpcode2["INV_TOTAL"] = 4322] = "INV_TOTAL"; - ScriptOpcode2[ScriptOpcode2["INV_TOTALCAT"] = 4323] = "INV_TOTALCAT"; - ScriptOpcode2[ScriptOpcode2["INV_TRANSMIT"] = 4324] = "INV_TRANSMIT"; - ScriptOpcode2[ScriptOpcode2["INVOTHER_TRANSMIT"] = 4325] = "INVOTHER_TRANSMIT"; - ScriptOpcode2[ScriptOpcode2["INV_STOPTRANSMIT"] = 4326] = "INV_STOPTRANSMIT"; - ScriptOpcode2[ScriptOpcode2["BOTH_DROPSLOT"] = 4327] = "BOTH_DROPSLOT"; - ScriptOpcode2[ScriptOpcode2["INV_DROPALL"] = 4328] = "INV_DROPALL"; - ScriptOpcode2[ScriptOpcode2["INV_TOTALPARAM"] = 4329] = "INV_TOTALPARAM"; - ScriptOpcode2[ScriptOpcode2["INV_TOTALPARAM_STACK"] = 4330] = "INV_TOTALPARAM_STACK"; - ScriptOpcode2[ScriptOpcode2["ENUM"] = 4400] = "ENUM"; - ScriptOpcode2[ScriptOpcode2["ENUM_GETOUTPUTCOUNT"] = 4401] = "ENUM_GETOUTPUTCOUNT"; - ScriptOpcode2[ScriptOpcode2["APPEND_NUM"] = 4500] = "APPEND_NUM"; - ScriptOpcode2[ScriptOpcode2["APPEND"] = 4501] = "APPEND"; - ScriptOpcode2[ScriptOpcode2["APPEND_SIGNNUM"] = 4502] = "APPEND_SIGNNUM"; - ScriptOpcode2[ScriptOpcode2["LOWERCASE"] = 4503] = "LOWERCASE"; - ScriptOpcode2[ScriptOpcode2["TEXT_GENDER"] = 4504] = "TEXT_GENDER"; - ScriptOpcode2[ScriptOpcode2["TOSTRING"] = 4505] = "TOSTRING"; - ScriptOpcode2[ScriptOpcode2["COMPARE"] = 4506] = "COMPARE"; - ScriptOpcode2[ScriptOpcode2["TEXT_SWITCH"] = 4507] = "TEXT_SWITCH"; - ScriptOpcode2[ScriptOpcode2["APPEND_CHAR"] = 4508] = "APPEND_CHAR"; - ScriptOpcode2[ScriptOpcode2["STRING_LENGTH"] = 4509] = "STRING_LENGTH"; - ScriptOpcode2[ScriptOpcode2["SUBSTRING"] = 4510] = "SUBSTRING"; - ScriptOpcode2[ScriptOpcode2["STRING_INDEXOF_CHAR"] = 4511] = "STRING_INDEXOF_CHAR"; - ScriptOpcode2[ScriptOpcode2["STRING_INDEXOF_STRING"] = 4512] = "STRING_INDEXOF_STRING"; - ScriptOpcode2[ScriptOpcode2["ADD"] = 4600] = "ADD"; - ScriptOpcode2[ScriptOpcode2["SUB"] = 4601] = "SUB"; - ScriptOpcode2[ScriptOpcode2["MULTIPLY"] = 4602] = "MULTIPLY"; - ScriptOpcode2[ScriptOpcode2["DIVIDE"] = 4603] = "DIVIDE"; - ScriptOpcode2[ScriptOpcode2["RANDOM"] = 4604] = "RANDOM"; - ScriptOpcode2[ScriptOpcode2["RANDOMINC"] = 4605] = "RANDOMINC"; - ScriptOpcode2[ScriptOpcode2["INTERPOLATE"] = 4606] = "INTERPOLATE"; - ScriptOpcode2[ScriptOpcode2["ADDPERCENT"] = 4607] = "ADDPERCENT"; - ScriptOpcode2[ScriptOpcode2["SETBIT"] = 4608] = "SETBIT"; - ScriptOpcode2[ScriptOpcode2["CLEARBIT"] = 4609] = "CLEARBIT"; - ScriptOpcode2[ScriptOpcode2["TESTBIT"] = 4610] = "TESTBIT"; - ScriptOpcode2[ScriptOpcode2["MODULO"] = 4611] = "MODULO"; - ScriptOpcode2[ScriptOpcode2["POW"] = 4612] = "POW"; - ScriptOpcode2[ScriptOpcode2["INVPOW"] = 4613] = "INVPOW"; - ScriptOpcode2[ScriptOpcode2["AND"] = 4614] = "AND"; - ScriptOpcode2[ScriptOpcode2["OR"] = 4615] = "OR"; - ScriptOpcode2[ScriptOpcode2["MIN"] = 4616] = "MIN"; - ScriptOpcode2[ScriptOpcode2["MAX"] = 4617] = "MAX"; - ScriptOpcode2[ScriptOpcode2["SCALE"] = 4618] = "SCALE"; - ScriptOpcode2[ScriptOpcode2["BITCOUNT"] = 4619] = "BITCOUNT"; - ScriptOpcode2[ScriptOpcode2["TOGGLEBIT"] = 4620] = "TOGGLEBIT"; - ScriptOpcode2[ScriptOpcode2["SETBIT_RANGE"] = 4621] = "SETBIT_RANGE"; - ScriptOpcode2[ScriptOpcode2["CLEARBIT_RANGE"] = 4622] = "CLEARBIT_RANGE"; - ScriptOpcode2[ScriptOpcode2["GETBIT_RANGE"] = 4623] = "GETBIT_RANGE"; - ScriptOpcode2[ScriptOpcode2["SETBIT_RANGE_TOINT"] = 4624] = "SETBIT_RANGE_TOINT"; - ScriptOpcode2[ScriptOpcode2["SIN_DEG"] = 4625] = "SIN_DEG"; - ScriptOpcode2[ScriptOpcode2["COS_DEG"] = 4626] = "COS_DEG"; - ScriptOpcode2[ScriptOpcode2["ATAN2_DEG"] = 4627] = "ATAN2_DEG"; - ScriptOpcode2[ScriptOpcode2["ABS"] = 4628] = "ABS"; - ScriptOpcode2[ScriptOpcode2["DB_FIND_WITH_COUNT"] = 7500] = "DB_FIND_WITH_COUNT"; - ScriptOpcode2[ScriptOpcode2["DB_FINDNEXT"] = 7501] = "DB_FINDNEXT"; - ScriptOpcode2[ScriptOpcode2["DB_GETFIELD"] = 7502] = "DB_GETFIELD"; - ScriptOpcode2[ScriptOpcode2["DB_GETFIELDCOUNT"] = 7503] = "DB_GETFIELDCOUNT"; - ScriptOpcode2[ScriptOpcode2["DB_LISTALL_WITH_COUNT"] = 7504] = "DB_LISTALL_WITH_COUNT"; - ScriptOpcode2[ScriptOpcode2["DB_GETROWTABLE"] = 7505] = "DB_GETROWTABLE"; - ScriptOpcode2[ScriptOpcode2["DB_FINDBYINDEX"] = 7506] = "DB_FINDBYINDEX"; - ScriptOpcode2[ScriptOpcode2["DB_FIND_REFINE_WITH_COUNT"] = 7507] = "DB_FIND_REFINE_WITH_COUNT"; - ScriptOpcode2[ScriptOpcode2["DB_FIND"] = 7508] = "DB_FIND"; - ScriptOpcode2[ScriptOpcode2["DB_FIND_REFINE"] = 7509] = "DB_FIND_REFINE"; - ScriptOpcode2[ScriptOpcode2["DB_LISTALL"] = 7510] = "DB_LISTALL"; - ScriptOpcode2[ScriptOpcode2["ERROR"] = 1e4] = "ERROR"; - ScriptOpcode2[ScriptOpcode2["MAP_PRODUCTION"] = 10001] = "MAP_PRODUCTION"; - ScriptOpcode2[ScriptOpcode2["MAP_LASTCLOCK"] = 10002] = "MAP_LASTCLOCK"; - ScriptOpcode2[ScriptOpcode2["MAP_LASTWORLD"] = 10003] = "MAP_LASTWORLD"; - ScriptOpcode2[ScriptOpcode2["MAP_LASTCLIENTIN"] = 10004] = "MAP_LASTCLIENTIN"; - ScriptOpcode2[ScriptOpcode2["MAP_LASTNPC"] = 10005] = "MAP_LASTNPC"; - ScriptOpcode2[ScriptOpcode2["MAP_LASTPLAYER"] = 10006] = "MAP_LASTPLAYER"; - ScriptOpcode2[ScriptOpcode2["MAP_LASTLOGOUT"] = 10007] = "MAP_LASTLOGOUT"; - ScriptOpcode2[ScriptOpcode2["MAP_LASTLOGIN"] = 10008] = "MAP_LASTLOGIN"; - ScriptOpcode2[ScriptOpcode2["MAP_LASTZONE"] = 10009] = "MAP_LASTZONE"; - ScriptOpcode2[ScriptOpcode2["MAP_LASTCLIENTOUT"] = 10010] = "MAP_LASTCLIENTOUT"; - ScriptOpcode2[ScriptOpcode2["MAP_LASTCLEANUP"] = 10011] = "MAP_LASTCLEANUP"; - ScriptOpcode2[ScriptOpcode2["MAP_LASTBANDWIDTHIN"] = 10012] = "MAP_LASTBANDWIDTHIN"; - ScriptOpcode2[ScriptOpcode2["MAP_LASTBANDWIDTHOUT"] = 10013] = "MAP_LASTBANDWIDTHOUT"; - return ScriptOpcode2; -})(ScriptOpcode || {}); -var ScriptOpcode_default = ScriptOpcode; - -// src/lostcity/engine/script/ScriptFile.ts -function isLargeOperand(opcode) { - if (opcode > 100) { - return false; - } - switch (opcode) { - case ScriptOpcode_default.RETURN: - case ScriptOpcode_default.POP_INT_DISCARD: - case ScriptOpcode_default.POP_STRING_DISCARD: - case ScriptOpcode_default.GOSUB: - case ScriptOpcode_default.JUMP: - return false; - } - return true; -} -var ScriptFile = class _ScriptFile { - info = { - scriptName: "", - sourceFilePath: "", - lookupKey: -1, - parameterTypes: [], - pcs: [], - lines: [] - }; - id; - intLocalCount = 0; - stringLocalCount = 0; - intArgCount = 0; - stringArgCount = 0; - switchTables = []; - opcodes = []; - intOperands = []; - stringOperands = []; - // decodes the same binary format as clientscript2 - static decode(id, stream) { - const length = stream.data.length; - if (length < 16) { - throw new Error("Invalid script file (minimum length)"); - } - stream.pos = length - 2; - const trailerLen = stream.g2(); - const trailerPos = length - trailerLen - 12 - 2; - if (trailerPos < 0 || trailerPos >= length) { - throw new Error("Invalid script file (bad trailer pos)"); - } - stream.pos = trailerPos; - const script = new _ScriptFile(id); - const _instructions = stream.g4(); - script.intLocalCount = stream.g2(); - script.stringLocalCount = stream.g2(); - script.intArgCount = stream.g2(); - script.stringArgCount = stream.g2(); - const switches = stream.g1(); - for (let i = 0; i < switches; i++) { - const count = stream.g2(); - const table = []; - for (let j = 0; j < count; j++) { - const key = stream.g4(); - const offset = stream.g4(); - table[key] = offset; - } - script.switchTables[i] = table; - } - stream.pos = 0; - script.info.scriptName = stream.gjstr(0); - script.info.sourceFilePath = stream.gjstr(0); - script.info.lookupKey = stream.g4(); - const parameterTypeCount = stream.g1(); - for (let i = 0; i < parameterTypeCount; i++) { - script.info.parameterTypes.push(stream.g1()); - } - const lineNumberTableLength = stream.g2(); - for (let i = 0; i < lineNumberTableLength; i++) { - script.info.pcs.push(stream.g4()); - script.info.lines.push(stream.g4()); - } - let instr = 0; - while (trailerPos > stream.pos) { - const opcode = stream.g2(); - if (opcode === ScriptOpcode_default.PUSH_CONSTANT_STRING) { - script.stringOperands[instr] = stream.gjstr(0); - } else if (isLargeOperand(opcode)) { - script.intOperands[instr] = stream.g4(); - } else { - script.intOperands[instr] = stream.g1(); - } - script.opcodes[instr++] = opcode; - } - return script; - } - constructor(id) { - this.id = id; - } - get name() { - return this.info.scriptName; - } - get fileName() { - if (typeof self === "undefined") { - return path2.basename(this.info.sourceFilePath); - } else { - return this.info.sourceFilePath.split("/").pop()?.split("\\").pop(); - } - } - lineNumber(pc) { - for (let i = 0; i < this.info.pcs.length; i++) { - if (this.info.pcs[i] > pc) { - return this.info.lines[i - 1]; - } - } - return this.info.lines[this.info.lines.length - 1]; - } -}; - -// src/lostcity/engine/script/ScriptProvider.ts -var ScriptProvider = class _ScriptProvider { - /** - * The expected version of the script compiler that the runtime should be loading scripts from. - */ - static COMPILER_VERSION = 19; - /** - * Array of loaded scripts. - */ - static scripts = []; - /** - * Mapping of unique trigger + type/category/global key to script. - */ - static scriptLookup = /* @__PURE__ */ new Map(); - /** - * Mapping of script names to its id. - */ - static scriptNames = /* @__PURE__ */ new Map(); - /** - * Loads all scripts from `dir`. - * - * @param dir The directory that holds the script.{dat,idx} files. - * @returns The number of scripts loaded. - */ - static load(dir) { - const dat = Packet.load(`${dir}/server/script.dat`); - const idx = Packet.load(`${dir}/server/script.idx`); - return this.parse(dat, idx); - } - static async loadAsync(dir) { - const [dat, idx] = await Promise.all([Packet.loadAsync(`${dir}/server/script.dat`), Packet.loadAsync(`${dir}/server/script.idx`)]); - return this.parse(dat, idx); - } - static parse(dat, idx) { - if (!dat.data.length || !idx.data.length) { - console.log("\nFatal: No script.dat or script.idx found. Please run the server:build script."); - process.exit(1); - } - const entries = dat.g2(); - idx.pos += 2; - const version = dat.g4(); - if (version !== _ScriptProvider.COMPILER_VERSION) { - console.error("\nFatal: Scripts were compiled with an older RuneScript compiler. Please update it, try `npm run build` and then restart the server."); - process.exit(1); - } - const scripts = new Array(entries); - const scriptNames = /* @__PURE__ */ new Map(); - const scriptLookup = /* @__PURE__ */ new Map(); - let loaded = 0; - for (let id = 0; id < entries; id++) { - const size = idx.g2(); - if (size === 0) { - continue; - } - try { - const data = new Uint8Array(size); - dat.gdata(data, 0, data.length); - const script = ScriptFile.decode(id, new Packet(data)); - scripts[id] = script; - scriptNames.set(script.name, id); - if (script.info.lookupKey !== 4294967295) { - scriptLookup.set(script.info.lookupKey, script); - } - loaded++; - } catch (err) { - console.error(err); - console.error(`Warning: Failed to load script ${id}, something may have been partially written`); - return -1; - } - } - _ScriptProvider.scripts = scripts; - _ScriptProvider.scriptNames = scriptNames; - _ScriptProvider.scriptLookup = scriptLookup; - return loaded; - } - /** - * Finds a script by `id`. - * @param id The script id to find. - * @returns The script. - */ - static get(id) { - return this.scripts[id]; - } - /** - * Finds a script by `name`. - * @param name The script name to find. - * @returns The script. - */ - static getByName(name) { - const id = _ScriptProvider.scriptNames.get(name); - if (id === void 0) { - return void 0; - } - return _ScriptProvider.scripts[id]; - } - /** - * Used to look up a script by the `type` and `category`. - * - * This function will attempt to search for a script given the specific `type`, - * if one is not found it attempts one for `category`, and if still not found - * it will attempt for the global script. - * - * @param trigger The script trigger to find. - * @param type The script subject type id. - * @param category The script subject category id. - */ - static getByTrigger(trigger, type = -1, category = -1) { - let script = _ScriptProvider.scriptLookup.get(trigger | 2 << 8 | type << 10); - if (script) { - return script; - } - script = _ScriptProvider.scriptLookup.get(trigger | 1 << 8 | category << 10); - if (script) { - return script; - } - return _ScriptProvider.scriptLookup.get(trigger); - } - /** - * Used to look up a script by a specific combo. Does not attempt any other combinations. - * - * If `type` is not `-1`, only the `type` specific script will be looked up. Likewise - * for `category`. If both `type` and `category` are `-1`, then only the global script - * will be looked up. - * - * @param trigger The script trigger to find. - * @param type The script subject type id. - * @param category The script subject category id. - */ - static getByTriggerSpecific(trigger, type = -1, category = -1) { - if (type !== -1) { - return _ScriptProvider.scriptLookup.get(trigger | 2 << 8 | type << 10); - } else if (category !== -1) { - return _ScriptProvider.scriptLookup.get(trigger | 1 << 8 | category << 10); - } - return _ScriptProvider.scriptLookup.get(trigger); - } -}; - -// src/lostcity/util/Numbers.ts -var MASK = initMaskArray(); -function toInt32(num) { - return num | 0; -} -function bitcount(num) { - num = num - (num >> 1 & 1431655765); - num = (num & 858993459) + (num >> 2 & 858993459); - return (num + (num >> 4) & 252645135) * 16843009 >> 24; -} -function setBitRange(num, startBit, endBit) { - const mask = MASK[endBit - startBit + 1]; - return num | mask << startBit; -} -function clearBitRange(num, startBit, endBit) { - const mask = MASK[endBit - startBit + 1]; - return num & ~(mask << startBit); -} -function initMaskArray() { - const data = [0]; - let incrementor = 2; - for (let i = 1; i < 33; ++i) { - data[i] = toInt32(incrementor - 1); - incrementor += incrementor; - } - return data; -} - -// src/lostcity/engine/script/ScriptState.ts -var ScriptState = class _ScriptState { - static ABORTED = -1; - static RUNNING = 0; - static FINISHED = 1; - static SUSPENDED = 2; - // suspended to move to player - static PAUSEBUTTON = 3; - static COUNTDIALOG = 4; - static NPC_SUSPENDED = 5; - // suspended to move to npc - static WORLD_SUSPENDED = 6; - // suspended to move to world - // interpreter - script; - trigger; - execution = _ScriptState.RUNNING; - executionHistory = []; - pc = -1; - // program counter - opcount = 0; - // number of opcodes executed - frames = []; - fp = 0; - // frame pointer - debugFrames = []; - debugFp = 0; - intStack = []; - isp = 0; - // int stack pointer - stringStack = []; - ssp = 0; - // string stack pointer - intLocals = []; - stringLocals = []; - /** - * Contains flags representing `ScriptPointer`s. - */ - pointers = 0; - // server - /** - * The primary entity. - */ - self = null; - // active entities - /** - * The primary active player. - */ - _activePlayer = null; - /** - * The secondary active player. - * @type {Player|null} - */ - _activePlayer2 = null; - /** - * The primary active npc. - */ - _activeNpc = null; - /** - * The secondary active npc. - */ - _activeNpc2 = null; - /** - * The primary active loc. - */ - _activeLoc = null; - /** - * The secondary active loc. - */ - _activeLoc2 = null; - _activeObj = null; - _activeObj2 = null; - /** - * Used for string splitting operations with split_init and related commands. - */ - splitPages = []; - splitMesanim = -1; - /** - * Used for db operations with db_find and related commands - */ - dbTable = null; - dbColumn = -1; - dbRow = -1; - dbRowQuery = []; - huntIterator = null; - npcIterator = null; - locIterator = null; - lastInt = 0; - constructor(script, args = []) { - this.script = script; - this.trigger = script.info.lookupKey & 255; - if (args) { - for (let i = 0; i < args.length; i++) { - const arg = args[i]; - if (typeof arg === "number") { - this.intLocals.push(arg); - } else { - this.stringLocals.push(arg); - } - } - } - } - /** - * Sets pointers to only the ones supplied. - * - * @param pointers The pointers to set. - */ - pointerSet(...pointers) { - this.pointers = 0; - for (let i = 0; i < pointers.length; i++) { - this.pointers |= 1 << pointers[i]; - } - } - /** - * Adds `pointer` to the state. - * - * @param pointer The pointer to add. - */ - pointerAdd(pointer) { - this.pointers |= 1 << pointer; - } - /** - * Removes `pointer` from the state. - * - * @param pointer The point to remove. - */ - pointerRemove(pointer) { - this.pointers &= ~(1 << pointer); - } - pointerGet(pointer) { - return (this.pointers & 1 << pointer) != 0; - } - /** - * Verifies all `pointers` are enabled. - * - * @param pointers The pointers to check for. - */ - pointerCheck(...pointers) { - for (let i = 0; i < pointers.length; i++) { - const flag = 1 << pointers[i]; - if ((this.pointers & flag) != flag) { - throw new Error(`Required pointer: ${_ScriptState.pointerPrint(flag)}, current: ${_ScriptState.pointerPrint(this.pointers)}`); - } - } - } - /** - * Pretty prints all enables flags using the names from `ScriptPointer`. - * - * @param flags The flags to print. - */ - static pointerPrint(flags) { - let text = ""; - for (let i = 0; i < ScriptPointer_default._LAST; i++) { - if ((flags & 1 << i) != 0) { - text += `${ScriptPointer_default[i]}, `; - } - } - return text.substring(0, text.lastIndexOf(",")); - } - /** - * Gets the active player. Automatically checks the operand to determine primary and secondary. - */ - get activePlayer() { - const player = this.intOperand === 0 ? this._activePlayer : this._activePlayer2; - if (player === null) { - throw new Error("Attempt to access null active_player"); - } - return player; - } - /** - * Sets the active player. Automatically checks the operand to determine primary and secondary. - * @param player The player to set. - */ - set activePlayer(player) { - if (this.intOperand === 0) { - this._activePlayer = player; - } else { - this._activePlayer2 = player; - } - } - /** - * Gets the active npc. Automatically checks the operand to determine primary and secondary. - */ - get activeNpc() { - const npc = this.intOperand === 0 ? this._activeNpc : this._activeNpc2; - if (npc === null) { - throw new Error("Attempt to access null active_npc"); - } - return npc; - } - /** - * Sets the active npc. Automatically checks the operand to determine primary and secondary. - * @param npc The npc to set. - */ - set activeNpc(npc) { - if (this.intOperand === 0) { - this._activeNpc = npc; - } else { - this._activeNpc2 = npc; - } - } - /** - * Gets the active location. Automatically checks the operand to determine primary and secondary. - */ - get activeLoc() { - const loc = this.intOperand === 0 ? this._activeLoc : this._activeLoc2; - if (loc === null) { - throw new Error("Attempt to access null active_loc"); - } - return loc; - } - /** - * Sets the active loc. Automatically checks the operand to determine primary and secondary. - * @param loc The loc to set. - */ - set activeLoc(loc) { - if (this.intOperand === 0) { - this._activeLoc = loc; - } else { - this._activeLoc2 = loc; - } - } - get activeObj() { - const obj = this.intOperand === 0 ? this._activeObj : this._activeObj2; - if (obj === null) { - throw new Error("Attempt to access null active_obj"); - } - return obj; - } - /** - * Sets the active obj. Automatically checks the operand to determine primary and secondary. - * @param obj The obj to set. - */ - set activeObj(obj) { - if (this.intOperand === 0) { - this._activeObj = obj; - } else { - this._activeObj2 = obj; - } - } - get intOperand() { - return this.script.intOperands[this.pc]; - } - get stringOperand() { - return this.script.stringOperands[this.pc]; - } - popInt() { - const value = this.intStack[--this.isp]; - if (!value) { - return 0; - } - return toInt32(value); - } - popInts(amount) { - const ints = Array(amount); - for (let i = amount - 1; i >= 0; i--) { - ints[i] = this.popInt(); - } - return ints; - } - pushInt(value) { - this.intStack[this.isp++] = toInt32(value); - } - popString() { - return this.stringStack[--this.ssp] ?? ""; - } - popStrings(amount) { - const strings = Array(amount); - for (let i = amount - 1; i >= 0; i--) { - strings[i] = this.popString(); - } - return strings; - } - pushString(value) { - this.stringStack[this.ssp++] = value; - } - reset() { - this.pc = -1; - this.frames = []; - this.fp = 0; - this.intStack = []; - this.isp = 0; - this.stringStack = []; - this.ssp = 0; - this.intLocals = []; - this.stringLocals = []; - this.pointers = 0; - } -}; - -// src/lostcity/engine/Inventory.ts -var InventoryTransaction = class { - requested = 0; - completed = 0; - items = []; - constructor(requested, completed = 0, items = []) { - this.requested = requested; - this.completed = completed; - this.items = items; - } - getLeftOver() { - return this.requested - this.completed; - } - hasSucceeded() { - return this.completed == this.requested; - } - hasFailed() { - return !this.hasSucceeded(); - } - revert(from) { - for (let i = 0; i < this.items.length; i++) { - const item = this.items[i].item; - from.remove(item.id, item.count, this.items[i].slot); - } - } -}; -var Inventory = class _Inventory { - static STACK_LIMIT = 2147483647; - static NORMAL_STACK = 0; - static ALWAYS_STACK = 1; - static NEVER_STACK = 2; - static fromType(inv) { - if (inv === -1) { - throw new Error("Invalid inventory type"); - } - const type = InvType.get(inv); - let stackType = _Inventory.NORMAL_STACK; - if (type.stackall) { - stackType = _Inventory.ALWAYS_STACK; - } - const container = new _Inventory(inv, type.size, stackType); - if (type.stockobj && type.stockcount && type.stockobj.length) { - for (let i = 0; i < type.stockobj.length; i++) { - container.set(i, { - id: type.stockobj[i], - count: type.stockcount[i] - }); - } - } - return container; - } - // 0 - stack based on item - // 1 - always stack - // 2 - never stack - stackType; - capacity; - type; - // inv ID - items; - update = false; - constructor(type, capacity, stackType = _Inventory.NORMAL_STACK) { - this.type = type; - this.capacity = capacity; - this.stackType = stackType; - this.items = new Array(capacity).fill(null); - } - contains(id) { - return this.items.some((item) => item && item.id == id); - } - hasAt(slot, id) { - const item = this.items[slot]; - return item && item.id == id; - } - get nextFreeSlot() { - return this.items.indexOf(null, 0); - } - get freeSlotCount() { - return this.items.filter((item) => item == null).length; - } - get occupiedSlotCount() { - return this.items.filter((item) => item != null).length; - } - get isFull() { - return this.occupiedSlotCount == this.capacity; - } - get isEmpty() { - return this.occupiedSlotCount == 0; - } - get hasAny() { - return this.items.some((item) => item != null); - } - get hasSpace() { - return this.nextFreeSlot != -1; - } - get itemsFiltered() { - return this.items.filter((item) => item != null); - } - getItemCount(id) { - let count = 0; - for (let i = 0; i < this.capacity; i++) { - const item = this.items[i]; - if (item && item.id == id) { - count += item.count; - } - } - return Math.min(_Inventory.STACK_LIMIT, count); - } - getItemIndex(id) { - return this.items.findIndex((item) => item && item.id == id); - } - removeAll() { - this.items.fill(null, 0, this.capacity); - this.update = true; - } - add(id, count = 1, beginSlot = -1, assureFullInsertion = true, forceNoStack = false, dryRun = false) { - const type = ObjType.get(id); - const stockObj = InvType.get(this.type).stockobj?.includes(id) === true; - const stack = !forceNoStack && this.stackType != _Inventory.NEVER_STACK && (type.stackable || this.stackType == _Inventory.ALWAYS_STACK); - let previousCount = 0; - if (stack) { - previousCount = this.getItemCount(id); - } - if (previousCount == _Inventory.STACK_LIMIT) { - return new InventoryTransaction(count, 0, []); - } - const freeSlotCount = this.freeSlotCount; - if (freeSlotCount == 0 && (!stack || stack && previousCount == 0 && !stockObj)) { - return new InventoryTransaction(count, 0, []); - } - if (assureFullInsertion) { - if (stack && previousCount > _Inventory.STACK_LIMIT - count) { - return new InventoryTransaction(count, 0, []); - } - if (!stack && count > freeSlotCount) { - return new InventoryTransaction(count, 0, []); - } - } else { - if (stack && previousCount == _Inventory.STACK_LIMIT) { - return new InventoryTransaction(count, 0, []); - } else if (!stack && freeSlotCount == 0) { - return new InventoryTransaction(count, 0, []); - } - } - let completed = 0; - const added = []; - if (!stack) { - const startSlot = Math.max(0, beginSlot); - for (let i = startSlot; i < this.capacity; i++) { - if (this.items[i] != null) { - continue; - } - const add = { id, count: 1 }; - if (!dryRun) { - this.set(i, add); - } - added.push({ slot: i, item: add }); - if (++completed >= count) { - break; - } - } - } else { - let stackIndex = this.getItemIndex(id); - if (stackIndex == -1) { - if (beginSlot == -1) { - stackIndex = this.nextFreeSlot; - } else { - stackIndex = this.items.indexOf(null, beginSlot); - } - if (stackIndex == -1) { - return new InventoryTransaction(count, completed, []); - } - } - const stackCount = this.get(stackIndex)?.count ?? 0; - const total = Math.min(_Inventory.STACK_LIMIT, stackCount + count); - const add = { id, count: total }; - if (!dryRun) { - this.set(stackIndex, add); - } - added.push({ slot: stackIndex, item: add }); - completed = total - stackCount; - } - return new InventoryTransaction(count, completed, added); - } - remove(id, count = 1, beginSlot = -1, assureFullRemoval = false) { - const hasCount = this.getItemCount(id); - const stockObj = InvType.get(this.type).stockobj?.includes(id) === true; - if (assureFullRemoval && hasCount < count) { - return new InventoryTransaction(count, 0, []); - } else if (!assureFullRemoval && hasCount < 1) { - return new InventoryTransaction(count, 0, []); - } - let totalRemoved = 0; - const removed = []; - let skippedIndices = null; - if (beginSlot != -1) { - skippedIndices = []; - for (let i = 0; i < beginSlot; i++) { - skippedIndices.push(i); - } - } - let index = 0; - if (beginSlot != -1) { - index = beginSlot; - } - for (let i = index; i < this.capacity; i++) { - const curItem = this.items[i]; - if (!curItem || curItem.id != id) { - continue; - } - const removeCount = Math.min(curItem.count, count - totalRemoved); - totalRemoved += removeCount; - curItem.count -= removeCount; - if (curItem.count == 0 && !stockObj) { - const removedItem = this.items[i]; - this.items[i] = null; - if (removedItem) { - removed.push({ slot: i, item: removedItem }); - } - } - if (totalRemoved >= count) { - break; - } - } - if (skippedIndices != null && totalRemoved < count) { - for (let i = 0; i < skippedIndices.length; i++) { - const curItem = this.items[i]; - if (!curItem || curItem.id != id) { - continue; - } - const removeCount = Math.min(curItem.count, count - totalRemoved); - totalRemoved += removeCount; - curItem.count -= removeCount; - if (curItem.count == 0 && !stockObj) { - const removedItem = this.items[i]; - this.items[i] = null; - if (removedItem) { - removed.push({ slot: i, item: removedItem }); - } - } - if (totalRemoved >= count) { - break; - } - } - } - if (totalRemoved > 0) { - this.update = true; - } - return new InventoryTransaction(count, totalRemoved, removed); - } - delete(slot) { - this.items[slot] = null; - this.update = true; - } - swap(from, to) { - const temp = this.items[from]; - this.set(from, this.items[to]); - this.set(to, temp); - } - // REVIEW: This method isn't used anywhere - shift() { - this.items.sort((a, b) => { - if (a === null || b === null) { - return +(a === null) - +(b === null); - } else { - return +(a > b) || -(a < b); - } - }); - this.update = true; - } - get(slot) { - return this.items[slot]; - } - set(slot, item) { - this.items[slot] = item; - this.update = true; - } - validSlot(slot) { - return slot >= 0 && slot < this.capacity; - } - transfer(to, item, fromSlot = -1, toSlot = -1, note = false, unnote = false) { - if (item.count <= 0) { - return null; - } - const count = Math.min(item.count, this.getItemCount(item.id)); - const objType = ObjType.get(item.id); - let finalItem = { id: item.id, count }; - if (note && objType.certlink !== -1 && objType.certtemplate === -1) { - finalItem = { id: objType.certlink, count }; - } else if (unnote && objType.certlink !== -1 && objType.certtemplate >= 0) { - finalItem = { id: objType.certlink, count }; - } - const add = to.add(finalItem.id, finalItem.count, toSlot, false); - if (add.completed == 0) { - return null; - } - const remove = this.remove(item.id, add.completed, fromSlot, false); - if (remove.completed == 0) { - return null; - } - return remove; - } -}; - -// node_modules/@2004scape/rsmod-pathfinder/dist/rsmod-pathfinder.js -async function instantiate(module, imports = {}) { - const adaptedImports = { - env: Object.assign(Object.create(globalThis), imports.env || {}, { - abort(message, fileName, lineNumber, columnNumber) { - message = __liftString(message >>> 0); - fileName = __liftString(fileName >>> 0); - lineNumber = lineNumber >>> 0; - columnNumber = columnNumber >>> 0; - (() => { - throw Error(`${message} in ${fileName}:${lineNumber}:${columnNumber}`); - })(); - }, - seed() { - return (() => { - return Date.now() * Math.random(); - })(); - } - }) - }; - const { exports } = await WebAssembly.instantiate(module, adaptedImports); - const memory2 = exports.memory || imports.env.memory; - const adaptedExports = Object.setPrototypeOf({ - findPath(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, shape, moveNear, blockAccessFlags, maxWaypoints, collision) { - moveNear = moveNear ? 1 : 0; - exports.__setArgumentsLength(arguments.length); - return __liftStaticArray(__getI32, 2, exports.findPath(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, shape, moveNear, blockAccessFlags, maxWaypoints, collision) >>> 0); - }, - findNaivePath(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, blockAccessFlags, collision) { - exports.__setArgumentsLength(arguments.length); - return __liftStaticArray(__getI32, 2, exports.findNaivePath(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, blockAccessFlags, collision) >>> 0); - }, - changeFloor(x, z, level, add) { - add = add ? 1 : 0; - exports.changeFloor(x, z, level, add); - }, - changeLoc(x, z, level, width, length, blockrange, breakroutefinding, add) { - blockrange = blockrange ? 1 : 0; - breakroutefinding = breakroutefinding ? 1 : 0; - add = add ? 1 : 0; - exports.changeLoc(x, z, level, width, length, blockrange, breakroutefinding, add); - }, - changeNpc(x, z, level, size, add) { - add = add ? 1 : 0; - exports.changeNpc(x, z, level, size, add); - }, - changePlayer(x, z, level, size, add) { - add = add ? 1 : 0; - exports.changePlayer(x, z, level, size, add); - }, - changeRoof(x, z, level, add) { - add = add ? 1 : 0; - exports.changeRoof(x, z, level, add); - }, - changeWall(x, z, level, angle, shape, blockrange, breakroutefinding, add) { - blockrange = blockrange ? 1 : 0; - breakroutefinding = breakroutefinding ? 1 : 0; - add = add ? 1 : 0; - exports.changeWall(x, z, level, angle, shape, blockrange, breakroutefinding, add); - }, - allocateIfAbsent(absoluteX, absoluteZ, level) { - return __liftStaticArray(__getI32, 2, exports.allocateIfAbsent(absoluteX, absoluteZ, level) >>> 0); - }, - isZoneAllocated(absoluteX, absoluteZ, level) { - return exports.isZoneAllocated(absoluteX, absoluteZ, level) != 0; - }, - isFlagged(x, z, level, masks) { - return exports.isFlagged(x, z, level, masks) != 0; - }, - canTravel(level, x, z, offsetX, offsetZ, size, extraFlag, collision) { - exports.__setArgumentsLength(arguments.length); - return exports.canTravel(level, x, z, offsetX, offsetZ, size, extraFlag, collision) != 0; - }, - hasLineOfSight(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) { - exports.__setArgumentsLength(arguments.length); - return exports.hasLineOfSight(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) != 0; - }, - hasLineOfWalk(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) { - exports.__setArgumentsLength(arguments.length); - return exports.hasLineOfWalk(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) != 0; - }, - lineOfSight(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) { - exports.__setArgumentsLength(arguments.length); - return __liftStaticArray(__getI32, 2, exports.lineOfSight(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) >>> 0); - }, - lineOfWalk(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) { - exports.__setArgumentsLength(arguments.length); - return __liftStaticArray(__getI32, 2, exports.lineOfWalk(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, extraFlag) >>> 0); - }, - reached(level, srcX, srcZ, destX, destZ, destWidth, destHeight, srcSize, angle, shape, blockAccessFlags) { - exports.__setArgumentsLength(arguments.length); - return exports.reached(level, srcX, srcZ, destX, destZ, destWidth, destHeight, srcSize, angle, shape, blockAccessFlags) != 0; - }, - __collides(srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight) { - return exports.__collides(srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight) != 0; - }, - __reachRectangle1(level, srcX, srcZ, destX, destZ, destWidth, destHeight, blockAccessFlags) { - return exports.__reachRectangle1(level, srcX, srcZ, destX, destZ, destWidth, destHeight, blockAccessFlags) != 0; - }, - __reachRectangleN(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, blockAccessFlags) { - return exports.__reachRectangleN(level, srcX, srcZ, destX, destZ, srcWidth, srcHeight, destWidth, destHeight, blockAccessFlags) != 0; - }, - __reachRectangle(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, blockAccessFlags) { - return exports.__reachRectangle(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, blockAccessFlags) != 0; - }, - __reachExclusiveRectangle(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, blockAccessFlags) { - return exports.__reachExclusiveRectangle(level, srcX, srcZ, destX, destZ, srcSize, destWidth, destHeight, angle, blockAccessFlags) != 0; - }, - CollisionFlag: ((values) => ( - // src/rsmod/flag/CollisionFlag/CollisionFlag - (values[values.NULL = exports["CollisionFlag.NULL"].valueOf()] = "NULL", values[values.OPEN = exports["CollisionFlag.OPEN"].valueOf()] = "OPEN", values[values.WALL_NORTH_WEST = exports["CollisionFlag.WALL_NORTH_WEST"].valueOf()] = "WALL_NORTH_WEST", values[values.WALL_NORTH = exports["CollisionFlag.WALL_NORTH"].valueOf()] = "WALL_NORTH", values[values.WALL_NORTH_EAST = exports["CollisionFlag.WALL_NORTH_EAST"].valueOf()] = "WALL_NORTH_EAST", values[values.WALL_EAST = exports["CollisionFlag.WALL_EAST"].valueOf()] = "WALL_EAST", values[values.WALL_SOUTH_EAST = exports["CollisionFlag.WALL_SOUTH_EAST"].valueOf()] = "WALL_SOUTH_EAST", values[values.WALL_SOUTH = exports["CollisionFlag.WALL_SOUTH"].valueOf()] = "WALL_SOUTH", values[values.WALL_SOUTH_WEST = exports["CollisionFlag.WALL_SOUTH_WEST"].valueOf()] = "WALL_SOUTH_WEST", values[values.WALL_WEST = exports["CollisionFlag.WALL_WEST"].valueOf()] = "WALL_WEST", values[values.LOC = exports["CollisionFlag.LOC"].valueOf()] = "LOC", values[values.WALL_NORTH_WEST_PROJ_BLOCKER = exports["CollisionFlag.WALL_NORTH_WEST_PROJ_BLOCKER"].valueOf()] = "WALL_NORTH_WEST_PROJ_BLOCKER", values[values.WALL_NORTH_PROJ_BLOCKER = exports["CollisionFlag.WALL_NORTH_PROJ_BLOCKER"].valueOf()] = "WALL_NORTH_PROJ_BLOCKER", values[values.WALL_NORTH_EAST_PROJ_BLOCKER = exports["CollisionFlag.WALL_NORTH_EAST_PROJ_BLOCKER"].valueOf()] = "WALL_NORTH_EAST_PROJ_BLOCKER", values[values.WALL_EAST_PROJ_BLOCKER = exports["CollisionFlag.WALL_EAST_PROJ_BLOCKER"].valueOf()] = "WALL_EAST_PROJ_BLOCKER", values[values.WALL_SOUTH_EAST_PROJ_BLOCKER = exports["CollisionFlag.WALL_SOUTH_EAST_PROJ_BLOCKER"].valueOf()] = "WALL_SOUTH_EAST_PROJ_BLOCKER", values[values.WALL_SOUTH_PROJ_BLOCKER = exports["CollisionFlag.WALL_SOUTH_PROJ_BLOCKER"].valueOf()] = "WALL_SOUTH_PROJ_BLOCKER", values[values.WALL_SOUTH_WEST_PROJ_BLOCKER = exports["CollisionFlag.WALL_SOUTH_WEST_PROJ_BLOCKER"].valueOf()] = "WALL_SOUTH_WEST_PROJ_BLOCKER", values[values.WALL_WEST_PROJ_BLOCKER = exports["CollisionFlag.WALL_WEST_PROJ_BLOCKER"].valueOf()] = "WALL_WEST_PROJ_BLOCKER", values[values.LOC_PROJ_BLOCKER = exports["CollisionFlag.LOC_PROJ_BLOCKER"].valueOf()] = "LOC_PROJ_BLOCKER", values[values.FLOOR_DECORATION = exports["CollisionFlag.FLOOR_DECORATION"].valueOf()] = "FLOOR_DECORATION", values[values.NPC = exports["CollisionFlag.NPC"].valueOf()] = "NPC", values[values.PLAYER = exports["CollisionFlag.PLAYER"].valueOf()] = "PLAYER", values[values.FLOOR = exports["CollisionFlag.FLOOR"].valueOf()] = "FLOOR", values[values.WALL_NORTH_WEST_ROUTE_BLOCKER = exports["CollisionFlag.WALL_NORTH_WEST_ROUTE_BLOCKER"].valueOf()] = "WALL_NORTH_WEST_ROUTE_BLOCKER", values[values.WALL_NORTH_ROUTE_BLOCKER = exports["CollisionFlag.WALL_NORTH_ROUTE_BLOCKER"].valueOf()] = "WALL_NORTH_ROUTE_BLOCKER", values[values.WALL_NORTH_EAST_ROUTE_BLOCKER = exports["CollisionFlag.WALL_NORTH_EAST_ROUTE_BLOCKER"].valueOf()] = "WALL_NORTH_EAST_ROUTE_BLOCKER", values[values.WALL_EAST_ROUTE_BLOCKER = exports["CollisionFlag.WALL_EAST_ROUTE_BLOCKER"].valueOf()] = "WALL_EAST_ROUTE_BLOCKER", values[values.WALL_SOUTH_EAST_ROUTE_BLOCKER = exports["CollisionFlag.WALL_SOUTH_EAST_ROUTE_BLOCKER"].valueOf()] = "WALL_SOUTH_EAST_ROUTE_BLOCKER", values[values.WALL_SOUTH_ROUTE_BLOCKER = exports["CollisionFlag.WALL_SOUTH_ROUTE_BLOCKER"].valueOf()] = "WALL_SOUTH_ROUTE_BLOCKER", values[values.WALL_SOUTH_WEST_ROUTE_BLOCKER = exports["CollisionFlag.WALL_SOUTH_WEST_ROUTE_BLOCKER"].valueOf()] = "WALL_SOUTH_WEST_ROUTE_BLOCKER", values[values.WALL_WEST_ROUTE_BLOCKER = exports["CollisionFlag.WALL_WEST_ROUTE_BLOCKER"].valueOf()] = "WALL_WEST_ROUTE_BLOCKER", values[values.LOC_ROUTE_BLOCKER = exports["CollisionFlag.LOC_ROUTE_BLOCKER"].valueOf()] = "LOC_ROUTE_BLOCKER", values[values.ROOF = exports["CollisionFlag.ROOF"].valueOf()] = "ROOF", values[values.FLOOR_BLOCKED = exports["CollisionFlag.FLOOR_BLOCKED"].valueOf()] = "FLOOR_BLOCKED", values[values.WALK_BLOCKED = exports["CollisionFlag.WALK_BLOCKED"].valueOf()] = "WALK_BLOCKED", values[values.BLOCK_WEST = exports["CollisionFlag.BLOCK_WEST"].valueOf()] = "BLOCK_WEST", values[values.BLOCK_EAST = exports["CollisionFlag.BLOCK_EAST"].valueOf()] = "BLOCK_EAST", values[values.BLOCK_SOUTH = exports["CollisionFlag.BLOCK_SOUTH"].valueOf()] = "BLOCK_SOUTH", values[values.BLOCK_NORTH = exports["CollisionFlag.BLOCK_NORTH"].valueOf()] = "BLOCK_NORTH", values[values.BLOCK_SOUTH_WEST = exports["CollisionFlag.BLOCK_SOUTH_WEST"].valueOf()] = "BLOCK_SOUTH_WEST", values[values.BLOCK_SOUTH_EAST = exports["CollisionFlag.BLOCK_SOUTH_EAST"].valueOf()] = "BLOCK_SOUTH_EAST", values[values.BLOCK_NORTH_WEST = exports["CollisionFlag.BLOCK_NORTH_WEST"].valueOf()] = "BLOCK_NORTH_WEST", values[values.BLOCK_NORTH_EAST = exports["CollisionFlag.BLOCK_NORTH_EAST"].valueOf()] = "BLOCK_NORTH_EAST", values[values.BLOCK_NORTH_AND_SOUTH_EAST = exports["CollisionFlag.BLOCK_NORTH_AND_SOUTH_EAST"].valueOf()] = "BLOCK_NORTH_AND_SOUTH_EAST", values[values.BLOCK_NORTH_AND_SOUTH_WEST = exports["CollisionFlag.BLOCK_NORTH_AND_SOUTH_WEST"].valueOf()] = "BLOCK_NORTH_AND_SOUTH_WEST", values[values.BLOCK_NORTH_EAST_AND_WEST = exports["CollisionFlag.BLOCK_NORTH_EAST_AND_WEST"].valueOf()] = "BLOCK_NORTH_EAST_AND_WEST", values[values.BLOCK_SOUTH_EAST_AND_WEST = exports["CollisionFlag.BLOCK_SOUTH_EAST_AND_WEST"].valueOf()] = "BLOCK_SOUTH_EAST_AND_WEST", values[values.BLOCK_WEST_ROUTE_BLOCKER = exports["CollisionFlag.BLOCK_WEST_ROUTE_BLOCKER"].valueOf()] = "BLOCK_WEST_ROUTE_BLOCKER", values[values.BLOCK_EAST_ROUTE_BLOCKER = exports["CollisionFlag.BLOCK_EAST_ROUTE_BLOCKER"].valueOf()] = "BLOCK_EAST_ROUTE_BLOCKER", values[values.BLOCK_SOUTH_ROUTE_BLOCKER = exports["CollisionFlag.BLOCK_SOUTH_ROUTE_BLOCKER"].valueOf()] = "BLOCK_SOUTH_ROUTE_BLOCKER", values[values.BLOCK_NORTH_ROUTE_BLOCKER = exports["CollisionFlag.BLOCK_NORTH_ROUTE_BLOCKER"].valueOf()] = "BLOCK_NORTH_ROUTE_BLOCKER", values[values.BLOCK_SOUTH_WEST_ROUTE_BLOCKER = exports["CollisionFlag.BLOCK_SOUTH_WEST_ROUTE_BLOCKER"].valueOf()] = "BLOCK_SOUTH_WEST_ROUTE_BLOCKER", values[values.BLOCK_SOUTH_EAST_ROUTE_BLOCKER = exports["CollisionFlag.BLOCK_SOUTH_EAST_ROUTE_BLOCKER"].valueOf()] = "BLOCK_SOUTH_EAST_ROUTE_BLOCKER", values[values.BLOCK_NORTH_WEST_ROUTE_BLOCKER = exports["CollisionFlag.BLOCK_NORTH_WEST_ROUTE_BLOCKER"].valueOf()] = "BLOCK_NORTH_WEST_ROUTE_BLOCKER", values[values.BLOCK_NORTH_EAST_ROUTE_BLOCKER = exports["CollisionFlag.BLOCK_NORTH_EAST_ROUTE_BLOCKER"].valueOf()] = "BLOCK_NORTH_EAST_ROUTE_BLOCKER", values[values.BLOCK_NORTH_AND_SOUTH_EAST_ROUTE_BLOCKER = exports["CollisionFlag.BLOCK_NORTH_AND_SOUTH_EAST_ROUTE_BLOCKER"].valueOf()] = "BLOCK_NORTH_AND_SOUTH_EAST_ROUTE_BLOCKER", values[values.BLOCK_NORTH_AND_SOUTH_WEST_ROUTE_BLOCKER = exports["CollisionFlag.BLOCK_NORTH_AND_SOUTH_WEST_ROUTE_BLOCKER"].valueOf()] = "BLOCK_NORTH_AND_SOUTH_WEST_ROUTE_BLOCKER", values[values.BLOCK_NORTH_EAST_AND_WEST_ROUTE_BLOCKER = exports["CollisionFlag.BLOCK_NORTH_EAST_AND_WEST_ROUTE_BLOCKER"].valueOf()] = "BLOCK_NORTH_EAST_AND_WEST_ROUTE_BLOCKER", values[values.BLOCK_SOUTH_EAST_AND_WEST_ROUTE_BLOCKER = exports["CollisionFlag.BLOCK_SOUTH_EAST_AND_WEST_ROUTE_BLOCKER"].valueOf()] = "BLOCK_SOUTH_EAST_AND_WEST_ROUTE_BLOCKER", values) - ))({}), - LocShape: ((values) => ( - // src/rsmod/LocShape/LocShape - (values[values.WALL_STRAIGHT = exports["LocShape.WALL_STRAIGHT"].valueOf()] = "WALL_STRAIGHT", values[values.WALL_DIAGONAL_CORNER = exports["LocShape.WALL_DIAGONAL_CORNER"].valueOf()] = "WALL_DIAGONAL_CORNER", values[values.WALL_L = exports["LocShape.WALL_L"].valueOf()] = "WALL_L", values[values.WALL_SQUARE_CORNER = exports["LocShape.WALL_SQUARE_CORNER"].valueOf()] = "WALL_SQUARE_CORNER", values[values.WALLDECOR_STRAIGHT_NOOFFSET = exports["LocShape.WALLDECOR_STRAIGHT_NOOFFSET"].valueOf()] = "WALLDECOR_STRAIGHT_NOOFFSET", values[values.WALLDECOR_STRAIGHT_OFFSET = exports["LocShape.WALLDECOR_STRAIGHT_OFFSET"].valueOf()] = "WALLDECOR_STRAIGHT_OFFSET", values[values.WALLDECOR_DIAGONAL_OFFSET = exports["LocShape.WALLDECOR_DIAGONAL_OFFSET"].valueOf()] = "WALLDECOR_DIAGONAL_OFFSET", values[values.WALLDECOR_DIAGONAL_NOOFFSET = exports["LocShape.WALLDECOR_DIAGONAL_NOOFFSET"].valueOf()] = "WALLDECOR_DIAGONAL_NOOFFSET", values[values.WALLDECOR_DIAGONAL_BOTH = exports["LocShape.WALLDECOR_DIAGONAL_BOTH"].valueOf()] = "WALLDECOR_DIAGONAL_BOTH", values[values.WALL_DIAGONAL = exports["LocShape.WALL_DIAGONAL"].valueOf()] = "WALL_DIAGONAL", values[values.CENTREPIECE_STRAIGHT = exports["LocShape.CENTREPIECE_STRAIGHT"].valueOf()] = "CENTREPIECE_STRAIGHT", values[values.CENTREPIECE_DIAGONAL = exports["LocShape.CENTREPIECE_DIAGONAL"].valueOf()] = "CENTREPIECE_DIAGONAL", values[values.ROOF_STRAIGHT = exports["LocShape.ROOF_STRAIGHT"].valueOf()] = "ROOF_STRAIGHT", values[values.ROOF_DIAGONAL_WITH_ROOFEDGE = exports["LocShape.ROOF_DIAGONAL_WITH_ROOFEDGE"].valueOf()] = "ROOF_DIAGONAL_WITH_ROOFEDGE", values[values.ROOF_DIAGONAL = exports["LocShape.ROOF_DIAGONAL"].valueOf()] = "ROOF_DIAGONAL", values[values.ROOF_L_CONCAVE = exports["LocShape.ROOF_L_CONCAVE"].valueOf()] = "ROOF_L_CONCAVE", values[values.ROOF_L_CONVEX = exports["LocShape.ROOF_L_CONVEX"].valueOf()] = "ROOF_L_CONVEX", values[values.ROOF_FLAT = exports["LocShape.ROOF_FLAT"].valueOf()] = "ROOF_FLAT", values[values.ROOFEDGE_STRAIGHT = exports["LocShape.ROOFEDGE_STRAIGHT"].valueOf()] = "ROOFEDGE_STRAIGHT", values[values.ROOFEDGE_DIAGONAL_CORNER = exports["LocShape.ROOFEDGE_DIAGONAL_CORNER"].valueOf()] = "ROOFEDGE_DIAGONAL_CORNER", values[values.ROOFEDGE_L = exports["LocShape.ROOFEDGE_L"].valueOf()] = "ROOFEDGE_L", values[values.ROOFEDGE_SQUARE_CORNER = exports["LocShape.ROOFEDGE_SQUARE_CORNER"].valueOf()] = "ROOFEDGE_SQUARE_CORNER", values[values.GROUND_DECOR = exports["LocShape.GROUND_DECOR"].valueOf()] = "GROUND_DECOR", values) - ))({}), - LocAngle: ((values) => ( - // src/rsmod/LocAngle/LocAngle - (values[values.WEST = exports["LocAngle.WEST"].valueOf()] = "WEST", values[values.NORTH = exports["LocAngle.NORTH"].valueOf()] = "NORTH", values[values.EAST = exports["LocAngle.EAST"].valueOf()] = "EAST", values[values.SOUTH = exports["LocAngle.SOUTH"].valueOf()] = "SOUTH", values) - ))({}), - CollisionType: ((values) => ( - // src/rsmod/collision/CollisionStrategy/CollisionType - (values[values.NORMAL = exports["CollisionType.NORMAL"].valueOf()] = "NORMAL", values[values.BLOCKED = exports["CollisionType.BLOCKED"].valueOf()] = "BLOCKED", values[values.INDOORS = exports["CollisionType.INDOORS"].valueOf()] = "INDOORS", values[values.OUTDOORS = exports["CollisionType.OUTDOORS"].valueOf()] = "OUTDOORS", values[values.LINE_OF_SIGHT = exports["CollisionType.LINE_OF_SIGHT"].valueOf()] = "LINE_OF_SIGHT", values) - ))({}), - LocLayer: ((values) => ( - // src/rsmod/LocLayer/LocLayer - (values[values.WALL = exports["LocLayer.WALL"].valueOf()] = "WALL", values[values.WALL_DECOR = exports["LocLayer.WALL_DECOR"].valueOf()] = "WALL_DECOR", values[values.GROUND = exports["LocLayer.GROUND"].valueOf()] = "GROUND", values[values.GROUND_DECOR = exports["LocLayer.GROUND_DECOR"].valueOf()] = "GROUND_DECOR", values) - ))({}), - BlockAccessFlag: ((values) => ( - // src/rsmod/flag/BlockAccessFlag/BlockAccessFlag - (values[values.BLOCK_NORTH = exports["BlockAccessFlag.BLOCK_NORTH"].valueOf()] = "BLOCK_NORTH", values[values.BLOCK_EAST = exports["BlockAccessFlag.BLOCK_EAST"].valueOf()] = "BLOCK_EAST", values[values.BLOCK_SOUTH = exports["BlockAccessFlag.BLOCK_SOUTH"].valueOf()] = "BLOCK_SOUTH", values[values.BLOCK_WEST = exports["BlockAccessFlag.BLOCK_WEST"].valueOf()] = "BLOCK_WEST", values) - ))({}) - }, exports); - function __liftString(pointer) { - if (!pointer) return null; - const end = pointer + new Uint32Array(memory2.buffer)[pointer - 4 >>> 2] >>> 1, memoryU16 = new Uint16Array(memory2.buffer); - let start = pointer >>> 1, string = ""; - while (end - start > 1024) string += String.fromCharCode(...memoryU16.subarray(start, start += 1024)); - return string + String.fromCharCode(...memoryU16.subarray(start, end)); - } - function __liftStaticArray(liftElement, align, pointer) { - if (!pointer) return null; - const length = __getU32(pointer - 4) >>> align, values = new Array(length); - for (let i = 0; i < length; ++i) values[i] = liftElement(pointer + (i << align >>> 0)); - return values; - } - let __dataview = new DataView(memory2.buffer); - function __getI32(pointer) { - try { - return __dataview.getInt32(pointer, true); - } catch { - __dataview = new DataView(memory2.buffer); - return __dataview.getInt32(pointer, true); - } - } - function __getU32(pointer) { - try { - return __dataview.getUint32(pointer, true); - } catch { - __dataview = new DataView(memory2.buffer); - return __dataview.getUint32(pointer, true); - } - } - return adaptedExports; -} -var { - memory, - findPath, - findNaivePath, - changeFloor, - changeLoc, - changeNpc, - changePlayer, - changeRoof, - changeWall, - allocateIfAbsent, - deallocateIfPresent, - isZoneAllocated, - isFlagged, - canTravel, - hasLineOfSight, - hasLineOfWalk, - lineOfSight, - lineOfWalk, - reached, - locShapeLayer, - __get, - __set, - __add, - __remove, - __rotate, - __rotateFlags, - __collides, - __reachRectangle1, - __reachRectangleN, - __alteredRotation, - __reachRectangle, - __reachExclusiveRectangle, - CollisionFlag, - LocShape, - LocAngle, - CollisionType, - LocLayer, - BlockAccessFlag -} = await (async (url) => instantiate( - await (async () => { - try { - return await globalThis.WebAssembly.compileStreaming(globalThis.fetch(url)); - } catch { - return globalThis.WebAssembly.compile(await (await import("node:fs/promises")).readFile(url)); - } - })(), - {} -))(new URL("rsmod-pathfinder.wasm", import.meta.url)); - -// src/lostcity/entity/Position.ts -var Direction = { - NORTH_WEST: 0, - NORTH: 1, - NORTH_EAST: 2, - WEST: 3, - EAST: 4, - SOUTH_WEST: 5, - SOUTH: 6, - SOUTH_EAST: 7 -}; -var Position = { - zone: (pos) => pos >> 3, - zoneCenter: (pos) => Position.zone(pos) - 6, - zoneOrigin: (pos) => Position.zoneCenter(pos) << 3, - mapsquare: (pos) => pos >> 6, - local: (pos, origin) => pos - (Position.zoneCenter(origin) << 3), - face: (srcX, srcZ, dstX, dstZ) => { - if (srcX == dstX) { - if (srcZ > dstZ) { - return Direction.SOUTH; - } else if (srcZ < dstZ) { - return Direction.NORTH; - } - } else if (srcX > dstX) { - if (srcZ > dstZ) { - return Direction.SOUTH_WEST; - } else if (srcZ < dstZ) { - return Direction.NORTH_WEST; - } else { - return Direction.WEST; - } - } else { - if (srcZ > dstZ) { - return Direction.SOUTH_EAST; - } else if (srcZ < dstZ) { - return Direction.NORTH_EAST; - } else { - return Direction.EAST; - } - } - return -1; - }, - moveX: (pos, dir) => { - return pos + Position.deltaX(dir); - }, - moveZ: (pos, dir) => { - return pos + Position.deltaZ(dir); - }, - distanceTo(pos, other) { - const p1 = Position.closest(pos, other); - const p2 = Position.closest(other, pos); - return Math.max(Math.abs(p1.x - p2.x), Math.abs(p1.z - p2.z)); - }, - closest(pos, other) { - const occupiedX = pos.x + pos.width - 1; - const occupiedZ = pos.z + pos.length - 1; - return { - x: other.x <= pos.x ? pos.x : other.x >= occupiedX ? occupiedX : other.x, - z: other.z <= pos.z ? pos.z : other.z >= occupiedZ ? occupiedZ : other.z - }; - }, - distanceToSW(pos, other) { - const deltaX = Math.abs(pos.x - other.x); - const deltaZ = Math.abs(pos.z - other.z); - return Math.max(deltaX, deltaZ); - }, - isWithinDistanceSW(pos, other, distance) { - if (Math.abs(pos.x - other.x) > distance || Math.abs(pos.z - other.z) > distance) { - return false; - } - return true; - }, - deltaX(dir) { - switch (dir) { - case Direction.SOUTH_EAST: - case Direction.NORTH_EAST: - case Direction.EAST: - return 1; - case Direction.SOUTH_WEST: - case Direction.NORTH_WEST: - case Direction.WEST: - return -1; - } - return 0; - }, - deltaZ(dir) { - switch (dir) { - case Direction.NORTH_WEST: - case Direction.NORTH_EAST: - case Direction.NORTH: - return 1; - case Direction.SOUTH_WEST: - case Direction.SOUTH_EAST: - case Direction.SOUTH: - return -1; - } - return 0; - }, - unpackCoord(coord) { - const level = coord >> 28 & 3; - const x = coord >> 14 & 16383; - const z = coord & 16383; - return { level, x, z }; - }, - packCoord(level, x, z) { - return z & 16383 | (x & 16383) << 14 | (level & 3) << 28; - }, - packZoneCoord(x, z) { - return (x & 7) << 4 | z & 7; - }, - intersects(srcX, srcZ, srcWidth, srcHeight, destX, destZ, destWidth, destHeight) { - const srcHorizontal = srcX + srcWidth; - const srcVertical = srcZ + srcHeight; - const destHorizontal = destX + destWidth; - const destVertical = destZ + destHeight; - return !(destX >= srcHorizontal || destHorizontal <= srcX || destZ >= srcVertical || destVertical <= srcZ); - }, - formatString(level, x, z, separator = "_") { - const mx = x >> 6; - const mz = z >> 6; - const lx = x & 63; - const lz = z & 63; - return level + separator + mx + separator + mz + separator + lx + separator + lz; - } -}; - -// src/lostcity/entity/HitType.ts -var HitType = /* @__PURE__ */ ((HitType2) => { - HitType2[HitType2["BLOCK"] = 0] = "BLOCK"; - HitType2[HitType2["DAMAGE"] = 1] = "DAMAGE"; - HitType2[HitType2["POISON"] = 2] = "POISON"; - return HitType2; -})(HitType || {}); -var HitType_default = HitType; - -// src/lostcity/entity/PlayerStat.ts -var PlayerStat = /* @__PURE__ */ ((PlayerStat2) => { - PlayerStat2[PlayerStat2["ATTACK"] = 0] = "ATTACK"; - PlayerStat2[PlayerStat2["DEFENCE"] = 1] = "DEFENCE"; - PlayerStat2[PlayerStat2["STRENGTH"] = 2] = "STRENGTH"; - PlayerStat2[PlayerStat2["HITPOINTS"] = 3] = "HITPOINTS"; - PlayerStat2[PlayerStat2["RANGED"] = 4] = "RANGED"; - PlayerStat2[PlayerStat2["PRAYER"] = 5] = "PRAYER"; - PlayerStat2[PlayerStat2["MAGIC"] = 6] = "MAGIC"; - PlayerStat2[PlayerStat2["COOKING"] = 7] = "COOKING"; - PlayerStat2[PlayerStat2["WOODCUTTING"] = 8] = "WOODCUTTING"; - PlayerStat2[PlayerStat2["FLETCHING"] = 9] = "FLETCHING"; - PlayerStat2[PlayerStat2["FISHING"] = 10] = "FISHING"; - PlayerStat2[PlayerStat2["FIREMAKING"] = 11] = "FIREMAKING"; - PlayerStat2[PlayerStat2["CRAFTING"] = 12] = "CRAFTING"; - PlayerStat2[PlayerStat2["SMITHING"] = 13] = "SMITHING"; - PlayerStat2[PlayerStat2["MINING"] = 14] = "MINING"; - PlayerStat2[PlayerStat2["HERBLORE"] = 15] = "HERBLORE"; - PlayerStat2[PlayerStat2["AGILITY"] = 16] = "AGILITY"; - PlayerStat2[PlayerStat2["THIEVING"] = 17] = "THIEVING"; - PlayerStat2[PlayerStat2["STAT18"] = 18] = "STAT18"; - PlayerStat2[PlayerStat2["STAT19"] = 19] = "STAT19"; - PlayerStat2[PlayerStat2["RUNECRAFT"] = 20] = "RUNECRAFT"; - return PlayerStat2; -})(PlayerStat || {}); -var PlayerStat_default = PlayerStat; - -// src/lostcity/entity/MapFindSquareType.ts -var MapFindSqaureType = /* @__PURE__ */ ((MapFindSqaureType2) => { - MapFindSqaureType2[MapFindSqaureType2["LINEOFWALK"] = 0] = "LINEOFWALK"; - MapFindSqaureType2[MapFindSqaureType2["LINEOFSIGHT"] = 1] = "LINEOFSIGHT"; - MapFindSqaureType2[MapFindSqaureType2["NONE"] = 2] = "NONE"; - return MapFindSqaureType2; -})(MapFindSqaureType || {}); -var MapFindSquareType_default = MapFindSqaureType; - -// src/lostcity/engine/script/ScriptValidators.ts -var ScriptInputNumberNotNullValidator = class { - validate(input) { - if (input !== -1) return input; - throw Error("An input number was null(-1)."); - } -}; -var ScriptInputNumberPositiveValidator = class { - validate(input) { - if (input >= 0) return input; - throw Error("An input number was negative."); - } -}; -var ScriptInputStringNotNullValidator = class { - validate(input) { - if (input.length > 0) return input; - throw Error("An input string was null(-1)."); - } -}; -var ScriptInputConfigTypeValidator = class { - type; - count; - name; - constructor(type, count, name) { - this.type = type; - this.count = count; - this.name = name; - } - validate(input) { - if (this.count(input)) return this.type(input); - throw new Error(`An input for a ${this.name} type was not valid to use. Input was ${input}.`); - } -}; -var ScriptInputRangeValidator = class { - min; - max; - name; - constructor(min, max, name) { - this.min = min; - this.max = max; - this.name = name; - } - validate(input) { - if (input >= this.min && input <= this.max) { - return input; - } - throw new Error(`An input for a ${this.name} was out of range. Range should be: ${this.min} to ${this.max}. Input was ${input}.`); - } -}; -var ScriptInputCoordValidator = class extends ScriptInputRangeValidator { - validate(input) { - if (input >= this.min && input <= this.max) { - return Position.unpackCoord(input); - } - throw new Error(`An input for a ${this.name} was out of range. Range should be: ${this.min} to ${this.max}. Input was ${input}.`); - } -}; -var NumberNotNull = new ScriptInputNumberNotNullValidator(); -var NumberPositive = new ScriptInputNumberPositiveValidator(); -var StringNotNull = new ScriptInputStringNotNullValidator(); -var LocTypeValid = new ScriptInputConfigTypeValidator(LocType.get, (input) => input >= 0 && input < LocType.count, "Loc"); -var LocAngleValid = new ScriptInputRangeValidator(LocAngle.WEST, LocAngle.SOUTH, "LocAngle"); -var LocShapeValid = new ScriptInputRangeValidator(LocShape.WALL_STRAIGHT, LocShape.GROUND_DECOR, "LocShape"); -var DurationValid = new ScriptInputRangeValidator(1, 2147483647, "Duration"); -var CoordValid = new ScriptInputCoordValidator(0, 2147483647, "Coord"); -var ParamTypeValid = new ScriptInputConfigTypeValidator(ParamType.get, (input) => input >= 0 && input < ParamType.count, "Param"); -var NpcTypeValid = new ScriptInputConfigTypeValidator(NpcType.get, (input) => input >= 0 && input < NpcType.count, "Npc"); -var NpcStatValid = new ScriptInputRangeValidator(NpcStat_default.ATTACK, NpcStat_default.MAGIC, "NpcStat"); -var PlayerStatValid = new ScriptInputRangeValidator(PlayerStat_default.ATTACK, PlayerStat_default.RUNECRAFT, "PlayerStat"); -var QueueValid = new ScriptInputRangeValidator(0, 19, "AIQueue"); -var HuntTypeValid = new ScriptInputConfigTypeValidator(HuntType.get, (input) => input >= 0 && input < HuntType.count, "Hunt"); -var NpcModeValid = new ScriptInputRangeValidator(NpcMode_default.NULL, NpcMode_default.APNPC5, "NpcMode"); -var HitTypeValid = new ScriptInputRangeValidator(HitType_default.BLOCK, HitType_default.POISON, "Hit"); -var SpotAnimTypeValid = new ScriptInputConfigTypeValidator(SpotanimType.get, (input) => input >= 0 && input < SpotanimType.count, "Spotanim"); -var EnumTypeValid = new ScriptInputConfigTypeValidator(EnumType.get, (input) => input >= 0 && input < EnumType.count, "Enum"); -var ObjTypeValid = new ScriptInputConfigTypeValidator(ObjType.get, (input) => input >= 0 && input < ObjType.count, "Obj"); -var ObjStackValid = new ScriptInputRangeValidator(1, Inventory.STACK_LIMIT, "ObjStack"); -var InvTypeValid = new ScriptInputConfigTypeValidator(InvType.get, (input) => input >= 0 && input < InvType.count, "Inv"); -var CategoryTypeValid = new ScriptInputConfigTypeValidator(CategoryType.get, (input) => input >= 0 && input < CategoryType.count, "Cat"); -var IDKTypeValid = new ScriptInputConfigTypeValidator(IdkType.get, (input) => input >= 0 && input < IdkType.count, "Idk"); -var HuntVisValid = new ScriptInputRangeValidator(HuntVis_default.OFF, HuntVis_default.LINEOFWALK, "HuntVis"); -var FindSquareValid = new ScriptInputRangeValidator(MapFindSquareType_default.LINEOFWALK, MapFindSquareType_default.NONE, "FindSquare"); -var SeqTypeValid = new ScriptInputConfigTypeValidator(SeqType.get, (input) => input >= 0 && input < SeqType.count, "Seq"); -var VarPlayerValid = new ScriptInputConfigTypeValidator(VarPlayerType.get, (input) => input >= 0 && input < VarPlayerType.count, "Varp"); -var VarNpcValid = new ScriptInputConfigTypeValidator(VarNpcType.get, (input) => input >= 0 && input < VarNpcType.count, "Varn"); -var VarSharedValid = new ScriptInputConfigTypeValidator(VarSharedType.get, (input) => input >= 0 && input < VarSharedType.count, "Vars"); -var FontTypeValid = new ScriptInputConfigTypeValidator(FontType.get, (input) => input >= 0 && input < FontType.count, "Font"); -var MesanimValid = new ScriptInputConfigTypeValidator(MesanimType.get, (input) => input >= 0 && input < MesanimType.count, "Mesanim"); -var StructTypeValid = new ScriptInputConfigTypeValidator(StructType.get, (input) => input >= 0 && input < StructType.count, "Struct"); -var DbRowTypeValid = new ScriptInputConfigTypeValidator(DbRowType.get, (input) => input >= 0 && input < DbRowType.count, "Dbrow"); -var DbTableTypeValid = new ScriptInputConfigTypeValidator(DbTableType.get, (input) => input >= 0 && input < DbTableType.count, "Dbtable"); -var GenderValid = new ScriptInputRangeValidator(0, 1, "Gender"); -var SkinColourValid = new ScriptInputRangeValidator(0, 7, "SkinColour"); -function check(input, validator) { - return validator.validate(input); -} - -// src/lostcity/engine/script/handlers/CoreOps.ts -function gosub(state, id) { - if (state.fp >= 50) { - throw new Error("stack overflow"); - } - state.frames[state.fp++] = { - script: state.script, - pc: state.pc, - intLocals: state.intLocals, - stringLocals: state.stringLocals - }; - const script = ScriptProvider.get(id); - if (!script) { - throw new Error(`unable to find proc ${script}`); - } - setupNewScript(state, script); -} -function jump(state, id) { - const label = ScriptProvider.get(id); - if (!label) { - throw new Error(`unable to find label ${id}`); - } - state.debugFrames[state.debugFp++] = { - script: state.script, - pc: state.pc - }; - setupNewScript(state, label); - state.fp = 0; - state.frames = []; -} -function setupNewScript(state, script) { - state.script = script; - state.pc = -1; - state.intLocals = state.popInts(script.intArgCount); - state.stringLocals = state.popStrings(script.stringArgCount); -} -var CoreOps = { - [ScriptOpcode_default.PUSH_CONSTANT_INT]: (state) => { - state.pushInt(state.intOperand); - }, - [ScriptOpcode_default.PUSH_CONSTANT_STRING]: (state) => { - state.pushString(state.stringOperand); - }, - [ScriptOpcode_default.PUSH_VARP]: (state) => { - const secondary = state.intOperand >> 16 & 1; - if (secondary && !state._activePlayer2) { - throw new Error("No secondary active_player."); - } else if (!secondary && !state._activePlayer) { - throw new Error("No active_player."); - } - const varpType = check(state.intOperand & 65535, VarPlayerValid); - if (varpType.type === ScriptVarType.STRING) { - state.pushString(secondary ? state._activePlayer2.getVar(varpType.id) : state._activePlayer.getVar(varpType.id)); - } else { - state.pushInt(secondary ? state._activePlayer2.getVar(varpType.id) : state._activePlayer.getVar(varpType.id)); - } - }, - [ScriptOpcode_default.POP_VARP]: (state) => { - const secondary = state.intOperand >> 16 & 1; - if (secondary && !state._activePlayer2) { - throw new Error("No secondary active_player."); - } else if (!secondary && !state._activePlayer) { - throw new Error("No active_player."); - } - const varpType = check(state.intOperand & 65535, VarPlayerValid); - if (!state.pointerGet(ProtectedActivePlayer[secondary]) && varpType.protect) { - throw new Error(`%${varpType.debugname} requires protected access`); - } - if (varpType.type === ScriptVarType.STRING) { - const value = state.popString(); - if (secondary) { - state._activePlayer2.setVar(varpType.id, value); - } else { - state._activePlayer.setVar(varpType.id, value); - } - } else { - const value = state.popInt(); - if (secondary) { - state._activePlayer2.setVar(varpType.id, value); - } else { - state._activePlayer.setVar(varpType.id, value); - } - } - }, - [ScriptOpcode_default.PUSH_VARN]: (state) => { - const secondary = state.intOperand >> 16 & 1; - if (secondary && !state._activeNpc2) { - throw new Error("No secondary active_npc."); - } else if (!secondary && !state._activeNpc) { - throw new Error("No active_npc."); - } - const varnType = check(state.intOperand & 65535, VarNpcValid); - if (varnType.type === ScriptVarType.STRING) { - state.pushString(secondary ? state._activeNpc2.getVar(varnType.id) : state._activeNpc.getVar(varnType.id)); - } else { - state.pushInt(secondary ? state._activeNpc2.getVar(varnType.id) : state._activeNpc.getVar(varnType.id)); - } - }, - [ScriptOpcode_default.POP_VARN]: (state) => { - const secondary = state.intOperand >> 16 & 1; - if (secondary && !state._activeNpc2) { - throw new Error("No secondary active_npc."); - } else if (!secondary && !state._activeNpc) { - throw new Error("No active_npc."); - } - const varnType = check(state.intOperand & 65535, VarNpcValid); - if (varnType.type === ScriptVarType.STRING) { - const value = state.popInt(); - if (secondary) { - state._activeNpc2.setVar(varnType.id, value); - } else { - state._activeNpc.setVar(varnType.id, value); - } - } else { - const value = state.popInt(); - if (secondary) { - state._activeNpc2.setVar(varnType.id, value); - } else { - state._activeNpc.setVar(varnType.id, value); - } - } - }, - [ScriptOpcode_default.PUSH_INT_LOCAL]: (state) => { - state.pushInt(state.intLocals[state.intOperand]); - }, - [ScriptOpcode_default.POP_INT_LOCAL]: (state) => { - state.intLocals[state.intOperand] = state.popInt(); - }, - [ScriptOpcode_default.PUSH_STRING_LOCAL]: (state) => { - state.pushString(state.stringLocals[state.intOperand]); - }, - [ScriptOpcode_default.POP_STRING_LOCAL]: (state) => { - state.stringLocals[state.intOperand] = state.popString(); - }, - [ScriptOpcode_default.BRANCH]: (state) => { - state.pc += state.intOperand; - }, - [ScriptOpcode_default.BRANCH_NOT]: (state) => { - const b = state.popInt(); - const a = state.popInt(); - if (a !== b) { - state.pc += state.intOperand; - } - }, - [ScriptOpcode_default.BRANCH_EQUALS]: (state) => { - const b = state.popInt(); - const a = state.popInt(); - if (a === b) { - state.pc += state.intOperand; - } - }, - [ScriptOpcode_default.BRANCH_LESS_THAN]: (state) => { - const b = state.popInt(); - const a = state.popInt(); - if (a < b) { - state.pc += state.intOperand; - } - }, - [ScriptOpcode_default.BRANCH_GREATER_THAN]: (state) => { - const b = state.popInt(); - const a = state.popInt(); - if (a > b) { - state.pc += state.intOperand; - } - }, - [ScriptOpcode_default.BRANCH_LESS_THAN_OR_EQUALS]: (state) => { - const b = state.popInt(); - const a = state.popInt(); - if (a <= b) { - state.pc += state.intOperand; - } - }, - [ScriptOpcode_default.BRANCH_GREATER_THAN_OR_EQUALS]: (state) => { - const b = state.popInt(); - const a = state.popInt(); - if (a >= b) { - state.pc += state.intOperand; - } - }, - [ScriptOpcode_default.POP_INT_DISCARD]: (state) => { - state.isp--; - }, - [ScriptOpcode_default.POP_STRING_DISCARD]: (state) => { - state.ssp--; - }, - [ScriptOpcode_default.RETURN]: (state) => { - if (state.fp === 0) { - state.execution = ScriptState.FINISHED; - return; - } - const frame = state.frames[--state.fp]; - state.pc = frame.pc; - state.script = frame.script; - state.intLocals = frame.intLocals; - state.stringLocals = frame.stringLocals; - }, - [ScriptOpcode_default.JOIN_STRING]: (state) => { - const count = state.intOperand; - const strings = []; - for (let i = 0; i < count; i++) { - strings.push(state.popString()); - } - state.pushString(strings.reverse().join("")); - }, - [ScriptOpcode_default.GOSUB]: (state) => { - gosub(state, state.popInt()); - }, - [ScriptOpcode_default.GOSUB_WITH_PARAMS]: (state) => { - gosub(state, state.intOperand); - }, - [ScriptOpcode_default.JUMP]: (state) => { - jump(state, state.popInt()); - }, - [ScriptOpcode_default.JUMP_WITH_PARAMS]: (state) => { - jump(state, state.intOperand); - }, - [ScriptOpcode_default.DEFINE_ARRAY]: (state) => { - throw new Error("unimplemented"); - }, - [ScriptOpcode_default.PUSH_ARRAY_INT]: (state) => { - throw new Error("unimplemented"); - }, - [ScriptOpcode_default.POP_ARRAY_INT]: (state) => { - throw new Error("unimplemented"); - }, - [ScriptOpcode_default.SWITCH]: (state) => { - const key = state.popInt(); - const table = state.script.switchTables[state.intOperand]; - if (table === void 0) { - return; - } - const result = table[key]; - if (result) { - state.pc += result; - } - }, - [ScriptOpcode_default.PUSH_VARS]: (state) => { - const varsType = check(state.intOperand & 65535, VarSharedValid); - if (varsType.type === ScriptVarType.STRING) { - state.pushString(World_default.varsString[varsType.id] ?? ""); - } else { - state.pushInt(World_default.vars[varsType.id]); - } - }, - [ScriptOpcode_default.POP_VARS]: (state) => { - const varsType = check(state.intOperand & 65535, VarSharedValid); - if (varsType.type === ScriptVarType.STRING) { - World_default.varsString[varsType.id] = state.popString(); - } else { - World_default.vars[varsType.id] = state.popInt(); - } - } -}; -var CoreOps_default = CoreOps; - -// src/lostcity/engine/script/handlers/DbOps.ts -var DebugOps = { - [ScriptOpcode_default.DB_FIND_WITH_COUNT]: (state) => { - throw new Error("unimplemented"); - }, - [ScriptOpcode_default.DB_FINDNEXT]: (state) => { - if (!state.dbTable) { - throw new Error("No table selected"); - } - if (state.dbRow + 1 >= state.dbRowQuery.length) { - state.pushInt(-1); - return; - } - state.dbRow++; - state.pushInt(check(state.dbRowQuery[state.dbRow], DbRowTypeValid).id); - }, - [ScriptOpcode_default.DB_GETFIELD]: (state) => { - const [row, tableColumnPacked, listIndex] = state.popInts(3); - const table = tableColumnPacked >> 12 & 65535; - const column = tableColumnPacked >> 4 & 127; - const tuple = tableColumnPacked & 63; - const rowType = check(row, DbRowTypeValid); - const tableType = check(table, DbTableTypeValid); - let values; - if (rowType.tableId !== table) { - values = tableType.getDefault(column); - } else { - values = rowType.getValue(column, listIndex); - } - const valueTypes = tableType.types[column]; - for (let i = 0; i < values.length; i++) { - if (valueTypes[i] === ScriptVarType.STRING) { - state.pushString(values[i]); - } else { - state.pushInt(values[i]); - } - } - }, - [ScriptOpcode_default.DB_GETFIELDCOUNT]: (state) => { - const [row, tableColumnPacked] = state.popInts(2); - const table = tableColumnPacked >> 12 & 65535; - const column = tableColumnPacked >> 4 & 127; - const tuple = tableColumnPacked & 63; - const rowType = check(row, DbRowTypeValid); - const tableType = check(table, DbTableTypeValid); - if (rowType.tableId !== table) { - state.pushInt(0); - return; - } - state.pushInt(rowType.columnValues[column].length / tableType.types[column].length); - }, - [ScriptOpcode_default.DB_LISTALL_WITH_COUNT]: (state) => { - throw new Error("unimplemented"); - }, - [ScriptOpcode_default.DB_GETROWTABLE]: (state) => { - state.pushInt(check(state.popInt(), DbRowTypeValid).tableId); - }, - [ScriptOpcode_default.DB_FINDBYINDEX]: (state) => { - throw new Error("unimplemented"); - }, - [ScriptOpcode_default.DB_FIND_REFINE_WITH_COUNT]: (state) => { - throw new Error("unimplemented"); - }, - [ScriptOpcode_default.DB_FIND]: (state) => { - const isString = state.popInt() == 2; - const query = isString ? state.popString() : state.popInt(); - const tableColumnPacked = state.popInt(); - const table = tableColumnPacked >> 12 & 65535; - const column = tableColumnPacked >> 4 & 127; - const tuple = tableColumnPacked & 63; - state.dbTable = check(table, DbTableTypeValid); - state.dbRow = -1; - state.dbRowQuery = []; - const rows = DbRowType.getInTable(table); - for (let i = 0; i < rows.length; i++) { - const row = rows[i]; - if (row.columnValues[column].includes(query)) { - state.dbRowQuery.push(row.id); - } - } - state.pushInt(state.dbRowQuery.length); - }, - [ScriptOpcode_default.DB_FIND_REFINE]: (state) => { - const isString = state.popInt() == 2; - const query = isString ? state.popString() : state.popInt(); - const tableColumnPacked = state.popInt(); - const table = tableColumnPacked >> 12 & 65535; - const column = tableColumnPacked >> 4 & 127; - const tuple = tableColumnPacked & 63; - const found = []; - const rows = DbRowType.getInTable(table); - for (let i = 0; i < rows.length; i++) { - const row = rows[i]; - if (row.columnValues[column].includes(query)) { - found.push(row.id); - } - } - const prevQuery = state.dbRowQuery; - state.dbRow = -1; - state.dbRowQuery = []; - for (let i = 0; i < prevQuery.length; i++) { - if (found.includes(prevQuery[i])) { - state.dbRowQuery.push(prevQuery[i]); - } - } - state.pushInt(state.dbRowQuery.length); - }, - [ScriptOpcode_default.DB_LISTALL]: (state) => { - throw new Error("unimplemented"); - } -}; -var DbOps_default = DebugOps; - -// src/lostcity/engine/WorldStat.ts -var WorldStat = /* @__PURE__ */ ((WorldStat2) => { - WorldStat2[WorldStat2["CYCLE"] = 0] = "CYCLE"; - WorldStat2[WorldStat2["WORLD"] = 1] = "WORLD"; - WorldStat2[WorldStat2["CLIENT_IN"] = 2] = "CLIENT_IN"; - WorldStat2[WorldStat2["NPC"] = 3] = "NPC"; - WorldStat2[WorldStat2["PLAYER"] = 4] = "PLAYER"; - WorldStat2[WorldStat2["LOGOUT"] = 5] = "LOGOUT"; - WorldStat2[WorldStat2["LOGIN"] = 6] = "LOGIN"; - WorldStat2[WorldStat2["ZONE"] = 7] = "ZONE"; - WorldStat2[WorldStat2["CLIENT_OUT"] = 8] = "CLIENT_OUT"; - WorldStat2[WorldStat2["CLEANUP"] = 9] = "CLEANUP"; - WorldStat2[WorldStat2["BANDWIDTH_IN"] = 10] = "BANDWIDTH_IN"; - WorldStat2[WorldStat2["BANDWIDTH_OUT"] = 11] = "BANDWIDTH_OUT"; - return WorldStat2; -})(WorldStat || {}); -var WorldStat_default = WorldStat; - -// src/lostcity/engine/script/handlers/DebugOps.ts -var DebugOps2 = { - [ScriptOpcode_default.ERROR]: (state) => { - throw new Error(state.popString()); - }, - [ScriptOpcode_default.MAP_PRODUCTION]: (state) => { - state.pushInt(Environment_default.NODE_PRODUCTION ? 1 : 0); - }, - [ScriptOpcode_default.MAP_LASTCLOCK]: (state) => { - state.pushInt(World_default.lastCycleStats[WorldStat_default.CYCLE]); - }, - [ScriptOpcode_default.MAP_LASTWORLD]: (state) => { - state.pushInt(World_default.lastCycleStats[WorldStat_default.WORLD]); - }, - [ScriptOpcode_default.MAP_LASTCLIENTIN]: (state) => { - state.pushInt(World_default.lastCycleStats[WorldStat_default.CLIENT_IN]); - }, - [ScriptOpcode_default.MAP_LASTNPC]: (state) => { - state.pushInt(World_default.lastCycleStats[WorldStat_default.NPC]); - }, - [ScriptOpcode_default.MAP_LASTPLAYER]: (state) => { - state.pushInt(World_default.lastCycleStats[WorldStat_default.PLAYER]); - }, - [ScriptOpcode_default.MAP_LASTLOGOUT]: (state) => { - state.pushInt(World_default.lastCycleStats[WorldStat_default.LOGOUT]); - }, - [ScriptOpcode_default.MAP_LASTLOGIN]: (state) => { - state.pushInt(World_default.lastCycleStats[WorldStat_default.LOGIN]); - }, - [ScriptOpcode_default.MAP_LASTZONE]: (state) => { - state.pushInt(World_default.lastCycleStats[WorldStat_default.ZONE]); - }, - [ScriptOpcode_default.MAP_LASTCLIENTOUT]: (state) => { - state.pushInt(World_default.lastCycleStats[WorldStat_default.CLIENT_OUT]); - }, - [ScriptOpcode_default.MAP_LASTCLEANUP]: (state) => { - state.pushInt(World_default.lastCycleStats[WorldStat_default.CLEANUP]); - }, - [ScriptOpcode_default.MAP_LASTBANDWIDTHIN]: (state) => { - state.pushInt(World_default.lastCycleStats[WorldStat_default.BANDWIDTH_IN]); - }, - [ScriptOpcode_default.MAP_LASTBANDWIDTHOUT]: (state) => { - state.pushInt(World_default.lastCycleStats[WorldStat_default.BANDWIDTH_OUT]); - } -}; -var DebugOps_default = DebugOps2; - -// src/lostcity/engine/script/handlers/EnumOps.ts -var EnumOps = { - [ScriptOpcode_default.ENUM]: (state) => { - const [inputType, outputType, enumId, key] = state.popInts(4); - const enumType = check(enumId, EnumTypeValid); - if (enumType.inputtype !== inputType || enumType.outputtype !== outputType) { - throw new Error(`Type validation error: ${enumType.debugname} key: ${key}. Expected input: ${inputType} got: ${enumType.inputtype}. Expected output: ${outputType} got: ${enumType.outputtype}`); - } - const value = enumType.values.get(key); - if (typeof value === "string") { - state.pushString(value ?? enumType.defaultString); - } else { - state.pushInt(value ?? enumType.defaultInt); - } - }, - [ScriptOpcode_default.ENUM_GETOUTPUTCOUNT]: (state) => { - state.pushInt(check(state.popInt(), EnumTypeValid).values.size); - } -}; -var EnumOps_default = EnumOps; - -// src/lostcity/entity/EntityLifeCycle.ts -var EntityLifeCycle = /* @__PURE__ */ ((EntityLifeCycle2) => { - EntityLifeCycle2[EntityLifeCycle2["FOREVER"] = 0] = "FOREVER"; - EntityLifeCycle2[EntityLifeCycle2["RESPAWN"] = 1] = "RESPAWN"; - EntityLifeCycle2[EntityLifeCycle2["DESPAWN"] = 2] = "DESPAWN"; - return EntityLifeCycle2; -})(EntityLifeCycle || {}); -var EntityLifeCycle_default = EntityLifeCycle; - -// src/lostcity/entity/Entity.ts -var Entity = class { - // constructor - level; - x; - z; - width; - length; - lifecycle; - // runtime - lifecycleTick = -1; - lastLifecycleTick = -1; - constructor(level, x, z, width, length, lifecycle) { - this.level = level; - this.x = x; - this.z = z; - this.width = width; - this.length = length; - this.lifecycle = lifecycle; - } - updateLifeCycle(tick) { - return this.lifecycleTick === tick && this.lifecycle !== EntityLifeCycle_default.FOREVER; - } - checkLifeCycle(tick) { - if (this.lifecycle === EntityLifeCycle_default.FOREVER) { - return true; - } - if (this.lifecycle === EntityLifeCycle_default.RESPAWN) { - return this.lifecycleTick < tick; - } - if (this.lifecycle === EntityLifeCycle_default.DESPAWN) { - return this.lifecycleTick > tick; - } - return false; - } - setLifeCycle(tick) { - this.lifecycleTick = tick; - this.lastLifecycleTick = World_default.currentTick; - } -}; - -// src/lostcity/entity/NonPathingEntity.ts -var NonPathingEntity = class extends Entity { - resetEntity(respawn) { - } -}; - -// src/lostcity/entity/Obj.ts -var Obj = class extends NonPathingEntity { - // constructor properties - type; - count; - // runtime - receiverId = -1; - reveal = -1; - constructor(level, x, z, lifecycle, type, count) { - super(level, x, z, 1, 1, lifecycle); - this.type = type; - this.count = count; - } -}; - -// src/lostcity/engine/script/handlers/InvOps.ts -var InvOps = { - // inv config - [ScriptOpcode_default.INV_ALLSTOCK]: (state) => { - const invType = check(state.popInt(), InvTypeValid); - state.pushInt(invType.allstock ? 1 : 0); - }, - // inv config - [ScriptOpcode_default.INV_SIZE]: (state) => { - const invType = check(state.popInt(), InvTypeValid); - state.pushInt(invType.size); - }, - // inv config - [ScriptOpcode_default.INV_STOCKBASE]: (state) => { - const [inv, obj] = state.popInts(2); - const invType = check(inv, InvTypeValid); - const objType = check(obj, ObjTypeValid); - if (!invType.stockobj || !invType.stockcount) { - state.pushInt(-1); - return; - } - const index = invType.stockobj.indexOf(objType.id); - state.pushInt(index >= 0 ? invType.stockcount[index] : -1); - }, - // inv write - [ScriptOpcode_default.INV_ADD]: checkedHandler(ActivePlayer, (state) => { - const [inv, objId, count] = state.popInts(3); - const invType = check(inv, InvTypeValid); - const objType = check(objId, ObjTypeValid); - check(count, ObjStackValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${invType.debugname}`); - } - if (!invType.dummyinv && objType.dummyitem !== 0) { - throw new Error(`dummyitem in non-dummyinv: ${objType.debugname} -> ${invType.debugname}`); - } - const player = state.activePlayer; - const overflow = count - player.invAdd(invType.id, objType.id, count, false); - if (overflow > 0) { - if (!objType.stackable || overflow === 1) { - for (let i = 0; i < overflow; i++) { - World_default.addObj(new Obj(player.level, player.x, player.z, EntityLifeCycle_default.DESPAWN, objType.id, 1), player.pid, 200); - } - } else { - World_default.addObj(new Obj(player.level, player.x, player.z, EntityLifeCycle_default.DESPAWN, objType.id, overflow), player.pid, 200); - } - } - }), - // inv write - [ScriptOpcode_default.INV_CHANGESLOT]: checkedHandler(ActivePlayer, (state) => { - const [inv, find, replace, replaceCount] = state.popInts(4); - throw new Error("unimplemented"); - }), - // inv write - [ScriptOpcode_default.INV_CLEAR]: checkedHandler(ActivePlayer, (state) => { - const invType = check(state.popInt(), InvTypeValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${invType.debugname}`); - } - state.activePlayer.invClear(invType.id); - }), - // inv write - [ScriptOpcode_default.INV_DEL]: checkedHandler(ActivePlayer, (state) => { - const [inv, obj, count] = state.popInts(3); - const invType = check(inv, InvTypeValid); - const objType = check(obj, ObjTypeValid); - check(count, ObjStackValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${invType.debugname}`); - } - state.activePlayer.invDel(invType.id, objType.id, count); - }), - // inv write - [ScriptOpcode_default.INV_DELSLOT]: checkedHandler(ActivePlayer, (state) => { - const [inv, slot] = state.popInts(2); - const invType = check(inv, InvTypeValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${invType.debugname}`); - } - const obj = state.activePlayer.invGetSlot(invType.id, slot); - if (!obj) { - return; - } - state.activePlayer.invDelSlot(invType.id, slot); - }), - // inv write - [ScriptOpcode_default.INV_DROPITEM]: checkedHandler(ActivePlayer, (state) => { - const [inv, coord, obj, count, duration] = state.popInts(5); - const invType = check(inv, InvTypeValid); - const position = check(coord, CoordValid); - const objType = check(obj, ObjTypeValid); - check(count, ObjStackValid); - check(duration, DurationValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${invType.debugname}`); - } - const player = state.activePlayer; - const completed = player.invDel(invType.id, objType.id, count); - if (completed == 0) { - return; - } - player.playerLog("Dropped item from", invType.debugname, objType.debugname); - const floorObj = new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, objType.id, completed); - World_default.addObj(floorObj, player.pid, duration); - state.activeObj = floorObj; - state.pointerAdd(ActiveObj[state.intOperand]); - }), - // inv write - [ScriptOpcode_default.INV_DROPSLOT]: checkedHandler(ActivePlayer, (state) => { - const [inv, coord, slot, duration] = state.popInts(4); - const invType = check(inv, InvTypeValid); - check(duration, DurationValid); - const position = check(coord, CoordValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${invType.debugname}`); - } - const obj = state.activePlayer.invGetSlot(invType.id, slot); - if (!obj) { - throw new Error("$slot is empty"); - } - const player = state.activePlayer; - const completed = player.invDel(invType.id, obj.id, obj.count, slot); - if (completed === 0) { - return; - } - const objType = ObjType.get(obj.id); - player.playerLog("Dropped item from", invType.debugname, objType.debugname); - if (!objType.stackable || completed === 1) { - for (let i = 0; i < completed; i++) { - const floorObj = new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, obj.id, 1); - World_default.addObj(floorObj, player.pid, duration); - state.activeObj = floorObj; - state.pointerAdd(ActiveObj[state.intOperand]); - } - } else { - const floorObj = new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, obj.id, completed); - World_default.addObj(floorObj, player.pid, duration); - state.activeObj = floorObj; - state.pointerAdd(ActiveObj[state.intOperand]); - } - }), - // inv read - [ScriptOpcode_default.INV_FREESPACE]: checkedHandler(ActivePlayer, (state) => { - const invType = check(state.popInt(), InvTypeValid); - state.pushInt(state.activePlayer.invFreeSpace(invType.id)); - }), - // inv read - [ScriptOpcode_default.INV_GETNUM]: checkedHandler(ActivePlayer, (state) => { - const [inv, slot] = state.popInts(2); - const invType = check(inv, InvTypeValid); - state.pushInt(state.activePlayer.invGetSlot(invType.id, slot)?.count ?? 0); - }), - // inv read - [ScriptOpcode_default.INV_GETOBJ]: checkedHandler(ActivePlayer, (state) => { - const [inv, slot] = state.popInts(2); - const invType = check(inv, InvTypeValid); - state.pushInt(state.activePlayer.invGetSlot(invType.id, slot)?.id ?? -1); - }), - // inv read - [ScriptOpcode_default.INV_ITEMSPACE]: checkedHandler(ActivePlayer, (state) => { - const [inv, obj, count, size] = state.popInts(4); - const invType = check(inv, InvTypeValid); - const objType = check(obj, ObjTypeValid); - check(count, ObjStackValid); - if (size < 0 || size > invType.size) { - throw new Error(`$count is out of range: ${count}`); - } - state.pushInt(state.activePlayer.invItemSpace(invType.id, objType.id, count, size) === 0 ? 1 : 0); - }), - // inv read - [ScriptOpcode_default.INV_ITEMSPACE2]: checkedHandler(ActivePlayer, (state) => { - const [inv, obj, count, size] = state.popInts(4); - const invType = check(inv, InvTypeValid); - const objType = check(obj, ObjTypeValid); - check(count, ObjStackValid); - state.pushInt(state.activePlayer.invItemSpace(invType.id, objType.id, count, size)); - }), - // inv write - [ScriptOpcode_default.INV_MOVEFROMSLOT]: checkedHandler(ActivePlayer, (state) => { - const [fromInv, toInv, fromSlot] = state.popInts(3); - const fromInvType = check(fromInv, InvTypeValid); - const toInvType = check(toInv, InvTypeValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${fromInvType.debugname}`); - } - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${toInvType.debugname}`); - } - const player = state.activePlayer; - const { overflow, fromObj } = player.invMoveFromSlot(fromInvType.id, toInvType.id, fromSlot); - if (overflow > 0) { - const objType = ObjType.get(fromObj); - if (!objType.stackable || overflow === 1) { - for (let i = 0; i < overflow; i++) { - World_default.addObj(new Obj(player.level, player.x, player.z, EntityLifeCycle_default.DESPAWN, fromObj, 1), player.pid, 200); - } - } else { - World_default.addObj(new Obj(player.level, player.x, player.z, EntityLifeCycle_default.DESPAWN, fromObj, overflow), player.pid, 200); - } - } - }), - // inv write - [ScriptOpcode_default.INV_MOVETOSLOT]: checkedHandler(ActivePlayer, (state) => { - const [fromInv, toInv, fromSlot, toSlot] = state.popInts(4); - const fromInvType = check(fromInv, InvTypeValid); - const toInvType = check(toInv, InvTypeValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${fromInvType.debugname}`); - } - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${toInvType.debugname}`); - } - state.activePlayer.invMoveToSlot(fromInvType.id, toInvType.id, fromSlot, toSlot); - }), - // inv write - [ScriptOpcode_default.BOTH_MOVEINV]: checkedHandler(ActivePlayer, (state) => { - const [from, to] = state.popInts(2); - const fromInvType = check(from, InvTypeValid); - const toInvType = check(to, InvTypeValid); - const secondary = state.intOperand == 1; - const fromPlayer = secondary ? state._activePlayer2 : state._activePlayer; - const toPlayer = secondary ? state._activePlayer : state._activePlayer2; - if (!fromPlayer || !toPlayer) { - throw new Error("player is null"); - } - if (!state.pointerGet(ProtectedActivePlayer[secondary ? 1 : 0]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$from_inv requires protected access: ${fromInvType.debugname}`); - } - if (!state.pointerGet(ProtectedActivePlayer[secondary ? 0 : 1]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$to_inv requires protected access: ${toInvType.debugname}`); - } - const fromInv = fromPlayer.getInventory(from); - const toInv = toPlayer.getInventory(to); - if (!fromInv || !toInv) { - throw new Error("inv is null"); - } - for (let slot = 0; slot < fromInv.capacity; slot++) { - const obj = fromInv.get(slot); - if (!obj) { - continue; - } - fromInv.delete(slot); - toInv.add(obj.id, obj.count); - fromPlayer.playerLog("Gave " + ObjType.get(obj.id).name + " x" + obj.count + " during trade with " + toPlayer.username); - toPlayer.playerLog("Received " + ObjType.get(obj.id).name + " x" + obj.count + " during trade with " + fromPlayer.username); - } - }), - // inv write - [ScriptOpcode_default.INV_MOVEITEM]: checkedHandler(ActivePlayer, (state) => { - const [fromInv, toInv, obj, count] = state.popInts(4); - const fromInvType = check(fromInv, InvTypeValid); - const toInvType = check(toInv, InvTypeValid); - const objType = check(obj, ObjTypeValid); - check(count, ObjStackValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${fromInvType.debugname}`); - } - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${toInvType.debugname}`); - } - const player = state.activePlayer; - const completed = player.invDel(fromInvType.id, objType.id, count); - if (completed == 0) { - return; - } - const overflow = count - player.invAdd(toInvType.id, objType.id, completed, false); - if (overflow > 0) { - if (!objType.stackable || overflow === 1) { - for (let i = 0; i < overflow; i++) { - World_default.addObj(new Obj(player.level, player.x, player.z, EntityLifeCycle_default.DESPAWN, objType.id, 1), player.pid, 200); - } - } else { - World_default.addObj(new Obj(player.level, player.x, player.z, EntityLifeCycle_default.DESPAWN, objType.id, overflow), player.pid, 200); - } - } - }), - // inv write - [ScriptOpcode_default.INV_MOVEITEM_CERT]: checkedHandler(ActivePlayer, (state) => { - const [fromInv, toInv, obj, count] = state.popInts(4); - const fromInvType = check(fromInv, InvTypeValid); - const toInvType = check(toInv, InvTypeValid); - const objType = check(obj, ObjTypeValid); - check(count, ObjStackValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${fromInvType.debugname}`); - } - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${toInvType.debugname}`); - } - const player = state.activePlayer; - const completed = player.invDel(fromInvType.id, objType.id, count); - if (completed == 0) { - return; - } - let finalObj = objType.id; - if (objType.certtemplate === -1 && objType.certlink >= 0) { - finalObj = objType.certlink; - } - const overflow = count - player.invAdd(toInvType.id, finalObj, completed, false); - if (overflow > 0) { - World_default.addObj(new Obj(player.level, player.x, player.z, EntityLifeCycle_default.DESPAWN, finalObj, overflow), player.pid, 200); - } - }), - // inv write - [ScriptOpcode_default.INV_MOVEITEM_UNCERT]: checkedHandler(ActivePlayer, (state) => { - const [fromInv, toInv, obj, count] = state.popInts(4); - const fromInvType = check(fromInv, InvTypeValid); - const toInvType = check(toInv, InvTypeValid); - const objType = check(obj, ObjTypeValid); - check(count, ObjStackValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && fromInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${fromInvType.debugname}`); - } - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && toInvType.protect && fromInvType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${toInvType.debugname}`); - } - const player = state.activePlayer; - const completed = player.invDel(fromInvType.id, objType.id, count); - if (completed == 0) { - return; - } - if (objType.certtemplate >= 0 && objType.certlink >= 0) { - player.invAdd(toInvType.id, objType.certlink, completed); - } else { - player.invAdd(toInvType.id, objType.id, completed); - } - }), - // inv write - [ScriptOpcode_default.INV_SETSLOT]: checkedHandler(ActivePlayer, (state) => { - const [inv, slot, objId, count] = state.popInts(4); - const invType = check(inv, InvTypeValid); - const objType = check(objId, ObjTypeValid); - check(count, ObjStackValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${invType.debugname}`); - } - if (!invType.dummyinv && objType.dummyitem !== 0) { - throw new Error(`dummyitem in non-dummyinv: ${objType.debugname} -> ${invType.debugname}`); - } - state.activePlayer.invSet(invType.id, objType.id, count, slot); - }), - // inv read - [ScriptOpcode_default.INV_TOTAL]: checkedHandler(ActivePlayer, (state) => { - const [inv, obj] = state.popInts(2); - const invType = check(inv, InvTypeValid); - if (obj === -1) { - state.pushInt(0); - return; - } - state.pushInt(state.activePlayer.invTotal(invType.id, obj)); - }), - // inv read - [ScriptOpcode_default.INV_TOTALCAT]: checkedHandler(ActivePlayer, (state) => { - const [inv, category] = state.popInts(2); - const invType = check(inv, InvTypeValid); - const catType = check(category, CategoryTypeValid); - state.pushInt(state.activePlayer.invTotalCat(invType.id, catType.id)); - }), - // inv protocol - [ScriptOpcode_default.INV_TRANSMIT]: checkedHandler(ActivePlayer, (state) => { - const [inv, com] = state.popInts(2); - const invType = check(inv, InvTypeValid); - check(com, NumberNotNull); - state.activePlayer.invListenOnCom(invType.id, com, state.activePlayer.uid); - }), - // inv protocol - [ScriptOpcode_default.INVOTHER_TRANSMIT]: checkedHandler(ActivePlayer, (state) => { - const [uid, inv, com] = state.popInts(3); - check(uid, NumberNotNull); - const invType = check(inv, InvTypeValid); - check(com, NumberNotNull); - state.activePlayer.invListenOnCom(invType.id, com, uid); - }), - // inv protocol - [ScriptOpcode_default.INV_STOPTRANSMIT]: checkedHandler(ActivePlayer, (state) => { - const com = check(state.popInt(), NumberNotNull); - state.activePlayer.invStopListenOnCom(com); - }), - // inv write - [ScriptOpcode_default.BOTH_DROPSLOT]: checkedHandler(ActivePlayer, (state) => { - const [inv, coord, slot, duration] = state.popInts(4); - const invType = check(inv, InvTypeValid); - check(duration, DurationValid); - const position = check(coord, CoordValid); - const secondary = state.intOperand == 1; - const fromPlayer = secondary ? state._activePlayer2 : state._activePlayer; - const toPlayer = secondary ? state._activePlayer : state._activePlayer2; - if (!fromPlayer || !toPlayer) { - throw new Error("player is null"); - } - if (!state.pointerGet(ProtectedActivePlayer[secondary ? 1 : 0]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`inv requires protected access: ${invType.debugname}`); - } - const obj = fromPlayer.invGetSlot(invType.id, slot); - if (!obj) { - throw new Error("$slot is empty"); - } - const completed = fromPlayer.invDel(invType.id, obj.id, obj.count, slot); - if (completed === 0) { - return; - } - const objType = ObjType.get(obj.id); - fromPlayer.playerLog("Dropped item from", invType.debugname, objType.debugname); - if (!objType.tradeable) { - return; - } - World_default.addObj(new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, obj.id, completed), toPlayer.pid, duration); - }), - // inv write - [ScriptOpcode_default.INV_DROPALL]: checkedHandler(ActivePlayer, (state) => { - const [inv, coord, duration] = state.popInts(3); - const invType = check(inv, InvTypeValid); - check(duration, DurationValid); - const position = check(coord, CoordValid); - if (!state.pointerGet(ProtectedActivePlayer[state.intOperand]) && invType.protect && invType.scope !== InvType.SCOPE_SHARED) { - throw new Error(`$inv requires protected access: ${invType.debugname}`); - } - const inventory = state.activePlayer.getInventory(invType.id); - if (!inventory) { - return; - } - for (let slot = 0; slot < inventory.capacity; slot++) { - const obj = inventory.get(slot); - if (!obj) { - continue; - } - inventory.delete(slot); - const objType = ObjType.get(obj.id); - if (!objType.tradeable) { - continue; - } - World_default.addObj(new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, obj.id, obj.count), -1, duration); - } - }), - [ScriptOpcode_default.INV_TOTALPARAM]: checkedHandler(ActivePlayer, (state) => { - const [inv, param] = state.popInts(2); - state.pushInt(state.activePlayer.invTotalParam(inv, param)); - }), - [ScriptOpcode_default.INV_TOTALPARAM_STACK]: checkedHandler(ActivePlayer, (state) => { - const [inv, param] = state.popInts(2); - state.pushInt(state.activePlayer.invTotalParamStack(inv, param)); - }) -}; -var InvOps_default = InvOps; - -// src/lostcity/entity/NpcIteratorType.ts -var NpcIteratorType = /* @__PURE__ */ ((NpcIteratorType2) => { - NpcIteratorType2[NpcIteratorType2["ZONE"] = 0] = "ZONE"; - NpcIteratorType2[NpcIteratorType2["DISTANCE"] = 1] = "DISTANCE"; - return NpcIteratorType2; -})(NpcIteratorType || {}); -var NpcIteratorType_default = NpcIteratorType; - -// src/lostcity/engine/script/ScriptIterators.ts -var ScriptIterator = class { - iterator; - tick; - constructor(tick) { - this.iterator = this.generator(); - this.tick = tick; - } - [Symbol.iterator]() { - return this.iterator; - } - next() { - return this.iterator.next(); - } -}; -var HuntIterator = class extends ScriptIterator { - // a radius of 1 will loop 9 zones - // a radius of 2 will loop 25 zones - // a radius of 3 will loop 49 zones - x; - z; - level; - minX; - maxX; - minZ; - maxZ; - distance; - checkVis; - checkType; - checkCategory; - type; - constructor(tick, level, x, z, distance, checkVis, checkType, checkCategory, type) { - super(tick); - const centerX = Position.zone(x); - const centerZ = Position.zone(z); - const radius = 1 + distance / 8 | 0; - this.x = x; - this.z = z; - this.level = level; - this.maxX = centerX + radius; - this.minX = centerX - radius; - this.maxZ = centerZ + radius; - this.minZ = centerZ - radius; - this.distance = distance; - this.checkVis = checkVis; - this.checkType = checkType; - this.checkCategory = checkCategory; - this.type = type; - } - *generator() { - for (let x = this.maxX; x >= this.minX; x--) { - const zoneX = x << 3; - for (let z = this.maxZ; z >= this.minZ; z--) { - const zoneZ = z << 3; - if (this.type === HuntModeType_default.PLAYER) { - for (const player of World_default.getZone(zoneX, zoneZ, this.level).getAllPlayersSafe()) { - if (World_default.currentTick > this.tick) { - throw new Error("[HuntIterator] tried to use an old iterator. Create a new iterator instead."); - } - if (Position.distanceToSW({ x: this.x, z: this.z }, player) > this.distance) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFSIGHT && !hasLineOfSight(this.level, this.x, this.z, player.x, player.z, 1, 1, 1, 1)) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFWALK && !hasLineOfWalk(this.level, this.x, this.z, player.x, player.z, 1, 1, 1, 1)) { - continue; - } - yield player; - } - } else if (this.type === HuntModeType_default.NPC) { - for (const npc of World_default.getZone(zoneX, zoneZ, this.level).getAllNpcsSafe()) { - if (World_default.currentTick > this.tick) { - throw new Error("[HuntIterator] tried to use an old iterator. Create a new iterator instead."); - } - if (this.checkType !== -1 && npc.type !== this.checkType) { - continue; - } - const npcType = NpcType.get(npc.type); - if (this.checkCategory !== -1 && npcType.category !== this.checkCategory) { - continue; - } - if (!npcType.op) { - continue; - } - if (!npcType.op[1]) { - continue; - } - if (Position.distanceToSW({ x: this.x, z: this.z }, npc) > this.distance) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFSIGHT && !hasLineOfSight(this.level, this.x, this.z, npc.x, npc.z, 1, 1, 1, 1)) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFWALK && !hasLineOfWalk(this.level, this.x, this.z, npc.x, npc.z, 1, 1, 1, 1)) { - continue; - } - yield npc; - } - } else if (this.type === HuntModeType_default.OBJ) { - for (const obj of World_default.getZone(zoneX, zoneZ, this.level).getAllObjsSafe()) { - if (World_default.currentTick > this.tick) { - throw new Error("[HuntIterator] tried to use an old iterator. Create a new iterator instead."); - } - if (this.checkType !== -1 && obj.type !== this.checkType) { - continue; - } - const objType = ObjType.get(obj.type); - if (this.checkCategory !== -1 && objType.category !== this.checkCategory) { - continue; - } - if (Position.distanceToSW({ x: this.x, z: this.z }, obj) > this.distance) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFSIGHT && !hasLineOfSight(this.level, this.x, this.z, obj.x, obj.z, 1, 1, 1, 1)) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFWALK && !hasLineOfWalk(this.level, this.x, this.z, obj.x, obj.z, 1, 1, 1, 1)) { - continue; - } - yield obj; - } - } else if (this.type === HuntModeType_default.SCENERY) { - for (const loc of World_default.getZone(zoneX, zoneZ, this.level).getAllLocsSafe()) { - if (World_default.currentTick > this.tick) { - throw new Error("[HuntIterator] tried to use an old iterator. Create a new iterator instead."); - } - if (this.checkType !== -1 && loc.type !== this.checkType) { - continue; - } - const locType = LocType.get(loc.type); - if (this.checkCategory !== -1 && locType.category !== this.checkCategory) { - continue; - } - if (Position.distanceToSW({ x: this.x, z: this.z }, loc) > this.distance) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFSIGHT && !hasLineOfSight(this.level, this.x, this.z, loc.x, loc.z, 1, 1, 1, 1)) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFWALK && !hasLineOfWalk(this.level, this.x, this.z, loc.x, loc.z, 1, 1, 1, 1)) { - continue; - } - yield loc; - } - } - } - } - } -}; -var NpcIterator = class extends ScriptIterator { - level; - x; - z; - minX; - maxX; - minZ; - maxZ; - distance; - checkVis; - type; - constructor(tick, level, x, z, distance, checkVis, type) { - super(tick); - const centerX = Position.zone(x); - const centerZ = Position.zone(z); - const radius = 1 + distance / 8 | 0; - this.x = x; - this.z = z; - this.level = level; - this.maxX = centerX + radius; - this.minX = centerX - radius; - this.maxZ = centerZ + radius; - this.minZ = centerZ - radius; - this.distance = distance; - this.checkVis = checkVis; - this.type = type; - } - *generator() { - if (this.type === NpcIteratorType_default.ZONE) { - for (const npc of World_default.getZone(this.x, this.z, this.level).getAllNpcsSafe()) { - if (World_default.currentTick > this.tick) { - throw new Error("[NpcIterator] tried to use an old iterator. Create a new iterator instead."); - } - yield npc; - } - } else if (this.type === NpcIteratorType_default.DISTANCE) { - for (let x = this.maxX; x >= this.minX; x--) { - const zoneX = x << 3; - for (let z = this.maxZ; z >= this.minZ; z--) { - const zoneZ = z << 3; - for (const npc of World_default.getZone(zoneX, zoneZ, this.level).getAllNpcsSafe()) { - if (World_default.currentTick > this.tick) { - throw new Error("[NpcIterator] tried to use an old iterator. Create a new iterator instead."); - } - if (Position.distanceToSW({ x: this.x, z: this.z }, npc) > this.distance) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFSIGHT && !hasLineOfSight(this.level, this.x, this.z, npc.x, npc.z, 1, 1, 1, 1)) { - continue; - } - if (this.checkVis === HuntVis_default.LINEOFWALK && !hasLineOfWalk(this.level, this.x, this.z, npc.x, npc.z, 1, 1, 1, 1)) { - continue; - } - yield npc; - } - } - } - } - } -}; -var LocIterator = class extends ScriptIterator { - level; - x; - z; - constructor(tick, level, x, z) { - super(tick); - this.level = level; - this.x = x; - this.z = z; - } - *generator() { - for (const loc of World_default.getZone(this.x, this.z, this.level).getAllLocsSafe()) { - if (World_default.currentTick > this.tick) { - throw new Error("[LocIterator] tried to use an old iterator. Create a new iterator instead."); - } - yield loc; - } - } -}; - -// src/lostcity/entity/Loc.ts -var Loc = class extends NonPathingEntity { - // constructor properties - info; - constructor(level, x, z, width, length, lifecycle, type, shape, angle) { - super(level, x, z, width, length, lifecycle); - this.info = type & 16383 | (shape & 31) << 14 | (angle & 3) << 19; - } - get type() { - return this.info & 16383; - } - get shape() { - return this.info >> 14 & 31; - } - get angle() { - return this.info >> 19 & 3; - } -}; - -// src/lostcity/engine/script/handlers/LocOps.ts -var LocOps = { - [ScriptOpcode_default.LOC_ADD]: (state) => { - const [coord, type, angle, shape, duration] = state.popInts(5); - const position = check(coord, CoordValid); - const locType = check(type, LocTypeValid); - const locAngle = check(angle, LocAngleValid); - const locShape = check(shape, LocShapeValid); - check(duration, DurationValid); - const created = new Loc(position.level, position.x, position.z, locType.width, locType.length, EntityLifeCycle_default.DESPAWN, locType.id, locShape, locAngle); - const locs = World_default.getZone(position.x, position.z, position.level).getLocsUnsafe(Position.packZoneCoord(position.x, position.z)); - for (const loc of locs) { - if (loc !== created && loc.angle === locAngle && loc.shape === locShape) { - World_default.removeLoc(loc, duration); - break; - } - } - World_default.addLoc(created, duration); - state.activeLoc = created; - state.pointerAdd(ActiveLoc[state.intOperand]); - }, - [ScriptOpcode_default.LOC_ANGLE]: checkedHandler(ActiveLoc, (state) => { - state.pushInt(check(state.activeLoc.angle, LocAngleValid)); - }), - [ScriptOpcode_default.LOC_ANIM]: checkedHandler(ActiveLoc, (state) => { - const seqType = check(state.popInt(), SeqTypeValid); - World_default.animLoc(state.activeLoc, seqType.id); - }), - [ScriptOpcode_default.LOC_CATEGORY]: checkedHandler(ActiveLoc, (state) => { - state.pushInt(check(state.activeLoc.type, LocTypeValid).category); - }), - [ScriptOpcode_default.LOC_CHANGE]: checkedHandler(ActiveLoc, (state) => { - const [id, duration] = state.popInts(2); - const locType = check(id, LocTypeValid); - check(duration, DurationValid); - World_default.removeLoc(state.activeLoc, duration); - const { level, x, z, angle, shape } = state.activeLoc; - const created = new Loc(level, x, z, locType.width, locType.length, EntityLifeCycle_default.DESPAWN, locType.id, shape, angle); - const locs = World_default.getZone(x, z, level).getLocsUnsafe(Position.packZoneCoord(x, z)); - for (const loc of locs) { - if (loc !== created && loc.angle === angle && loc.shape === shape) { - World_default.removeLoc(loc, duration); - break; - } - } - World_default.addLoc(created, duration); - state.activeLoc = created; - state.pointerAdd(ActiveLoc[state.intOperand]); - }), - [ScriptOpcode_default.LOC_COORD]: checkedHandler(ActiveLoc, (state) => { - const position = state.activeLoc; - state.pushInt(Position.packCoord(position.level, position.x, position.z)); - }), - [ScriptOpcode_default.LOC_DEL]: checkedHandler(ActiveLoc, (state) => { - const duration = check(state.popInt(), DurationValid); - const { level, x, z, angle, shape } = state.activeLoc; - const locs = World_default.getZone(x, z, level).getLocsUnsafe(Position.packZoneCoord(x, z)); - for (const loc of locs) { - if (loc !== state.activeLoc && loc.angle === angle && loc.shape === shape) { - World_default.removeLoc(loc, duration); - break; - } - } - World_default.removeLoc(state.activeLoc, duration); - }), - [ScriptOpcode_default.LOC_FIND]: (state) => { - const [coord, locId] = state.popInts(2); - const locType = check(locId, LocTypeValid); - const position = check(coord, CoordValid); - const loc = World_default.getLoc(position.x, position.z, position.level, locType.id); - if (!loc) { - state.pushInt(0); - return; - } - state.activeLoc = loc; - state.pointerAdd(ActiveLoc[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.LOC_FINDALLZONE]: (state) => { - const position = check(state.popInt(), CoordValid); - state.locIterator = new LocIterator(World_default.currentTick, position.level, position.x, position.z); - if (state._activeLoc) { - state._activeLoc2 = state._activeLoc; - state.pointerAdd(ScriptPointer_default.ActiveLoc2); - } - }, - [ScriptOpcode_default.LOC_FINDNEXT]: (state) => { - const result = state.locIterator?.next(); - if (!result || result.done) { - state.pushInt(0); - return; - } - state.activeLoc = result.value; - state.pointerAdd(ActiveLoc[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.LOC_PARAM]: checkedHandler(ActiveLoc, (state) => { - const paramType = check(state.popInt(), ParamTypeValid); - const locType = check(state.activeLoc.type, LocTypeValid); - if (paramType.isString()) { - state.pushString(ParamHelper.getStringParam(paramType.id, locType, paramType.defaultString)); - } else { - state.pushInt(ParamHelper.getIntParam(paramType.id, locType, paramType.defaultInt)); - } - }), - [ScriptOpcode_default.LOC_TYPE]: checkedHandler(ActiveLoc, (state) => { - state.pushInt(check(state.activeLoc.type, LocTypeValid).id); - }), - [ScriptOpcode_default.LOC_NAME]: checkedHandler(ActiveLoc, (state) => { - state.pushString(check(state.activeLoc.type, LocTypeValid).name ?? "null"); - }), - [ScriptOpcode_default.LOC_SHAPE]: checkedHandler(ActiveLoc, (state) => { - state.pushInt(check(state.activeLoc.shape, LocShapeValid)); - }) -}; -var LocOps_default = LocOps; - -// src/lostcity/engine/script/handlers/LocConfigOps.ts -var LocConfigOps = { - [ScriptOpcode_default.LC_NAME]: (state) => { - const locType = check(state.popInt(), LocTypeValid); - state.pushString(locType.name ?? locType.debugname ?? "null"); - }, - [ScriptOpcode_default.LC_PARAM]: (state) => { - const [locId, paramId] = state.popInts(2); - const locType = check(locId, LocTypeValid); - const paramType = check(paramId, ParamTypeValid); - if (paramType.isString()) { - state.pushString(ParamHelper.getStringParam(paramType.id, locType, paramType.defaultString)); - } else { - state.pushInt(ParamHelper.getIntParam(paramType.id, locType, paramType.defaultInt)); - } - }, - [ScriptOpcode_default.LC_CATEGORY]: (state) => { - state.pushInt(check(state.popInt(), LocTypeValid).category); - }, - [ScriptOpcode_default.LC_DESC]: (state) => { - state.pushString(check(state.popInt(), LocTypeValid).desc ?? "null"); - }, - [ScriptOpcode_default.LC_DEBUGNAME]: (state) => { - state.pushString(check(state.popInt(), LocTypeValid).debugname ?? "null"); - }, - [ScriptOpcode_default.LC_WIDTH]: (state) => { - state.pushInt(check(state.popInt(), LocTypeValid).width); - }, - [ScriptOpcode_default.LC_LENGTH]: (state) => { - state.pushInt(check(state.popInt(), LocTypeValid).length); - } -}; -var LocConfigOps_default = LocConfigOps; - -// src/lostcity/engine/script/ServerTriggerType.ts -var ServerTriggerType = /* @__PURE__ */ ((ServerTriggerType2) => { - ServerTriggerType2[ServerTriggerType2["PROC"] = 0] = "PROC"; - ServerTriggerType2[ServerTriggerType2["LABEL"] = 1] = "LABEL"; - ServerTriggerType2[ServerTriggerType2["DEBUGPROC"] = 2] = "DEBUGPROC"; - ServerTriggerType2[ServerTriggerType2["APNPC1"] = 3] = "APNPC1"; - ServerTriggerType2[ServerTriggerType2["APNPC2"] = 4] = "APNPC2"; - ServerTriggerType2[ServerTriggerType2["APNPC3"] = 5] = "APNPC3"; - ServerTriggerType2[ServerTriggerType2["APNPC4"] = 6] = "APNPC4"; - ServerTriggerType2[ServerTriggerType2["APNPC5"] = 7] = "APNPC5"; - ServerTriggerType2[ServerTriggerType2["APNPCU"] = 8] = "APNPCU"; - ServerTriggerType2[ServerTriggerType2["APNPCT"] = 9] = "APNPCT"; - ServerTriggerType2[ServerTriggerType2["OPNPC1"] = 10] = "OPNPC1"; - ServerTriggerType2[ServerTriggerType2["OPNPC2"] = 11] = "OPNPC2"; - ServerTriggerType2[ServerTriggerType2["OPNPC3"] = 12] = "OPNPC3"; - ServerTriggerType2[ServerTriggerType2["OPNPC4"] = 13] = "OPNPC4"; - ServerTriggerType2[ServerTriggerType2["OPNPC5"] = 14] = "OPNPC5"; - ServerTriggerType2[ServerTriggerType2["OPNPCU"] = 15] = "OPNPCU"; - ServerTriggerType2[ServerTriggerType2["OPNPCT"] = 16] = "OPNPCT"; - ServerTriggerType2[ServerTriggerType2["AI_APNPC1"] = 17] = "AI_APNPC1"; - ServerTriggerType2[ServerTriggerType2["AI_APNPC2"] = 18] = "AI_APNPC2"; - ServerTriggerType2[ServerTriggerType2["AI_APNPC3"] = 19] = "AI_APNPC3"; - ServerTriggerType2[ServerTriggerType2["AI_APNPC4"] = 20] = "AI_APNPC4"; - ServerTriggerType2[ServerTriggerType2["AI_APNPC5"] = 21] = "AI_APNPC5"; - ServerTriggerType2[ServerTriggerType2["AI_OPNPC1"] = 24] = "AI_OPNPC1"; - ServerTriggerType2[ServerTriggerType2["AI_OPNPC2"] = 25] = "AI_OPNPC2"; - ServerTriggerType2[ServerTriggerType2["AI_OPNPC3"] = 26] = "AI_OPNPC3"; - ServerTriggerType2[ServerTriggerType2["AI_OPNPC4"] = 27] = "AI_OPNPC4"; - ServerTriggerType2[ServerTriggerType2["AI_OPNPC5"] = 28] = "AI_OPNPC5"; - ServerTriggerType2[ServerTriggerType2["APOBJ1"] = 31] = "APOBJ1"; - ServerTriggerType2[ServerTriggerType2["APOBJ2"] = 32] = "APOBJ2"; - ServerTriggerType2[ServerTriggerType2["APOBJ3"] = 33] = "APOBJ3"; - ServerTriggerType2[ServerTriggerType2["APOBJ4"] = 34] = "APOBJ4"; - ServerTriggerType2[ServerTriggerType2["APOBJ5"] = 35] = "APOBJ5"; - ServerTriggerType2[ServerTriggerType2["APOBJU"] = 36] = "APOBJU"; - ServerTriggerType2[ServerTriggerType2["APOBJT"] = 37] = "APOBJT"; - ServerTriggerType2[ServerTriggerType2["OPOBJ1"] = 38] = "OPOBJ1"; - ServerTriggerType2[ServerTriggerType2["OPOBJ2"] = 39] = "OPOBJ2"; - ServerTriggerType2[ServerTriggerType2["OPOBJ3"] = 40] = "OPOBJ3"; - ServerTriggerType2[ServerTriggerType2["OPOBJ4"] = 41] = "OPOBJ4"; - ServerTriggerType2[ServerTriggerType2["OPOBJ5"] = 42] = "OPOBJ5"; - ServerTriggerType2[ServerTriggerType2["OPOBJU"] = 43] = "OPOBJU"; - ServerTriggerType2[ServerTriggerType2["OPOBJT"] = 44] = "OPOBJT"; - ServerTriggerType2[ServerTriggerType2["AI_APOBJ1"] = 45] = "AI_APOBJ1"; - ServerTriggerType2[ServerTriggerType2["AI_APOBJ2"] = 46] = "AI_APOBJ2"; - ServerTriggerType2[ServerTriggerType2["AI_APOBJ3"] = 47] = "AI_APOBJ3"; - ServerTriggerType2[ServerTriggerType2["AI_APOBJ4"] = 48] = "AI_APOBJ4"; - ServerTriggerType2[ServerTriggerType2["AI_APOBJ5"] = 49] = "AI_APOBJ5"; - ServerTriggerType2[ServerTriggerType2["AI_OPOBJ1"] = 52] = "AI_OPOBJ1"; - ServerTriggerType2[ServerTriggerType2["AI_OPOBJ2"] = 53] = "AI_OPOBJ2"; - ServerTriggerType2[ServerTriggerType2["AI_OPOBJ3"] = 54] = "AI_OPOBJ3"; - ServerTriggerType2[ServerTriggerType2["AI_OPOBJ4"] = 55] = "AI_OPOBJ4"; - ServerTriggerType2[ServerTriggerType2["AI_OPOBJ5"] = 56] = "AI_OPOBJ5"; - ServerTriggerType2[ServerTriggerType2["APLOC1"] = 59] = "APLOC1"; - ServerTriggerType2[ServerTriggerType2["APLOC2"] = 60] = "APLOC2"; - ServerTriggerType2[ServerTriggerType2["APLOC3"] = 61] = "APLOC3"; - ServerTriggerType2[ServerTriggerType2["APLOC4"] = 62] = "APLOC4"; - ServerTriggerType2[ServerTriggerType2["APLOC5"] = 63] = "APLOC5"; - ServerTriggerType2[ServerTriggerType2["APLOCU"] = 64] = "APLOCU"; - ServerTriggerType2[ServerTriggerType2["APLOCT"] = 65] = "APLOCT"; - ServerTriggerType2[ServerTriggerType2["OPLOC1"] = 66] = "OPLOC1"; - ServerTriggerType2[ServerTriggerType2["OPLOC2"] = 67] = "OPLOC2"; - ServerTriggerType2[ServerTriggerType2["OPLOC3"] = 68] = "OPLOC3"; - ServerTriggerType2[ServerTriggerType2["OPLOC4"] = 69] = "OPLOC4"; - ServerTriggerType2[ServerTriggerType2["OPLOC5"] = 70] = "OPLOC5"; - ServerTriggerType2[ServerTriggerType2["OPLOCU"] = 71] = "OPLOCU"; - ServerTriggerType2[ServerTriggerType2["OPLOCT"] = 72] = "OPLOCT"; - ServerTriggerType2[ServerTriggerType2["AI_APLOC1"] = 73] = "AI_APLOC1"; - ServerTriggerType2[ServerTriggerType2["AI_APLOC2"] = 74] = "AI_APLOC2"; - ServerTriggerType2[ServerTriggerType2["AI_APLOC3"] = 75] = "AI_APLOC3"; - ServerTriggerType2[ServerTriggerType2["AI_APLOC4"] = 76] = "AI_APLOC4"; - ServerTriggerType2[ServerTriggerType2["AI_APLOC5"] = 77] = "AI_APLOC5"; - ServerTriggerType2[ServerTriggerType2["AI_OPLOC1"] = 80] = "AI_OPLOC1"; - ServerTriggerType2[ServerTriggerType2["AI_OPLOC2"] = 81] = "AI_OPLOC2"; - ServerTriggerType2[ServerTriggerType2["AI_OPLOC3"] = 82] = "AI_OPLOC3"; - ServerTriggerType2[ServerTriggerType2["AI_OPLOC4"] = 83] = "AI_OPLOC4"; - ServerTriggerType2[ServerTriggerType2["AI_OPLOC5"] = 84] = "AI_OPLOC5"; - ServerTriggerType2[ServerTriggerType2["APPLAYER1"] = 87] = "APPLAYER1"; - ServerTriggerType2[ServerTriggerType2["APPLAYER2"] = 88] = "APPLAYER2"; - ServerTriggerType2[ServerTriggerType2["APPLAYER3"] = 89] = "APPLAYER3"; - ServerTriggerType2[ServerTriggerType2["APPLAYER4"] = 90] = "APPLAYER4"; - ServerTriggerType2[ServerTriggerType2["APPLAYER5"] = 91] = "APPLAYER5"; - ServerTriggerType2[ServerTriggerType2["APPLAYERU"] = 92] = "APPLAYERU"; - ServerTriggerType2[ServerTriggerType2["APPLAYERT"] = 93] = "APPLAYERT"; - ServerTriggerType2[ServerTriggerType2["OPPLAYER1"] = 94] = "OPPLAYER1"; - ServerTriggerType2[ServerTriggerType2["OPPLAYER2"] = 95] = "OPPLAYER2"; - ServerTriggerType2[ServerTriggerType2["OPPLAYER3"] = 96] = "OPPLAYER3"; - ServerTriggerType2[ServerTriggerType2["OPPLAYER4"] = 97] = "OPPLAYER4"; - ServerTriggerType2[ServerTriggerType2["OPPLAYER5"] = 98] = "OPPLAYER5"; - ServerTriggerType2[ServerTriggerType2["OPPLAYERU"] = 99] = "OPPLAYERU"; - ServerTriggerType2[ServerTriggerType2["OPPLAYERT"] = 100] = "OPPLAYERT"; - ServerTriggerType2[ServerTriggerType2["AI_APPLAYER1"] = 101] = "AI_APPLAYER1"; - ServerTriggerType2[ServerTriggerType2["AI_APPLAYER2"] = 102] = "AI_APPLAYER2"; - ServerTriggerType2[ServerTriggerType2["AI_APPLAYER3"] = 103] = "AI_APPLAYER3"; - ServerTriggerType2[ServerTriggerType2["AI_APPLAYER4"] = 104] = "AI_APPLAYER4"; - ServerTriggerType2[ServerTriggerType2["AI_APPLAYER5"] = 105] = "AI_APPLAYER5"; - ServerTriggerType2[ServerTriggerType2["AI_OPPLAYER1"] = 108] = "AI_OPPLAYER1"; - ServerTriggerType2[ServerTriggerType2["AI_OPPLAYER2"] = 109] = "AI_OPPLAYER2"; - ServerTriggerType2[ServerTriggerType2["AI_OPPLAYER3"] = 110] = "AI_OPPLAYER3"; - ServerTriggerType2[ServerTriggerType2["AI_OPPLAYER4"] = 111] = "AI_OPPLAYER4"; - ServerTriggerType2[ServerTriggerType2["AI_OPPLAYER5"] = 112] = "AI_OPPLAYER5"; - ServerTriggerType2[ServerTriggerType2["QUEUE"] = 116] = "QUEUE"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE1"] = 117] = "AI_QUEUE1"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE2"] = 118] = "AI_QUEUE2"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE3"] = 119] = "AI_QUEUE3"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE4"] = 120] = "AI_QUEUE4"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE5"] = 121] = "AI_QUEUE5"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE6"] = 122] = "AI_QUEUE6"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE7"] = 123] = "AI_QUEUE7"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE8"] = 124] = "AI_QUEUE8"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE9"] = 125] = "AI_QUEUE9"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE10"] = 126] = "AI_QUEUE10"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE11"] = 127] = "AI_QUEUE11"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE12"] = 128] = "AI_QUEUE12"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE13"] = 129] = "AI_QUEUE13"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE14"] = 130] = "AI_QUEUE14"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE15"] = 131] = "AI_QUEUE15"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE16"] = 132] = "AI_QUEUE16"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE17"] = 133] = "AI_QUEUE17"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE18"] = 134] = "AI_QUEUE18"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE19"] = 135] = "AI_QUEUE19"; - ServerTriggerType2[ServerTriggerType2["AI_QUEUE20"] = 136] = "AI_QUEUE20"; - ServerTriggerType2[ServerTriggerType2["SOFTTIMER"] = 137] = "SOFTTIMER"; - ServerTriggerType2[ServerTriggerType2["TIMER"] = 138] = "TIMER"; - ServerTriggerType2[ServerTriggerType2["AI_TIMER"] = 139] = "AI_TIMER"; - ServerTriggerType2[ServerTriggerType2["OPHELD1"] = 140] = "OPHELD1"; - ServerTriggerType2[ServerTriggerType2["OPHELD2"] = 141] = "OPHELD2"; - ServerTriggerType2[ServerTriggerType2["OPHELD3"] = 142] = "OPHELD3"; - ServerTriggerType2[ServerTriggerType2["OPHELD4"] = 143] = "OPHELD4"; - ServerTriggerType2[ServerTriggerType2["OPHELD5"] = 144] = "OPHELD5"; - ServerTriggerType2[ServerTriggerType2["OPHELDU"] = 145] = "OPHELDU"; - ServerTriggerType2[ServerTriggerType2["OPHELDT"] = 146] = "OPHELDT"; - ServerTriggerType2[ServerTriggerType2["IF_BUTTON"] = 147] = "IF_BUTTON"; - ServerTriggerType2[ServerTriggerType2["IF_CLOSE"] = 148] = "IF_CLOSE"; - ServerTriggerType2[ServerTriggerType2["INV_BUTTON1"] = 149] = "INV_BUTTON1"; - ServerTriggerType2[ServerTriggerType2["INV_BUTTON2"] = 150] = "INV_BUTTON2"; - ServerTriggerType2[ServerTriggerType2["INV_BUTTON3"] = 151] = "INV_BUTTON3"; - ServerTriggerType2[ServerTriggerType2["INV_BUTTON4"] = 152] = "INV_BUTTON4"; - ServerTriggerType2[ServerTriggerType2["INV_BUTTON5"] = 153] = "INV_BUTTON5"; - ServerTriggerType2[ServerTriggerType2["INV_BUTTOND"] = 154] = "INV_BUTTOND"; - ServerTriggerType2[ServerTriggerType2["WALKTRIGGER"] = 155] = "WALKTRIGGER"; - ServerTriggerType2[ServerTriggerType2["AI_WALKTRIGGER"] = 156] = "AI_WALKTRIGGER"; - ServerTriggerType2[ServerTriggerType2["LOGIN"] = 157] = "LOGIN"; - ServerTriggerType2[ServerTriggerType2["LOGOUT"] = 158] = "LOGOUT"; - ServerTriggerType2[ServerTriggerType2["TUTORIAL"] = 159] = "TUTORIAL"; - ServerTriggerType2[ServerTriggerType2["ADVANCESTAT"] = 160] = "ADVANCESTAT"; - ServerTriggerType2[ServerTriggerType2["MAPZONE"] = 161] = "MAPZONE"; - ServerTriggerType2[ServerTriggerType2["MAPZONEEXIT"] = 162] = "MAPZONEEXIT"; - ServerTriggerType2[ServerTriggerType2["ZONE"] = 163] = "ZONE"; - ServerTriggerType2[ServerTriggerType2["ZONEEXIT"] = 164] = "ZONEEXIT"; - return ServerTriggerType2; -})(ServerTriggerType || {}); -((ServerTriggerType2) => { - function toString(trigger) { - return ServerTriggerType2[trigger].toLowerCase(); - } - ServerTriggerType2.toString = toString; -})(ServerTriggerType || (ServerTriggerType = {})); -var ServerTriggerType_default = ServerTriggerType; - -// src/lostcity/entity/Interaction.ts -var Interaction = /* @__PURE__ */ ((Interaction2) => { - Interaction2[Interaction2["SCRIPT"] = 0] = "SCRIPT"; - Interaction2[Interaction2["ENGINE"] = 1] = "ENGINE"; - return Interaction2; -})(Interaction || {}); -var Interaction_default = Interaction; - -// src/lostcity/engine/script/handlers/NpcOps.ts -var NpcOps = { - [ScriptOpcode_default.NPC_FINDUID]: (state) => { - const npcUid = state.popInt(); - const slot = npcUid & 65535; - const expectedType = npcUid >> 16 & 65535; - const npc = World_default.getNpc(slot); - if (!npc || npc.type !== expectedType) { - state.pushInt(0); - return; - } - state.activeNpc = npc; - state.pointerAdd(ActiveNpc[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.NPC_ADD]: (state) => { - const [coord, id, duration] = state.popInts(3); - const position = check(coord, CoordValid); - const npcType = check(id, NpcTypeValid); - check(duration, DurationValid); - const npc = new Npc(position.level, position.x, position.z, npcType.size, npcType.size, EntityLifeCycle_default.DESPAWN, World_default.getNextNid(), npcType.id, npcType.moverestrict, npcType.blockwalk); - World_default.addNpc(npc, duration); - state.activeNpc = npc; - state.pointerAdd(ActiveNpc[state.intOperand]); - }, - [ScriptOpcode_default.NPC_ANIM]: checkedHandler(ActiveNpc, (state) => { - const delay = check(state.popInt(), NumberNotNull); - const seq = state.popInt(); - state.activeNpc.playAnimation(seq, delay); - }), - [ScriptOpcode_default.NPC_BASESTAT]: checkedHandler(ActiveNpc, (state) => { - const stat = check(state.popInt(), NpcStatValid); - state.pushInt(state.activeNpc.baseLevels[stat]); - }), - [ScriptOpcode_default.NPC_CATEGORY]: checkedHandler(ActiveNpc, (state) => { - state.pushInt(check(state.activeNpc.type, NpcTypeValid).category); - }), - [ScriptOpcode_default.NPC_COORD]: checkedHandler(ActiveNpc, (state) => { - const position = state.activeNpc; - state.pushInt(Position.packCoord(position.level, position.x, position.z)); - }), - [ScriptOpcode_default.NPC_DEL]: checkedHandler(ActiveNpc, (state) => { - World_default.removeNpc(state.activeNpc, check(state.activeNpc.type, NpcTypeValid).respawnrate); - }), - [ScriptOpcode_default.NPC_DELAY]: checkedHandler(ActiveNpc, (state) => { - state.activeNpc.delay = check(state.popInt(), NumberNotNull) + 1; - state.execution = ScriptState.NPC_SUSPENDED; - }), - [ScriptOpcode_default.NPC_FACESQUARE]: checkedHandler(ActiveNpc, (state) => { - const position = check(state.popInt(), CoordValid); - state.activeNpc.faceSquare(position.x, position.z); - }), - [ScriptOpcode_default.NPC_FINDEXACT]: (state) => { - const [coord, id] = state.popInts(2); - const position = check(coord, CoordValid); - const npcType = check(id, NpcTypeValid); - state.npcIterator = new NpcIterator(World_default.currentTick, position.level, position.x, position.z, 0, 0, NpcIteratorType_default.ZONE); - for (const npc of state.npcIterator) { - if (npc.type === npcType.id && npc.x === position.x && npc.level === position.level && npc.z === position.z) { - state.activeNpc = npc; - state.pointerAdd(ActiveNpc[state.intOperand]); - state.pushInt(1); - return; - } - } - state.pushInt(0); - return; - }, - [ScriptOpcode_default.NPC_FINDHERO]: checkedHandler(ActiveNpc, (state) => { - const uid = state.activeNpc.findHero(); - if (uid === -1) { - state.pushInt(0); - return; - } - const player = World_default.getPlayerByUid(uid); - if (!player) { - state.pushInt(0); - return; - } - state.activePlayer = player; - state.pointerAdd(ScriptPointer_default.ActivePlayer); - state.pushInt(1); - }), - [ScriptOpcode_default.NPC_PARAM]: checkedHandler(ActiveNpc, (state) => { - const paramType = check(state.popInt(), ParamTypeValid); - const npcType = check(state.activeNpc.type, NpcTypeValid); - if (paramType.isString()) { - state.pushString(ParamHelper.getStringParam(paramType.id, npcType, paramType.defaultString)); - } else { - state.pushInt(ParamHelper.getIntParam(paramType.id, npcType, paramType.defaultInt)); - } - }), - [ScriptOpcode_default.NPC_QUEUE]: checkedHandler(ActiveNpc, (state) => { - const delay = check(state.popInt(), NumberNotNull); - const arg = state.popInt(); - const queueId = check(state.popInt(), QueueValid); - const npcType = check(state.activeNpc.type, NpcTypeValid); - const script = ScriptProvider.getByTrigger(ServerTriggerType_default.AI_QUEUE1 + queueId - 1, npcType.id, npcType.category); - if (script) { - state.activeNpc.enqueueScript(script, delay, arg); - } - }), - [ScriptOpcode_default.NPC_RANGE]: checkedHandler(ActiveNpc, (state) => { - const position = check(state.popInt(), CoordValid); - const npc = state.activeNpc; - if (position.level !== npc.level) { - state.pushInt(-1); - } else { - state.pushInt( - Position.distanceTo(npc, { - x: position.x, - z: position.z, - width: 1, - length: 1 - }) - ); - } - }), - [ScriptOpcode_default.NPC_SAY]: checkedHandler(ActiveNpc, (state) => { - state.activeNpc.say(state.popString()); - }), - [ScriptOpcode_default.NPC_SETHUNT]: checkedHandler(ActiveNpc, (state) => { - state.activeNpc.huntrange = check(state.popInt(), NumberNotNull); - }), - [ScriptOpcode_default.NPC_SETHUNTMODE]: checkedHandler(ActiveNpc, (state) => { - state.activeNpc.huntMode = check(state.popInt(), HuntTypeValid).id; - }), - [ScriptOpcode_default.NPC_SETMODE]: checkedHandler(ActiveNpc, (state) => { - const mode = check(state.popInt(), NpcModeValid); - state.activeNpc.clearWaypoints(); - if (mode === NpcMode_default.NULL || mode === NpcMode_default.NONE || mode === NpcMode_default.WANDER || mode === NpcMode_default.PATROL) { - state.activeNpc.clearInteraction(); - state.activeNpc.targetOp = mode; - return; - } - state.activeNpc.targetOp = mode; - let target; - if (mode >= NpcMode_default.OPNPC1) { - target = state._activeNpc2; - } else if (mode >= NpcMode_default.OPOBJ1) { - target = state._activeObj; - } else if (mode >= NpcMode_default.OPLOC1) { - target = state._activeLoc; - } else { - target = state._activePlayer; - } - if (target) { - if (target instanceof Npc || target instanceof Obj || target instanceof Loc) { - state.activeNpc.setInteraction(Interaction_default.SCRIPT, target, mode, { type: target.type, com: -1 }); - } else { - state.activeNpc.setInteraction(Interaction_default.SCRIPT, target, mode); - } - } else { - state.activeNpc.noMode(); - } - }), - [ScriptOpcode_default.NPC_STAT]: checkedHandler(ActiveNpc, (state) => { - const stat = check(state.popInt(), NpcStatValid); - state.pushInt(state.activeNpc.levels[stat]); - }), - [ScriptOpcode_default.NPC_STATHEAL]: checkedHandler(ActiveNpc, (state) => { - const [stat, constant, percent] = state.popInts(3); - check(stat, NpcStatValid); - check(constant, NumberNotNull); - check(percent, NumberNotNull); - const npc = state.activeNpc; - const base = npc.baseLevels[stat]; - const current = npc.levels[stat]; - const healed = current + (constant + current * percent / 100); - npc.levels[stat] = Math.min(healed, base); - if (stat === 0 && npc.levels[stat] === npc.baseLevels[stat]) { - npc.resetHeroPoints(); - } - }), - [ScriptOpcode_default.NPC_TYPE]: checkedHandler(ActiveNpc, (state) => { - state.pushInt(check(state.activeNpc.type, NpcTypeValid).id); - }), - [ScriptOpcode_default.NPC_DAMAGE]: checkedHandler(ActiveNpc, (state) => { - const amount = check(state.popInt(), NumberNotNull); - const type = check(state.popInt(), HitTypeValid); - state.activeNpc.applyDamage(amount, type); - }), - [ScriptOpcode_default.NPC_NAME]: checkedHandler(ActiveNpc, (state) => { - state.pushString(check(state.activeNpc.type, NpcTypeValid).name ?? "null"); - }), - [ScriptOpcode_default.NPC_UID]: checkedHandler(ActiveNpc, (state) => { - state.pushInt(state.activeNpc.uid); - }), - [ScriptOpcode_default.NPC_SETTIMER]: checkedHandler(ActiveNpc, (state) => { - state.activeNpc.setTimer(check(state.popInt(), NumberNotNull)); - }), - [ScriptOpcode_default.SPOTANIM_NPC]: checkedHandler(ActiveNpc, (state) => { - const delay = check(state.popInt(), NumberNotNull); - const height = check(state.popInt(), NumberNotNull); - const spotanimType = check(state.popInt(), SpotAnimTypeValid); - state.activeNpc.spotanim(spotanimType.id, height, delay); - }), - [ScriptOpcode_default.NPC_FIND]: (state) => { - const [coord, npc, distance, checkVis] = state.popInts(4); - const position = check(coord, CoordValid); - const npcType = check(npc, NpcTypeValid); - check(distance, NumberNotNull); - const huntvis = check(checkVis, HuntVisValid); - let closestNpc; - let closestDistance = distance; - const npcs = new NpcIterator(World_default.currentTick, position.level, position.x, position.z, distance, huntvis, NpcIteratorType_default.DISTANCE); - for (const npc2 of npcs) { - if (npc2 && npc2.type === npcType.id) { - const npcDistance = Position.distanceToSW(position, npc2); - if (npcDistance <= closestDistance) { - closestNpc = npc2; - closestDistance = npcDistance; - } - } - } - if (!closestNpc) { - state.pushInt(0); - return; - } - state.activeNpc = closestNpc; - state.pointerAdd(ActiveNpc[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.NPC_FINDALLANY]: (state) => { - const [coord, distance, checkVis] = state.popInts(3); - const position = check(coord, CoordValid); - check(distance, NumberNotNull); - const huntvis = check(checkVis, HuntVisValid); - state.npcIterator = new NpcIterator(World_default.currentTick, position.level, position.x, position.z, distance, huntvis, NpcIteratorType_default.DISTANCE); - if (state._activeNpc) { - state._activeNpc2 = state._activeNpc; - state.pointerAdd(ScriptPointer_default.ActiveNpc2); - } - }, - [ScriptOpcode_default.NPC_FINDALLZONE]: (state) => { - const position = check(state.popInt(), CoordValid); - state.npcIterator = new NpcIterator(World_default.currentTick, position.level, position.x, position.z, 0, 0, NpcIteratorType_default.ZONE); - if (state._activeNpc) { - state._activeNpc2 = state._activeNpc; - state.pointerAdd(ScriptPointer_default.ActiveNpc2); - } - }, - [ScriptOpcode_default.NPC_FINDNEXT]: (state) => { - const result = state.npcIterator?.next(); - if (!result || result.done) { - state.pushInt(0); - return; - } - state.activeNpc = result.value; - state.pointerAdd(ActiveNpc[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.NPC_TELE]: checkedHandler(ActiveNpc, (state) => { - const position = check(state.popInt(), CoordValid); - state.activeNpc.teleport(position.x, position.z, position.level); - }), - [ScriptOpcode_default.NPC_WALK]: checkedHandler(ActiveNpc, (state) => { - const position = check(state.popInt(), CoordValid); - state.activeNpc.queueWaypoint(position.x, position.z); - }), - [ScriptOpcode_default.NPC_CHANGETYPE]: checkedHandler(ActiveNpc, (state) => { - state.activeNpc.changeType(check(state.popInt(), NpcTypeValid).id); - }), - [ScriptOpcode_default.NPC_GETMODE]: checkedHandler(ActiveNpc, (state) => { - state.pushInt(state.activeNpc.targetOp); - }), - [ScriptOpcode_default.NPC_HEROPOINTS]: checkedHandler([ScriptPointer_default.ActivePlayer, ...ActiveNpc], (state) => { - state.activeNpc.addHero(state.activePlayer.uid, check(state.popInt(), NumberNotNull)); - }), - [ScriptOpcode_default.NPC_WALKTRIGGER]: checkedHandler(ActiveNpc, (state) => { - const [queueId, arg] = state.popInts(2); - check(queueId, QueueValid); - state.activeNpc.walktrigger = queueId - 1; - state.activeNpc.walktriggerArg = arg; - }), - [ScriptOpcode_default.NPC_STATADD]: checkedHandler(ActiveNpc, (state) => { - const [stat, constant, percent] = state.popInts(3); - check(stat, NpcStatValid); - check(constant, NumberNotNull); - check(percent, NumberNotNull); - const npc = state.activeNpc; - const current = npc.levels[stat]; - const added = current + (constant + current * percent / 100); - npc.levels[stat] = Math.min(added, 255); - if (stat === 0 && npc.levels[stat] >= npc.baseLevels[stat]) { - npc.resetHeroPoints(); - } - }), - [ScriptOpcode_default.NPC_STATSUB]: checkedHandler(ActiveNpc, (state) => { - const [stat, constant, percent] = state.popInts(3); - check(stat, NpcStatValid); - check(constant, NumberNotNull); - check(percent, NumberNotNull); - const npc = state.activeNpc; - const current = npc.levels[stat]; - const subbed = current - (constant + current * percent / 100); - npc.levels[stat] = Math.max(subbed, 0); - }), - // https://twitter.com/JagexAsh/status/1614498680144527360 - [ScriptOpcode_default.NPC_ATTACKRANGE]: checkedHandler(ActiveNpc, (state) => { - state.pushInt(check(state.activeNpc.type, NpcTypeValid).attackrange); - }) -}; -var NpcOps_default = NpcOps; - -// src/lostcity/engine/script/handlers/NpcConfigOps.ts -var NpcConfigOps = { - [ScriptOpcode_default.NC_NAME]: (state) => { - const npcType = check(state.popInt(), NpcTypeValid); - state.pushString(npcType.name ?? npcType.debugname ?? "null"); - }, - [ScriptOpcode_default.NC_PARAM]: (state) => { - const [npcId, paramId] = state.popInts(2); - const npcType = check(npcId, NpcTypeValid); - const paramType = check(paramId, ParamTypeValid); - if (paramType.isString()) { - state.pushString(ParamHelper.getStringParam(paramId, npcType, paramType.defaultString)); - } else { - state.pushInt(ParamHelper.getIntParam(paramId, npcType, paramType.defaultInt)); - } - }, - [ScriptOpcode_default.NC_CATEGORY]: (state) => { - state.pushInt(check(state.popInt(), NpcTypeValid).category); - }, - [ScriptOpcode_default.NC_DESC]: (state) => { - state.pushString(check(state.popInt(), NpcTypeValid).desc ?? "null"); - }, - [ScriptOpcode_default.NC_DEBUGNAME]: (state) => { - state.pushString(check(state.popInt(), NpcTypeValid).debugname ?? "null"); - }, - [ScriptOpcode_default.NC_OP]: (state) => { - const [npcId, op] = state.popInts(2); - const npcType = check(npcId, NpcTypeValid); - check(op, NumberNotNull); - if (!npcType.op) { - state.pushString(""); - return; - } - state.pushString(npcType.op[op - 1] ?? ""); - } -}; -var NpcConfigOps_default = NpcConfigOps; - -// src/jagex2/Trig.ts -var Trig = class { - static _sin = new Int32Array(16384); - static _cos = new Int32Array(16384); - static { - const size = 3834951969714103e-19; - for (let index = 0; index < 16384; index++) { - this._sin[index] = Math.sin(index * size) * 16384 | 0; - this._cos[index] = Math.cos(index * size) * 16384 | 0; - } - } - static radians(x) { - return (x & 16383) / 16384 * 6.283185307179586; - } - static atan2(y, x) { - return Math.round(Math.atan2(y, x) * 2607.5945876176133) & 16383 | 0; - } - static sin(x) { - return this._sin[x & 16383]; - } - static cos(x) { - return this._cos[x & 16383]; - } -}; - -// src/lostcity/engine/script/handlers/NumberOps.ts -var NumberOps = { - [ScriptOpcode_default.ADD]: (state) => { - const b = state.popInt(); - const a = state.popInt(); - state.pushInt(a + b); - }, - [ScriptOpcode_default.SUB]: (state) => { - const b = state.popInt(); - const a = state.popInt(); - state.pushInt(a - b); - }, - [ScriptOpcode_default.MULTIPLY]: (state) => { - const b = state.popInt(); - const a = state.popInt(); - state.pushInt(a * b); - }, - [ScriptOpcode_default.DIVIDE]: (state) => { - const b = state.popInt(); - const a = state.popInt(); - state.pushInt(a / b); - }, - [ScriptOpcode_default.RANDOM]: (state) => { - const a = state.popInt(); - state.pushInt(Math.random() * a); - }, - [ScriptOpcode_default.RANDOMINC]: (state) => { - const a = state.popInt(); - state.pushInt(Math.random() * (a + 1)); - }, - [ScriptOpcode_default.INTERPOLATE]: (state) => { - const [y0, y1, x0, x1, x] = state.popInts(5); - const lerp = Math.floor((y1 - y0) / (x1 - x0)) * (x - x0) + y0; - state.pushInt(lerp); - }, - [ScriptOpcode_default.ADDPERCENT]: (state) => { - const [num, percent] = state.popInts(2); - state.pushInt(num * percent / 100 + num | 0); - }, - [ScriptOpcode_default.SETBIT]: (state) => { - const [value, bit] = state.popInts(2); - state.pushInt(value | 1 << bit); - }, - [ScriptOpcode_default.CLEARBIT]: (state) => { - const [value, bit] = state.popInts(2); - state.pushInt(value & ~(1 << bit)); - }, - [ScriptOpcode_default.TESTBIT]: (state) => { - const [value, bit] = state.popInts(2); - state.pushInt(value & 1 << bit ? 1 : 0); - }, - [ScriptOpcode_default.MODULO]: (state) => { - const [n1, n2] = state.popInts(2); - state.pushInt(n1 % n2); - }, - [ScriptOpcode_default.POW]: (state) => { - const [base, exponent] = state.popInts(2); - state.pushInt(Math.pow(base, exponent)); - }, - [ScriptOpcode_default.INVPOW]: (state) => { - const [n1, n2] = state.popInts(2); - if (n1 === 0 || n2 === 0) { - state.pushInt(0); - } else { - switch (n2) { - case 1: - state.pushInt(n1); - return; - case 2: - state.pushInt(Math.sqrt(n1)); - return; - case 3: - state.pushInt(Math.cbrt(n1)); - return; - case 4: - state.pushInt(Math.sqrt(Math.sqrt(n1))); - return; - default: - state.pushInt(Math.pow(n1, 1 / n2)); - return; - } - } - }, - [ScriptOpcode_default.AND]: (state) => { - const [n1, n2] = state.popInts(2); - state.pushInt(n1 & n2); - }, - [ScriptOpcode_default.OR]: (state) => { - const [n1, n2] = state.popInts(2); - state.pushInt(n1 | n2); - }, - [ScriptOpcode_default.MIN]: (state) => { - const [a, b] = state.popInts(2); - state.pushInt(Math.min(a, b)); - }, - [ScriptOpcode_default.MAX]: (state) => { - const [a, b] = state.popInts(2); - state.pushInt(Math.max(a, b)); - }, - [ScriptOpcode_default.SCALE]: (state) => { - const [a, b, c] = state.popInts(3); - state.pushInt(a * c / b); - }, - [ScriptOpcode_default.BITCOUNT]: (state) => { - state.pushInt(bitcount(state.popInt())); - }, - [ScriptOpcode_default.TOGGLEBIT]: (state) => { - const [value, bit] = state.popInts(2); - state.pushInt(value ^ 1 << bit); - }, - [ScriptOpcode_default.SETBIT_RANGE]: (state) => { - const [num, startBit, endBit] = state.popInts(3); - state.pushInt(setBitRange(num, startBit, endBit)); - }, - [ScriptOpcode_default.CLEARBIT_RANGE]: (state) => { - const [num, startBit, endBit] = state.popInts(3); - state.pushInt(clearBitRange(num, startBit, endBit)); - }, - [ScriptOpcode_default.GETBIT_RANGE]: (state) => { - const [num, startBit, endBit] = state.popInts(3); - const a = 31 - endBit; - state.pushInt(num << a >>> startBit + a); - }, - [ScriptOpcode_default.SETBIT_RANGE_TOINT]: (state) => { - const [num, value, startBit, endBit] = state.popInts(4); - const clearedBitRange = clearBitRange(num, startBit, endBit); - const maxValue = MASK[endBit - startBit + 1]; - let assignValue = value; - if (value > maxValue) { - assignValue = maxValue; - } - state.pushInt(clearedBitRange | assignValue << startBit); - }, - [ScriptOpcode_default.SIN_DEG]: (state) => { - state.pushInt(Trig.sin(state.popInt())); - }, - [ScriptOpcode_default.COS_DEG]: (state) => { - state.pushInt(Trig.cos(state.popInt())); - }, - [ScriptOpcode_default.ATAN2_DEG]: (state) => { - state.pushInt(Trig.atan2(state.popInt(), state.popInt())); - }, - [ScriptOpcode_default.ABS]: (state) => { - state.pushInt(Math.abs(state.popInt())); - } -}; -var NumberOps_default = NumberOps; - -// src/lostcity/engine/script/handlers/ObjOps.ts -var ObjOps = { - [ScriptOpcode_default.OBJ_ADD]: (state) => { - const [coord, objId, count, duration] = state.popInts(4); - if (objId === -1 || count === -1) { - return; - } - const objType = check(objId, ObjTypeValid); - check(duration, DurationValid); - const position = check(coord, CoordValid); - check(count, ObjStackValid); - if (objType.dummyitem !== 0) { - throw new Error(`attempted to add dummy item: ${objType.debugname}`); - } - if (objType.members && !Environment_default.NODE_MEMBERS) { - return; - } - if (!objType.stackable || count === 1) { - for (let i = 0; i < count; i++) { - const obj = new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, objId, 1); - World_default.addObj(obj, state.activePlayer.pid, duration); - state.activeObj = obj; - state.pointerAdd(ActiveObj[state.intOperand]); - } - } else { - const obj = new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, objId, count); - World_default.addObj(obj, state.activePlayer.pid, duration); - state.activeObj = obj; - state.pointerAdd(ActiveObj[state.intOperand]); - } - }, - [ScriptOpcode_default.OBJ_ADDALL]: (state) => { - const [coord, objId, count, duration] = state.popInts(4); - if (objId === -1 || count === -1) { - return; - } - const objType = check(objId, ObjTypeValid); - check(duration, DurationValid); - const position = check(coord, CoordValid); - check(count, ObjStackValid); - if (objType.dummyitem !== 0) { - throw new Error(`attempted to add dummy item: ${objType.debugname}`); - } - if (objType.members && !Environment_default.NODE_MEMBERS) { - return; - } - if (!objType.stackable || count === 1) { - for (let i = 0; i < count; i++) { - const obj = new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, objId, 1); - World_default.addObj(obj, -1, duration); - state.activeObj = obj; - state.pointerAdd(ActiveObj[state.intOperand]); - } - } else { - const obj = new Obj(position.level, position.x, position.z, EntityLifeCycle_default.DESPAWN, objId, count); - World_default.addObj(obj, -1, duration); - state.activeObj = obj; - state.pointerAdd(ActiveObj[state.intOperand]); - } - }, - [ScriptOpcode_default.OBJ_PARAM]: (state) => { - const paramType = check(state.popInt(), ParamTypeValid); - const objType = check(state.activeObj.type, ObjTypeValid); - if (paramType.isString()) { - state.pushString(ParamHelper.getStringParam(paramType.id, objType, paramType.defaultString)); - } else { - state.pushInt(ParamHelper.getIntParam(paramType.id, objType, paramType.defaultInt)); - } - }, - [ScriptOpcode_default.OBJ_NAME]: (state) => { - const objType = check(state.activeObj.type, ObjTypeValid); - state.pushString(objType.name ?? objType.debugname ?? "null"); - }, - [ScriptOpcode_default.OBJ_DEL]: (state) => { - const duration = ObjType.get(state.activeObj.type).respawnrate; - if (state.pointerGet(ActivePlayer[state.intOperand])) { - World_default.removeObj(state.activeObj, duration); - } else { - World_default.removeObj(state.activeObj, duration); - } - }, - [ScriptOpcode_default.OBJ_COUNT]: (state) => { - state.pushInt(check(state.activeObj.count, ObjStackValid)); - }, - [ScriptOpcode_default.OBJ_TYPE]: (state) => { - state.pushInt(check(state.activeObj.type, ObjTypeValid).id); - }, - [ScriptOpcode_default.OBJ_TAKEITEM]: (state) => { - const invType = check(state.popInt(), InvTypeValid); - const obj = state.activeObj; - const objType = ObjType.get(obj.type); - const zone = World_default.getZone(obj.x, obj.z, obj.level); - for (const o of zone.getObjsSafe(Position.packZoneCoord(obj.x, obj.z))) { - if (o.type !== obj.type || o.count !== obj.count) { - continue; - } - if (o.receiverId !== -1 && o.receiverId !== state.activePlayer.pid) { - continue; - } - state.activePlayer.playerLog("Picked up item", objType.debugname); - state.activePlayer.invAdd(invType.id, obj.type, obj.count); - if (obj.lifecycle === EntityLifeCycle_default.RESPAWN) { - World_default.removeObj(obj, objType.respawnrate); - break; - } else if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { - World_default.removeObj(obj, 0); - break; - } - } - }, - [ScriptOpcode_default.OBJ_COORD]: (state) => { - const position = state.activeObj; - state.pushInt(Position.packCoord(position.level, position.x, position.z)); - } -}; -var ObjOps_default = ObjOps; - -// src/lostcity/engine/script/handlers/ObjConfigOps.ts -var ObjConfigOps = { - [ScriptOpcode_default.OC_NAME]: (state) => { - const objType = check(state.popInt(), ObjTypeValid); - state.pushString(objType.name ?? objType.debugname ?? "null"); - }, - [ScriptOpcode_default.OC_PARAM]: (state) => { - const [objId, paramId] = state.popInts(2); - const objType = check(objId, ObjTypeValid); - const paramType = check(paramId, ParamTypeValid); - if (paramType.isString()) { - state.pushString(ParamHelper.getStringParam(paramType.id, objType, paramType.defaultString)); - } else { - state.pushInt(ParamHelper.getIntParam(paramType.id, objType, paramType.defaultInt)); - } - }, - [ScriptOpcode_default.OC_CATEGORY]: (state) => { - state.pushInt(check(state.popInt(), ObjTypeValid).category); - }, - [ScriptOpcode_default.OC_DESC]: (state) => { - state.pushString(check(state.popInt(), ObjTypeValid).desc ?? "null"); - }, - [ScriptOpcode_default.OC_MEMBERS]: (state) => { - state.pushInt(check(state.popInt(), ObjTypeValid).members ? 1 : 0); - }, - [ScriptOpcode_default.OC_WEIGHT]: (state) => { - state.pushInt(check(state.popInt(), ObjTypeValid).weight); - }, - [ScriptOpcode_default.OC_WEARPOS]: (state) => { - state.pushInt(check(state.popInt(), ObjTypeValid).wearpos); - }, - [ScriptOpcode_default.OC_WEARPOS2]: (state) => { - state.pushInt(check(state.popInt(), ObjTypeValid).wearpos2); - }, - [ScriptOpcode_default.OC_WEARPOS3]: (state) => { - state.pushInt(check(state.popInt(), ObjTypeValid).wearpos3); - }, - [ScriptOpcode_default.OC_COST]: (state) => { - state.pushInt(check(state.popInt(), ObjTypeValid).cost); - }, - [ScriptOpcode_default.OC_TRADEABLE]: (state) => { - state.pushInt(check(state.popInt(), ObjTypeValid).tradeable ? 1 : 0); - }, - [ScriptOpcode_default.OC_DEBUGNAME]: (state) => { - state.pushString(check(state.popInt(), ObjTypeValid).debugname ?? "null"); - }, - [ScriptOpcode_default.OC_CERT]: (state) => { - const objType = check(state.popInt(), ObjTypeValid); - if (objType.certtemplate == -1 && objType.certlink >= 0) { - state.pushInt(objType.certlink); - } else { - state.pushInt(objType.id); - } - }, - [ScriptOpcode_default.OC_UNCERT]: (state) => { - const objType = check(state.popInt(), ObjTypeValid); - if (objType.certtemplate >= 0 && objType.certlink >= 0) { - state.pushInt(objType.certlink); - } else { - state.pushInt(objType.id); - } - }, - [ScriptOpcode_default.OC_STACKABLE]: (state) => { - state.pushInt(check(state.popInt(), ObjTypeValid).stackable ? 1 : 0); - } -}; -var ObjConfigOps_default = ObjConfigOps; - -// src/lostcity/entity/EntityQueueRequest.ts -var EntityQueueRequest = class extends Linkable { - /** - * The type of queue request. - */ - type; - /** - * The script to execute. - */ - script; - /** - * The arguments to execute the script with. - */ - args; - /** - * The number of ticks remaining until the queue executes. - */ - delay; - lastInt = 0; - constructor(type, script, args, delay) { - super(); - this.type = type; - this.script = script; - this.args = args; - this.delay = delay; - } -}; -var EntityQueueState = class extends Linkable { - script; - delay; - constructor(script, delay) { - super(); - this.script = script; - this.delay = delay; - } -}; - -// src/lostcity/entity/NetworkPlayer.ts - -// src/lostcity/network/225/outgoing/prot/ServerProt.ts -var ServerProt = class _ServerProt { - // NXT naming - constructor(id, length) { - this.id = id; - this.length = length; - _ServerProt.all.push(this); - _ServerProt.byId[id] = this; - } - static all = []; - static byId = []; - // interfaces - static IF_OPENCHATMODAL = new _ServerProt(14, 2); - static IF_OPENMAINSIDEMODAL = new _ServerProt(28, 4); - static IF_CLOSE = new _ServerProt(129, 0); - // NXT has "IF_CLOSESUB" - static IF_OPENSIDEOVERLAY = new _ServerProt(167, 3); - static IF_OPENMAINMODAL = new _ServerProt(168, 2); - static IF_OPENSIDEMODAL = new _ServerProt(195, 2); - // updating interfaces - static IF_SETCOLOUR = new _ServerProt(2, 4); - // NXT naming - static IF_SETHIDE = new _ServerProt(26, 3); - // NXT naming - static IF_SETOBJECT = new _ServerProt(46, 6); - // NXT naming - static IF_SHOWSIDE = new _ServerProt(84, 1); - static IF_SETMODEL = new _ServerProt(87, 4); - // NXT naming - static IF_SETRECOL = new _ServerProt(103, 6); - // NXT naming - static IF_SETANIM = new _ServerProt(146, 4); - // NXT naming - static IF_SETPLAYERHEAD = new _ServerProt(197, 2); - // NXT naming - static IF_SETTEXT = new _ServerProt(201, -2); - // NXT naming - static IF_SETNPCHEAD = new _ServerProt(204, 4); - // NXT naming - static IF_SETPOSITION = new _ServerProt(209, 6); - // NXT naming - // tutorial area - static TUTORIAL_FLASHSIDE = new _ServerProt(126, 1); - static TUTORIAL_OPENCHAT = new _ServerProt(185, 2); - // inventory - static UPDATE_INV_STOP_TRANSMIT = new _ServerProt(15, 2); - // NXT naming - static UPDATE_INV_FULL = new _ServerProt(98, -2); - // NXT naming - static UPDATE_INV_PARTIAL = new _ServerProt(213, -2); - // NXT naming - // camera control - static CAM_LOOKAT = new _ServerProt(74, 6); - // NXT naming - static CAM_SHAKE = new _ServerProt(13, 4); - // NXT naming - static CAM_MOVETO = new _ServerProt(3, 6); - // NXT naming - static CAM_RESET = new _ServerProt(239, 0); - // NXT naming - // entity updates - static NPC_INFO = new _ServerProt(1, -2); - // NXT naming - static PLAYER_INFO = new _ServerProt(184, -2); - // NXT naming - // input tracking - static FINISH_TRACKING = new _ServerProt(133, 0); - static ENABLE_TRACKING = new _ServerProt(226, 0); - // social - static MESSAGE_GAME = new _ServerProt(4, -1); - // NXT naming - static UPDATE_IGNORELIST = new _ServerProt(21, -2); - // NXT naming - static CHAT_FILTER_SETTINGS = new _ServerProt(32, 3); - // NXT naming - static MESSAGE_PRIVATE = new _ServerProt(41, -1); - // NXT naming - static UPDATE_FRIENDLIST = new _ServerProt(152, 9); - // NXT naming - // misc - static UNSET_MAP_FLAG = new _ServerProt(19, 0); - // NXT has "SET_MAP_FLAG" but we cannot control the position - static UPDATE_RUNWEIGHT = new _ServerProt(22, 2); - // NXT naming - static HINT_ARROW = new _ServerProt(25, 6); - // NXT naming - static UPDATE_REBOOT_TIMER = new _ServerProt(43, 2); - // NXT naming - static UPDATE_STAT = new _ServerProt(44, 6); - // NXT naming - static UPDATE_RUNENERGY = new _ServerProt(68, 1); - // NXT naming - static RESET_ANIMS = new _ServerProt(136, 0); - // NXT naming - static UPDATE_UID192 = new _ServerProt(139, 2); - // NXT naming (not 100% certain if "uid192" means local player) - static LAST_LOGIN_INFO = new _ServerProt(140, 9); - // NXT naming - static LOGOUT = new _ServerProt(142, 0); - // NXT naming - static P_COUNTDIALOG = new _ServerProt(243, 0); - // named after runescript command + client resume_p_countdialog packet - static SET_MULTIWAY = new _ServerProt(254, 1); - // maps - static DATA_LOC_DONE = new _ServerProt(20, 2); - static DATA_LAND_DONE = new _ServerProt(80, 2); - static DATA_LAND = new _ServerProt(132, -2); - static DATA_LOC = new _ServerProt(220, -2); - static REBUILD_NORMAL = new _ServerProt(237, -2); - // NXT naming (do we really need _normal if there's no region rebuild?) - // vars - static VARP_SMALL = new _ServerProt(150, 3); - // NXT naming - static VARP_LARGE = new _ServerProt(175, 6); - // NXT naming - static RESET_CLIENT_VARCACHE = new _ServerProt(193, 0); - // NXT naming - // audio - static SYNTH_SOUND = new _ServerProt(12, 5); - // NXT naming - static MIDI_SONG = new _ServerProt(54, -1); - // NXT naming - static MIDI_JINGLE = new _ServerProt(212, -2); - // NXT naming - // zones - static UPDATE_ZONE_PARTIAL_FOLLOWS = new _ServerProt(7, 2); - // NXT naming - static UPDATE_ZONE_FULL_FOLLOWS = new _ServerProt(135, 2); - // NXT naming - static UPDATE_ZONE_PARTIAL_ENCLOSED = new _ServerProt(162, -2); -}; - -// src/lostcity/entity/Player.ts - -// src/lostcity/entity/MoveSpeed.ts -var MoveSpeed = /* @__PURE__ */ ((MoveSpeed2) => { - MoveSpeed2[MoveSpeed2["STATIONARY"] = 0] = "STATIONARY"; - MoveSpeed2[MoveSpeed2["CRAWL"] = 1] = "CRAWL"; - MoveSpeed2[MoveSpeed2["WALK"] = 2] = "WALK"; - MoveSpeed2[MoveSpeed2["RUN"] = 3] = "RUN"; - MoveSpeed2[MoveSpeed2["INSTANT"] = 4] = "INSTANT"; - return MoveSpeed2; -})(MoveSpeed || {}); -var MoveSpeed_default = MoveSpeed; - -// src/lostcity/entity/MoveStrategy.ts -var MoveStrategy = /* @__PURE__ */ ((MoveStrategy2) => { - MoveStrategy2[MoveStrategy2["SMART"] = 0] = "SMART"; - MoveStrategy2[MoveStrategy2["NAIVE"] = 1] = "NAIVE"; - MoveStrategy2[MoveStrategy2["FLY"] = 2] = "FLY"; - return MoveStrategy2; -})(MoveStrategy || {}); -var MoveStrategy_default = MoveStrategy; - -// src/lostcity/entity/PathingEntity.ts -var PathingEntity = class _PathingEntity extends Entity { - // constructor properties - moveRestrict; - blockWalk; - moveStrategy; - coordmask; - entitymask; - // runtime properties - moveSpeed = MoveSpeed_default.INSTANT; - walkDir = -1; - runDir = -1; - waypointIndex = -1; - waypoints = new Int32Array(25); - lastX = -1; - lastZ = -1; - lastLevel = -1; - tele = false; - jump = false; - lastStepX = -1; - lastStepZ = -1; - stepsTaken = 0; - lastInt = -1; - // resume_p_countdialog, ai_queue - lastCrawl = false; - walktrigger = -1; - walktriggerArg = 0; - // used for npcs - delay = -1; - interacted = false; - repathed = false; - target = null; - targetOp = -1; - targetSubject = { type: -1, com: -1 }; - targetX = -1; - targetZ = -1; - apRange = 10; - apRangeCalled = false; - alreadyFacedEntity = false; - mask = 0; - exactStartX = -1; - exactStartZ = -1; - exactEndX = -1; - exactEndZ = -1; - exactMoveStart = -1; - exactMoveEnd = -1; - exactMoveDirection = -1; - faceX = -1; - faceZ = -1; - orientationX = -1; - orientationZ = -1; - faceEntity = -1; - damageTaken = -1; - damageType = -1; - animId = -1; - animDelay = -1; - chat = null; - graphicId = -1; - graphicHeight = -1; - graphicDelay = -1; - constructor(level, x, z, width, length, lifecycle, moveRestrict, blockWalk, moveStrategy, coordmask, entitymask) { - super(level, x, z, width, length, lifecycle); - this.moveRestrict = moveRestrict; - this.blockWalk = blockWalk; - this.moveStrategy = moveStrategy; - this.coordmask = coordmask; - this.entitymask = entitymask; - this.lastStepX = x - 1; - this.lastStepZ = z; - } - /** - * Process movement function for a PathingEntity to use. - * Checks for if this PathingEntity has any waypoints to move towards. - * Handles force movement. Validates and moves depending on if this - * PathingEntity is walking or running only. - * Applies an orientation update to this PathingEntity if a step - * direction was taken. - * Updates this PathingEntity zone presence if moved. - * Returns false is this PathingEntity has no waypoints. - * Returns true if a step was taken and movement processed. - */ - processMovement() { - if (!this.hasWaypoints() || this.moveSpeed === MoveSpeed_default.STATIONARY || this.moveSpeed === MoveSpeed_default.INSTANT) { - return false; - } - if (this.moveSpeed === MoveSpeed_default.CRAWL) { - this.lastCrawl = !this.lastCrawl; - if (this.lastCrawl && this.walkDir === -1) { - this.walkDir = this.validateAndAdvanceStep(); - } - return true; - } - if (this.walkDir === -1) { - this.walkDir = this.validateAndAdvanceStep(); - if (this.moveSpeed === MoveSpeed_default.RUN && this.walkDir !== -1 && this.runDir === -1) { - this.runDir = this.validateAndAdvanceStep(); - } - } - return true; - } - /** - * Zone presence implementation for a PathingEntity. - * Can allow updating collision map, removing a PathingEntity from a zone, etc. - * @param previousX Their previous recorded x position before movement. - * @param previousZ Their previous recorded z position before movement. - * @param previousLevel Their previous recorded level position before movement. This one is important for teleport. - */ - refreshZonePresence(previousX, previousZ, previousLevel) { - if (this.x != previousX || this.z !== previousZ || this.level !== previousLevel) { - switch (this.blockWalk) { - case BlockWalk_default.NPC: - World_default.gameMap.changeNpcCollision(this.width, previousX, previousZ, previousLevel, false); - World_default.gameMap.changeNpcCollision(this.width, this.x, this.z, this.level, true); - break; - case BlockWalk_default.ALL: - World_default.gameMap.changeNpcCollision(this.width, previousX, previousZ, previousLevel, false); - World_default.gameMap.changeNpcCollision(this.width, this.x, this.z, this.level, true); - World_default.gameMap.changePlayerCollision(this.width, previousX, previousZ, previousLevel, false); - World_default.gameMap.changePlayerCollision(this.width, this.x, this.z, this.level, true); - break; - } - this.lastStepX = previousX; - this.lastStepZ = previousZ; - } - if (Position.zone(previousX) !== Position.zone(this.x) || Position.zone(previousZ) !== Position.zone(this.z) || previousLevel != this.level) { - World_default.getZone(previousX, previousZ, previousLevel).leave(this); - World_default.getZone(this.x, this.z, this.level).enter(this); - } - } - /** - * Validates the next step in our current waypoint. - * - * Deques to the next step if reached the end of current step, - * then attempts to look for a possible second next step, - * validates and repeats. - * - * Moves this PathingEntity each time a step is validated. - * - * A PathingEntity can persist their current step for example if - * blocked by another PathingEntity. Unless a PathingEntity does - * a random walk again while still persisting their current step. - * - * Returns the final validated step direction. - */ - validateAndAdvanceStep() { - const dir = this.takeStep(); - if (dir === null) { - return -1; - } - if (dir === -1) { - this.waypointIndex--; - if (this.waypointIndex != -1) { - return this.validateAndAdvanceStep(); - } - return -1; - } - const previousX = this.x; - const previousZ = this.z; - this.x = Position.moveX(this.x, dir); - this.z = Position.moveZ(this.z, dir); - this.orientationX = Position.moveX(this.x, dir) * 2 + 1; - this.orientationZ = Position.moveZ(this.z, dir) * 2 + 1; - this.stepsTaken++; - this.refreshZonePresence(previousX, previousZ, this.level); - return dir; - } - /** - * Queue this PathingEntity to a single waypoint. - * @param x The x position of the step. - * @param z The z position of the step. - */ - queueWaypoint(x, z) { - this.waypoints[0] = Position.packCoord(0, x, z); - this.waypointIndex = 0; - } - /** - * Queue waypoints to this PathingEntity. - * @param waypoints The waypoints to queue. - */ - queueWaypoints(waypoints) { - let index = -1; - for (let input = waypoints.length - 1, output = 0; input >= 0 && output < this.waypoints.length; input--, output++) { - this.waypoints[output] = waypoints[input]; - index++; - } - this.waypointIndex = index; - } - clearWaypoints() { - this.waypointIndex = -1; - } - teleJump(x, z, level) { - this.teleport(x, z, level); - this.jump = true; - } - teleport(x, z, level) { - if (isNaN(level)) { - level = 0; - } - level = Math.max(0, Math.min(level, 3)); - const previousX = this.x; - const previousZ = this.z; - const previousLevel = this.level; - this.x = x; - this.z = z; - this.level = level; - this.refreshZonePresence(previousX, previousZ, previousLevel); - this.lastStepX = this.x - 1; - this.lastStepZ = this.z; - this.moveSpeed = MoveSpeed_default.INSTANT; - if (previousLevel != level) { - this.jump = true; - } - } - /** - * Check if the number of tiles moved is > 2, we use Teleport for this PathingEntity. - */ - validateDistanceWalked() { - const distanceCheck = Position.distanceTo(this, { - x: this.lastX, - z: this.lastZ, - width: this.width, - length: this.length - }) > 2; - if (distanceCheck) { - this.jump = true; - } - } - convertMovementDir() { - let walkDir = this.walkDir; - let runDir = this.runDir; - let tele = this.moveSpeed === MoveSpeed_default.INSTANT; - const distanceMoved = Position.distanceTo(this, { - x: this.lastX, - z: this.lastZ, - width: this.width, - length: this.length - }); - if (tele && !this.jump && distanceMoved <= 2) { - if (distanceMoved === 2) { - const firstX = (this.x + this.lastX) / 2 | 0; - const firstZ = (this.z + this.lastZ) / 2 | 0; - walkDir = Position.face(this.lastX, this.lastZ, firstX, firstZ); - runDir = Position.face(firstX, firstZ, this.x, this.z); - } else { - walkDir = Position.face(this.lastX, this.lastZ, this.x, this.z); - runDir = -1; - } - tele = false; - } - this.walkDir = walkDir; - this.runDir = runDir; - this.tele = tele; - } - /** - * Returns if this PathingEntity has any queued waypoints. - */ - hasWaypoints() { - return this.waypointIndex !== -1; - } - /* - * Returns if this PathingEntity is at the last waypoint or has no waypoint. - */ - isLastOrNoWaypoint() { - return this.waypointIndex <= 0; - } - inOperableDistance(target) { - if (target.level !== this.level) { - return false; - } - if (target instanceof _PathingEntity) { - return reached(this.level, this.x, this.z, target.x, target.z, target.width, target.length, this.width, -1, -2); - } else if (target instanceof Loc) { - const forceapproach = LocType.get(target.type).forceapproach; - return reached(this.level, this.x, this.z, target.x, target.z, target.width, target.length, this.width, target.angle, target.shape, forceapproach); - } - const reachedAdjacent = reached(this.level, this.x, this.z, target.x, target.z, target.width, target.length, this.width, 0, -2); - if (isFlagged(target.x, target.z, target.level, CollisionFlag.WALK_BLOCKED)) { - return reachedAdjacent; - } - if (!this.hasWaypoints() && reachedAdjacent) { - return true; - } - return reached(this.level, this.x, this.z, target.x, target.z, target.width, target.length, this.width, 0, -1); - } - inApproachDistance(range, target) { - if (target.level !== this.level) { - return false; - } - if (target instanceof _PathingEntity && Position.intersects(this.x, this.z, this.width, this.length, target.x, target.z, target.width, target.length)) { - return false; - } - return Position.distanceTo(this, target) <= range && hasLineOfSight(this.level, this.x, this.z, target.x, target.z, this.width, this.length, target.width, target.length, CollisionFlag.PLAYER); - } - pathToMoveClick(input, needsfinding) { - if (this.moveStrategy === MoveStrategy_default.SMART) { - if (needsfinding) { - const { x, z } = Position.unpackCoord(input[0]); - this.queueWaypoints(findPath(this.level, this.x, this.z, x, z)); - } else { - this.queueWaypoints(input); - } - } else { - const { x, z } = Position.unpackCoord(input[input.length - 1]); - this.queueWaypoint(x, z); - } - } - pathToPathingTarget() { - if (!this.target || !(this.target instanceof _PathingEntity)) { - return; - } - if (!this.isLastOrNoWaypoint()) { - return; - } - if (this.targetOp === ServerTriggerType_default.APPLAYER3 || this.targetOp === ServerTriggerType_default.OPPLAYER3) { - this.queueWaypoint(this.target.lastStepX, this.target.lastStepZ); - return; - } - this.pathToTarget(); - } - pathToTarget() { - if (!this.target) { - return; - } - this.targetX = this.target.x; - this.targetZ = this.target.z; - const faceX = this.target.x * 2 + this.target.width; - const faceZ = this.target.z * 2 + this.target.length; - this.orientationX = faceX; - this.orientationZ = faceZ; - if (this.moveStrategy === MoveStrategy_default.SMART) { - if (this.target instanceof _PathingEntity) { - this.queueWaypoints(findPath(this.level, this.x, this.z, this.target.x, this.target.z, this.width, this.target.width, this.target.length, 0, -2)); - } else if (this.target instanceof Loc) { - const forceapproach = LocType.get(this.target.type).forceapproach; - this.queueWaypoints(findPath(this.level, this.x, this.z, this.target.x, this.target.z, this.width, this.target.width, this.target.length, this.target.angle, this.target.shape, true, forceapproach)); - } else { - this.queueWaypoints(findPath(this.level, this.x, this.z, this.target.x, this.target.z)); - } - } else if (this.moveStrategy === MoveStrategy_default.NAIVE) { - const collisionStrategy = this.getCollisionStrategy(); - if (collisionStrategy === null) { - return; - } - const extraFlag = this.blockWalkFlag(); - if (extraFlag === CollisionFlag.NULL) { - return; - } - if (this.target instanceof _PathingEntity) { - this.queueWaypoints(findNaivePath(this.level, this.x, this.z, this.target.x, this.target.z, this.width, this.length, this.target.width, this.target.length, extraFlag, collisionStrategy)); - } else { - this.queueWaypoint(this.target.x, this.target.z); - } - } else { - const collisionStrategy = this.getCollisionStrategy(); - if (collisionStrategy === null) { - return; - } - const extraFlag = this.blockWalkFlag(); - if (extraFlag === CollisionFlag.NULL) { - return; - } - this.queueWaypoint(this.target.x, this.target.z); - } - } - setInteraction(interaction, target, op, subject) { - this.target = target; - this.targetOp = op; - this.targetSubject = subject ?? { type: -1, com: -1 }; - this.targetX = target.x; - this.targetZ = target.z; - this.apRange = 10; - this.apRangeCalled = false; - const faceX = target.x * 2 + target.width; - const faceZ = target.z * 2 + target.length; - if (target instanceof Player) { - const pid = target.pid + 32768; - if (this.faceEntity !== pid) { - this.faceEntity = pid; - this.mask |= this.entitymask; - } - } else if (target instanceof Npc) { - const nid = target.nid; - if (this.faceEntity !== nid) { - this.faceEntity = nid; - this.mask |= this.entitymask; - } - } else if (this.orientationX !== faceX || this.orientationZ !== faceZ) { - this.orientationX = faceX; - this.orientationZ = faceZ; - this.faceX = faceX; - this.faceZ = faceZ; - this.mask |= this.coordmask; - } - if (interaction === Interaction_default.SCRIPT) { - this.pathToTarget(); - } - } - clearInteraction() { - this.target = null; - this.targetOp = -1; - this.targetSubject = { type: -1, com: -1 }; - this.targetX = -1; - this.targetZ = -1; - this.apRange = 10; - this.apRangeCalled = false; - this.alreadyFacedEntity = true; - } - getCollisionStrategy() { - if (this.moveRestrict === MoveRestrict_default.NORMAL) { - return CollisionType.NORMAL; - } else if (this.moveRestrict === MoveRestrict_default.BLOCKED) { - return CollisionType.BLOCKED; - } else if (this.moveRestrict === MoveRestrict_default.BLOCKED_NORMAL) { - return CollisionType.LINE_OF_SIGHT; - } else if (this.moveRestrict === MoveRestrict_default.INDOORS) { - return CollisionType.INDOORS; - } else if (this.moveRestrict === MoveRestrict_default.OUTDOORS) { - return CollisionType.OUTDOORS; - } else if (this.moveRestrict === MoveRestrict_default.NOMOVE) { - return null; - } else if (this.moveRestrict === MoveRestrict_default.PASSTHRU) { - return CollisionType.NORMAL; - } - return null; - } - resetPathingEntity() { - this.moveSpeed = this.defaultMoveSpeed(); - this.walkDir = -1; - this.runDir = -1; - this.jump = false; - this.tele = false; - this.lastX = this.x; - this.lastZ = this.z; - this.lastLevel = this.level; - this.stepsTaken = 0; - this.interacted = false; - this.apRangeCalled = false; - this.mask = 0; - this.exactStartX = -1; - this.exactStartZ = -1; - this.exactEndX = -1; - this.exactEndZ = -1; - this.exactMoveStart = -1; - this.exactMoveEnd = -1; - this.exactMoveDirection = -1; - this.animId = -1; - this.animDelay = -1; - this.animId = -1; - this.animDelay = -1; - this.chat = null; - this.damageTaken = -1; - this.damageType = -1; - this.graphicId = -1; - this.graphicHeight = -1; - this.graphicDelay = -1; - if (this.alreadyFacedEntity && !this.target && this.faceEntity !== -1) { - this.mask |= this.entitymask; - this.faceEntity = -1; - this.alreadyFacedEntity = false; - } - } - takeStep() { - if (this.waypointIndex === -1) { - return null; - } - const srcX = this.x; - const srcZ = this.z; - const { x, z } = Position.unpackCoord(this.waypoints[this.waypointIndex]); - const dir = Position.face(srcX, srcZ, x, z); - const dx = Position.deltaX(dir); - const dz = Position.deltaZ(dir); - if (dx == 0 && dz == 0) { - return -1; - } - const collisionStrategy = this.getCollisionStrategy(); - if (collisionStrategy === null) { - return -1; - } - const extraFlag = this.blockWalkFlag(); - if (extraFlag === CollisionFlag.NULL) { - return -1; - } - if (this.moveStrategy === MoveStrategy_default.FLY) { - return dir; - } - if (canTravel(this.level, this.x, this.z, dx, dz, this.width, extraFlag, collisionStrategy)) { - return dir; - } - if (dx != 0 && canTravel(this.level, this.x, this.z, dx, 0, this.width, extraFlag, collisionStrategy)) { - return Position.face(srcX, srcZ, x, srcZ); - } - if (dz != 0 && canTravel(this.level, this.x, this.z, 0, dz, this.width, extraFlag, collisionStrategy)) { - return Position.face(srcX, srcZ, srcX, z); - } - return null; - } -}; - -// src/jagex2/datastruct/Stack.ts -var Stack = class { - sentinel; - cursor = null; - constructor() { - const head = new Hashable(); - head.nextHashable = head; - head.prevHashable = head; - this.sentinel = head; - } - push(node) { - if (node.prevHashable) { - node.uncache(); - } - node.prevHashable = this.sentinel.prevHashable; - node.nextHashable = this.sentinel; - if (node.prevHashable) { - node.prevHashable.nextHashable = node; - } - node.nextHashable.prevHashable = node; - } - pop() { - const node = this.sentinel.nextHashable; - if (node === this.sentinel) { - return null; - } - node?.uncache(); - return node; - } - head() { - const node = this.sentinel.nextHashable; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.nextHashable || null; - return node; - } - next() { - const node = this.cursor; - if (node === this.sentinel) { - this.cursor = null; - return null; - } - this.cursor = node?.nextHashable || null; - return node; - } - clear() { - while (true) { - const node = this.sentinel.next; - if (node == this.sentinel) { - return; - } - if (node) { - node.unlink(); - } - } - } -}; - -// src/lostcity/server/PreloadedPacks.ts -var PRELOADED = /* @__PURE__ */ new Map(); -var PRELOADED_CRC = /* @__PURE__ */ new Map(); -function preloadClient() { - const allMaps = fs23.readdirSync("data/pack/client/maps"); - for (let i = 0; i < allMaps.length; i++) { - const name = allMaps[i]; - const map = new Uint8Array(fs23.readFileSync(`data/pack/client/maps/${name}`)); - const crc = Packet.getcrc(map, 0, map.length); - PRELOADED.set(name, map); - PRELOADED_CRC.set(name, crc); - } - const allSongs = fs23.readdirSync("data/pack/client/songs"); - for (let i = 0; i < allSongs.length; i++) { - const name = allSongs[i]; - const song = new Uint8Array(fs23.readFileSync(`data/pack/client/songs/${name}`)); - const crc = Packet.getcrc(song, 0, song.length); - PRELOADED.set(name, song); - PRELOADED_CRC.set(name, crc); - } - const allJingles = fs23.readdirSync("data/pack/client/jingles"); - for (let i = 0; i < allJingles.length; i++) { - const name = allJingles[i]; - const jingle = new Uint8Array(fs23.readFileSync(`data/pack/client/jingles/${name}`).subarray(4)); - const crc = Packet.getcrc(jingle, 0, jingle.length); - PRELOADED.set(name, jingle); - PRELOADED_CRC.set(name, crc); - } -} -async function preloadClientAsync() { - const fetchAll = async (type, name) => { - let data = new Uint8Array(await (await fetch(`data/pack/client/${type}/${name}`)).arrayBuffer()); - if (type === "jingles") { - data = data.subarray(4); - } - const crc = Packet.getcrc(data, 0, data.length); - PRELOADED.set(name, data); - PRELOADED_CRC.set(name, crc); - }; - const { jingles: jingles2, maps: maps2, songs: songs2 } = await Promise.resolve().then(() => (init_PreloadedDirs(), PreloadedDirs_exports)); - const allPacks = [ - ...maps2.map((name) => fetchAll("maps", name)), - ...songs2.map((name) => fetchAll("songs", name)), - ...jingles2.map((name) => fetchAll("jingles", name)) - ]; - await Promise.all(allPacks); -} - -// src/lostcity/network/outgoing/OutgoingMessage.ts -var OutgoingMessage = class extends Hashable { -}; - -// src/lostcity/network/outgoing/prot/ServerProtPriority.ts -var ServerProtPriority = class _ServerProtPriority { - static LOW = new _ServerProtPriority(); - static HIGH = new _ServerProtPriority(); -}; - -// src/lostcity/network/outgoing/model/IfClose.ts -var IfClose = class extends OutgoingMessage { - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/outgoing/model/UpdateUid192.ts -var UpdateUid192 = class extends OutgoingMessage { - // todo: low or high priority - constructor(uid) { - super(); - this.uid = uid; - } - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/outgoing/model/ResetAnims.ts -var ResetAnims = class extends OutgoingMessage { - priority = ServerProtPriority.HIGH; - // todo: low or high priority -}; - -// src/lostcity/network/outgoing/model/ResetClientVarCache.ts -var ResetClientVarCache = class extends OutgoingMessage { - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/outgoing/model/TutorialOpenChat.ts -var TutorialOpenChat = class extends OutgoingMessage { - constructor(component) { - super(); - this.component = component; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/outgoing/model/UpdateInvStopTransmit.ts -var UpdateInvStopTransmit = class extends OutgoingMessage { - constructor(component) { - super(); - this.component = component; - } - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/outgoing/model/VarpSmall.ts -var VarpSmall = class extends OutgoingMessage { - constructor(varp, value) { - super(); - this.varp = varp; - this.value = value; - } - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/outgoing/model/VarpLarge.ts -var VarpLarge = class extends OutgoingMessage { - constructor(varp, value) { - super(); - this.varp = varp; - this.value = value; - } - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/outgoing/model/MidiSong.ts -var MidiSong = class extends OutgoingMessage { - constructor(name, crc, length) { - super(); - this.name = name; - this.crc = crc; - this.length = length; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/outgoing/model/MidiJingle.ts -var MidiJingle = class extends OutgoingMessage { - constructor(delay, data) { - super(); - this.delay = delay; - this.data = data; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/outgoing/model/IfOpenSideOverlay.ts -var IfOpenSideOverlay = class extends OutgoingMessage { - constructor(component, tab) { - super(); - this.component = component; - this.tab = tab; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/outgoing/model/UnsetMapFlag.ts -var UnsetMapFlag = class extends OutgoingMessage { - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/outgoing/model/HintArrow.ts -var HintArrow = class extends OutgoingMessage { - // todo: is HINT_ARROW low or high priority? - constructor(type, nid, pid, x, z, y) { - super(); - this.type = type; - this.nid = nid; - this.pid = pid; - this.x = x; - this.z = z; - this.y = y; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/outgoing/model/LastLoginInfo.ts -var LastLoginInfo = class extends OutgoingMessage { - constructor(lastLoginIp, daysSinceLogin, daysSinceRecoveryChange, unreadMessageCount) { - super(); - this.lastLoginIp = lastLoginIp; - this.daysSinceLogin = daysSinceLogin; - this.daysSinceRecoveryChange = daysSinceRecoveryChange; - this.unreadMessageCount = unreadMessageCount; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/outgoing/model/MessageGame.ts -var MessageGame = class extends OutgoingMessage { - constructor(msg) { - super(); - this.msg = msg; - } - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/engine/zone/ZoneEvent.ts -var ZoneEvent = class { - type; - receiverId; - message; - constructor(type, receiverId, message) { - this.type = type; - this.receiverId = receiverId; - this.message = message; - } -}; - -// src/lostcity/engine/zone/ZoneEventType.ts -var ZoneEventType = /* @__PURE__ */ ((ZoneEventType2) => { - ZoneEventType2[ZoneEventType2["ENCLOSED"] = 0] = "ENCLOSED"; - ZoneEventType2[ZoneEventType2["FOLLOWS"] = 1] = "FOLLOWS"; - return ZoneEventType2; -})(ZoneEventType || {}); -var ZoneEventType_default = ZoneEventType; - -// src/lostcity/network/outgoing/model/UpdateZonePartialEnclosed.ts -var UpdateZonePartialEnclosed = class extends OutgoingMessage { - constructor(zoneX, zoneZ, originX, originZ, data) { - super(); - this.zoneX = zoneX; - this.zoneZ = zoneZ; - this.originX = originX; - this.originZ = originZ; - this.data = data; - } - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/outgoing/model/UpdateZoneFullFollows.ts -var UpdateZoneFullFollows = class extends OutgoingMessage { - constructor(zoneX, zoneZ, originX, originZ) { - super(); - this.zoneX = zoneX; - this.zoneZ = zoneZ; - this.originX = originX; - this.originZ = originZ; - } - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/outgoing/model/UpdateZonePartialFollows.ts -var UpdateZonePartialFollows = class extends OutgoingMessage { - constructor(zoneX, zoneZ, originX, originZ) { - super(); - this.zoneX = zoneX; - this.zoneZ = zoneZ; - this.originX = originX; - this.originZ = originZ; - } - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/outgoing/ZoneMessage.ts -var ZoneMessage = class extends OutgoingMessage { - constructor(coord) { - super(); - this.coord = coord; - } - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/outgoing/model/ObjAdd.ts -var ObjAdd = class extends ZoneMessage { - constructor(coord, obj, count) { - super(coord); - this.coord = coord; - this.obj = obj; - this.count = count; - } -}; - -// src/lostcity/network/outgoing/model/LocAddChange.ts -var LocAddChange = class extends ZoneMessage { - constructor(coord, loc, shape, angle) { - super(coord); - this.coord = coord; - this.loc = loc; - this.shape = shape; - this.angle = angle; - } -}; - -// src/lostcity/network/outgoing/model/LocDel.ts -var LocDel = class extends ZoneMessage { - constructor(coord, shape, angle) { - super(coord); - this.coord = coord; - this.shape = shape; - this.angle = angle; - } -}; - -// src/lostcity/network/outgoing/model/MapProjAnim.ts -var MapProjAnim = class extends ZoneMessage { - constructor(srcX, srcZ, dstX, dstZ, target, spotanim, srcHeight, dstHeight, startDelay, endDelay, peak, arc) { - super(Position.packZoneCoord(srcX, srcZ)); - this.srcX = srcX; - this.srcZ = srcZ; - this.dstX = dstX; - this.dstZ = dstZ; - this.target = target; - this.spotanim = spotanim; - this.srcHeight = srcHeight; - this.dstHeight = dstHeight; - this.startDelay = startDelay; - this.endDelay = endDelay; - this.peak = peak; - this.arc = arc; - } -}; - -// src/lostcity/network/outgoing/model/MapAnim.ts -var MapAnim = class extends ZoneMessage { - constructor(coord, spotanim, height, delay) { - super(coord); - this.coord = coord; - this.spotanim = spotanim; - this.height = height; - this.delay = delay; - } -}; - -// src/lostcity/network/outgoing/model/ObjDel.ts -var ObjDel = class extends ZoneMessage { - constructor(coord, obj) { - super(coord); - this.coord = coord; - this.obj = obj; - } -}; - -// src/lostcity/network/outgoing/model/ObjCount.ts -var ObjCount = class extends ZoneMessage { - constructor(coord, obj, oldCount, newCount) { - super(coord); - this.coord = coord; - this.obj = obj; - this.oldCount = oldCount; - this.newCount = newCount; - } -}; - -// src/lostcity/network/outgoing/model/ObjReveal.ts -var ObjReveal = class extends ZoneMessage { - constructor(coord, obj, count, receiverId) { - super(coord); - this.coord = coord; - this.obj = obj; - this.count = count; - this.receiverId = receiverId; - } -}; - -// src/lostcity/network/outgoing/model/LocAnim.ts -var LocAnim = class extends ZoneMessage { - constructor(coord, shape, angle, seq) { - super(coord); - this.coord = coord; - this.shape = shape; - this.angle = angle; - this.seq = seq; - } -}; - -// src/lostcity/network/outgoing/model/LocMerge.ts -var LocMerge = class extends ZoneMessage { - constructor(srcX, srcZ, shape, angle, locId, startCycle, endCycle, pid, east, south, west, north) { - super(Position.packZoneCoord(srcX, srcZ)); - this.srcX = srcX; - this.srcZ = srcZ; - this.shape = shape; - this.angle = angle; - this.locId = locId; - this.startCycle = startCycle; - this.endCycle = endCycle; - this.pid = pid; - this.east = east; - this.south = south; - this.west = west; - this.north = north; - } -}; - -// src/lostcity/network/outgoing/codec/MessageEncoder.ts -var MessageEncoder = class { - test(_) { - return this.prot.length; - } -}; - -// src/lostcity/network/225/outgoing/codec/IfOpenChatModalEncoder.ts -var IfOpenChatModalEncoder = class extends MessageEncoder { - prot = ServerProt.IF_OPENCHATMODAL; - encode(buf, message) { - buf.p2(message.component); - } -}; - -// src/lostcity/network/outgoing/model/IfOpenChatModal.ts -var IfOpenChatModal = class extends OutgoingMessage { - constructor(component) { - super(); - this.component = component; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/outgoing/model/PlayerInfo.ts -var PlayerInfo = class extends OutgoingMessage { - constructor(buildArea, level, x, z, originX, originZ, uid, mask, tele, jump2, walkDir, runDir, deltaX, deltaZ, changedLevel) { - super(); - this.buildArea = buildArea; - this.level = level; - this.x = x; - this.z = z; - this.originX = originX; - this.originZ = originZ; - this.uid = uid; - this.mask = mask; - this.tele = tele; - this.jump = jump2; - this.walkDir = walkDir; - this.runDir = runDir; - this.deltaX = deltaX; - this.deltaZ = deltaZ; - this.changedLevel = changedLevel; - } - priority = ServerProtPriority.HIGH; - accumulator = 0; -}; - -// src/lostcity/network/225/outgoing/codec/PlayerInfoEncoder.ts -var PlayerInfoEncoder = class _PlayerInfoEncoder extends MessageEncoder { - static BITS_NEW = 11 + 5 + 5 + 1 + 1; - static BITS_IDLE = 1; - static BITS_RUN = 1 + 2 + 3 + 3 + 1; - static BITS_WALK = 1 + 2 + 3 + 1; - static BITS_EXTENDED = 1 + 2; - static BYTES_LIMIT = 4997; - prot = ServerProt.PLAYER_INFO; - encode(buf, message) { - const buildArea = message.buildArea; - if (message.changedLevel || message.deltaX > buildArea.viewDistance || message.deltaZ > buildArea.viewDistance) { - buildArea.players.clear(); - buildArea.lastResize = 0; - buildArea.viewDistance = BuildArea.PREFERRED_VIEW_DISTANCE; - } else { - buildArea.resize(); - } - this.writeLocalPlayer(buf, message); - this.writePlayers(buf, message); - this.writeNewPlayers(buf, message); - const extended = buildArea.extendedInfo; - if (extended.size > 0) { - for (const info of extended) { - const other = World_default.getPlayerByUid(info.id); - if (!other) { - buf.p1(0); - continue; - } - this.writeExtendedInfo(other, message, buf, info.id === message.uid, info.added); - } - } - buildArea.clearExtended(); - } - test(_) { - return _PlayerInfoEncoder.BYTES_LIMIT; - } - willFit(message, buf, bitsToAdd, bytesToAdd) { - return (buf.bitPos + bitsToAdd + 7 >>> 3) + (message.accumulator + bytesToAdd) <= _PlayerInfoEncoder.BYTES_LIMIT; - } - writeLocalPlayer(buf, message) { - const { buildArea, uid, level, x, z, tele, jump: jump2, walkDir, runDir } = message; - const player = World_default.getPlayerByUid(uid); - if (!player) { - return; - } - const extendedInfoSize = this.calculateExtendedInfo(player, message, true, false); - const extendedInfo = extendedInfoSize > 0; - buf.bits(); - buf.pBit(1, tele || runDir !== -1 || walkDir !== -1 || extendedInfo ? 1 : 0); - if (tele) { - buf.pBit(2, 3); - buf.pBit(2, level); - buf.pBit(7, Position.local(x, player.originX)); - buf.pBit(7, Position.local(z, player.originZ)); - buf.pBit(1, jump2 ? 1 : 0); - buf.pBit(1, extendedInfo ? 1 : 0); - } else if (runDir !== -1) { - buf.pBit(2, 2); - buf.pBit(3, walkDir); - buf.pBit(3, runDir); - buf.pBit(1, extendedInfo ? 1 : 0); - } else if (walkDir !== -1) { - buf.pBit(2, 1); - buf.pBit(3, walkDir); - buf.pBit(1, extendedInfo ? 1 : 0); - } else if (extendedInfo) { - buf.pBit(2, 0); - } - if (extendedInfo) { - buildArea.extendedInfo.add({ id: uid, added: false }); - message.accumulator += extendedInfoSize; - } - } - writePlayers(buf, message) { - const buildArea = message.buildArea; - buf.pBit(8, buildArea.players.size); - for (const uid of buildArea.players) { - const other = World_default.getPlayerByUid(uid); - if (!other || other.tele || other.level !== message.level || !Position.isWithinDistanceSW(message, other, buildArea.viewDistance) || !other.checkLifeCycle(World_default.currentTick)) { - buf.pBit(1, 1); - buf.pBit(2, 3); - buildArea.players.delete(uid); - continue; - } - const extendedInfoSize = this.calculateExtendedInfo(other, message, false, false); - let extendedInfo = extendedInfoSize > 0; - const { walkDir, runDir } = other; - let bits = _PlayerInfoEncoder.BITS_IDLE; - if (runDir !== -1) { - bits = _PlayerInfoEncoder.BITS_RUN; - } else if (walkDir !== -1) { - bits = _PlayerInfoEncoder.BITS_WALK; - } else if (extendedInfo) { - bits = _PlayerInfoEncoder.BITS_EXTENDED; - } - if (!this.willFit(message, buf, bits, extendedInfoSize)) { - extendedInfo = false; - } - buf.pBit(1, runDir !== -1 || walkDir !== -1 || extendedInfo ? 1 : 0); - if (runDir !== -1) { - buf.pBit(2, 2); - buf.pBit(3, walkDir); - buf.pBit(3, runDir); - buf.pBit(1, extendedInfo ? 1 : 0); - } else if (walkDir !== -1) { - buf.pBit(2, 1); - buf.pBit(3, walkDir); - buf.pBit(1, extendedInfo ? 1 : 0); - } else if (extendedInfo) { - buf.pBit(2, 0); - } - if (extendedInfo) { - buildArea.extendedInfo.add({ id: uid, added: false }); - message.accumulator += extendedInfoSize; - } - } - } - writeNewPlayers(buf, message) { - const buildArea = message.buildArea; - for (const other of buildArea.getNearbyPlayers(message.uid, message.x, message.z, message.originX, message.originZ)) { - const extendedInfoSize = this.calculateExtendedInfo(other, message, false, true); - const extendedInfo = extendedInfoSize > 0; - if (!this.willFit(message, buf, _PlayerInfoEncoder.BITS_NEW + 11, extendedInfoSize)) { - break; - } - buf.pBit(11, other.pid); - buf.pBit(5, other.x - message.x); - buf.pBit(5, other.z - message.z); - buf.pBit(1, other.jump ? 1 : 0); - buf.pBit(1, extendedInfo ? 1 : 0); - if (extendedInfo) { - buildArea.extendedInfo.add({ id: other.uid, added: true }); - message.accumulator += extendedInfoSize; - } - buildArea.players.add(other.uid); - } - if (buildArea.extendedInfo.size > 0) { - buf.pBit(11, 2047); - } - buf.bytes(); - } - writeExtendedInfo(player, message, buf, self2 = false, newlyObserved = false) { - let mask = player.mask; - if (newlyObserved) { - if (player.orientationX !== -1 || player.faceX !== -1) { - mask |= Player.FACE_COORD; - } - if (player.faceEntity !== -1) { - mask |= Player.FACE_ENTITY; - } - } - if (self2 && (mask & Player.CHAT) != 0) { - mask &= ~Player.CHAT; - } - if (message.buildArea.hasAppearance(player.uid, player.lastAppearance) || !player.appearance) { - mask &= ~Player.APPEARANCE; - } else { - mask |= Player.APPEARANCE; - } - if (mask > 255) { - mask |= Player.BIG_UPDATE; - } - buf.p1(mask & 255); - if (mask & Player.BIG_UPDATE) { - buf.p1(mask >> 8); - } - if (mask & Player.APPEARANCE) { - buf.p1(player.appearance.length); - buf.pdata(player.appearance, 0, player.appearance.length); - message.buildArea.saveAppearance(player.uid, player.lastAppearance); - } - if (mask & Player.ANIM) { - buf.p2(player.animId); - buf.p1(player.animDelay); - } - if (mask & Player.FACE_ENTITY) { - if (player.faceEntity !== -1) { - player.alreadyFacedEntity = true; - } - buf.p2(player.faceEntity); - } - if (mask & Player.SAY) { - buf.pjstr(player.chat ?? ""); - } - if (mask & Player.DAMAGE) { - buf.p1(player.damageTaken); - buf.p1(player.damageType); - buf.p1(player.levels[PlayerStat_default.HITPOINTS]); - buf.p1(player.baseLevels[PlayerStat_default.HITPOINTS]); - } - if (mask & Player.FACE_COORD) { - if (newlyObserved && player.orientationX !== -1) { - buf.p2(player.orientationX); - buf.p2(player.orientationZ); - } else { - buf.p2(player.faceX); - buf.p2(player.faceZ); - } - } - if (mask & Player.CHAT) { - buf.p1(player.messageColor); - buf.p1(player.messageEffect); - buf.p1(player.messageType); - buf.p1(player.message.length); - buf.pdata(player.message, 0, player.message.length); - } - if (mask & Player.SPOTANIM) { - buf.p2(player.graphicId); - buf.p2(player.graphicHeight); - buf.p2(player.graphicDelay); - } - if (mask & Player.EXACT_MOVE) { - buf.p1(player.exactStartX - Position.zoneOrigin(message.originX)); - buf.p1(player.exactStartZ - Position.zoneOrigin(message.originZ)); - buf.p1(player.exactEndX - Position.zoneOrigin(message.originX)); - buf.p1(player.exactEndZ - Position.zoneOrigin(message.originZ)); - buf.p2(player.exactMoveStart); - buf.p2(player.exactMoveEnd); - buf.p1(player.exactMoveDirection); - } - } - calculateExtendedInfo(player, message, self2 = false, newlyObserved = false) { - let length = 0; - let mask = player.mask; - if (newlyObserved) { - if (player.orientationX !== -1 || player.faceX !== -1) { - mask |= Player.FACE_COORD; - } - if (player.faceEntity !== -1) { - mask |= Player.FACE_ENTITY; - } - } - if (self2 && (mask & Player.CHAT) != 0) { - mask &= ~Player.CHAT; - } - if (message.buildArea.hasAppearance(player.uid, player.lastAppearance) || !player.appearance) { - mask &= ~Player.APPEARANCE; - } else { - mask |= Player.APPEARANCE; - } - if (mask > 255) { - mask |= Player.BIG_UPDATE; - } - if (mask === 0) { - return 0; - } - length += 1; - if (mask & Player.BIG_UPDATE) { - length += 1; - } - if (mask & Player.APPEARANCE) { - length += 1 + player.appearance.length; - } - if (mask & Player.ANIM) { - length += 3; - } - if (mask & Player.FACE_ENTITY) { - length += 2; - } - if (mask & Player.SAY) { - length += 1 + player.chat.length; - } - if (mask & Player.DAMAGE) { - length += 4; - } - if (mask & Player.FACE_COORD) { - length += 4; - } - if (mask & Player.CHAT) { - length += 4 + player.message.length; - } - if (mask & Player.SPOTANIM) { - length += 6; - } - if (mask & Player.EXACT_MOVE) { - length += 9; - } - return length; - } -}; - -// src/lostcity/network/outgoing/model/RebuildNormal.ts -var RebuildNormal = class extends OutgoingMessage { - constructor(zoneX, zoneZ) { - super(); - this.zoneX = zoneX; - this.zoneZ = zoneZ; - } - priority = ServerProtPriority.HIGH; - get mapsquares() { - const minX = this.zoneX - 6; - const maxX = this.zoneX + 6; - const minZ = this.zoneZ - 6; - const maxZ = this.zoneZ + 6; - const result = /* @__PURE__ */ new Set(); - for (let x = minX; x <= maxX; x++) { - const mx = Position.mapsquare(x << 3); - for (let z = minZ; z <= maxZ; z++) { - const mz = Position.mapsquare(z << 3); - result.add(mx << 8 | mz); - } - } - return result; - } -}; - -// src/lostcity/network/225/outgoing/codec/RebuildNormalEncoder.ts -var RebuildNormalEncoder = class extends MessageEncoder { - prot = ServerProt.REBUILD_NORMAL; - encode(buf, message) { - buf.p2(message.zoneX); - buf.p2(message.zoneZ); - for (const packed of message.mapsquares) { - const x = packed >> 8; - const z = packed & 255; - buf.p1(x); - buf.p1(z); - buf.p4(PRELOADED_CRC.get(`m${x}_${z}`) ?? 0); - buf.p4(PRELOADED_CRC.get(`l${x}_${z}`) ?? 0); - } - } - test(message) { - return 2 + 2 + message.mapsquares.size * (1 + 1 + 4 + 4); - } -}; - -// src/lostcity/network/outgoing/model/DataLand.ts -var DataLand = class extends OutgoingMessage { - constructor(x, z, offset, length, data) { - super(); - this.x = x; - this.z = z; - this.offset = offset; - this.length = length; - this.data = data; - } - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/225/outgoing/codec/DataLandEncoder.ts -var DataLandEncoder = class extends MessageEncoder { - prot = ServerProt.DATA_LAND; - encode(buf, message) { - buf.p1(message.x); - buf.p1(message.z); - buf.p2(message.offset); - buf.p2(message.length); - buf.pdata(message.data, 0, message.data.length); - } - test(message) { - return 1 + 1 + 2 + 2 + message.data.length; - } -}; - -// src/lostcity/network/outgoing/model/DataLandDone.ts -var DataLandDone = class extends OutgoingMessage { - constructor(x, z) { - super(); - this.x = x; - this.z = z; - } - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/225/outgoing/codec/DataLandDoneEncoder.ts -var DataLandDoneEncoder = class extends MessageEncoder { - prot = ServerProt.DATA_LAND_DONE; - encode(buf, message) { - buf.p1(message.x); - buf.p1(message.z); - } -}; - -// src/lostcity/network/outgoing/model/DataLoc.ts -var DataLoc = class extends OutgoingMessage { - constructor(x, z, offset, length, data) { - super(); - this.x = x; - this.z = z; - this.offset = offset; - this.length = length; - this.data = data; - } - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/225/outgoing/codec/DataLocEncoder.ts -var DataLocEncoder = class extends MessageEncoder { - prot = ServerProt.DATA_LOC; - encode(buf, message) { - buf.p1(message.x); - buf.p1(message.z); - buf.p2(message.offset); - buf.p2(message.length); - buf.pdata(message.data, 0, message.data.length); - } - test(message) { - return 1 + 1 + 2 + 2 + message.data.length; - } -}; - -// src/lostcity/network/outgoing/model/DataLocDone.ts -var DataLocDone = class extends OutgoingMessage { - constructor(x, z) { - super(); - this.x = x; - this.z = z; - } - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/225/outgoing/codec/DataLocDoneEncoder.ts -var DataLocDoneEncoder = class extends MessageEncoder { - prot = ServerProt.DATA_LOC_DONE; - encode(buf, message) { - buf.p1(message.x); - buf.p1(message.z); - } -}; - -// src/lostcity/network/outgoing/model/CamLookAt.ts -var CamLookAt = class extends OutgoingMessage { - constructor(x, z, height, speed, multiplier) { - super(); - this.x = x; - this.z = z; - this.height = height; - this.speed = speed; - this.multiplier = multiplier; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/CamLookAtEncoder.ts -var CamLookAtEncoder = class extends MessageEncoder { - prot = ServerProt.CAM_LOOKAT; - encode(buf, message) { - buf.p1(message.x); - buf.p1(message.z); - buf.p2(message.height); - buf.p1(message.speed); - buf.p1(message.multiplier); - } -}; - -// src/lostcity/network/outgoing/model/CamMoveTo.ts -var CamMoveTo = class extends OutgoingMessage { - constructor(x, z, height, speed, multiplier) { - super(); - this.x = x; - this.z = z; - this.height = height; - this.speed = speed; - this.multiplier = multiplier; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/CamMoveToEncoder.ts -var CamMoveToEncoder = class extends MessageEncoder { - prot = ServerProt.CAM_MOVETO; - encode(buf, message) { - buf.p1(message.x); - buf.p1(message.z); - buf.p2(message.height); - buf.p1(message.speed); - buf.p1(message.multiplier); - } -}; - -// src/lostcity/network/outgoing/model/CamReset.ts -var CamReset = class extends OutgoingMessage { - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/CamResetEncoder.ts -var CamResetEncoder = class extends MessageEncoder { - prot = ServerProt.CAM_RESET; - encode(_, __) { - } -}; - -// src/lostcity/network/outgoing/model/CamShake.ts -var CamShake = class extends OutgoingMessage { - constructor(type, jitter, amplitude, frequency) { - super(); - this.type = type; - this.jitter = jitter; - this.amplitude = amplitude; - this.frequency = frequency; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/CamShakeEncoder.ts -var CamShakeEncoder = class extends MessageEncoder { - prot = ServerProt.CAM_SHAKE; - encode(buf, message) { - buf.p1(message.type); - buf.p1(message.jitter); - buf.p1(message.amplitude); - buf.p1(message.frequency); - } -}; - -// src/lostcity/network/outgoing/model/ChatFilterSettings.ts -var ChatFilterSettings = class extends OutgoingMessage { - constructor(publicChat, privateChat, tradeDuel) { - super(); - this.publicChat = publicChat; - this.privateChat = privateChat; - this.tradeDuel = tradeDuel; - } - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/225/outgoing/codec/ChatFilterSettingsEncoder.ts -var ChatFilterSettingsEncoder = class extends MessageEncoder { - prot = ServerProt.CHAT_FILTER_SETTINGS; - encode(buf, message) { - buf.p1(message.publicChat); - buf.p1(message.privateChat); - buf.p1(message.tradeDuel); - } -}; - -// src/lostcity/network/outgoing/model/EnableTracking.ts -var EnableTracking = class extends OutgoingMessage { - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/EnableTrackingEncoder.ts -var EnableTrackingEncoder = class extends MessageEncoder { - prot = ServerProt.ENABLE_TRACKING; - encode(_, __) { - } -}; - -// src/lostcity/network/outgoing/model/FinishTracking.ts -var FinishTracking = class extends OutgoingMessage { - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/FinishTrackingEncoder.ts -var FinishTrackingEncoder = class extends MessageEncoder { - prot = ServerProt.FINISH_TRACKING; - encode(_, __) { - } -}; - -// src/lostcity/network/225/outgoing/codec/HintArrowEncoder.ts -var HintArrowEncoder = class extends MessageEncoder { - prot = ServerProt.HINT_ARROW; - encode(buf, message) { - const { type, nid, pid, x, z, y } = message; - if (type === 1) { - buf.p1(type); - buf.p2(nid); - buf.p2(0); - buf.p1(0); - } else if (type >= 2 && type <= 6) { - buf.p1(type); - buf.p2(x); - buf.p2(z); - buf.p1(y); - } else if (type === 10) { - buf.p1(type); - buf.p2(pid); - buf.p2(0); - buf.p1(0); - } else if (type === -1) { - buf.p1(-1); - buf.p2(0); - buf.p2(0); - buf.p1(0); - } - } -}; - -// src/lostcity/network/225/outgoing/codec/IfCloseEncoder.ts -var IfCloseEncoder = class extends MessageEncoder { - prot = ServerProt.IF_CLOSE; - encode(_, __) { - } -}; - -// src/lostcity/network/outgoing/model/IfOpenMainModal.ts -var IfOpenMainModal = class extends OutgoingMessage { - constructor(component) { - super(); - this.component = component; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/IfOpenMainModalEncoder.ts -var IfOpenMainModalEncoder = class extends MessageEncoder { - prot = ServerProt.IF_OPENMAINMODAL; - encode(buf, message) { - buf.p2(message.component); - } -}; - -// src/lostcity/network/outgoing/model/IfOpenMainSideModal.ts -var IfOpenMainSideModal = class extends OutgoingMessage { - constructor(main, side) { - super(); - this.main = main; - this.side = side; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/IfOpenMainSideModalEncoder.ts -var IfOpenMainSideModalEncoder = class extends MessageEncoder { - prot = ServerProt.IF_OPENMAINSIDEMODAL; - encode(buf, message) { - buf.p2(message.main); - buf.p2(message.side); - } -}; - -// src/lostcity/network/outgoing/model/IfOpenSideModal.ts -var IfOpenSideModal = class extends OutgoingMessage { - constructor(component) { - super(); - this.component = component; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/IfOpenSideModalEncoder.ts -var IfOpenSideModalEncoder = class extends MessageEncoder { - prot = ServerProt.IF_OPENSIDEMODAL; - encode(buf, message) { - buf.p2(message.component); - } -}; - -// src/lostcity/network/225/outgoing/codec/IfOpenSideOverlayEncoder.ts -var IfOpenSideOverlayEncoder = class extends MessageEncoder { - prot = ServerProt.IF_OPENSIDEOVERLAY; - encode(buf, message) { - buf.p2(message.component); - buf.p1(message.tab); - } -}; - -// src/lostcity/network/outgoing/model/IfSetAnim.ts -var IfSetAnim = class extends OutgoingMessage { - constructor(component, seq) { - super(); - this.component = component; - this.seq = seq; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/IfSetAnimEncoder.ts -var IfSetAnimEncoder = class extends MessageEncoder { - prot = ServerProt.IF_SETANIM; - encode(buf, message) { - buf.p2(message.component); - buf.p2(message.seq); - } -}; - -// src/lostcity/network/outgoing/model/IfSetColour.ts -var IfSetColour = class extends OutgoingMessage { - constructor(component, colour) { - super(); - this.component = component; - this.colour = colour; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/IfSetColourEncoder.ts -var IfSetColourEncoder = class extends MessageEncoder { - prot = ServerProt.IF_SETCOLOUR; - encode(buf, message) { - buf.p2(message.component); - buf.p2(message.colour); - } -}; - -// src/lostcity/network/outgoing/model/IfSetHide.ts -var IfSetHide = class extends OutgoingMessage { - constructor(component, hidden) { - super(); - this.component = component; - this.hidden = hidden; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/IfSetHideEncoder.ts -var IfSetHideEncoder = class extends MessageEncoder { - prot = ServerProt.IF_SETHIDE; - encode(buf, message) { - buf.p2(message.component); - buf.pbool(message.hidden); - } -}; - -// src/lostcity/network/outgoing/model/IfSetModel.ts -var IfSetModel = class extends OutgoingMessage { - constructor(component, model) { - super(); - this.component = component; - this.model = model; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/IfSetModelEncoder.ts -var IfSetModelEncoder = class extends MessageEncoder { - prot = ServerProt.IF_SETMODEL; - encode(buf, message) { - buf.p2(message.component); - buf.p2(message.model); - } -}; - -// src/lostcity/network/outgoing/model/IfSetNpcHead.ts -var IfSetNpcHead = class extends OutgoingMessage { - constructor(component, npc) { - super(); - this.component = component; - this.npc = npc; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/IfSetNpcHeadEncoder.ts -var IfSetNpcHeadEncoder = class extends MessageEncoder { - prot = ServerProt.IF_SETNPCHEAD; - encode(buf, message) { - buf.p2(message.component); - buf.p2(message.npc); - } -}; - -// src/lostcity/network/outgoing/model/IfSetObject.ts -var IfSetObject = class extends OutgoingMessage { - constructor(component, obj, scale) { - super(); - this.component = component; - this.obj = obj; - this.scale = scale; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/IfSetObjectEncoder.ts -var IfSetObjectEncoder = class extends MessageEncoder { - prot = ServerProt.IF_SETOBJECT; - encode(buf, message) { - buf.p2(message.component); - buf.p2(message.obj); - buf.p2(message.scale); - } -}; - -// src/lostcity/network/outgoing/model/IfSetPlayerHead.ts -var IfSetPlayerHead = class extends OutgoingMessage { - constructor(component) { - super(); - this.component = component; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/IfSetPlayerHeadEncoder.ts -var IfSetPlayerHeadEncoder = class extends MessageEncoder { - prot = ServerProt.IF_SETPLAYERHEAD; - encode(buf, message) { - buf.p2(message.component); - } -}; - -// src/lostcity/network/outgoing/model/IfSetPosition.ts -var IfSetPosition = class extends OutgoingMessage { - constructor(component, x, y) { - super(); - this.component = component; - this.x = x; - this.y = y; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/IfSetPositionEncoder.ts -var IfSetPositionEncoder = class extends MessageEncoder { - prot = ServerProt.IF_SETPOSITION; - encode(buf, message) { - buf.p2(message.component); - buf.p2(message.x); - buf.p2(message.y); - } -}; - -// src/lostcity/network/outgoing/model/IfSetRecol.ts -var IfSetRecol = class extends OutgoingMessage { - constructor(component, src, dst) { - super(); - this.component = component; - this.src = src; - this.dst = dst; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/IfSetRecolEncoder.ts -var IfSetRecolEncoder = class extends MessageEncoder { - prot = ServerProt.IF_SETRECOL; - encode(buf, message) { - buf.p2(message.component); - buf.p2(message.src); - buf.p2(message.dst); - } -}; - -// src/lostcity/network/outgoing/model/IfSetText.ts -var IfSetText = class extends OutgoingMessage { - constructor(component, text) { - super(); - this.component = component; - this.text = text; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/IfSetTextEncoder.ts -var IfSetTextEncoder = class extends MessageEncoder { - prot = ServerProt.IF_SETTEXT; - encode(buf, message) { - buf.p2(message.component); - buf.pjstr(message.text); - } - test(message) { - return 2 + 1 + message.text.length; - } -}; - -// src/lostcity/network/outgoing/model/IfShowSide.ts -var IfShowSide = class extends OutgoingMessage { - constructor(tab) { - super(); - this.tab = tab; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/IfShowSideEncoder.ts -var IfShowSideEncoder = class extends MessageEncoder { - prot = ServerProt.IF_SHOWSIDE; - encode(buf, message) { - buf.p1(message.tab); - } -}; - -// src/lostcity/network/225/outgoing/codec/LastLoginInfoEncoder.ts -var LastLoginInfoEncoder = class extends MessageEncoder { - prot = ServerProt.LAST_LOGIN_INFO; - encode(buf, message) { - buf.p4(message.lastLoginIp); - buf.p2(message.daysSinceLogin); - buf.p1(message.daysSinceRecoveryChange); - buf.p2(message.unreadMessageCount); - } -}; - -// src/lostcity/network/225/outgoing/prot/ZoneProt.ts -var ZoneProt = class _ZoneProt extends ServerProt { - // zone protocol - static LOC_MERGE = new _ZoneProt(23, 14); - // based on runescript command p_locmerge - static LOC_ANIM = new _ZoneProt(42, 4); - // NXT naming - static OBJ_DEL = new _ZoneProt(49, 3); - // NXT naming - static OBJ_REVEAL = new _ZoneProt(50, 7); - // NXT naming - static LOC_ADD_CHANGE = new _ZoneProt(59, 4); - // NXT naming - static MAP_PROJANIM = new _ZoneProt(69, 15); - // NXT naming - static LOC_DEL = new _ZoneProt(76, 2); - // NXT naming - static OBJ_COUNT = new _ZoneProt(151, 7); - // NXT naming - static MAP_ANIM = new _ZoneProt(191, 6); - // NXT naming - static OBJ_ADD = new _ZoneProt(223, 5); - // NXT naming -}; - -// src/lostcity/network/outgoing/codec/ZoneMessageEncoder.ts -var ZoneMessageEncoder = class extends MessageEncoder { - enclose(message) { - const buf = new Packet(new Uint8Array(1 + this.prot.length)); - buf.p1(this.prot.id); - this.encode(buf, message); - return buf.data; - } -}; - -// src/lostcity/network/225/outgoing/codec/LocAddChangeEncoder.ts -var LocAddChangeEncoder = class extends ZoneMessageEncoder { - prot = ZoneProt.LOC_ADD_CHANGE; - encode(buf, message) { - buf.p1(message.coord); - buf.p1(message.shape << 2 | message.angle & 3); - buf.p2(message.loc); - } -}; - -// src/lostcity/network/225/outgoing/codec/LocAnimEncoder.ts -var LocAnimEncoder = class extends ZoneMessageEncoder { - prot = ZoneProt.LOC_ANIM; - encode(buf, message) { - buf.p1(message.coord); - buf.p1(message.shape << 2 | message.angle & 3); - buf.p2(message.seq); - } -}; - -// src/lostcity/network/225/outgoing/codec/LocDelEncoder.ts -var LocDelEncoder = class extends ZoneMessageEncoder { - prot = ZoneProt.LOC_DEL; - encode(buf, message) { - buf.p1(message.coord); - buf.p1(message.shape << 2 | message.angle & 3); - } -}; - -// src/lostcity/network/225/outgoing/codec/LocMergeEncoder.ts -var LocMergeEncoder = class extends ZoneMessageEncoder { - prot = ZoneProt.LOC_MERGE; - encode(buf, message) { - buf.p1(message.coord); - buf.p1(message.shape << 2 | message.angle & 3); - buf.p2(message.locId); - buf.p2(message.startCycle); - buf.p2(message.endCycle); - buf.p2(message.pid); - buf.p1(message.east - message.srcX); - buf.p1(message.south - message.srcZ); - buf.p1(message.west - message.srcX); - buf.p1(message.north - message.srcZ); - } -}; - -// src/lostcity/network/outgoing/model/Logout.ts -var Logout = class extends OutgoingMessage { - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/225/outgoing/codec/LogoutEncoder.ts -var LogoutEncoder = class extends MessageEncoder { - prot = ServerProt.LOGOUT; - encode(_, __) { - } -}; - -// src/lostcity/network/225/outgoing/codec/MapAnimEncoder.ts -var MapAnimEncoder = class extends ZoneMessageEncoder { - prot = ZoneProt.MAP_ANIM; - encode(buf, message) { - buf.p1(message.coord); - buf.p2(message.spotanim); - buf.p1(message.height); - buf.p2(message.delay); - } -}; - -// src/lostcity/network/225/outgoing/codec/MapProjAnimEncoder.ts -var MapProjAnimEncoder = class extends ZoneMessageEncoder { - prot = ZoneProt.MAP_PROJANIM; - // variables fully broken out for now - //coord $from, coord $to, spotanim $spotanim, int $fromHeight, int $toHeight, int $startDelay, int $endDelay, int $peak, int $arc - encode(buf, message) { - buf.p1(message.coord); - buf.p1(message.dstX - message.srcX); - buf.p1(message.dstZ - message.srcZ); - buf.p2(message.target); - buf.p2(message.spotanim); - buf.p1(message.srcHeight); - buf.p1(message.dstHeight); - buf.p2(message.startDelay); - buf.p2(message.endDelay); - buf.p1(message.peak); - buf.p1(message.arc); - } -}; - -// src/lostcity/network/225/outgoing/codec/MessageGameEncoder.ts -var MessageGameEncoder = class extends MessageEncoder { - prot = ServerProt.MESSAGE_GAME; - encode(buf, message) { - buf.pjstr(message.msg); - } - test(message) { - return 1 + message.msg.length; - } -}; - -// src/jagex2/wordenc/WordPack.ts -var WordPack = class { - // prettier-ignore - static CHAR_LOOKUP = [ - " ", - "e", - "t", - "a", - "o", - "i", - "h", - "n", - "s", - "r", - "d", - "l", - "u", - "m", - "w", - "c", - "y", - "f", - "g", - "p", - "b", - "v", - "k", - "x", - "j", - "q", - "z", - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9", - " ", - "!", - "?", - ".", - ",", - ":", - ";", - "(", - ")", - "-", - "&", - "*", - "\\", - "'", - "@", - "#", - "+", - "=", - "\xA3", - "$", - "%", - '"', - "[", - "]" - ]; - static unpack(packet, length) { - const charBuffer = []; - let pos = 0; - let carry = -1; - let nibble; - for (let i = 0; i < length && pos < 80; i++) { - const data = packet.g1(); - nibble = data >> 4 & 15; - if (carry !== -1) { - charBuffer[pos++] = this.CHAR_LOOKUP[(carry << 4) + nibble - 195]; - carry = -1; - } else if (nibble < 13) { - charBuffer[pos++] = this.CHAR_LOOKUP[nibble]; - } else { - carry = nibble; - } - nibble = data & 15; - if (carry != -1) { - charBuffer[pos++] = this.CHAR_LOOKUP[(carry << 4) + nibble - 195]; - carry = -1; - } else if (nibble < 13) { - charBuffer[pos++] = this.CHAR_LOOKUP[nibble]; - } else { - carry = nibble; - } - } - return this.toSentenceCase(charBuffer.slice(0, pos).join("")); - } - static pack(packet, input) { - if (input.length > 80) { - input = input.substring(0, 80); - } - input = input.toLowerCase(); - let carry = -1; - for (let i = 0; i < input.length; i++) { - const char = input.charAt(i); - let index = 0; - for (let j = 0; j < this.CHAR_LOOKUP.length; j++) { - if (char === this.CHAR_LOOKUP[j]) { - index = j; - break; - } - } - if (index > 12) { - index += 195; - } - if (carry == -1) { - if (index < 13) { - carry = index; - } else { - packet.p1(index); - } - } else if (index < 13) { - packet.p1((carry << 4) + index); - carry = -1; - } else { - packet.p1((carry << 4) + (index >> 4)); - carry = index & 15; - } - } - if (carry != -1) { - packet.p1(carry << 4); - } - } - static toSentenceCase(input) { - const chars = [...input.toLowerCase()]; - let punctuation = true; - for (let index = 0; index < chars.length; index++) { - const char = chars[index]; - if (punctuation && char >= "a" && char <= "z") { - chars[index] = char.toUpperCase(); - punctuation = false; - } - if (char === "." || char === "!") { - punctuation = true; - } - } - return chars.join(""); - } -}; - -// src/lostcity/network/225/outgoing/codec/MessagePrivateEncoder.ts -var MessagePrivateEncoder = class extends MessageEncoder { - prot = ServerProt.MESSAGE_PRIVATE; - encode(buf, message) { - buf.p8(message.from); - buf.p4(message.messageId); - buf.p1(message.staffModLevel); - WordPack.pack(buf, WordEnc.filter(message.msg)); - } - test(message) { - return 8 + 4 + 1 + 1 + message.msg.length; - } -}; - -// src/lostcity/network/outgoing/model/MessagePrivate.ts -var MessagePrivate = class extends OutgoingMessage { - constructor(from, messageId, staffModLevel, msg) { - super(); - this.from = from; - this.messageId = messageId; - this.staffModLevel = staffModLevel; - this.msg = msg; - } - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/225/outgoing/codec/MidiJingleEncoder.ts -var MidiJingleEncoder = class extends MessageEncoder { - prot = ServerProt.MIDI_JINGLE; - encode(buf, message) { - buf.p2(message.delay); - buf.p4(message.data.length); - buf.pdata(message.data, 0, message.data.length); - } - test(message) { - return 2 + 4 + message.data.length; - } -}; - -// src/lostcity/network/225/outgoing/codec/MidiSongEncoder.ts -var MidiSongEncoder = class extends MessageEncoder { - prot = ServerProt.MIDI_SONG; - encode(buf, message) { - buf.pjstr(message.name); - buf.p4(message.crc); - buf.p4(message.length); - } - test(message) { - return 1 + message.name.length + 4 + 4; - } -}; - -// src/lostcity/network/225/outgoing/codec/ObjAddEncoder.ts -var ObjAddEncoder = class extends ZoneMessageEncoder { - prot = ZoneProt.OBJ_ADD; - encode(buf, message) { - buf.p1(message.coord); - buf.p2(message.obj); - buf.p2(Math.min(message.count, 65535)); - } -}; - -// src/lostcity/network/225/outgoing/codec/ObjCountEncoder.ts -var ObjCountEncoder = class extends ZoneMessageEncoder { - prot = ZoneProt.OBJ_COUNT; - encode(buf, message) { - buf.p1(message.coord); - buf.p2(message.obj); - buf.p2(Math.min(message.oldCount, 65535)); - buf.p2(Math.min(message.newCount, 65535)); - } -}; - -// src/lostcity/network/225/outgoing/codec/ObjDelEncoder.ts -var ObjDelEncoder = class extends ZoneMessageEncoder { - prot = ZoneProt.OBJ_DEL; - encode(buf, message) { - buf.p1(message.coord); - buf.p2(message.obj); - } -}; - -// src/lostcity/network/225/outgoing/codec/ObjRevealEncoder.ts -var ObjRevealEncoder = class extends ZoneMessageEncoder { - prot = ZoneProt.OBJ_REVEAL; - encode(buf, message) { - buf.p1(message.coord); - buf.p2(message.obj); - buf.p2(Math.min(message.count, 65535)); - buf.p2(message.receiverId); - } -}; - -// src/lostcity/network/outgoing/model/PCountDialog.ts -var PCountDialog = class extends OutgoingMessage { - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/PCountDialogEncoder.ts -var PCountDialogEncoder = class extends MessageEncoder { - prot = ServerProt.P_COUNTDIALOG; - encode(_, __) { - } -}; - -// src/lostcity/network/225/outgoing/codec/ResetAnimsEncoder.ts -var ResetAnimsEncoder = class extends MessageEncoder { - prot = ServerProt.RESET_ANIMS; - encode(_, __) { - } -}; - -// src/lostcity/network/225/outgoing/codec/ResetClientVarCacheEncoder.ts -var ResetClientVarCacheEncoder = class extends MessageEncoder { - prot = ServerProt.RESET_CLIENT_VARCACHE; - encode(_, __) { - } -}; - -// src/lostcity/network/outgoing/model/SetMultiway.ts -var SetMultiway = class extends OutgoingMessage { - constructor(hidden) { - super(); - this.hidden = hidden; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/SetMultiwayEncoder.ts -var SetMultiwayEncoder = class extends MessageEncoder { - prot = ServerProt.SET_MULTIWAY; - encode(buf, message) { - buf.pbool(message.hidden); - } -}; - -// src/lostcity/network/outgoing/model/SynthSound.ts -var SynthSound = class extends OutgoingMessage { - constructor(synth, loops, delay) { - super(); - this.synth = synth; - this.loops = loops; - this.delay = delay; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/SynthSoundEncoder.ts -var SynthSoundEncoder = class extends MessageEncoder { - prot = ServerProt.SYNTH_SOUND; - encode(buf, message) { - buf.p2(message.synth); - buf.p1(message.loops); - buf.p2(message.delay); - } -}; - -// src/lostcity/network/outgoing/model/TutorialFlashSide.ts -var TutorialFlashSide = class extends OutgoingMessage { - constructor(tab) { - super(); - this.tab = tab; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/TutorialFlashSideEncoder.ts -var TutorialFlashSideEncoder = class extends MessageEncoder { - prot = ServerProt.TUTORIAL_FLASHSIDE; - encode(buf, message) { - buf.p1(message.tab); - } -}; - -// src/lostcity/network/225/outgoing/codec/TutorialOpenChatEncoder.ts -var TutorialOpenChatEncoder = class extends MessageEncoder { - prot = ServerProt.TUTORIAL_OPENCHAT; - encode(buf, message) { - buf.p2(message.component); - } -}; - -// src/lostcity/network/225/outgoing/codec/UnsetMapFlagEncoder.ts -var UnsetMapFlagEncoder = class extends MessageEncoder { - prot = ServerProt.UNSET_MAP_FLAG; - encode(_, __) { - } -}; - -// src/lostcity/network/outgoing/model/UpdateFriendList.ts -var UpdateFriendList = class extends OutgoingMessage { - constructor(name, nodeId) { - super(); - this.name = name; - this.nodeId = nodeId; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/UpdateFriendListEncoder.ts -var UpdateFriendListEncoder = class extends MessageEncoder { - prot = ServerProt.UPDATE_FRIENDLIST; - encode(buf, message) { - buf.p8(message.name); - buf.p1(message.nodeId); - } -}; - -// src/lostcity/network/outgoing/model/UpdateIgnoreList.ts -var UpdateIgnoreList = class extends OutgoingMessage { - constructor(names) { - super(); - this.names = names; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/UpdateIgnoreListEncoder.ts -var UpdateIgnoreListEncoder = class extends MessageEncoder { - prot = ServerProt.UPDATE_IGNORELIST; - encode(buf, message) { - for (const name of message.names) { - buf.p8(name); - } - } - test(message) { - return 8 * message.names.length; - } -}; - -// src/lostcity/network/outgoing/model/UpdateInvFull.ts -var UpdateInvFull = class extends OutgoingMessage { - constructor(component, inv) { - super(); - this.component = component; - this.inv = inv; - } - priority = ServerProtPriority.HIGH; -}; - -// src/lostcity/network/225/outgoing/codec/UpdateInvFullEncoder.ts -var UpdateInvFullEncoder = class extends MessageEncoder { - prot = ServerProt.UPDATE_INV_FULL; - encode(buf, message) { - const { component, inv } = message; - const comType = Component.get(component); - const size = Math.min(inv.capacity, comType.width * comType.height); - buf.p2(component); - buf.p1(size); - for (let slot = 0; slot < size; slot++) { - const obj = inv.get(slot); - if (obj) { - buf.p2(obj.id + 1); - if (obj.count >= 255) { - buf.p1(255); - buf.p4(obj.count); - } else { - buf.p1(obj.count); - } - } else { - buf.p2(0); - buf.p1(0); - } - } - } - test(message) { - const { component, inv } = message; - const comType = Component.get(component); - const size = Math.min(inv.capacity, comType.width * comType.height); - let length = 0; - length += 3; - for (let slot = 0; slot < size; slot++) { - const obj = inv.get(slot); - if (obj) { - length += 2; - if (obj.count >= 255) { - length += 5; - } else { - length += 1; - } - } else { - length += 3; - } - } - return length; - } -}; - -// src/lostcity/network/outgoing/model/UpdateInvPartial.ts -var UpdateInvPartial = class extends OutgoingMessage { - constructor(component, inv, ...slots) { - super(); - this.component = component; - this.inv = inv; - this.slots = slots; - } - priority = ServerProtPriority.HIGH; - slots; -}; - -// src/lostcity/network/225/outgoing/codec/UpdateInvPartialEncoder.ts -var UpdateInvPartialEncoder = class extends MessageEncoder { - prot = ServerProt.UPDATE_INV_PARTIAL; - encode(buf, message) { - const { component, inv } = message; - buf.p2(component); - for (const slot of message.slots) { - const obj = inv.get(slot); - buf.p1(slot); - if (obj) { - buf.p2(obj.id + 1); - if (obj.count >= 255) { - buf.p1(255); - buf.p4(obj.count); - } else { - buf.p1(obj.count); - } - } else { - buf.p2(0); - buf.p1(0); - } - } - } - test(message) { - const { inv } = message; - let length = 0; - length += 2; - for (const slot of message.slots) { - const obj = inv.get(slot); - length += 1; - if (obj) { - length += 2; - if (obj.count >= 255) { - length += 5; - } else { - length += 1; - } - } else { - length += 3; - } - } - return length; - } -}; - -// src/lostcity/network/225/outgoing/codec/UpdateInvStopTransmitEncoder.ts -var UpdateInvStopTransmitEncoder = class extends MessageEncoder { - prot = ServerProt.UPDATE_INV_STOP_TRANSMIT; - encode(buf, message) { - buf.p2(message.component); - } -}; - -// src/lostcity/network/outgoing/model/UpdateRunEnergy.ts -var UpdateRunEnergy = class extends OutgoingMessage { - constructor(energy) { - super(); - this.energy = energy; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/UpdateRunEnergyEncoder.ts -var UpdateRunEnergyEncoder = class extends MessageEncoder { - prot = ServerProt.UPDATE_RUNENERGY; - encode(buf, message) { - buf.p1(message.energy / 100 | 0); - } -}; - -// src/lostcity/network/outgoing/model/UpdateRunWeight.ts -var UpdateRunWeight = class extends OutgoingMessage { - constructor(kg) { - super(); - this.kg = kg; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/UpdateRunWeightEncoder.ts -var UpdateRunWeightEncoder = class extends MessageEncoder { - prot = ServerProt.UPDATE_RUNWEIGHT; - encode(buf, message) { - buf.p2(message.kg); - } -}; - -// src/lostcity/network/outgoing/model/UpdateStat.ts -var UpdateStat = class extends OutgoingMessage { - constructor(stat, exp, level) { - super(); - this.stat = stat; - this.exp = exp; - this.level = level; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/UpdateStatEncoder.ts -var UpdateStatEncoder = class extends MessageEncoder { - prot = ServerProt.UPDATE_STAT; - encode(buf, message) { - buf.p1(message.stat); - buf.p4(message.exp / 10 | 0); - buf.p1(message.level); - } -}; - -// src/lostcity/network/225/outgoing/codec/UpdateUid192Encoder.ts -var UpdateUid192Encoder = class extends MessageEncoder { - prot = ServerProt.UPDATE_UID192; - encode(buf, message) { - buf.p2(message.uid); - } -}; - -// src/lostcity/network/225/outgoing/codec/UpdateZoneFullFollowsEncoder.ts -var UpdateZoneFullFollowsEncoder = class extends MessageEncoder { - prot = ServerProt.UPDATE_ZONE_FULL_FOLLOWS; - encode(buf, message) { - buf.p1((message.zoneX << 3) - Position.zoneOrigin(message.originX)); - buf.p1((message.zoneZ << 3) - Position.zoneOrigin(message.originZ)); - } -}; - -// src/lostcity/network/225/outgoing/codec/UpdateZonePartialFollowsEncoder.ts -var UpdateZonePartialFollowsEncoder = class extends MessageEncoder { - prot = ServerProt.UPDATE_ZONE_PARTIAL_FOLLOWS; - encode(buf, message) { - buf.p1((message.zoneX << 3) - Position.zoneOrigin(message.originX)); - buf.p1((message.zoneZ << 3) - Position.zoneOrigin(message.originZ)); - } -}; - -// src/lostcity/network/225/outgoing/codec/UpdateZonePartialEnclosedEncoder.ts -var UpdateZonePartialEnclosedEncoder = class extends MessageEncoder { - prot = ServerProt.UPDATE_ZONE_PARTIAL_ENCLOSED; - encode(buf, message) { - buf.p1((message.zoneX << 3) - Position.zoneOrigin(message.originX)); - buf.p1((message.zoneZ << 3) - Position.zoneOrigin(message.originZ)); - buf.pdata(message.data, 0, message.data.length); - } - test(message) { - return 1 + 1 + message.data.length; - } -}; - -// src/lostcity/network/225/outgoing/codec/VarpLargeEncoder.ts -var VarpLargeEncoder = class extends MessageEncoder { - prot = ServerProt.VARP_LARGE; - encode(buf, message) { - buf.p2(message.varp); - buf.p4(message.value); - } -}; - -// src/lostcity/network/225/outgoing/codec/VarpSmallEncoder.ts -var VarpSmallEncoder = class extends MessageEncoder { - prot = ServerProt.VARP_SMALL; - encode(buf, message) { - buf.p2(message.varp); - buf.p1(message.value); - } -}; - -// src/lostcity/network/outgoing/model/NpcInfo.ts -var NpcInfo = class extends OutgoingMessage { - constructor(buildArea, level, x, z, originX, originZ, deltaX, deltaZ, changedLevel) { - super(); - this.buildArea = buildArea; - this.level = level; - this.x = x; - this.z = z; - this.originX = originX; - this.originZ = originZ; - this.deltaX = deltaX; - this.deltaZ = deltaZ; - this.changedLevel = changedLevel; - } - priority = ServerProtPriority.HIGH; - accumulator = 0; -}; - -// src/lostcity/network/225/outgoing/codec/NpcInfoEncoder.ts -var NpcInfoEncoder = class _NpcInfoEncoder extends MessageEncoder { - static BITS_NEW = 13 + 11 + 5 + 5 + 1; - static BITS_IDLE = 1; - static BITS_RUN = 1 + 2 + 3 + 3 + 1; - static BITS_WALK = 1 + 2 + 3 + 1; - static BITS_EXTENDED = 1 + 2; - static BYTES_LIMIT = 4997; - prot = ServerProt.NPC_INFO; - encode(buf, message) { - const buildArea = message.buildArea; - if (message.changedLevel || message.deltaX > buildArea.viewDistance || message.deltaZ > buildArea.viewDistance) { - buildArea.npcs.clear(); - } - this.writeNpcs(buf, message); - this.writeNewNpcs(buf, message); - const extended = buildArea.extendedInfo; - if (extended.size > 0) { - for (const info of extended) { - const npc = World_default.getNpc(info.id); - if (!npc) { - buf.p1(0); - continue; - } - this.writeExtendedInfo(npc, buf, info.added); - } - } - buildArea.clearExtended(); - } - test(_) { - return _NpcInfoEncoder.BYTES_LIMIT; - } - willFit(message, buf, bitsToAdd, bytesToAdd) { - return (buf.bitPos + bitsToAdd + 7 >>> 3) + (message.accumulator + bytesToAdd) <= _NpcInfoEncoder.BYTES_LIMIT; - } - writeNpcs(buf, message) { - const buildArea = message.buildArea; - buf.bits(); - buf.pBit(8, buildArea.npcs.size); - for (const nid of buildArea.npcs) { - const npc = World_default.getNpc(nid); - if (!npc || npc.tele || npc.level !== message.level || !Position.isWithinDistanceSW(message, npc, 15) || !npc.checkLifeCycle(World_default.currentTick)) { - buf.pBit(1, 1); - buf.pBit(2, 3); - buildArea.npcs.delete(nid); - continue; - } - const extendedInfoSize = this.calculateExtendedInfo(npc, false); - let extendedInfo = extendedInfoSize > 0; - const { walkDir, runDir } = npc; - let bits = _NpcInfoEncoder.BITS_IDLE; - if (runDir !== -1) { - bits = _NpcInfoEncoder.BITS_RUN; - } else if (walkDir !== -1) { - bits = _NpcInfoEncoder.BITS_WALK; - } else if (extendedInfo) { - bits = _NpcInfoEncoder.BITS_EXTENDED; - } - if (!this.willFit(message, buf, bits, extendedInfoSize)) { - extendedInfo = false; - } - buf.pBit(1, runDir !== -1 || walkDir !== -1 || extendedInfo ? 1 : 0); - if (runDir !== -1) { - buf.pBit(2, 2); - buf.pBit(3, walkDir); - buf.pBit(3, runDir); - buf.pBit(1, extendedInfo ? 1 : 0); - } else if (walkDir !== -1) { - buf.pBit(2, 1); - buf.pBit(3, walkDir); - buf.pBit(1, extendedInfo ? 1 : 0); - } else if (extendedInfo) { - buf.pBit(2, 0); - } - if (extendedInfo) { - buildArea.extendedInfo.add({ id: nid, added: false }); - message.accumulator += extendedInfoSize; - } - } - } - writeNewNpcs(buf, message) { - const buildArea = message.buildArea; - for (const npc of buildArea.getNearbyNpcs(message.x, message.z, message.originX, message.originZ)) { - const extendedInfoSize = this.calculateExtendedInfo(npc, true); - const extendedInfo = extendedInfoSize > 0; - if (!this.willFit(message, buf, _NpcInfoEncoder.BITS_NEW + 13, extendedInfoSize)) { - break; - } - buf.pBit(13, npc.nid); - buf.pBit(11, npc.type); - buf.pBit(5, npc.x - message.x); - buf.pBit(5, npc.z - message.z); - buf.pBit(1, extendedInfo ? 1 : 0); - if (extendedInfo) { - buildArea.extendedInfo.add({ id: npc.nid, added: true }); - message.accumulator += extendedInfoSize; - } - buildArea.npcs.add(npc.nid); - } - if (buildArea.extendedInfo.size > 0) { - buf.pBit(13, 8191); - } - buf.bytes(); - } - writeExtendedInfo(npc, buf, newlyObserved) { - let mask = npc.mask; - if (newlyObserved) { - if (npc.orientationX !== -1 || npc.faceX !== -1) { - mask |= Npc.FACE_COORD; - } - if (npc.faceEntity !== -1) { - mask |= Npc.FACE_ENTITY; - } - } - buf.p1(mask); - if (mask & Npc.ANIM) { - buf.p2(npc.animId); - buf.p1(npc.animDelay); - } - if (mask & Npc.FACE_ENTITY) { - if (npc.faceEntity !== -1) { - npc.alreadyFacedEntity = true; - } - buf.p2(npc.faceEntity); - } - if (mask & Npc.SAY) { - buf.pjstr(npc.chat ?? ""); - } - if (mask & Npc.DAMAGE) { - buf.p1(npc.damageTaken); - buf.p1(npc.damageType); - buf.p1(npc.levels[NpcStat_default.HITPOINTS]); - buf.p1(npc.baseLevels[NpcStat_default.HITPOINTS]); - } - if (mask & Npc.CHANGE_TYPE) { - buf.p2(npc.type); - } - if (mask & Npc.SPOTANIM) { - buf.p2(npc.graphicId); - buf.p2(npc.graphicHeight); - buf.p2(npc.graphicDelay); - } - if (mask & Npc.FACE_COORD) { - if (newlyObserved && npc.orientationX != -1) { - buf.p2(npc.orientationX); - buf.p2(npc.orientationZ); - } else { - buf.p2(npc.faceX); - buf.p2(npc.faceZ); - } - } - } - calculateExtendedInfo(npc, newlyObserved) { - let length = 0; - let mask = npc.mask; - if (newlyObserved) { - if (npc.orientationX !== -1 || npc.faceX !== -1) { - mask |= Npc.FACE_COORD; - } - if (npc.faceEntity !== -1) { - mask |= Npc.FACE_ENTITY; - } - } - if (mask === 0) { - return 0; - } - length += 1; - if (mask & Npc.ANIM) { - length += 3; - } - if (mask & Npc.FACE_ENTITY) { - length += 2; - } - if (mask & Npc.SAY) { - length += 1 + npc.chat.length; - } - if (mask & Npc.DAMAGE) { - length += 4; - } - if (mask & Npc.CHANGE_TYPE) { - length += 2; - } - if (mask & Npc.SPOTANIM) { - length += 6; - } - if (mask & Npc.FACE_COORD) { - length += 4; - } - return length; - } -}; - -// src/lostcity/network/outgoing/model/UpdateRebootTimer.ts -var UpdateRebootTimer = class extends OutgoingMessage { - // todo: confirm if reboot timer is low or high priority - constructor(ticks) { - super(); - this.ticks = ticks; - } - priority = ServerProtPriority.LOW; -}; - -// src/lostcity/network/225/outgoing/codec/UpdateRebootTimerEncoder.ts -var UpdateRebootTimerEncoder = class extends MessageEncoder { - prot = ServerProt.UPDATE_REBOOT_TIMER; - encode(buf, message) { - buf.p2(message.ticks); - } -}; - -// src/lostcity/network/225/outgoing/prot/ServerProtRepository.ts -var ServerProtRepository = class { - encoders = /* @__PURE__ */ new Map(); - bind(message, encoder) { - if (this.encoders.has(message)) { - throw new Error(`[ServerProtRepository] Already defines a ${message.name}.`); - } - this.encoders.set(message, encoder); - } - constructor() { - this.bind(CamLookAt, new CamLookAtEncoder()); - this.bind(CamMoveTo, new CamMoveToEncoder()); - this.bind(CamReset, new CamResetEncoder()); - this.bind(CamShake, new CamShakeEncoder()); - this.bind(ChatFilterSettings, new ChatFilterSettingsEncoder()); - this.bind(DataLand, new DataLandEncoder()); - this.bind(DataLandDone, new DataLandDoneEncoder()); - this.bind(DataLoc, new DataLocEncoder()); - this.bind(DataLocDone, new DataLocDoneEncoder()); - this.bind(EnableTracking, new EnableTrackingEncoder()); - this.bind(FinishTracking, new FinishTrackingEncoder()); - this.bind(HintArrow, new HintArrowEncoder()); - this.bind(IfClose, new IfCloseEncoder()); - this.bind(IfOpenChatModal, new IfOpenChatModalEncoder()); - this.bind(IfOpenMainModal, new IfOpenMainModalEncoder()); - this.bind(IfOpenMainSideModal, new IfOpenMainSideModalEncoder()); - this.bind(IfOpenSideModal, new IfOpenSideModalEncoder()); - this.bind(IfOpenSideOverlay, new IfOpenSideOverlayEncoder()); - this.bind(IfSetAnim, new IfSetAnimEncoder()); - this.bind(IfSetColour, new IfSetColourEncoder()); - this.bind(IfSetHide, new IfSetHideEncoder()); - this.bind(IfSetModel, new IfSetModelEncoder()); - this.bind(IfSetNpcHead, new IfSetNpcHeadEncoder()); - this.bind(IfSetObject, new IfSetObjectEncoder()); - this.bind(IfSetPlayerHead, new IfSetPlayerHeadEncoder()); - this.bind(IfSetPosition, new IfSetPositionEncoder()); - this.bind(IfSetRecol, new IfSetRecolEncoder()); - this.bind(IfSetText, new IfSetTextEncoder()); - this.bind(IfShowSide, new IfShowSideEncoder()); - this.bind(LastLoginInfo, new LastLoginInfoEncoder()); - this.bind(LocAddChange, new LocAddChangeEncoder()); - this.bind(LocAnim, new LocAnimEncoder()); - this.bind(LocDel, new LocDelEncoder()); - this.bind(LocMerge, new LocMergeEncoder()); - this.bind(Logout, new LogoutEncoder()); - this.bind(MapAnim, new MapAnimEncoder()); - this.bind(MapProjAnim, new MapProjAnimEncoder()); - this.bind(MessageGame, new MessageGameEncoder()); - this.bind(MessagePrivate, new MessagePrivateEncoder()); - this.bind(MidiJingle, new MidiJingleEncoder()); - this.bind(MidiSong, new MidiSongEncoder()); - this.bind(NpcInfo, new NpcInfoEncoder()); - this.bind(ObjAdd, new ObjAddEncoder()); - this.bind(ObjCount, new ObjCountEncoder()); - this.bind(ObjDel, new ObjDelEncoder()); - this.bind(ObjReveal, new ObjRevealEncoder()); - this.bind(PCountDialog, new PCountDialogEncoder()); - this.bind(PlayerInfo, new PlayerInfoEncoder()); - this.bind(RebuildNormal, new RebuildNormalEncoder()); - this.bind(ResetAnims, new ResetAnimsEncoder()); - this.bind(ResetClientVarCache, new ResetClientVarCacheEncoder()); - this.bind(SetMultiway, new SetMultiwayEncoder()); - this.bind(SynthSound, new SynthSoundEncoder()); - this.bind(TutorialFlashSide, new TutorialFlashSideEncoder()); - this.bind(TutorialOpenChat, new TutorialOpenChatEncoder()); - this.bind(UnsetMapFlag, new UnsetMapFlagEncoder()); - this.bind(UpdateFriendList, new UpdateFriendListEncoder()); - this.bind(UpdateIgnoreList, new UpdateIgnoreListEncoder()); - this.bind(UpdateInvFull, new UpdateInvFullEncoder()); - this.bind(UpdateInvPartial, new UpdateInvPartialEncoder()); - this.bind(UpdateInvStopTransmit, new UpdateInvStopTransmitEncoder()); - this.bind(UpdateRunEnergy, new UpdateRunEnergyEncoder()); - this.bind(UpdateRunWeight, new UpdateRunWeightEncoder()); - this.bind(UpdateRebootTimer, new UpdateRebootTimerEncoder()); - this.bind(UpdateStat, new UpdateStatEncoder()); - this.bind(UpdateUid192, new UpdateUid192Encoder()); - this.bind(UpdateZoneFullFollows, new UpdateZoneFullFollowsEncoder()); - this.bind(UpdateZonePartialEnclosed, new UpdateZonePartialEnclosedEncoder()); - this.bind(UpdateZonePartialFollows, new UpdateZonePartialFollowsEncoder()); - this.bind(VarpLarge, new VarpLargeEncoder()); - this.bind(VarpSmall, new VarpSmallEncoder()); - } - getEncoder(message) { - return this.encoders.get(message.constructor); - } - getZoneEncoder(message) { - return this.encoders.get(message.constructor); - } -}; -var ServerProtRepository_default = new ServerProtRepository(); - -// src/lostcity/engine/zone/ZoneEntityList.ts -var ZoneEntityList = class extends Array { - capacity; - onFilled; - constructor(capacity, onFilled) { - super(); - this.capacity = capacity; - this.onFilled = onFilled; - } - // ---- - *stack(coord) { - const items = this[coord]; - if (typeof items === "undefined") { - return; - } - for (let index = 0; index < items.length; index++) { - yield items[index]; - } - } - *all(reverse = false) { - for (let index = 0; index < this.length; index++) { - const items = this[index]; - if (typeof items === "undefined") { - continue; - } - if (reverse) { - for (let i = items.length - 1; i >= 0; i--) { - yield items[i]; - } - } else { - for (let i = 0; i < items.length; i++) { - yield items[i]; - } - } - } - } - // ---- - addLast(coord, item, unchecked = false) { - this.check(coord, unchecked); - this[coord]?.push(item); - } - addFirst(coord, item, unchecked = false) { - this.check(coord, unchecked); - this[coord]?.unshift(item); - } - sortStack(coord, unchecked = false) { - const top = this.nextTopStack(coord); - if (typeof top === "undefined") { - return; - } - const items = this[coord]; - if (typeof items === "undefined") { - return; - } - if (items[0] !== top) { - this.remove(coord, top); - this.addFirst(coord, top, unchecked); - } - } - remove(coord, item) { - const items = this[coord]; - if (typeof items === "undefined") { - return; - } - const index = items.indexOf(item); - if (index === -1) { - return; - } - items.splice(index, 1); - } - contains(coord, item) { - const items = this[coord]; - if (typeof items === "undefined") { - return false; - } - return items.indexOf(item) !== -1; - } - check(coord, unchecked) { - const items = this[coord]; - if (typeof items === "undefined") { - this[coord] = []; - } - if (!unchecked && this.total === this.capacity) { - const bottom = this.nextBottomAll(); - if (typeof bottom !== "undefined") { - this.onFilled(bottom); - } - } - } - get total() { - let total = 0; - for (let index = 0; index < this.length; index++) { - const items = this[index]; - if (typeof items === "undefined") { - continue; - } - total += items.length; - } - return total; - } -}; -var LocList = class extends ZoneEntityList { - nextTopStack(coord) { - const locs = this[coord]; - if (typeof locs === "undefined") { - return void 0; - } - let topCost = -99999999; - let topLoc; - for (const loc of locs) { - const cost = loc.lifecycle; - if (cost > topCost) { - topCost = cost; - topLoc = loc; - } - } - return topLoc; - } - nextBottomAll() { - let bottomCost = Number.POSITIVE_INFINITY; - let bottomLoc; - for (let index = 0; index < this.length; index++) { - const locs = this[index]; - if (typeof locs === "undefined") { - continue; - } - for (const loc of locs) { - if (bottomCost === 0) { - break; - } - if (loc.lifecycle !== EntityLifeCycle_default.DESPAWN) { - continue; - } - const cost = loc.lifecycle; - if (cost < bottomCost) { - bottomCost = cost; - bottomLoc = loc; - } - } - } - return bottomLoc; - } -}; -var ObjList = class extends ZoneEntityList { - nextTopStack(coord) { - const objs = this[coord]; - if (typeof objs === "undefined") { - return void 0; - } - let topCost = -99999999; - let topObj; - for (const obj of objs) { - const type = ObjType.get(obj.type); - let cost = type.cost; - if (type.stackable) { - cost *= obj.count + 1; - } - cost += obj.lifecycle; - if (cost > topCost) { - topCost = cost; - topObj = obj; - } - } - return topObj; - } - nextBottomAll() { - let bottomCost = Number.POSITIVE_INFINITY; - let bottomObj; - for (let index = 0; index < this.length; index++) { - const objs = this[index]; - if (typeof objs === "undefined") { - continue; - } - for (const obj of objs) { - if (bottomCost === 0) { - break; - } - if (obj.lifecycle !== EntityLifeCycle_default.DESPAWN) { - continue; - } - const type = ObjType.get(obj.type); - let cost = type.cost; - if (type.stackable) { - cost *= obj.count + 1; - } - cost += obj.lifecycle; - if (cost < bottomCost) { - bottomCost = cost; - bottomObj = obj; - } - } - } - return bottomObj; - } -}; - -// src/lostcity/engine/zone/Zone.ts -var Zone = class _Zone { - static SIZE = 8 * 8; - static LOCS = this.SIZE << 2; - static OBJS = (this.SIZE << 1) + 1; - index; - // packed coord - x; - z; - level; - // zone entities - players; - // list of player uids - npcs; - // list of npc nids (not uid because type may change) - locs; - objs; - entityEvents; - // zone events - events; - shared = null; - totalLocs = 0; - totalObjs = 0; - constructor(index) { - this.index = index; - const coord = ZoneMap.unpackIndex(index); - this.x = coord.x >> 3; - this.z = coord.z >> 3; - this.level = coord.level; - this.events = /* @__PURE__ */ new Set(); - this.players = /* @__PURE__ */ new Set(); - this.npcs = /* @__PURE__ */ new Set(); - this.locs = new LocList(_Zone.LOCS, (loc) => World_default.removeLoc(loc, 100)); - this.objs = new ObjList(_Zone.OBJS, (obj) => World_default.removeObj(obj, 100)); - this.entityEvents = /* @__PURE__ */ new Map(); - } - enter(entity) { - if (entity instanceof Player) { - this.players.add(entity.uid); - World_default.getZoneGrid(this.level).flag(this.x, this.z); - } else if (entity instanceof Npc) { - this.npcs.add(entity.nid); - } - } - leave(entity) { - if (entity instanceof Player) { - this.players.delete(entity.uid); - if (this.players.size === 0) { - World_default.getZoneGrid(this.level).unflag(this.x, this.z); - } - } else if (entity instanceof Npc) { - this.npcs.delete(entity.nid); - } - } - tick(tick) { - let updated; - do { - updated = false; - for (const obj of this.getAllObjsUnsafe()) { - if (!obj.updateLifeCycle(tick) || obj.lastLifecycleTick === tick) { - continue; - } - if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { - if (obj.receiverId !== -1) { - World_default.revealObj(obj); - } else { - World_default.removeObj(obj, 0); - updated = true; - } - } else if (obj.lifecycle === EntityLifeCycle_default.RESPAWN) { - World_default.addObj(obj, -1, 0); - updated = true; - } - } - for (const loc of this.getAllLocsUnsafe()) { - if (!loc.updateLifeCycle(tick) || loc.lastLifecycleTick === tick) { - continue; - } - if (loc.lifecycle === EntityLifeCycle_default.DESPAWN) { - World_default.removeLoc(loc, 0); - updated = true; - } else if (loc.lifecycle === EntityLifeCycle_default.RESPAWN) { - World_default.addLoc(loc, 0); - updated = true; - } - } - } while (updated); - } - computeShared() { - this.shared = null; - let length = 0; - const enclosed = []; - for (const event of this.events.values()) { - if (event.type !== ZoneEventType_default.ENCLOSED) { - continue; - } - const encoder = ServerProtRepository_default.getZoneEncoder(event.message); - if (typeof encoder === "undefined") { - continue; - } - const bytes = encoder.enclose(event.message); - enclosed.push(bytes); - length += bytes.length; - } - if (enclosed.length === 0 || length === 0) { - return; - } - const shared = new Uint8Array(length); - let ptr = 0; - for (const bytes of enclosed) { - shared.set(bytes, ptr); - ptr += bytes.length; - } - this.shared = shared; - } - writeFullFollows(player) { - player.write(new UpdateZoneFullFollows(this.x, this.z, player.originX, player.originZ)); - for (const obj of this.getAllObjsUnsafe(true)) { - if (obj.receiverId !== -1 && obj.receiverId !== player.pid) { - continue; - } - player.write(new UpdateZonePartialFollows(this.x, this.z, player.originX, player.originZ)); - if (obj.lifecycle === EntityLifeCycle_default.DESPAWN && obj.checkLifeCycle(World_default.currentTick)) { - player.write(new ObjAdd(Position.packZoneCoord(obj.x, obj.z), obj.type, obj.count)); - } else if (obj.lifecycle === EntityLifeCycle_default.RESPAWN && obj.checkLifeCycle(World_default.currentTick)) { - player.write(new ObjAdd(Position.packZoneCoord(obj.x, obj.z), obj.type, obj.count)); - } - } - for (const loc of this.getAllLocsUnsafe(true)) { - if (loc.lifecycle === EntityLifeCycle_default.DESPAWN && loc.checkLifeCycle(World_default.currentTick)) { - player.write(new LocAddChange(Position.packZoneCoord(loc.x, loc.z), loc.type, loc.shape, loc.angle)); - } else if (loc.lifecycle === EntityLifeCycle_default.RESPAWN && !loc.checkLifeCycle(World_default.currentTick)) { - player.write(new LocDel(Position.packZoneCoord(loc.x, loc.z), loc.shape, loc.angle)); - } - } - } - writePartialEncloses(player) { - if (!this.shared) { - return; - } - player.write(new UpdateZonePartialEnclosed(this.x, this.z, player.originX, player.originZ, this.shared)); - } - writePartialFollows(player) { - if (this.events.size === 0) { - return; - } - player.write(new UpdateZonePartialFollows(this.x, this.z, player.originX, player.originZ)); - for (const event of this.events) { - if (event.type !== ZoneEventType_default.FOLLOWS) { - continue; - } - if (event.receiverId !== -1 && event.receiverId !== player.pid) { - continue; - } - player.write(event.message); - } - } - reset() { - this.events.clear(); - this.entityEvents.clear(); - } - // ---- static locs/objs are added during world init ---- - addStaticLoc(loc) { - const coord = Position.packZoneCoord(loc.x, loc.z); - this.locs.addLast(coord, loc, true); - this.totalLocs++; - this.locs.sortStack(coord, true); - } - addStaticObj(obj) { - const coord = Position.packZoneCoord(obj.x, obj.z); - this.objs.addLast(coord, obj, true); - this.totalObjs++; - this.objs.sortStack(coord, true); - } - // ---- - appendEvent(entity, event) { - this.events.add(event); - const exist = this.entityEvents.get(entity); - if (typeof exist === "undefined") { - this.entityEvents.set(entity, [event]); - return; - } - this.entityEvents.set(entity, exist.concat(event)); - } - addLoc(loc) { - const coord = Position.packZoneCoord(loc.x, loc.z); - if (loc.lifecycle === EntityLifeCycle_default.DESPAWN) { - this.locs.addLast(coord, loc); - this.totalLocs++; - } - this.locs.sortStack(coord); - this.appendEvent(loc, new ZoneEvent(ZoneEventType_default.ENCLOSED, -1, new LocAddChange(coord, loc.type, loc.shape, loc.angle))); - } - removeLoc(loc) { - const coord = Position.packZoneCoord(loc.x, loc.z); - if (loc.lifecycle === EntityLifeCycle_default.DESPAWN) { - this.locs.remove(coord, loc); - this.totalLocs--; - } - this.locs.sortStack(coord); - const events = this.entityEvents.get(loc); - if (typeof events !== "undefined") { - for (let index = 0; index < events.length; index++) { - this.events.delete(events[index]); - } - this.entityEvents.delete(loc); - } - if (loc.lastLifecycleTick !== World_default.currentTick) { - this.appendEvent(loc, new ZoneEvent(ZoneEventType_default.ENCLOSED, -1, new LocDel(coord, loc.shape, loc.angle))); - } - } - getLoc(x, z, type) { - for (const loc of this.getLocsSafe(Position.packZoneCoord(x, z))) { - if (loc.type === type) { - return loc; - } - } - return null; - } - mergeLoc(loc, player, startCycle, endCycle, south, east, north, west) { - this.appendEvent(loc, new ZoneEvent(ZoneEventType_default.ENCLOSED, -1, new LocMerge(loc.x, loc.z, loc.shape, loc.angle, loc.type, startCycle, endCycle, player.pid, east, south, west, north))); - } - animLoc(loc, seq) { - this.appendEvent(loc, new ZoneEvent(ZoneEventType_default.ENCLOSED, -1, new LocAnim(Position.packZoneCoord(loc.x, loc.z), loc.shape, loc.angle, seq))); - } - // ---- - addObj(obj, receiverId) { - const coord = Position.packZoneCoord(obj.x, obj.z); - if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { - this.objs.addLast(coord, obj); - this.totalObjs++; - } - this.objs.sortStack(coord); - if (obj.lifecycle === EntityLifeCycle_default.RESPAWN || receiverId === -1) { - this.appendEvent(obj, new ZoneEvent(ZoneEventType_default.ENCLOSED, receiverId, new ObjAdd(coord, obj.type, obj.count))); - } else if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { - this.appendEvent(obj, new ZoneEvent(ZoneEventType_default.FOLLOWS, receiverId, new ObjAdd(coord, obj.type, obj.count))); - } - } - revealObj(obj, receiverId) { - obj.receiverId = -1; - obj.reveal = -1; - const coord = Position.packZoneCoord(obj.x, obj.z); - this.objs.sortStack(coord); - this.appendEvent(obj, new ZoneEvent(ZoneEventType_default.ENCLOSED, receiverId, new ObjReveal(coord, obj.type, obj.count, receiverId))); - } - changeObj(obj, receiverId, oldCount, newCount) { - obj.count = newCount; - const coord = Position.packZoneCoord(obj.x, obj.z); - this.objs.sortStack(coord); - this.appendEvent(obj, new ZoneEvent(ZoneEventType_default.FOLLOWS, receiverId, new ObjCount(coord, obj.type, oldCount, newCount))); - } - removeObj(obj) { - const coord = Position.packZoneCoord(obj.x, obj.z); - if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { - this.objs.remove(coord, obj); - this.totalObjs--; - } - this.objs.sortStack(coord); - const exist = this.entityEvents.get(obj); - if (typeof exist !== "undefined") { - for (let index = 0; index < exist.length; index++) { - this.events.delete(exist[index]); - } - this.entityEvents.delete(obj); - } - if (obj.lastLifecycleTick !== World_default.currentTick) { - if (obj.lifecycle === EntityLifeCycle_default.RESPAWN || obj.receiverId === -1) { - this.appendEvent(obj, new ZoneEvent(ZoneEventType_default.ENCLOSED, -1, new ObjDel(coord, obj.type))); - } else if (obj.lifecycle === EntityLifeCycle_default.DESPAWN) { - this.appendEvent(obj, new ZoneEvent(ZoneEventType_default.FOLLOWS, -1, new ObjDel(coord, obj.type))); - } - } - } - // ---- not tied to any entities ---- - animMap(x, z, spotanim, height, delay) { - this.events.add({ - type: ZoneEventType_default.ENCLOSED, - receiverId: -1, - message: new MapAnim(Position.packZoneCoord(x, z), spotanim, height, delay) - }); - } - mapProjAnim(x, z, dstX, dstZ, target, spotanim, srcHeight, dstHeight, startDelay, endDelay, peak, arc) { - this.events.add({ - type: ZoneEventType_default.ENCLOSED, - receiverId: -1, - message: new MapProjAnim(x, z, dstX, dstZ, target, spotanim, srcHeight, dstHeight, startDelay, endDelay, peak, arc) - }); - } - getObj(x, z, type, receiverId) { - for (const obj of this.getObjsSafe(Position.packZoneCoord(x, z))) { - if (obj.receiverId !== -1 && obj.receiverId !== receiverId || obj.type !== type) { - continue; - } - return obj; - } - return null; - } - *getAllPlayersSafe() { - for (const uid of this.players) { - const player = World_default.getPlayerByUid(uid); - if (player && player.checkLifeCycle(World_default.currentTick)) { - yield player; - } - } - } - *getAllNpcsSafe() { - for (const nid of this.npcs) { - const npc = World_default.getNpc(nid); - if (npc && npc.checkLifeCycle(World_default.currentTick)) { - yield npc; - } - } - } - *getAllObjsSafe() { - for (const obj of this.objs.all()) { - if (obj.checkLifeCycle(World_default.currentTick)) { - yield obj; - } - } - } - *getObjsSafe(coord) { - for (const obj of this.objs.stack(coord)) { - if (obj.checkLifeCycle(World_default.currentTick)) { - yield obj; - } - } - } - *getObjsUnsafe(coord) { - yield* this.objs.stack(coord); - } - *getAllObjsUnsafe(reverse = false) { - yield* this.objs.all(reverse); - } - *getAllLocsSafe() { - for (const loc of this.locs.all()) { - if (loc.checkLifeCycle(World_default.currentTick)) { - yield loc; - } - } - } - *getLocsSafe(coord) { - for (const loc of this.locs.stack(coord)) { - if (loc.checkLifeCycle(World_default.currentTick)) { - yield loc; - } - } - } - *getLocsUnsafe(coord) { - yield* this.locs.stack(coord); - } - *getAllLocsUnsafe(reverse = false) { - yield* this.locs.all(reverse); - } -}; - -// src/lostcity/engine/zone/ZoneGrid.ts -var ZoneGrid = class _ZoneGrid { - static GRID_SIZE = 2048; - static INT_BITS = 5; - static INT_BITS_FLAG = (1 << this.INT_BITS) - 1; - static DEFAULT_GRID_SIZE = this.GRID_SIZE * (this.GRID_SIZE >> this.INT_BITS); - grid; - constructor(size = _ZoneGrid.DEFAULT_GRID_SIZE) { - this.grid = new Int32Array(size); - } - index(zoneX, zoneY) { - return zoneX << _ZoneGrid.INT_BITS | zoneY >>> _ZoneGrid.INT_BITS; - } - flag(zoneX, zoneY) { - this.grid[this.index(zoneX, zoneY)] |= 1 << (zoneY & _ZoneGrid.INT_BITS_FLAG); - } - unflag(zoneX, zoneY) { - this.grid[this.index(zoneX, zoneY)] &= ~(1 << (zoneY & _ZoneGrid.INT_BITS_FLAG)); - } - isFlagged(zoneX, zoneY, radius) { - const minX = Math.max(0, zoneX - radius); - const maxX = Math.min(_ZoneGrid.GRID_SIZE - 1, zoneX + radius); - const minY = Math.max(0, zoneY - radius); - const maxY = Math.min(_ZoneGrid.GRID_SIZE - 1, zoneY + radius); - const bits = _ZoneGrid.INT_BITS_FLAG; - const startY = minY & ~bits; - const endY = maxY >>> _ZoneGrid.INT_BITS << _ZoneGrid.INT_BITS; - for (let x = minX; x <= maxX; x++) { - for (let y = startY; y <= endY; y += 32) { - const index = this.index(x, y); - const line = this.grid[index]; - let trailingTrimmed = line; - if (y + bits > maxY) { - trailingTrimmed = line & (1 << maxY - y + 1) - 1; - } - let leadingTrimmed = trailingTrimmed; - if (y < minY) { - leadingTrimmed = trailingTrimmed >>> minY - y; - } - if (leadingTrimmed !== 0) { - return true; - } - } - } - return false; - } -}; - -// src/lostcity/engine/zone/ZoneMap.ts -var ZoneMap = class _ZoneMap { - static zoneIndex(x, z, level) { - return x >> 3 & 2047 | (z >> 3 & 2047) << 11 | (level & 3) << 22; - } - static unpackIndex(index) { - const x = (index & 2047) << 3; - const z = (index >> 11 & 2047) << 3; - const level = index >> 22; - return { x, z, level }; - } - zones; - grids; - constructor() { - this.zones = /* @__PURE__ */ new Map(); - this.grids = /* @__PURE__ */ new Map(); - } - zone(x, z, level) { - const zoneIndex = _ZoneMap.zoneIndex(x, z, level); - let zone = this.zones.get(zoneIndex); - if (typeof zone == "undefined") { - zone = new Zone(zoneIndex); - this.zones.set(zoneIndex, zone); - } - return zone; - } - zoneByIndex(index) { - let zone = this.zones.get(index); - if (typeof zone == "undefined") { - zone = new Zone(index); - this.zones.set(index, zone); - } - return zone; - } - grid(level) { - let grid = this.grids.get(level); - if (typeof grid == "undefined") { - grid = new ZoneGrid(); - this.grids.set(level, grid); - } - return grid; - } - zoneCount() { - return this.zones.size; - } - locCount() { - let total = 0; - for (const zone of this.zones.values()) { - total += zone.totalLocs; - } - return total; - } - objCount() { - let total = 0; - for (const zone of this.zones.values()) { - total += zone.totalObjs; - } - return total; - } -}; - -// src/lostcity/entity/BuildArea.ts -var BuildArea = class _BuildArea { - static INTERVAL = 10; - static PREFERRED_PLAYERS = 250; - static PREFERRED_NPCS = 255; - static PREFERRED_VIEW_DISTANCE = 15; - // constructor - npcs; - // observed npcs - players; - // observed players - loadedZones; - activeZones; - extendedInfo; - appearances; - // runtime - forceViewDistance = false; - viewDistance = _BuildArea.PREFERRED_VIEW_DISTANCE; - lastResize = 0; - constructor() { - this.npcs = /* @__PURE__ */ new Set(); - this.players = /* @__PURE__ */ new Set(); - this.loadedZones = /* @__PURE__ */ new Set(); - this.activeZones = /* @__PURE__ */ new Set(); - this.extendedInfo = /* @__PURE__ */ new Set(); - this.appearances = /* @__PURE__ */ new Map(); - } - resize() { - if (this.forceViewDistance) { - return; - } - if (this.players.size >= _BuildArea.PREFERRED_PLAYERS) { - if (this.viewDistance > 1) { - this.viewDistance--; - } - this.lastResize = 0; - return; - } - if (++this.lastResize >= _BuildArea.INTERVAL) { - if (this.viewDistance < _BuildArea.PREFERRED_VIEW_DISTANCE) { - this.viewDistance++; - } else { - this.lastResize = 0; - } - } - } - clearExtended() { - this.extendedInfo.clear(); - } - hasAppearance(pid, tick) { - const appearance = this.appearances.get(pid); - if (typeof appearance === "undefined") { - return false; - } - return appearance === tick; - } - saveAppearance(pid, tick) { - this.appearances.set(pid, tick); - } - *getNearbyPlayers(uid, x, z, originX, originZ) { - players: for (const zoneIndex of this.proximitySort(x, z, this.activeZones)) { - for (const other of this.getNearby(World_default.getZoneIndex(zoneIndex).getAllPlayersSafe(), x, z, originX, originZ, this.viewDistance)) { - if (this.players.size >= _BuildArea.PREFERRED_PLAYERS) { - break players; - } - if (this.players.has(other.uid)) { - continue; - } - if (other.uid === uid) { - continue; - } - yield other; - } - } - } - *getNearbyNpcs(x, z, originX, originZ) { - npcs: for (const zoneIndex of this.proximitySort(x, z, this.activeZones)) { - for (const npc of this.getNearby(World_default.getZoneIndex(zoneIndex).getAllNpcsSafe(), x, z, originX, originZ, 15)) { - if (this.npcs.size >= _BuildArea.PREFERRED_NPCS) { - break npcs; - } - if (this.npcs.has(npc.nid)) { - continue; - } - yield npc; - } - } - } - *getNearby(entities, x, z, originX, originZ, distance) { - const absLeftX = originX - 48; - const absRightX = originX + 48; - const absTopZ = originZ + 48; - const absBottomZ = originZ - 48; - for (const entity of entities) { - if (entity.x <= absLeftX || entity.x >= absRightX || entity.z >= absTopZ || entity.z <= absBottomZ) { - continue; - } - if (!Position.isWithinDistanceSW({ x, z }, entity, distance)) { - continue; - } - yield entity; - } - } - proximitySort(zoneX, zoneZ, zones) { - return Array.from(zones.values()).map((zoneIndex) => this.zoneToDistance(zoneIndex, zoneX, zoneZ)).sort((a, b) => a.distance - b.distance).map(({ zoneIndex }) => zoneIndex); - } - zoneToDistance(zoneIndex, zoneX, zoneZ) { - const pos = ZoneMap.unpackIndex(zoneIndex); - const distance = Math.abs(pos.x - zoneX) + Math.abs(pos.z - zoneZ); - return { zoneIndex, distance }; - } -}; - -// src/lostcity/entity/Player.ts -var levelExperience = new Int32Array(99); -var acc = 0; -for (let i = 0; i < 99; i++) { - const level = i + 1; - const delta = Math.floor(level + Math.pow(2, level / 7) * 300); - acc += delta; - levelExperience[i] = Math.floor(acc / 4) * 10; -} -function getLevelByExp(exp) { - for (let i = 98; i >= 0; i--) { - if (exp >= levelExperience[i]) { - return Math.min(i + 2, 99); - } - } - return 1; -} -function getExpByLevel(level) { - return levelExperience[level - 2]; -} -var Player = class _Player extends PathingEntity { - static APPEARANCE = 1; - static ANIM = 2; - static FACE_ENTITY = 4; - static SAY = 8; - static DAMAGE = 16; - static FACE_COORD = 32; - static CHAT = 64; - static BIG_UPDATE = 128; - static SPOTANIM = 256; - static EXACT_MOVE = 512; - static SKILLS = [ - "attack", - "defence", - "strength", - "hitpoints", - "ranged", - "prayer", - "magic", - "cooking", - "woodcutting", - "fletching", - "fishing", - "firemaking", - "crafting", - "smithing", - "mining", - "herblore", - "agility", - "thieving", - "stat18", - "stat19", - "runecraft" - ]; - static DESIGN_BODY_COLORS = [ - [6798, 107, 10283, 16, 4797, 7744, 5799, 4634, 33697, 22433, 2983, 54193], - [8741, 12, 64030, 43162, 7735, 8404, 1701, 38430, 24094, 10153, 56621, 4783, 1341, 16578, 35003, 25239], - [25238, 8742, 12, 64030, 43162, 7735, 8404, 1701, 38430, 24094, 10153, 56621, 4783, 1341, 16578, 35003], - [4626, 11146, 6439, 12, 4758, 10270], - [4550, 4537, 5681, 5673, 5790, 6806, 8076, 4574] - ]; - save() { - const sav = Packet.alloc(1); - sav.p2(8196); - sav.p2(3); - sav.p2(this.x); - sav.p2(this.z); - sav.p1(this.level); - for (let i = 0; i < 7; i++) { - sav.p1(this.body[i]); - } - for (let i = 0; i < 5; i++) { - sav.p1(this.colors[i]); - } - sav.p1(this.gender); - sav.p2(this.runenergy); - sav.p4(this.playtime); - for (let i = 0; i < 21; i++) { - sav.p4(this.stats[i]); - sav.p1(this.levels[i]); - } - sav.p2(this.vars.length); - for (let i = 0; i < this.vars.length; i++) { - const type = VarPlayerType.get(i); - if (type.scope === VarPlayerType.SCOPE_PERM) { - sav.p4(this.vars[i]); - } else { - sav.p4(0); - } - } - let invCount = 0; - const invStartPos = sav.pos; - sav.p1(0); - for (const [typeId, inventory] of this.invs) { - const invType = InvType.get(typeId); - if (invType.scope !== InvType.SCOPE_PERM) { - continue; - } - sav.p2(typeId); - for (let slot = 0; slot < inventory.capacity; slot++) { - const obj = inventory.get(slot); - if (!obj) { - sav.p2(0); - continue; - } - sav.p2(obj.id + 1); - if (obj.count >= 255) { - sav.p1(255); - sav.p4(obj.count); - } else { - sav.p1(obj.count); - } - } - invCount++; - } - sav.data[invStartPos] = invCount; - sav.p1(this.afkZones.length); - for (let index = 0; index < this.afkZones.length; index++) { - sav.p4(this.afkZones[index]); - } - sav.p2(this.lastAfkZone); - sav.p4(Packet.getcrc(sav.data, 0, sav.pos)); - const safeName = fromBase37(this.username37); - sav.save(`data/players/${safeName}.sav`); - return sav; - } - // constructor properties - username; - username37; - displayName; - body; - colors; - gender; - runenergy = 1e4; - lastRunEnergy = -1; - runweight; - playtime; - stats = new Int32Array(21); - levels = new Uint8Array(21); - vars; - varsString; - invs = /* @__PURE__ */ new Map(); - // runtime variables - pid = -1; - uid = -1; - lowMemory = false; - webClient = false; - combatLevel = 3; - headicons = 0; - appearance = null; - // cached appearance - lastAppearance = 0; - baseLevels = new Uint8Array(21); - lastStats = new Int32Array(21); - // we track this so we know to flush stats only once a tick on changes - lastLevels = new Uint8Array(21); - // we track this so we know to flush stats only once a tick on changes - originX = -1; - originZ = -1; - buildArea = new BuildArea(); - lastMovement = 0; - // for p_arrivedelay - basReadyAnim = -1; - basTurnOnSpot = -1; - basWalkForward = -1; - basWalkBackward = -1; - basWalkLeft = -1; - basWalkRight = -1; - basRunning = -1; - animProtect = 0; - logoutRequested = false; - invListeners = []; - allowDesign = false; - afkEventReady = false; - interactWalkTrigger = false; - highPriorityOut = new Stack(); - lowPriorityOut = new Stack(); - lastResponse = -1; - messageColor = null; - messageEffect = null; - messageType = null; - message = null; - // --- - // script variables - delay = 0; - queue = new LinkList(); - weakQueue = new LinkList(); - engineQueue = new LinkList(); - cameraPackets = new LinkList(); - timers = /* @__PURE__ */ new Map(); - modalState = 0; - modalTop = -1; - lastModalTop = -1; - modalBottom = -1; - lastModalBottom = -1; - modalSidebar = -1; - lastModalSidebar = -1; - refreshModalClose = false; - refreshModal = false; - modalSticky = -1; - overlaySide = new Array(14).fill(-1); - receivedFirstClose = true; - // workaround to not close welcome screen on login - protect = false; - // whether protected access is available - activeScript = null; - resumeButtons = []; - lastItem = -1; - // opheld, opheldu, opheldt, inv_button - lastSlot = -1; - // opheld, opheldu, opheldt, inv_button, inv_buttond - lastUseItem = -1; - // opheldu, opobju, oplocu, opnpcu, opplayeru - lastUseSlot = -1; - // opheldu, opobju, oplocu, opnpcu, opplayeru - lastTargetSlot = -1; - // inv_buttond - lastCom = -1; - // if_button - staffModLevel = 0; - heroPoints = new Array(16); - // be sure to reset when stats are recovered/reset - afkZones = new Int32Array(2); - lastAfkZone = 0; - // movement triggers - lastMapZone = -1; - lastZone = -1; - constructor(username, username37) { - super(0, 3094, 3106, 1, 1, EntityLifeCycle_default.FOREVER, MoveRestrict_default.NORMAL, BlockWalk_default.NPC, MoveStrategy_default.SMART, _Player.FACE_COORD, _Player.FACE_ENTITY); - this.username = username; - this.username37 = username37; - this.displayName = toDisplayName(username); - this.vars = new Int32Array(VarPlayerType.count); - this.varsString = new Array(VarPlayerType.count); - this.body = [ - 0, - // hair - 10, - // beard - 18, - // body - 26, - // arms - 33, - // gloves - 36, - // legs - 42 - // boots - ]; - this.colors = [0, 0, 0, 0, 0]; - this.gender = 0; - this.runenergy = 1e4; - this.runweight = 0; - this.playtime = 0; - this.lastStats.fill(-1); - this.lastLevels.fill(-1); - } - resetHeroPoints() { - this.heroPoints = new Array(16); - this.heroPoints.fill({ uid: -1, points: 0 }); - } - addHero(uid, points) { - const index = this.heroPoints.findIndex((hero) => hero && hero.uid === uid); - if (index !== -1) { - this.heroPoints[index].points += points; - return; - } - const emptyIndex = this.heroPoints.findIndex((hero) => hero && hero.uid === -1); - if (emptyIndex !== -1) { - this.heroPoints[emptyIndex] = { uid, points }; - return; - } - } - findHero() { - this.heroPoints.sort((a, b) => { - return b.points - a.points; - }); - return this.heroPoints[0]?.uid ?? -1; - } - resetEntity(respawn) { - if (respawn) { - this.faceX = -1; - this.faceZ = -1; - this.orientationX = -1; - this.orientationZ = -1; - } - super.resetPathingEntity(); - this.repathed = false; - this.protect = false; - this.messageColor = null; - this.messageEffect = null; - this.messageType = null; - this.message = null; - } - // ---- - onLogin() { - this.playerLog("Logging in"); - this.write(new IfClose()); - this.write(new UpdateUid192(this.pid)); - this.unsetMapFlag(); - this.write(new ResetAnims()); - this.resetHeroPoints(); - this.write(new ResetClientVarCache()); - for (let varp = 0; varp < this.vars.length; varp++) { - const type = VarPlayerType.get(varp); - const value = this.vars[varp]; - if (type.transmit) { - this.writeVarp(varp, value); - } - } - const loginTrigger = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.LOGIN, -1, -1); - if (loginTrigger) { - this.executeScript(ScriptRunner.init(loginTrigger, this), true); - } - this.lastStepX = this.x - 1; - this.lastStepZ = this.z; - } - triggerMapzone(x, z) { - const trigger = ScriptProvider.getByName(`[mapzone,0_${x >> 6}_${z >> 6}]`); - if (trigger) { - this.enqueueScript(trigger, 1 /* ENGINE */); - } - } - triggerMapzoneExit(x, z) { - const trigger = ScriptProvider.getByName(`[mapzoneexit,0_${x >> 6}_${z >> 6}]`); - if (trigger) { - this.enqueueScript(trigger, 1 /* ENGINE */); - } - } - triggerZone(level, x, z) { - const mx = x >> 6; - const mz = z >> 6; - const lx = (x & 63) >> 3 << 3; - const lz = (z & 63) >> 3 << 3; - const trigger = ScriptProvider.getByName(`[zone,${level}_${mx}_${mz}_${lx}_${lz}]`); - if (trigger) { - this.enqueueScript(trigger, 1 /* ENGINE */); - } - } - triggerZoneExit(level, x, z) { - const mx = x >> 6; - const mz = z >> 6; - const lx = (x & 63) >> 3 << 3; - const lz = (z & 63) >> 3 << 3; - const trigger = ScriptProvider.getByName(`[zoneexit,${level}_${mx}_${mz}_${lx}_${lz}]`); - if (trigger) { - this.enqueueScript(trigger, 1 /* ENGINE */); - } - } - calculateRunWeight() { - this.runweight = 0; - const invs = this.invs.values(); - for (let i = 0; i < this.invs.size; i++) { - const inv = invs.next().value; - if (!inv) { - continue; - } - const invType = InvType.get(inv.type); - if (!invType || !invType.runweight) { - continue; - } - for (let slot = 0; slot < inv.capacity; slot++) { - const item = inv.get(slot); - if (!item) { - continue; - } - const type = ObjType.get(item.id); - if (!type || type.stackable) { - continue; - } - this.runweight += type.weight * item.count; - } - } - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - playerLog(message, ...args) { - } - processEngineQueue() { - for (let request = this.engineQueue.head(); request !== null; request = this.engineQueue.next()) { - const delay = request.delay--; - if (this.canAccess() && delay <= 0) { - const script = ScriptRunner.init(request.script, this, null, request.args); - this.executeScript(script, true); - request.unlink(); - } - } - } - // ---- - updateMovement(repathAllowed = true) { - if (this.containsModalInterface()) { - this.recoverEnergy(false); - return false; - } - if (repathAllowed && this.target instanceof PathingEntity && !this.interacted && this.walktrigger === -1) { - this.pathToPathingTarget(); - } - if (this.hasWaypoints() && this.walktrigger !== -1 && (!this.protect && !this.delayed())) { - const trigger = ScriptProvider.get(this.walktrigger); - this.walktrigger = -1; - if (trigger) { - const script = ScriptRunner.init(trigger, this); - this.runScript(script, true); - } - } - if (this.moveSpeed !== MoveSpeed_default.INSTANT) { - this.moveSpeed = this.defaultMoveSpeed(); - if (this.basRunning === -1) { - this.moveSpeed = MoveSpeed_default.WALK; - } else if (this.getVar(VarPlayerType.TEMP_RUN)) { - this.moveSpeed = MoveSpeed_default.RUN; - } - } - if (!super.processMovement()) { - this.setVar(VarPlayerType.TEMP_RUN, 0); - } - const moved = this.lastX !== this.x || this.lastZ !== this.z; - this.drainEnergy(moved); - this.recoverEnergy(moved); - if (this.runenergy === 0) { - this.setVar(VarPlayerType.PLAYER_RUN, 0); - this.setVar(VarPlayerType.TEMP_RUN, 0); - } - return moved; - } - drainEnergy(moved) { - if (!moved || this.stepsTaken === 0) { - return; - } - if (!this.delayed() && this.moveSpeed === MoveSpeed_default.RUN && this.stepsTaken > 1) { - const weightKg = Math.floor(this.runweight / 1e3); - const clampWeight = Math.min(Math.max(weightKg, 0), 64); - const loss = 67 + 67 * clampWeight / 64 | 0; - this.runenergy = Math.max(this.runenergy - loss, 0); - } - } - recoverEnergy(moved) { - if (!this.delayed() && (!moved || this.moveSpeed !== MoveSpeed_default.RUN) && this.runenergy < 1e4) { - const recovered = (this.baseLevels[PlayerStat_default.AGILITY] / 9 | 0) + 8; - this.runenergy = Math.min(this.runenergy + recovered, 1e4); - } - } - blockWalkFlag() { - return CollisionFlag.PLAYER; - } - defaultMoveSpeed() { - return this.getVar(VarPlayerType.PLAYER_RUN) ? MoveSpeed_default.RUN : MoveSpeed_default.WALK; - } - // ---- - closeSticky() { - if (this.modalSticky !== -1) { - const closeTrigger = ScriptProvider.getByTrigger(ServerTriggerType_default.IF_CLOSE, this.modalSticky); - if (closeTrigger) { - this.enqueueScript(closeTrigger, 1 /* ENGINE */); - } - this.modalSticky = -1; - this.write(new TutorialOpenChat(-1)); - } - } - closeModal() { - if (!this.receivedFirstClose) { - this.receivedFirstClose = true; - return; - } - this.weakQueue.clear(); - if (!this.delayed()) { - this.protect = false; - } - if (this.modalState === 0) { - return; - } - if (this.modalTop !== -1) { - const closeTrigger = ScriptProvider.getByTrigger(ServerTriggerType_default.IF_CLOSE, this.modalTop); - if (closeTrigger) { - this.enqueueScript(closeTrigger, 1 /* ENGINE */); - } - this.modalTop = -1; - } - if (this.modalBottom !== -1) { - const closeTrigger = ScriptProvider.getByTrigger(ServerTriggerType_default.IF_CLOSE, this.modalBottom); - if (closeTrigger) { - this.enqueueScript(closeTrigger, 1 /* ENGINE */); - } - this.modalBottom = -1; - } - if (this.modalSidebar !== -1) { - const closeTrigger = ScriptProvider.getByTrigger(ServerTriggerType_default.IF_CLOSE, this.modalSidebar); - if (closeTrigger) { - this.enqueueScript(closeTrigger, 1 /* ENGINE */); - } - this.modalSidebar = -1; - } - this.modalState = 0; - this.refreshModalClose = true; - } - delayed() { - return this.delay > 0; - } - containsModalInterface() { - return (this.modalState & 1) === 1 || (this.modalState & 2) === 2 || (this.modalState & 16) === 16; - } - busy() { - return this.delayed() || this.containsModalInterface(); - } - canAccess() { - return !this.protect && !this.busy(); - } - /** - * - * @param script - * @param {QueueType} type - * @param delay - * @param args - */ - enqueueScript(script, type = 0 /* NORMAL */, delay = 0, args = []) { - const request = new EntityQueueRequest(type, script, args, delay); - if (type === 1 /* ENGINE */) { - request.delay = 0; - this.engineQueue.addTail(request); - } else if (type === 2 /* WEAK */) { - this.weakQueue.addTail(request); - } else { - this.queue.addTail(request); - } - } - processQueues() { - let hasStrong = false; - for (let request = this.queue.head(); request !== null; request = this.queue.next()) { - if (request.type === 3 /* STRONG */) { - hasStrong = true; - break; - } - } - if (hasStrong) { - this.closeModal(); - } - this.processQueue(); - this.processWeakQueue(); - } - processQueue() { - for (let request = this.queue.head(); request !== null; request = this.queue.next()) { - if (request.type === 3 /* STRONG */) { - this.closeModal(); - } - const delay = request.delay--; - if (this.canAccess() && delay <= 0) { - const script = ScriptRunner.init(request.script, this, null, request.args); - this.executeScript(script, true); - request.unlink(); - } - } - } - processWeakQueue() { - for (let request = this.weakQueue.head(); request !== null; request = this.weakQueue.next()) { - const delay = request.delay--; - if (this.canAccess() && delay <= 0) { - const script = ScriptRunner.init(request.script, this, null, request.args); - this.executeScript(script, true); - request.unlink(); - } - } - } - setTimer(type, script, args = [], interval) { - const timerId = script.id; - const timer = { - type, - script, - args, - interval, - clock: interval - }; - this.timers.set(timerId, timer); - } - clearTimer(timerId) { - this.timers.delete(timerId); - } - processTimers(type) { - for (const timer of this.timers.values()) { - if (type !== timer.type) { - continue; - } - if (--timer.clock <= 0 && (timer.type === 1 /* SOFT */ || this.canAccess())) { - timer.clock = timer.interval; - const script = ScriptRunner.init(timer.script, this, null, timer.args); - this.runScript(script, timer.type === 0 /* NORMAL */); - } - } - } - // clear current interaction and walk queue - stopAction() { - this.clearPendingAction(); - this.unsetMapFlag(); - } - // clear current interaction but leave walk queue intact - clearPendingAction() { - this.clearInteraction(); - this.closeModal(); - } - hasInteraction() { - return this.target !== null; - } - getOpTrigger() { - if (!this.target) { - return null; - } - let typeId = -1; - let categoryId = -1; - if (this.target instanceof Npc || this.target instanceof Loc || this.target instanceof Obj) { - const type = this.target instanceof Npc ? NpcType.get(this.target.type) : this.target instanceof Loc ? LocType.get(this.target.type) : ObjType.get(this.target.type); - typeId = type.id; - categoryId = type.category; - } - if (this.targetSubject.type !== -1) { - typeId = this.targetSubject.type; - } - if (this.targetSubject.com !== -1) { - typeId = this.targetSubject.com; - } - return ScriptProvider.getByTrigger(this.targetOp + 7, typeId, categoryId) ?? null; - } - getApTrigger() { - if (!this.target) { - return null; - } - let typeId = -1; - let categoryId = -1; - if (this.target instanceof Npc || this.target instanceof Loc || this.target instanceof Obj) { - const type = this.target instanceof Npc ? NpcType.get(this.target.type) : this.target instanceof Loc ? LocType.get(this.target.type) : ObjType.get(this.target.type); - typeId = type.id; - categoryId = type.category; - } - if (this.targetSubject.type !== -1) { - typeId = this.targetSubject.type; - } - if (this.targetSubject.com !== -1) { - typeId = this.targetSubject.com; - } - return ScriptProvider.getByTrigger(this.targetOp, typeId, categoryId) ?? null; - } - processInteraction() { - if (this.target === null || !this.canAccess()) { - this.updateMovement(); - return; - } - if (this.target.level !== this.level) { - this.clearInteraction(); - this.unsetMapFlag(); - return; - } - if (this.target instanceof Npc && (typeof World_default.getNpc(this.target.nid) === "undefined" || this.target.delayed())) { - this.clearInteraction(); - this.unsetMapFlag(); - return; - } - if (this.target instanceof Npc && this.targetSubject.type !== -1 && World_default.getNpcByUid(this.targetSubject.type << 16 | this.target.nid) === null) { - this.clearInteraction(); - this.unsetMapFlag(); - return; - } - if (this.target instanceof Obj && World_default.getObj(this.target.x, this.target.z, this.level, this.target.type, this.pid) === null) { - this.clearInteraction(); - this.unsetMapFlag(); - return; - } - if (this.target instanceof Loc && World_default.getLoc(this.target.x, this.target.z, this.level, this.target.type) === null) { - this.clearInteraction(); - this.unsetMapFlag(); - return; - } - if (this.target instanceof _Player && World_default.getPlayerByUid(this.target.uid) === null) { - this.clearInteraction(); - this.unsetMapFlag(); - return; - } - if (this.targetOp === ServerTriggerType_default.APPLAYER3 || this.targetOp === ServerTriggerType_default.OPPLAYER3) { - const moved2 = this.updateMovement(false); - if (moved2) { - this.alreadyFacedEntity = false; - this.lastMovement = World_default.currentTick + 1; - } - return; - } - const opTrigger = this.getOpTrigger(); - const apTrigger = this.getApTrigger(); - if (opTrigger && this.target instanceof PathingEntity && this.inOperableDistance(this.target)) { - const target = this.target; - this.target = null; - this.executeScript(ScriptRunner.init(opTrigger, this, target), true); - if (this.target === null) { - this.unsetMapFlag(); - } - this.interacted = true; - this.clearWaypoints(); - } else if (apTrigger && this.inApproachDistance(this.apRange, this.target)) { - const target = this.target; - this.target = null; - this.executeScript(ScriptRunner.init(apTrigger, this, target), true); - if (this.apRangeCalled) { - this.target = target; - } else { - this.clearWaypoints(); - this.interacted = true; - } - if (this.target === null) { - this.unsetMapFlag(); - } - } else if (this.target instanceof PathingEntity && this.inOperableDistance(this.target)) { - if (Environment_default.NODE_DEBUG && !opTrigger && !apTrigger) { - let debugname = "_"; - if (this.target instanceof Npc) { - if (this.targetSubject.com !== -1 && this.targetOp === ServerTriggerType_default.APNPCT || this.targetOp === ServerTriggerType_default.OPNPCT) { - debugname = Component.get(this.targetSubject.com)?.comName ?? this.targetSubject.toString(); - } else { - debugname = NpcType.get(this.target.type)?.debugname ?? this.target.type.toString(); - } - } else if (this.target instanceof Loc) { - debugname = LocType.get(this.target.type)?.debugname ?? this.target.type.toString(); - } else if (this.target instanceof Obj) { - debugname = ObjType.get(this.target.type)?.debugname ?? this.target.type.toString(); - } else if (this.targetSubject.com !== -1 && this.targetOp === ServerTriggerType_default.APNPCT || this.targetOp === ServerTriggerType_default.APPLAYERT || this.targetOp === ServerTriggerType_default.APLOCT || this.targetOp === ServerTriggerType_default.APOBJT) { - debugname = Component.get(this.targetSubject.com)?.comName ?? this.targetSubject.toString(); - } else if (this.targetSubject.type !== -1) { - debugname = ObjType.get(this.targetSubject.type)?.debugname ?? this.targetSubject.toString(); - } - this.messageGame(`No trigger for [${ServerTriggerType_default[this.targetOp + 7].toLowerCase()},${debugname}]`); - } - this.target = null; - this.messageGame("Nothing interesting happens."); - this.interacted = true; - this.clearWaypoints(); - } - const moved = this.updateMovement(); - if (moved) { - this.alreadyFacedEntity = false; - this.lastMovement = World_default.currentTick + 1; - } - if (this.target && (!this.interacted || this.apRangeCalled)) { - this.interacted = false; - if (opTrigger && (this.target instanceof PathingEntity || !moved) && this.inOperableDistance(this.target)) { - const target = this.target; - this.target = null; - this.executeScript(ScriptRunner.init(opTrigger, this, target), true); - if (this.target === null) { - this.unsetMapFlag(); - } - this.interacted = true; - this.clearWaypoints(); - } else if (apTrigger && this.inApproachDistance(this.apRange, this.target)) { - this.apRangeCalled = false; - const target = this.target; - this.target = null; - this.executeScript(ScriptRunner.init(apTrigger, this, target), true); - if (this.apRangeCalled) { - this.target = target; - } else { - this.clearWaypoints(); - this.interacted = true; - } - if (this.target === null) { - this.unsetMapFlag(); - } - } else if ((this.target instanceof PathingEntity || !moved) && this.inOperableDistance(this.target)) { - if (!Environment_default.NODE_PRODUCTION && !opTrigger && !apTrigger) { - let debugname = "_"; - if (this.target instanceof Npc) { - debugname = NpcType.get(this.target.type)?.debugname ?? this.target.type.toString(); - } else if (this.target instanceof Loc) { - debugname = LocType.get(this.target.type)?.debugname ?? this.target.type.toString(); - } else if (this.target instanceof Obj) { - debugname = ObjType.get(this.target.type)?.debugname ?? this.target.type.toString(); - } else if (this.targetSubject.com !== -1 && this.targetOp === ServerTriggerType_default.APNPCT || this.targetOp === ServerTriggerType_default.APPLAYERT || this.targetOp === ServerTriggerType_default.APLOCT || this.targetOp === ServerTriggerType_default.APOBJT) { - debugname = Component.get(this.targetSubject.com)?.comName ?? this.targetSubject.toString(); - } else if (this.targetSubject.type !== -1) { - debugname = ObjType.get(this.targetSubject.type)?.debugname ?? this.targetSubject.toString(); - } - this.messageGame(`No trigger for [${ServerTriggerType_default[this.targetOp + 7].toLowerCase()},${debugname}]`); - } - this.target = null; - this.messageGame("Nothing interesting happens."); - this.interacted = true; - this.clearWaypoints(); - } - } - if (!this.interactWalkTrigger && this.walktrigger !== -1 && (!this.protect && !this.delayed())) { - const trigger = ScriptProvider.get(this.walktrigger); - this.walktrigger = -1; - if (trigger) { - const script = ScriptRunner.init(trigger, this); - this.interactWalkTrigger = true; - this.unsetMapFlag(); - this.runScript(script, true); - } - } - if (!this.interacted && !this.hasWaypoints() && !moved) { - this.messageGame("I can't reach that!"); - this.clearInteraction(); - } - if (this.interacted && !this.apRangeCalled && this.target === null) { - this.clearInteraction(); - } - } - // ---- - getAppearanceInSlot(slot) { - let part = -1; - if (slot === 8) { - part = this.body[0]; - } else if (slot === 11) { - part = this.body[1]; - } else if (slot === 4) { - part = this.body[2]; - } else if (slot === 6) { - part = this.body[3]; - } else if (slot === 9) { - part = this.body[4]; - } else if (slot === 7) { - part = this.body[5]; - } else if (slot === 10) { - part = this.body[6]; - } - if (part === -1) { - return 0; - } else { - return 256 + part; - } - } - getCombatLevel() { - const base = 0.25 * (this.baseLevels[PlayerStat_default.DEFENCE] + this.baseLevels[PlayerStat_default.HITPOINTS] + Math.floor(this.baseLevels[PlayerStat_default.PRAYER] / 2)); - const melee = 0.325 * (this.baseLevels[PlayerStat_default.ATTACK] + this.baseLevels[PlayerStat_default.STRENGTH]); - const range = 0.325 * (Math.floor(this.baseLevels[PlayerStat_default.RANGED] / 2) + this.baseLevels[PlayerStat_default.RANGED]); - const magic = 0.325 * (Math.floor(this.baseLevels[PlayerStat_default.MAGIC] / 2) + this.baseLevels[PlayerStat_default.MAGIC]); - return Math.floor(base + Math.max(melee, range, magic)); - } - generateAppearance(inv) { - const stream = Packet.alloc(0); - stream.p1(this.gender); - stream.p1(this.headicons); - const skippedSlots = []; - let worn = this.getInventory(inv); - if (!worn) { - worn = new Inventory(InvType.WORN, 0); - } - for (let i = 0; i < worn.capacity; i++) { - const equip = worn.get(i); - if (!equip) { - continue; - } - const config = ObjType.get(equip.id); - if (config.wearpos2 !== -1) { - if (skippedSlots.indexOf(config.wearpos2) === -1) { - skippedSlots.push(config.wearpos2); - } - } - if (config.wearpos3 !== -1) { - if (skippedSlots.indexOf(config.wearpos3) === -1) { - skippedSlots.push(config.wearpos3); - } - } - } - for (let slot = 0; slot < 12; slot++) { - if (skippedSlots.indexOf(slot) !== -1) { - stream.p1(0); - continue; - } - const equip = worn.get(slot); - if (!equip) { - const appearanceValue = this.getAppearanceInSlot(slot); - if (appearanceValue < 1) { - stream.p1(0); - } else { - stream.p2(appearanceValue); - } - } else { - stream.p2(512 + equip.id); - } - } - for (let i = 0; i < this.colors.length; i++) { - stream.p1(this.colors[i]); - } - stream.p2(this.basReadyAnim); - stream.p2(this.basTurnOnSpot); - stream.p2(this.basWalkForward); - stream.p2(this.basWalkBackward); - stream.p2(this.basWalkLeft); - stream.p2(this.basWalkRight); - stream.p2(this.basRunning); - stream.p8(this.username37); - stream.p1(this.combatLevel); - this.mask |= _Player.APPEARANCE; - this.appearance = new Uint8Array(stream.pos); - stream.pos = 0; - stream.gdata(this.appearance, 0, this.appearance.length); - stream.release(); - this.lastAppearance = World_default.currentTick; - } - // ---- - getInventoryFromListener(listener) { - if (listener.source === -1) { - return World_default.getInventory(listener.type); - } else { - const player = World_default.getPlayerByUid(listener.source); - if (!player) { - return null; - } - return player.getInventory(listener.type); - } - } - getInventory(inv) { - if (inv === -1) { - return null; - } - const invType = InvType.get(inv); - let container = null; - if (!invType) { - return null; - } - if (invType.scope === InvType.SCOPE_SHARED) { - container = World_default.getInventory(inv); - } else { - container = this.invs.get(inv); - if (!container) { - container = Inventory.fromType(inv); - this.invs.set(inv, container); - } - } - return container; - } - invListenOnCom(inv, com, source) { - if (inv === -1) { - return; - } - const index = this.invListeners.findIndex((l) => l.type === inv && l.com === com); - if (index !== -1) { - return; - } - const invType = InvType.get(inv); - if (invType.scope === InvType.SCOPE_SHARED) { - source = -1; - } - this.invListeners.push({ type: inv, com, source, firstSeen: true }); - } - invStopListenOnCom(com) { - const index = this.invListeners.findIndex((l) => l.com === com); - if (index === -1) { - return; - } - this.invListeners.splice(index, 1); - this.write(new UpdateInvStopTransmit(com)); - } - invGetSlot(inv, slot) { - const container = this.getInventory(inv); - if (!container) { - throw new Error("invGetSlot: Invalid inventory type: " + inv); - } - if (!container.validSlot(slot)) { - throw new Error("invGetSlot: Invalid slot: " + slot); - } - return container.get(slot); - } - invClear(inv) { - const container = this.getInventory(inv); - if (!container) { - throw new Error("invClear: Invalid inventory type: " + inv); - } - container.removeAll(); - } - invAdd(inv, obj, count, assureFullInsertion = true) { - const container = this.getInventory(inv); - if (!container) { - throw new Error("invAdd: Invalid inventory type: " + inv); - } - const transaction = container.add(obj, count, -1, assureFullInsertion); - return transaction.completed; - } - invSet(inv, obj, count, slot) { - const container = this.getInventory(inv); - if (!container) { - throw new Error("invSet: Invalid inventory type: " + inv); - } - if (!container.validSlot(slot)) { - throw new Error("invSet: Invalid slot: " + slot); - } - container.set(slot, { id: obj, count }); - } - invDel(inv, obj, count, beginSlot = -1) { - const container = this.getInventory(inv); - if (!container) { - throw new Error("invDel: Invalid inventory type: " + inv); - } - if (beginSlot < -1 || beginSlot >= this.invSize(inv)) { - throw new Error("invDel: Invalid beginSlot: " + beginSlot); - } - const transaction = container.remove(obj, count, beginSlot); - return transaction.completed; - } - invDelSlot(inv, slot) { - const container = this.getInventory(inv); - if (!container) { - throw new Error("invDelSlot: Invalid inventory type: " + inv); - } - if (!container.validSlot(slot)) { - throw new Error("invDelSlot: Invalid slot: " + slot); - } - container.delete(slot); - } - invSize(inv) { - const container = this.getInventory(inv); - if (!container) { - throw new Error("invSize: Invalid inventory type: " + inv); - } - return container.capacity; - } - invTotal(inv, obj) { - const container = this.getInventory(inv); - if (!container) { - throw new Error("invTotal: Invalid inventory type: " + inv); - } - return container.getItemCount(obj); - } - invFreeSpace(inv) { - const container = this.getInventory(inv); - if (!container) { - throw new Error("invFreeSpace: Invalid inventory type: " + inv); - } - return container.freeSlotCount; - } - invItemSpace(inv, obj, count, size) { - const container = this.getInventory(inv); - if (!container) { - throw new Error("invItemSpace: Invalid inventory type: " + inv); - } - const objType = ObjType.get(obj); - let uncert = obj; - if (objType.certtemplate >= 0 && objType.certlink >= 0) { - uncert = objType.certlink; - } - if (objType.stackable || uncert != obj || container.stackType == Inventory.ALWAYS_STACK) { - const stockObj = InvType.get(inv).stockobj?.includes(obj) === true; - if (this.invTotal(inv, obj) == 0 && this.invFreeSpace(inv) == 0 && !stockObj) { - return count; - } - return Math.max(0, count - (Inventory.STACK_LIMIT - this.invTotal(inv, obj))); - } - return Math.max(0, count - (this.invFreeSpace(inv) - (this.invSize(inv) - size))); - } - invMoveToSlot(fromInv, toInv, fromSlot, toSlot) { - const from = this.getInventory(fromInv); - if (!from) { - throw new Error("invMoveToSlot: Invalid inventory type: " + fromInv); - } - if (!from.validSlot(fromSlot)) { - throw new Error("invMoveToSlot: Invalid from slot: " + fromSlot); - } - const to = this.getInventory(toInv); - if (!to) { - throw new Error("invMoveToSlot: Invalid inventory type: " + toInv); - } - if (!to.validSlot(toSlot)) { - throw new Error("invMoveToSlot: Invalid to slot: " + toSlot); - } - const fromObj = this.invGetSlot(fromInv, fromSlot); - if (!fromObj) { - throw new Error(`invMoveToSlot: Invalid from obj was null. This means the obj does not exist at this slot: ${fromSlot}`); - } - const toObj = this.invGetSlot(toInv, toSlot); - this.invSet(toInv, fromObj.id, fromObj.count, toSlot); - if (toObj) { - this.invSet(fromInv, toObj.id, toObj.count, fromSlot); - } else { - this.invDelSlot(fromInv, fromSlot); - } - } - invMoveFromSlot(fromInv, toInv, fromSlot) { - const from = this.getInventory(fromInv); - if (!from) { - throw new Error("invMoveFromSlot: Invalid inventory type: " + fromInv); - } - const to = this.getInventory(toInv); - if (!to) { - throw new Error("invMoveFromSlot: Invalid inventory type: " + toInv); - } - if (!from.validSlot(fromSlot)) { - throw new Error("invMoveFromSlot: Invalid from slot: " + fromSlot); - } - const fromObj = this.invGetSlot(fromInv, fromSlot); - if (!fromObj) { - throw new Error(`invMoveFromSlot: Invalid from obj was null. This means the obj does not exist at this slot: ${fromSlot}`); - } - this.invDelSlot(fromInv, fromSlot); - return { - overflow: fromObj.count - this.invAdd(toInv, fromObj.id, fromObj.count, false), - fromObj: fromObj.id - }; - } - invTotalCat(inv, category) { - const container = this.getInventory(inv); - if (!container) { - throw new Error("invTotalCat: Invalid inventory type: " + inv); - } - return container.itemsFiltered.filter((obj) => ObjType.get(obj.id).category == category).reduce((count, obj) => count + obj.count, 0); - } - _invTotalParam(inv, param, stack) { - const container = this.getInventory(inv); - if (!container) { - throw new Error("invTotalParam: Invalid inventory type: " + inv); - } - const paramType = ParamType.get(param); - let total = 0; - for (let slot = 0; slot < container.capacity; slot++) { - const item = container.items[slot]; - if (!item || item.id < 0 || item.id >= ObjType.count) { - continue; - } - const obj = ObjType.get(item.id); - const value = ParamHelper.getIntParam(paramType.id, obj, paramType.defaultInt); - if (stack) { - total += item.count * value; - } else { - total += value; - } - } - return total; - } - invTotalParam(inv, param) { - return this._invTotalParam(inv, param, false); - } - invTotalParamStack(inv, param) { - return this._invTotalParam(inv, param, true); - } - // ---- - getVar(id) { - const varp = VarPlayerType.get(id); - return varp.type === ScriptVarType.STRING ? this.varsString[varp.id] : this.vars[varp.id]; - } - setVar(id, value) { - const varp = VarPlayerType.get(id); - if (varp.type === ScriptVarType.STRING && typeof value === "string") { - this.varsString[varp.id] = value; - } else if (typeof value === "number") { - this.vars[varp.id] = value; - if (varp.transmit) { - this.writeVarp(id, value); - } - } - } - writeVarp(id, value) { - if (value >= -128 && value <= 127) { - this.write(new VarpSmall(id, value)); - } else { - this.write(new VarpLarge(id, value)); - } - } - addXp(stat, xp) { - if (xp < 0) { - throw new Error(`Invalid xp parameter for addXp call: Stat was: ${stat}, Exp was: ${xp}`); - } - if (xp == 0) { - return; - } - const multi = Number(Environment_default.NODE_XPRATE) || 1; - this.stats[stat] += xp * multi; - if (this.stats[stat] > 2e9) { - this.stats[stat] = 2e9; - } - const before = this.baseLevels[stat]; - if (this.levels[stat] === this.baseLevels[stat]) { - this.levels[stat] = getLevelByExp(this.stats[stat]); - } - this.baseLevels[stat] = getLevelByExp(this.stats[stat]); - if (this.baseLevels[stat] > before) { - if (this.levels[stat] < before) { - this.levels[stat] += 1; - } - const script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.ADVANCESTAT, stat, -1); - if (script) { - this.enqueueScript(script, 1 /* ENGINE */); - } - } - if (this.combatLevel != this.getCombatLevel()) { - this.combatLevel = this.getCombatLevel(); - this.generateAppearance(InvType.WORN); - } - } - setLevel(stat, level) { - level = Math.min(99, Math.max(1, level)); - this.baseLevels[stat] = level; - this.levels[stat] = level; - this.stats[stat] = getExpByLevel(level); - if (this.getCombatLevel() != this.combatLevel) { - this.combatLevel = this.getCombatLevel(); - this.generateAppearance(InvType.WORN); - } - } - playAnimation(anim, delay) { - if (anim >= SeqType.count || this.animProtect) { - return; - } - if (anim == -1 || this.animId == -1 || SeqType.get(anim).priority > SeqType.get(this.animId).priority || SeqType.get(this.animId).priority === 0) { - this.animId = anim; - this.animDelay = delay; - this.mask |= _Player.ANIM; - } - } - spotanim(spotanim, height, delay) { - this.graphicId = spotanim; - this.graphicHeight = height; - this.graphicDelay = delay; - this.mask |= _Player.SPOTANIM; - } - applyDamage(damage, type) { - this.damageTaken = damage; - this.damageType = type; - const current = this.levels[PlayerStat_default.HITPOINTS]; - if (current - damage <= 0) { - this.levels[PlayerStat_default.HITPOINTS] = 0; - this.damageTaken = current; - } else { - this.levels[PlayerStat_default.HITPOINTS] = current - damage; - } - this.mask |= _Player.DAMAGE; - } - say(message) { - this.chat = message; - this.mask |= _Player.SAY; - } - faceSquare(x, z) { - this.faceX = x * 2 + 1; - this.faceZ = z * 2 + 1; - this.orientationX = this.faceX; - this.orientationZ = this.faceZ; - this.mask |= _Player.FACE_COORD; - } - playSong(name) { - name = name.toLowerCase().replaceAll(" ", "_"); - if (!name) { - return; - } - const song = PRELOADED.get(name + ".mid"); - const crc = PRELOADED_CRC.get(name + ".mid"); - if (song && crc) { - const length = song.length; - this.write(new MidiSong(name, crc, length)); - } - } - playJingle(delay, name) { - name = name.toLowerCase().replaceAll("_", " "); - if (!name) { - return; - } - const jingle = PRELOADED.get(name + ".mid"); - if (jingle) { - this.write(new MidiJingle(delay, jingle)); - } - } - openMainModal(com) { - if (this.modalState & 4) { - this.write(new IfClose()); - this.modalState &= ~4; - this.modalSidebar = -1; - } - this.modalState |= 1; - this.modalTop = com; - this.refreshModal = true; - } - openChat(com) { - this.modalState |= 2; - this.modalBottom = com; - this.refreshModal = true; - } - openSideOverlay(com) { - this.modalState |= 4; - this.modalSidebar = com; - this.refreshModal = true; - } - openChatSticky(com) { - this.write(new TutorialOpenChat(com)); - this.modalState |= 8; - this.modalSticky = com; - } - openMainModalSideOverlay(top, side) { - this.modalState |= 1; - this.modalTop = top; - this.modalState |= 4; - this.modalSidebar = side; - this.refreshModal = true; - } - exactMove(startX, startZ, endX, endZ, startCycle, endCycle, direction) { - this.exactStartX = startX; - this.exactStartZ = startZ; - this.exactEndX = endX; - this.exactEndZ = endZ; - this.exactMoveStart = startCycle; - this.exactMoveEnd = endCycle; - this.exactMoveDirection = direction; - this.mask |= _Player.EXACT_MOVE; - this.x = endX; - this.z = endZ; - this.lastStepX = this.x - 1; - this.lastStepZ = this.z; - } - setTab(com, tab) { - this.overlaySide[tab] = com; - this.write(new IfOpenSideOverlay(com, tab)); - } - isComponentVisible(com) { - return this.modalTop === com.rootLayer || this.modalBottom === com.rootLayer || this.modalSidebar === com.rootLayer || this.overlaySide.findIndex((l) => l === com.rootLayer) !== -1 || this.modalSticky === com.rootLayer; - } - updateAfkZones() { - this.lastAfkZone = Math.min(1e3, this.lastAfkZone + 1); - if (this.withinAfkZone()) { - return; - } - const coord = Position.packCoord(0, this.x - 10, this.z - 10); - if (this.moveSpeed === MoveSpeed_default.INSTANT && this.jump) { - this.afkZones[1] = coord; - } else { - this.afkZones[1] = this.afkZones[0]; - } - this.afkZones[0] = coord; - this.lastAfkZone = 0; - } - zonesAfk() { - return this.lastAfkZone === 1e3; - } - withinAfkZone() { - const size = 21; - for (let index = 0; index < this.afkZones.length; index++) { - const coord = Position.unpackCoord(this.afkZones[index]); - if (Position.intersects(this.x, this.z, this.width, this.length, coord.x, coord.z, size, size)) { - return true; - } - } - return false; - } - // copied from client - isInWilderness() { - if (this.x >= 2944 && this.x < 3392 && this.z >= 3520 && this.z < 6400) { - return true; - } else if (this.x >= 2944 && this.x < 3392 && this.z >= 9920 && this.z < 12800) { - return true; - } else { - return false; - } - } - // ---- - runScript(script, protect = false, force = false) { - if (!force && protect && (this.protect || this.delayed())) { - return -1; - } - if (protect) { - script.pointerAdd(ScriptPointer_default.ProtectedActivePlayer); - this.protect = true; - } - const state = ScriptRunner.execute(script); - if (protect) { - this.protect = false; - } - if (script.pointerGet(ScriptPointer_default.ProtectedActivePlayer) && script._activePlayer) { - script.pointerRemove(ScriptPointer_default.ProtectedActivePlayer); - script._activePlayer.protect = false; - } - if (script.pointerGet(ScriptPointer_default.ProtectedActivePlayer2) && script._activePlayer2) { - script.pointerRemove(ScriptPointer_default.ProtectedActivePlayer2); - script._activePlayer2.protect = false; - } - return state; - } - executeScript(script, protect = false, force = false) { - const state = this.runScript(script, protect, force); - if (state === -1) { - return; - } - if (state !== ScriptState.FINISHED && state !== ScriptState.ABORTED) { - if (state === ScriptState.WORLD_SUSPENDED) { - World_default.enqueueScript(script, script.popInt()); - } else if (state === ScriptState.NPC_SUSPENDED) { - script.activeNpc.activeScript = script; - } else { - script.activePlayer.activeScript = script; - script.activePlayer.protect = protect; - } - } else if (script === this.activeScript) { - this.activeScript = null; - if ((this.modalState & 1) == 0) { - this.closeModal(); - } - } - } - wrappedMessageGame(mes) { - const font = FontType.get(1); - const lines = font.split(mes, 456); - for (const line of lines) { - this.messageGame(line); - } - } - write(message) { - if (message.priority === ServerProtPriority.HIGH) { - this.highPriorityOut.push(message); - } else { - this.lowPriorityOut.push(message); - } - } - unsetMapFlag() { - this.clearWaypoints(); - this.write(new UnsetMapFlag()); - } - hintNpc(nid) { - this.write(new HintArrow(1, nid, 0, 0, 0, 0)); - } - hintTile(offset, x, z, height) { - this.write(new HintArrow(offset, 0, 0, x, z, height)); - } - hintPlayer(pid) { - this.write(new HintArrow(10, 0, pid, 0, 0, 0)); - } - stopHint() { - this.write(new HintArrow(-1, 0, 0, 0, 0, 0)); - } - lastLoginInfo(lastLoginIp, daysSinceLogin, daysSinceRecoveryChange, unreadMessageCount) { - this.write(new LastLoginInfo(lastLoginIp, daysSinceLogin, daysSinceRecoveryChange, unreadMessageCount)); - this.modalState |= 16; - } - logout() { - } - terminate() { - } - messageGame(msg) { - this.write(new MessageGame(msg)); - } -}; - -// src/lostcity/network/225/incoming/prot/ClientProt.ts -var ClientProt = class _ClientProt { - // NXT naming - // in these old revisions we can actually get the packet index from a leftover array in the client source - constructor(index, id, length) { - this.index = index; - this.id = id; - this.length = length; - _ClientProt.all[index] = this; - _ClientProt.byId[id] = this; - } - static all = []; - static byId = []; - static REBUILD_GETMAPS = new _ClientProt(4, 150, -1); - static NO_TIMEOUT = new _ClientProt(6, 108, 0); - // NXT naming - static IDLE_TIMER = new _ClientProt(30, 70, 0); - static EVENT_TRACKING = new _ClientProt(34, 81, -2); - static EVENT_CAMERA_POSITION = new _ClientProt(35, 189, 6); - // NXT naming - // autogenerated as part of obfuscation process - static ANTICHEAT_OPLOGIC1 = new _ClientProt(60, 7, 4); - static ANTICHEAT_OPLOGIC2 = new _ClientProt(61, 88, 4); - static ANTICHEAT_OPLOGIC3 = new _ClientProt(62, 30, 3); - static ANTICHEAT_OPLOGIC4 = new _ClientProt(63, 176, 2); - static ANTICHEAT_OPLOGIC5 = new _ClientProt(64, 220, 0); - static ANTICHEAT_OPLOGIC6 = new _ClientProt(65, 66, 4); - static ANTICHEAT_OPLOGIC7 = new _ClientProt(66, 17, 4); - static ANTICHEAT_OPLOGIC8 = new _ClientProt(67, 2, 2); - static ANTICHEAT_OPLOGIC9 = new _ClientProt(68, 238, 1); - // autogenerated as part of obfuscation process - static ANTICHEAT_CYCLELOGIC1 = new _ClientProt(70, 233, 1); - static ANTICHEAT_CYCLELOGIC2 = new _ClientProt(71, 146, -1); - static ANTICHEAT_CYCLELOGIC3 = new _ClientProt(74, 215, 3); - static ANTICHEAT_CYCLELOGIC4 = new _ClientProt(72, 236, 4); - static ANTICHEAT_CYCLELOGIC5 = new _ClientProt(75, 85, 0); - static ANTICHEAT_CYCLELOGIC6 = new _ClientProt(73, 219, -1); - static OPOBJ1 = new _ClientProt(80, 140, 6); - // NXT naming - static OPOBJ2 = new _ClientProt(81, 40, 6); - // NXT naming - static OPOBJ3 = new _ClientProt(82, 200, 6); - // NXT naming - static OPOBJ4 = new _ClientProt(83, 178, 6); - // NXT naming - static OPOBJ5 = new _ClientProt(84, 247, 6); - // NXT naming - static OPOBJT = new _ClientProt(88, 138, 8); - // NXT naming - static OPOBJU = new _ClientProt(89, 239, 12); - // NXT naming - static OPNPC1 = new _ClientProt(100, 194, 2); - // NXT naming - static OPNPC2 = new _ClientProt(101, 8, 2); - // NXT naming - static OPNPC3 = new _ClientProt(102, 27, 2); - // NXT naming - static OPNPC4 = new _ClientProt(103, 113, 2); - // NXT naming - static OPNPC5 = new _ClientProt(104, 100, 2); - // NXT naming - static OPNPCT = new _ClientProt(108, 134, 4); - // NXT naming - static OPNPCU = new _ClientProt(109, 202, 8); - // NXT naming - static OPLOC1 = new _ClientProt(120, 245, 6); - // NXT naming - static OPLOC2 = new _ClientProt(121, 172, 6); - // NXT naming - static OPLOC3 = new _ClientProt(122, 96, 6); - // NXT naming - static OPLOC4 = new _ClientProt(123, 97, 6); - // NXT naming - static OPLOC5 = new _ClientProt(124, 116, 6); - // NXT naming - static OPLOCT = new _ClientProt(128, 9, 8); - // NXT naming - static OPLOCU = new _ClientProt(129, 75, 12); - // NXT naming - static OPPLAYER1 = new _ClientProt(140, 164, 2); - // NXT naming - static OPPLAYER2 = new _ClientProt(141, 53, 2); - // NXT naming - static OPPLAYER3 = new _ClientProt(142, 185, 2); - // NXT naming - static OPPLAYER4 = new _ClientProt(143, 206, 2); - // NXT naming - static OPPLAYERT = new _ClientProt(148, 177, 4); - // NXT naming - static OPPLAYERU = new _ClientProt(149, 248, 8); - // NXT naming - static OPHELD1 = new _ClientProt(160, 195, 6); - // name based on runescript trigger - static OPHELD2 = new _ClientProt(161, 71, 6); - // name based on runescript trigger - static OPHELD3 = new _ClientProt(162, 133, 6); - // name based on runescript trigger - static OPHELD4 = new _ClientProt(163, 157, 6); - // name based on runescript trigger - static OPHELD5 = new _ClientProt(164, 211, 6); - // name based on runescript trigger - static OPHELDT = new _ClientProt(168, 48, 8); - // name based on runescript trigger - static OPHELDU = new _ClientProt(169, 130, 12); - // name based on runescript trigger - static INV_BUTTON1 = new _ClientProt(190, 31, 6); - // NXT has "IF_BUTTON1" but for our interface system, this makes more sense - static INV_BUTTON2 = new _ClientProt(191, 59, 6); - // NXT has "IF_BUTTON2" but for our interface system, this makes more sense - static INV_BUTTON3 = new _ClientProt(192, 212, 6); - // NXT has "IF_BUTTON3" but for our interface system, this makes more sense - static INV_BUTTON4 = new _ClientProt(193, 38, 6); - // NXT has "IF_BUTTON4" but for our interface system, this makes more sense - static INV_BUTTON5 = new _ClientProt(194, 6, 6); - // NXT has "IF_BUTTON5" but for our interface system, this makes more sense - static IF_BUTTON = new _ClientProt(200, 155, 2); - // NXT naming - static RESUME_PAUSEBUTTON = new _ClientProt(201, 235, 2); - // NXT naming - static CLOSE_MODAL = new _ClientProt(202, 231, 0); - // NXT naming - static RESUME_P_COUNTDIALOG = new _ClientProt(203, 237, 4); - // NXT naming - static TUTORIAL_CLICKSIDE = new _ClientProt(204, 175, 1); - static MOVE_OPCLICK = new _ClientProt(242, 93, -1); - // comes with OP packets, name based on other MOVE packets - static BUG_REPORT = new _ClientProt(243, 190, 10); - // NXT naming - static MOVE_MINIMAPCLICK = new _ClientProt(244, 165, -1); - // NXT naming - static INV_BUTTOND = new _ClientProt(245, 159, 6); - // NXT has "IF_BUTTOND" but for our interface system, this makes more sense - static IGNORELIST_DEL = new _ClientProt(246, 171, 8); - // NXT naming - static IGNORELIST_ADD = new _ClientProt(247, 79, 8); - // NXT naming - static IF_PLAYERDESIGN = new _ClientProt(248, 52, 13); - static CHAT_SETMODE = new _ClientProt(249, 244, 3); - // NXT naming - static MESSAGE_PRIVATE = new _ClientProt(250, 148, -1); - // NXT naming - static FRIENDLIST_DEL = new _ClientProt(251, 11, 8); - // NXT naming - static FRIENDLIST_ADD = new _ClientProt(252, 118, 8); - // NXT naming - static CLIENT_CHEAT = new _ClientProt(253, 4, -1); - // NXT naming - static MESSAGE_PUBLIC = new _ClientProt(254, 158, -1); - // NXT naming - static MOVE_GAMECLICK = new _ClientProt(255, 181, -1); -}; - -// src/lostcity/network/incoming/codec/MessageDecoder.ts -var MessageDecoder = class { -}; - -// src/lostcity/network/incoming/IncomingMessage.ts -var IncomingMessage = class { -}; - -// src/lostcity/network/incoming/prot/ClientProtCategory.ts -var ClientProtCategory = class _ClientProtCategory { - // packet decoding limit per tick, exceeding this ends decoding and picks up where it left off on the next tick - constructor(id, limit) { - this.id = id; - this.limit = limit; - } - // todo: measure how many events we should expect to receive from the client - // osrs has this as 50/10 but we know that's not true in rs2 - // todo: determine which packets belong in which category for this era - static CLIENT_EVENT = new _ClientProtCategory(0, 20); - static USER_EVENT = new _ClientProtCategory(1, 5); -}; - -// src/lostcity/network/incoming/model/ClientCheat.ts -var ClientCheat = class extends IncomingMessage { - constructor(input) { - super(); - this.input = input; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/ClientCheatDecoder.ts -var ClientCheatDecoder = class extends MessageDecoder { - prot = ClientProt.CLIENT_CHEAT; - decode(buf) { - const input = buf.gjstr(); - return new ClientCheat(input); - } -}; - -// src/lostcity/network/incoming/model/CloseModal.ts -var CloseModal = class extends IncomingMessage { - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/CloseModalDecoder.ts -var CloseModalDecoder = class extends MessageDecoder { - prot = ClientProt.CLOSE_MODAL; - decode() { - return new CloseModal(); - } -}; - -// src/lostcity/network/incoming/model/IdleTimer.ts -var IdleTimer = class extends IncomingMessage { - category = ClientProtCategory.CLIENT_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/IdleTimerDecoder.ts -var IdleTimerDecoder = class extends MessageDecoder { - prot = ClientProt.IDLE_TIMER; - decode() { - return new IdleTimer(); - } -}; - -// src/lostcity/network/incoming/model/IfButton.ts -var IfButton = class extends IncomingMessage { - constructor(component) { - super(); - this.component = component; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/IfButtonDecoder.ts -var IfButtonDecoder = class extends MessageDecoder { - prot = ClientProt.IF_BUTTON; - decode(buf) { - const component = buf.g2(); - return new IfButton(component); - } -}; - -// src/lostcity/network/incoming/model/IfPlayerDesign.ts -var IfPlayerDesign = class extends IncomingMessage { - constructor(gender, idkit, color) { - super(); - this.gender = gender; - this.idkit = idkit; - this.color = color; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/IfPlayerDesignDecoder.ts -var IfPlayerDesignDecoder = class extends MessageDecoder { - prot = ClientProt.IF_PLAYERDESIGN; - decode(buf) { - const gender = buf.g1(); - const idkit = []; - for (let i = 0; i < 7; i++) { - idkit[i] = buf.g1(); - if (idkit[i] === 255) { - idkit[i] = -1; - } - } - const color = []; - for (let i = 0; i < 5; i++) { - color[i] = buf.g1(); - } - return new IfPlayerDesign(gender, idkit, color); - } -}; - -// src/lostcity/network/incoming/model/InvButton.ts -var InvButton = class extends IncomingMessage { - constructor(op, obj, slot, component) { - super(); - this.op = op; - this.obj = obj; - this.slot = slot; - this.component = component; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/InvButtonDecoder.ts -var InvButtonDecoder = class extends MessageDecoder { - constructor(prot, op) { - super(); - this.prot = prot; - this.op = op; - } - decode(buf) { - const obj = buf.g2(); - const slot = buf.g2(); - const component = buf.g2(); - return new InvButton(this.op, obj, slot, component); - } -}; - -// src/lostcity/network/incoming/model/InvButtonD.ts -var InvButtonD = class extends IncomingMessage { - constructor(component, slot, targetSlot) { - super(); - this.component = component; - this.slot = slot; - this.targetSlot = targetSlot; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/InvButtonDDecoder.ts -var InvButtonDDecoder = class extends MessageDecoder { - prot = ClientProt.INV_BUTTOND; - decode(buf) { - const component = buf.g2(); - const slot = buf.g2(); - const targetSlot = buf.g2(); - return new InvButtonD(component, slot, targetSlot); - } -}; - -// src/lostcity/network/incoming/model/MessagePrivate.ts -var MessagePrivate2 = class extends IncomingMessage { - constructor(username, input) { - super(); - this.username = username; - this.input = input; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/MessagePrivateDecoder.ts -var MessagePrivateDecoder = class extends MessageDecoder { - prot = ClientProt.MESSAGE_PRIVATE; - decode(buf) { - const username = buf.g8(); - const input = WordPack.unpack(buf, buf.length - 8); - return new MessagePrivate2(username, input); - } -}; - -// src/lostcity/network/incoming/model/MessagePublic.ts -var MessagePublic = class extends IncomingMessage { - constructor(input, color, effect) { - super(); - this.input = input; - this.color = color; - this.effect = effect; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/MessagePublicDecoder.ts -var MessagePublicDecoder = class extends MessageDecoder { - prot = ClientProt.MESSAGE_PUBLIC; - decode(buf) { - const color = buf.g1(); - const effect = buf.g1(); - const input = WordPack.unpack(buf, buf.length - 2); - return new MessagePublic(input, color, effect); - } -}; - -// src/lostcity/network/incoming/model/OpHeld.ts -var OpHeld = class extends IncomingMessage { - constructor(op, obj, slot, component) { - super(); - this.op = op; - this.obj = obj; - this.slot = slot; - this.component = component; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/OpHeldDecoder.ts -var OpHeldDecoder = class extends MessageDecoder { - constructor(prot, op) { - super(); - this.prot = prot; - this.op = op; - } - decode(buf) { - const obj = buf.g2(); - const slot = buf.g2(); - const component = buf.g2(); - return new OpHeld(this.op, obj, slot, component); - } -}; - -// src/lostcity/network/incoming/model/OpHeldT.ts -var OpHeldT = class extends IncomingMessage { - constructor(obj, slot, component, spellComponent) { - super(); - this.obj = obj; - this.slot = slot; - this.component = component; - this.spellComponent = spellComponent; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/OpHeldTDecoder.ts -var OpHeldTDecoder = class extends MessageDecoder { - prot = ClientProt.OPHELDT; - decode(buf) { - const obj = buf.g2(); - const slot = buf.g2(); - const component = buf.g2(); - const spellComponent = buf.g2(); - return new OpHeldT(obj, slot, component, spellComponent); - } -}; - -// src/lostcity/network/incoming/model/OpHeldU.ts -var OpHeldU = class extends IncomingMessage { - constructor(obj, slot, component, useObj, useSlot, useComponent) { - super(); - this.obj = obj; - this.slot = slot; - this.component = component; - this.useObj = useObj; - this.useSlot = useSlot; - this.useComponent = useComponent; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/OpHeldUDecoder.ts -var OpHeldUDecoder = class extends MessageDecoder { - prot = ClientProt.OPHELDU; - decode(buf) { - const obj = buf.g2(); - const slot = buf.g2(); - const component = buf.g2(); - const useObj = buf.g2(); - const useSlot = buf.g2(); - const useComponent = buf.g2(); - return new OpHeldU(obj, slot, component, useObj, useSlot, useComponent); - } -}; - -// src/lostcity/network/incoming/model/OpLoc.ts -var OpLoc = class extends IncomingMessage { - constructor(op, x, z, loc) { - super(); - this.op = op; - this.x = x; - this.z = z; - this.loc = loc; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/OpLocDecoder.ts -var OpLocDecoder = class extends MessageDecoder { - constructor(prot, op) { - super(); - this.prot = prot; - this.op = op; - } - decode(buf) { - const x = buf.g2(); - const z = buf.g2(); - const loc = buf.g2(); - return new OpLoc(this.op, x, z, loc); - } -}; - -// src/lostcity/network/incoming/model/OpLocT.ts -var OpLocT = class extends IncomingMessage { - constructor(x, z, loc, spellComponent) { - super(); - this.x = x; - this.z = z; - this.loc = loc; - this.spellComponent = spellComponent; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/OpLocTDecoder.ts -var OpLocTDecoder = class extends MessageDecoder { - prot = ClientProt.OPLOCT; - decode(buf) { - const x = buf.g2(); - const z = buf.g2(); - const loc = buf.g2(); - const spellComponent = buf.g2(); - return new OpLocT(x, z, loc, spellComponent); - } -}; - -// src/lostcity/network/incoming/model/OpLocU.ts -var OpLocU = class extends IncomingMessage { - constructor(x, z, loc, useObj, useSlot, useComponent) { - super(); - this.x = x; - this.z = z; - this.loc = loc; - this.useObj = useObj; - this.useSlot = useSlot; - this.useComponent = useComponent; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/OpLocUDecoder.ts -var OpLocUDecoder = class extends MessageDecoder { - prot = ClientProt.OPLOCU; - decode(buf) { - const x = buf.g2(); - const z = buf.g2(); - const loc = buf.g2(); - const useObj = buf.g2(); - const useSlot = buf.g2(); - const useComponent = buf.g2(); - return new OpLocU(x, z, loc, useObj, useSlot, useComponent); - } -}; - -// src/lostcity/network/incoming/model/OpNpc.ts -var OpNpc = class extends IncomingMessage { - constructor(op, nid) { - super(); - this.op = op; - this.nid = nid; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/OpNpcDecoder.ts -var OpNpcDecoder = class extends MessageDecoder { - constructor(prot, op) { - super(); - this.prot = prot; - this.op = op; - } - decode(buf) { - const nid = buf.g2(); - return new OpNpc(this.op, nid); - } -}; - -// src/lostcity/network/incoming/model/OpNpcT.ts -var OpNpcT = class extends IncomingMessage { - constructor(nid, spellComponent) { - super(); - this.nid = nid; - this.spellComponent = spellComponent; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/OpNpcTDecoder.ts -var OpNpcTDecoder = class extends MessageDecoder { - prot = ClientProt.OPNPCT; - decode(buf) { - const nid = buf.g2(); - const spellComponent = buf.g2(); - return new OpNpcT(nid, spellComponent); - } -}; - -// src/lostcity/network/incoming/model/OpNpcU.ts -var OpNpcU = class extends IncomingMessage { - constructor(nid, useObj, useSlot, useComponent) { - super(); - this.nid = nid; - this.useObj = useObj; - this.useSlot = useSlot; - this.useComponent = useComponent; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/OpNpcUDecoder.ts -var OpNpcUDecoder = class extends MessageDecoder { - prot = ClientProt.OPNPCU; - decode(buf) { - const nid = buf.g2(); - const useObj = buf.g2(); - const useSlot = buf.g2(); - const useComponent = buf.g2(); - return new OpNpcU(nid, useObj, useSlot, useComponent); - } -}; - -// src/lostcity/network/incoming/model/OpObj.ts -var OpObj = class extends IncomingMessage { - constructor(op, x, z, obj) { - super(); - this.op = op; - this.x = x; - this.z = z; - this.obj = obj; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/OpObjDecoder.ts -var OpObjDecoder = class extends MessageDecoder { - constructor(prot, op) { - super(); - this.prot = prot; - this.op = op; - } - decode(buf) { - const x = buf.g2(); - const z = buf.g2(); - const obj = buf.g2(); - return new OpObj(this.op, x, z, obj); - } -}; - -// src/lostcity/network/incoming/model/OpObjT.ts -var OpObjT = class extends IncomingMessage { - constructor(x, z, obj, spellComponent) { - super(); - this.x = x; - this.z = z; - this.obj = obj; - this.spellComponent = spellComponent; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/OpObjTDecoder.ts -var OpObjTDecoder = class extends MessageDecoder { - prot = ClientProt.OPOBJT; - decode(buf) { - const x = buf.g2(); - const z = buf.g2(); - const obj = buf.g2(); - const spellComponent = buf.g2(); - return new OpObjT(x, z, obj, spellComponent); - } -}; - -// src/lostcity/network/incoming/model/OpObjU.ts -var OpObjU = class extends IncomingMessage { - constructor(x, z, obj, useObj, useSlot, useComponent) { - super(); - this.x = x; - this.z = z; - this.obj = obj; - this.useObj = useObj; - this.useSlot = useSlot; - this.useComponent = useComponent; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/OpObjUDecoder.ts -var OpObjUDecoder = class extends MessageDecoder { - prot = ClientProt.OPOBJU; - decode(buf) { - const x = buf.g2(); - const z = buf.g2(); - const obj = buf.g2(); - const useObj = buf.g2(); - const useSlot = buf.g2(); - const useComponent = buf.g2(); - return new OpObjU(x, z, obj, useObj, useSlot, useComponent); - } -}; - -// src/lostcity/network/incoming/model/OpPlayer.ts -var OpPlayer = class extends IncomingMessage { - constructor(op, pid) { - super(); - this.op = op; - this.pid = pid; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/OpPlayerDecoder.ts -var OpPlayerDecoder = class extends MessageDecoder { - constructor(prot, op) { - super(); - this.prot = prot; - this.op = op; - } - decode(buf) { - const pid = buf.g2(); - return new OpPlayer(this.op, pid); - } -}; - -// src/lostcity/network/incoming/model/OpPlayerT.ts -var OpPlayerT = class extends IncomingMessage { - constructor(pid, spellComponent) { - super(); - this.pid = pid; - this.spellComponent = spellComponent; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/OpPlayerTDecoder.ts -var OpPlayerTDecoder = class extends MessageDecoder { - prot = ClientProt.OPPLAYERT; - decode(buf) { - const pid = buf.g2(); - const spellComponent = buf.g2(); - return new OpPlayerT(pid, spellComponent); - } -}; - -// src/lostcity/network/incoming/model/OpPlayerU.ts -var OpPlayerU = class extends IncomingMessage { - constructor(pid, useObj, useSlot, useComponent) { - super(); - this.pid = pid; - this.useObj = useObj; - this.useSlot = useSlot; - this.useComponent = useComponent; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/OpPlayerUDecoder.ts -var OpPlayerUDecoder = class extends MessageDecoder { - prot = ClientProt.OPPLAYERU; - decode(buf) { - const pid = buf.g2(); - const useObj = buf.g2(); - const useSlot = buf.g2(); - const useComponent = buf.g2(); - return new OpPlayerU(pid, useObj, useSlot, useComponent); - } -}; - -// src/lostcity/network/incoming/model/RebuildGetMaps.ts -var RebuildGetMaps = class extends IncomingMessage { - constructor(maps2) { - super(); - this.maps = maps2; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/RebuildGetMapsDecoder.ts -var RebuildGetMapsDecoder = class extends MessageDecoder { - prot = ClientProt.REBUILD_GETMAPS; - decode(buf) { - const maps2 = []; - const count = buf.length / 3; - for (let i = 0; i < count; i++) { - const type = buf.g1(); - const x = buf.g1(); - const z = buf.g1(); - maps2.push({ type, x, z }); - } - return new RebuildGetMaps(maps2); - } -}; - -// src/lostcity/network/incoming/model/ResumePauseButton.ts -var ResumePauseButton = class extends IncomingMessage { - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/ResumePauseButtonDecoder.ts -var ResumePauseButtonDecoder = class extends MessageDecoder { - prot = ClientProt.RESUME_PAUSEBUTTON; - decode() { - return new ResumePauseButton(); - } -}; - -// src/lostcity/network/incoming/model/ResumePCountDialog.ts -var ResumePCountDialog = class extends IncomingMessage { - constructor(input) { - super(); - this.input = input; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/ResumePCountDialogDecoder.ts -var ResumePCountDialogDecoder = class extends MessageDecoder { - prot = ClientProt.RESUME_P_COUNTDIALOG; - decode(buf) { - const input = buf.g4(); - return new ResumePCountDialog(input); - } -}; - -// src/lostcity/network/incoming/model/TutorialClickSide.ts -var TutorialClickSide = class extends IncomingMessage { - constructor(tab) { - super(); - this.tab = tab; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/TutorialClickSideDecoder.ts -var TutorialClickSideDecoder = class extends MessageDecoder { - prot = ClientProt.TUTORIAL_CLICKSIDE; - decode(buf) { - const tab = buf.g1(); - return new TutorialClickSide(tab); - } -}; - -// src/lostcity/network/incoming/handler/MessageHandler.ts -var MessageHandler = class { -}; - -// src/lostcity/network/225/incoming/handler/InvButtonHandler.ts -var InvButtonHandler = class extends MessageHandler { - handle(message, player) { - const { op, obj: item, slot, component: comId } = message; - const com = Component.get(comId); - if (typeof com === "undefined" || !com.inventoryOptions || !com.inventoryOptions.length || !player.isComponentVisible(com)) { - return false; - } - if (!com.inventoryOptions[op - 1]) { - return false; - } - const listener = player.invListeners.find((l) => l.com === comId); - if (!listener) { - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { - return false; - } - if (player.delayed()) { - return false; - } - player.lastItem = item; - player.lastSlot = slot; - let trigger; - if (op === 1) { - trigger = ServerTriggerType_default.INV_BUTTON1; - } else if (op === 2) { - trigger = ServerTriggerType_default.INV_BUTTON2; - } else if (op === 3) { - trigger = ServerTriggerType_default.INV_BUTTON3; - } else if (op === 4) { - trigger = ServerTriggerType_default.INV_BUTTON4; - } else { - trigger = ServerTriggerType_default.INV_BUTTON5; - } - const script = ScriptProvider.getByTrigger(trigger, comId, -1); - if (script) { - const root = Component.get(com.rootLayer); - player.executeScript(ScriptRunner.init(script, player), root.overlay == false); - } else if (Environment_default.NODE_DEBUG) { - player.messageGame(`No trigger for [${ServerTriggerType_default.toString(trigger)},${com.comName}]`); - } - return true; - } -}; - -// src/lostcity/server/ClientSocket.ts -var ClientSocket = class _ClientSocket { - static TCP = 0; - static WEBSOCKET = 1; - socket = null; - type = -1; - state = -1; - remoteAddress; - totalBytesRead = 0; - totalBytesWritten = 0; - uniqueId; - encryptor = null; - decryptor = null; - // we only want to receive 5KB per tick to mitigate bad actors - in = new Uint8Array(5e3); - inOffset = 0; - // we limit the amount of packets we receive per opcode (no more than 10) to mitigate bad actors - inCount = new Uint8Array(256); - // packets are flushed in up to 5KB chunks - // out = new Uint8Array(5000); - // outOffset = 0; - out = new Packet(new Uint8Array(5e3)); - player = null; - constructor(socket, remoteAddress, type = _ClientSocket.TCP, state = -1, uniqueId = randomUUID()) { - this.socket = socket; - this.remoteAddress = remoteAddress; - this.type = type; - this.state = state; - this.uniqueId = uniqueId; - } - isTCP() { - return this.type === _ClientSocket.TCP; - } - isWebSocket() { - return this.type === _ClientSocket.WEBSOCKET; - } - send(data) { - if (!this.socket) { - return; - } - this.totalBytesWritten += data.length; - if (this.isTCP()) { - this.socket.write(data); - } else if (this.isWebSocket()) { - this.socket.send(data); - } else if (typeof self !== "undefined") { - this.socket.postMessage({ type: "data", data, id: this.uniqueId }); - } - } - // close the connection gracefully - close() { - if (!this.socket) { - return; - } - setTimeout(() => { - if (this.isTCP()) { - this.socket.end(); - } else if (this.isWebSocket()) { - this.socket.close(); - } else if (typeof self !== "undefined") { - this.socket.postMessage({ type: "close", id: this.uniqueId }); - } - }, 100); - } - // terminate the connection immediately - terminate() { - if (!this.socket) { - return; - } - if (this.isTCP()) { - this.socket.destroy(); - } else if (this.isWebSocket()) { - this.socket.terminate(); - } else if (typeof self !== "undefined") { - this.socket.postMessage({ type: "close", id: this.uniqueId }); - } - } - reset() { - this.inOffset = 0; - this.inCount.fill(0); - } - writeImmediate(data) { - this.send(data); - } - flush() { - const out = this.out; - if (out.pos === 0) { - return; - } - this.send(out.data.subarray(0, out.pos)); - out.pos = 0; - } -}; - -// src/lostcity/server/NullClientSocket.ts -var NullClientSocket = class extends ClientSocket { - constructor() { - super(null, ""); - } - isTCP() { - return this.type === ClientSocket.TCP; - } - isWebSocket() { - return this.type === ClientSocket.WEBSOCKET; - } - send(data) { - if (!this.socket) { - return; - } - } - // close the connection gracefully - close() { - if (!this.socket) { - return; - } - } - // terminate the connection immediately - terminate() { - if (!this.socket) { - return; - } - } - reset() { - this.inOffset = 0; - this.inCount.fill(0); - } -}; - -// src/lostcity/entity/PlayerLoading.ts -var PlayerLoading = class _PlayerLoading { - /** - * Creates a non-networked player from a save file. - * - * Used for tooling. - */ - static loadFromFile(name) { - const name37 = toBase37(name); - const safeName = fromBase37(name37); - let save; - if (fs24.existsSync(`data/players/${safeName}.sav`)) { - save = Packet.load(`data/players/${safeName}.sav`); - } else { - save = new Packet(new Uint8Array()); - } - return _PlayerLoading.load(name, save, null); - } - static load(name, sav, client) { - const name37 = toBase37(name); - const safeName = fromBase37(name37); - const player = client ? new NetworkPlayer(safeName, name37, client) : new Player(safeName, name37); - if (!Environment_default.NODE_PRODUCTION) { - player.staffModLevel = 3; - } else if (Environment_default.NODE_STAFF.find((name2) => name2 === safeName) !== void 0) { - player.staffModLevel = 3; - } - if (sav.data.length < 2) { - for (let i = 0; i < 21; i++) { - player.stats[i] = 0; - player.baseLevels[i] = 1; - player.levels[i] = 1; - } - player.stats[PlayerStat_default.HITPOINTS] = getExpByLevel(10); - player.baseLevels[PlayerStat_default.HITPOINTS] = 10; - player.levels[PlayerStat_default.HITPOINTS] = 10; - return player; - } - if (sav.g2() !== 8196) { - throw new Error("Invalid player save"); - } - const version = sav.g2(); - if (version > 3) { - throw new Error("Unsupported player save format"); - } - sav.pos = sav.data.length - 4; - const crc = sav.g4(); - if (crc != Packet.getcrc(sav.data, 0, sav.data.length - 4)) { - throw new Error("Player save corrupted"); - } - sav.pos = 4; - player.x = sav.g2(); - player.z = sav.g2(); - player.level = sav.g1(); - for (let i = 0; i < 7; i++) { - player.body[i] = sav.g1(); - if (player.body[i] === 255) { - player.body[i] = -1; - } - } - for (let i = 0; i < 5; i++) { - player.colors[i] = sav.g1(); - } - player.gender = sav.g1(); - player.runenergy = sav.g2(); - if (version >= 2) { - player.playtime = sav.g4(); - } else { - player.playtime = sav.g2(); - } - for (let i = 0; i < 21; i++) { - player.stats[i] = sav.g4(); - player.baseLevels[i] = getLevelByExp(player.stats[i]); - player.levels[i] = sav.g1(); - } - const varpCount = sav.g2(); - for (let i = 0; i < varpCount; i++) { - player.vars[i] = sav.g4(); - } - const invCount = sav.g1(); - for (let i = 0; i < invCount; i++) { - const type = sav.g2(); - const inv = player.getInventory(type); - if (inv) { - for (let j = 0; j < inv.capacity; j++) { - const id = sav.g2(); - if (id === 0) { - continue; - } - let count = sav.g1(); - if (count === 255) { - count = sav.g4(); - } - inv.set(j, { - id: id - 1, - count - }); - } - } - } - if (version >= 3) { - const afkZones = sav.g1(); - for (let index = 0; index < afkZones; index++) { - player.afkZones[index] = sav.g4(); - } - player.lastAfkZone = sav.g2(); - } - player.combatLevel = player.getCombatLevel(); - player.lastResponse = World_default.currentTick; - return player; - } -}; - -// src/lostcity/network/225/incoming/handler/ClientCheatHandler.ts -var ClientCheatHandler = class extends MessageHandler { - handle(message, player) { - if (message.input.length > 80) { - return false; - } - const { input: cheat } = message; - const args = cheat.toLowerCase().split(" "); - const cmd = args.shift(); - if (cmd === void 0 || cmd.length <= 0) { - return false; - } - player.playerLog("Cheat ran", cheat); - if (player.staffModLevel >= 3) { - if (cmd === "reload" && typeof self === "undefined" && !Environment_default.NODE_PRODUCTION) { - World_default.reload(); - const count = ScriptProvider.load("data/pack"); - player.messageGame(`Reloaded ${count} scripts.`); - } else if (cmd === "rebuild" && !Environment_default.NODE_PRODUCTION) { - World_default.devThread.postMessage({ - type: "pack" - }); - } else if (cmd === "serverdrop") { - player.terminate(); - } else if (cmd === "bench") { - const start = Date.now(); - for (let index = 0; index < 1e5; index++) { - findPath(player.level, player.x, player.z, player.x, player.z + 10); - } - const end = Date.now(); - console.log(`took = ${end - start} ms`); - } else if (cmd === "bots") { - player.messageGame("Adding bots"); - for (let i = 0; i < 1999; i++) { - const bot = PlayerLoading.load(`bot${i}`, new Packet(new Uint8Array()), new NullClientSocket()); - World_default.addPlayer(bot); - } - } else if (cmd === "lightbots") { - player.messageGame("Adding lightweight bots"); - for (let i = 0; i < 1999; i++) { - const bot = PlayerLoading.load(`bot${i}`, new Packet(new Uint8Array()), null); - World_default.addPlayer(bot); - } - } else if (cmd === "teleall") { - player.messageGame("Teleporting all players"); - for (const player2 of World_default.players) { - player2.closeModal(); - do { - const x = Math.floor(Math.random() * 64) + 3200; - const z = Math.floor(Math.random() * 64) + 3200; - player2.teleJump(x + Math.floor(Math.random() * 64) - 32, z + Math.floor(Math.random() * 64) - 32, 0); - } while (isFlagged(player2.x, player2.z, player2.level, CollisionFlag.WALK_BLOCKED)); - } - } else if (cmd === "moveall") { - player.messageGame("Moving all players"); - console.time("moveall"); - for (const player2 of World_default.players) { - player2.closeModal(); - player2.queueWaypoints(findPath(player2.level, player2.x, player2.z, (player2.x >>> 6 << 6) + 32, (player2.z >>> 6 << 6) + 32)); - } - console.timeEnd("moveall"); - } else if (cmd === "speed") { - if (args.length < 1) { - player.messageGame("Usage: ::speed "); - return false; - } - const speed = tryParseInt(args.shift(), 20); - if (speed < 20) { - player.messageGame("::speed input was too low."); - return false; - } - player.messageGame(`World speed was changed to ${speed}ms`); - World_default.tickRate = speed; - } else if (cmd === "fly") { - if (player.moveStrategy === MoveStrategy_default.FLY) { - player.moveStrategy = MoveStrategy_default.SMART; - } else { - player.moveStrategy = MoveStrategy_default.FLY; - } - player.messageGame(`Fly is on? ${player.moveStrategy === MoveStrategy_default.FLY}`); - } else if (cmd === "naive") { - if (player.moveStrategy === MoveStrategy_default.NAIVE) { - player.moveStrategy = MoveStrategy_default.SMART; - } else { - player.moveStrategy = MoveStrategy_default.NAIVE; - } - player.messageGame(`Naive is on? ${player.moveStrategy === MoveStrategy_default.NAIVE}`); - } else if (cmd === "teleto") { - if (args.length < 1) { - return false; - } - const other = World_default.getPlayerByUsername(args[0]); - if (!other) { - player.messageGame(`${args[0]} is not logged in.`); - return false; - } - player.teleJump(other.x, other.z, other.level); - } else if (cmd === "teleother") { - if (args.length < 1) { - return false; - } - const other = World_default.getPlayerByUsername(args[0]); - if (!other) { - player.messageGame(`${args[0]} is not logged in.`); - return false; - } - other.teleJump(player.x, player.z, player.level); - } else if (cmd === "setvarother") { - if (args.length < 3) { - return false; - } - const other = World_default.getPlayerByUsername(args[0]); - if (!other) { - player.messageGame(`${args[0]} is not logged in.`); - return false; - } - const varp = VarPlayerType.getId(args[1]); - const value = Math.max(-2147483648, Math.min(tryParseInt(args[2], 0), 2147483647)); - if (varp === -1) { - return false; - } - other.setVar(varp, value); - player.messageGame("set " + args[1] + ": to " + value + " on " + other.username); - } else if (cmd === "shutdown") { - if (args.length < 1) { - return false; - } - World_default.rebootTimer(tryParseInt(args[0], 50)); - } - } - if (Environment_default.NODE_ALLOW_CHEATS || player.staffModLevel >= 2) { - if (cmd === "tele") { - if (args.length < 1) { - return false; - } - if (args[0] === "up") { - player.teleJump(player.x, player.z, player.level + 1); - player.messageGame("::tele " + Position.formatString(player.level, player.x, player.z, ",")); - } else if (args[0] === "down") { - player.teleJump(player.x, player.z, player.level - 1); - player.messageGame("::tele " + Position.formatString(player.level, player.x, player.z, ",")); - } else if (args[0].indexOf(",") === -1) { - player.teleJump(tryParseInt(args[0], 3200), tryParseInt(args[1], 3200), tryParseInt(args[2], player.level)); - } else { - const coord = args[0].split(","); - if (coord.length !== 5) { - return false; - } - const level = tryParseInt(coord[0], 0); - const mx = tryParseInt(coord[1], 50); - const mz = tryParseInt(coord[2], 50); - const lx = tryParseInt(coord[3], 0); - const lz = tryParseInt(coord[4], 0); - if (level < 0 || level > 3 || mx < 0 || mx > 255 || mz < 0 || mz > 255 || lx < 0 || lx > 63 || lz < 0 || lz > 63) { - return false; - } - player.teleJump((mx << 6) + lx, (mz << 6) + lz, level); - } - } else if (cmd === "setvar") { - if (args.length < 2) { - return false; - } - const varp = VarPlayerType.getId(args[0]); - const value = Math.max(-2147483648, Math.min(tryParseInt(args[1], 0), 2147483647)); - if (varp === -1) { - return false; - } - player.setVar(varp, value); - player.messageGame("set " + args[0] + ": to " + value); - } else if (cmd === "random") { - player.afkEventReady = true; - } else if (cmd === "minme") { - for (let i = 0; i < Player.SKILLS.length; i++) { - if (i === PlayerStat_default.HITPOINTS) { - player.setLevel(i, 10); - } else { - player.setLevel(i, 1); - } - } - } else if (cmd === "setxp") { - if (args.length < 2) { - player.messageGame("Usage: ::setxp "); - return false; - } - const stat = Player.SKILLS.indexOf(args[0]); - if (stat === -1) { - player.messageGame(`Unknown stat ${args[0]}`); - return false; - } - const exp = parseInt(args[1]) * 10; - player.stats[stat] = exp; - } else if (cmd === "setstat") { - if (args.length < 2) { - return false; - } - const stat = Player.SKILLS.indexOf(args[0]); - if (stat === -1) { - return false; - } - player.setLevel(stat, parseInt(args[1])); - } else if (cmd === "advancestat") { - if (args.length < 1) { - return false; - } - const stat = Player.SKILLS.indexOf(args[0]); - const level = Math.min(99, Math.max(1, tryParseInt(args[1], 1))); - if (stat === -1) { - return false; - } - player.setLevel(stat, player.baseLevels[stat] + level); - } else if (cmd === "getvar") { - if (args.length < 1) { - return false; - } - const varp = VarPlayerType.getId(args[0]); - if (varp === -1) { - return false; - } - const value = player.getVar(varp); - player.messageGame("get " + args[0] + ": " + value); - } else if (cmd === "give") { - if (args.length < 1) { - return false; - } - const obj = ObjType.getId(args[0]); - const count = Math.max(1, Math.min(tryParseInt(args[1], 1), 2147483647)); - if (obj === -1) { - return false; - } - player.invAdd(InvType.INV, obj, count, false); - } else if (cmd === "givecrap") { - } else if (cmd === "givemany") { - } - } - if (Environment_default.NODE_ALLOW_CHEATS || player.staffModLevel >= 1) { - if (cmd === "getcoord") { - player.messageGame(Position.formatString(player.level, player.x, player.z, "_")); - } - } - if (Environment_default.NODE_ALLOW_CHEATS || player.staffModLevel >= 2) { - const script = ScriptProvider.getByName(`[debugproc,${cmd}]`); - if (!script) { - return false; - } - const params = new Array(script.info.parameterTypes.length).fill(-1); - for (let i = 0; i < script.info.parameterTypes.length; i++) { - const type = script.info.parameterTypes[i]; - try { - switch (type) { - case ScriptVarType.STRING: { - const value = args.shift(); - params[i] = value ?? ""; - break; - } - case ScriptVarType.INT: { - const value = args.shift(); - params[i] = parseInt(value ?? "0", 10) | 0; - break; - } - case ScriptVarType.OBJ: - case ScriptVarType.NAMEDOBJ: { - const name = args.shift(); - params[i] = ObjType.getId(name ?? ""); - break; - } - case ScriptVarType.NPC: { - const name = args.shift(); - params[i] = NpcType.getId(name ?? ""); - break; - } - case ScriptVarType.LOC: { - const name = args.shift(); - params[i] = LocType.getId(name ?? ""); - break; - } - case ScriptVarType.SEQ: { - const name = args.shift(); - params[i] = SeqType.getId(name ?? ""); - break; - } - case ScriptVarType.STAT: { - const name = args.shift(); - params[i] = Player.SKILLS.indexOf(name ?? ""); - break; - } - case ScriptVarType.INV: { - const name = args.shift(); - params[i] = InvType.getId(name ?? ""); - break; - } - case ScriptVarType.COORD: { - const args2 = cheat.split("_"); - const level = parseInt(args2[0].slice(6)); - const mx = parseInt(args2[1]); - const mz = parseInt(args2[2]); - const lx = parseInt(args2[3]); - const lz = parseInt(args2[4]); - params[i] = Position.packCoord(level, (mx << 6) + lx, (mz << 6) + lz); - break; - } - case ScriptVarType.INTERFACE: { - const name = args.shift(); - params[i] = Component.getId(name ?? ""); - break; - } - case ScriptVarType.SPOTANIM: { - const name = args.shift(); - params[i] = SpotanimType.getId(name ?? ""); - break; - } - case ScriptVarType.IDKIT: { - const name = args.shift(); - params[i] = IdkType.getId(name ?? ""); - break; - } - } - } catch (err) { - return false; - } - } - player.executeScript(ScriptRunner.init(script, player, null, params), false); - } - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/CloseModalHandler.ts -var CloseModalHandler = class extends MessageHandler { - handle(_message, player) { - player.closeModal(); - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/IdleTimerHandler.ts -var IdleTimerHandler = class extends MessageHandler { - handle(_message, player) { - if (Environment_default.NODE_PRODUCTION) { - player.logout(); - player.logoutRequested = true; - } - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/IfButtonHandler.ts -var IfButtonHandler = class extends MessageHandler { - handle(message, player) { - const { component: comId } = message; - const com = Component.get(comId); - if (typeof com === "undefined" || !player.isComponentVisible(com)) { - return false; - } - player.lastCom = comId; - if (player.resumeButtons.indexOf(player.lastCom) !== -1) { - if (player.activeScript && player.activeScript.execution === ScriptState.PAUSEBUTTON) { - player.executeScript(player.activeScript, true, true); - } - } else { - const root = Component.get(com.rootLayer); - const script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.IF_BUTTON, comId, -1); - if (script) { - player.executeScript(ScriptRunner.init(script, player), root.overlay == false); - } else if (Environment_default.NODE_DEBUG) { - player.messageGame(`No trigger for [if_button,${com.comName}]`); - } - } - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/IfPlayerDesignHandler.ts -var IfPlayerDesignHandler = class extends MessageHandler { - handle(message, player) { - const { gender, idkit, color } = message; - if (!player.allowDesign) { - return false; - } - if (gender > 1) { - return false; - } - let pass = true; - for (let i = 0; i < 7; i++) { - let type = i; - if (gender === 1) { - type += 7; - } - if (type == 8 && idkit[i] === -1) { - continue; - } - const idk = IdkType.get(idkit[i]); - if (!idk || idk.disable || idk.type != type) { - pass = false; - break; - } - } - if (!pass) { - return false; - } - for (let i = 0; i < 5; i++) { - if (color[i] >= Player.DESIGN_BODY_COLORS[i].length) { - pass = false; - break; - } - } - if (!pass) { - return false; - } - player.gender = gender; - player.body = idkit; - player.colors = color; - player.generateAppearance(InvType.WORN); - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/InvButtonDHandler.ts -var InvButtonDHandler = class extends MessageHandler { - handle(message, player) { - const { component: comId, slot, targetSlot } = message; - const com = Component.get(comId); - if (typeof com === "undefined" || !player.isComponentVisible(com)) { - return false; - } - const listener = player.invListeners.find((l) => l.com === comId); - if (!listener) { - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.get(slot) || !inv.validSlot(targetSlot)) { - return false; - } - if (player.delayed()) { - player.write(new UpdateInvPartial(comId, inv, slot, targetSlot)); - return false; - } - player.lastSlot = slot; - player.lastTargetSlot = targetSlot; - const dragTrigger = ScriptProvider.getByTrigger(ServerTriggerType_default.INV_BUTTOND, comId); - if (dragTrigger) { - const root = Component.get(com.rootLayer); - player.executeScript(ScriptRunner.init(dragTrigger, player), root.overlay == false); - } else if (Environment_default.NODE_DEBUG) { - player.messageGame(`No trigger for [inv_buttond,${com.comName}]`); - } - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/MessagePrivateHandler.ts -var MessagePrivateHandler = class extends MessageHandler { - handle(message, player) { - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/MessagePublicHandler.ts -var MessagePublicHandler = class extends MessageHandler { - handle(message, player) { - const { color, effect, input } = message; - if (color < 0 || color > 11 || effect < 0 || effect > 2 || input.length > 100) { - return false; - } - player.messageColor = color; - player.messageEffect = effect; - player.messageType = 0; - const out = Packet.alloc(0); - WordPack.pack(out, WordEnc.filter(input)); - player.message = new Uint8Array(out.pos); - out.pos = 0; - out.gdata(player.message, 0, player.message.length); - out.release(); - player.mask |= Player.CHAT; - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/OpHeldHandler.ts -var OpHeldHandler = class extends MessageHandler { - handle(message, player) { - const { obj: item, slot, component: comId } = message; - const com = Component.get(comId); - if (typeof com === "undefined" || !player.isComponentVisible(com)) { - return false; - } - const type = ObjType.get(item); - if (message.op !== 5 && (type.iop && !type.iop[message.op - 1] || !type.iop)) { - return false; - } - const listener = player.invListeners.find((l) => l.com === comId); - if (!listener) { - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { - return false; - } - if (player.delayed()) { - return false; - } - player.lastItem = item; - player.lastSlot = slot; - player.clearInteraction(); - player.closeModal(); - let trigger; - if (message.op === 1) { - trigger = ServerTriggerType_default.OPHELD1; - } else if (message.op === 2) { - trigger = ServerTriggerType_default.OPHELD2; - } else if (message.op === 3) { - trigger = ServerTriggerType_default.OPHELD3; - } else if (message.op === 4) { - trigger = ServerTriggerType_default.OPHELD4; - } else { - trigger = ServerTriggerType_default.OPHELD5; - } - const script = ScriptProvider.getByTrigger(trigger, type.id, type.category); - if (script) { - player.executeScript(ScriptRunner.init(script, player), true); - } else if (Environment_default.NODE_DEBUG) { - player.messageGame(`No trigger for [${ServerTriggerType_default.toString(trigger)},${type.debugname}]`); - } - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/OpHeldTHandler.ts -var OpHeldTHandler = class extends MessageHandler { - handle(message, player) { - const { obj: item, slot, component: comId, spellComponent: spellComId } = message; - const com = Component.get(comId); - if (typeof com === "undefined" || !player.isComponentVisible(com)) { - player.unsetMapFlag(); - return false; - } - const spellCom = Component.get(comId); - if (typeof spellCom === "undefined" || !player.isComponentVisible(spellCom)) { - player.unsetMapFlag(); - return false; - } - const listener = player.invListeners.find((l) => l.com === comId); - if (!listener) { - player.unsetMapFlag(); - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { - player.unsetMapFlag(); - return false; - } - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - player.lastItem = item; - player.lastSlot = slot; - player.clearInteraction(); - player.closeModal(); - const script = ScriptProvider.getByTrigger(ServerTriggerType_default.OPHELDT, spellComId, -1); - if (script) { - player.executeScript(ScriptRunner.init(script, player), true); - } else { - if (Environment_default.NODE_DEBUG) { - player.messageGame(`No trigger for [opheldt,${spellCom.comName}]`); - } - player.messageGame("Nothing interesting happens."); - } - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/OpHeldUHandler.ts -var OpHeldUHandler = class extends MessageHandler { - handle(message, player) { - const { obj: item, slot, component: comId, useObj: useItem, useSlot, useComponent: useComId } = message; - const com = Component.get(comId); - if (typeof com === "undefined" || !player.isComponentVisible(com)) { - player.unsetMapFlag(); - return false; - } - const useCom = Component.get(comId); - if (typeof useCom === "undefined" || !player.isComponentVisible(useCom)) { - player.unsetMapFlag(); - return false; - } - { - const listener = player.invListeners.find((l) => l.com === comId); - if (!listener) { - player.unsetMapFlag(); - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { - player.unsetMapFlag(); - return false; - } - } - { - const listener = player.invListeners.find((l) => l.com === useComId); - if (!listener) { - player.unsetMapFlag(); - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(useSlot) || !inv.hasAt(useSlot, useItem)) { - player.unsetMapFlag(); - return false; - } - } - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - player.lastItem = item; - player.lastSlot = slot; - player.lastUseItem = useItem; - player.lastUseSlot = useSlot; - const objType = ObjType.get(player.lastItem); - const useObjType = ObjType.get(player.lastUseItem); - if ((objType.members || useObjType.members) && !Environment_default.NODE_MEMBERS) { - player.messageGame("To use this item please login to a members' server."); - player.unsetMapFlag(); - return false; - } - let script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.OPHELDU, objType.id, -1); - if (!script) { - script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.OPHELDU, useObjType.id, -1); - [player.lastItem, player.lastUseItem] = [player.lastUseItem, player.lastItem]; - [player.lastSlot, player.lastUseSlot] = [player.lastUseSlot, player.lastSlot]; - } - const objCategory = objType.category !== -1 ? CategoryType.get(objType.category) : null; - if (!script && objCategory) { - script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.OPHELDU, -1, objCategory.id); - } - const useObjCategory = useObjType.category !== -1 ? CategoryType.get(useObjType.category) : null; - if (!script && useObjCategory) { - script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.OPHELDU, -1, useObjCategory.id); - [player.lastItem, player.lastUseItem] = [player.lastUseItem, player.lastItem]; - [player.lastSlot, player.lastUseSlot] = [player.lastUseSlot, player.lastSlot]; - } - player.clearInteraction(); - player.closeModal(); - if (script) { - player.executeScript(ScriptRunner.init(script, player), true); - } else { - if (Environment_default.NODE_DEBUG) { - player.messageGame(`No trigger for [opheldu,${objType.debugname}]`); - } - player.messageGame("Nothing interesting happens."); - } - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/OpLocHandler.ts -var OpLocHandler = class extends MessageHandler { - handle(message, player) { - const { x, z, loc: locId } = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const absLeftX = player.originX - 52; - const absRightX = player.originX + 52; - const absTopZ = player.originZ + 52; - const absBottomZ = player.originZ - 52; - if (x < absLeftX || x > absRightX || z < absBottomZ || z > absTopZ) { - return false; - } - const loc = World_default.getLoc(x, z, player.level, locId); - if (!loc) { - player.unsetMapFlag(); - return false; - } - const locType = LocType.get(loc.type); - if (!locType.op || !locType.op[message.op - 1]) { - player.unsetMapFlag(); - return false; - } - let mode; - if (message.op === 1) { - mode = ServerTriggerType_default.APLOC1; - } else if (message.op === 2) { - mode = ServerTriggerType_default.APLOC2; - } else if (message.op === 3) { - mode = ServerTriggerType_default.APLOC3; - } else if (message.op === 4) { - mode = ServerTriggerType_default.APLOC4; - } else { - mode = ServerTriggerType_default.APLOC5; - } - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, loc, mode); - player.opcalled = true; - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/OpLocTHandler.ts -var OpLocTHandler = class extends MessageHandler { - handle(message, player) { - const { x, z, loc: locId, spellComponent: spellComId } = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const spellCom = Component.get(spellComId); - if (typeof spellCom === "undefined" || !player.isComponentVisible(spellCom)) { - player.unsetMapFlag(); - return false; - } - const absLeftX = player.originX - 52; - const absRightX = player.originX + 52; - const absTopZ = player.originZ + 52; - const absBottomZ = player.originZ - 52; - if (x < absLeftX || x > absRightX || z < absBottomZ || z > absTopZ) { - player.unsetMapFlag(); - return false; - } - const loc = World_default.getLoc(x, z, player.level, locId); - if (!loc) { - player.unsetMapFlag(); - return false; - } - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, loc, ServerTriggerType_default.APLOCT, { type: loc.type, com: spellComId }); - player.opcalled = true; - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/OpLocUHandler.ts -var OpLocUHandler = class extends MessageHandler { - handle(message, player) { - const { x, z, loc: locId, useObj: item, useSlot: slot, useComponent: comId } = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const com = Component.get(comId); - if (typeof com === "undefined" || !player.isComponentVisible(com)) { - player.unsetMapFlag(); - return false; - } - const absLeftX = player.originX - 52; - const absRightX = player.originX + 52; - const absTopZ = player.originZ + 52; - const absBottomZ = player.originZ - 52; - if (x < absLeftX || x > absRightX || z < absBottomZ || z > absTopZ) { - player.unsetMapFlag(); - return false; - } - const listener = player.invListeners.find((l) => l.com === comId); - if (!listener) { - player.unsetMapFlag(); - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { - player.unsetMapFlag(); - return false; - } - const loc = World_default.getLoc(x, z, player.level, locId); - if (!loc) { - player.unsetMapFlag(); - return false; - } - if (ObjType.get(item).members && !Environment_default.NODE_MEMBERS) { - player.messageGame("To use this item please login to a members' server."); - player.unsetMapFlag(); - return false; - } - player.lastUseItem = item; - player.lastUseSlot = slot; - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, loc, ServerTriggerType_default.APLOCU); - player.opcalled = true; - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/OpNpcHandler.ts -var OpNpcHandler = class extends MessageHandler { - handle(message, player) { - const { nid } = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const npc = World_default.getNpc(nid); - if (!npc || npc.delayed()) { - player.unsetMapFlag(); - return false; - } - if (!player.buildArea.npcs.has(npc.nid)) { - player.unsetMapFlag(); - return false; - } - const npcType = NpcType.get(npc.type); - if (!npcType.op || !npcType.op[message.op - 1]) { - player.unsetMapFlag(); - return false; - } - let mode; - if (message.op === 1) { - mode = ServerTriggerType_default.APNPC1; - } else if (message.op === 2) { - mode = ServerTriggerType_default.APNPC2; - } else if (message.op === 3) { - mode = ServerTriggerType_default.APNPC3; - } else if (message.op === 4) { - mode = ServerTriggerType_default.APNPC4; - } else { - mode = ServerTriggerType_default.APNPC5; - } - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, npc, mode, { type: npc.type, com: -1 }); - player.opcalled = true; - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/OpNpcTHandler.ts -var OpNpcTHandler = class extends MessageHandler { - handle(message, player) { - const { nid, spellComponent: spellComId } = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const spellCom = Component.get(spellComId); - if (typeof spellCom === "undefined" || !player.isComponentVisible(spellCom)) { - player.unsetMapFlag(); - return false; - } - const npc = World_default.getNpc(nid); - if (!npc || npc.delayed()) { - player.unsetMapFlag(); - return false; - } - if (!player.buildArea.npcs.has(npc.nid)) { - player.unsetMapFlag(); - return false; - } - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, npc, ServerTriggerType_default.APNPCT, { type: npc.type, com: spellComId }); - player.opcalled = true; - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/OpNpcUHandler.ts -var OpNpcUHandler = class extends MessageHandler { - handle(message, player) { - const { nid, useObj: item, useSlot: slot, useComponent: comId } = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const com = Component.get(comId); - if (typeof com === "undefined" || !player.isComponentVisible(com)) { - player.unsetMapFlag(); - return false; - } - const listener = player.invListeners.find((l) => l.com === comId); - if (!listener) { - player.unsetMapFlag(); - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { - player.unsetMapFlag(); - return false; - } - const npc = World_default.getNpc(nid); - if (!npc || npc.delayed()) { - player.unsetMapFlag(); - return false; - } - if (!player.buildArea.npcs.has(npc.nid)) { - player.unsetMapFlag(); - return false; - } - if (ObjType.get(item).members && !Environment_default.NODE_MEMBERS) { - player.messageGame("To use this item please login to a members' server."); - player.unsetMapFlag(); - return false; - } - player.lastUseItem = item; - player.lastUseSlot = slot; - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, npc, ServerTriggerType_default.APNPCU, { type: npc.type, com: -1 }); - player.opcalled = true; - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/OpObjHandler.ts -var OpObjHandler = class extends MessageHandler { - handle(message, player) { - const { x, z, obj: objId } = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const absLeftX = player.originX - 52; - const absRightX = player.originX + 52; - const absTopZ = player.originZ + 52; - const absBottomZ = player.originZ - 52; - if (x < absLeftX || x > absRightX || z < absBottomZ || z > absTopZ) { - player.unsetMapFlag(); - return false; - } - const obj = World_default.getObj(x, z, player.level, objId, player.pid); - if (!obj) { - player.unsetMapFlag(); - return false; - } - const objType = ObjType.get(obj.type); - if (message.op === 1 && (objType.op && !objType.op[0] || !objType.op) || message.op === 4 && (objType.op && !objType.op[3] || !objType.op)) { - player.unsetMapFlag(); - return false; - } - let mode; - if (message.op === 1) { - mode = ServerTriggerType_default.APOBJ1; - } else if (message.op === 2) { - mode = ServerTriggerType_default.APOBJ2; - } else if (message.op === 3) { - mode = ServerTriggerType_default.APOBJ3; - } else if (message.op === 4) { - mode = ServerTriggerType_default.APOBJ4; - } else { - mode = ServerTriggerType_default.APOBJ5; - } - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, obj, mode); - player.opcalled = true; - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/OpObjTHandler.ts -var OpObjTHandler = class extends MessageHandler { - handle(message, player) { - const { x, z, obj: objId, spellComponent: spellComId } = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const spellCom = Component.get(spellComId); - if (typeof spellCom === "undefined" || !player.isComponentVisible(spellCom)) { - player.unsetMapFlag(); - return false; - } - const absLeftX = player.originX - 52; - const absRightX = player.originX + 52; - const absTopZ = player.originZ + 52; - const absBottomZ = player.originZ - 52; - if (x < absLeftX || x > absRightX || z < absBottomZ || z > absTopZ) { - player.unsetMapFlag(); - return false; - } - const obj = World_default.getObj(x, z, player.level, objId, player.pid); - if (!obj) { - player.unsetMapFlag(); - return false; - } - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, obj, ServerTriggerType_default.APOBJT, { type: obj.type, com: spellComId }); - player.opcalled = true; - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/OpObjUHandler.ts -var OpObjUHandler = class extends MessageHandler { - handle(message, player) { - const { x, z, obj: objId, useObj: item, useSlot: slot, useComponent: comId } = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const com = Component.get(comId); - if (typeof com === "undefined" || !player.isComponentVisible(com)) { - player.unsetMapFlag(); - return false; - } - const absLeftX = player.originX - 52; - const absRightX = player.originX + 52; - const absTopZ = player.originZ + 52; - const absBottomZ = player.originZ - 52; - if (x < absLeftX || x > absRightX || z < absBottomZ || z > absTopZ) { - player.unsetMapFlag(); - return false; - } - const listener = player.invListeners.find((l) => l.com === comId); - if (!listener) { - player.unsetMapFlag(); - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { - player.unsetMapFlag(); - return false; - } - const obj = World_default.getObj(x, z, player.level, objId, player.pid); - if (!obj) { - player.unsetMapFlag(); - return false; - } - if (ObjType.get(item).members && !Environment_default.NODE_MEMBERS) { - player.messageGame("To use this item please login to a members' server."); - player.unsetMapFlag(); - return false; - } - player.lastUseItem = item; - player.lastUseSlot = slot; - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, obj, ServerTriggerType_default.APOBJU); - player.opcalled = true; - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/OpPlayerHandler.ts -var OpPlayerHandler = class extends MessageHandler { - handle(message, player) { - const { pid } = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const other = World_default.getPlayer(pid); - if (!other) { - player.unsetMapFlag(); - return false; - } - if (!player.buildArea.players.has(other.uid)) { - player.unsetMapFlag(); - return false; - } - let mode; - if (message.op === 1) { - mode = ServerTriggerType_default.APPLAYER1; - } else if (message.op === 2) { - mode = ServerTriggerType_default.APPLAYER2; - } else if (message.op === 3) { - mode = ServerTriggerType_default.APPLAYER3; - } else { - mode = ServerTriggerType_default.APPLAYER4; - } - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, other, mode); - player.opcalled = true; - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/OpPlayerTHandler.ts -var OpPlayerTHandler = class extends MessageHandler { - handle(message, player) { - const { pid, spellComponent: spellComId } = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const spellCom = Component.get(spellComId); - if (typeof spellCom === "undefined" || !player.isComponentVisible(spellCom)) { - player.unsetMapFlag(); - return false; - } - const other = World_default.getPlayer(pid); - if (!other) { - player.unsetMapFlag(); - return false; - } - if (!player.buildArea.players.has(other.uid)) { - player.unsetMapFlag(); - return false; - } - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, other, ServerTriggerType_default.APPLAYERT, { type: -1, com: spellComId }); - player.opcalled = true; - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/OpPlayerUHandler.ts -var OpPlayerUHandler = class extends MessageHandler { - handle(message, player) { - const { pid, useObj: item, useSlot: slot, useComponent: comId } = message; - if (player.delayed()) { - player.unsetMapFlag(); - return false; - } - const com = Component.get(comId); - if (typeof com === "undefined" || !player.isComponentVisible(com)) { - player.unsetMapFlag(); - return false; - } - const listener = player.invListeners.find((l) => l.com === comId); - if (!listener) { - player.unsetMapFlag(); - return false; - } - const inv = player.getInventoryFromListener(listener); - if (!inv || !inv.validSlot(slot) || !inv.hasAt(slot, item)) { - player.unsetMapFlag(); - return false; - } - const other = World_default.getPlayer(pid); - if (!other) { - player.unsetMapFlag(); - return false; - } - if (!player.buildArea.players.has(other.uid)) { - player.unsetMapFlag(); - return false; - } - if (ObjType.get(item).members && !Environment_default.NODE_MEMBERS) { - player.messageGame("To use this item please login to a members' server."); - player.unsetMapFlag(); - return false; - } - player.lastUseSlot = slot; - player.clearPendingAction(); - player.setInteraction(Interaction_default.ENGINE, other, ServerTriggerType_default.APPLAYERU, { type: item, com: -1 }); - player.opcalled = true; - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/RebuildGetMapsHandler.ts -var RebuildGetMapsHandler = class extends MessageHandler { - handle(message, player) { - const { maps: requested } = message; - for (let i = 0; i < requested.length; i++) { - const { type, x, z } = requested[i]; - const CHUNK_SIZE = 1e3 - 1 - 2 - 1 - 1 - 2 - 2; - if (type == 0) { - const land = PRELOADED.get(`m${x}_${z}`); - if (!land) { - continue; - } - for (let off = 0; off < land.length; off += CHUNK_SIZE) { - player.write(new DataLand(x, z, off, land.length, land.subarray(off, off + CHUNK_SIZE))); - } - player.write(new DataLandDone(x, z)); - } else if (type == 1) { - const loc = PRELOADED.get(`l${x}_${z}`); - if (!loc) { - continue; - } - for (let off = 0; off < loc.length; off += CHUNK_SIZE) { - player.write(new DataLoc(x, z, off, loc.length, loc.subarray(off, off + CHUNK_SIZE))); - } - player.write(new DataLocDone(x, z)); - } - } - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/ResumePauseButtonHandler.ts -var ResumePauseButtonHandler = class extends MessageHandler { - handle(_message, player) { - if (!player.activeScript || player.activeScript.execution !== ScriptState.PAUSEBUTTON) { - return false; - } - player.executeScript(player.activeScript, true, true); - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/ResumePCountDialogHandler.ts -var ResumePCountDialogHandler = class extends MessageHandler { - handle(message, player) { - const { input } = message; - if (!player.activeScript || player.activeScript.execution !== ScriptState.COUNTDIALOG) { - return false; - } - player.activeScript.lastInt = input; - player.executeScript(player.activeScript, true, true); - return true; - } -}; - -// src/lostcity/network/225/incoming/handler/TutorialClickSideHandler.ts -var TutorialClickSideHandler = class extends MessageHandler { - handle(message, player) { - const { tab } = message; - if (tab < 0 || tab > 13) { - return false; - } - const script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.TUTORIAL, -1, -1); - if (script) { - player.executeScript(ScriptRunner.init(script, player), true); - } - return true; - } -}; - -// src/lostcity/network/incoming/model/MoveClick.ts -var MoveClick = class extends IncomingMessage { - constructor(path4, ctrlHeld, opClick) { - super(); - this.path = path4; - this.ctrlHeld = ctrlHeld; - this.opClick = opClick; - } - category = ClientProtCategory.USER_EVENT; -}; - -// src/lostcity/network/225/incoming/codec/MoveClickDecoder.ts -var MoveClickDecoder = class extends MessageDecoder { - constructor(prot) { - super(); - this.prot = prot; - } - decode(buf) { - const ctrlHeld = buf.g1(); - const startX = buf.g2(); - const startZ = buf.g2(); - const offset = this.prot === ClientProt.MOVE_MINIMAPCLICK ? 14 : 0; - const waypoints = buf.available - offset >> 1; - const path4 = [ - { x: startX, z: startZ } - ]; - for (let index = 1; index <= waypoints && index < 25; index++) { - path4.push({ - x: startX + buf.g1b(), - z: startZ + buf.g1b() - }); - } - return new MoveClick(path4, ctrlHeld, this.prot === ClientProt.MOVE_OPCLICK); - } -}; - -// src/lostcity/network/225/incoming/handler/MoveClickHandler.ts -var MoveClickHandler = class extends MessageHandler { - handle(message, player) { - const start = message.path[0]; - if (player.delayed() || message.ctrlHeld < 0 || message.ctrlHeld > 1 || Position.distanceToSW(player, { x: start.x, z: start.z }) > 104) { - player.unsetMapFlag(); - player.userPath = []; - return false; - } - if (Environment_default.NODE_CLIENT_ROUTEFINDER) { - player.userPath = []; - for (let i = 0; i < message.path.length; i++) { - player.userPath[i] = Position.packCoord(player.level, message.path[i].x, message.path[i].z); - } - } else { - const dest = message.path[message.path.length - 1]; - player.userPath = [Position.packCoord(player.level, dest.x, dest.z)]; - } - player.interactWalkTrigger = false; - if (!message.opClick) { - player.clearInteraction(); - player.closeModal(); - } - if (player.runenergy < 100) { - player.setVar(VarPlayerType.TEMP_RUN, 0); - } else { - player.setVar(VarPlayerType.TEMP_RUN, message.ctrlHeld); - } - return true; - } -}; - -// src/lostcity/network/225/incoming/prot/ClientProtRepository.ts -var ClientProtRepository = class { - decoders = /* @__PURE__ */ new Map(); - handlers = /* @__PURE__ */ new Map(); - bind(decoder, handler) { - if (this.decoders.has(decoder.prot.id)) { - throw new Error(`[ClientProtRepository] Already defines a ${decoder.prot.id}.`); - } - this.decoders.set(decoder.prot.id, decoder); - if (handler) { - this.handlers.set(decoder.prot.id, handler); - } - } - constructor() { - this.bind(new ClientCheatDecoder(), new ClientCheatHandler()); - this.bind(new CloseModalDecoder(), new CloseModalHandler()); - this.bind(new IdleTimerDecoder(), new IdleTimerHandler()); - this.bind(new IfButtonDecoder(), new IfButtonHandler()); - this.bind(new IfPlayerDesignDecoder(), new IfPlayerDesignHandler()); - this.bind(new InvButtonDecoder(ClientProt.INV_BUTTON1, 1), new InvButtonHandler()); - this.bind(new InvButtonDecoder(ClientProt.INV_BUTTON2, 2), new InvButtonHandler()); - this.bind(new InvButtonDecoder(ClientProt.INV_BUTTON3, 3), new InvButtonHandler()); - this.bind(new InvButtonDecoder(ClientProt.INV_BUTTON4, 4), new InvButtonHandler()); - this.bind(new InvButtonDecoder(ClientProt.INV_BUTTON5, 5), new InvButtonHandler()); - this.bind(new InvButtonDDecoder(), new InvButtonDHandler()); - this.bind(new MessagePrivateDecoder(), new MessagePrivateHandler()); - this.bind(new MessagePublicDecoder(), new MessagePublicHandler()); - this.bind(new MoveClickDecoder(ClientProt.MOVE_GAMECLICK), new MoveClickHandler()); - this.bind(new MoveClickDecoder(ClientProt.MOVE_OPCLICK), new MoveClickHandler()); - this.bind(new MoveClickDecoder(ClientProt.MOVE_MINIMAPCLICK), new MoveClickHandler()); - this.bind(new OpHeldDecoder(ClientProt.OPHELD1, 1), new OpHeldHandler()); - this.bind(new OpHeldDecoder(ClientProt.OPHELD2, 2), new OpHeldHandler()); - this.bind(new OpHeldDecoder(ClientProt.OPHELD3, 3), new OpHeldHandler()); - this.bind(new OpHeldDecoder(ClientProt.OPHELD4, 4), new OpHeldHandler()); - this.bind(new OpHeldDecoder(ClientProt.OPHELD5, 5), new OpHeldHandler()); - this.bind(new OpHeldTDecoder(), new OpHeldTHandler()); - this.bind(new OpHeldUDecoder(), new OpHeldUHandler()); - this.bind(new OpLocDecoder(ClientProt.OPLOC1, 1), new OpLocHandler()); - this.bind(new OpLocDecoder(ClientProt.OPLOC2, 2), new OpLocHandler()); - this.bind(new OpLocDecoder(ClientProt.OPLOC3, 3), new OpLocHandler()); - this.bind(new OpLocDecoder(ClientProt.OPLOC4, 4), new OpLocHandler()); - this.bind(new OpLocDecoder(ClientProt.OPLOC5, 5), new OpLocHandler()); - this.bind(new OpLocTDecoder(), new OpLocTHandler()); - this.bind(new OpLocUDecoder(), new OpLocUHandler()); - this.bind(new OpNpcDecoder(ClientProt.OPNPC1, 1), new OpNpcHandler()); - this.bind(new OpNpcDecoder(ClientProt.OPNPC2, 2), new OpNpcHandler()); - this.bind(new OpNpcDecoder(ClientProt.OPNPC3, 3), new OpNpcHandler()); - this.bind(new OpNpcDecoder(ClientProt.OPNPC4, 4), new OpNpcHandler()); - this.bind(new OpNpcDecoder(ClientProt.OPNPC5, 5), new OpNpcHandler()); - this.bind(new OpNpcTDecoder(), new OpNpcTHandler()); - this.bind(new OpNpcUDecoder(), new OpNpcUHandler()); - this.bind(new OpObjDecoder(ClientProt.OPOBJ1, 1), new OpObjHandler()); - this.bind(new OpObjDecoder(ClientProt.OPOBJ2, 2), new OpObjHandler()); - this.bind(new OpObjDecoder(ClientProt.OPOBJ3, 3), new OpObjHandler()); - this.bind(new OpObjDecoder(ClientProt.OPOBJ4, 4), new OpObjHandler()); - this.bind(new OpObjDecoder(ClientProt.OPOBJ5, 5), new OpObjHandler()); - this.bind(new OpObjTDecoder(), new OpObjTHandler()); - this.bind(new OpObjUDecoder(), new OpObjUHandler()); - this.bind(new OpPlayerDecoder(ClientProt.OPPLAYER1, 1), new OpPlayerHandler()); - this.bind(new OpPlayerDecoder(ClientProt.OPPLAYER2, 2), new OpPlayerHandler()); - this.bind(new OpPlayerDecoder(ClientProt.OPPLAYER3, 3), new OpPlayerHandler()); - this.bind(new OpPlayerDecoder(ClientProt.OPPLAYER4, 4), new OpPlayerHandler()); - this.bind(new OpPlayerTDecoder(), new OpPlayerTHandler()); - this.bind(new OpPlayerUDecoder(), new OpPlayerUHandler()); - this.bind(new RebuildGetMapsDecoder(), new RebuildGetMapsHandler()); - this.bind(new ResumePauseButtonDecoder(), new ResumePauseButtonHandler()); - this.bind(new ResumePCountDialogDecoder(), new ResumePCountDialogHandler()); - this.bind(new TutorialClickSideDecoder(), new TutorialClickSideHandler()); - } - getDecoder(prot) { - return this.decoders.get(prot.id); - } - getHandler(prot) { - return this.handlers.get(prot.id); - } -}; -var ClientProtRepository_default = new ClientProtRepository(); - -// src/lostcity/entity/NetworkPlayer.ts -var NetworkPlayer = class extends Player { - client = null; - userPath = []; - opcalled = false; - constructor(username, username37, client) { - super(username, username37); - this.client = client; - this.client.player = this; - } - decodeIn() { - this.userPath = []; - this.opcalled = false; - if (this.client === null) { - return; - } - let offset = 0; - this.lastResponse = World_default.currentTick; - World_default.cycleStats[WorldStat_default.BANDWIDTH_IN] += this.client.inOffset; - while (this.client.inOffset > offset) { - const packetType = ClientProt.byId[this.client.in[offset++]]; - let length = packetType.length; - if (length == -1) { - length = this.client.in[offset++]; - } else if (length == -2) { - length = this.client.in[offset++] << 8 | this.client.in[offset++]; - } - const data = new Packet(this.client.in.slice(offset, offset + length)); - offset += length; - const decoder = ClientProtRepository_default.getDecoder(packetType); - if (decoder) { - const message = decoder.decode(data); - const handler = ClientProtRepository_default.getHandler(packetType); - if (handler) { - handler.handle(message, this); - } - } - } - this.client?.reset(); - } - encodeOut() { - if (!this.client) { - return; - } - if (this.modalTop !== this.lastModalTop || this.modalBottom !== this.lastModalBottom || this.modalSidebar !== this.lastModalSidebar || this.refreshModalClose) { - if (this.refreshModalClose) { - this.write(new IfClose()); - } - this.refreshModalClose = false; - this.lastModalTop = this.modalTop; - this.lastModalBottom = this.modalBottom; - this.lastModalSidebar = this.modalSidebar; - } - if (this.refreshModal) { - if ((this.modalState & 1) === 1 && (this.modalState & 4) === 4) { - this.write(new IfOpenMainSideModal(this.modalTop, this.modalSidebar)); - } else if ((this.modalState & 1) === 1) { - this.write(new IfOpenMainModal(this.modalTop)); - } else if ((this.modalState & 2) === 2) { - this.write(new IfOpenChatModal(this.modalBottom)); - } else if ((this.modalState & 4) === 4) { - this.write(new IfOpenSideModal(this.modalSidebar)); - } - this.refreshModal = false; - } - for (let message = this.highPriorityOut.head(); message; message = this.highPriorityOut.next()) { - this.writeInner(message); - message.uncache(); - } - for (let message = this.lowPriorityOut.head(); message; message = this.lowPriorityOut.next()) { - this.writeInner(message); - message.uncache(); - } - this.client.flush(); - } - writeInner(message) { - const client = this.client; - if (!client) { - return; - } - const encoder = ServerProtRepository_default.getEncoder(message); - if (!encoder) { - console.error("No encoder for message", message); - return; - } - const prot = encoder.prot; - const buf = client.out; - const test = 1 + (prot.length === -1 ? 1 : prot.length === -2 ? 2 : 0) + encoder.test(message); - if (buf.pos + test >= buf.length) { - client.flush(); - } - const pos = buf.pos; - buf.p1(prot.id); - if (prot.length === -1) { - buf.pos += 1; - } else if (prot.length === -2) { - buf.pos += 2; - } - const start = buf.pos; - encoder.encode(buf, message); - if (prot.length === -1) { - buf.psize1(buf.pos - start); - } else if (prot.length === -2) { - buf.psize2(buf.pos - start); - } - if (client.encryptor) { - buf.data[pos] = buf.data[pos] + client.encryptor.nextInt() & 255; - } - World_default.cycleStats[WorldStat_default.BANDWIDTH_OUT] += buf.pos - pos; - } - logout() { - this.writeInner(new Logout()); - this.client?.flush(); - } - terminate() { - this.client?.terminate(); - this.client = null; - } - playerLog(message, ...args) { - if (typeof self !== "undefined") { - return; - } - if (args.length > 0) { - fs25.appendFileSync(`data/players/${this.username}.log`, `[${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]} ${this.client?.remoteAddress}]: ${message} ${args.join(" ")} -`); - } else { - fs25.appendFileSync(`data/players/${this.username}.log`, `[${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]} ${this.client?.remoteAddress}]: ${message} -`); - } - } - updateMap() { - const loadedZones = this.buildArea.loadedZones; - const activeZones = this.buildArea.activeZones; - const reloadLeftX = Position.zone(this.originX) - 4 << 3; - const reloadRightX = Position.zone(this.originX) + 5 << 3; - const reloadTopZ = Position.zone(this.originZ) + 5 << 3; - const reloadBottomZ = Position.zone(this.originZ) - 4 << 3; - if (this.x < reloadLeftX || this.z < reloadBottomZ || this.x > reloadRightX - 1 || this.z > reloadTopZ - 1) { - this.write(new RebuildNormal(Position.zone(this.x), Position.zone(this.z))); - this.originX = this.x; - this.originZ = this.z; - loadedZones.clear(); - } - for (let info = this.cameraPackets.head(); info !== null; info = this.cameraPackets.next()) { - const localX = info.camX - Position.zoneOrigin(this.originX); - const localZ = info.camZ - Position.zoneOrigin(this.originZ); - if (info.type === ServerProt.CAM_MOVETO) { - this.write(new CamMoveTo(localX, localZ, info.height, info.rotationSpeed, info.rotationMultiplier)); - } else if (info.type === ServerProt.CAM_LOOKAT) { - this.write(new CamLookAt(localX, localZ, info.height, info.rotationSpeed, info.rotationMultiplier)); - } - info.unlink(); - } - if (this.moveSpeed === MoveSpeed_default.INSTANT && this.jump) { - loadedZones.clear(); - } - activeZones.clear(); - const centerX = Position.zone(this.x); - const centerZ = Position.zone(this.z); - const leftX = Position.zone(this.originX) - 6; - const rightX = Position.zone(this.originX) + 6; - const topZ = Position.zone(this.originZ) + 6; - const bottomZ = Position.zone(this.originZ) - 6; - for (let x = centerX - 3; x <= centerX + 3; x++) { - for (let z = centerZ - 3; z <= centerZ + 3; z++) { - if (x < leftX || x > rightX || z > topZ || z < bottomZ) { - continue; - } - activeZones.add(ZoneMap.zoneIndex(x << 3, z << 3, this.level)); - } - } - const mapZone = Position.packCoord(0, this.x >> 6 << 6, this.z >> 6 << 6); - if (this.lastMapZone !== mapZone) { - if (this.lastMapZone !== -1) { - const { x, z } = Position.unpackCoord(this.lastMapZone); - this.triggerMapzoneExit(x, z); - } - this.triggerMapzone(this.x >> 6 << 6, this.z >> 6 << 6); - this.lastMapZone = mapZone; - } - const zone = Position.packCoord(this.level, this.x >> 3 << 3, this.z >> 3 << 3); - if (this.lastZone !== zone) { - if (this.lastZone !== -1) { - const { level, x, z } = Position.unpackCoord(this.lastZone); - this.triggerZoneExit(level, x, z); - } - this.triggerZone(this.level, this.x >> 3 << 3, this.z >> 3 << 3); - this.lastZone = zone; - } - } - updatePlayers() { - this.write(new PlayerInfo(this.buildArea, this.level, this.x, this.z, this.originX, this.originZ, this.uid, this.mask, this.tele, this.jump, this.walkDir, this.runDir, Math.abs(this.lastX - this.x), Math.abs(this.lastZ - this.z), this.lastLevel !== this.level)); - } - updateNpcs() { - this.write(new NpcInfo(this.buildArea, this.level, this.x, this.z, this.originX, this.originZ, Math.abs(this.lastX - this.x), Math.abs(this.lastZ - this.z), this.lastLevel !== this.level)); - } - updateZones() { - const loadedZones = this.buildArea.loadedZones; - const activeZones = this.buildArea.activeZones; - for (const zoneIndex of loadedZones) { - if (!activeZones.has(zoneIndex)) { - loadedZones.delete(zoneIndex); - } - } - for (const zoneIndex of activeZones) { - const zone = World_default.getZoneIndex(zoneIndex); - if (!loadedZones.has(zone.index)) { - zone.writeFullFollows(this); - } else { - zone.writePartialEncloses(this); - zone.writePartialFollows(this); - } - loadedZones.add(zone.index); - } - } - updateStats() { - for (let i = 0; i < this.stats.length; i++) { - if (this.stats[i] !== this.lastStats[i] || this.levels[i] !== this.lastLevels[i]) { - this.write(new UpdateStat(i, this.stats[i], this.levels[i])); - this.lastStats[i] = this.stats[i]; - this.lastLevels[i] = this.levels[i]; - } - } - if (Math.floor(this.runenergy) / 100 !== Math.floor(this.lastRunEnergy) / 100) { - this.write(new UpdateRunEnergy(this.runenergy)); - this.lastRunEnergy = this.runenergy; - } - } - // todo: partial updates - updateInvs() { - let runWeightChanged = false; - let firstSeen = false; - for (let i = 0; i < this.invListeners.length; i++) { - const listener = this.invListeners[i]; - if (!listener) { - continue; - } - if (listener.source === -1) { - const inv = World_default.getInventory(listener.type); - if (!inv) { - continue; - } - if (inv.update || listener.firstSeen) { - this.write(new UpdateInvFull(listener.com, inv)); - listener.firstSeen = false; - } - } else { - const player = World_default.getPlayerByUid(listener.source); - if (!player) { - continue; - } - const inv = player.getInventory(listener.type); - if (!inv) { - continue; - } - if (inv.update || listener.firstSeen) { - this.write(new UpdateInvFull(listener.com, inv)); - if (listener.firstSeen) { - firstSeen = true; - } - listener.firstSeen = false; - const invType = InvType.get(listener.type); - if (invType.runweight) { - runWeightChanged = true; - } - } - } - } - if (runWeightChanged) { - const current = this.runweight; - this.calculateRunWeight(); - runWeightChanged = current !== this.runweight; - } - if (runWeightChanged || firstSeen) { - this.write(new UpdateRunWeight(Math.ceil(this.runweight / 1e3))); - } - } -}; -function isNetworkPlayer(player) { - return player.client !== null && player.client !== void 0; -} - -// src/lostcity/entity/CameraInfo.ts -var CameraInfo = class extends Linkable { - type; - camX; - camZ; - height; - rotationSpeed; - rotationMultiplier; - constructor(type, camX, camZ, height, rotationSpeed, rotationMultiplier) { - super(); - this.type = type; - this.camX = camX; - this.camZ = camZ; - this.height = height; - this.rotationSpeed = rotationSpeed; - this.rotationMultiplier = rotationMultiplier; - } -}; - -// src/lostcity/util/ColorConversion.ts -var ColorConversion = class _ColorConversion { - static hsl24to16(hue, saturation, lightness) { - if (lightness > 243) { - saturation >>= 4; - } else if (lightness > 217) { - saturation >>= 3; - } else if (lightness > 192) { - saturation >>= 2; - } else if (lightness > 179) { - saturation >>= 1; - } - return ((hue & 255) >> 2 << 10) + (saturation >> 5 << 7) + (lightness >> 1); - } - static rgb15to24(rgb) { - const r = rgb >> 10 & 31; - const g = rgb >> 5 & 31; - const b = rgb & 31; - return (r << 3 << 16) + (g << 3 << 8) + (b << 3); - } - static rgb15toHsl16(rgb) { - const r = rgb >> 10 & 31; - const g = rgb >> 5 & 31; - const b = rgb & 31; - const red = r / 31; - const green = g / 31; - const blue = b / 31; - return _ColorConversion.rgbToHsl(red, green, blue); - } - static rgb24to15(rgb) { - const r = rgb >> 16 & 255; - const g = rgb >> 8 & 255; - const b = rgb & 255; - return (r >> 3 << 10) + (g >> 3 << 5) + (b >> 3); - } - static rgb24toHsl16(rgb) { - const r = rgb >> 16 & 255; - const g = rgb >> 8 & 255; - const b = rgb & 255; - const red = r / 256; - const green = g / 256; - const blue = b / 256; - return _ColorConversion.rgbToHsl(red, green, blue); - } - static rgbToHsl(red, green, blue) { - let min = red; - if (green < min) { - min = green; - } - if (blue < min) { - min = blue; - } - let max = red; - if (green > max) { - max = green; - } - if (blue > max) { - max = blue; - } - let hNorm = 0; - let sNorm = 0; - const lNorm = (min + max) / 2; - if (min !== max) { - if (lNorm < 0.5) { - sNorm = (max - min) / (max + min); - } else if (lNorm >= 0.5) { - sNorm = (max - min) / (2 - max - min); - } - if (red === max) { - hNorm = (green - blue) / (max - min); - } else if (green === max) { - hNorm = (blue - red) / (max - min) + 2; - } else if (blue === max) { - hNorm = (red - green) / (max - min) + 4; - } - } - hNorm /= 6; - const hue = hNorm * 256 | 0; - let saturation = sNorm * 256 | 0; - let lightness = lNorm * 256 | 0; - if (saturation < 0) { - saturation = 0; - } else if (saturation > 255) { - saturation = 255; - } - if (lightness < 0) { - lightness = 0; - } else if (lightness > 255) { - lightness = 255; - } - return _ColorConversion.hsl24to16(hue, saturation, lightness); - } - static RGB15_HSL16 = new Int32Array(32768); - static { - for (let rgb = 0; rgb < 32768; rgb++) { - _ColorConversion.RGB15_HSL16[rgb] = _ColorConversion.rgb15toHsl16(rgb); - } - } - static reverseHsl(hsl) { - const possible = []; - for (let rgb = 0; rgb < 32768; rgb++) { - if (_ColorConversion.RGB15_HSL16[rgb] === hsl) { - possible.push(rgb); - } - } - return possible; - } -}; - -// src/lostcity/engine/script/handlers/PlayerOps.ts -var PlayerOps = { - [ScriptOpcode_default.FINDUID]: (state) => { - const uid = state.popInt(); - const player = World_default.getPlayerByUid(uid); - if (!player) { - state.pushInt(0); - return; - } - state.activePlayer = player; - state.pointerAdd(ActivePlayer[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.P_FINDUID]: (state) => { - const uid = state.popInt() >>> 0; - const player = World_default.getPlayerByUid(uid); - if (state.pointerGet(ProtectedActivePlayer[state.intOperand]) && state.activePlayer.uid === uid) { - state.pushInt(1); - return; - } - if (!player || !player.canAccess()) { - state.pushInt(0); - return; - } - state.activePlayer = player; - state.pointerAdd(ActivePlayer[state.intOperand]); - state.pointerAdd(ProtectedActivePlayer[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.STRONGQUEUE]: checkedHandler(ActivePlayer, (state) => { - const args = popScriptArgs(state); - const delay = check(state.popInt(), NumberNotNull); - const scriptId = state.popInt(); - const script = ScriptProvider.get(scriptId); - if (!script) { - throw new Error(`Unable to find queue script: ${scriptId}`); - } - state.activePlayer.enqueueScript(script, 3 /* STRONG */, delay, args); - }), - [ScriptOpcode_default.WEAKQUEUE]: checkedHandler(ActivePlayer, (state) => { - const args = popScriptArgs(state); - const delay = check(state.popInt(), NumberNotNull); - const scriptId = state.popInt(); - const script = ScriptProvider.get(scriptId); - if (!script) { - throw new Error(`Unable to find queue script: ${scriptId}`); - } - state.activePlayer.enqueueScript(script, 2 /* WEAK */, delay, args); - }), - [ScriptOpcode_default.QUEUE]: checkedHandler(ActivePlayer, (state) => { - const args = popScriptArgs(state); - const delay = check(state.popInt(), NumberNotNull); - const scriptId = state.popInt(); - const script = ScriptProvider.get(scriptId); - if (!script) { - throw new Error(`Unable to find queue script: ${scriptId}`); - } - state.activePlayer.enqueueScript(script, 0 /* NORMAL */, delay, args); - }), - [ScriptOpcode_default.ANIM]: checkedHandler(ActivePlayer, (state) => { - const delay = state.popInt(); - const seq = state.popInt(); - state.activePlayer.playAnimation(seq, delay); - }), - [ScriptOpcode_default.BUFFER_FULL]: checkedHandler(ActivePlayer, (state) => { - throw new Error("unimplemented"); - }), - [ScriptOpcode_default.BUILDAPPEARANCE]: checkedHandler(ActivePlayer, (state) => { - state.activePlayer.generateAppearance(check(state.popInt(), InvTypeValid).id); - }), - [ScriptOpcode_default.CAM_LOOKAT]: checkedHandler(ActivePlayer, (state) => { - const [coord, height, rotationSpeed, rotationMultiplier] = state.popInts(4); - const pos = check(coord, CoordValid); - state.activePlayer.cameraPackets.addTail(new CameraInfo(ServerProt.CAM_LOOKAT, pos.x, pos.z, height, rotationSpeed, rotationMultiplier)); - }), - [ScriptOpcode_default.CAM_MOVETO]: checkedHandler(ActivePlayer, (state) => { - const [coord, height, rotationSpeed, rotationMultiplier] = state.popInts(4); - const pos = check(coord, CoordValid); - state.activePlayer.cameraPackets.addTail(new CameraInfo(ServerProt.CAM_MOVETO, pos.x, pos.z, height, rotationSpeed, rotationMultiplier)); - }), - [ScriptOpcode_default.CAM_SHAKE]: checkedHandler(ActivePlayer, (state) => { - const [type, jitter, amplitude, frequency] = state.popInts(4); - state.activePlayer.write(new CamShake(type, jitter, amplitude, frequency)); - }), - [ScriptOpcode_default.CAM_RESET]: checkedHandler(ActivePlayer, (state) => { - state.activePlayer.write(new CamReset()); - }), - [ScriptOpcode_default.COORD]: checkedHandler(ActivePlayer, (state) => { - const position = state.activePlayer; - state.pushInt(Position.packCoord(position.level, position.x, position.z)); - }), - [ScriptOpcode_default.DISPLAYNAME]: checkedHandler(ActivePlayer, (state) => { - state.pushString(state.activePlayer.displayName); - }), - [ScriptOpcode_default.FACESQUARE]: checkedHandler(ActivePlayer, (state) => { - const pos = check(state.popInt(), CoordValid); - state.activePlayer.faceSquare(pos.x, pos.z); - }), - [ScriptOpcode_default.IF_CLOSE]: checkedHandler(ActivePlayer, (state) => { - state.activePlayer.closeModal(); - }), - [ScriptOpcode_default.LAST_COM]: (state) => { - state.pushInt(state.activePlayer.lastCom); - }, - // todo: move out of PlayerOps - [ScriptOpcode_default.LAST_INT]: (state) => { - state.pushInt(state.lastInt); - }, - [ScriptOpcode_default.LAST_ITEM]: (state) => { - const allowedTriggers = [ - ServerTriggerType_default.OPHELD1, - ServerTriggerType_default.OPHELD2, - ServerTriggerType_default.OPHELD3, - ServerTriggerType_default.OPHELD4, - ServerTriggerType_default.OPHELD5, - ServerTriggerType_default.OPHELDU, - ServerTriggerType_default.OPHELDT, - ServerTriggerType_default.INV_BUTTON1, - ServerTriggerType_default.INV_BUTTON2, - ServerTriggerType_default.INV_BUTTON3, - ServerTriggerType_default.INV_BUTTON4, - ServerTriggerType_default.INV_BUTTON5 - ]; - if (!allowedTriggers.includes(state.trigger)) { - throw new Error("is not safe to use in this trigger"); - } - state.pushInt(state.activePlayer.lastItem); - }, - [ScriptOpcode_default.LAST_SLOT]: (state) => { - const allowedTriggers = [ - ServerTriggerType_default.OPHELD1, - ServerTriggerType_default.OPHELD2, - ServerTriggerType_default.OPHELD3, - ServerTriggerType_default.OPHELD4, - ServerTriggerType_default.OPHELD5, - ServerTriggerType_default.OPHELDU, - ServerTriggerType_default.OPHELDT, - ServerTriggerType_default.INV_BUTTON1, - ServerTriggerType_default.INV_BUTTON2, - ServerTriggerType_default.INV_BUTTON3, - ServerTriggerType_default.INV_BUTTON4, - ServerTriggerType_default.INV_BUTTON5, - ServerTriggerType_default.INV_BUTTOND - ]; - if (!allowedTriggers.includes(state.trigger)) { - throw new Error("is not safe to use in this trigger"); - } - state.pushInt(state.activePlayer.lastSlot); - }, - [ScriptOpcode_default.LAST_USEITEM]: (state) => { - const allowedTriggers = [ - ServerTriggerType_default.OPHELDU, - ServerTriggerType_default.APOBJU, - ServerTriggerType_default.APLOCU, - ServerTriggerType_default.APNPCU, - ServerTriggerType_default.APPLAYERU, - ServerTriggerType_default.OPOBJU, - ServerTriggerType_default.OPLOCU, - ServerTriggerType_default.OPNPCU, - ServerTriggerType_default.OPPLAYERU - ]; - if (!allowedTriggers.includes(state.trigger)) { - throw new Error("is not safe to use in this trigger"); - } - state.pushInt(state.activePlayer.lastUseItem); - }, - [ScriptOpcode_default.LAST_USESLOT]: (state) => { - const allowedTriggers = [ - ServerTriggerType_default.OPHELDU, - ServerTriggerType_default.APOBJU, - ServerTriggerType_default.APLOCU, - ServerTriggerType_default.APNPCU, - ServerTriggerType_default.APPLAYERU, - ServerTriggerType_default.OPOBJU, - ServerTriggerType_default.OPLOCU, - ServerTriggerType_default.OPNPCU, - ServerTriggerType_default.OPPLAYERU - ]; - if (!allowedTriggers.includes(state.trigger)) { - throw new Error("is not safe to use in this trigger"); - } - state.pushInt(state.activePlayer.lastUseSlot); - }, - [ScriptOpcode_default.MES]: checkedHandler(ActivePlayer, (state) => { - const message = state.popString(); - state.activePlayer.messageGame(message); - }), - [ScriptOpcode_default.NAME]: checkedHandler(ActivePlayer, (state) => { - state.pushString(state.activePlayer.username); - }), - [ScriptOpcode_default.P_APRANGE]: checkedHandler(ProtectedActivePlayer, (state) => { - state.activePlayer.apRange = check(state.popInt(), NumberNotNull); - state.activePlayer.apRangeCalled = true; - }), - [ScriptOpcode_default.P_ARRIVEDELAY]: checkedHandler(ProtectedActivePlayer, (state) => { - if (state.activePlayer.lastMovement < World_default.currentTick) { - return; - } - state.activePlayer.delay = 1; - state.execution = ScriptState.SUSPENDED; - }), - [ScriptOpcode_default.P_COUNTDIALOG]: checkedHandler(ProtectedActivePlayer, (state) => { - state.activePlayer.write(new PCountDialog()); - state.execution = ScriptState.COUNTDIALOG; - }), - [ScriptOpcode_default.P_DELAY]: checkedHandler(ProtectedActivePlayer, (state) => { - state.activePlayer.delay = check(state.popInt(), NumberNotNull) + 1; - state.execution = ScriptState.SUSPENDED; - }), - [ScriptOpcode_default.P_OPHELD]: checkedHandler(ProtectedActivePlayer, (state) => { - throw new Error("unimplemented"); - }), - [ScriptOpcode_default.P_OPLOC]: checkedHandler(ProtectedActivePlayer, (state) => { - const type = check(state.popInt(), NumberNotNull) - 1; - if (type < 0 || type >= 5) { - throw new Error(`Invalid oploc: ${type + 1}`); - } - state.activePlayer.stopAction(); - state.activePlayer.setInteraction(Interaction_default.SCRIPT, state.activeLoc, ServerTriggerType_default.APLOC1 + type); - }), - [ScriptOpcode_default.P_OPNPC]: checkedHandler(ProtectedActivePlayer, (state) => { - const type = check(state.popInt(), NumberNotNull) - 1; - if (type < 0 || type >= 5) { - throw new Error(`Invalid opnpc: ${type + 1}`); - } - state.activePlayer.stopAction(); - state.activePlayer.setInteraction(Interaction_default.SCRIPT, state.activeNpc, ServerTriggerType_default.APNPC1 + type, { type: state.activeNpc.type, com: -1 }); - }), - [ScriptOpcode_default.P_OPNPCT]: checkedHandler(ProtectedActivePlayer, (state) => { - const spellId = check(state.popInt(), NumberNotNull); - state.activePlayer.stopAction(); - state.activePlayer.setInteraction(Interaction_default.SCRIPT, state.activeNpc, ServerTriggerType_default.APNPCT, { type: state.activeNpc.type, com: spellId }); - }), - [ScriptOpcode_default.P_PAUSEBUTTON]: checkedHandler(ProtectedActivePlayer, (state) => { - state.execution = ScriptState.PAUSEBUTTON; - }), - [ScriptOpcode_default.P_STOPACTION]: checkedHandler(ProtectedActivePlayer, (state) => { - state.activePlayer.stopAction(); - }), - [ScriptOpcode_default.P_CLEARPENDINGACTION]: checkedHandler(ProtectedActivePlayer, (state) => { - state.activePlayer.clearPendingAction(); - }), - [ScriptOpcode_default.P_TELEJUMP]: checkedHandler(ProtectedActivePlayer, (state) => { - const position = check(state.popInt(), CoordValid); - state.activePlayer.teleJump(position.x, position.z, position.level); - }), - [ScriptOpcode_default.P_TELEPORT]: checkedHandler(ProtectedActivePlayer, (state) => { - const position = check(state.popInt(), CoordValid); - state.activePlayer.teleport(position.x, position.z, position.level); - }), - [ScriptOpcode_default.P_WALK]: checkedHandler(ProtectedActivePlayer, (state) => { - const pos = check(state.popInt(), CoordValid); - const player = state.activePlayer; - player.queueWaypoints(findPath(player.level, player.x, player.z, pos.x, pos.z, player.width, player.width, player.length)); - player.updateMovement(false); - }), - [ScriptOpcode_default.SAY]: checkedHandler(ActivePlayer, (state) => { - state.activePlayer.say(state.popString()); - }), - [ScriptOpcode_default.SOUND_SYNTH]: checkedHandler(ActivePlayer, (state) => { - const [synth, loops, delay] = state.popInts(3); - state.activePlayer.write(new SynthSound(synth, loops, delay)); - }), - [ScriptOpcode_default.STAFFMODLEVEL]: checkedHandler(ActivePlayer, (state) => { - state.pushInt(state.activePlayer.staffModLevel); - }), - [ScriptOpcode_default.STAT]: checkedHandler(ActivePlayer, (state) => { - const stat = check(state.popInt(), PlayerStatValid); - state.pushInt(state.activePlayer.levels[stat]); - }), - [ScriptOpcode_default.STAT_BASE]: checkedHandler(ActivePlayer, (state) => { - const stat = check(state.popInt(), PlayerStatValid); - state.pushInt(state.activePlayer.baseLevels[stat]); - }), - [ScriptOpcode_default.STAT_ADD]: checkedHandler(ActivePlayer, (state) => { - const [stat, constant, percent] = state.popInts(3); - check(stat, PlayerStatValid); - check(constant, NumberNotNull); - check(percent, NumberNotNull); - const player = state.activePlayer; - const current = player.levels[stat]; - const added = current + (constant + current * percent / 100); - player.levels[stat] = Math.min(added, 255); - if (stat === 3 && player.levels[3] >= player.baseLevels[3]) { - player.resetHeroPoints(); - } - }), - [ScriptOpcode_default.STAT_SUB]: checkedHandler(ActivePlayer, (state) => { - const [stat, constant, percent] = state.popInts(3); - check(stat, PlayerStatValid); - check(constant, NumberNotNull); - check(percent, NumberNotNull); - const player = state.activePlayer; - const current = player.levels[stat]; - const subbed = current - (constant + current * percent / 100); - player.levels[stat] = Math.max(subbed, 0); - }), - [ScriptOpcode_default.SPOTANIM_PL]: checkedHandler(ActivePlayer, (state) => { - const delay = check(state.popInt(), NumberNotNull); - const height = state.popInt(); - const spotanimType = check(state.popInt(), SpotAnimTypeValid); - state.activePlayer.spotanim(spotanimType.id, height, delay); - }), - [ScriptOpcode_default.STAT_HEAL]: checkedHandler(ActivePlayer, (state) => { - const [stat, constant, percent] = state.popInts(3); - check(stat, PlayerStatValid); - check(constant, NumberNotNull); - check(percent, NumberNotNull); - const player = state.activePlayer; - const base = player.baseLevels[stat]; - const current = player.levels[stat]; - const healed = current + (constant + current * percent / 100); - player.levels[stat] = Math.max(Math.min(healed, base), current); - if (stat === 3 && player.levels[3] >= player.baseLevels[3]) { - player.resetHeroPoints(); - } - }), - [ScriptOpcode_default.UID]: checkedHandler(ActivePlayer, (state) => { - state.pushInt(state.activePlayer.uid); - }), - [ScriptOpcode_default.P_LOGOUT]: checkedHandler(ProtectedActivePlayer, (state) => { - state.activePlayer.logoutRequested = true; - }), - [ScriptOpcode_default.IF_SETCOLOUR]: checkedHandler(ActivePlayer, (state) => { - const [com, colour] = state.popInts(2); - check(com, NumberNotNull); - check(colour, NumberNotNull); - state.activePlayer.write(new IfSetColour(com, ColorConversion.rgb24to15(colour))); - }), - [ScriptOpcode_default.IF_OPENCHAT]: checkedHandler(ActivePlayer, (state) => { - state.activePlayer.openChat(check(state.popInt(), NumberNotNull)); - }), - [ScriptOpcode_default.IF_OPENMAINMODALSIDEOVERLAY]: checkedHandler(ActivePlayer, (state) => { - const [main, side] = state.popInts(2); - check(main, NumberNotNull); - check(side, NumberNotNull); - state.activePlayer.openMainModalSideOverlay(main, side); - }), - [ScriptOpcode_default.IF_SETHIDE]: checkedHandler(ActivePlayer, (state) => { - const [com, hide] = state.popInts(2); - check(com, NumberNotNull); - check(hide, NumberNotNull); - state.activePlayer.write(new IfSetHide(com, hide === 1)); - }), - [ScriptOpcode_default.IF_SETOBJECT]: checkedHandler(ActivePlayer, (state) => { - const [com, obj, scale] = state.popInts(3); - check(com, NumberNotNull); - check(obj, ObjTypeValid); - check(scale, NumberNotNull); - state.activePlayer.write(new IfSetObject(com, obj, scale)); - }), - [ScriptOpcode_default.IF_SETTABACTIVE]: checkedHandler(ActivePlayer, (state) => { - state.activePlayer.write(new IfShowSide(check(state.popInt(), NumberNotNull))); - }), - [ScriptOpcode_default.IF_SETMODEL]: checkedHandler(ActivePlayer, (state) => { - const [com, model] = state.popInts(2); - check(com, NumberNotNull); - check(model, NumberNotNull); - state.activePlayer.write(new IfSetModel(com, model)); - }), - [ScriptOpcode_default.IF_SETRECOL]: checkedHandler(ActivePlayer, (state) => { - const [com, src, dest] = state.popInts(3); - check(com, NumberNotNull); - state.activePlayer.write(new IfSetRecol(com, src, dest)); - }), - [ScriptOpcode_default.IF_SETTABFLASH]: checkedHandler(ActivePlayer, (state) => { - state.activePlayer.write(new TutorialFlashSide(check(state.popInt(), NumberNotNull))); - }), - [ScriptOpcode_default.IF_SETANIM]: checkedHandler(ActivePlayer, (state) => { - const [com, seq] = state.popInts(2); - check(com, NumberNotNull); - if (seq === -1) { - return; - } - state.activePlayer.write(new IfSetAnim(com, seq)); - }), - [ScriptOpcode_default.IF_SETTAB]: checkedHandler(ActivePlayer, (state) => { - const [com, tab] = state.popInts(2); - check(tab, NumberNotNull); - state.activePlayer.setTab(com, tab); - }), - [ScriptOpcode_default.IF_OPENMAINMODAL]: checkedHandler(ActivePlayer, (state) => { - state.activePlayer.openMainModal(check(state.popInt(), NumberNotNull)); - }), - [ScriptOpcode_default.IF_OPENCHATSTICKY]: checkedHandler(ActivePlayer, (state) => { - state.activePlayer.openChatSticky(check(state.popInt(), NumberNotNull)); - }), - [ScriptOpcode_default.IF_OPENSIDEOVERLAY]: checkedHandler(ActivePlayer, (state) => { - state.activePlayer.openSideOverlay(check(state.popInt(), NumberNotNull)); - }), - [ScriptOpcode_default.IF_SETPLAYERHEAD]: checkedHandler(ActivePlayer, (state) => { - state.activePlayer.write(new IfSetPlayerHead(check(state.popInt(), NumberNotNull))); - }), - [ScriptOpcode_default.IF_SETTEXT]: checkedHandler(ActivePlayer, (state) => { - const text = state.popString(); - const com = check(state.popInt(), NumberNotNull); - state.activePlayer.write(new IfSetText(com, text)); - }), - [ScriptOpcode_default.IF_SETNPCHEAD]: checkedHandler(ActivePlayer, (state) => { - const [com, npc] = state.popInts(2); - check(com, NumberNotNull); - check(npc, NpcTypeValid); - state.activePlayer.write(new IfSetNpcHead(com, npc)); - }), - [ScriptOpcode_default.IF_SETPOSITION]: checkedHandler(ActivePlayer, (state) => { - const [com, x, y] = state.popInts(3); - check(com, NumberNotNull); - state.activePlayer.write(new IfSetPosition(com, x, y)); - }), - [ScriptOpcode_default.IF_MULTIZONE]: checkedHandler(ActivePlayer, (state) => { - state.activePlayer.write(new SetMultiway(check(state.popInt(), NumberNotNull) === 1)); - }), - [ScriptOpcode_default.STAT_ADVANCE]: checkedHandler(ProtectedActivePlayer, (state) => { - const [stat, xp] = state.popInts(2); - check(stat, NumberNotNull); - check(xp, NumberNotNull); - state.activePlayer.addXp(stat, xp); - }), - [ScriptOpcode_default.DAMAGE]: (state) => { - const amount = check(state.popInt(), NumberNotNull); - const type = check(state.popInt(), HitTypeValid); - const uid = check(state.popInt(), NumberNotNull); - const player = World_default.getPlayerByUid(uid); - if (!player) { - return; - } - player.applyDamage(amount, type); - }, - [ScriptOpcode_default.IF_SETRESUMEBUTTONS]: checkedHandler(ActivePlayer, (state) => { - const [button1, button2, button3, button4, button5] = state.popInts(5); - state.activePlayer.resumeButtons = [button1, button2, button3, button4, button5]; - }), - [ScriptOpcode_default.TEXT_GENDER]: checkedHandler(ActivePlayer, (state) => { - const [male, female] = state.popStrings(2); - if (state.activePlayer.gender == 0) { - state.pushString(male); - } else { - state.pushString(female); - } - }), - [ScriptOpcode_default.MIDI_SONG]: (state) => { - state.activePlayer.playSong(check(state.popString(), StringNotNull)); - }, - [ScriptOpcode_default.MIDI_JINGLE]: (state) => { - const delay = check(state.popInt(), NumberNotNull); - const name = check(state.popString(), StringNotNull); - state.activePlayer.playJingle(delay, name); - }, - [ScriptOpcode_default.SOFTTIMER]: checkedHandler(ActivePlayer, (state) => { - const args = popScriptArgs(state); - const interval = state.popInt(); - const timerId = state.popInt(); - const script = ScriptProvider.get(timerId); - if (!script) { - throw new Error(`Unable to find timer script: ${timerId}`); - } - state.activePlayer.setTimer(1 /* SOFT */, script, args, interval); - }), - [ScriptOpcode_default.CLEARSOFTTIMER]: checkedHandler(ActivePlayer, (state) => { - state.activePlayer.clearTimer(state.popInt()); - }), - [ScriptOpcode_default.SETTIMER]: checkedHandler(ActivePlayer, (state) => { - const args = popScriptArgs(state); - const interval = state.popInt(); - const timerId = state.popInt(); - const script = ScriptProvider.get(timerId); - if (!script) { - throw new Error(`Unable to find timer script: ${timerId}`); - } - state.activePlayer.setTimer(0 /* NORMAL */, script, args, interval); - }), - [ScriptOpcode_default.CLEARTIMER]: checkedHandler(ActivePlayer, (state) => { - state.activePlayer.clearTimer(state.popInt()); - }), - [ScriptOpcode_default.HINT_COORD]: (state) => { - const [offset, coord, height] = state.popInts(3); - const position = check(coord, CoordValid); - state.activePlayer.hintTile(offset, position.x, position.z, height); - }, - [ScriptOpcode_default.HINT_STOP]: (state) => { - state.activePlayer.stopHint(); - }, - [ScriptOpcode_default.IF_CLOSESTICKY]: (state) => { - state.activePlayer.closeSticky(); - }, - [ScriptOpcode_default.P_EXACTMOVE]: checkedHandler(ProtectedActivePlayer, (state) => { - const [start, end, startCycle, endCycle, direction] = state.popInts(5); - const startPos = check(start, CoordValid); - const endPos = check(end, CoordValid); - state.activePlayer.unsetMapFlag(); - state.activePlayer.exactMove(startPos.x, startPos.z, endPos.x, endPos.z, startCycle, endCycle, direction); - }), - [ScriptOpcode_default.BUSY]: (state) => { - state.pushInt(state.activePlayer.busy() ? 1 : 0); - }, - [ScriptOpcode_default.BUSY2]: (state) => { - state.pushInt(state.activePlayer.hasInteraction() || state.activePlayer.hasWaypoints() ? 1 : 0); - }, - [ScriptOpcode_default.GETQUEUE]: (state) => { - const scriptId = state.popInt(); - let count = 0; - for (let request = state.activePlayer.queue.head(); request !== null; request = state.activePlayer.queue.next()) { - if (request.script.id === scriptId) { - count++; - } - } - for (let request = state.activePlayer.weakQueue.head(); request !== null; request = state.activePlayer.weakQueue.next()) { - if (request.script.id === scriptId) { - count++; - } - } - state.pushInt(count); - }, - // TODO: check active loc too - [ScriptOpcode_default.P_LOCMERGE]: checkedHandler(ProtectedActivePlayer, (state) => { - const [startCycle, endCycle, southEast, northWest] = state.popInts(4); - const se = check(southEast, CoordValid); - const nw = check(northWest, CoordValid); - World_default.mergeLoc(state.activeLoc, state.activePlayer, startCycle, endCycle, se.z, se.x, nw.z, nw.x); - }), - [ScriptOpcode_default.LAST_LOGIN_INFO]: (state) => { - const player = state.activePlayer; - if (!isNetworkPlayer(player) || player.client === null) { - return; - } - const client = player.client; - const remoteAddress = client.remoteAddress; - if (remoteAddress == null) { - return; - } - const lastLoginIp = new Uint32Array(new Uint8Array(remoteAddress.split(".").map((x) => parseInt(x))).reverse().buffer)[0]; - player.lastLoginInfo(lastLoginIp, 0, 201, 0); - }, - [ScriptOpcode_default.BAS_READYANIM]: (state) => { - state.activePlayer.basReadyAnim = check(state.popInt(), SeqTypeValid).id; - }, - [ScriptOpcode_default.BAS_TURNONSPOT]: (state) => { - state.activePlayer.basTurnOnSpot = check(state.popInt(), SeqTypeValid).id; - }, - [ScriptOpcode_default.BAS_WALK_F]: (state) => { - state.activePlayer.basWalkForward = check(state.popInt(), SeqTypeValid).id; - }, - [ScriptOpcode_default.BAS_WALK_B]: (state) => { - state.activePlayer.basWalkBackward = check(state.popInt(), SeqTypeValid).id; - }, - [ScriptOpcode_default.BAS_WALK_L]: (state) => { - state.activePlayer.basWalkLeft = check(state.popInt(), SeqTypeValid).id; - }, - [ScriptOpcode_default.BAS_WALK_R]: (state) => { - state.activePlayer.basWalkRight = check(state.popInt(), SeqTypeValid).id; - }, - [ScriptOpcode_default.BAS_RUNNING]: (state) => { - const seq = state.popInt(); - if (seq === -1) { - state.activePlayer.basRunning = -1; - return; - } - state.activePlayer.basRunning = check(seq, SeqTypeValid).id; - }, - [ScriptOpcode_default.GENDER]: (state) => { - state.pushInt(state.activePlayer.gender); - }, - [ScriptOpcode_default.HINT_NPC]: (state) => { - state.activePlayer.hintNpc(check(state.popInt(), NumberNotNull)); - }, - [ScriptOpcode_default.HINT_PLAYER]: (state) => { - const uid = check(state.popInt(), NumberNotNull); - const player = World_default.getPlayerByUid(uid); - if (!player) { - return; - } - state.activePlayer.hintPlayer(player.pid); - }, - [ScriptOpcode_default.HEADICONS_GET]: (state) => { - state.pushInt(state.activePlayer.headicons); - }, - [ScriptOpcode_default.HEADICONS_SET]: (state) => { - state.activePlayer.headicons = check(state.popInt(), NumberNotNull); - }, - [ScriptOpcode_default.P_OPOBJ]: checkedHandler(ProtectedActivePlayer, (state) => { - const type = check(state.popInt(), NumberNotNull) - 1; - if (type < 0 || type >= 5) { - throw new Error(`Invalid opobj: ${type + 1}`); - } - state.activePlayer.stopAction(); - state.activePlayer.setInteraction(Interaction_default.SCRIPT, state.activeObj, ServerTriggerType_default.APOBJ1 + type); - }), - [ScriptOpcode_default.P_OPPLAYER]: checkedHandler(ProtectedActivePlayer, (state) => { - const type = check(state.popInt(), NumberNotNull) - 1; - if (type < 0 || type >= 5) { - throw new Error(`Invalid opplayer: ${type + 1}`); - } - const target = state._activePlayer2; - if (!target) { - return; - } - state.activePlayer.stopAction(); - state.activePlayer.setInteraction(Interaction_default.SCRIPT, target, ServerTriggerType_default.APPLAYER1 + type); - }), - [ScriptOpcode_default.ALLOWDESIGN]: (state) => { - state.activePlayer.allowDesign = check(state.popInt(), NumberNotNull) === 1; - }, - [ScriptOpcode_default.LAST_TARGETSLOT]: (state) => { - const allowedTriggers = [ServerTriggerType_default.INV_BUTTOND]; - if (!allowedTriggers.includes(state.trigger)) { - throw new Error("is not safe to use in this trigger"); - } - state.pushInt(state.activePlayer.lastTargetSlot); - }, - [ScriptOpcode_default.WALKTRIGGER]: (state) => { - state.activePlayer.walktrigger = state.popInt(); - }, - [ScriptOpcode_default.GETWALKTRIGGER]: (state) => { - state.pushInt(state.activePlayer.walktrigger); - }, - [ScriptOpcode_default.CLEARQUEUE]: (state) => { - const scriptId = state.popInt(); - for (let request = state.activePlayer.queue.head(); request !== null; request = state.activePlayer.queue.next()) { - if (request.script.id === scriptId) { - request.unlink(); - } - } - for (let request = state.activePlayer.weakQueue.head(); request !== null; request = state.activePlayer.weakQueue.next()) { - if (request.script.id === scriptId) { - request.unlink(); - } - } - }, - [ScriptOpcode_default.HEALENERGY]: (state) => { - const amount = check(state.popInt(), NumberNotNull); - const player = state.activePlayer; - player.runenergy = Math.min(Math.max(player.runenergy + amount, 0), 1e4); - }, - [ScriptOpcode_default.AFK_EVENT]: (state) => { - state.pushInt(state.activePlayer.afkEventReady ? 1 : 0); - state.activePlayer.afkEventReady = false; - }, - [ScriptOpcode_default.LOWMEMORY]: (state) => { - state.pushInt(state.activePlayer.lowMemory ? 1 : 0); - }, - [ScriptOpcode_default.SETIDKIT]: (state) => { - const [idkit, color] = state.popInts(2); - const idkType = check(idkit, IDKTypeValid); - let slot = idkType.type; - if (state.activePlayer.gender === 1) { - slot -= 7; - } - state.activePlayer.body[slot] = idkType.id; - let type = idkType.type; - if (state.activePlayer.gender === 1) { - type -= 7; - } - let colorSlot = -1; - if (type === 0 || type === 1) { - colorSlot = 0; - } else if (type === 2 || type === 3) { - colorSlot = 1; - } else if (type === 4) { - } else if (type === 5) { - colorSlot = 2; - } else if (type === 6) { - colorSlot = 3; - } - if (colorSlot !== -1) { - state.activePlayer.colors[colorSlot] = color; - } - }, - [ScriptOpcode_default.SETGENDER]: (state) => { - const gender = check(state.popInt(), GenderValid); - for (let i = 0; i < 7; i++) { - state.activePlayer.body[i] = -1; - for (let j = 0; j < IdkType.count; j++) { - if (!IdkType.get(j).disable && IdkType.get(j).type == i + (gender === 0 ? 0 : 7)) { - state.activePlayer.body[i] = j; - break; - } - } - } - state.activePlayer.gender = gender; - }, - [ScriptOpcode_default.SETSKINCOLOUR]: (state) => { - const skin = check(state.popInt(), SkinColourValid); - state.activePlayer.colors[4] = skin; - }, - [ScriptOpcode_default.P_OPPLAYERT]: checkedHandler(ProtectedActivePlayer, (state) => { - const spellId = check(state.popInt(), NumberNotNull); - const target = state._activePlayer2; - if (!target) { - return; - } - state.activePlayer.stopAction(); - state.activePlayer.setInteraction(Interaction_default.SCRIPT, target, ServerTriggerType_default.APPLAYERT, { type: -1, com: spellId }); - }), - [ScriptOpcode_default.FINDHERO]: checkedHandler(ActivePlayer, (state) => { - const uid = state.activePlayer.findHero(); - if (uid === -1) { - state.pushInt(0); - return; - } - const player = World_default.getPlayerByUid(uid); - if (!player) { - state.pushInt(0); - return; - } - state._activePlayer2 = player; - state.pointerAdd(ScriptPointer_default.ActivePlayer2); - state.pushInt(1); - }), - [ScriptOpcode_default.BOTH_HEROPOINTS]: checkedHandler(ActivePlayer, (state) => { - const damage = check(state.popInt(), NumberNotNull); - const secondary = state.intOperand === 1; - const fromPlayer = secondary ? state._activePlayer2 : state._activePlayer; - const toPlayer = secondary ? state._activePlayer : state._activePlayer2; - if (!fromPlayer || !toPlayer) { - throw new Error("player is null"); - } - toPlayer.addHero(fromPlayer.uid, damage); - }), - [ScriptOpcode_default.P_ANIMPROTECT]: checkedHandler(ProtectedActivePlayer, (state) => { - state.activePlayer.animProtect = check(state.popInt(), NumberNotNull); - }), - [ScriptOpcode_default.RUNENERGY]: checkedHandler(ActivePlayer, (state) => { - const player = state.activePlayer; - state.pushInt(player.runenergy); - }), - [ScriptOpcode_default.WEIGHT]: checkedHandler(ProtectedActivePlayer, (state) => { - state.pushInt(state.activePlayer.runweight); - }), - [ScriptOpcode_default.LAST_COORD]: checkedHandler(ActivePlayer, (state) => { - state.pushInt(Position.packCoord(state.activePlayer.level, state.activePlayer.lastX, state.activePlayer.lastZ)); - }) -}; -function popScriptArgs(state) { - const types = state.popString(); - const count = types.length; - const args = []; - for (let i = count - 1; i >= 0; i--) { - const type = types.charAt(i); - if (type === "s") { - args[i] = state.popString(); - } else { - args[i] = state.popInt(); - } - } - return args; -} -var PlayerOps_default = PlayerOps; - -// src/lostcity/engine/script/handlers/ServerOps.ts -var ServerOps = { - [ScriptOpcode_default.MAP_CLOCK]: (state) => { - state.pushInt(World_default.currentTick); - }, - [ScriptOpcode_default.MAP_MEMBERS]: (state) => { - state.pushInt(Environment_default.NODE_MEMBERS ? 1 : 0); - }, - [ScriptOpcode_default.MAP_PLAYERCOUNT]: (state) => { - const [c1, c2] = state.popInts(2); - const from = check(c1, CoordValid); - const to = check(c2, CoordValid); - let count = 0; - for (let x = Math.floor(from.x / 8); x <= Math.ceil(to.x / 8); x++) { - for (let z = Math.floor(from.z / 8); z <= Math.ceil(to.z / 8); z++) { - for (const player of World_default.getZone(x << 3, z << 3, from.level).getAllPlayersSafe()) { - if (player.x >= from.x && player.x <= to.x && player.z >= from.z && player.z <= to.z) { - count++; - } - } - } - } - state.pushInt(count); - }, - [ScriptOpcode_default.HUNTALL]: (state) => { - const [coord, distance, checkVis] = state.popInts(3); - const position = check(coord, CoordValid); - check(distance, NumberNotNull); - const huntvis = check(checkVis, HuntVisValid); - state.huntIterator = new HuntIterator(World_default.currentTick, position.level, position.x, position.z, distance, huntvis, -1, -1, HuntModeType_default.PLAYER); - }, - [ScriptOpcode_default.HUNTNEXT]: (state) => { - const result = state.huntIterator?.next(); - if (!result || result.done) { - state.pushInt(0); - return; - } - if (!(result.value instanceof Player)) { - throw new Error("[ServerOps] huntnext command must result instance of Player."); - } - state.activePlayer = result.value; - state.pointerAdd(ActivePlayer[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.NPC_HUNTALL]: (state) => { - const [coord, distance, checkVis] = state.popInts(3); - const position = check(coord, CoordValid); - check(distance, NumberNotNull); - const huntvis = check(checkVis, HuntVisValid); - state.huntIterator = new HuntIterator(World_default.currentTick, position.level, position.x, position.z, distance, huntvis, -1, -1, HuntModeType_default.NPC); - }, - [ScriptOpcode_default.NPC_HUNTNEXT]: (state) => { - const result = state.huntIterator?.next(); - if (!result || result.done) { - state.pushInt(0); - return; - } - if (!(result.value instanceof Npc)) { - throw new Error("[ServerOps] npc_huntnext command must result instance of Npc."); - } - state.activeNpc = result.value; - state.pointerAdd(ActiveNpc[state.intOperand]); - state.pushInt(1); - }, - [ScriptOpcode_default.INZONE]: (state) => { - const [c1, c2, c3] = state.popInts(3); - const from = check(c1, CoordValid); - const to = check(c2, CoordValid); - const pos = check(c3, CoordValid); - if (pos.x < from.x || pos.x > to.x) { - state.pushInt(0); - } else if (pos.level < from.level || pos.level > to.level) { - state.pushInt(0); - } else if (pos.z < from.z || pos.z > to.z) { - state.pushInt(0); - } else { - state.pushInt(1); - } - }, - [ScriptOpcode_default.LINEOFWALK]: (state) => { - const [c1, c2] = state.popInts(2); - const from = check(c1, CoordValid); - const to = check(c2, CoordValid); - if (from.level !== to.level) { - state.pushInt(0); - return; - } - state.pushInt(hasLineOfWalk(from.level, from.x, from.z, to.x, to.z, 1, 1, 1, 1) ? 1 : 0); - }, - [ScriptOpcode_default.STAT_RANDOM]: (state) => { - const [level, low, high] = state.popInts(3); - const value = Math.floor(low * (99 - level) / 98) + Math.floor(high * (level - 1) / 98) + 1; - const chance = Math.floor(Math.random() * 256); - state.pushInt(value > chance ? 1 : 0); - }, - [ScriptOpcode_default.SPOTANIM_MAP]: (state) => { - const [spotanim, coord, height, delay] = state.popInts(4); - const position = check(coord, CoordValid); - const spotanimType = check(spotanim, SpotAnimTypeValid); - World_default.animMap(position.level, position.x, position.z, spotanimType.id, height, delay); - }, - [ScriptOpcode_default.DISTANCE]: (state) => { - const [c1, c2] = state.popInts(2); - const from = check(c1, CoordValid); - const to = check(c2, CoordValid); - state.pushInt(Position.distanceToSW(from, to)); - }, - [ScriptOpcode_default.MOVECOORD]: (state) => { - const [coord, x, y, z] = state.popInts(4); - const position = check(coord, CoordValid); - state.pushInt(Position.packCoord(position.level + y, position.x + x, position.z + z)); - }, - [ScriptOpcode_default.SEQLENGTH]: (state) => { - state.pushInt(check(state.popInt(), SeqTypeValid).duration); - }, - [ScriptOpcode_default.SPLIT_INIT]: (state) => { - const [maxWidth, linesPerPage, fontId] = state.popInts(3); - let text = state.popString(); - const font = check(fontId, FontTypeValid); - if (text.startsWith("") !== -1) { - const mesanim = text.substring(3, text.indexOf(">")); - state.splitMesanim = MesanimType.getId(mesanim); - text = text.substring(text.indexOf(">") + 1); - } else { - state.splitMesanim = -1; - } - state.splitPages = []; - const lines = font.split(text, maxWidth); - while (lines.length > 0) { - state.splitPages.push(lines.splice(0, linesPerPage)); - } - }, - [ScriptOpcode_default.SPLIT_GET]: (state) => { - const [page, line] = state.popInts(2); - state.pushString(state.splitPages[page][line]); - }, - [ScriptOpcode_default.SPLIT_PAGECOUNT]: (state) => { - state.pushInt(state.splitPages.length); - }, - [ScriptOpcode_default.SPLIT_LINECOUNT]: (state) => { - const page = state.popInt(); - state.pushInt(state.splitPages[page].length); - }, - [ScriptOpcode_default.SPLIT_GETANIM]: (state) => { - const page = state.popInt(); - if (state.splitMesanim === -1) { - state.pushInt(-1); - return; - } - state.pushInt(check(state.splitMesanim, MesanimValid).len[state.splitPages[page].length - 1]); - }, - [ScriptOpcode_default.STRUCT_PARAM]: (state) => { - const [structId, paramId] = state.popInts(2); - const paramType = check(paramId, ParamTypeValid); - const structType = check(structId, StructTypeValid); - if (paramType.isString()) { - state.pushString(ParamHelper.getStringParam(paramType.id, structType, paramType.defaultString)); - } else { - state.pushInt(ParamHelper.getIntParam(paramType.id, structType, paramType.defaultInt)); - } - }, - [ScriptOpcode_default.COORDX]: (state) => { - state.pushInt(check(state.popInt(), CoordValid).x); - }, - [ScriptOpcode_default.COORDY]: (state) => { - state.pushInt(check(state.popInt(), CoordValid).level); - }, - [ScriptOpcode_default.COORDZ]: (state) => { - state.pushInt(check(state.popInt(), CoordValid).z); - }, - [ScriptOpcode_default.PLAYERCOUNT]: (state) => { - state.pushInt(World_default.getTotalPlayers()); - }, - [ScriptOpcode_default.MAP_BLOCKED]: (state) => { - const position = check(state.popInt(), CoordValid); - state.pushInt(isFlagged(position.x, position.z, position.level, CollisionFlag.WALK_BLOCKED) ? 1 : 0); - }, - [ScriptOpcode_default.MAP_INDOORS]: (state) => { - const position = check(state.popInt(), CoordValid); - state.pushInt(isFlagged(position.x, position.z, position.level, CollisionFlag.ROOF) ? 1 : 0); - }, - [ScriptOpcode_default.LINEOFSIGHT]: (state) => { - const [c1, c2] = state.popInts(2); - const from = check(c1, CoordValid); - const to = check(c2, CoordValid); - if (from.level !== to.level) { - state.pushInt(0); - return; - } - state.pushInt(hasLineOfSight(from.level, from.x, from.z, to.x, to.z, 1, 1, 1, 1) ? 1 : 0); - }, - [ScriptOpcode_default.WORLD_DELAY]: (state) => { - state.execution = ScriptState.WORLD_SUSPENDED; - }, - [ScriptOpcode_default.PROJANIM_PL]: (state) => { - const [srcCoord, uid, spotanim, srcHeight, dstHeight, delay, duration, peak, arc] = state.popInts(9); - const srcPos = check(srcCoord, CoordValid); - const spotanimType = check(spotanim, SpotAnimTypeValid); - const player = World_default.getPlayerByUid(uid); - if (!player) { - throw new Error(`attempted to use invalid player uid: ${uid}`); - } - World_default.mapProjAnim(srcPos.level, srcPos.x, srcPos.z, player.x, player.z, -player.pid - 1, spotanimType.id, srcHeight + 100, dstHeight + 100, delay, duration, peak, arc); - }, - [ScriptOpcode_default.PROJANIM_NPC]: (state) => { - const [srcCoord, npcUid, spotanim, srcHeight, dstHeight, delay, duration, peak, arc] = state.popInts(9); - const srcPos = check(srcCoord, CoordValid); - const spotanimType = check(spotanim, SpotAnimTypeValid); - const slot = npcUid & 65535; - const expectedType = npcUid >> 16 & 65535; - const npc = World_default.getNpc(slot); - if (!npc) { - throw new Error(`attempted to use invalid npc uid: ${npcUid}`); - } - World_default.mapProjAnim(srcPos.level, srcPos.x, srcPos.z, npc.x, npc.z, npc.nid + 1, spotanimType.id, srcHeight + 100, dstHeight + 100, delay, duration, peak, arc); - }, - [ScriptOpcode_default.PROJANIM_MAP]: (state) => { - const [srcCoord, dstCoord, spotanim, srcHeight, dstHeight, delay, duration, peak, arc] = state.popInts(9); - const spotanimType = check(spotanim, SpotAnimTypeValid); - const srcPos = check(srcCoord, CoordValid); - const dstPos = check(dstCoord, CoordValid); - World_default.mapProjAnim(srcPos.level, srcPos.x, srcPos.z, dstPos.x, dstPos.z, 0, spotanimType.id, srcHeight + 100, dstHeight, delay, duration, peak, arc); - }, - [ScriptOpcode_default.MAP_LOCADDUNSAFE]: (state) => { - const pos = check(state.popInt(), CoordValid); - for (const loc of World_default.getZone(pos.x, pos.z, pos.level).getAllLocsUnsafe()) { - const type = check(loc.type, LocTypeValid); - if (type.active !== 1) { - continue; - } - const layer = locShapeLayer(loc.shape); - if (!loc.checkLifeCycle(World_default.currentTick) && layer === LocLayer.WALL) { - continue; - } - if (layer === LocLayer.WALL) { - if (loc.x === pos.x && loc.z === pos.z) { - state.pushInt(1); - return; - } - } else if (layer === LocLayer.GROUND) { - const width = loc.angle === LocAngle.NORTH || loc.angle === LocAngle.SOUTH ? loc.length : loc.width; - const length = loc.angle === LocAngle.NORTH || loc.angle === LocAngle.SOUTH ? loc.width : loc.length; - for (let index = 0; index < width * length; index++) { - const deltaX = loc.x + index % width; - const deltaZ = loc.z + (index / width | 0); - if (deltaX === pos.x && deltaZ === pos.z) { - state.pushInt(1); - return; - } - } - } else if (layer === LocLayer.GROUND_DECOR) { - if (loc.x === pos.x && loc.z === pos.z) { - state.pushInt(1); - return; - } - } - } - state.pushInt(0); - }, - [ScriptOpcode_default.NPCCOUNT]: (state) => { - state.pushInt(World_default.getTotalNpcs()); - }, - [ScriptOpcode_default.ZONECOUNT]: (state) => { - state.pushInt(World_default.getTotalZones()); - }, - [ScriptOpcode_default.LOCCOUNT]: (state) => { - state.pushInt(World_default.getTotalLocs()); - }, - [ScriptOpcode_default.OBJCOUNT]: (state) => { - state.pushInt(World_default.getTotalObjs()); - }, - [ScriptOpcode_default.MAP_FINDSQUARE]: (state) => { - const [coord, minRadius, maxRadius, type] = state.popInts(4); - check(minRadius, NumberPositive); - check(maxRadius, NumberPositive); - check(type, FindSquareValid); - const origin = check(coord, CoordValid); - if (maxRadius < 10) { - if (type === MapFindSquareType_default.NONE) { - for (let i = 0; i < 50; i++) { - const randomX = origin.x + (Math.floor(Math.random() * (maxRadius - minRadius + 1)) + minRadius) * (Math.random() < 0.5 ? 1 : -1); - const randomZ = origin.z + (Math.floor(Math.random() * (maxRadius - minRadius + 1)) + minRadius) * (Math.random() < 0.5 ? 1 : -1); - if (!isFlagged(randomX, randomZ, origin.level, CollisionFlag.WALK_BLOCKED)) { - state.pushInt(Position.packCoord(origin.level, randomX, randomZ)); - return; - } - } - } else if (type === MapFindSquareType_default.LINEOFWALK) { - for (let i = 0; i < 50; i++) { - const randomX = origin.x + (Math.floor(Math.random() * (maxRadius - minRadius + 1)) + minRadius) * (Math.random() < 0.5 ? 1 : -1); - const randomZ = origin.z + (Math.floor(Math.random() * (maxRadius - minRadius + 1)) + minRadius) * (Math.random() < 0.5 ? 1 : -1); - console.log((Math.floor(Math.random() * (maxRadius - minRadius)) + minRadius) * (Math.random() < 0.5 ? 1 : -1)); - if (hasLineOfWalk(origin.level, randomX, randomZ, origin.x, origin.z) && !isFlagged(randomX, randomZ, origin.level, CollisionFlag.WALK_BLOCKED)) { - state.pushInt(Position.packCoord(origin.level, randomX, randomZ)); - return; - } - } - } else if (type === MapFindSquareType_default.LINEOFSIGHT) { - for (let i = 0; i < 50; i++) { - const randomX = origin.x + (Math.floor(Math.random() * (maxRadius - minRadius + 1)) + minRadius) * (Math.random() < 0.5 ? 1 : -1); - const randomZ = origin.z + (Math.floor(Math.random() * (maxRadius - minRadius + 1)) + minRadius) * (Math.random() < 0.5 ? 1 : -1); - if (hasLineOfSight(origin.level, randomX, randomZ, origin.x, origin.z) && !isFlagged(randomX, randomZ, origin.level, CollisionFlag.WALK_BLOCKED)) { - state.pushInt(Position.packCoord(origin.level, randomX, randomZ)); - return; - } - } - } - } else { - if (type === MapFindSquareType_default.NONE) { - for (let x = origin.x - maxRadius; x <= origin.x + maxRadius; x++) { - const randomZ = origin.z + (Math.floor(Math.random() * (maxRadius - minRadius + 1)) + minRadius) * (Math.random() < 0.5 ? 1 : -1); - if (!isFlagged(x, randomZ, origin.level, CollisionFlag.WALK_BLOCKED) && !Position.isWithinDistanceSW({ x, z: randomZ }, origin, minRadius)) { - state.pushInt(Position.packCoord(origin.level, x, randomZ)); - return; - } - } - } else if (type === MapFindSquareType_default.LINEOFWALK) { - for (let x = origin.x - maxRadius; x <= origin.x + maxRadius; x++) { - const randomZ = origin.z + (Math.floor(Math.random() * (maxRadius - minRadius + 1)) + minRadius) * (Math.random() < 0.5 ? 1 : -1); - if (hasLineOfWalk(origin.level, x, randomZ, origin.x, origin.z) && !isFlagged(x, randomZ, origin.level, CollisionFlag.WALK_BLOCKED) && !Position.isWithinDistanceSW({ x, z: randomZ }, origin, minRadius)) { - state.pushInt(Position.packCoord(origin.level, x, randomZ)); - return; - } - } - } else if (type === MapFindSquareType_default.LINEOFSIGHT) { - for (let x = origin.x - maxRadius; x <= origin.x + maxRadius; x++) { - const randomZ = origin.z + (Math.floor(Math.random() * (maxRadius - minRadius + 1)) + minRadius) * (Math.random() < 0.5 ? 1 : -1); - if (hasLineOfSight(origin.level, x, randomZ, origin.x, origin.z) && !isFlagged(x, randomZ, origin.level, CollisionFlag.WALK_BLOCKED) && !Position.isWithinDistanceSW({ x, z: randomZ }, origin, minRadius)) { - state.pushInt(Position.packCoord(origin.level, x, randomZ)); - return; - } - } - } - } - state.pushInt(coord); - } -}; -var ServerOps_default = ServerOps; - -// src/lostcity/engine/script/handlers/StringOps.ts -var StringOps = { - [ScriptOpcode_default.APPEND_NUM]: (state) => { - const text = state.popString(); - const num = state.popInt(); - state.pushString(text + num); - }, - [ScriptOpcode_default.APPEND]: (state) => { - const [t1, t2] = state.popStrings(2); - state.pushString(t1 + t2); - }, - [ScriptOpcode_default.APPEND_SIGNNUM]: (state) => { - const text = state.popString(); - const num = state.popInt(); - if (num >= 0) { - state.pushString(`${text}+${num}`); - } else { - state.pushString(text + num); - } - }, - [ScriptOpcode_default.LOWERCASE]: (state) => { - state.pushString(state.popString().toLowerCase()); - }, - [ScriptOpcode_default.TOSTRING]: (state) => { - state.pushString(state.popInt().toString()); - }, - [ScriptOpcode_default.COMPARE]: (state) => { - const [s1, s2] = state.popStrings(2); - state.pushInt(javaStringCompare(s1, s2)); - }, - [ScriptOpcode_default.TEXT_SWITCH]: (state) => { - const value = state.popInt(); - const [s1, s2] = state.popStrings(2); - state.pushString(value === 1 ? s1 : s2); - }, - [ScriptOpcode_default.APPEND_CHAR]: (state) => { - const text = state.popString(); - const char = state.popInt(); - state.pushString(text + String.fromCharCode(char)); - }, - [ScriptOpcode_default.STRING_LENGTH]: (state) => { - state.pushInt(state.popString().length); - }, - [ScriptOpcode_default.SUBSTRING]: (state) => { - const text = state.popString(); - const [start, end] = state.popInts(2); - state.pushString(text.substring(start, end)); - }, - [ScriptOpcode_default.STRING_INDEXOF_CHAR]: (state) => { - const text = state.popString(); - const find = String.fromCharCode(state.popInt()); - state.pushInt(text.indexOf(find)); - }, - [ScriptOpcode_default.STRING_INDEXOF_STRING]: (state) => { - const text = state.popString(); - const find = state.popString(); - state.pushInt(text.indexOf(find)); - } -}; -function javaStringCompare(a, b) { - const len1 = a.length; - const len2 = b.length; - const lim = Math.min(len1, len2); - let k = 0; - while (k < lim) { - const c1 = a.charCodeAt(k); - const c2 = b.charCodeAt(k); - if (c1 != c2) { - return c1 - c2; - } - k++; - } - return len1 - len2; -} -var StringOps_default = StringOps; - -// src/lostcity/engine/script/ScriptRunner.ts -var ScriptRunner = class _ScriptRunner { - static HANDLERS = { - // Language required opcodes - ...CoreOps_default, - ...ServerOps_default, - ...PlayerOps_default, - ...NpcOps_default, - ...LocOps_default, - ...ObjOps_default, - ...NpcConfigOps_default, - ...LocConfigOps_default, - ...ObjConfigOps_default, - ...InvOps_default, - ...EnumOps_default, - ...StringOps_default, - ...NumberOps_default, - ...DbOps_default, - ...DebugOps_default - }; - /** - * - * @param script - * @param self - * @param target - * @param on - * @param args - */ - static init(script, self2 = null, target = null, args = []) { - const state = new ScriptState(script, args); - state.self = self2; - if (self2 instanceof Player) { - state._activePlayer = self2; - state.pointerAdd(ScriptPointer_default.ActivePlayer); - } else if (self2 instanceof Npc) { - state._activeNpc = self2; - state.pointerAdd(ScriptPointer_default.ActiveNpc); - } else if (self2 instanceof Loc) { - state._activeLoc = self2; - state.pointerAdd(ScriptPointer_default.ActiveLoc); - } else if (self2 instanceof Obj) { - state._activeObj = self2; - state.pointerAdd(ScriptPointer_default.ActiveObj); - } - if (target instanceof Player) { - if (self2 instanceof Player) { - state._activePlayer2 = target; - state.pointerAdd(ScriptPointer_default.ActivePlayer2); - } else { - state._activePlayer = target; - state.pointerAdd(ScriptPointer_default.ActivePlayer); - } - } else if (target instanceof Npc) { - if (self2 instanceof Npc) { - state._activeNpc2 = target; - state.pointerAdd(ScriptPointer_default.ActiveNpc2); - } else { - state._activeNpc = target; - state.pointerAdd(ScriptPointer_default.ActiveNpc); - } - } else if (target instanceof Loc) { - if (self2 instanceof Loc) { - state._activeLoc2 = target; - state.pointerAdd(ScriptPointer_default.ActiveLoc2); - } else { - state._activeLoc = target; - state.pointerAdd(ScriptPointer_default.ActiveLoc); - } - } else if (target instanceof Obj) { - if (self2 instanceof Obj) { - state._activeObj2 = target; - state.pointerAdd(ScriptPointer_default.ActiveObj2); - } else { - state._activeObj = target; - state.pointerAdd(ScriptPointer_default.ActiveObj); - } - } - return state; - } - static execute(state, reset = false, benchmark = false) { - if (!state || !state.script || !state.script.info) { - return ScriptState.ABORTED; - } - try { - if (reset) { - state.reset(); - } - if (state.execution !== ScriptState.RUNNING) { - state.executionHistory.push(state.execution); - } - state.execution = ScriptState.RUNNING; - const start = performance.now() * 1e3; - while (state.execution === ScriptState.RUNNING) { - if (state.pc >= state.script.opcodes.length || state.pc < -1) { - throw new Error("Invalid program counter: " + state.pc + ", max expected: " + state.script.opcodes.length); - } - if (!benchmark && state.opcount > 5e5) { - throw new Error("Too many instructions"); - } - state.opcount++; - _ScriptRunner.executeInner(state, state.script.opcodes[++state.pc]); - } - const time = performance.now() * 1e3 - start | 0; - if (Environment_default.NODE_DEBUG_PROFILE && time > 1e3) { - const message = `Warning [cpu time]: Script: ${state.script.info.scriptName}, time: ${time}us, opcount: ${state.opcount}`; - if (state.self instanceof Player) { - state.self.wrappedMessageGame(message); - } else { - console.warn(message); - } - } - } catch (err) { - if (state.pc >= 0 && state.pc < state.script.opcodes.length) { - const opcode = state.script.opcodes[state.pc]; - let secondary = state.intOperand; - if (opcode === ScriptOpcode_default.POP_VARP || opcode === ScriptOpcode_default.POP_VARN || opcode === ScriptOpcode_default.PUSH_VARP || opcode === ScriptOpcode_default.PUSH_VARN) { - secondary = state.intOperand >> 16 & 1; - } else if (opcode <= ScriptOpcode_default.POP_ARRAY_INT) { - secondary = 0; - } - err.message = ScriptOpcode_default[opcode].toLowerCase() + " " + err.message; - if (secondary) { - err.message = "." + err.message; - } - } - if (state.self instanceof Player) { - state.self.wrappedMessageGame(`script error: ${err.message}`); - state.self.wrappedMessageGame(`file: ${state.script.fileName}`); - state.self.wrappedMessageGame(""); - state.self.wrappedMessageGame("stack backtrace:"); - state.self.wrappedMessageGame(` 1: ${state.script.name} - ${state.script.fileName}:${state.script.lineNumber(state.pc)}`); - let trace2 = 1; - for (let i = state.fp; i > 0; i--) { - const frame = state.frames[i]; - if (frame) { - trace2++; - state.self.wrappedMessageGame(` ${trace2}: ${frame.script.name} - ${frame.script.fileName}:${frame.script.lineNumber(frame.pc)}`); - } - } - for (let i = state.debugFp; i >= 0; i--) { - const frame = state.debugFrames[i]; - if (frame) { - trace2++; - state.self.wrappedMessageGame(` ${trace2}: ${frame.script.name} - ${frame.script.fileName}:${frame.script.lineNumber(frame.pc)}`); - } - } - } - console.error(`script error: ${err.message}`); - console.error(`file: ${state.script.fileName}`); - console.error(""); - console.error("stack backtrace:"); - console.error(` 1: ${state.script.name} - ${state.script.fileName}:${state.script.lineNumber(state.pc)}`); - let trace = 1; - for (let i = state.fp; i > 0; i--) { - const frame = state.frames[i]; - if (frame) { - trace++; - console.error(` ${trace}: ${frame.script.name} - ${frame.script.fileName}:${frame.script.lineNumber(frame.pc)}`); - } - } - for (let i = state.debugFp; i >= 0; i--) { - const frame = state.debugFrames[i]; - if (frame) { - trace++; - console.error(` ${trace}: ${frame.script.name} - ${frame.script.fileName}:${frame.script.lineNumber(frame.pc)}`); - } - } - state.execution = ScriptState.ABORTED; - } - return state.execution; - } - static executeInner(state, opcode) { - const handler = _ScriptRunner.HANDLERS[opcode]; - if (!handler) { - throw new Error(`Unknown opcode ${opcode}`); - } - handler(state); - } -}; - -// src/lostcity/entity/Npc.ts -var Npc = class _Npc extends PathingEntity { - static ANIM = 2; - static FACE_ENTITY = 4; - static SAY = 8; - static DAMAGE = 16; - static CHANGE_TYPE = 32; - static SPOTANIM = 64; - static FACE_COORD = 128; - // constructor properties - nid; - type; - uid; - origType; - startX; - startZ; - levels = new Uint8Array(6); - baseLevels = new Uint8Array(6); - // runtime variables - vars; - varsString; - // script variables - activeScript = null; - delay = 0; - queue = new LinkList(); - timerInterval = 0; - timerClock = 0; - huntMode = -1; - nextHuntTick = -1; - huntrange = 5; - nextPatrolTick = -1; - nextPatrolPoint = 0; - delayedPatrol = false; - heroPoints = new Array(16); - // be sure to reset when stats are recovered/reset - constructor(level, x, z, width, length, lifecycle, nid, type, moveRestrict, blockWalk) { - super(level, x, z, width, length, lifecycle, moveRestrict, blockWalk, MoveStrategy_default.NAIVE, _Npc.FACE_COORD, _Npc.FACE_ENTITY); - this.nid = nid; - this.type = type; - this.uid = type << 16 | nid; - this.startX = this.x; - this.startZ = this.z; - this.origType = type; - const npcType = NpcType.get(type); - for (let index = 0; index < npcType.stats.length; index++) { - const level2 = npcType.stats[index]; - this.levels[index] = level2; - this.baseLevels[index] = level2; - } - if (npcType.timer !== -1) { - this.setTimer(npcType.timer); - } - this.vars = new Int32Array(VarNpcType.count); - this.varsString = new Array(VarNpcType.count); - this.targetOp = npcType.defaultmode; - this.huntMode = npcType.huntmode; - this.huntrange = npcType.huntrange; - } - resetHeroPoints() { - this.heroPoints = new Array(16); - this.heroPoints.fill({ uid: -1, points: 0 }); - } - addHero(uid, points) { - const index = this.heroPoints.findIndex((hero) => hero && hero.uid === uid); - if (index !== -1) { - this.heroPoints[index].points += points; - return; - } - const emptyIndex = this.heroPoints.findIndex((hero) => hero && hero.uid === -1); - if (emptyIndex !== -1) { - this.heroPoints[emptyIndex] = { uid, points }; - return; - } - } - findHero() { - this.heroPoints.sort((a, b) => { - return b.points - a.points; - }); - return this.heroPoints[0]?.uid ?? -1; - } - getVar(id) { - const varn = VarNpcType.get(id); - return varn.type === ScriptVarType.STRING ? this.varsString[varn.id] : this.vars[varn.id]; - } - setVar(id, value) { - const varn = VarNpcType.get(id); - if (varn.type === ScriptVarType.STRING && typeof value === "string") { - this.varsString[varn.id] = value; - } else if (typeof value === "number") { - this.vars[varn.id] = value; - } - } - resetEntity(respawn) { - if (respawn) { - this.type = this.origType; - this.uid = this.type << 16 | this.nid; - this.faceX = -1; - this.faceZ = -1; - this.orientationX = -1; - this.orientationZ = -1; - for (let index = 0; index < this.baseLevels.length; index++) { - this.levels[index] = this.baseLevels[index]; - } - this.resetHeroPoints(); - this.defaultMode(); - const npcType = NpcType.get(this.type); - this.huntrange = npcType.huntrange; - } - super.resetPathingEntity(); - } - updateMovement(repathAllowed = true) { - const type = NpcType.get(this.type); - if (type.moverestrict === MoveRestrict_default.NOMOVE) { - return false; - } - if (this.target && this.targetOp !== NpcMode_default.PLAYERFOLLOW && this.targetOp !== NpcMode_default.WANDER) { - if (this.targetOp === NpcMode_default.PLAYERESCAPE) { - const distanceToEscape = Position.distanceTo(this, { - x: this.startX, - z: this.startZ, - width: this.width, - length: this.length - }); - const targetDistanceFromStart = Position.distanceTo(this.target, { - x: this.startX, - z: this.startZ, - width: this.target.width, - length: this.target.length - }); - if (targetDistanceFromStart > type.maxrange && distanceToEscape > type.maxrange) { - return false; - } - } - if (this.targetOp >= NpcMode_default.OPPLAYER1 && this.targetOp <= NpcMode_default.OPPLAYER5) { - const distanceToX = Math.abs(this.target.x - this.startX); - const distanceToZ = Math.abs(this.target.z - this.startZ); - if (Math.max(distanceToX, distanceToZ) > type.maxrange + 1) { - this.defaultMode(); - return false; - } - if (distanceToX === type.maxrange + 1 && distanceToZ === type.maxrange + 1) { - this.defaultMode(); - return false; - } - } else if (this.targetOp >= NpcMode_default.APPLAYER1 && this.targetOp <= NpcMode_default.APPLAYER5) { - if (Position.distanceToSW(this.target, { x: this.startX, z: this.startZ }) > type.maxrange + type.attackrange) { - this.defaultMode(); - return false; - } - } - } - if (repathAllowed && this.target instanceof PathingEntity && !this.interacted && this.walktrigger === -1) { - this.pathToPathingTarget(); - } - if (this.walktrigger !== -1) { - const type2 = NpcType.get(this.type); - const script = ScriptProvider.getByTrigger(ServerTriggerType_default.AI_QUEUE1 + this.walktrigger, type2.id, type2.category); - this.walktrigger = -1; - if (script) { - const state = ScriptRunner.init(script, this, null, [this.walktriggerArg]); - ScriptRunner.execute(state); - } - } - if (this.moveSpeed !== MoveSpeed_default.INSTANT) { - this.moveSpeed = this.defaultMoveSpeed(); - } - return super.processMovement(); - } - blockWalkFlag() { - if (this.moveRestrict === MoveRestrict_default.NORMAL) { - return CollisionFlag.NPC; - } else if (this.moveRestrict === MoveRestrict_default.BLOCKED) { - return CollisionFlag.OPEN; - } else if (this.moveRestrict === MoveRestrict_default.BLOCKED_NORMAL) { - return CollisionFlag.NPC; - } else if (this.moveRestrict === MoveRestrict_default.INDOORS) { - return CollisionFlag.NPC; - } else if (this.moveRestrict === MoveRestrict_default.OUTDOORS) { - return CollisionFlag.NPC; - } else if (this.moveRestrict === MoveRestrict_default.NOMOVE) { - return CollisionFlag.NULL; - } else if (this.moveRestrict === MoveRestrict_default.PASSTHRU) { - return CollisionFlag.OPEN; - } - return CollisionFlag.NULL; - } - defaultMoveSpeed() { - return MoveSpeed_default.WALK; - } - // ---- - delayed() { - return this.delay > 0; - } - setTimer(interval) { - this.timerInterval = interval; - this.timerClock = 0; - } - executeScript(script) { - if (!script) { - return; - } - const state = ScriptRunner.execute(script); - if (state !== ScriptState.FINISHED && state !== ScriptState.ABORTED) { - if (state === ScriptState.WORLD_SUSPENDED) { - World_default.enqueueScript(script, script.popInt()); - } else if (state === ScriptState.NPC_SUSPENDED) { - script.activeNpc.activeScript = script; - } else { - script.activePlayer.activeScript = script; - } - } else if (script === this.activeScript) { - this.activeScript = null; - } - if (script.pointerGet(ScriptPointer_default.ProtectedActivePlayer) && script._activePlayer) { - script._activePlayer.protect = false; - script.pointerRemove(ScriptPointer_default.ProtectedActivePlayer); - } - if (script.pointerGet(ScriptPointer_default.ProtectedActivePlayer2) && script._activePlayer2) { - script._activePlayer2.protect = false; - script.pointerRemove(ScriptPointer_default.ProtectedActivePlayer2); - } - } - processTimers() { - if (this.timerInterval !== 0 && ++this.timerClock >= this.timerInterval) { - this.timerClock = 0; - const type = NpcType.get(this.type); - const script = ScriptProvider.getByTrigger(ServerTriggerType_default.AI_TIMER, type.id, type.category); - if (script) { - this.executeScript(ScriptRunner.init(script, this)); - } - } - } - processQueue() { - for (let request = this.queue.head(); request !== null; request = this.queue.next()) { - if (!this.delayed()) { - request.delay--; - } - if (!this.delayed() && request.delay <= 0) { - const state = ScriptRunner.init(request.script, this, null, request.args); - state.lastInt = request.lastInt; - this.executeScript(state); - request.unlink(); - } - } - } - enqueueScript(script, delay = 0, arg = 0) { - const request = new EntityQueueRequest(0 /* NORMAL */, script, [], delay); - request.lastInt = arg; - this.queue.addTail(request); - } - randomWalk(range) { - const dx = Math.round(Math.random() * (range * 2) - range); - const dz = Math.round(Math.random() * (range * 2) - range); - const destX = this.startX + dx; - const destZ = this.startZ + dz; - if (destX !== this.x || destZ !== this.z) { - this.queueWaypoint(destX, destZ); - } - } - processNpcModes() { - if (this.targetOp === NpcMode_default.NULL) { - this.defaultMode(); - } else if (this.targetOp === NpcMode_default.NONE) { - this.noMode(); - } else if (this.targetOp === NpcMode_default.WANDER) { - this.wanderMode(); - } else if (this.targetOp === NpcMode_default.PATROL) { - this.patrolMode(); - } else if (this.targetOp === NpcMode_default.PLAYERESCAPE) { - this.playerEscapeMode(); - } else if (this.targetOp === NpcMode_default.PLAYERFOLLOW) { - this.playerFollowMode(); - } else if (this.targetOp === NpcMode_default.PLAYERFACE) { - this.playerFaceMode(); - } else if (this.targetOp === NpcMode_default.PLAYERFACECLOSE) { - this.playerFaceCloseMode(); - } else { - this.aiMode(); - } - } - noMode() { - this.clearInteraction(); - this.updateMovement(false); - this.targetOp = NpcMode_default.NONE; - } - defaultMode() { - this.clearInteraction(); - this.updateMovement(false); - const type = NpcType.get(this.type); - this.targetOp = type.defaultmode; - } - wanderMode() { - const type = NpcType.get(this.type); - if (type.moverestrict !== MoveRestrict_default.NOMOVE && Math.random() < 0.125) { - this.randomWalk(type.wanderrange); - } - this.updateMovement(false); - } - patrolMode() { - const type = NpcType.get(this.type); - const patrolPoints = type.patrolCoord; - const patrolDelay = type.patrolDelay[this.nextPatrolPoint]; - let dest = Position.unpackCoord(patrolPoints[this.nextPatrolPoint]); - this.updateMovement(false); - if (!this.hasWaypoints() && !this.target) { - this.queueWaypoint(dest.x, dest.z); - } - if (!(this.x === dest.x && this.z === dest.z) && World_default.currentTick >= this.nextPatrolTick) { - this.teleport(dest.x, dest.z, dest.level); - } - if (this.x === dest.x && this.z === dest.z && !this.delayedPatrol) { - this.nextPatrolTick = World_default.currentTick + patrolDelay; - this.delayedPatrol = true; - } - if (this.nextPatrolTick > World_default.currentTick) { - return; - } - this.nextPatrolPoint = (this.nextPatrolPoint + 1) % patrolPoints.length; - this.nextPatrolTick = World_default.currentTick + 30; - this.delayedPatrol = false; - dest = Position.unpackCoord(patrolPoints[this.nextPatrolPoint]); - this.queueWaypoint(dest.x, dest.z); - } - playerEscapeMode() { - if (!this.target) { - this.defaultMode(); - return; - } - if (!(this.target instanceof Player)) { - throw new Error("[Npc] Target must be a Player for playerescape mode."); - } - if (World_default.getPlayerByUid(this.target.uid) === null) { - this.defaultMode(); - return; - } - if (Position.distanceToSW(this, this.target) > 25) { - this.defaultMode(); - return; - } - let direction; - let flags; - if (this.target.x >= this.x && this.target.z >= this.z) { - direction = Direction.SOUTH_WEST; - flags = CollisionFlag.WALL_SOUTH | CollisionFlag.WALL_WEST; - } else if (this.target.x >= this.x && this.target.z < this.z) { - direction = Direction.NORTH_WEST; - flags = CollisionFlag.WALL_NORTH | CollisionFlag.WALL_WEST; - } else if (this.target.x < this.x && this.target.z >= this.z) { - direction = Direction.SOUTH_EAST; - flags = CollisionFlag.WALL_SOUTH | CollisionFlag.WALL_EAST; - } else { - direction = Direction.NORTH_EAST; - flags = CollisionFlag.WALL_NORTH | CollisionFlag.WALL_EAST; - } - const mx = Position.moveX(this.x, direction); - const mz = Position.moveZ(this.z, direction); - if (isFlagged(mx, mz, this.level, flags)) { - this.defaultMode(); - return; - } - const position = { x: mx, z: mz, level: this.level }; - if (Position.distanceToSW(position, { - x: this.startX, - z: this.startZ - }) < NpcType.get(this.type).maxrange) { - this.queueWaypoint(position.x, position.z); - this.updateMovement(false); - return; - } - if (direction === Direction.NORTH_EAST || direction === Direction.NORTH_WEST) { - this.queueWaypoint(this.x, position.z); - } else { - this.queueWaypoint(position.x, this.z); - } - this.updateMovement(false); - } - playerFollowMode() { - const player = this.target; - if (!player) { - this.defaultMode(); - return; - } - if (!(player instanceof Player)) { - throw new Error("[Npc] Target must be a Player for playerfollow mode."); - } - if (World_default.getPlayerByUid(player.uid) === null) { - this.defaultMode(); - return; - } - if (player.level !== this.level || !Position.isWithinDistanceSW(this, player, 15)) { - this.teleport(player.x, player.z, player.level); - this.startX = player.x; - this.startZ = player.z; - } - this.pathToTarget(); - this.updateMovement(); - } - playerFaceMode() { - if (!this.target) { - this.defaultMode(); - return; - } - if (!(this.target instanceof Player)) { - throw new Error("[Npc] Target must be a Player for playerface mode."); - } - if (World_default.getPlayerByUid(this.target.uid) === null) { - this.defaultMode(); - return; - } - if (this.level !== this.target.level) { - this.defaultMode(); - return; - } - const type = NpcType.get(this.type); - if (Position.distanceTo(this, this.target) > type.maxrange) { - this.defaultMode(); - return; - } - this.clearWaypoints(); - this.updateMovement(false); - } - playerFaceCloseMode() { - if (!this.target) { - this.defaultMode(); - return; - } - if (!(this.target instanceof Player)) { - throw new Error("[Npc] Target must be a Player for playerfaceclose mode."); - } - if (World_default.getPlayerByUid(this.target.uid) == null) { - this.defaultMode(); - return; - } - if (this.level !== this.target.level) { - this.defaultMode(); - return; - } - if (Position.distanceTo(this, this.target) > 1) { - this.defaultMode(); - return; - } - this.clearWaypoints(); - this.updateMovement(false); - } - aiMode() { - if (this.delayed() || !this.target) { - this.defaultMode(); - return; - } - if (this.target.level !== this.level) { - this.defaultMode(); - return; - } - if (this.target instanceof _Npc && (typeof World_default.getNpc(this.target.nid) === "undefined" || this.target.delayed())) { - this.defaultMode(); - return; - } - if (this.target instanceof _Npc && this.targetSubject.type !== -1 && World_default.getNpcByUid(this.targetSubject.type << 16 | this.target.nid) === null) { - this.defaultMode(); - return; - } - if (this.target instanceof Obj && World_default.getObj(this.target.x, this.target.z, this.level, this.target.type, -1) === null) { - this.defaultMode(); - return; - } - if (this.target instanceof Loc && World_default.getLoc(this.target.x, this.target.z, this.level, this.target.type) === null) { - this.defaultMode(); - return; - } - if (this.target instanceof Player && World_default.getPlayerByUid(this.target.uid) === null) { - this.defaultMode(); - return; - } - const type = NpcType.get(this.type); - const apTrigger = this.targetOp >= NpcMode_default.APNPC1 && this.targetOp <= NpcMode_default.APNPC5 || this.targetOp >= NpcMode_default.APPLAYER1 && this.targetOp <= NpcMode_default.APPLAYER5 || this.targetOp >= NpcMode_default.APLOC1 && this.targetOp <= NpcMode_default.APLOC5 || this.targetOp >= NpcMode_default.APOBJ1 && this.targetOp <= NpcMode_default.APOBJ5; - const opTrigger = !apTrigger; - const script = this.getTrigger(); - if (script && opTrigger && this.inOperableDistance(this.target) && this.target instanceof PathingEntity) { - this.executeScript(ScriptRunner.init(script, this, this.target)); - this.interacted = true; - this.clearWaypoints(); - } else if (script && apTrigger && this.inApproachDistance(type.attackrange, this.target)) { - this.executeScript(ScriptRunner.init(script, this, this.target)); - this.interacted = true; - this.clearWaypoints(); - } else if (this.inOperableDistance(this.target) && this.target instanceof PathingEntity) { - this.target = null; - this.interacted = true; - this.clearWaypoints(); - } - const moved = this.updateMovement(); - if (moved) { - if (!type.givechase) { - this.defaultMode(); - return; - } - this.alreadyFacedEntity = false; - } - if (this.target && !this.interacted) { - this.interacted = false; - if (script && opTrigger && this.inOperableDistance(this.target) && (this.target instanceof PathingEntity || !moved)) { - this.executeScript(ScriptRunner.init(script, this, this.target)); - this.interacted = true; - this.clearWaypoints(); - } else if (script && apTrigger && this.inApproachDistance(type.attackrange, this.target)) { - this.executeScript(ScriptRunner.init(script, this, this.target)); - this.interacted = true; - this.clearWaypoints(); - } else if (this.inOperableDistance(this.target) && (this.target instanceof PathingEntity || !moved)) { - this.target = null; - this.interacted = true; - this.clearWaypoints(); - } - } - } - getTrigger() { - const trigger = this.getTriggerForMode(this.targetOp); - if (trigger) { - return ScriptProvider.getByTrigger(trigger, this.type, -1) ?? null; - } - return null; - } - getTriggerForMode(mode) { - if (mode === NpcMode_default.OPPLAYER1) { - return ServerTriggerType_default.AI_OPPLAYER1; - } else if (mode === NpcMode_default.OPPLAYER2) { - return ServerTriggerType_default.AI_OPPLAYER2; - } else if (mode === NpcMode_default.OPPLAYER3) { - return ServerTriggerType_default.AI_OPPLAYER3; - } else if (mode === NpcMode_default.OPPLAYER4) { - return ServerTriggerType_default.AI_OPPLAYER4; - } else if (mode === NpcMode_default.OPPLAYER5) { - return ServerTriggerType_default.AI_OPPLAYER5; - } else if (mode === NpcMode_default.APPLAYER1) { - return ServerTriggerType_default.AI_APPLAYER1; - } else if (mode === NpcMode_default.APPLAYER2) { - return ServerTriggerType_default.AI_APPLAYER2; - } else if (mode === NpcMode_default.APPLAYER3) { - return ServerTriggerType_default.AI_APPLAYER3; - } else if (mode === NpcMode_default.APPLAYER4) { - return ServerTriggerType_default.AI_APPLAYER4; - } else if (mode === NpcMode_default.APPLAYER5) { - return ServerTriggerType_default.AI_APPLAYER5; - } else if (mode === NpcMode_default.OPLOC1) { - return ServerTriggerType_default.AI_OPLOC1; - } else if (mode === NpcMode_default.OPLOC2) { - return ServerTriggerType_default.AI_OPLOC2; - } else if (mode === NpcMode_default.OPLOC3) { - return ServerTriggerType_default.AI_OPLOC3; - } else if (mode === NpcMode_default.OPLOC4) { - return ServerTriggerType_default.AI_OPLOC4; - } else if (mode === NpcMode_default.OPLOC5) { - return ServerTriggerType_default.AI_OPLOC5; - } else if (mode === NpcMode_default.APLOC1) { - return ServerTriggerType_default.AI_APLOC1; - } else if (mode === NpcMode_default.APLOC2) { - return ServerTriggerType_default.AI_APLOC2; - } else if (mode === NpcMode_default.APLOC3) { - return ServerTriggerType_default.AI_APLOC3; - } else if (mode === NpcMode_default.APLOC4) { - return ServerTriggerType_default.AI_APLOC4; - } else if (mode === NpcMode_default.APLOC5) { - return ServerTriggerType_default.AI_APLOC5; - } else if (mode === NpcMode_default.OPOBJ1) { - return ServerTriggerType_default.AI_OPOBJ1; - } else if (mode === NpcMode_default.OPOBJ2) { - return ServerTriggerType_default.AI_OPOBJ2; - } else if (mode === NpcMode_default.OPOBJ3) { - return ServerTriggerType_default.AI_OPOBJ3; - } else if (mode === NpcMode_default.OPOBJ4) { - return ServerTriggerType_default.AI_OPOBJ4; - } else if (mode === NpcMode_default.OPOBJ5) { - return ServerTriggerType_default.AI_OPOBJ5; - } else if (mode === NpcMode_default.APOBJ1) { - return ServerTriggerType_default.AI_APOBJ1; - } else if (mode === NpcMode_default.APOBJ2) { - return ServerTriggerType_default.AI_APOBJ2; - } else if (mode === NpcMode_default.APOBJ3) { - return ServerTriggerType_default.AI_APOBJ3; - } else if (mode === NpcMode_default.APOBJ4) { - return ServerTriggerType_default.AI_APOBJ4; - } else if (mode === NpcMode_default.APOBJ5) { - return ServerTriggerType_default.AI_APOBJ5; - } else if (mode === NpcMode_default.OPNPC1) { - return ServerTriggerType_default.AI_OPNPC1; - } else if (mode === NpcMode_default.OPNPC2) { - return ServerTriggerType_default.AI_OPNPC2; - } else if (mode === NpcMode_default.OPNPC3) { - return ServerTriggerType_default.AI_OPNPC3; - } else if (mode === NpcMode_default.OPNPC4) { - return ServerTriggerType_default.AI_OPNPC4; - } else if (mode === NpcMode_default.OPNPC5) { - return ServerTriggerType_default.AI_OPNPC5; - } else if (mode === NpcMode_default.APNPC1) { - return ServerTriggerType_default.AI_APNPC1; - } else if (mode === NpcMode_default.APNPC2) { - return ServerTriggerType_default.AI_APNPC2; - } else if (mode === NpcMode_default.APNPC3) { - return ServerTriggerType_default.AI_APNPC3; - } else if (mode === NpcMode_default.APNPC4) { - return ServerTriggerType_default.AI_APNPC4; - } else if (mode === NpcMode_default.APNPC5) { - return ServerTriggerType_default.AI_APNPC5; - } else if (mode === NpcMode_default.QUEUE1) { - return ServerTriggerType_default.AI_QUEUE1; - } else if (mode === NpcMode_default.QUEUE2) { - return ServerTriggerType_default.AI_QUEUE2; - } else if (mode === NpcMode_default.QUEUE3) { - return ServerTriggerType_default.AI_QUEUE3; - } else if (mode === NpcMode_default.QUEUE4) { - return ServerTriggerType_default.AI_QUEUE4; - } else if (mode === NpcMode_default.QUEUE5) { - return ServerTriggerType_default.AI_QUEUE5; - } else if (mode === NpcMode_default.QUEUE6) { - return ServerTriggerType_default.AI_QUEUE6; - } else if (mode === NpcMode_default.QUEUE7) { - return ServerTriggerType_default.AI_QUEUE7; - } else if (mode === NpcMode_default.QUEUE8) { - return ServerTriggerType_default.AI_QUEUE8; - } else if (mode === NpcMode_default.QUEUE9) { - return ServerTriggerType_default.AI_QUEUE9; - } else if (mode === NpcMode_default.QUEUE10) { - return ServerTriggerType_default.AI_QUEUE10; - } else if (mode === NpcMode_default.QUEUE11) { - return ServerTriggerType_default.AI_QUEUE11; - } else if (mode === NpcMode_default.QUEUE12) { - return ServerTriggerType_default.AI_QUEUE12; - } else if (mode === NpcMode_default.QUEUE13) { - return ServerTriggerType_default.AI_QUEUE13; - } else if (mode === NpcMode_default.QUEUE14) { - return ServerTriggerType_default.AI_QUEUE14; - } else if (mode === NpcMode_default.QUEUE15) { - return ServerTriggerType_default.AI_QUEUE15; - } else if (mode === NpcMode_default.QUEUE16) { - return ServerTriggerType_default.AI_QUEUE16; - } else if (mode === NpcMode_default.QUEUE17) { - return ServerTriggerType_default.AI_QUEUE17; - } else if (mode === NpcMode_default.QUEUE18) { - return ServerTriggerType_default.AI_QUEUE18; - } else if (mode === NpcMode_default.QUEUE19) { - return ServerTriggerType_default.AI_QUEUE19; - } else if (mode === NpcMode_default.QUEUE20) { - return ServerTriggerType_default.AI_QUEUE20; - } - return null; - } - huntAll() { - if (this.nextHuntTick > World_default.currentTick) { - return; - } - const hunt = HuntType.get(this.huntMode); - if (hunt.type === HuntModeType_default.OFF) { - return; - } - if (hunt.nobodyNear === HuntNobodyNear_default.PAUSEHUNT && !World_default.getZoneGrid(this.level).isFlagged(Position.zone(this.x), Position.zone(this.z), 5)) { - return; - } - if (!hunt.findKeepHunting && this.target !== null) { - return; - } - let hunted; - if (hunt.type === HuntModeType_default.PLAYER) { - hunted = this.huntPlayers(hunt); - } else if (hunt.type === HuntModeType_default.NPC) { - hunted = this.huntNpcs(hunt); - } else if (hunt.type === HuntModeType_default.OBJ) { - hunted = this.huntObjs(hunt); - } else { - hunted = this.huntLocs(hunt); - } - if (hunted.length > 0) { - const entity = hunted[Math.floor(Math.random() * hunted.length)]; - this.setInteraction(Interaction_default.SCRIPT, entity, hunt.findNewMode); - } - this.nextHuntTick = World_default.currentTick + hunt.rate; - } - huntPlayers(hunt) { - const type = NpcType.get(this.type); - const players = []; - const hunted = new HuntIterator(World_default.currentTick, this.level, this.x, this.z, this.huntrange, hunt.checkVis, -1, -1, HuntModeType_default.PLAYER); - const opTrigger = hunt.findNewMode >= NpcMode_default.OPPLAYER1 && hunt.findNewMode <= NpcMode_default.OPPLAYER5; - for (const player of hunted) { - if (!(player instanceof Player)) { - throw new Error("[Npc] huntAll must be of type Player here."); - } - if (opTrigger) { - const distanceToX = Math.abs(player.x - this.startX); - const distanceToZ = Math.abs(player.z - this.startZ); - if (Math.max(distanceToX, distanceToZ) > type.maxrange + 1) { - continue; - } - if (distanceToX === type.maxrange + 1 && distanceToZ === type.maxrange + 1) { - continue; - } - } else { - if (Position.distanceToSW(player, { x: this.startX, z: this.startZ }) > type.maxrange + type.attackrange) { - continue; - } - } - if (hunt.checkAfk && player.zonesAfk()) { - continue; - } - if (hunt.checkNotTooStrong === HuntCheckNotTooStrong_default.OUTSIDE_WILDERNESS && !player.isInWilderness() && player.combatLevel > type.vislevel * 2) { - continue; - } - if (hunt.checkNotCombat !== -1 && player.getVar(hunt.checkNotCombat) + 8 > World_default.currentTick) { - continue; - } else if (hunt.checkNotCombatSelf !== -1 && this.getVar(hunt.checkNotCombatSelf) >= World_default.currentTick) { - continue; - } - if (hunt.checkInv !== -1) { - let quantity = 0; - if (hunt.checkObj !== -1) { - quantity = player.invTotal(hunt.checkInv, hunt.checkObj); - } else if (hunt.checkObjParam !== -1) { - quantity = player.invTotalParam(hunt.checkInv, hunt.checkObjParam); - } - if (quantity < hunt.checkInvMinQuantity || quantity > hunt.checkInvMaxQuantity) { - continue; - } - } - if (hunt.checkNotBusy && player.busy()) { - continue; - } - players.push(player); - } - return players; - } - huntNpcs(hunt) { - return Array.from(new HuntIterator(World_default.currentTick, this.level, this.x, this.z, this.huntrange, hunt.checkVis, hunt.checkNpc, hunt.checkCategory, HuntModeType_default.NPC)); - } - huntObjs(hunt) { - return Array.from(new HuntIterator(World_default.currentTick, this.level, this.x, this.z, this.huntrange, hunt.checkVis, hunt.checkObj, hunt.checkCategory, HuntModeType_default.OBJ)); - } - huntLocs(hunt) { - return Array.from(new HuntIterator(World_default.currentTick, this.level, this.x, this.z, this.huntrange, hunt.checkVis, hunt.checkLoc, hunt.checkCategory, HuntModeType_default.SCENERY)); - } - // ---- - playAnimation(anim, delay) { - if (anim >= SeqType.count) { - return; - } - if (anim == -1 || this.animId == -1 || SeqType.get(anim).priority > SeqType.get(this.animId).priority || SeqType.get(this.animId).priority === 0) { - this.animId = anim; - this.animDelay = delay; - this.mask |= _Npc.ANIM; - } - } - spotanim(spotanim, height, delay) { - this.graphicId = spotanim; - this.graphicHeight = height; - this.graphicDelay = delay; - this.mask |= _Npc.SPOTANIM; - } - applyDamage(damage, type) { - this.damageTaken = damage; - this.damageType = type; - const current = this.levels[NpcStat_default.HITPOINTS]; - if (current - damage <= 0) { - this.levels[NpcStat_default.HITPOINTS] = 0; - this.damageTaken = current; - } else { - this.levels[NpcStat_default.HITPOINTS] = current - damage; - } - this.mask |= _Npc.DAMAGE; - } - say(text) { - if (!text) { - return; - } - this.chat = text; - this.mask |= _Npc.SAY; - } - faceSquare(x, z) { - this.faceX = x * 2 + 1; - this.faceZ = z * 2 + 1; - this.orientationX = this.faceX; - this.orientationZ = this.faceZ; - this.mask |= _Npc.FACE_COORD; - } - changeType(type) { - this.type = type; - this.mask |= _Npc.CHANGE_TYPE; - this.uid = type << 16 | this.nid; - const npcType = NpcType.get(type); - this.setTimer(npcType.timer); - } -}; - -// src/lostcity/engine/GameMap.ts -var GameMap = class _GameMap { - static OPEN = 0; - static BLOCKED = 1; - static BRIDGE = 2; - static ROOF = 4; - static WALL = 8; - static LOWMEMORY = 16; - static Y = 4; - static X = 64; - static Z = 64; - static MAPSQUARE = _GameMap.X * _GameMap.Y * _GameMap.Z; - init(zoneMap) { - console.time("Loading game map"); - const path4 = "data/pack/server/maps/"; - const maps2 = fs26.readdirSync(path4).filter((x) => x[0] === "m"); - for (let index = 0; index < maps2.length; index++) { - const [mx, mz] = maps2[index].substring(1).split("_").map(Number); - const mapsquareX = mx << 6; - const mapsquareZ = mz << 6; - this.decodeNpcs(Packet.load(`${path4}n${mx}_${mz}`), mapsquareX, mapsquareZ); - this.decodeObjs(Packet.load(`${path4}o${mx}_${mz}`), mapsquareX, mapsquareZ, zoneMap); - const lands = new Int8Array(_GameMap.MAPSQUARE); - this.decodeLands(lands, Packet.load(`${path4}m${mx}_${mz}`), mapsquareX, mapsquareZ); - this.decodeLocs(lands, Packet.load(`${path4}l${mx}_${mz}`), mapsquareX, mapsquareZ, zoneMap); - } - console.timeEnd("Loading game map"); - } - async initAsync(zoneMap) { - console.time("Loading game map"); - const path4 = "data/pack/server/maps/"; - const { serverMaps: serverMaps2 } = await Promise.resolve().then(() => (init_PreloadedDirs(), PreloadedDirs_exports)); - const maps2 = serverMaps2.map(async (map) => { - const [mx, mz] = map.substring(1).split("_").map(Number); - const mapsquareX = mx << 6; - const mapsquareZ = mz << 6; - const [npcData, objData, landData, locData] = await Promise.all([ - await Packet.loadAsync(`${path4}n${mx}_${mz}`), - await Packet.loadAsync(`${path4}o${mx}_${mz}`), - await Packet.loadAsync(`${path4}m${mx}_${mz}`), - await Packet.loadAsync(`${path4}l${mx}_${mz}`) - ]); - this.decodeNpcs(npcData, mapsquareX, mapsquareZ); - this.decodeObjs(objData, mapsquareX, mapsquareZ, zoneMap); - const lands = new Int8Array(_GameMap.MAPSQUARE); - this.decodeLands(lands, landData, mapsquareX, mapsquareZ); - this.decodeLocs(lands, locData, mapsquareX, mapsquareZ, zoneMap); - }); - console.timeEnd("Loading game map"); - } - /** - * Change collision at a specified Position for lands/floors. - * @param x The x pos. - * @param z The z pos. - * @param level The level pos. - * @param add True if adding this collision. False if removing. - */ - changeLandCollision(x, z, level, add) { - changeFloor(x, z, level, add); - } - /** - * Change collision at a specified Position for locs. - * @param shape The shape of the loc to change. - * @param angle The angle of the loc to change. - * @param blockrange If this loc blocks range. - * @param length The length of this loc. - * @param width The width of this loc. - * @param active If this loc is active. - * @param x The x pos. - * @param z The z pos. - * @param level The level pos. - * @param add True if adding this collision. False if removing. - */ - changeLocCollision(shape, angle, blockrange, length, width, active, x, z, level, add) { - const locLayer = locShapeLayer(shape); - if (locLayer === LocLayer.WALL) { - changeWall(x, z, level, angle, shape, blockrange, false, add); - } else if (locLayer === LocLayer.GROUND) { - if (angle === LocAngle.NORTH || angle === LocAngle.SOUTH) { - changeLoc(x, z, level, length, width, blockrange, false, add); - } else { - changeLoc(x, z, level, width, length, blockrange, false, add); - } - } else if (locLayer === LocLayer.GROUND_DECOR) { - if (active === 1) { - changeFloor(x, z, level, add); - } - } - } - /** - * Change collision at a specified Position for npcs. - * @param size The size square of this npc. (1x1, 2x2, etc). - * @param x The x pos. - * @param z The z pos. - * @param level The level pos. - * @param add True if adding this collision. False if removing. - */ - changeNpcCollision(size, x, z, level, add) { - changeNpc(x, z, level, size, add); - } - /** - * Change collision at a specified Position for players. - * @param size The size square of this npc. (1x1, 2x2, etc). - * @param x The x pos. - * @param z The z pos. - * @param level The level pos. - * @param add True if adding this collision. False if removing. - */ - changePlayerCollision(size, x, z, level, add) { - changePlayer(x, z, level, size, add); - } - /** - * Change collision at a specified Position for roofs. - * @param x The x pos. - * @param z The z pos. - * @param level The level pos. - * @param add True if adding this collision. False if removing. - */ - changeRoofCollision(x, z, level, add) { - changeRoof(x, z, level, add); - } - decodeNpcs(packet, mapsquareX, mapsquareZ) { - while (packet.available > 0) { - const { x, z, level } = this.unpackCoord(packet.g2()); - const absoluteX = mapsquareX + x; - const absoluteZ = mapsquareZ + z; - const count = packet.g1(); - for (let index = 0; index < count; index++) { - const npcType = NpcType.get(packet.g2()); - const size = npcType.size; - const npc = new Npc(level, absoluteX, absoluteZ, size, size, EntityLifeCycle_default.RESPAWN, World_default.getNextNid(), npcType.id, npcType.moverestrict, npcType.blockwalk); - if (npcType.members && Environment_default.NODE_MEMBERS || !npcType.members) { - World_default.addNpc(npc, -1); - } - } - } - } - decodeObjs(packet, mapsquareX, mapsquareZ, zoneMap) { - while (packet.available > 0) { - const { x, z, level } = this.unpackCoord(packet.g2()); - const absoluteX = mapsquareX + x; - const absoluteZ = mapsquareZ + z; - const count = packet.g1(); - for (let j = 0; j < count; j++) { - const objType = ObjType.get(packet.g2()); - const obj = new Obj(level, absoluteX, absoluteZ, EntityLifeCycle_default.RESPAWN, objType.id, packet.g1()); - if (objType.members && Environment_default.NODE_MEMBERS || !objType.members) { - zoneMap.zone(obj.x, obj.z, obj.level).addStaticObj(obj); - } - } - } - } - decodeLands(lands, packet, mapsquareX, mapsquareZ) { - for (let level = 0; level < _GameMap.Y; level++) { - for (let x = 0; x < _GameMap.X; x++) { - for (let z = 0; z < _GameMap.Z; z++) { - while (true) { - const opcode = packet.g1(); - if (opcode === 0) { - break; - } else if (opcode === 1) { - packet.pos++; - break; - } - if (opcode <= 49) { - packet.pos++; - } else if (opcode <= 81) { - lands[this.packCoord(x, z, level)] = opcode - 49; - } - } - } - } - } - for (let level = 0; level < _GameMap.Y; level++) { - for (let x = 0; x < _GameMap.X; x++) { - const absoluteX = x + mapsquareX; - for (let z = 0; z < _GameMap.Z; z++) { - const absoluteZ = z + mapsquareZ; - if (x % 7 === 0 && z % 7 === 0) { - allocateIfAbsent(absoluteX, absoluteZ, level); - } - const land = lands[this.packCoord(x, z, level)]; - if ((land & _GameMap.ROOF) !== _GameMap.OPEN) { - this.changeRoofCollision(absoluteX, absoluteZ, level, true); - } - if ((land & _GameMap.BLOCKED) !== _GameMap.BLOCKED) { - continue; - } - const bridged = (level === 1 ? land & _GameMap.BRIDGE : lands[this.packCoord(x, z, 1)] & _GameMap.BRIDGE) === _GameMap.BRIDGE; - const actualLevel = bridged ? level - 1 : level; - if (actualLevel < 0) { - continue; - } - this.changeLandCollision(absoluteX, absoluteZ, actualLevel, true); - } - } - } - } - decodeLocs(lands, packet, mapsquareX, mapsquareZ, zoneMap) { - let locId = -1; - let locIdOffset = packet.gsmart(); - while (locIdOffset !== 0) { - locId += locIdOffset; - let coord = 0; - let coordOffset = packet.gsmart(); - while (coordOffset !== 0) { - const { x, z, level } = this.unpackCoord(coord += coordOffset - 1); - const info = packet.g1(); - coordOffset = packet.gsmart(); - const bridged = (level === 1 ? lands[coord] & _GameMap.BRIDGE : lands[this.packCoord(x, z, 1)] & _GameMap.BRIDGE) === _GameMap.BRIDGE; - const actualLevel = bridged ? level - 1 : level; - if (actualLevel < 0) { - continue; - } - const type = LocType.get(locId); - const width = type.width; - const length = type.length; - const shape = info >> 2; - const angle = info & 3; - const absoluteX = x + mapsquareX; - const absoluteZ = z + mapsquareZ; - zoneMap.zone(absoluteX, absoluteZ, actualLevel).addStaticLoc(new Loc(actualLevel, absoluteX, absoluteZ, width, length, EntityLifeCycle_default.RESPAWN, locId, shape, angle)); - if (type.blockwalk) { - this.changeLocCollision(shape, angle, type.blockrange, length, width, type.active, absoluteX, absoluteZ, actualLevel, true); - } - } - locIdOffset = packet.gsmart(); - } - } - packCoord(x, z, level) { - return z & 63 | (x & 63) << 6 | (level & 3) << 12; - } - unpackCoord(packed) { - const z = packed & 63; - const x = packed >> 6 & 63; - const level = packed >> 12 & 3; - return { x, z, level }; - } -}; - -// src/lostcity/engine/Login.ts - -// src/jagex2/io/Isaac.ts -var Isaac = class { - count = 0; - rsl = new Int32Array(256); - mem = new Int32Array(256); - a = 0; - b = 0; - c = 0; - constructor(seed = [0, 0, 0, 0]) { - for (let i = 0; i < seed.length; i++) { - this.rsl[i] = seed[i]; - } - this.init(); - } - // prettier-ignore - init() { - let a = 2654435769, b = 2654435769, c = 2654435769, d = 2654435769, e = 2654435769, f = 2654435769, g = 2654435769, h = 2654435769; - for (let i = 0; i < 4; i++) { - a ^= b << 11; - d += a; - b += c; - b ^= c >>> 2; - e += b; - c += d; - c ^= d << 8; - f += c; - d += e; - d ^= e >>> 16; - g += d; - e += f; - e ^= f << 10; - h += e; - f += g; - f ^= g >>> 4; - a += f; - g += h; - g ^= h << 8; - b += g; - h += a; - h ^= a >>> 9; - c += h; - a += b; - } - for (let i = 0; i < 256; i += 8) { - a += this.rsl[i]; - b += this.rsl[i + 1]; - c += this.rsl[i + 2]; - d += this.rsl[i + 3]; - e += this.rsl[i + 4]; - f += this.rsl[i + 5]; - g += this.rsl[i + 6]; - h += this.rsl[i + 7]; - a ^= b << 11; - d += a; - b += c; - b ^= c >>> 2; - e += b; - c += d; - c ^= d << 8; - f += c; - d += e; - d ^= e >>> 16; - g += d; - e += f; - e ^= f << 10; - h += e; - f += g; - f ^= g >>> 4; - a += f; - g += h; - g ^= h << 8; - b += g; - h += a; - h ^= a >>> 9; - c += h; - a += b; - this.mem[i] = a; - this.mem[i + 1] = b; - this.mem[i + 2] = c; - this.mem[i + 3] = d; - this.mem[i + 4] = e; - this.mem[i + 5] = f; - this.mem[i + 6] = g; - this.mem[i + 7] = h; - } - for (let i = 0; i < 256; i += 8) { - a += this.mem[i]; - b += this.mem[i + 1]; - c += this.mem[i + 2]; - d += this.mem[i + 3]; - e += this.mem[i + 4]; - f += this.mem[i + 5]; - g += this.mem[i + 6]; - h += this.mem[i + 7]; - a ^= b << 11; - d += a; - b += c; - b ^= c >>> 2; - e += b; - c += d; - c ^= d << 8; - f += c; - d += e; - d ^= e >>> 16; - g += d; - e += f; - e ^= f << 10; - h += e; - f += g; - f ^= g >>> 4; - a += f; - g += h; - g ^= h << 8; - b += g; - h += a; - h ^= a >>> 9; - c += h; - a += b; - this.mem[i] = a; - this.mem[i + 1] = b; - this.mem[i + 2] = c; - this.mem[i + 3] = d; - this.mem[i + 4] = e; - this.mem[i + 5] = f; - this.mem[i + 6] = g; - this.mem[i + 7] = h; - } - this.isaac(); - this.count = 256; - } - isaac() { - this.c++; - this.b += this.c; - for (let i = 0; i < 256; i++) { - const x = this.mem[i]; - switch (i & 3) { - case 0: - this.a ^= this.a << 13; - break; - case 1: - this.a ^= this.a >>> 6; - break; - case 2: - this.a ^= this.a << 2; - break; - case 3: - this.a ^= this.a >>> 16; - break; - } - this.a += this.mem[i + 128 & 255]; - let y; - this.mem[i] = y = this.mem[x >>> 2 & 255] + this.a + this.b; - this.rsl[i] = this.b = this.mem[y >>> 8 >>> 2 & 255] + x; - } - } - nextInt() { - if (this.count-- === 0) { - this.isaac(); - this.count = 255; - } - return this.rsl[this.count]; - } -}; - -// src/lostcity/util/WorkerFactory.ts -function createWorker(fileName) { - if (typeof self === "undefined") { - return new NodeWorker(fileName); - } else { - return new Worker(fileName, { type: "module" }); - } -} - -// src/lostcity/server/LoginServer.ts -var LoginResponse = class { - static SUCCESSFUL = Uint8Array.from([2]); - static INVALID_USER_OR_PASS = Uint8Array.from([3]); - // Invalid username or password. - static ACCOUNT_DISABLED = Uint8Array.from([4]); - // Your account has been disabled. - static LOGGED_IN = Uint8Array.from([5]); - // Your account is already logged in. - static SERVER_UPDATED = Uint8Array.from([6]); - // RuneScape has been updated! - static WORLD_FULL = Uint8Array.from([7]); - // This world is full. - static LOGIN_SERVER_OFFLINE = Uint8Array.from([8]); - // Unable to connect. - static LOGIN_LIMIT_EXCEEDED = Uint8Array.from([9]); - // Login limit exceeded. - static UNABLE_TO_CONNECT = Uint8Array.from([10]); - // Unable to connect. - static LOGIN_REJECTED = Uint8Array.from([11]); - // Login server rejected session. - static NEED_MEMBERS_ACCOUNT = Uint8Array.from([12]); - // You need a members account to login to this world. - static COULD_NOT_COMPLETE = Uint8Array.from([13]); - // Could not complete login. - static SERVER_UPDATING = Uint8Array.from([14]); - // The server is being updated. - static RECONNECTING = Uint8Array.from([15]); - static LOGIN_ATTEMPTS_EXCEEDED = Uint8Array.from([16]); - // Login attempts exceeded. - static STANDING_IN_MEMBERS = Uint8Array.from([17]); - // You are standing in a members-only area. - static STAFF_MOD_LEVEL = Uint8Array.from([18]); -}; - -// src/lostcity/server/CrcTable.ts -var CrcBuffer = new Packet(new Uint8Array(4 * 9)); -var CrcTable = []; -var CrcBuffer32 = 0; -function makeCrc(path4) { - if (!fs28.existsSync(path4)) { - return; - } - const packet = Packet.load(path4); - const crc = Packet.getcrc(packet.data, 0, packet.data.length); - CrcTable.push(crc); - CrcBuffer.p4(crc); -} -function makeCrcs() { - CrcTable = []; - CrcBuffer.pos = 0; - CrcBuffer.p4(0); - makeCrc("data/pack/client/title"); - makeCrc("data/pack/client/config"); - makeCrc("data/pack/client/interface"); - makeCrc("data/pack/client/media"); - makeCrc("data/pack/client/models"); - makeCrc("data/pack/client/textures"); - makeCrc("data/pack/client/wordenc"); - makeCrc("data/pack/client/sounds"); - CrcBuffer32 = Packet.getcrc(CrcBuffer.data, 0, CrcBuffer.data.length); -} -async function makeCrcAsync(path4) { - const file = await fetch(path4); - if (!file.ok) { - return; - } - const packet = new Packet(new Uint8Array(await file.arrayBuffer())); - const crc = Packet.getcrc(packet.data, 0, packet.data.length); - return crc; -} -async function makeCrcsAsync() { - CrcTable = []; - CrcBuffer.pos = 0; - CrcBuffer.p4(0); - const [title, config, iface, media, models, textures, wordenc, sounds] = await Promise.all([ - makeCrcAsync("data/pack/client/title"), - makeCrcAsync("data/pack/client/config"), - makeCrcAsync("data/pack/client/interface"), - makeCrcAsync("data/pack/client/media"), - makeCrcAsync("data/pack/client/models"), - makeCrcAsync("data/pack/client/textures"), - makeCrcAsync("data/pack/client/wordenc"), - makeCrcAsync("data/pack/client/sounds") - ]); - for (const crc of [title, config, iface, media, models, textures, wordenc, sounds]) { - if (crc) { - CrcTable.push(crc); - CrcBuffer.p4(crc); - } - } - CrcBuffer32 = Packet.getcrc(CrcBuffer.data, 0, CrcBuffer.data.length); -} -if (typeof self === "undefined") { - if (fs28.existsSync("data/pack/client/")) { - makeCrcs(); - } -} - -// src/lostcity/engine/Login.ts -var Login = class { - loginThread = createWorker(typeof self === "undefined" ? "./src/lostcity/server/LoginThread.ts" : "LoginThread.js"); - loginRequests = /* @__PURE__ */ new Map(); - logoutRequests = /* @__PURE__ */ new Set(); - constructor() { - try { - if (typeof self === "undefined") { - if (this.loginThread instanceof NodeWorker2) { - this.loginThread.on("message", (msg) => { - this.onMessage(msg); - }); - } - } else { - if (this.loginThread instanceof Worker) { - this.loginThread.onmessage = (msg) => { - this.onMessage(msg.data); - }; - } - } - } catch (err) { - console.error("Login Thread:", err); - } - } - async readIn(socket, data) { - const opcode = data.g1(); - if (opcode === 16) { - const length = data.g1(); - if (data.available < length) { - socket.terminate(); - return; - } - const post = new Uint8Array(length); - data.gdata(post, 0, post.length); - data.pos -= post.length; - const revision = data.g1(); - if (revision !== 225) { - socket.writeImmediate(LoginResponse.SERVER_UPDATED); - socket.close(); - return; - } - data.pos += 1; - const crcs = new Uint8Array(9 * 4); - data.gdata(crcs, 0, crcs.length); - if (!Packet.checkcrc(crcs, 0, crcs.length, CrcBuffer32)) { - socket.writeImmediate(LoginResponse.SERVER_UPDATED); - socket.close(); - return; - } - this.loginThread.postMessage({ - type: "loginreq", - opcode, - data: post, - socket: socket.uniqueId - }); - this.loginRequests.set(socket.uniqueId, socket); - } else { - socket.terminate(); - } - } - logout(player) { - if (this.logoutRequests.has(player.username37)) { - return; - } - const save = player.save(); - this.loginThread.postMessage({ - type: "logout", - username: player.username, - save: save.data.subarray(0, save.pos) - }); - save.release(); - } - onMessage(msg) { - switch (msg.type) { - case "loginreply": { - const { status, socket } = msg; - const client = this.loginRequests.get(socket); - if (!client) { - return; - } - this.loginRequests.delete(socket); - if (status[0] !== 2) { - client.writeImmediate(status); - client.close(); - return; - } - const { info, seed, username, save } = msg; - if (World_default.getTotalPlayers() >= 2e3) { - client.writeImmediate(LoginResponse.WORLD_FULL); - client.close(); - return; - } - if (World_default.shutdownTick > -1 && World_default.currentTick - World_default.shutdownTick > 0) { - client.writeImmediate(LoginResponse.SERVER_UPDATING); - client.close(); - return; - } - if (!Environment_default.LOGIN_KEY) { - for (const player2 of World_default.players) { - if (player2.username === username) { - client.writeImmediate(LoginResponse.LOGGED_IN); - client.close(); - return; - } - } - } - client.decryptor = new Isaac(seed); - for (let i = 0; i < 4; i++) { - seed[i] += 50; - } - client.encryptor = new Isaac(seed); - const player = PlayerLoading.load(username, new Packet(save), client); - player.lowMemory = (info & 1) !== 0; - player.webClient = client.isWebSocket(); - World_default.addPlayer(player); - break; - } - case "logoutreply": { - const { username } = msg; - const player = World_default.getPlayerByUsername(username); - if (player) { - World_default.getZone(player.x, player.z, player.level).leave(player); - World_default.players.remove(player.pid); - player.pid = -1; - player.terminate(); - this.logoutRequests.delete(player.username37); - } - break; - } - default: - throw new Error("Unknown message type: " + msg.type); - } - } -}; -var Login_default = new Login(); - -// src/lostcity/entity/EntityList.ts -var EntityList = class extends Array { - // constructor - free; - indexPadding; - ids; - // runtime - lastUsedIndex = 0; - constructor(size, indexPadding) { - super(size); - this.ids = new Int32Array(size).fill(-1); - this.free = new Set(Array.from({ length: size }, (_, index) => index)); - this.indexPadding = indexPadding; - } - next(_ = false, start = this.lastUsedIndex + 1) { - const length = this.ids.length; - for (let index = start; index < length; index++) { - if (this.ids[index] === -1) { - return index; - } - } - for (let index = this.indexPadding; index < start; index++) { - if (this.ids[index] === -1) { - return index; - } - } - throw new Error("[EntityList] no space for new entities"); - } - *[Symbol.iterator]() { - for (const index of this.ids) { - if (index === -1) { - continue; - } - const entity = this[index]; - if (typeof entity === "undefined") { - continue; - } - yield entity; - } - } - get count() { - let count = 0; - for (const _ of this[Symbol.iterator]()) { - count++; - } - return count; - } - get(id) { - const index = this.ids[id]; - return index !== -1 ? this[index] : void 0; - } - set(id, entity) { - if (!this.free.size) { - throw new Error("[EntityList] cannot find available entities slot."); - } - const index = this.free.values().next().value; - this.free.delete(index); - this.ids[id] = index; - this[index] = entity; - this.lastUsedIndex = id; - } - remove(id) { - const index = this.ids[id]; - if (index !== -1) { - this.ids[id] = -1; - this.free.add(index); - } - } - reset() { - this.length = 0; - this.ids.fill(-1); - this.free.clear(); - for (let i = 0; i < this.ids.length; i++) { - this.free.add(i); - } - } -}; -var NpcList = class extends EntityList { - constructor(size) { - super(size, 0); - } -}; -var PlayerList = class extends EntityList { - constructor(size) { - super(size, 1); - } - next(priority = false, start = this.lastUsedIndex + 1) { - if (priority) { - const init = start === 0 ? 1 : 0; - for (let i = init; i < 100; i++) { - const index = start + i; - const id = this.ids[index]; - if (id === -1) { - return index; - } - } - } - return super.next(); - } -}; - -// src/lostcity/engine/World.ts -var World = class _World { - static PLAYERS = 2048; - static NPCS = 8192; - static NORMAL_TICKRATE = 600; - static SHUTDOWN_TICKRATE = 1; - static LOGIN_PINGRATE = 100; - static INV_STOCKRATE = 100; - static AFK_EVENTRATE = 500; - static PLAYER_SAVERATE = 1500; - static SHUTDOWN_TICKS = 24e3; - static TIMEOUT_IDLE_TICKS = 75; - static TIMEOUT_LOGOUT_TICKS = 100; - gameMap; - zoneMap; - invs; - // shared inventories (shops) - // entities - newPlayers; - // players joining at the end of this tick - players; - npcs; - // zones - zonesTracking; - queue; - // debug data - lastCycleStats; - cycleStats; - tickRate = _World.NORMAL_TICKRATE; - // speeds up when we're processing server shutdown - currentTick = 0; - shutdownTick = -1; - // packed data timestamps - allLastModified = 0; - datLastModified = /* @__PURE__ */ new Map(); - vars = new Int32Array(); - // var shared - varsString = []; - devWatcher = null; - devThread = null; - devRebuilding = false; - devMTime = /* @__PURE__ */ new Map(); - constructor() { - this.gameMap = new GameMap(); - this.zoneMap = new ZoneMap(); - this.invs = /* @__PURE__ */ new Set(); - this.newPlayers = /* @__PURE__ */ new Set(); - this.players = new PlayerList(_World.PLAYERS - 1); - this.npcs = new NpcList(_World.NPCS - 1); - this.zonesTracking = /* @__PURE__ */ new Map(); - this.queue = new LinkList(); - this.lastCycleStats = new Array(12).fill(0); - this.cycleStats = new Array(12).fill(0); - } - // ---- - shouldReload(type, client = false) { - if (typeof self !== "undefined") { - return true; - } - const current = Math.max(getModified(`data/pack/server/${type}.dat`), client ? getModified("data/pack/client/config") : 0); - if (!this.datLastModified.has(type)) { - this.datLastModified.set(type, current); - return true; - } - const changed = this.datLastModified.get(type) !== current; - if (changed) { - this.datLastModified.set(type, current); - } - return changed; - } - reload() { - let transmitted = false; - if (this.shouldReload("varp", true)) { - VarPlayerType.load("data/pack"); - transmitted = true; - } - if (this.shouldReload("param")) { - ParamType.load("data/pack"); - } - if (this.shouldReload("obj", true)) { - ObjType.load("data/pack"); - transmitted = true; - } - if (this.shouldReload("loc", true)) { - LocType.load("data/pack"); - transmitted = true; - } - if (this.shouldReload("npc", true)) { - NpcType.load("data/pack"); - transmitted = true; - } - if (this.shouldReload("idk", true)) { - IdkType.load("data/pack"); - transmitted = true; - } - if (this.shouldReload("frame_del")) { - SeqFrame.load("data/pack"); - } - if (this.shouldReload("seq", true)) { - SeqType.load("data/pack"); - transmitted = true; - } - if (this.shouldReload("spotanim", true)) { - SpotanimType.load("data/pack"); - transmitted = true; - } - if (this.shouldReload("category")) { - CategoryType.load("data/pack"); - } - if (this.shouldReload("enum")) { - EnumType.load("data/pack"); - } - if (this.shouldReload("struct")) { - StructType.load("data/pack"); - } - if (this.shouldReload("inv")) { - InvType.load("data/pack"); - this.invs.clear(); - for (let i = 0; i < InvType.count; i++) { - const inv = InvType.get(i); - if (inv && inv.scope === InvType.SCOPE_SHARED) { - this.invs.add(Inventory.fromType(i)); - } - } - } - if (this.shouldReload("mesanim")) { - MesanimType.load("data/pack"); - } - if (this.shouldReload("dbtable")) { - DbTableType.load("data/pack"); - } - if (this.shouldReload("dbrow")) { - DbRowType.load("data/pack"); - } - if (this.shouldReload("hunt")) { - HuntType.load("data/pack"); - } - if (this.shouldReload("varn")) { - VarNpcType.load("data/pack"); - } - if (this.shouldReload("vars")) { - VarSharedType.load("data/pack"); - if (this.vars.length !== VarSharedType.count) { - const old = this.vars; - this.vars = new Int32Array(VarSharedType.count); - for (let i = 0; i < VarSharedType.count && i < old.length; i++) { - this.vars[i] = old[i]; - } - const oldString = this.varsString; - this.varsString = new Array(VarSharedType.count); - for (let i = 0; i < VarSharedType.count && i < old.length; i++) { - this.varsString[i] = oldString[i]; - } - } - } - if (this.shouldReload("interface")) { - Component.load("data/pack"); - transmitted = true; - } - if (this.shouldReload("script")) { - const count = ScriptProvider.load("data/pack"); - if (count === -1) { - this.broadcastMes("There was an issue while reloading scripts."); - } else { - this.broadcastMes(`Reloaded ${count} scripts.`); - } - } - makeCrcs(); - preloadClient(); - this.allLastModified = getLatestModified("data/pack", ".dat"); - } - async loadAsync() { - console.time("Loading packs"); - const count = (await Promise.all([ - NpcType.loadAsync("data/pack"), - ObjType.loadAsync("data/pack"), - LocType.loadAsync("data/pack"), - FontType.loadAsync("data/pack"), - WordEnc.loadAsync("data/pack"), - VarPlayerType.loadAsync("data/pack"), - ParamType.loadAsync("data/pack"), - IdkType.loadAsync("data/pack"), - SeqFrame.loadAsync("data/pack"), - SeqType.loadAsync("data/pack"), - SpotanimType.loadAsync("data/pack"), - CategoryType.loadAsync("data/pack"), - EnumType.loadAsync("data/pack"), - StructType.loadAsync("data/pack"), - InvType.loadAsync("data/pack"), - MesanimType.loadAsync("data/pack"), - DbTableType.loadAsync("data/pack"), - DbRowType.loadAsync("data/pack"), - HuntType.loadAsync("data/pack"), - VarNpcType.loadAsync("data/pack"), - VarSharedType.loadAsync("data/pack"), - Component.loadAsync("data/pack"), - makeCrcsAsync(), - preloadClientAsync(), - ScriptProvider.loadAsync("data/pack") - ])).at(-1); - this.invs.clear(); - for (let i = 0; i < InvType.count; i++) { - const inv = InvType.get(i); - if (inv && inv.scope === InvType.SCOPE_SHARED) { - this.invs.add(Inventory.fromType(i)); - } - } - if (this.vars.length !== VarSharedType.count) { - const old = this.vars; - this.vars = new Int32Array(VarSharedType.count); - for (let i = 0; i < VarSharedType.count && i < old.length; i++) { - this.vars[i] = old[i]; - } - const oldString = this.varsString; - this.varsString = new Array(VarSharedType.count); - for (let i = 0; i < VarSharedType.count && i < old.length; i++) { - this.varsString[i] = oldString[i]; - } - } - if (count === -1) { - this.broadcastMes("There was an issue while reloading scripts."); - } else { - this.broadcastMes(`Reloaded ${count} scripts.`); - } - console.timeEnd("Loading packs"); - } - broadcastMes(message) { - for (const player of this.players) { - player.messageGame(message); - } - } - async start(skipMaps = false, startCycle = true) { - console.log("Starting world..."); - if (typeof self === "undefined") { - FontType.load("data/pack"); - WordEnc.load("data/pack"); - this.reload(); - if (!skipMaps) { - this.gameMap.init(this.zoneMap); - } - } else { - console.time("World ready"); - await this.loadAsync(); - if (!skipMaps) { - await this.gameMap.initAsync(this.zoneMap); - } - console.timeEnd("World ready"); - } - Login_default.loginThread.postMessage({ - type: "reset" - }); - if (typeof self === "undefined") { - if (!Environment_default.NODE_PRODUCTION) { - this.startDevWatcher(); - if (Environment_default.BUILD_STARTUP && (shouldBuildFileAny("data/pack/client", "data/pack/client/lastbuild.pack") || shouldBuildFileAny("data/pack/server", "data/pack/server/lastbuild.pack"))) { - this.devThread.postMessage({ - type: "pack" - }); - } - } - if (Environment_default.WEB_PORT === 80) { - console.log(kleur.green().bold("World ready") + kleur.white().bold(": http://localhost")); - } else { - console.log(kleur.green().bold("World ready") + kleur.white().bold(": http://localhost:" + Environment_default.WEB_PORT)); - } - } - if (startCycle) { - await this.cycle(); - } - } - startDevWatcher() { - this.devThread = createWorker("./src/lostcity/server/DevThread.ts"); - this.devThread.on("message", (msg) => { - if (msg.type === "done") { - this.devRebuilding = false; - this.reload(); - } - }); - this.devThread.on("exit", () => { - this.devRebuilding = false; - this.stopDevWatcher(); - if (this.shutdownTick === -1) { - this.broadcastMes("Error while rebuilding - see console for more info."); - this.startDevWatcher(); - } - }); - this.devWatcher = new Watcher("./data/src", { - recursive: true - }); - this.devWatcher.on("add", (targetPath) => { - if (targetPath.endsWith(".pack")) { - return; - } - const stat = fs29.statSync(targetPath); - this.devMTime.set(targetPath, stat.mtimeMs); - }); - this.devWatcher.on("change", (targetPath) => { - if (targetPath.endsWith(".pack")) { - return; - } - const stat = fs29.statSync(targetPath); - const known = this.devMTime.get(targetPath); - if (known && known >= stat.mtimeMs) { - return; - } - this.devMTime.set(targetPath, stat.mtimeMs); - if (this.devRebuilding) { - return; - } - console.log("dev:", path3.basename(targetPath), "was edited"); - this.devRebuilding = true; - this.broadcastMes("Rebuilding, please wait..."); - if (!this.devThread) { - this.devThread = createWorker("./src/lostcity/server/DevThread.ts"); - } - this.devThread.postMessage({ - type: "pack" - }); - }); - } - stopDevWatcher() { - if (this.devWatcher) { - this.devWatcher.close(); - } - if (this.devThread) { - this.devThread.terminate(); - this.devThread = null; - } - } - rebootTimer(duration) { - this.shutdownTick = this.currentTick + duration; - this.stopDevWatcher(); - for (const player of this.players) { - player.write(new UpdateRebootTimer(this.shutdownTick - this.currentTick)); - } - } - async cycle(continueCycle = true) { - const start = Date.now(); - this.processWorld(); - await this.processClientsIn(); - this.processNpcs(); - await this.processPlayers(); - await this.processLogouts(); - await this.processLogins(); - this.processZones(); - this.processMovementDirections(); - await this.processClientsOut(); - this.processCleanup(); - const tick = this.currentTick; - if (tick % _World.LOGIN_PINGRATE === 0) { - this.heartbeat(); - } - if (this.shutdownTick > -1 && tick >= this.shutdownTick) { - await this.processShutdown(); - } - if (tick % _World.PLAYER_SAVERATE === 0 && tick > 0) { - this.savePlayers(); - } - this.currentTick++; - this.cycleStats[WorldStat_default.CYCLE] = Date.now() - start; - this.lastCycleStats[WorldStat_default.CYCLE] = this.cycleStats[WorldStat_default.CYCLE]; - this.lastCycleStats[WorldStat_default.WORLD] = this.cycleStats[WorldStat_default.WORLD]; - this.lastCycleStats[WorldStat_default.CLIENT_IN] = this.cycleStats[WorldStat_default.CLIENT_IN]; - this.lastCycleStats[WorldStat_default.NPC] = this.cycleStats[WorldStat_default.NPC]; - this.lastCycleStats[WorldStat_default.PLAYER] = this.cycleStats[WorldStat_default.PLAYER]; - this.lastCycleStats[WorldStat_default.LOGOUT] = this.cycleStats[WorldStat_default.LOGOUT]; - this.lastCycleStats[WorldStat_default.LOGIN] = this.cycleStats[WorldStat_default.LOGIN]; - this.lastCycleStats[WorldStat_default.ZONE] = this.cycleStats[WorldStat_default.ZONE]; - this.lastCycleStats[WorldStat_default.CLIENT_OUT] = this.cycleStats[WorldStat_default.CLIENT_OUT]; - this.lastCycleStats[WorldStat_default.CLEANUP] = this.cycleStats[WorldStat_default.CLEANUP]; - this.lastCycleStats[WorldStat_default.BANDWIDTH_IN] = this.cycleStats[WorldStat_default.BANDWIDTH_IN]; - this.lastCycleStats[WorldStat_default.BANDWIDTH_OUT] = this.cycleStats[WorldStat_default.BANDWIDTH_OUT]; - if (continueCycle) { - setTimeout(this.cycle.bind(this), this.tickRate - this.cycleStats[WorldStat_default.CYCLE]); - } - if (Environment_default.NODE_DEBUG_PROFILE) { - console.log(`tick ${this.currentTick} took ${this.cycleStats[WorldStat_default.CYCLE]}ms: ${this.getTotalPlayers()} players`); - console.log(`${this.cycleStats[WorldStat_default.WORLD]} ms world | ${this.cycleStats[WorldStat_default.CLIENT_IN]} ms client in | ${this.cycleStats[WorldStat_default.NPC]} ms npcs | ${this.cycleStats[WorldStat_default.PLAYER]} ms players | ${this.cycleStats[WorldStat_default.LOGOUT]} ms logout | ${this.cycleStats[WorldStat_default.LOGIN]} ms login | ${this.cycleStats[WorldStat_default.ZONE]} ms zones | ${this.cycleStats[WorldStat_default.CLIENT_OUT]} ms client out | ${this.cycleStats[WorldStat_default.CLEANUP]} ms cleanup`); - console.log("----"); - } - } - // - world queue - // - calculate afk event readiness - // - npc spawn scripts - // - npc hunt - processWorld() { - const start = Date.now(); - const tick = this.currentTick; - for (let request = this.queue.head(); request; request = this.queue.next()) { - const delay = request.delay--; - if (delay > 0) { - continue; - } - const script = request.script; - try { - const state = ScriptRunner.execute(script); - request.unlink(); - if (state === ScriptState.SUSPENDED) { - script.activePlayer.activeScript = script; - } else if (state === ScriptState.NPC_SUSPENDED) { - script.activeNpc.activeScript = script; - } else if (state === ScriptState.WORLD_SUSPENDED) { - this.enqueueScript(script, script.popInt()); - } - } catch (err) { - console.error(err); - } - } - if (tick % _World.AFK_EVENTRATE === 0) { - for (const player of this.players) { - player.afkEventReady = Math.random() < (player.zonesAfk() ? 0.1666 : 0.0833); - } - } - for (const npc of this.npcs) { - if (!npc.updateLifeCycle(tick)) { - continue; - } - if (npc.lifecycle === EntityLifeCycle_default.RESPAWN) { - this.addNpc(npc, -1); - } else if (npc.lifecycle === EntityLifeCycle_default.DESPAWN) { - this.removeNpc(npc, -1); - } - } - for (const npc of this.npcs) { - if (!npc.checkLifeCycle(tick) || npc.delayed()) { - continue; - } - if (npc.huntMode !== -1) { - npc.huntAll(); - } - } - this.cycleStats[WorldStat_default.WORLD] = Date.now() - start; - } - // - decode packets - // - process pathfinding/following - async processClientsIn() { - const start = Date.now(); - this.cycleStats[WorldStat_default.BANDWIDTH_IN] = 0; - for (const player of this.players) { - if (!isNetworkPlayer(player)) { - continue; - } - try { - player.decodeIn(); - } catch (err) { - console.error(err); - await this.removePlayer(player); - } - } - for (const player of this.players) { - if (!isNetworkPlayer(player)) { - continue; - } - if (player.userPath.length > 0 || player.opcalled) { - if (player.delayed()) { - player.unsetMapFlag(); - continue; - } - if ((!player.target || player.target instanceof Loc || player.target instanceof Obj) && player.faceEntity !== -1) { - player.faceEntity = -1; - player.mask |= Player.FACE_ENTITY; - } - if (player.opcalled && (player.userPath.length === 0 || !Environment_default.NODE_CLIENT_ROUTEFINDER)) { - player.pathToTarget(); - continue; - } - player.pathToMoveClick(player.userPath, !Environment_default.NODE_CLIENT_ROUTEFINDER); - } - if (player.target instanceof Player && (player.targetOp === ServerTriggerType_default.APPLAYER3 || player.targetOp === ServerTriggerType_default.OPPLAYER3)) { - if (Position.distanceToSW(player, player.target) <= 25) { - player.pathToPathingTarget(); - } else { - player.clearWaypoints(); - } - } - } - this.cycleStats[WorldStat_default.CLIENT_IN] = Date.now() - start; - } - // - resume suspended script - // - stat regen - // - timer - // - queue - // - movement - // - modes - processNpcs() { - const start = Date.now(); - for (const npc of this.npcs) { - if (!npc.checkLifeCycle(this.currentTick)) { - continue; - } - try { - if (npc.delayed()) { - npc.delay--; - } - if (npc.delayed()) { - continue; - } - if (npc.activeScript && npc.activeScript.execution === ScriptState.NPC_SUSPENDED) { - npc.executeScript(npc.activeScript); - } - if (!npc.checkLifeCycle(this.currentTick)) { - continue; - } - npc.processTimers(); - npc.processQueue(); - npc.processNpcModes(); - npc.validateDistanceWalked(); - } catch (err) { - console.error(err); - this.removeNpc(npc, -1); - } - } - this.cycleStats[WorldStat_default.NPC] = Date.now() - start; - } - // - resume suspended script - // - primary queue - // - weak queue - // - timers - // - soft timers - // - engine queue - // - interactions - // - movement - // - close interface if attempting to logout - async processPlayers() { - const start = Date.now(); - for (const player of this.players) { - try { - player.playtime++; - if (player.delayed()) { - player.delay--; - } - if (player.activeScript && player.activeScript.execution === ScriptState.SUSPENDED && !player.delayed()) { - player.executeScript(player.activeScript, true, true); - } - player.processQueues(); - player.processTimers(0 /* NORMAL */); - player.processTimers(1 /* SOFT */); - player.processEngineQueue(); - player.processInteraction(); - if ((player.mask & Player.EXACT_MOVE) == 0) { - player.validateDistanceWalked(); - } - if (this.shutdownTick < this.currentTick) { - if (Environment_default.NODE_SOCKET_TIMEOUT && this.currentTick - player.lastResponse >= _World.TIMEOUT_IDLE_TICKS) { - player.logoutRequested = true; - } - } - if (player.logoutRequested) { - player.closeModal(); - } - } catch (err) { - console.error(err); - await this.removePlayer(player); - } - } - this.cycleStats[WorldStat_default.PLAYER] = Date.now() - start; - } - async processLogouts() { - const start = Date.now(); - for (const player of this.players) { - if (Environment_default.NODE_SOCKET_TIMEOUT && this.currentTick - player.lastResponse >= _World.TIMEOUT_LOGOUT_TICKS) { - player.queue.clear(); - player.weakQueue.clear(); - player.engineQueue.clear(); - player.clearInteraction(); - player.closeModal(); - player.unsetMapFlag(); - player.logoutRequested = true; - player.setVar(VarPlayerType.LASTCOMBAT, 0); - } - if (!player.logoutRequested) { - continue; - } - if (player.queue.head() === null) { - const script = ScriptProvider.getByTriggerSpecific(ServerTriggerType_default.LOGOUT, -1, -1); - if (!script) { - console.error("LOGOUT TRIGGER IS BROKEN!"); - continue; - } - const state = ScriptRunner.init(script, player); - state.pointerAdd(ScriptPointer_default.ProtectedActivePlayer); - ScriptRunner.execute(state); - const result = state.popInt(); - if (result === 0) { - player.logoutRequested = false; - } - if (player.logoutRequested) { - await this.removePlayer(player); - } - } else { - player.messageGame("[DEBUG]: Waiting for queue to empty before logging out."); - } - } - this.cycleStats[WorldStat_default.LOGOUT] = Date.now() - start; - } - async processLogins() { - const start = Date.now(); - player: for (const player of this.newPlayers) { - for (const other of this.players) { - if (player.username !== other.username) { - continue; - } - if (isNetworkPlayer(player) && player.client) { - player.client.send(LoginResponse.LOGGED_IN); - player.client.close(); - } - continue player; - } - let pid; - try { - pid = this.getNextPid(isNetworkPlayer(player) ? player.client : null); - } catch (e) { - if (isNetworkPlayer(player)) { - player.client?.send(LoginResponse.WORLD_FULL); - player.client?.close(); - } - continue; - } - this.players.set(pid, player); - player.pid = pid; - player.uid = (Number(player.username37 & 0x1fffffn) << 11 | player.pid) >>> 0; - player.tele = true; - this.getZone(player.x, player.z, player.level).enter(player); - player.onLogin(); - if (this.shutdownTick > -1) { - player.write(new UpdateRebootTimer(this.shutdownTick - this.currentTick)); - } - if (isNetworkPlayer(player) && player.client) { - player.client.state = 1; - if (player.staffModLevel >= 2) { - player.client.send(LoginResponse.STAFF_MOD_LEVEL); - } else { - player.client.send(LoginResponse.SUCCESSFUL); - } - } - } - this.newPlayers.clear(); - this.cycleStats[WorldStat_default.LOGIN] = Date.now() - start; - } - // - build list of active zones around players - // - loc/obj despawn/respawn - // - compute shared buffer - processZones() { - const start = Date.now(); - const tick = this.currentTick; - const zones = this.zonesTracking.get(tick); - if (typeof zones !== "undefined") { - for (const zone of zones) { - zone.tick(tick); - } - } - this.computeSharedEvents(); - this.cycleStats[WorldStat_default.ZONE] = Date.now() - start; - } - // - convert player movements - // - convert npc movements - processMovementDirections() { - for (const player of this.players) { - player.convertMovementDir(); - } - for (const npc of this.npcs) { - npc.convertMovementDir(); - } - } - // - map update - // - player info - // - npc info - // - zone updates - // - inv changes - // - stat changes - // - afk zones changes - // - flush packets - async processClientsOut() { - const start = Date.now(); - this.cycleStats[WorldStat_default.BANDWIDTH_OUT] = 0; - for (const player of this.players) { - if (!isNetworkPlayer(player)) { - player.highPriorityOut.clear(); - player.lowPriorityOut.clear(); - continue; - } - try { - player.updateMap(); - player.updatePlayers(); - player.updateNpcs(); - player.updateZones(); - player.updateInvs(); - player.updateStats(); - player.updateAfkZones(); - player.encodeOut(); - } catch (err) { - console.error(err); - await this.removePlayer(player); - } - } - this.cycleStats[WorldStat_default.CLIENT_OUT] = Date.now() - start; - } - // - reset zones - // - reset players - // - reset npcs - // - reset invs - processCleanup() { - const start = Date.now(); - const tick = this.currentTick; - const zones = this.zonesTracking.get(tick); - if (typeof zones !== "undefined") { - for (const zone of zones) { - zone.reset(); - } - } - this.zonesTracking.delete(tick); - for (const player of this.players) { - player.resetEntity(false); - for (const inv of player.invs.values()) { - if (!inv) { - continue; - } - inv.update = false; - } - } - for (const npc of this.npcs) { - if (!npc.checkLifeCycle(tick)) { - continue; - } - npc.resetEntity(false); - } - for (const inv of this.invs) { - inv.update = false; - const invType = InvType.get(inv.type); - if (!invType.restock || !invType.stockcount || !invType.stockrate) { - continue; - } - for (let index = 0; index < inv.items.length; index++) { - const item = inv.items[index]; - if (!item) { - continue; - } - if (item.count < invType.stockcount[index] && tick % invType.stockrate[index] === 0) { - inv.add(item?.id, 1, index, true, false, false); - inv.update = true; - continue; - } - if (item.count > invType.stockcount[index] && tick % invType.stockrate[index] === 0) { - inv.remove(item?.id, 1, index, true); - inv.update = true; - continue; - } - if (invType.allstock && !invType.stockcount[index] && tick % _World.INV_STOCKRATE === 0) { - inv.remove(item?.id, 1, index, true); - inv.update = true; - } - } - } - this.cycleStats[WorldStat_default.CLEANUP] = Date.now() - start; - } - heartbeat() { - const players = []; - for (const player of this.players) { - players.push(player.username37); - } - Login_default.loginThread.postMessage({ - type: "heartbeat", - players - }); - } - async processShutdown() { - const duration = this.currentTick - this.shutdownTick; - const online = this.getTotalPlayers(); - if (online) { - for (const player of this.players) { - player.logoutRequested = true; - if (isNetworkPlayer(player)) { - player.logout(); - if (player.client && duration > 2) { - player.client.close(); - } - } - } - this.npcs.reset(); - if (duration > 2) { - console.log("Super fast shutdown initiated..."); - if (this.tickRate > _World.SHUTDOWN_TICKRATE) { - this.tickRate = _World.SHUTDOWN_TICKRATE; - } - if (duration > _World.SHUTDOWN_TICKS) { - for (const player of this.players) { - await this.removePlayer(player); - } - this.tickRate = _World.NORMAL_TICKRATE; - } - if (!Environment_default.NODE_PRODUCTION) { - process.exit(0); - } - } - } else { - process.exit(0); - } - } - savePlayers() { - if (typeof self !== "undefined") { - return; - } - for (const player of this.players) { - player.save().release(); - } - } - enqueueScript(script, delay = 0) { - this.queue.addTail(new EntityQueueState(script, delay + 1)); - } - getInventory(inv) { - if (inv === -1) { - return null; - } - for (const inventory2 of this.invs) { - if (inventory2.type === inv) { - return inventory2; - } - } - const inventory = Inventory.fromType(inv); - this.invs.add(inventory); - return inventory; - } - getZone(x, z, level) { - return this.zoneMap.zone(x, z, level); - } - getZoneIndex(zoneIndex) { - return this.zoneMap.zoneByIndex(zoneIndex); - } - getZoneGrid(level) { - return this.zoneMap.grid(level); - } - computeSharedEvents() { - const zones = /* @__PURE__ */ new Set(); - for (const player of this.players) { - if (!isNetworkPlayer(player)) { - continue; - } - for (const zone of player.buildArea.loadedZones) { - zones.add(zone); - } - } - for (const zoneIndex of zones) { - this.getZoneIndex(zoneIndex).computeShared(); - } - } - addNpc(npc, duration) { - this.npcs.set(npc.nid, npc); - npc.x = npc.startX; - npc.z = npc.startZ; - const zone = this.getZone(npc.x, npc.z, npc.level); - zone.enter(npc); - switch (npc.blockWalk) { - case BlockWalk_default.NPC: - this.gameMap.changeNpcCollision(npc.width, npc.x, npc.z, npc.level, true); - break; - case BlockWalk_default.ALL: - this.gameMap.changeNpcCollision(npc.width, npc.x, npc.z, npc.level, true); - this.gameMap.changePlayerCollision(npc.width, npc.x, npc.z, npc.level, true); - break; - } - npc.resetEntity(true); - npc.playAnimation(-1, 0); - npc.setLifeCycle(this.currentTick + duration); - } - removeNpc(npc, duration) { - const zone = this.getZone(npc.x, npc.z, npc.level); - zone.leave(npc); - switch (npc.blockWalk) { - case BlockWalk_default.NPC: - this.gameMap.changeNpcCollision(npc.width, npc.x, npc.z, npc.level, false); - break; - case BlockWalk_default.ALL: - this.gameMap.changeNpcCollision(npc.width, npc.x, npc.z, npc.level, false); - this.gameMap.changePlayerCollision(npc.width, npc.x, npc.z, npc.level, false); - break; - } - if (npc.lifecycle === EntityLifeCycle_default.DESPAWN) { - this.npcs.remove(npc.nid); - } else if (npc.lifecycle === EntityLifeCycle_default.RESPAWN) { - npc.setLifeCycle(this.currentTick + duration); - } - } - getLoc(x, z, level, locId) { - return this.getZone(x, z, level).getLoc(x, z, locId); - } - getObj(x, z, level, objId, receiverId) { - return this.getZone(x, z, level).getObj(x, z, objId, receiverId); - } - trackZone(tick, zone) { - let zones; - const active = this.zonesTracking.get(tick); - if (!active) { - zones = /* @__PURE__ */ new Set(); - } else { - zones = active; - } - zones.add(zone); - this.zonesTracking.set(tick, zones); - } - addLoc(loc, duration) { - const type = LocType.get(loc.type); - if (type.blockwalk) { - this.gameMap.changeLocCollision(loc.shape, loc.angle, type.blockrange, type.length, type.width, type.active, loc.x, loc.z, loc.level, true); - } - const zone = this.getZone(loc.x, loc.z, loc.level); - zone.addLoc(loc); - loc.setLifeCycle(this.currentTick + duration); - this.trackZone(this.currentTick + duration, zone); - this.trackZone(this.currentTick, zone); - } - mergeLoc(loc, player, startCycle, endCycle, south, east, north, west) { - const zone = this.getZone(loc.x, loc.z, loc.level); - zone.mergeLoc(loc, player, startCycle, endCycle, south, east, north, west); - this.trackZone(this.currentTick, zone); - } - animLoc(loc, seq) { - const zone = this.getZone(loc.x, loc.z, loc.level); - zone.animLoc(loc, seq); - this.trackZone(this.currentTick, zone); - } - removeLoc(loc, duration) { - const type = LocType.get(loc.type); - if (type.blockwalk) { - this.gameMap.changeLocCollision(loc.shape, loc.angle, type.blockrange, type.length, type.width, type.active, loc.x, loc.z, loc.level, false); - } - const zone = this.getZone(loc.x, loc.z, loc.level); - zone.removeLoc(loc); - loc.setLifeCycle(this.currentTick + duration); - this.trackZone(this.currentTick + duration, zone); - this.trackZone(this.currentTick, zone); - } - addObj(obj, receiverId, duration) { - const objType = ObjType.get(obj.type); - const existing = this.getObj(obj.x, obj.z, obj.level, obj.type, receiverId); - if (existing && existing.lifecycle === EntityLifeCycle_default.DESPAWN && obj.lifecycle === EntityLifeCycle_default.DESPAWN) { - const nextCount = obj.count + existing.count; - if (objType.stackable && nextCount <= Inventory.STACK_LIMIT) { - this.changeObj(existing, receiverId, nextCount); - return; - } - } - const zone = this.getZone(obj.x, obj.z, obj.level); - zone.addObj(obj, receiverId); - if (receiverId !== -1 && objType.tradeable) { - obj.setLifeCycle(this.currentTick + 100); - this.trackZone(this.currentTick + 100, zone); - this.trackZone(this.currentTick, zone); - obj.receiverId = receiverId; - obj.reveal = duration; - } else { - obj.setLifeCycle(this.currentTick + duration); - this.trackZone(this.currentTick + duration, zone); - this.trackZone(this.currentTick, zone); - } - } - revealObj(obj) { - const duration = obj.reveal; - const zone = this.getZone(obj.x, obj.z, obj.level); - zone.revealObj(obj, obj.receiverId); - obj.setLifeCycle(this.currentTick + duration); - this.trackZone(this.currentTick + duration, zone); - this.trackZone(this.currentTick, zone); - } - changeObj(obj, receiverId, newCount) { - const zone = this.getZone(obj.x, obj.z, obj.level); - zone.changeObj(obj, receiverId, obj.count, newCount); - this.trackZone(this.currentTick, zone); - } - removeObj(obj, duration) { - const zone = this.getZone(obj.x, obj.z, obj.level); - zone.removeObj(obj); - obj.setLifeCycle(this.currentTick + duration); - this.trackZone(this.currentTick + duration, zone); - this.trackZone(this.currentTick, zone); - } - animMap(level, x, z, spotanim, height, delay) { - const zone = this.getZone(x, z, level); - zone.animMap(x, z, spotanim, height, delay); - this.trackZone(this.currentTick, zone); - } - mapProjAnim(level, x, z, dstX, dstZ, target, spotanim, srcHeight, dstHeight, startDelay, endDelay, peak, arc) { - const zone = this.getZone(x, z, level); - zone.mapProjAnim(x, z, dstX, dstZ, target, spotanim, srcHeight, dstHeight, startDelay, endDelay, peak, arc); - this.trackZone(this.currentTick, zone); - } - // ---- - async readIn(socket, stream) { - while (stream.available > 0) { - const start = stream.pos; - let opcode = stream.g1(); - if (socket.decryptor) { - opcode = opcode - socket.decryptor.nextInt() & 255; - stream.data[start] = opcode; - } - if (typeof ClientProt.byId[opcode] === "undefined") { - socket.state = -1; - socket.close(); - return; - } - let length = ClientProt.byId[opcode].length; - if (length === -1) { - length = stream.g1(); - } else if (length === -2) { - length = stream.g2(); - } - if (stream.available < length) { - break; - } - stream.pos += length; - socket.inCount[opcode]++; - if (socket.inCount[opcode] > 5) { - continue; - } - const data = new Uint8Array(stream.pos - start); - const pos = stream.pos; - stream.pos = start; - stream.gdata(data, 0, data.length); - stream.pos = pos; - socket.in.set(data, socket.inOffset); - socket.inOffset += stream.pos - start; - } - } - addPlayer(player) { - this.newPlayers.add(player); - } - async removePlayer(player) { - if (player.pid === -1) { - return; - } - player.playerLog("Logging out"); - if (isNetworkPlayer(player)) { - player.logout(); - player.client.close(); - player.client = null; - } - Login_default.logout(player); - } - getPlayer(pid) { - return this.players.get(pid); - } - getPlayerByUid(uid) { - const pid = uid & 2047; - const name37 = uid >> 11 & 2097151; - const player = this.getPlayer(pid); - if (!player) { - return null; - } - if (Number(player.username37 & 0x1fffffn) !== name37) { - return null; - } - return player; - } - getPlayerByUsername(username) { - const username37 = toBase37(username); - for (const player of this.players) { - if (player.username37 === username37) { - return player; - } - } - for (const player of this.newPlayers) { - if (player.username37 === username37) { - return player; - } - } - return void 0; - } - getTotalPlayers() { - return this.players.count; - } - getTotalNpcs() { - return this.npcs.count; - } - getTotalZones() { - return this.zoneMap.zoneCount(); - } - getTotalLocs() { - return this.zoneMap.locCount(); - } - getTotalObjs() { - return this.zoneMap.objCount(); - } - getNpc(nid) { - return this.npcs.get(nid); - } - getNpcByUid(uid) { - const slot = uid & 65535; - const type = uid >> 16 & 65535; - const npc = this.getNpc(slot); - if (!npc || npc.type !== type) { - return null; - } - return npc; - } - getNextNid() { - return this.npcs.next(); - } - getNextPid(client = null) { - if (client) { - const ip = client.remoteAddress; - const octets = ip.split("."); - const start = parseInt(octets[3]) % 20 * 100; - return this.players.next(true, start); - } - return this.players.next(); - } -}; -var World_default = new World(); - -// src/lostcity/server/WorkerServer.ts -var WorkerServer = class { - sockets = /* @__PURE__ */ new Map(); - constructor() { - } - start() { - self.onmessage = async (e) => { - const packet = new Packet(new Uint8Array(e.data.data)); - const socket = this.sockets.get(e.data.id); - switch (e.data.type) { - case "connection": { - this.sockets.set(e.data.id, new ClientSocket(self, "127.0.0.1", -1, -1, e.data.id)); - const seed = new Packet(new Uint8Array(4 + 4)); - seed.p4(Math.floor(Math.random() * 4294967295)); - seed.p4(Math.floor(Math.random() * 4294967295)); - this.sockets.get(e.data.id)?.send(seed.data); - break; - } - case "data": { - if (socket) { - try { - if (socket.state === 1) { - await World_default.readIn(socket, packet); - } else { - await Login_default.readIn(socket, packet); - } - } catch (err) { - console.log("error", err); - socket.close(); - this.sockets.delete(e.data.id); - } - } - break; - } - case "close": { - if (socket) { - if (socket.player) { - socket.player.client = null; - } - socket.close(); - this.sockets.delete(e.data.id); - } - break; - } - } - }; - self.onerror = async (e) => { - console.log(e); - }; - self.onmessageerror = async (e) => { - console.log(e); - this.sockets.get(e.data.id)?.close(); - this.sockets.delete(e.data.id); - }; - } -}; - -// src/lostcity/worker.ts -await World_default.start(); -var workerServer = new WorkerServer(); -workerServer.start();