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 new 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 )); // (disabled):crypto var require_crypto = __commonJS({ "(disabled):crypto"() { } }); // node_modules/tweetnacl/nacl-fast.js var require_nacl_fast = __commonJS({ "node_modules/tweetnacl/nacl-fast.js"(exports, module) { (function(nacl2) { "use strict"; var gf = function(init) { var i, r = new Float64Array(16); if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; return r; }; var randombytes = function() { throw new Error("no PRNG"); }; var _0 = new Uint8Array(16); var _9 = new Uint8Array(32); _9[0] = 9; var gf0 = gf(), gf1 = gf([1]), _121665 = gf([56129, 1]), D = gf([30883, 4953, 19914, 30187, 55467, 16705, 2637, 112, 59544, 30585, 16505, 36039, 65139, 11119, 27886, 20995]), D2 = gf([61785, 9906, 39828, 60374, 45398, 33411, 5274, 224, 53552, 61171, 33010, 6542, 64743, 22239, 55772, 9222]), X = gf([54554, 36645, 11616, 51542, 42930, 38181, 51040, 26924, 56412, 64982, 57905, 49316, 21502, 52590, 14035, 8553]), Y = gf([26200, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214]), I = gf([41136, 18958, 6951, 50414, 58488, 44335, 6150, 12099, 55207, 15867, 153, 11085, 57099, 20417, 9344, 11139]); function ts64(x, i, h, l) { x[i] = h >> 24 & 255; x[i + 1] = h >> 16 & 255; x[i + 2] = h >> 8 & 255; x[i + 3] = h & 255; x[i + 4] = l >> 24 & 255; x[i + 5] = l >> 16 & 255; x[i + 6] = l >> 8 & 255; x[i + 7] = l & 255; } 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 crypto_verify_16(x, xi, y, yi) { return vn(x, xi, y, yi, 16); } function crypto_verify_32(x, xi, y, yi) { return vn(x, xi, y, yi, 32); } function core_salsa20(o, p, k, c) { var j0 = c[0] & 255 | (c[1] & 255) << 8 | (c[2] & 255) << 16 | (c[3] & 255) << 24, j1 = k[0] & 255 | (k[1] & 255) << 8 | (k[2] & 255) << 16 | (k[3] & 255) << 24, j2 = k[4] & 255 | (k[5] & 255) << 8 | (k[6] & 255) << 16 | (k[7] & 255) << 24, j3 = k[8] & 255 | (k[9] & 255) << 8 | (k[10] & 255) << 16 | (k[11] & 255) << 24, j4 = k[12] & 255 | (k[13] & 255) << 8 | (k[14] & 255) << 16 | (k[15] & 255) << 24, j5 = c[4] & 255 | (c[5] & 255) << 8 | (c[6] & 255) << 16 | (c[7] & 255) << 24, j6 = p[0] & 255 | (p[1] & 255) << 8 | (p[2] & 255) << 16 | (p[3] & 255) << 24, j7 = p[4] & 255 | (p[5] & 255) << 8 | (p[6] & 255) << 16 | (p[7] & 255) << 24, j8 = p[8] & 255 | (p[9] & 255) << 8 | (p[10] & 255) << 16 | (p[11] & 255) << 24, j9 = p[12] & 255 | (p[13] & 255) << 8 | (p[14] & 255) << 16 | (p[15] & 255) << 24, j10 = c[8] & 255 | (c[9] & 255) << 8 | (c[10] & 255) << 16 | (c[11] & 255) << 24, j11 = k[16] & 255 | (k[17] & 255) << 8 | (k[18] & 255) << 16 | (k[19] & 255) << 24, j12 = k[20] & 255 | (k[21] & 255) << 8 | (k[22] & 255) << 16 | (k[23] & 255) << 24, j13 = k[24] & 255 | (k[25] & 255) << 8 | (k[26] & 255) << 16 | (k[27] & 255) << 24, j14 = k[28] & 255 | (k[29] & 255) << 8 | (k[30] & 255) << 16 | (k[31] & 255) << 24, j15 = c[12] & 255 | (c[13] & 255) << 8 | (c[14] & 255) << 16 | (c[15] & 255) << 24; var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u; for (var i = 0; i < 20; i += 2) { u = x0 + x12 | 0; x4 ^= u << 7 | u >>> 32 - 7; u = x4 + x0 | 0; x8 ^= u << 9 | u >>> 32 - 9; u = x8 + x4 | 0; x12 ^= u << 13 | u >>> 32 - 13; u = x12 + x8 | 0; x0 ^= u << 18 | u >>> 32 - 18; u = x5 + x1 | 0; x9 ^= u << 7 | u >>> 32 - 7; u = x9 + x5 | 0; x13 ^= u << 9 | u >>> 32 - 9; u = x13 + x9 | 0; x1 ^= u << 13 | u >>> 32 - 13; u = x1 + x13 | 0; x5 ^= u << 18 | u >>> 32 - 18; u = x10 + x6 | 0; x14 ^= u << 7 | u >>> 32 - 7; u = x14 + x10 | 0; x2 ^= u << 9 | u >>> 32 - 9; u = x2 + x14 | 0; x6 ^= u << 13 | u >>> 32 - 13; u = x6 + x2 | 0; x10 ^= u << 18 | u >>> 32 - 18; u = x15 + x11 | 0; x3 ^= u << 7 | u >>> 32 - 7; u = x3 + x15 | 0; x7 ^= u << 9 | u >>> 32 - 9; u = x7 + x3 | 0; x11 ^= u << 13 | u >>> 32 - 13; u = x11 + x7 | 0; x15 ^= u << 18 | u >>> 32 - 18; u = x0 + x3 | 0; x1 ^= u << 7 | u >>> 32 - 7; u = x1 + x0 | 0; x2 ^= u << 9 | u >>> 32 - 9; u = x2 + x1 | 0; x3 ^= u << 13 | u >>> 32 - 13; u = x3 + x2 | 0; x0 ^= u << 18 | u >>> 32 - 18; u = x5 + x4 | 0; x6 ^= u << 7 | u >>> 32 - 7; u = x6 + x5 | 0; x7 ^= u << 9 | u >>> 32 - 9; u = x7 + x6 | 0; x4 ^= u << 13 | u >>> 32 - 13; u = x4 + x7 | 0; x5 ^= u << 18 | u >>> 32 - 18; u = x10 + x9 | 0; x11 ^= u << 7 | u >>> 32 - 7; u = x11 + x10 | 0; x8 ^= u << 9 | u >>> 32 - 9; u = x8 + x11 | 0; x9 ^= u << 13 | u >>> 32 - 13; u = x9 + x8 | 0; x10 ^= u << 18 | u >>> 32 - 18; u = x15 + x14 | 0; x12 ^= u << 7 | u >>> 32 - 7; u = x12 + x15 | 0; x13 ^= u << 9 | u >>> 32 - 9; u = x13 + x12 | 0; x14 ^= u << 13 | u >>> 32 - 13; u = x14 + x13 | 0; x15 ^= u << 18 | u >>> 32 - 18; } x0 = x0 + j0 | 0; x1 = x1 + j1 | 0; x2 = x2 + j2 | 0; x3 = x3 + j3 | 0; x4 = x4 + j4 | 0; x5 = x5 + j5 | 0; x6 = x6 + j6 | 0; x7 = x7 + j7 | 0; x8 = x8 + j8 | 0; x9 = x9 + j9 | 0; x10 = x10 + j10 | 0; x11 = x11 + j11 | 0; x12 = x12 + j12 | 0; x13 = x13 + j13 | 0; x14 = x14 + j14 | 0; x15 = x15 + j15 | 0; o[0] = x0 >>> 0 & 255; o[1] = x0 >>> 8 & 255; o[2] = x0 >>> 16 & 255; o[3] = x0 >>> 24 & 255; o[4] = x1 >>> 0 & 255; o[5] = x1 >>> 8 & 255; o[6] = x1 >>> 16 & 255; o[7] = x1 >>> 24 & 255; o[8] = x2 >>> 0 & 255; o[9] = x2 >>> 8 & 255; o[10] = x2 >>> 16 & 255; o[11] = x2 >>> 24 & 255; o[12] = x3 >>> 0 & 255; o[13] = x3 >>> 8 & 255; o[14] = x3 >>> 16 & 255; o[15] = x3 >>> 24 & 255; o[16] = x4 >>> 0 & 255; o[17] = x4 >>> 8 & 255; o[18] = x4 >>> 16 & 255; o[19] = x4 >>> 24 & 255; o[20] = x5 >>> 0 & 255; o[21] = x5 >>> 8 & 255; o[22] = x5 >>> 16 & 255; o[23] = x5 >>> 24 & 255; o[24] = x6 >>> 0 & 255; o[25] = x6 >>> 8 & 255; o[26] = x6 >>> 16 & 255; o[27] = x6 >>> 24 & 255; o[28] = x7 >>> 0 & 255; o[29] = x7 >>> 8 & 255; o[30] = x7 >>> 16 & 255; o[31] = x7 >>> 24 & 255; o[32] = x8 >>> 0 & 255; o[33] = x8 >>> 8 & 255; o[34] = x8 >>> 16 & 255; o[35] = x8 >>> 24 & 255; o[36] = x9 >>> 0 & 255; o[37] = x9 >>> 8 & 255; o[38] = x9 >>> 16 & 255; o[39] = x9 >>> 24 & 255; o[40] = x10 >>> 0 & 255; o[41] = x10 >>> 8 & 255; o[42] = x10 >>> 16 & 255; o[43] = x10 >>> 24 & 255; o[44] = x11 >>> 0 & 255; o[45] = x11 >>> 8 & 255; o[46] = x11 >>> 16 & 255; o[47] = x11 >>> 24 & 255; o[48] = x12 >>> 0 & 255; o[49] = x12 >>> 8 & 255; o[50] = x12 >>> 16 & 255; o[51] = x12 >>> 24 & 255; o[52] = x13 >>> 0 & 255; o[53] = x13 >>> 8 & 255; o[54] = x13 >>> 16 & 255; o[55] = x13 >>> 24 & 255; o[56] = x14 >>> 0 & 255; o[57] = x14 >>> 8 & 255; o[58] = x14 >>> 16 & 255; o[59] = x14 >>> 24 & 255; o[60] = x15 >>> 0 & 255; o[61] = x15 >>> 8 & 255; o[62] = x15 >>> 16 & 255; o[63] = x15 >>> 24 & 255; } function core_hsalsa20(o, p, k, c) { var j0 = c[0] & 255 | (c[1] & 255) << 8 | (c[2] & 255) << 16 | (c[3] & 255) << 24, j1 = k[0] & 255 | (k[1] & 255) << 8 | (k[2] & 255) << 16 | (k[3] & 255) << 24, j2 = k[4] & 255 | (k[5] & 255) << 8 | (k[6] & 255) << 16 | (k[7] & 255) << 24, j3 = k[8] & 255 | (k[9] & 255) << 8 | (k[10] & 255) << 16 | (k[11] & 255) << 24, j4 = k[12] & 255 | (k[13] & 255) << 8 | (k[14] & 255) << 16 | (k[15] & 255) << 24, j5 = c[4] & 255 | (c[5] & 255) << 8 | (c[6] & 255) << 16 | (c[7] & 255) << 24, j6 = p[0] & 255 | (p[1] & 255) << 8 | (p[2] & 255) << 16 | (p[3] & 255) << 24, j7 = p[4] & 255 | (p[5] & 255) << 8 | (p[6] & 255) << 16 | (p[7] & 255) << 24, j8 = p[8] & 255 | (p[9] & 255) << 8 | (p[10] & 255) << 16 | (p[11] & 255) << 24, j9 = p[12] & 255 | (p[13] & 255) << 8 | (p[14] & 255) << 16 | (p[15] & 255) << 24, j10 = c[8] & 255 | (c[9] & 255) << 8 | (c[10] & 255) << 16 | (c[11] & 255) << 24, j11 = k[16] & 255 | (k[17] & 255) << 8 | (k[18] & 255) << 16 | (k[19] & 255) << 24, j12 = k[20] & 255 | (k[21] & 255) << 8 | (k[22] & 255) << 16 | (k[23] & 255) << 24, j13 = k[24] & 255 | (k[25] & 255) << 8 | (k[26] & 255) << 16 | (k[27] & 255) << 24, j14 = k[28] & 255 | (k[29] & 255) << 8 | (k[30] & 255) << 16 | (k[31] & 255) << 24, j15 = c[12] & 255 | (c[13] & 255) << 8 | (c[14] & 255) << 16 | (c[15] & 255) << 24; var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u; for (var i = 0; i < 20; i += 2) { u = x0 + x12 | 0; x4 ^= u << 7 | u >>> 32 - 7; u = x4 + x0 | 0; x8 ^= u << 9 | u >>> 32 - 9; u = x8 + x4 | 0; x12 ^= u << 13 | u >>> 32 - 13; u = x12 + x8 | 0; x0 ^= u << 18 | u >>> 32 - 18; u = x5 + x1 | 0; x9 ^= u << 7 | u >>> 32 - 7; u = x9 + x5 | 0; x13 ^= u << 9 | u >>> 32 - 9; u = x13 + x9 | 0; x1 ^= u << 13 | u >>> 32 - 13; u = x1 + x13 | 0; x5 ^= u << 18 | u >>> 32 - 18; u = x10 + x6 | 0; x14 ^= u << 7 | u >>> 32 - 7; u = x14 + x10 | 0; x2 ^= u << 9 | u >>> 32 - 9; u = x2 + x14 | 0; x6 ^= u << 13 | u >>> 32 - 13; u = x6 + x2 | 0; x10 ^= u << 18 | u >>> 32 - 18; u = x15 + x11 | 0; x3 ^= u << 7 | u >>> 32 - 7; u = x3 + x15 | 0; x7 ^= u << 9 | u >>> 32 - 9; u = x7 + x3 | 0; x11 ^= u << 13 | u >>> 32 - 13; u = x11 + x7 | 0; x15 ^= u << 18 | u >>> 32 - 18; u = x0 + x3 | 0; x1 ^= u << 7 | u >>> 32 - 7; u = x1 + x0 | 0; x2 ^= u << 9 | u >>> 32 - 9; u = x2 + x1 | 0; x3 ^= u << 13 | u >>> 32 - 13; u = x3 + x2 | 0; x0 ^= u << 18 | u >>> 32 - 18; u = x5 + x4 | 0; x6 ^= u << 7 | u >>> 32 - 7; u = x6 + x5 | 0; x7 ^= u << 9 | u >>> 32 - 9; u = x7 + x6 | 0; x4 ^= u << 13 | u >>> 32 - 13; u = x4 + x7 | 0; x5 ^= u << 18 | u >>> 32 - 18; u = x10 + x9 | 0; x11 ^= u << 7 | u >>> 32 - 7; u = x11 + x10 | 0; x8 ^= u << 9 | u >>> 32 - 9; u = x8 + x11 | 0; x9 ^= u << 13 | u >>> 32 - 13; u = x9 + x8 | 0; x10 ^= u << 18 | u >>> 32 - 18; u = x15 + x14 | 0; x12 ^= u << 7 | u >>> 32 - 7; u = x12 + x15 | 0; x13 ^= u << 9 | u >>> 32 - 9; u = x13 + x12 | 0; x14 ^= u << 13 | u >>> 32 - 13; u = x14 + x13 | 0; x15 ^= u << 18 | u >>> 32 - 18; } o[0] = x0 >>> 0 & 255; o[1] = x0 >>> 8 & 255; o[2] = x0 >>> 16 & 255; o[3] = x0 >>> 24 & 255; o[4] = x5 >>> 0 & 255; o[5] = x5 >>> 8 & 255; o[6] = x5 >>> 16 & 255; o[7] = x5 >>> 24 & 255; o[8] = x10 >>> 0 & 255; o[9] = x10 >>> 8 & 255; o[10] = x10 >>> 16 & 255; o[11] = x10 >>> 24 & 255; o[12] = x15 >>> 0 & 255; o[13] = x15 >>> 8 & 255; o[14] = x15 >>> 16 & 255; o[15] = x15 >>> 24 & 255; o[16] = x6 >>> 0 & 255; o[17] = x6 >>> 8 & 255; o[18] = x6 >>> 16 & 255; o[19] = x6 >>> 24 & 255; o[20] = x7 >>> 0 & 255; o[21] = x7 >>> 8 & 255; o[22] = x7 >>> 16 & 255; o[23] = x7 >>> 24 & 255; o[24] = x8 >>> 0 & 255; o[25] = x8 >>> 8 & 255; o[26] = x8 >>> 16 & 255; o[27] = x8 >>> 24 & 255; o[28] = x9 >>> 0 & 255; o[29] = x9 >>> 8 & 255; o[30] = x9 >>> 16 & 255; o[31] = x9 >>> 24 & 255; } function crypto_core_salsa20(out, inp, k, c) { core_salsa20(out, inp, k, c); } function crypto_core_hsalsa20(out, inp, k, c) { core_hsalsa20(out, inp, k, c); } var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); function crypto_stream_salsa20_xor(c, cpos, m, mpos, b, n, k) { var z = new Uint8Array(16), x = new Uint8Array(64); var u, i; for (i = 0; i < 16; i++) z[i] = 0; for (i = 0; i < 8; i++) z[i] = n[i]; while (b >= 64) { crypto_core_salsa20(x, z, k, sigma); for (i = 0; i < 64; i++) c[cpos + i] = m[mpos + i] ^ x[i]; u = 1; for (i = 8; i < 16; i++) { u = u + (z[i] & 255) | 0; z[i] = u & 255; u >>>= 8; } b -= 64; cpos += 64; mpos += 64; } if (b > 0) { crypto_core_salsa20(x, z, k, sigma); for (i = 0; i < b; i++) c[cpos + i] = m[mpos + i] ^ x[i]; } return 0; } function crypto_stream_salsa20(c, cpos, b, n, k) { var z = new Uint8Array(16), x = new Uint8Array(64); var u, i; for (i = 0; i < 16; i++) z[i] = 0; for (i = 0; i < 8; i++) z[i] = n[i]; while (b >= 64) { crypto_core_salsa20(x, z, k, sigma); for (i = 0; i < 64; i++) c[cpos + i] = x[i]; u = 1; for (i = 8; i < 16; i++) { u = u + (z[i] & 255) | 0; z[i] = u & 255; u >>>= 8; } b -= 64; cpos += 64; } if (b > 0) { crypto_core_salsa20(x, z, k, sigma); for (i = 0; i < b; i++) c[cpos + i] = x[i]; } return 0; } function crypto_stream(c, cpos, d, n, k) { var s = new Uint8Array(32); crypto_core_hsalsa20(s, n, k, sigma); var sn = new Uint8Array(8); for (var i = 0; i < 8; i++) sn[i] = n[i + 16]; return crypto_stream_salsa20(c, cpos, d, sn, s); } function crypto_stream_xor(c, cpos, m, mpos, d, n, k) { var s = new Uint8Array(32); crypto_core_hsalsa20(s, n, k, sigma); var sn = new Uint8Array(8); for (var i = 0; i < 8; i++) sn[i] = n[i + 16]; return crypto_stream_salsa20_xor(c, cpos, m, mpos, d, sn, s); } var poly1305 = function(key) { this.buffer = new Uint8Array(16); this.r = new Uint16Array(10); this.h = new Uint16Array(10); this.pad = new Uint16Array(8); this.leftover = 0; this.fin = 0; var t0, t1, t2, t3, t4, t5, t6, t7; t0 = key[0] & 255 | (key[1] & 255) << 8; this.r[0] = t0 & 8191; t1 = key[2] & 255 | (key[3] & 255) << 8; this.r[1] = (t0 >>> 13 | t1 << 3) & 8191; t2 = key[4] & 255 | (key[5] & 255) << 8; this.r[2] = (t1 >>> 10 | t2 << 6) & 7939; t3 = key[6] & 255 | (key[7] & 255) << 8; this.r[3] = (t2 >>> 7 | t3 << 9) & 8191; t4 = key[8] & 255 | (key[9] & 255) << 8; this.r[4] = (t3 >>> 4 | t4 << 12) & 255; this.r[5] = t4 >>> 1 & 8190; t5 = key[10] & 255 | (key[11] & 255) << 8; this.r[6] = (t4 >>> 14 | t5 << 2) & 8191; t6 = key[12] & 255 | (key[13] & 255) << 8; this.r[7] = (t5 >>> 11 | t6 << 5) & 8065; t7 = key[14] & 255 | (key[15] & 255) << 8; this.r[8] = (t6 >>> 8 | t7 << 8) & 8191; this.r[9] = t7 >>> 5 & 127; this.pad[0] = key[16] & 255 | (key[17] & 255) << 8; this.pad[1] = key[18] & 255 | (key[19] & 255) << 8; this.pad[2] = key[20] & 255 | (key[21] & 255) << 8; this.pad[3] = key[22] & 255 | (key[23] & 255) << 8; this.pad[4] = key[24] & 255 | (key[25] & 255) << 8; this.pad[5] = key[26] & 255 | (key[27] & 255) << 8; this.pad[6] = key[28] & 255 | (key[29] & 255) << 8; this.pad[7] = key[30] & 255 | (key[31] & 255) << 8; }; poly1305.prototype.blocks = function(m, mpos, bytes) { var hibit = this.fin ? 0 : 1 << 11; var t0, t1, t2, t3, t4, t5, t6, t7, c; var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; var h0 = this.h[0], h1 = this.h[1], h2 = this.h[2], h3 = this.h[3], h4 = this.h[4], h5 = this.h[5], h6 = this.h[6], h7 = this.h[7], h8 = this.h[8], h9 = this.h[9]; var r0 = this.r[0], r1 = this.r[1], r2 = this.r[2], r3 = this.r[3], r4 = this.r[4], r5 = this.r[5], r6 = this.r[6], r7 = this.r[7], r8 = this.r[8], r9 = this.r[9]; while (bytes >= 16) { t0 = m[mpos + 0] & 255 | (m[mpos + 1] & 255) << 8; h0 += t0 & 8191; t1 = m[mpos + 2] & 255 | (m[mpos + 3] & 255) << 8; h1 += (t0 >>> 13 | t1 << 3) & 8191; t2 = m[mpos + 4] & 255 | (m[mpos + 5] & 255) << 8; h2 += (t1 >>> 10 | t2 << 6) & 8191; t3 = m[mpos + 6] & 255 | (m[mpos + 7] & 255) << 8; h3 += (t2 >>> 7 | t3 << 9) & 8191; t4 = m[mpos + 8] & 255 | (m[mpos + 9] & 255) << 8; h4 += (t3 >>> 4 | t4 << 12) & 8191; h5 += t4 >>> 1 & 8191; t5 = m[mpos + 10] & 255 | (m[mpos + 11] & 255) << 8; h6 += (t4 >>> 14 | t5 << 2) & 8191; t6 = m[mpos + 12] & 255 | (m[mpos + 13] & 255) << 8; h7 += (t5 >>> 11 | t6 << 5) & 8191; t7 = m[mpos + 14] & 255 | (m[mpos + 15] & 255) << 8; h8 += (t6 >>> 8 | t7 << 8) & 8191; h9 += t7 >>> 5 | hibit; c = 0; d0 = c; d0 += h0 * r0; d0 += h1 * (5 * r9); d0 += h2 * (5 * r8); d0 += h3 * (5 * r7); d0 += h4 * (5 * r6); c = d0 >>> 13; d0 &= 8191; d0 += h5 * (5 * r5); d0 += h6 * (5 * r4); d0 += h7 * (5 * r3); d0 += h8 * (5 * r2); d0 += h9 * (5 * r1); c += d0 >>> 13; d0 &= 8191; d1 = c; d1 += h0 * r1; d1 += h1 * r0; d1 += h2 * (5 * r9); d1 += h3 * (5 * r8); d1 += h4 * (5 * r7); c = d1 >>> 13; d1 &= 8191; d1 += h5 * (5 * r6); d1 += h6 * (5 * r5); d1 += h7 * (5 * r4); d1 += h8 * (5 * r3); d1 += h9 * (5 * r2); c += d1 >>> 13; d1 &= 8191; d2 = c; d2 += h0 * r2; d2 += h1 * r1; d2 += h2 * r0; d2 += h3 * (5 * r9); d2 += h4 * (5 * r8); c = d2 >>> 13; d2 &= 8191; d2 += h5 * (5 * r7); d2 += h6 * (5 * r6); d2 += h7 * (5 * r5); d2 += h8 * (5 * r4); d2 += h9 * (5 * r3); c += d2 >>> 13; d2 &= 8191; d3 = c; d3 += h0 * r3; d3 += h1 * r2; d3 += h2 * r1; d3 += h3 * r0; d3 += h4 * (5 * r9); c = d3 >>> 13; d3 &= 8191; d3 += h5 * (5 * r8); d3 += h6 * (5 * r7); d3 += h7 * (5 * r6); d3 += h8 * (5 * r5); d3 += h9 * (5 * r4); c += d3 >>> 13; d3 &= 8191; d4 = c; d4 += h0 * r4; d4 += h1 * r3; d4 += h2 * r2; d4 += h3 * r1; d4 += h4 * r0; c = d4 >>> 13; d4 &= 8191; d4 += h5 * (5 * r9); d4 += h6 * (5 * r8); d4 += h7 * (5 * r7); d4 += h8 * (5 * r6); d4 += h9 * (5 * r5); c += d4 >>> 13; d4 &= 8191; d5 = c; d5 += h0 * r5; d5 += h1 * r4; d5 += h2 * r3; d5 += h3 * r2; d5 += h4 * r1; c = d5 >>> 13; d5 &= 8191; d5 += h5 * r0; d5 += h6 * (5 * r9); d5 += h7 * (5 * r8); d5 += h8 * (5 * r7); d5 += h9 * (5 * r6); c += d5 >>> 13; d5 &= 8191; d6 = c; d6 += h0 * r6; d6 += h1 * r5; d6 += h2 * r4; d6 += h3 * r3; d6 += h4 * r2; c = d6 >>> 13; d6 &= 8191; d6 += h5 * r1; d6 += h6 * r0; d6 += h7 * (5 * r9); d6 += h8 * (5 * r8); d6 += h9 * (5 * r7); c += d6 >>> 13; d6 &= 8191; d7 = c; d7 += h0 * r7; d7 += h1 * r6; d7 += h2 * r5; d7 += h3 * r4; d7 += h4 * r3; c = d7 >>> 13; d7 &= 8191; d7 += h5 * r2; d7 += h6 * r1; d7 += h7 * r0; d7 += h8 * (5 * r9); d7 += h9 * (5 * r8); c += d7 >>> 13; d7 &= 8191; d8 = c; d8 += h0 * r8; d8 += h1 * r7; d8 += h2 * r6; d8 += h3 * r5; d8 += h4 * r4; c = d8 >>> 13; d8 &= 8191; d8 += h5 * r3; d8 += h6 * r2; d8 += h7 * r1; d8 += h8 * r0; d8 += h9 * (5 * r9); c += d8 >>> 13; d8 &= 8191; d9 = c; d9 += h0 * r9; d9 += h1 * r8; d9 += h2 * r7; d9 += h3 * r6; d9 += h4 * r5; c = d9 >>> 13; d9 &= 8191; d9 += h5 * r4; d9 += h6 * r3; d9 += h7 * r2; d9 += h8 * r1; d9 += h9 * r0; c += d9 >>> 13; d9 &= 8191; c = (c << 2) + c | 0; c = c + d0 | 0; d0 = c & 8191; c = c >>> 13; d1 += c; h0 = d0; h1 = d1; h2 = d2; h3 = d3; h4 = d4; h5 = d5; h6 = d6; h7 = d7; h8 = d8; h9 = d9; mpos += 16; bytes -= 16; } this.h[0] = h0; this.h[1] = h1; this.h[2] = h2; this.h[3] = h3; this.h[4] = h4; this.h[5] = h5; this.h[6] = h6; this.h[7] = h7; this.h[8] = h8; this.h[9] = h9; }; poly1305.prototype.finish = function(mac, macpos) { var g = new Uint16Array(10); var c, mask, f, i; if (this.leftover) { i = this.leftover; this.buffer[i++] = 1; for (; i < 16; i++) this.buffer[i] = 0; this.fin = 1; this.blocks(this.buffer, 0, 16); } c = this.h[1] >>> 13; this.h[1] &= 8191; for (i = 2; i < 10; i++) { this.h[i] += c; c = this.h[i] >>> 13; this.h[i] &= 8191; } this.h[0] += c * 5; c = this.h[0] >>> 13; this.h[0] &= 8191; this.h[1] += c; c = this.h[1] >>> 13; this.h[1] &= 8191; this.h[2] += c; g[0] = this.h[0] + 5; c = g[0] >>> 13; g[0] &= 8191; for (i = 1; i < 10; i++) { g[i] = this.h[i] + c; c = g[i] >>> 13; g[i] &= 8191; } g[9] -= 1 << 13; mask = (c ^ 1) - 1; for (i = 0; i < 10; i++) g[i] &= mask; mask = ~mask; for (i = 0; i < 10; i++) this.h[i] = this.h[i] & mask | g[i]; this.h[0] = (this.h[0] | this.h[1] << 13) & 65535; this.h[1] = (this.h[1] >>> 3 | this.h[2] << 10) & 65535; this.h[2] = (this.h[2] >>> 6 | this.h[3] << 7) & 65535; this.h[3] = (this.h[3] >>> 9 | this.h[4] << 4) & 65535; this.h[4] = (this.h[4] >>> 12 | this.h[5] << 1 | this.h[6] << 14) & 65535; this.h[5] = (this.h[6] >>> 2 | this.h[7] << 11) & 65535; this.h[6] = (this.h[7] >>> 5 | this.h[8] << 8) & 65535; this.h[7] = (this.h[8] >>> 8 | this.h[9] << 5) & 65535; f = this.h[0] + this.pad[0]; this.h[0] = f & 65535; for (i = 1; i < 8; i++) { f = (this.h[i] + this.pad[i] | 0) + (f >>> 16) | 0; this.h[i] = f & 65535; } mac[macpos + 0] = this.h[0] >>> 0 & 255; mac[macpos + 1] = this.h[0] >>> 8 & 255; mac[macpos + 2] = this.h[1] >>> 0 & 255; mac[macpos + 3] = this.h[1] >>> 8 & 255; mac[macpos + 4] = this.h[2] >>> 0 & 255; mac[macpos + 5] = this.h[2] >>> 8 & 255; mac[macpos + 6] = this.h[3] >>> 0 & 255; mac[macpos + 7] = this.h[3] >>> 8 & 255; mac[macpos + 8] = this.h[4] >>> 0 & 255; mac[macpos + 9] = this.h[4] >>> 8 & 255; mac[macpos + 10] = this.h[5] >>> 0 & 255; mac[macpos + 11] = this.h[5] >>> 8 & 255; mac[macpos + 12] = this.h[6] >>> 0 & 255; mac[macpos + 13] = this.h[6] >>> 8 & 255; mac[macpos + 14] = this.h[7] >>> 0 & 255; mac[macpos + 15] = this.h[7] >>> 8 & 255; }; poly1305.prototype.update = function(m, mpos, bytes) { var i, want; if (this.leftover) { want = 16 - this.leftover; if (want > bytes) want = bytes; for (i = 0; i < want; i++) this.buffer[this.leftover + i] = m[mpos + i]; bytes -= want; mpos += want; this.leftover += want; if (this.leftover < 16) return; this.blocks(this.buffer, 0, 16); this.leftover = 0; } if (bytes >= 16) { want = bytes - bytes % 16; this.blocks(m, mpos, want); mpos += want; bytes -= want; } if (bytes) { for (i = 0; i < bytes; i++) this.buffer[this.leftover + i] = m[mpos + i]; this.leftover += bytes; } }; function crypto_onetimeauth(out, outpos, m, mpos, n, k) { var s = new poly1305(k); s.update(m, mpos, n); s.finish(out, outpos); return 0; } function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { var x = new Uint8Array(16); crypto_onetimeauth(x, 0, m, mpos, n, k); return crypto_verify_16(h, hpos, x, 0); } function crypto_secretbox(c, m, d, n, k) { var i; if (d < 32) return -1; crypto_stream_xor(c, 0, m, 0, d, n, k); crypto_onetimeauth(c, 16, c, 32, d - 32, c); for (i = 0; i < 16; i++) c[i] = 0; return 0; } function crypto_secretbox_open(m, c, d, n, k) { var i; var x = new Uint8Array(32); if (d < 32) return -1; crypto_stream(x, 0, 32, n, k); if (crypto_onetimeauth_verify(c, 16, c, 32, d - 32, x) !== 0) return -1; crypto_stream_xor(m, 0, c, 0, d, n, k); for (i = 0; i < 32; i++) m[i] = 0; return 0; } function set25519(r, a) { var i; for (i = 0; i < 16; i++) r[i] = a[i] | 0; } 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 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 neq25519(a, b) { var c = new Uint8Array(32), d = new Uint8Array(32); pack25519(c, a); pack25519(d, b); return crypto_verify_32(c, 0, d, 0); } function par25519(a) { var d = new Uint8Array(32); pack25519(d, a); return d[0] & 1; } 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 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 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; } function S(o, a) { M(o, a, a); } 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 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 crypto_scalarmult(q, n, p) { var z = new Uint8Array(32); var x = new Float64Array(80), r, i; var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(); for (i = 0; i < 31; i++) z[i] = n[i]; z[31] = n[31] & 127 | 64; z[0] &= 248; unpack25519(x, p); for (i = 0; i < 16; i++) { b[i] = x[i]; d[i] = a[i] = c[i] = 0; } a[0] = d[0] = 1; for (i = 254; i >= 0; --i) { r = z[i >>> 3] >>> (i & 7) & 1; sel25519(a, b, r); sel25519(c, d, r); A(e, a, c); Z(a, a, c); A(c, b, d); Z(b, b, d); S(d, e); S(f, a); M(a, c, a); M(c, b, e); A(e, a, c); Z(a, a, c); S(b, a); Z(c, d, f); M(a, c, _121665); A(a, a, d); M(c, c, a); M(a, d, f); M(d, b, x); S(b, e); sel25519(a, b, r); sel25519(c, d, r); } for (i = 0; i < 16; i++) { x[i + 16] = a[i]; x[i + 32] = c[i]; x[i + 48] = b[i]; x[i + 64] = d[i]; } var x32 = x.subarray(32); var x16 = x.subarray(16); inv25519(x32, x32); M(x16, x16, x32); pack25519(q, x16); return 0; } function crypto_scalarmult_base(q, n) { return crypto_scalarmult(q, n, _9); } function crypto_box_keypair(y, x) { randombytes(x, 32); return crypto_scalarmult_base(y, x); } function crypto_box_beforenm(k, y, x) { var s = new Uint8Array(32); crypto_scalarmult(s, x, y); return crypto_core_hsalsa20(k, _0, s, sigma); } var crypto_box_afternm = crypto_secretbox; var crypto_box_open_afternm = crypto_secretbox_open; function crypto_box(c, m, d, n, y, x) { var k = new Uint8Array(32); crypto_box_beforenm(k, y, x); return crypto_box_afternm(c, m, d, n, k); } function crypto_box_open(m, c, d, n, y, x) { var k = new Uint8Array(32); crypto_box_beforenm(k, y, x); return crypto_box_open_afternm(m, c, d, n, k); } var 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 ]; function crypto_hashblocks_hl(hh, hl, m, n) { var wh = new Int32Array(16), wl = new Int32Array(16), bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, th, tl, i, j, h, l, a, b, c, d; var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7]; var pos = 0; while (n >= 128) { for (i = 0; i < 16; i++) { j = 8 * i + pos; wh[i] = m[j + 0] << 24 | m[j + 1] << 16 | m[j + 2] << 8 | m[j + 3]; wl[i] = m[j + 4] << 24 | m[j + 5] << 16 | m[j + 6] << 8 | m[j + 7]; } for (i = 0; i < 80; i++) { bh0 = ah0; bh1 = ah1; bh2 = ah2; bh3 = ah3; bh4 = ah4; bh5 = ah5; bh6 = ah6; bh7 = ah7; bl0 = al0; bl1 = al1; bl2 = al2; bl3 = al3; bl4 = al4; bl5 = al5; bl6 = al6; bl7 = al7; h = ah7; l = al7; a = l & 65535; b = l >>> 16; c = h & 65535; d = h >>> 16; h = (ah4 >>> 14 | al4 << 32 - 14) ^ (ah4 >>> 18 | al4 << 32 - 18) ^ (al4 >>> 41 - 32 | ah4 << 32 - (41 - 32)); l = (al4 >>> 14 | ah4 << 32 - 14) ^ (al4 >>> 18 | ah4 << 32 - 18) ^ (ah4 >>> 41 - 32 | al4 << 32 - (41 - 32)); a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; h = ah4 & ah5 ^ ~ah4 & ah6; l = al4 & al5 ^ ~al4 & al6; a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; h = K[i * 2]; l = K[i * 2 + 1]; a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; h = wh[i % 16]; l = wl[i % 16]; a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; th = c & 65535 | d << 16; tl = a & 65535 | b << 16; h = th; l = tl; a = l & 65535; b = l >>> 16; c = h & 65535; d = h >>> 16; h = (ah0 >>> 28 | al0 << 32 - 28) ^ (al0 >>> 34 - 32 | ah0 << 32 - (34 - 32)) ^ (al0 >>> 39 - 32 | ah0 << 32 - (39 - 32)); l = (al0 >>> 28 | ah0 << 32 - 28) ^ (ah0 >>> 34 - 32 | al0 << 32 - (34 - 32)) ^ (ah0 >>> 39 - 32 | al0 << 32 - (39 - 32)); a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; h = ah0 & ah1 ^ ah0 & ah2 ^ ah1 & ah2; l = al0 & al1 ^ al0 & al2 ^ al1 & al2; a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; bh7 = c & 65535 | d << 16; bl7 = a & 65535 | b << 16; h = bh3; l = bl3; a = l & 65535; b = l >>> 16; c = h & 65535; d = h >>> 16; h = th; l = tl; a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; bh3 = c & 65535 | d << 16; bl3 = a & 65535 | b << 16; ah1 = bh0; ah2 = bh1; ah3 = bh2; ah4 = bh3; ah5 = bh4; ah6 = bh5; ah7 = bh6; ah0 = bh7; al1 = bl0; al2 = bl1; al3 = bl2; al4 = bl3; al5 = bl4; al6 = bl5; al7 = bl6; al0 = bl7; if (i % 16 === 15) { for (j = 0; j < 16; j++) { h = wh[j]; l = wl[j]; a = l & 65535; b = l >>> 16; c = h & 65535; d = h >>> 16; h = wh[(j + 9) % 16]; l = wl[(j + 9) % 16]; a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; th = wh[(j + 1) % 16]; tl = wl[(j + 1) % 16]; h = (th >>> 1 | tl << 32 - 1) ^ (th >>> 8 | tl << 32 - 8) ^ th >>> 7; l = (tl >>> 1 | th << 32 - 1) ^ (tl >>> 8 | th << 32 - 8) ^ (tl >>> 7 | th << 32 - 7); a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; th = wh[(j + 14) % 16]; tl = wl[(j + 14) % 16]; h = (th >>> 19 | tl << 32 - 19) ^ (tl >>> 61 - 32 | th << 32 - (61 - 32)) ^ th >>> 6; l = (tl >>> 19 | th << 32 - 19) ^ (th >>> 61 - 32 | tl << 32 - (61 - 32)) ^ (tl >>> 6 | th << 32 - 6); a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; wh[j] = c & 65535 | d << 16; wl[j] = a & 65535 | b << 16; } } } h = ah0; l = al0; a = l & 65535; b = l >>> 16; c = h & 65535; d = h >>> 16; h = hh[0]; l = hl[0]; a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[0] = ah0 = c & 65535 | d << 16; hl[0] = al0 = a & 65535 | b << 16; h = ah1; l = al1; a = l & 65535; b = l >>> 16; c = h & 65535; d = h >>> 16; h = hh[1]; l = hl[1]; a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[1] = ah1 = c & 65535 | d << 16; hl[1] = al1 = a & 65535 | b << 16; h = ah2; l = al2; a = l & 65535; b = l >>> 16; c = h & 65535; d = h >>> 16; h = hh[2]; l = hl[2]; a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[2] = ah2 = c & 65535 | d << 16; hl[2] = al2 = a & 65535 | b << 16; h = ah3; l = al3; a = l & 65535; b = l >>> 16; c = h & 65535; d = h >>> 16; h = hh[3]; l = hl[3]; a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[3] = ah3 = c & 65535 | d << 16; hl[3] = al3 = a & 65535 | b << 16; h = ah4; l = al4; a = l & 65535; b = l >>> 16; c = h & 65535; d = h >>> 16; h = hh[4]; l = hl[4]; a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[4] = ah4 = c & 65535 | d << 16; hl[4] = al4 = a & 65535 | b << 16; h = ah5; l = al5; a = l & 65535; b = l >>> 16; c = h & 65535; d = h >>> 16; h = hh[5]; l = hl[5]; a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[5] = ah5 = c & 65535 | d << 16; hl[5] = al5 = a & 65535 | b << 16; h = ah6; l = al6; a = l & 65535; b = l >>> 16; c = h & 65535; d = h >>> 16; h = hh[6]; l = hl[6]; a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[6] = ah6 = c & 65535 | d << 16; hl[6] = al6 = a & 65535 | b << 16; h = ah7; l = al7; a = l & 65535; b = l >>> 16; c = h & 65535; d = h >>> 16; h = hh[7]; l = hl[7]; a += l & 65535; b += l >>> 16; c += h & 65535; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[7] = ah7 = c & 65535 | d << 16; hl[7] = al7 = a & 65535 | b << 16; pos += 128; n -= 128; } return n; } function crypto_hash(out, m, n) { var hh = new Int32Array(8), hl = new Int32Array(8), x = new Uint8Array(256), i, b = n; hh[0] = 1779033703; hh[1] = 3144134277; hh[2] = 1013904242; hh[3] = 2773480762; hh[4] = 1359893119; hh[5] = 2600822924; hh[6] = 528734635; hh[7] = 1541459225; hl[0] = 4089235720; hl[1] = 2227873595; hl[2] = 4271175723; hl[3] = 1595750129; hl[4] = 2917565137; hl[5] = 725511199; hl[6] = 4215389547; hl[7] = 327033209; crypto_hashblocks_hl(hh, hl, m, n); n %= 128; for (i = 0; i < n; i++) x[i] = m[b - n + i]; x[n] = 128; n = 256 - 128 * (n < 112 ? 1 : 0); x[n - 9] = 0; ts64(x, n - 8, b / 536870912 | 0, b << 3); crypto_hashblocks_hl(hh, hl, x, n); for (i = 0; i < 8; i++) ts64(out, 8 * i, hh[i], hl[i]); return 0; } 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) { var i; for (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 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 crypto_sign_keypair(pk, sk, seeded) { var d = new Uint8Array(64); var p = [gf(), gf(), gf(), gf()]; var i; if (!seeded) randombytes(sk, 32); crypto_hash(d, 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; } 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]); 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 = Math.floor((x[j] + 128) / 256); 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), i; for (i = 0; i < 64; i++) x[i] = r[i]; for (i = 0; i < 64; i++) r[i] = 0; modL(r, x); } function crypto_sign(sm, m, n, sk) { var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); var i, j, x = new Float64Array(64); var p = [gf(), gf(), gf(), gf()]; crypto_hash(d, 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]; crypto_hash(r, sm.subarray(32), n + 32); reduce(r); scalarbase(p, r); pack(sm, p); for (i = 32; i < 64; i++) sm[i] = sk[i]; crypto_hash(h, sm, n + 64); reduce(h); for (i = 0; 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 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 crypto_sign_open(m, sm, n, pk) { var i; var t = new Uint8Array(32), h = new Uint8Array(64); var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; 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]; crypto_hash(h, 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]; return n; } var crypto_secretbox_KEYBYTES = 32, crypto_secretbox_NONCEBYTES = 24, crypto_secretbox_ZEROBYTES = 32, crypto_secretbox_BOXZEROBYTES = 16, crypto_scalarmult_BYTES = 32, crypto_scalarmult_SCALARBYTES = 32, crypto_box_PUBLICKEYBYTES = 32, crypto_box_SECRETKEYBYTES = 32, crypto_box_BEFORENMBYTES = 32, crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, crypto_sign_BYTES = 64, crypto_sign_PUBLICKEYBYTES = 32, crypto_sign_SECRETKEYBYTES = 64, crypto_sign_SEEDBYTES = 32, crypto_hash_BYTES = 64; nacl2.lowlevel = { crypto_core_hsalsa20, crypto_stream_xor, crypto_stream, crypto_stream_salsa20_xor, crypto_stream_salsa20, crypto_onetimeauth, crypto_onetimeauth_verify, crypto_verify_16, crypto_verify_32, crypto_secretbox, crypto_secretbox_open, crypto_scalarmult, crypto_scalarmult_base, crypto_box_beforenm, crypto_box_afternm, crypto_box, crypto_box_open, crypto_box_keypair, crypto_hash, crypto_sign, crypto_sign_keypair, crypto_sign_open, crypto_secretbox_KEYBYTES, crypto_secretbox_NONCEBYTES, crypto_secretbox_ZEROBYTES, crypto_secretbox_BOXZEROBYTES, crypto_scalarmult_BYTES, crypto_scalarmult_SCALARBYTES, crypto_box_PUBLICKEYBYTES, crypto_box_SECRETKEYBYTES, crypto_box_BEFORENMBYTES, crypto_box_NONCEBYTES, crypto_box_ZEROBYTES, crypto_box_BOXZEROBYTES, crypto_sign_BYTES, crypto_sign_PUBLICKEYBYTES, crypto_sign_SECRETKEYBYTES, crypto_sign_SEEDBYTES, crypto_hash_BYTES, gf, D, L, pack25519, unpack25519, M, A, S, Z, pow2523, add, set25519, modL, scalarmult, scalarbase }; function checkLengths(k, n) { if (k.length !== crypto_secretbox_KEYBYTES) throw new Error("bad key size"); if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error("bad nonce size"); } function checkBoxLengths(pk, sk) { if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error("bad public key size"); if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error("bad secret key size"); } function checkArrayTypes() { for (var i = 0; i < arguments.length; i++) { if (!(arguments[i] instanceof Uint8Array)) throw new TypeError("unexpected type, use Uint8Array"); } } function cleanup(arr) { for (var i = 0; i < arr.length; i++) arr[i] = 0; } nacl2.randomBytes = function(n) { var b = new Uint8Array(n); randombytes(b, n); return b; }; nacl2.secretbox = function(msg, nonce, key) { checkArrayTypes(msg, nonce, key); checkLengths(key, nonce); var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); var c = new Uint8Array(m.length); for (var i = 0; i < msg.length; i++) m[i + crypto_secretbox_ZEROBYTES] = msg[i]; crypto_secretbox(c, m, m.length, nonce, key); return c.subarray(crypto_secretbox_BOXZEROBYTES); }; nacl2.secretbox.open = function(box, nonce, key) { checkArrayTypes(box, nonce, key); checkLengths(key, nonce); var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); var m = new Uint8Array(c.length); for (var i = 0; i < box.length; i++) c[i + crypto_secretbox_BOXZEROBYTES] = box[i]; if (c.length < 32) return null; if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null; return m.subarray(crypto_secretbox_ZEROBYTES); }; nacl2.secretbox.keyLength = crypto_secretbox_KEYBYTES; nacl2.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; nacl2.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; nacl2.scalarMult = function(n, p) { checkArrayTypes(n, p); if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size"); if (p.length !== crypto_scalarmult_BYTES) throw new Error("bad p size"); var q = new Uint8Array(crypto_scalarmult_BYTES); crypto_scalarmult(q, n, p); return q; }; nacl2.scalarMult.base = function(n) { checkArrayTypes(n); if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size"); var q = new Uint8Array(crypto_scalarmult_BYTES); crypto_scalarmult_base(q, n); return q; }; nacl2.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; nacl2.scalarMult.groupElementLength = crypto_scalarmult_BYTES; nacl2.box = function(msg, nonce, publicKey, secretKey) { var k = nacl2.box.before(publicKey, secretKey); return nacl2.secretbox(msg, nonce, k); }; nacl2.box.before = function(publicKey, secretKey) { checkArrayTypes(publicKey, secretKey); checkBoxLengths(publicKey, secretKey); var k = new Uint8Array(crypto_box_BEFORENMBYTES); crypto_box_beforenm(k, publicKey, secretKey); return k; }; nacl2.box.after = nacl2.secretbox; nacl2.box.open = function(msg, nonce, publicKey, secretKey) { var k = nacl2.box.before(publicKey, secretKey); return nacl2.secretbox.open(msg, nonce, k); }; nacl2.box.open.after = nacl2.secretbox.open; nacl2.box.keyPair = function() { var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); crypto_box_keypair(pk, sk); return { publicKey: pk, secretKey: sk }; }; nacl2.box.keyPair.fromSecretKey = function(secretKey) { checkArrayTypes(secretKey); if (secretKey.length !== crypto_box_SECRETKEYBYTES) throw new Error("bad secret key size"); var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); crypto_scalarmult_base(pk, secretKey); return { publicKey: pk, secretKey: new Uint8Array(secretKey) }; }; nacl2.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; nacl2.box.secretKeyLength = crypto_box_SECRETKEYBYTES; nacl2.box.sharedKeyLength = crypto_box_BEFORENMBYTES; nacl2.box.nonceLength = crypto_box_NONCEBYTES; nacl2.box.overheadLength = nacl2.secretbox.overheadLength; nacl2.sign = function(msg, secretKey) { checkArrayTypes(msg, secretKey); if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error("bad secret key size"); var signedMsg = new Uint8Array(crypto_sign_BYTES + msg.length); crypto_sign(signedMsg, msg, msg.length, secretKey); return signedMsg; }; nacl2.sign.open = function(signedMsg, publicKey) { checkArrayTypes(signedMsg, publicKey); if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error("bad public key size"); var tmp = new Uint8Array(signedMsg.length); var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); if (mlen < 0) return null; var m = new Uint8Array(mlen); for (var i = 0; i < m.length; i++) m[i] = tmp[i]; return m; }; nacl2.sign.detached = function(msg, secretKey) { var signedMsg = nacl2.sign(msg, secretKey); var sig = new Uint8Array(crypto_sign_BYTES); for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; return sig; }; nacl2.sign.detached.verify = function(msg, sig, publicKey) { checkArrayTypes(msg, sig, publicKey); if (sig.length !== crypto_sign_BYTES) throw new Error("bad signature size"); if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error("bad public key size"); var sm = new Uint8Array(crypto_sign_BYTES + msg.length); var m = new Uint8Array(crypto_sign_BYTES + msg.length); var i; for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; for (i = 0; i < msg.length; i++) sm[i + crypto_sign_BYTES] = msg[i]; return crypto_sign_open(m, sm, sm.length, publicKey) >= 0; }; nacl2.sign.keyPair = function() { var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); crypto_sign_keypair(pk, sk); return { publicKey: pk, secretKey: sk }; }; nacl2.sign.keyPair.fromSecretKey = function(secretKey) { checkArrayTypes(secretKey); if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error("bad secret key size"); var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32 + i]; return { publicKey: pk, secretKey: new Uint8Array(secretKey) }; }; nacl2.sign.keyPair.fromSeed = function(seed) { checkArrayTypes(seed); if (seed.length !== crypto_sign_SEEDBYTES) throw new Error("bad seed size"); var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); for (var i = 0; i < 32; i++) sk[i] = seed[i]; crypto_sign_keypair(pk, sk, true); return { publicKey: pk, secretKey: sk }; }; nacl2.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; nacl2.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; nacl2.sign.seedLength = crypto_sign_SEEDBYTES; nacl2.sign.signatureLength = crypto_sign_BYTES; nacl2.hash = function(msg) { checkArrayTypes(msg); var h = new Uint8Array(crypto_hash_BYTES); crypto_hash(h, msg, msg.length); return h; }; nacl2.hash.hashLength = crypto_hash_BYTES; nacl2.verify = function(x, y) { checkArrayTypes(x, y); if (x.length === 0 || y.length === 0) return false; if (x.length !== y.length) return false; return vn(x, 0, y, 0, x.length) === 0 ? true : false; }; nacl2.setPRNG = function(fn) { randombytes = fn; }; (function() { var crypto2 = typeof self !== "undefined" ? self.crypto || self.msCrypto : null; if (crypto2 && crypto2.getRandomValues) { var QUOTA = 65536; nacl2.setPRNG(function(x, n) { var i, v = new Uint8Array(n); for (i = 0; i < n; i += QUOTA) { crypto2.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); } for (i = 0; i < n; i++) x[i] = v[i]; cleanup(v); }); } else if (typeof __require !== "undefined") { crypto2 = require_crypto(); if (crypto2 && crypto2.randomBytes) { nacl2.setPRNG(function(x, n) { var i, v = crypto2.randomBytes(n); for (i = 0; i < n; i++) x[i] = v[i]; cleanup(v); }); } } })(); })(typeof module !== "undefined" && module.exports ? module.exports : self.nacl = self.nacl || {}); } }); // (disabled):buffer var require_buffer = __commonJS({ "(disabled):buffer"() { } }); // node_modules/js-sha256/src/sha256.js var require_sha256 = __commonJS({ "node_modules/js-sha256/src/sha256.js"(exports, module) { (function() { "use strict"; var ERROR = "input is invalid type"; var WINDOW = typeof window === "object"; var root = WINDOW ? window : {}; if (root.JS_SHA256_NO_WINDOW) { WINDOW = false; } var WEB_WORKER = !WINDOW && typeof self === "object"; var NODE_JS = !root.JS_SHA256_NO_NODE_JS && typeof process === "object" && process.versions && process.versions.node; if (NODE_JS) { root = global; } else if (WEB_WORKER) { root = self; } var COMMON_JS = !root.JS_SHA256_NO_COMMON_JS && typeof module === "object" && module.exports; var AMD = typeof define === "function" && define.amd; var ARRAY_BUFFER = !root.JS_SHA256_NO_ARRAY_BUFFER && typeof ArrayBuffer !== "undefined"; var HEX_CHARS = "0123456789abcdef".split(""); var EXTRA = [-2147483648, 8388608, 32768, 128]; var SHIFT = [24, 16, 8, 0]; var 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 ]; var OUTPUT_TYPES = ["hex", "array", "digest", "arrayBuffer"]; var blocks = []; if (root.JS_SHA256_NO_NODE_JS || !Array.isArray) { Array.isArray = function(obj) { return Object.prototype.toString.call(obj) === "[object Array]"; }; } if (ARRAY_BUFFER && (root.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) { ArrayBuffer.isView = function(obj) { return typeof obj === "object" && obj.buffer && obj.buffer.constructor === ArrayBuffer; }; } var createOutputMethod = function(outputType, is224) { return function(message2) { return new Sha256(is224, true).update(message2)[outputType](); }; }; var createMethod = function(is224) { var method = createOutputMethod("hex", is224); if (NODE_JS) { method = nodeWrap(method, is224); } method.create = function() { return new Sha256(is224); }; method.update = function(message2) { return method.create().update(message2); }; for (var i = 0; i < OUTPUT_TYPES.length; ++i) { var type = OUTPUT_TYPES[i]; method[type] = createOutputMethod(type, is224); } return method; }; var nodeWrap = function(method, is224) { var crypto2 = require_crypto(); var Buffer2 = require_buffer().Buffer; var algorithm = is224 ? "sha224" : "sha256"; var bufferFrom; if (Buffer2.from && !root.JS_SHA256_NO_BUFFER_FROM) { bufferFrom = Buffer2.from; } else { bufferFrom = function(message2) { return new Buffer2(message2); }; } var nodeMethod = function(message2) { if (typeof message2 === "string") { return crypto2.createHash(algorithm).update(message2, "utf8").digest("hex"); } else { if (message2 === null || message2 === void 0) { throw new Error(ERROR); } else if (message2.constructor === ArrayBuffer) { message2 = new Uint8Array(message2); } } if (Array.isArray(message2) || ArrayBuffer.isView(message2) || message2.constructor === Buffer2) { return crypto2.createHash(algorithm).update(bufferFrom(message2)).digest("hex"); } else { return method(message2); } }; return nodeMethod; }; var createHmacOutputMethod = function(outputType, is224) { return function(key, message2) { return new HmacSha256(key, is224, true).update(message2)[outputType](); }; }; var createHmacMethod = function(is224) { var method = createHmacOutputMethod("hex", is224); method.create = function(key) { return new HmacSha256(key, is224); }; method.update = function(key, message2) { return method.create(key).update(message2); }; for (var i = 0; i < OUTPUT_TYPES.length; ++i) { var type = OUTPUT_TYPES[i]; method[type] = createHmacOutputMethod(type, is224); } return method; }; function Sha256(is224, sharedMemory) { if (sharedMemory) { blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; this.blocks = blocks; } else { this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; } if (is224) { this.h0 = 3238371032; this.h1 = 914150663; this.h2 = 812702999; this.h3 = 4144912697; this.h4 = 4290775857; this.h5 = 1750603025; this.h6 = 1694076839; this.h7 = 3204075428; } else { this.h0 = 1779033703; this.h1 = 3144134277; this.h2 = 1013904242; this.h3 = 2773480762; this.h4 = 1359893119; this.h5 = 2600822924; this.h6 = 528734635; this.h7 = 1541459225; } this.block = this.start = this.bytes = this.hBytes = 0; this.finalized = this.hashed = false; this.first = true; this.is224 = is224; } Sha256.prototype.update = function(message2) { if (this.finalized) { return; } var notString, type = typeof message2; if (type !== "string") { if (type === "object") { if (message2 === null) { throw new Error(ERROR); } else if (ARRAY_BUFFER && message2.constructor === ArrayBuffer) { message2 = new Uint8Array(message2); } else if (!Array.isArray(message2)) { if (!ARRAY_BUFFER || !ArrayBuffer.isView(message2)) { throw new Error(ERROR); } } } else { throw new Error(ERROR); } notString = true; } var code, index = 0, i, length = message2.length, blocks2 = this.blocks; while (index < length) { if (this.hashed) { this.hashed = false; blocks2[0] = this.block; this.block = blocks2[16] = blocks2[1] = blocks2[2] = blocks2[3] = blocks2[4] = blocks2[5] = blocks2[6] = blocks2[7] = blocks2[8] = blocks2[9] = blocks2[10] = blocks2[11] = blocks2[12] = blocks2[13] = blocks2[14] = blocks2[15] = 0; } if (notString) { for (i = this.start; index < length && i < 64; ++index) { blocks2[i >>> 2] |= message2[index] << SHIFT[i++ & 3]; } } else { for (i = this.start; index < length && i < 64; ++index) { code = message2.charCodeAt(index); if (code < 128) { blocks2[i >>> 2] |= code << SHIFT[i++ & 3]; } else if (code < 2048) { blocks2[i >>> 2] |= (192 | code >>> 6) << SHIFT[i++ & 3]; blocks2[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; } else if (code < 55296 || code >= 57344) { blocks2[i >>> 2] |= (224 | code >>> 12) << SHIFT[i++ & 3]; blocks2[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i++ & 3]; blocks2[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; } else { code = 65536 + ((code & 1023) << 10 | message2.charCodeAt(++index) & 1023); blocks2[i >>> 2] |= (240 | code >>> 18) << SHIFT[i++ & 3]; blocks2[i >>> 2] |= (128 | code >>> 12 & 63) << SHIFT[i++ & 3]; blocks2[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i++ & 3]; blocks2[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; } } } this.lastByteIndex = i; this.bytes += i - this.start; if (i >= 64) { this.block = blocks2[16]; this.start = i - 64; this.hash(); this.hashed = true; } else { this.start = i; } } if (this.bytes > 4294967295) { this.hBytes += this.bytes / 4294967296 << 0; this.bytes = this.bytes % 4294967296; } return this; }; Sha256.prototype.finalize = function() { if (this.finalized) { return; } this.finalized = true; var blocks2 = this.blocks, i = this.lastByteIndex; blocks2[16] = this.block; blocks2[i >>> 2] |= EXTRA[i & 3]; this.block = blocks2[16]; if (i >= 56) { if (!this.hashed) { this.hash(); } blocks2[0] = this.block; blocks2[16] = blocks2[1] = blocks2[2] = blocks2[3] = blocks2[4] = blocks2[5] = blocks2[6] = blocks2[7] = blocks2[8] = blocks2[9] = blocks2[10] = blocks2[11] = blocks2[12] = blocks2[13] = blocks2[14] = blocks2[15] = 0; } blocks2[14] = this.hBytes << 3 | this.bytes >>> 29; blocks2[15] = this.bytes << 3; this.hash(); }; Sha256.prototype.hash = function() { var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f = this.h5, g = this.h6, h = this.h7, blocks2 = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc; for (j = 16; j < 64; ++j) { t1 = blocks2[j - 15]; s0 = (t1 >>> 7 | t1 << 25) ^ (t1 >>> 18 | t1 << 14) ^ t1 >>> 3; t1 = blocks2[j - 2]; s1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10; blocks2[j] = blocks2[j - 16] + s0 + blocks2[j - 7] + s1 << 0; } bc = b & c; for (j = 0; j < 64; j += 4) { if (this.first) { if (this.is224) { ab = 300032; t1 = blocks2[0] - 1413257819; h = t1 - 150054599 << 0; d = t1 + 24177077 << 0; } else { ab = 704751109; t1 = blocks2[0] - 210244248; h = t1 - 1521486534 << 0; d = t1 + 143694565 << 0; } this.first = false; } else { s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7); ab = a & b; maj = ab ^ a & c ^ bc; ch = e & f ^ ~e & g; t1 = h + s1 + ch + K[j] + blocks2[j]; t2 = s0 + maj; h = d + t1 << 0; d = t1 + t2 << 0; } s0 = (d >>> 2 | d << 30) ^ (d >>> 13 | d << 19) ^ (d >>> 22 | d << 10); s1 = (h >>> 6 | h << 26) ^ (h >>> 11 | h << 21) ^ (h >>> 25 | h << 7); da = d & a; maj = da ^ d & b ^ ab; ch = h & e ^ ~h & f; t1 = g + s1 + ch + K[j + 1] + blocks2[j + 1]; t2 = s0 + maj; g = c + t1 << 0; c = t1 + t2 << 0; s0 = (c >>> 2 | c << 30) ^ (c >>> 13 | c << 19) ^ (c >>> 22 | c << 10); s1 = (g >>> 6 | g << 26) ^ (g >>> 11 | g << 21) ^ (g >>> 25 | g << 7); cd = c & d; maj = cd ^ c & a ^ da; ch = g & h ^ ~g & e; t1 = f + s1 + ch + K[j + 2] + blocks2[j + 2]; t2 = s0 + maj; f = b + t1 << 0; b = t1 + t2 << 0; s0 = (b >>> 2 | b << 30) ^ (b >>> 13 | b << 19) ^ (b >>> 22 | b << 10); s1 = (f >>> 6 | f << 26) ^ (f >>> 11 | f << 21) ^ (f >>> 25 | f << 7); bc = b & c; maj = bc ^ b & d ^ cd; ch = f & g ^ ~f & h; t1 = e + s1 + ch + K[j + 3] + blocks2[j + 3]; t2 = s0 + maj; e = a + t1 << 0; a = t1 + t2 << 0; this.chromeBugWorkAround = true; } this.h0 = this.h0 + a << 0; this.h1 = this.h1 + b << 0; this.h2 = this.h2 + c << 0; this.h3 = this.h3 + d << 0; this.h4 = this.h4 + e << 0; this.h5 = this.h5 + f << 0; this.h6 = this.h6 + g << 0; this.h7 = this.h7 + h << 0; }; Sha256.prototype.hex = function() { this.finalize(); var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; var hex = HEX_CHARS[h0 >>> 28 & 15] + HEX_CHARS[h0 >>> 24 & 15] + HEX_CHARS[h0 >>> 20 & 15] + HEX_CHARS[h0 >>> 16 & 15] + HEX_CHARS[h0 >>> 12 & 15] + HEX_CHARS[h0 >>> 8 & 15] + HEX_CHARS[h0 >>> 4 & 15] + HEX_CHARS[h0 & 15] + HEX_CHARS[h1 >>> 28 & 15] + HEX_CHARS[h1 >>> 24 & 15] + HEX_CHARS[h1 >>> 20 & 15] + HEX_CHARS[h1 >>> 16 & 15] + HEX_CHARS[h1 >>> 12 & 15] + HEX_CHARS[h1 >>> 8 & 15] + HEX_CHARS[h1 >>> 4 & 15] + HEX_CHARS[h1 & 15] + HEX_CHARS[h2 >>> 28 & 15] + HEX_CHARS[h2 >>> 24 & 15] + HEX_CHARS[h2 >>> 20 & 15] + HEX_CHARS[h2 >>> 16 & 15] + HEX_CHARS[h2 >>> 12 & 15] + HEX_CHARS[h2 >>> 8 & 15] + HEX_CHARS[h2 >>> 4 & 15] + HEX_CHARS[h2 & 15] + HEX_CHARS[h3 >>> 28 & 15] + HEX_CHARS[h3 >>> 24 & 15] + HEX_CHARS[h3 >>> 20 & 15] + HEX_CHARS[h3 >>> 16 & 15] + HEX_CHARS[h3 >>> 12 & 15] + HEX_CHARS[h3 >>> 8 & 15] + HEX_CHARS[h3 >>> 4 & 15] + HEX_CHARS[h3 & 15] + HEX_CHARS[h4 >>> 28 & 15] + HEX_CHARS[h4 >>> 24 & 15] + HEX_CHARS[h4 >>> 20 & 15] + HEX_CHARS[h4 >>> 16 & 15] + HEX_CHARS[h4 >>> 12 & 15] + HEX_CHARS[h4 >>> 8 & 15] + HEX_CHARS[h4 >>> 4 & 15] + HEX_CHARS[h4 & 15] + HEX_CHARS[h5 >>> 28 & 15] + HEX_CHARS[h5 >>> 24 & 15] + HEX_CHARS[h5 >>> 20 & 15] + HEX_CHARS[h5 >>> 16 & 15] + HEX_CHARS[h5 >>> 12 & 15] + HEX_CHARS[h5 >>> 8 & 15] + HEX_CHARS[h5 >>> 4 & 15] + HEX_CHARS[h5 & 15] + HEX_CHARS[h6 >>> 28 & 15] + HEX_CHARS[h6 >>> 24 & 15] + HEX_CHARS[h6 >>> 20 & 15] + HEX_CHARS[h6 >>> 16 & 15] + HEX_CHARS[h6 >>> 12 & 15] + HEX_CHARS[h6 >>> 8 & 15] + HEX_CHARS[h6 >>> 4 & 15] + HEX_CHARS[h6 & 15]; if (!this.is224) { hex += HEX_CHARS[h7 >>> 28 & 15] + HEX_CHARS[h7 >>> 24 & 15] + HEX_CHARS[h7 >>> 20 & 15] + HEX_CHARS[h7 >>> 16 & 15] + HEX_CHARS[h7 >>> 12 & 15] + HEX_CHARS[h7 >>> 8 & 15] + HEX_CHARS[h7 >>> 4 & 15] + HEX_CHARS[h7 & 15]; } return hex; }; Sha256.prototype.toString = Sha256.prototype.hex; Sha256.prototype.digest = function() { this.finalize(); var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; var arr = [ h0 >>> 24 & 255, h0 >>> 16 & 255, h0 >>> 8 & 255, h0 & 255, h1 >>> 24 & 255, h1 >>> 16 & 255, h1 >>> 8 & 255, h1 & 255, h2 >>> 24 & 255, h2 >>> 16 & 255, h2 >>> 8 & 255, h2 & 255, h3 >>> 24 & 255, h3 >>> 16 & 255, h3 >>> 8 & 255, h3 & 255, h4 >>> 24 & 255, h4 >>> 16 & 255, h4 >>> 8 & 255, h4 & 255, h5 >>> 24 & 255, h5 >>> 16 & 255, h5 >>> 8 & 255, h5 & 255, h6 >>> 24 & 255, h6 >>> 16 & 255, h6 >>> 8 & 255, h6 & 255 ]; if (!this.is224) { arr.push(h7 >>> 24 & 255, h7 >>> 16 & 255, h7 >>> 8 & 255, h7 & 255); } return arr; }; Sha256.prototype.array = Sha256.prototype.digest; Sha256.prototype.arrayBuffer = function() { this.finalize(); var buffer = new ArrayBuffer(this.is224 ? 28 : 32); var dataView = new DataView(buffer); dataView.setUint32(0, this.h0); dataView.setUint32(4, this.h1); dataView.setUint32(8, this.h2); dataView.setUint32(12, this.h3); dataView.setUint32(16, this.h4); dataView.setUint32(20, this.h5); dataView.setUint32(24, this.h6); if (!this.is224) { dataView.setUint32(28, this.h7); } return buffer; }; function HmacSha256(key, is224, sharedMemory) { var i, type = typeof key; if (type === "string") { var bytes = [], length = key.length, index = 0, code; for (i = 0; i < length; ++i) { code = key.charCodeAt(i); if (code < 128) { bytes[index++] = code; } else if (code < 2048) { bytes[index++] = 192 | code >>> 6; bytes[index++] = 128 | code & 63; } else if (code < 55296 || code >= 57344) { bytes[index++] = 224 | code >>> 12; bytes[index++] = 128 | code >>> 6 & 63; bytes[index++] = 128 | code & 63; } else { code = 65536 + ((code & 1023) << 10 | key.charCodeAt(++i) & 1023); bytes[index++] = 240 | code >>> 18; bytes[index++] = 128 | code >>> 12 & 63; bytes[index++] = 128 | code >>> 6 & 63; bytes[index++] = 128 | code & 63; } } key = bytes; } else { if (type === "object") { if (key === null) { throw new Error(ERROR); } else if (ARRAY_BUFFER && key.constructor === ArrayBuffer) { key = new Uint8Array(key); } else if (!Array.isArray(key)) { if (!ARRAY_BUFFER || !ArrayBuffer.isView(key)) { throw new Error(ERROR); } } } else { throw new Error(ERROR); } } if (key.length > 64) { key = new Sha256(is224, true).update(key).array(); } var oKeyPad = [], iKeyPad = []; for (i = 0; i < 64; ++i) { var b = key[i] || 0; oKeyPad[i] = 92 ^ b; iKeyPad[i] = 54 ^ b; } Sha256.call(this, is224, sharedMemory); this.update(iKeyPad); this.oKeyPad = oKeyPad; this.inner = true; this.sharedMemory = sharedMemory; } HmacSha256.prototype = new Sha256(); HmacSha256.prototype.finalize = function() { Sha256.prototype.finalize.call(this); if (this.inner) { this.inner = false; var innerHash = this.array(); Sha256.call(this, this.is224, this.sharedMemory); this.update(this.oKeyPad); this.update(innerHash); Sha256.prototype.finalize.call(this); } }; var exports2 = createMethod(); exports2.sha256 = exports2; exports2.sha224 = createMethod(true); exports2.sha256.hmac = createHmacMethod(); exports2.sha224.hmac = createHmacMethod(true); if (COMMON_JS) { module.exports = exports2; } else { root.sha256 = exports2.sha256; root.sha224 = exports2.sha224; if (AMD) { define(function() { return exports2; }); } } })(); } }); // src/worker.js var import_tweetnacl = __toESM(require_nacl_fast()); var import_js_sha256 = __toESM(require_sha256()); import { connect } from "cloudflare:sockets"; // node_modules/jose/dist/browser/runtime/webcrypto.js var webcrypto_default = crypto; var isCryptoKey = (key) => key instanceof CryptoKey; // node_modules/jose/dist/browser/lib/buffer_utils.js var encoder = new TextEncoder(); var decoder = new TextDecoder(); var MAX_INT32 = 2 ** 32; function concat(...buffers) { const size = buffers.reduce((acc, { length }) => acc + length, 0); const buf = new Uint8Array(size); let i = 0; for (const buffer of buffers) { buf.set(buffer, i); i += buffer.length; } return buf; } // node_modules/jose/dist/browser/runtime/base64url.js var encodeBase64 = (input) => { let unencoded = input; if (typeof unencoded === "string") { unencoded = encoder.encode(unencoded); } const CHUNK_SIZE = 32768; const arr = []; for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) { arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE))); } return btoa(arr.join("")); }; var encode = (input) => { return encodeBase64(input).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); }; var decodeBase64 = (encoded) => { const binary = atob(encoded); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) { bytes[i] = binary.charCodeAt(i); } return bytes; }; var decode = (input) => { let encoded = input; if (encoded instanceof Uint8Array) { encoded = decoder.decode(encoded); } encoded = encoded.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""); try { return decodeBase64(encoded); } catch { throw new TypeError("The input to be decoded is not correctly encoded."); } }; // node_modules/jose/dist/browser/util/errors.js var JOSEError = class extends Error { constructor(message2, options) { super(message2, options); this.code = "ERR_JOSE_GENERIC"; this.name = this.constructor.name; Error.captureStackTrace?.(this, this.constructor); } }; JOSEError.code = "ERR_JOSE_GENERIC"; var JWTClaimValidationFailed = class extends JOSEError { constructor(message2, payload, claim = "unspecified", reason = "unspecified") { super(message2, { cause: { claim, reason, payload } }); this.code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; this.claim = claim; this.reason = reason; this.payload = payload; } }; JWTClaimValidationFailed.code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; var JWTExpired = class extends JOSEError { constructor(message2, payload, claim = "unspecified", reason = "unspecified") { super(message2, { cause: { claim, reason, payload } }); this.code = "ERR_JWT_EXPIRED"; this.claim = claim; this.reason = reason; this.payload = payload; } }; JWTExpired.code = "ERR_JWT_EXPIRED"; var JOSEAlgNotAllowed = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JOSE_ALG_NOT_ALLOWED"; } }; JOSEAlgNotAllowed.code = "ERR_JOSE_ALG_NOT_ALLOWED"; var JOSENotSupported = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JOSE_NOT_SUPPORTED"; } }; JOSENotSupported.code = "ERR_JOSE_NOT_SUPPORTED"; var JWEDecryptionFailed = class extends JOSEError { constructor(message2 = "decryption operation failed", options) { super(message2, options); this.code = "ERR_JWE_DECRYPTION_FAILED"; } }; JWEDecryptionFailed.code = "ERR_JWE_DECRYPTION_FAILED"; var JWEInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWE_INVALID"; } }; JWEInvalid.code = "ERR_JWE_INVALID"; var JWSInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWS_INVALID"; } }; JWSInvalid.code = "ERR_JWS_INVALID"; var JWTInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWT_INVALID"; } }; JWTInvalid.code = "ERR_JWT_INVALID"; var JWKInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWK_INVALID"; } }; JWKInvalid.code = "ERR_JWK_INVALID"; var JWKSInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWKS_INVALID"; } }; JWKSInvalid.code = "ERR_JWKS_INVALID"; var JWKSNoMatchingKey = class extends JOSEError { constructor(message2 = "no applicable key found in the JSON Web Key Set", options) { super(message2, options); this.code = "ERR_JWKS_NO_MATCHING_KEY"; } }; JWKSNoMatchingKey.code = "ERR_JWKS_NO_MATCHING_KEY"; var JWKSMultipleMatchingKeys = class extends JOSEError { constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) { super(message2, options); this.code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; } }; JWKSMultipleMatchingKeys.code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; var JWKSTimeout = class extends JOSEError { constructor(message2 = "request timed out", options) { super(message2, options); this.code = "ERR_JWKS_TIMEOUT"; } }; JWKSTimeout.code = "ERR_JWKS_TIMEOUT"; var JWSSignatureVerificationFailed = class extends JOSEError { constructor(message2 = "signature verification failed", options) { super(message2, options); this.code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; } }; JWSSignatureVerificationFailed.code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; // node_modules/jose/dist/browser/lib/crypto_key.js function unusable(name, prop = "algorithm.name") { return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); } function isAlgorithm(algorithm, name) { return algorithm.name === name; } function getHashLength(hash) { return parseInt(hash.name.slice(4), 10); } function getNamedCurve(alg) { switch (alg) { case "ES256": return "P-256"; case "ES384": return "P-384"; case "ES512": return "P-521"; default: throw new Error("unreachable"); } } function checkUsage(key, usages) { if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { let msg = "CryptoKey does not support this operation, its usages must include "; if (usages.length > 2) { const last = usages.pop(); msg += `one of ${usages.join(", ")}, or ${last}.`; } else if (usages.length === 2) { msg += `one of ${usages[0]} or ${usages[1]}.`; } else { msg += `${usages[0]}.`; } throw new TypeError(msg); } } function checkSigCryptoKey(key, alg, ...usages) { switch (alg) { case "HS256": case "HS384": case "HS512": { if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC"); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); break; } case "RS256": case "RS384": case "RS512": { if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5"); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); break; } case "PS256": case "PS384": case "PS512": { if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS"); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); break; } case "EdDSA": { if (key.algorithm.name !== "Ed25519" && key.algorithm.name !== "Ed448") { throw unusable("Ed25519 or Ed448"); } break; } case "ES256": case "ES384": case "ES512": { if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA"); const expected = getNamedCurve(alg); const actual = key.algorithm.namedCurve; if (actual !== expected) throw unusable(expected, "algorithm.namedCurve"); break; } default: throw new TypeError("CryptoKey does not support this operation"); } checkUsage(key, usages); } // node_modules/jose/dist/browser/lib/invalid_key_input.js function message(msg, actual, ...types2) { types2 = types2.filter(Boolean); if (types2.length > 2) { const last = types2.pop(); msg += `one of type ${types2.join(", ")}, or ${last}.`; } else if (types2.length === 2) { msg += `one of type ${types2[0]} or ${types2[1]}.`; } else { msg += `of type ${types2[0]}.`; } if (actual == null) { msg += ` Received ${actual}`; } else if (typeof actual === "function" && actual.name) { msg += ` Received function ${actual.name}`; } else if (typeof actual === "object" && actual != null) { if (actual.constructor?.name) { msg += ` Received an instance of ${actual.constructor.name}`; } } return msg; } var invalid_key_input_default = (actual, ...types2) => { return message("Key must be ", actual, ...types2); }; function withAlg(alg, actual, ...types2) { return message(`Key for the ${alg} algorithm must be `, actual, ...types2); } // node_modules/jose/dist/browser/runtime/is_key_like.js var is_key_like_default = (key) => { if (isCryptoKey(key)) { return true; } return key?.[Symbol.toStringTag] === "KeyObject"; }; var types = ["CryptoKey"]; // node_modules/jose/dist/browser/lib/is_disjoint.js var isDisjoint = (...headers) => { const sources = headers.filter(Boolean); if (sources.length === 0 || sources.length === 1) { return true; } let acc; for (const header of sources) { const parameters = Object.keys(header); if (!acc || acc.size === 0) { acc = new Set(parameters); continue; } for (const parameter of parameters) { if (acc.has(parameter)) { return false; } acc.add(parameter); } } return true; }; var is_disjoint_default = isDisjoint; // node_modules/jose/dist/browser/lib/is_object.js function isObjectLike(value) { return typeof value === "object" && value !== null; } function isObject(input) { if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") { return false; } if (Object.getPrototypeOf(input) === null) { return true; } let proto = input; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(input) === proto; } // node_modules/jose/dist/browser/runtime/check_key_length.js var check_key_length_default = (alg, key) => { if (alg.startsWith("RS") || alg.startsWith("PS")) { const { modulusLength } = key.algorithm; if (typeof modulusLength !== "number" || modulusLength < 2048) { throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); } } }; // node_modules/jose/dist/browser/lib/is_jwk.js function isJWK(key) { return isObject(key) && typeof key.kty === "string"; } function isPrivateJWK(key) { return key.kty !== "oct" && typeof key.d === "string"; } function isPublicJWK(key) { return key.kty !== "oct" && typeof key.d === "undefined"; } function isSecretJWK(key) { return isJWK(key) && key.kty === "oct" && typeof key.k === "string"; } // node_modules/jose/dist/browser/runtime/jwk_to_key.js function subtleMapping(jwk) { let algorithm; let keyUsages; switch (jwk.kty) { case "RSA": { switch (jwk.alg) { case "PS256": case "PS384": case "PS512": algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "RS256": case "RS384": case "RS512": algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "RSA-OAEP": case "RSA-OAEP-256": case "RSA-OAEP-384": case "RSA-OAEP-512": algorithm = { name: "RSA-OAEP", hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}` }; keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"]; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } case "EC": { switch (jwk.alg) { case "ES256": algorithm = { name: "ECDSA", namedCurve: "P-256" }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "ES384": algorithm = { name: "ECDSA", namedCurve: "P-384" }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "ES512": algorithm = { name: "ECDSA", namedCurve: "P-521" }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "ECDH-ES": case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": algorithm = { name: "ECDH", namedCurve: jwk.crv }; keyUsages = jwk.d ? ["deriveBits"] : []; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } case "OKP": { switch (jwk.alg) { case "EdDSA": algorithm = { name: jwk.crv }; keyUsages = jwk.d ? ["sign"] : ["verify"]; break; case "ECDH-ES": case "ECDH-ES+A128KW": case "ECDH-ES+A192KW": case "ECDH-ES+A256KW": algorithm = { name: jwk.crv }; keyUsages = jwk.d ? ["deriveBits"] : []; break; default: throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value'); } break; } default: throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value'); } return { algorithm, keyUsages }; } var parse = async (jwk) => { if (!jwk.alg) { throw new TypeError('"alg" argument is required when "jwk.alg" is not present'); } const { algorithm, keyUsages } = subtleMapping(jwk); const rest = [ algorithm, jwk.ext ?? false, jwk.key_ops ?? keyUsages ]; const keyData = { ...jwk }; delete keyData.alg; delete keyData.use; return webcrypto_default.subtle.importKey("jwk", keyData, ...rest); }; var jwk_to_key_default = parse; // node_modules/jose/dist/browser/runtime/normalize_key.js var exportKeyValue = (k) => decode(k); var privCache; var pubCache; var isKeyObject = (key) => { return key?.[Symbol.toStringTag] === "KeyObject"; }; var importAndCache = async (cache, key, jwk, alg, freeze = false) => { let cached = cache.get(key); if (cached?.[alg]) { return cached[alg]; } const cryptoKey = await jwk_to_key_default({ ...jwk, alg }); if (freeze) Object.freeze(key); if (!cached) { cache.set(key, { [alg]: cryptoKey }); } else { cached[alg] = cryptoKey; } return cryptoKey; }; var normalizePublicKey = (key, alg) => { if (isKeyObject(key)) { let jwk = key.export({ format: "jwk" }); delete jwk.d; delete jwk.dp; delete jwk.dq; delete jwk.p; delete jwk.q; delete jwk.qi; if (jwk.k) { return exportKeyValue(jwk.k); } pubCache || (pubCache = /* @__PURE__ */ new WeakMap()); return importAndCache(pubCache, key, jwk, alg); } if (isJWK(key)) { if (key.k) return decode(key.k); pubCache || (pubCache = /* @__PURE__ */ new WeakMap()); const cryptoKey = importAndCache(pubCache, key, key, alg, true); return cryptoKey; } return key; }; var normalizePrivateKey = (key, alg) => { if (isKeyObject(key)) { let jwk = key.export({ format: "jwk" }); if (jwk.k) { return exportKeyValue(jwk.k); } privCache || (privCache = /* @__PURE__ */ new WeakMap()); return importAndCache(privCache, key, jwk, alg); } if (isJWK(key)) { if (key.k) return decode(key.k); privCache || (privCache = /* @__PURE__ */ new WeakMap()); const cryptoKey = importAndCache(privCache, key, key, alg, true); return cryptoKey; } return key; }; var normalize_key_default = { normalizePublicKey, normalizePrivateKey }; // node_modules/jose/dist/browser/key/import.js async function importJWK(jwk, alg) { if (!isObject(jwk)) { throw new TypeError("JWK must be an object"); } alg || (alg = jwk.alg); switch (jwk.kty) { case "oct": if (typeof jwk.k !== "string" || !jwk.k) { throw new TypeError('missing "k" (Key Value) Parameter value'); } return decode(jwk.k); case "RSA": if (jwk.oth !== void 0) { throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported'); } case "EC": case "OKP": return jwk_to_key_default({ ...jwk, alg }); default: throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value'); } } // node_modules/jose/dist/browser/lib/check_key_type.js var tag = (key) => key?.[Symbol.toStringTag]; var jwkMatchesOp = (alg, key, usage) => { if (key.use !== void 0 && key.use !== "sig") { throw new TypeError("Invalid key for this operation, when present its use must be sig"); } if (key.key_ops !== void 0 && key.key_ops.includes?.(usage) !== true) { throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${usage}`); } if (key.alg !== void 0 && key.alg !== alg) { throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`); } return true; }; var symmetricTypeCheck = (alg, key, usage, allowJwk) => { if (key instanceof Uint8Array) return; if (allowJwk && isJWK(key)) { if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) return; throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`); } if (!is_key_like_default(key)) { throw new TypeError(withAlg(alg, key, ...types, "Uint8Array", allowJwk ? "JSON Web Key" : null)); } if (key.type !== "secret") { throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`); } }; var asymmetricTypeCheck = (alg, key, usage, allowJwk) => { if (allowJwk && isJWK(key)) { switch (usage) { case "sign": if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) return; throw new TypeError(`JSON Web Key for this operation be a private JWK`); case "verify": if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) return; throw new TypeError(`JSON Web Key for this operation be a public JWK`); } } if (!is_key_like_default(key)) { throw new TypeError(withAlg(alg, key, ...types, allowJwk ? "JSON Web Key" : null)); } if (key.type === "secret") { throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`); } if (usage === "sign" && key.type === "public") { throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`); } if (usage === "decrypt" && key.type === "public") { throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`); } if (key.algorithm && usage === "verify" && key.type === "private") { throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`); } if (key.algorithm && usage === "encrypt" && key.type === "private") { throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`); } }; function checkKeyType(allowJwk, alg, key, usage) { const symmetric = alg.startsWith("HS") || alg === "dir" || alg.startsWith("PBES2") || /^A\d{3}(?:GCM)?KW$/.test(alg); if (symmetric) { symmetricTypeCheck(alg, key, usage, allowJwk); } else { asymmetricTypeCheck(alg, key, usage, allowJwk); } } var check_key_type_default = checkKeyType.bind(void 0, false); var checkKeyTypeWithJwk = checkKeyType.bind(void 0, true); // node_modules/jose/dist/browser/lib/validate_crit.js function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) { throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); } if (!protectedHeader || protectedHeader.crit === void 0) { return /* @__PURE__ */ new Set(); } if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) { throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); } let recognized; if (recognizedOption !== void 0) { recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); } else { recognized = recognizedDefault; } for (const parameter of protectedHeader.crit) { if (!recognized.has(parameter)) { throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); } if (joseHeader[parameter] === void 0) { throw new Err(`Extension Header Parameter "${parameter}" is missing`); } if (recognized.get(parameter) && protectedHeader[parameter] === void 0) { throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); } } return new Set(protectedHeader.crit); } var validate_crit_default = validateCrit; // node_modules/jose/dist/browser/lib/validate_algorithms.js var validateAlgorithms = (option, algorithms) => { if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) { throw new TypeError(`"${option}" option must be an array of strings`); } if (!algorithms) { return void 0; } return new Set(algorithms); }; var validate_algorithms_default = validateAlgorithms; // node_modules/jose/dist/browser/runtime/subtle_dsa.js function subtleDsa(alg, algorithm) { const hash = `SHA-${alg.slice(-3)}`; switch (alg) { case "HS256": case "HS384": case "HS512": return { hash, name: "HMAC" }; case "PS256": case "PS384": case "PS512": return { hash, name: "RSA-PSS", saltLength: alg.slice(-3) >> 3 }; case "RS256": case "RS384": case "RS512": return { hash, name: "RSASSA-PKCS1-v1_5" }; case "ES256": case "ES384": case "ES512": return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve }; case "EdDSA": return { name: algorithm.name }; default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } } // node_modules/jose/dist/browser/runtime/get_sign_verify_key.js async function getCryptoKey(alg, key, usage) { if (usage === "sign") { key = await normalize_key_default.normalizePrivateKey(key, alg); } if (usage === "verify") { key = await normalize_key_default.normalizePublicKey(key, alg); } if (isCryptoKey(key)) { checkSigCryptoKey(key, alg, usage); return key; } if (key instanceof Uint8Array) { if (!alg.startsWith("HS")) { throw new TypeError(invalid_key_input_default(key, ...types)); } return webcrypto_default.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]); } throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array", "JSON Web Key")); } // node_modules/jose/dist/browser/runtime/verify.js var verify = async (alg, key, signature, data) => { const cryptoKey = await getCryptoKey(alg, key, "verify"); check_key_length_default(alg, cryptoKey); const algorithm = subtleDsa(alg, cryptoKey.algorithm); try { return await webcrypto_default.subtle.verify(algorithm, cryptoKey, signature, data); } catch { return false; } }; var verify_default = verify; // node_modules/jose/dist/browser/jws/flattened/verify.js async function flattenedVerify(jws, key, options) { if (!isObject(jws)) { throw new JWSInvalid("Flattened JWS must be an object"); } if (jws.protected === void 0 && jws.header === void 0) { throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members'); } if (jws.protected !== void 0 && typeof jws.protected !== "string") { throw new JWSInvalid("JWS Protected Header incorrect type"); } if (jws.payload === void 0) { throw new JWSInvalid("JWS Payload missing"); } if (typeof jws.signature !== "string") { throw new JWSInvalid("JWS Signature missing or incorrect type"); } if (jws.header !== void 0 && !isObject(jws.header)) { throw new JWSInvalid("JWS Unprotected Header incorrect type"); } let parsedProt = {}; if (jws.protected) { try { const protectedHeader = decode(jws.protected); parsedProt = JSON.parse(decoder.decode(protectedHeader)); } catch { throw new JWSInvalid("JWS Protected Header is invalid"); } } if (!is_disjoint_default(parsedProt, jws.header)) { throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); } const joseHeader = { ...parsedProt, ...jws.header }; const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader); let b64 = true; if (extensions.has("b64")) { b64 = parsedProt.b64; if (typeof b64 !== "boolean") { throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); } } const { alg } = joseHeader; if (typeof alg !== "string" || !alg) { throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); } const algorithms = options && validate_algorithms_default("algorithms", options.algorithms); if (algorithms && !algorithms.has(alg)) { throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed'); } if (b64) { if (typeof jws.payload !== "string") { throw new JWSInvalid("JWS Payload must be a string"); } } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) { throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance"); } let resolvedKey = false; if (typeof key === "function") { key = await key(parsedProt, jws); resolvedKey = true; checkKeyTypeWithJwk(alg, key, "verify"); if (isJWK(key)) { key = await importJWK(key, alg); } } else { checkKeyTypeWithJwk(alg, key, "verify"); } const data = concat(encoder.encode(jws.protected ?? ""), encoder.encode("."), typeof jws.payload === "string" ? encoder.encode(jws.payload) : jws.payload); let signature; try { signature = decode(jws.signature); } catch { throw new JWSInvalid("Failed to base64url decode the signature"); } const verified = await verify_default(alg, key, signature, data); if (!verified) { throw new JWSSignatureVerificationFailed(); } let payload; if (b64) { try { payload = decode(jws.payload); } catch { throw new JWSInvalid("Failed to base64url decode the payload"); } } else if (typeof jws.payload === "string") { payload = encoder.encode(jws.payload); } else { payload = jws.payload; } const result = { payload }; if (jws.protected !== void 0) { result.protectedHeader = parsedProt; } if (jws.header !== void 0) { result.unprotectedHeader = jws.header; } if (resolvedKey) { return { ...result, key }; } return result; } // node_modules/jose/dist/browser/jws/compact/verify.js async function compactVerify(jws, key, options) { if (jws instanceof Uint8Array) { jws = decoder.decode(jws); } if (typeof jws !== "string") { throw new JWSInvalid("Compact JWS must be a string or Uint8Array"); } const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split("."); if (length !== 3) { throw new JWSInvalid("Invalid Compact JWS"); } const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options); const result = { payload: verified.payload, protectedHeader: verified.protectedHeader }; if (typeof key === "function") { return { ...result, key: verified.key }; } return result; } // node_modules/jose/dist/browser/lib/epoch.js var epoch_default = (date) => Math.floor(date.getTime() / 1e3); // node_modules/jose/dist/browser/lib/secs.js var minute = 60; var hour = minute * 60; var day = hour * 24; var week = day * 7; var year = day * 365.25; var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; var secs_default = (str) => { const matched = REGEX.exec(str); if (!matched || matched[4] && matched[1]) { throw new TypeError("Invalid time period format"); } const value = parseFloat(matched[2]); const unit = matched[3].toLowerCase(); let numericDate; switch (unit) { case "sec": case "secs": case "second": case "seconds": case "s": numericDate = Math.round(value); break; case "minute": case "minutes": case "min": case "mins": case "m": numericDate = Math.round(value * minute); break; case "hour": case "hours": case "hr": case "hrs": case "h": numericDate = Math.round(value * hour); break; case "day": case "days": case "d": numericDate = Math.round(value * day); break; case "week": case "weeks": case "w": numericDate = Math.round(value * week); break; default: numericDate = Math.round(value * year); break; } if (matched[1] === "-" || matched[4] === "ago") { return -numericDate; } return numericDate; }; // node_modules/jose/dist/browser/lib/jwt_claims_set.js var normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, ""); var checkAudiencePresence = (audPayload, audOption) => { if (typeof audPayload === "string") { return audOption.includes(audPayload); } if (Array.isArray(audPayload)) { return audOption.some(Set.prototype.has.bind(new Set(audPayload))); } return false; }; var jwt_claims_set_default = (protectedHeader, encodedPayload, options = {}) => { let payload; try { payload = JSON.parse(decoder.decode(encodedPayload)); } catch { } if (!isObject(payload)) { throw new JWTInvalid("JWT Claims Set must be a top-level JSON object"); } const { typ } = options; if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) { throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed"); } const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options; const presenceCheck = [...requiredClaims]; if (maxTokenAge !== void 0) presenceCheck.push("iat"); if (audience !== void 0) presenceCheck.push("aud"); if (subject !== void 0) presenceCheck.push("sub"); if (issuer !== void 0) presenceCheck.push("iss"); for (const claim of new Set(presenceCheck.reverse())) { if (!(claim in payload)) { throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing"); } } if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) { throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed"); } if (subject && payload.sub !== subject) { throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed"); } if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) { throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed"); } let tolerance; switch (typeof options.clockTolerance) { case "string": tolerance = secs_default(options.clockTolerance); break; case "number": tolerance = options.clockTolerance; break; case "undefined": tolerance = 0; break; default: throw new TypeError("Invalid clockTolerance option type"); } const { currentDate } = options; const now = epoch_default(currentDate || /* @__PURE__ */ new Date()); if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") { throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid"); } if (payload.nbf !== void 0) { if (typeof payload.nbf !== "number") { throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid"); } if (payload.nbf > now + tolerance) { throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed"); } } if (payload.exp !== void 0) { if (typeof payload.exp !== "number") { throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid"); } if (payload.exp <= now - tolerance) { throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed"); } } if (maxTokenAge) { const age = now - payload.iat; const max = typeof maxTokenAge === "number" ? maxTokenAge : secs_default(maxTokenAge); if (age - tolerance > max) { throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed"); } if (age < 0 - tolerance) { throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed"); } } return payload; }; // node_modules/jose/dist/browser/jwt/verify.js async function jwtVerify(jwt, key, options) { const verified = await compactVerify(jwt, key, options); if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) { throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); } const payload = jwt_claims_set_default(verified.protectedHeader, verified.payload, options); const result = { payload, protectedHeader: verified.protectedHeader }; if (typeof key === "function") { return { ...result, key: verified.key }; } return result; } // node_modules/jose/dist/browser/runtime/sign.js var sign = async (alg, key, data) => { const cryptoKey = await getCryptoKey(alg, key, "sign"); check_key_length_default(alg, cryptoKey); const signature = await webcrypto_default.subtle.sign(subtleDsa(alg, cryptoKey.algorithm), cryptoKey, data); return new Uint8Array(signature); }; var sign_default = sign; // node_modules/jose/dist/browser/jws/flattened/sign.js var FlattenedSign = class { constructor(payload) { if (!(payload instanceof Uint8Array)) { throw new TypeError("payload must be an instance of Uint8Array"); } this._payload = payload; } setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError("setProtectedHeader can only be called once"); } this._protectedHeader = protectedHeader; return this; } setUnprotectedHeader(unprotectedHeader) { if (this._unprotectedHeader) { throw new TypeError("setUnprotectedHeader can only be called once"); } this._unprotectedHeader = unprotectedHeader; return this; } async sign(key, options) { if (!this._protectedHeader && !this._unprotectedHeader) { throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()"); } if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader)) { throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader }; const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this._protectedHeader, joseHeader); let b64 = true; if (extensions.has("b64")) { b64 = this._protectedHeader.b64; if (typeof b64 !== "boolean") { throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); } } const { alg } = joseHeader; if (typeof alg !== "string" || !alg) { throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); } checkKeyTypeWithJwk(alg, key, "sign"); let payload = this._payload; if (b64) { payload = encoder.encode(encode(payload)); } let protectedHeader; if (this._protectedHeader) { protectedHeader = encoder.encode(encode(JSON.stringify(this._protectedHeader))); } else { protectedHeader = encoder.encode(""); } const data = concat(protectedHeader, encoder.encode("."), payload); const signature = await sign_default(alg, key, data); const jws = { signature: encode(signature), payload: "" }; if (b64) { jws.payload = decoder.decode(payload); } if (this._unprotectedHeader) { jws.header = this._unprotectedHeader; } if (this._protectedHeader) { jws.protected = decoder.decode(protectedHeader); } return jws; } }; // node_modules/jose/dist/browser/jws/compact/sign.js var CompactSign = class { constructor(payload) { this._flattened = new FlattenedSign(payload); } setProtectedHeader(protectedHeader) { this._flattened.setProtectedHeader(protectedHeader); return this; } async sign(key, options) { const jws = await this._flattened.sign(key, options); if (jws.payload === void 0) { throw new TypeError("use the flattened module for creating JWS with b64: false"); } return `${jws.protected}.${jws.payload}.${jws.signature}`; } }; // node_modules/jose/dist/browser/jwt/produce.js function validateInput(label, input) { if (!Number.isFinite(input)) { throw new TypeError(`Invalid ${label} input`); } return input; } var ProduceJWT = class { constructor(payload = {}) { if (!isObject(payload)) { throw new TypeError("JWT Claims Set MUST be an object"); } this._payload = payload; } setIssuer(issuer) { this._payload = { ...this._payload, iss: issuer }; return this; } setSubject(subject) { this._payload = { ...this._payload, sub: subject }; return this; } setAudience(audience) { this._payload = { ...this._payload, aud: audience }; return this; } setJti(jwtId) { this._payload = { ...this._payload, jti: jwtId }; return this; } setNotBefore(input) { if (typeof input === "number") { this._payload = { ...this._payload, nbf: validateInput("setNotBefore", input) }; } else if (input instanceof Date) { this._payload = { ...this._payload, nbf: validateInput("setNotBefore", epoch_default(input)) }; } else { this._payload = { ...this._payload, nbf: epoch_default(/* @__PURE__ */ new Date()) + secs_default(input) }; } return this; } setExpirationTime(input) { if (typeof input === "number") { this._payload = { ...this._payload, exp: validateInput("setExpirationTime", input) }; } else if (input instanceof Date) { this._payload = { ...this._payload, exp: validateInput("setExpirationTime", epoch_default(input)) }; } else { this._payload = { ...this._payload, exp: epoch_default(/* @__PURE__ */ new Date()) + secs_default(input) }; } return this; } setIssuedAt(input) { if (typeof input === "undefined") { this._payload = { ...this._payload, iat: epoch_default(/* @__PURE__ */ new Date()) }; } else if (input instanceof Date) { this._payload = { ...this._payload, iat: validateInput("setIssuedAt", epoch_default(input)) }; } else if (typeof input === "string") { this._payload = { ...this._payload, iat: validateInput("setIssuedAt", epoch_default(/* @__PURE__ */ new Date()) + secs_default(input)) }; } else { this._payload = { ...this._payload, iat: validateInput("setIssuedAt", input) }; } return this; } }; // node_modules/jose/dist/browser/jwt/sign.js var SignJWT = class extends ProduceJWT { setProtectedHeader(protectedHeader) { this._protectedHeader = protectedHeader; return this; } async sign(key, options) { const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload))); sig.setProtectedHeader(this._protectedHeader); if (Array.isArray(this._protectedHeader?.crit) && this._protectedHeader.crit.includes("b64") && this._protectedHeader.b64 === false) { throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); } return sig.sign(key, options); } }; // src/worker.js var userID = "89b3cbba-e6ac-485a-9481-976a0415eab9"; var trojanPassword = `bpb-trojan`; var proxyIPs = ["bpb.yousef.isegaro.com"]; var defaultHttpPorts = ["80", "8080", "2052", "2082", "2086", "2095", "8880"]; var defaultHttpsPorts = ["443", "8443", "2053", "2083", "2087", "2096"]; var proxyIP = proxyIPs[Math.floor(Math.random() * proxyIPs.length)]; var dohURL = "https://cloudflare-dns.com/dns-query"; var hashPassword; var panelVersion = "2.7"; var worker_default = { /** * @param {import("@cloudflare/workers-types").Request} request * @param {{UUID: string, PROXYIP: string, DNS_RESOLVER_URL: string}} env * @param {import("@cloudflare/workers-types").ExecutionContext} ctx * @returns {Promise} */ async fetch(request, env) { try { userID = env.UUID || userID; proxyIP = env.PROXYIP || proxyIP; dohURL = env.DNS_RESOLVER_URL || dohURL; trojanPassword = env.TROJAN_PASS || trojanPassword; hashPassword = import_js_sha256.default.sha224(trojanPassword); if (!isValidUUID(userID)) throw new Error(`Invalid UUID: ${userID}`); const upgradeHeader = request.headers.get("Upgrade"); const url = new URL(request.url); if (!upgradeHeader || upgradeHeader !== "websocket") { const searchParams = new URLSearchParams(url.search); const host = request.headers.get("Host"); const client = searchParams.get("app"); const { kvNotFound, proxySettings: settings, warpConfigs } = await getDataset(env); if (kvNotFound) { const errorPage = renderErrorPage("KV Dataset is not properly set!", null, true); return new Response(errorPage, { status: 200, headers: { "Content-Type": "text/html" } }); } switch (url.pathname) { case "/cf": return new Response(JSON.stringify(request.cf, null, 4), { status: 200, headers: { "Content-Type": "application/json;charset=utf-8" } }); case "/update-warp": const Auth = await Authenticate(request, env); if (!Auth) return new Response("Unauthorized", { status: 401 }); if (request.method === "POST") { try { const { error: warpPlusError } = await fetchWgConfig(env, settings); if (warpPlusError) { return new Response(warpPlusError, { status: 400 }); } else { return new Response("Warp configs updated successfully", { status: 200 }); } } catch (error) { console.log(error); return new Response(`An error occurred while updating Warp configs! - ${error}`, { status: 500 }); } } else { return new Response("Unsupported request", { status: 405 }); } case `/sub/${userID}`: if (client === "sfa") { const BestPingSFA = await getSingBoxCustomConfig(env, settings, host, client, false); return new Response(JSON.stringify(BestPingSFA, null, 4), { status: 200, headers: { "Content-Type": "application/json;charset=utf-8", "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate", "CDN-Cache-Control": "no-store" } }); } if (client === "clash") { const BestPingClash = await getClashNormalConfig(env, settings, host); return new Response(JSON.stringify(BestPingClash, null, 4), { status: 200, headers: { "Content-Type": "application/json;charset=utf-8", "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate", "CDN-Cache-Control": "no-store" } }); } if (client === "xray") { const xrayFullConfigs = await getXrayCustomConfigs(env, settings, host, false); return new Response(JSON.stringify(xrayFullConfigs, null, 4), { status: 200, headers: { "Content-Type": "application/json;charset=utf-8", "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate", "CDN-Cache-Control": "no-store" } }); } const normalConfigs = await getNormalConfigs(settings, host, client); return new Response(normalConfigs, { status: 200, headers: { "Content-Type": "text/plain;charset=utf-8", "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate", "CDN-Cache-Control": "no-store" } }); case `/fragsub/${userID}`: let fragConfigs = client === "hiddify" ? await getSingBoxCustomConfig(env, settings, host, client, true) : await getXrayCustomConfigs(env, settings, host, true); return new Response(JSON.stringify(fragConfigs, null, 4), { status: 200, headers: { "Content-Type": "application/json;charset=utf-8", "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate", "CDN-Cache-Control": "no-store" } }); case `/warpsub/${userID}`: if (client === "clash") { const clashWarpConfig = await getClashWarpConfig(settings, warpConfigs); return new Response(JSON.stringify(clashWarpConfig, null, 4), { status: 200, headers: { "Content-Type": "application/json;charset=utf-8", "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate", "CDN-Cache-Control": "no-store" } }); } if (client === "singbox" || client === "hiddify") { const singboxWarpConfig = await getSingBoxWarpConfig(settings, warpConfigs, client); return new Response(JSON.stringify(singboxWarpConfig, null, 4), { status: 200, headers: { "Content-Type": "application/json;charset=utf-8", "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate", "CDN-Cache-Control": "no-store" } }); } const warpConfig = await getXrayWarpConfigs(settings, warpConfigs, client); return new Response(JSON.stringify(warpConfig, null, 4), { status: 200, headers: { "Content-Type": "application/json;charset=utf-8", "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate", "CDN-Cache-Control": "no-store" } }); case "/panel": const pwd = await env.bpb.get("pwd"); const isAuth = await Authenticate(request, env); if (request.method === "POST") { if (!isAuth) return new Response("Unauthorized or expired session!", { status: 401 }); const formData = await request.formData(); const isReset = formData.get("resetSettings") === "true"; isReset ? await updateDataset(env, null, true) : await updateDataset(env, formData); return new Response("Success", { status: 200 }); } if (pwd && !isAuth) return Response.redirect(`${url.origin}/login`, 302); const isPassSet = pwd?.length >= 8; const homePage = renderHomePage(settings, host, isPassSet); return new Response(homePage, { status: 200, headers: { "Content-Type": "text/html", "Access-Control-Allow-Origin": url.origin, "Access-Control-Allow-Methods": "GET, POST", "Access-Control-Allow-Headers": "Content-Type, Authorization", "X-Content-Type-Options": "nosniff", "X-Frame-Options": "DENY", "Referrer-Policy": "strict-origin-when-cross-origin" } }); case "/login": if (typeof env.bpb !== "object") { const errorPage = renderErrorPage("KV Dataset is not properly set!", null, true); return new Response(errorPage, { status: 200, headers: { "Content-Type": "text/html" } }); } const loginAuth = await Authenticate(request, env); if (loginAuth) return Response.redirect(`${url.origin}/panel`, 302); let secretKey = await env.bpb.get("secretKey"); if (!secretKey) { secretKey = generateSecretKey(); await env.bpb.put("secretKey", secretKey); } if (request.method === "POST") { const password = await request.text(); const savedPass = await env.bpb.get("pwd"); if (password === savedPass) { const jwtToken = await generateJWTToken(secretKey); const cookieHeader = `jwtToken=${jwtToken}; HttpOnly; Secure; Max-Age=${7 * 24 * 60 * 60}; Path=/; SameSite=Strict`; return new Response("Success", { status: 200, headers: { "Set-Cookie": cookieHeader, "Content-Type": "text/plain" } }); } else { return new Response("Method Not Allowed", { status: 405 }); } } const loginPage = renderLoginPage(); return new Response(loginPage, { status: 200, headers: { "Content-Type": "text/html", "Access-Control-Allow-Origin": url.origin, "Access-Control-Allow-Methods": "GET, POST", "Access-Control-Allow-Headers": "Content-Type, Authorization", "X-Content-Type-Options": "nosniff", "X-Frame-Options": "DENY", "Referrer-Policy": "strict-origin-when-cross-origin" } }); case "/logout": return new Response("Success", { status: 200, headers: { "Set-Cookie": "jwtToken=; Secure; SameSite=None; Expires=Thu, 01 Jan 1970 00:00:00 GMT", "Content-Type": "text/plain" } }); case "/panel/password": const oldPwd = await env.bpb.get("pwd"); let passAuth = await Authenticate(request, env); if (oldPwd && !passAuth) return new Response("Unauthorized!", { status: 401 }); const newPwd = await request.text(); if (newPwd === oldPwd) return new Response("Please enter a new Password!", { status: 400 }); await env.bpb.put("pwd", newPwd); return new Response("Success", { status: 200, headers: { "Set-Cookie": "jwtToken=; Path=/; Secure; SameSite=None; Expires=Thu, 01 Jan 1970 00:00:00 GMT", "Content-Type": "text/plain" } }); default: url.hostname = "www.speedtest.net"; url.protocol = "https:"; request = new Request(url, request); return await fetch(request); } } else { return url.pathname.startsWith("/tr") ? await trojanOverWSHandler(request) : await vlessOverWSHandler(request); } } catch (err) { const errorPage = renderErrorPage("Something went wrong!", err, false); return new Response(errorPage, { status: 200, headers: { "Content-Type": "text/html" } }); } } }; async function vlessOverWSHandler(request) { const webSocketPair = new WebSocketPair(); const [client, webSocket] = Object.values(webSocketPair); webSocket.accept(); let address = ""; let portWithRandomLog = ""; const log = (info, event) => { console.log(`[${address}:${portWithRandomLog}] ${info}`, event || ""); }; const earlyDataHeader = request.headers.get("sec-websocket-protocol") || ""; const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log); let remoteSocketWapper = { value: null }; let udpStreamWrite = null; let isDns = false; readableWebSocketStream.pipeTo( new WritableStream({ async write(chunk, controller) { if (isDns && udpStreamWrite) { return udpStreamWrite(chunk); } if (remoteSocketWapper.value) { const writer = remoteSocketWapper.value.writable.getWriter(); await writer.write(chunk); writer.releaseLock(); return; } const { hasError, message: message2, portRemote = 443, addressRemote = "", rawDataIndex, vlessVersion = new Uint8Array([0, 0]), isUDP } = await processVlessHeader(chunk, userID); address = addressRemote; portWithRandomLog = `${portRemote}--${Math.random()} ${isUDP ? "udp " : "tcp "} `; if (hasError) { throw new Error(message2); return; } if (isUDP) { if (portRemote === 53) { isDns = true; } else { throw new Error("UDP proxy only enable for DNS which is port 53"); return; } } const vlessResponseHeader = new Uint8Array([vlessVersion[0], 0]); const rawClientData = chunk.slice(rawDataIndex); if (isDns) { const { write } = await handleUDPOutBound(webSocket, vlessResponseHeader, log); udpStreamWrite = write; udpStreamWrite(rawClientData); return; } handleTCPOutBound( request, remoteSocketWapper, addressRemote, portRemote, rawClientData, webSocket, vlessResponseHeader, log ); }, close() { log(`readableWebSocketStream is close`); }, abort(reason) { log(`readableWebSocketStream is abort`, JSON.stringify(reason)); } }) ).catch((err) => { log("readableWebSocketStream pipeTo error", err); }); return new Response(null, { status: 101, // @ts-ignore webSocket: client }); } async function checkUuidInApiResponse(targetUuid) { try { const apiResponse = await getApiResponse(); if (!apiResponse) { return false; } const isUuidInResponse = apiResponse.users.some((user) => user.uuid === targetUuid); return isUuidInResponse; } catch (error) { console.error("Error:", error); return false; } } async function trojanOverWSHandler(request) { const webSocketPair = new WebSocketPair(); const [client, webSocket] = Object.values(webSocketPair); webSocket.accept(); let address = ""; let portWithRandomLog = ""; const log = (info, event) => { console.log(`[${address}:${portWithRandomLog}] ${info}`, event || ""); }; const earlyDataHeader = request.headers.get("sec-websocket-protocol") || ""; const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log); let remoteSocketWapper = { value: null }; let udpStreamWrite = null; readableWebSocketStream.pipeTo( new WritableStream({ async write(chunk, controller) { if (udpStreamWrite) { return udpStreamWrite(chunk); } if (remoteSocketWapper.value) { const writer = remoteSocketWapper.value.writable.getWriter(); await writer.write(chunk); writer.releaseLock(); return; } const { hasError, message: message2, portRemote = 443, addressRemote = "", rawClientData } = await parseTrojanHeader(chunk); address = addressRemote; portWithRandomLog = `${portRemote}--${Math.random()} tcp`; if (hasError) { throw new Error(message2); return; } handleTCPOutBound(request, remoteSocketWapper, addressRemote, portRemote, rawClientData, webSocket, false, log); }, close() { log(`readableWebSocketStream is closed`); }, abort(reason) { log(`readableWebSocketStream is aborted`, JSON.stringify(reason)); } }) ).catch((err) => { log("readableWebSocketStream pipeTo error", err); }); return new Response(null, { status: 101, // @ts-ignore webSocket: client }); } async function parseTrojanHeader(buffer) { if (buffer.byteLength < 56) { return { hasError: true, message: "invalid data" }; } let crLfIndex = 56; if (new Uint8Array(buffer.slice(56, 57))[0] !== 13 || new Uint8Array(buffer.slice(57, 58))[0] !== 10) { return { hasError: true, message: "invalid header format (missing CR LF)" }; } const password = new TextDecoder().decode(buffer.slice(0, crLfIndex)); if (password !== hashPassword) { return { hasError: true, message: "invalid password" }; } const socks5DataBuffer = buffer.slice(crLfIndex + 2); if (socks5DataBuffer.byteLength < 6) { return { hasError: true, message: "invalid SOCKS5 request data" }; } const view = new DataView(socks5DataBuffer); const cmd = view.getUint8(0); if (cmd !== 1) { return { hasError: true, message: "unsupported command, only TCP (CONNECT) is allowed" }; } const atype = view.getUint8(1); let addressLength = 0; let addressIndex = 2; let address = ""; switch (atype) { case 1: addressLength = 4; address = new Uint8Array(socks5DataBuffer.slice(addressIndex, addressIndex + addressLength)).join("."); break; case 3: addressLength = new Uint8Array(socks5DataBuffer.slice(addressIndex, addressIndex + 1))[0]; addressIndex += 1; address = new TextDecoder().decode(socks5DataBuffer.slice(addressIndex, addressIndex + addressLength)); break; case 4: addressLength = 16; const dataView = new DataView(socks5DataBuffer.slice(addressIndex, addressIndex + addressLength)); const ipv6 = []; for (let i = 0; i < 8; i++) { ipv6.push(dataView.getUint16(i * 2).toString(16)); } address = ipv6.join(":"); break; default: return { hasError: true, message: `invalid addressType is ${atype}` }; } if (!address) { return { hasError: true, message: `address is empty, addressType is ${atype}` }; } const portIndex = addressIndex + addressLength; const portBuffer = socks5DataBuffer.slice(portIndex, portIndex + 2); const portRemote = new DataView(portBuffer).getUint16(0); return { hasError: false, addressRemote: address, portRemote, rawClientData: socks5DataBuffer.slice(portIndex + 4) }; } async function handleTCPOutBound(request, remoteSocket, addressRemote, portRemote, rawClientData, webSocket, vlessResponseHeader, log) { async function connectAndWrite(address, port) { if (/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(address)) address = `${atob("d3d3Lg==")}${address}${atob("LnNzbGlwLmlv")}`; const tcpSocket2 = connect({ hostname: address, port }); remoteSocket.value = tcpSocket2; log(`connected to ${address}:${port}`); const writer = tcpSocket2.writable.getWriter(); await writer.write(rawClientData); writer.releaseLock(); return tcpSocket2; } async function retry() { const { pathname } = new URL(request.url); let panelProxyIP = pathname.split("/")[2]; panelProxyIP = panelProxyIP ? atob(panelProxyIP) : void 0; const tcpSocket2 = await connectAndWrite(panelProxyIP || proxyIP || addressRemote, portRemote); tcpSocket2.closed.catch((error) => { console.log("retry tcpSocket closed error", error); }).finally(() => { safeCloseWebSocket(webSocket); }); vlessResponseHeader ? vlessRemoteSocketToWS(tcpSocket2, webSocket, vlessResponseHeader, null, log) : trojanRemoteSocketToWS(tcpSocket2, webSocket, null, log); } const tcpSocket = await connectAndWrite(addressRemote, portRemote); vlessResponseHeader ? vlessRemoteSocketToWS(tcpSocket, webSocket, vlessResponseHeader, retry, log) : trojanRemoteSocketToWS(tcpSocket, webSocket, retry, log); } function makeReadableWebSocketStream(webSocketServer, earlyDataHeader, log) { let readableStreamCancel = false; const stream = new ReadableStream({ start(controller) { webSocketServer.addEventListener("message", (event) => { if (readableStreamCancel) { return; } const message2 = event.data; controller.enqueue(message2); }); webSocketServer.addEventListener("close", () => { safeCloseWebSocket(webSocketServer); if (readableStreamCancel) { return; } controller.close(); }); webSocketServer.addEventListener("error", (err) => { log("webSocketServer has error"); controller.error(err); }); const { earlyData, error } = base64ToArrayBuffer(earlyDataHeader); if (error) { controller.error(error); } else if (earlyData) { controller.enqueue(earlyData); } }, pull(controller) { }, cancel(reason) { if (readableStreamCancel) { return; } log(`ReadableStream was canceled, due to ${reason}`); readableStreamCancel = true; safeCloseWebSocket(webSocketServer); } }); return stream; } async function processVlessHeader(vlessBuffer, userID2) { if (vlessBuffer.byteLength < 24) { return { hasError: true, message: "invalid data" }; } const version = new Uint8Array(vlessBuffer.slice(0, 1)); let isValidUser = false; let isUDP = false; const slicedBuffer = new Uint8Array(vlessBuffer.slice(1, 17)); const slicedBufferString = stringify(slicedBuffer); const uuids = userID2.includes(",") ? userID2.split(",") : [userID2]; const checkUuidInApi = await checkUuidInApiResponse(slicedBufferString); isValidUser = uuids.some((userUuid) => checkUuidInApi || slicedBufferString === userUuid.trim()); console.log(`checkUuidInApi: ${await checkUuidInApiResponse(slicedBufferString)}, userID: ${slicedBufferString}`); if (!isValidUser) { return { hasError: true, message: "invalid user" }; } const optLength = new Uint8Array(vlessBuffer.slice(17, 18))[0]; const command = new Uint8Array(vlessBuffer.slice(18 + optLength, 18 + optLength + 1))[0]; if (command === 1) { } else if (command === 2) { isUDP = true; } else { return { hasError: true, message: `command ${command} is not support, command 01-tcp,02-udp,03-mux` }; } const portIndex = 18 + optLength + 1; const portBuffer = vlessBuffer.slice(portIndex, portIndex + 2); const portRemote = new DataView(portBuffer).getUint16(0); let addressIndex = portIndex + 2; const addressBuffer = new Uint8Array(vlessBuffer.slice(addressIndex, addressIndex + 1)); const addressType = addressBuffer[0]; let addressLength = 0; let addressValueIndex = addressIndex + 1; let addressValue = ""; switch (addressType) { case 1: addressLength = 4; addressValue = new Uint8Array(vlessBuffer.slice(addressValueIndex, addressValueIndex + addressLength)).join("."); break; case 2: addressLength = new Uint8Array(vlessBuffer.slice(addressValueIndex, addressValueIndex + 1))[0]; addressValueIndex += 1; addressValue = new TextDecoder().decode(vlessBuffer.slice(addressValueIndex, addressValueIndex + addressLength)); break; case 3: addressLength = 16; const dataView = new DataView(vlessBuffer.slice(addressValueIndex, addressValueIndex + addressLength)); const ipv6 = []; for (let i = 0; i < 8; i++) { ipv6.push(dataView.getUint16(i * 2).toString(16)); } addressValue = ipv6.join(":"); break; default: return { hasError: true, message: `invild addressType is ${addressType}` }; } if (!addressValue) { return { hasError: true, message: `addressValue is empty, addressType is ${addressType}` }; } return { hasError: false, addressRemote: addressValue, addressType, portRemote, rawDataIndex: addressValueIndex + addressLength, vlessVersion: version, isUDP }; } async function vlessRemoteSocketToWS(remoteSocket, webSocket, vlessResponseHeader, retry, log) { let remoteChunkCount = 0; let chunks = []; let vlessHeader = vlessResponseHeader; let hasIncomingData = false; await remoteSocket.readable.pipeTo( new WritableStream({ start() { }, /** * * @param {Uint8Array} chunk * @param {*} controller */ async write(chunk, controller) { hasIncomingData = true; if (webSocket.readyState !== WS_READY_STATE_OPEN) { controller.error("webSocket.readyState is not open, maybe close"); } if (vlessHeader) { webSocket.send(await new Blob([vlessHeader, chunk]).arrayBuffer()); vlessHeader = null; } else { webSocket.send(chunk); } }, close() { log(`remoteConnection!.readable is close with hasIncomingData is ${hasIncomingData}`); }, abort(reason) { console.error(`remoteConnection!.readable abort`, reason); } }) ).catch((error) => { console.error(`vlessRemoteSocketToWS has exception `, error.stack || error); safeCloseWebSocket(webSocket); }); if (hasIncomingData === false && retry) { log(`retry`); retry(); } } async function trojanRemoteSocketToWS(remoteSocket, webSocket, retry, log) { let hasIncomingData = false; await remoteSocket.readable.pipeTo( new WritableStream({ start() { }, /** * * @param {Uint8Array} chunk * @param {*} controller */ async write(chunk, controller) { hasIncomingData = true; if (webSocket.readyState !== WS_READY_STATE_OPEN) { controller.error("webSocket connection is not open"); } webSocket.send(chunk); }, close() { log(`remoteSocket.readable is closed, hasIncomingData: ${hasIncomingData}`); }, abort(reason) { console.error("remoteSocket.readable abort", reason); } }) ).catch((error) => { console.error(`trojanRemoteSocketToWS error:`, error.stack || error); safeCloseWebSocket(webSocket); }); if (hasIncomingData === false && retry) { log(`retry`); retry(); } } function base64ToArrayBuffer(base64Str) { if (!base64Str) { return { earlyData: null, error: null }; } try { base64Str = base64Str.replace(/-/g, "+").replace(/_/g, "/"); const decode2 = atob(base64Str); const arryBuffer = Uint8Array.from(decode2, (c) => c.charCodeAt(0)); return { earlyData: arryBuffer.buffer, error: null }; } catch (error) { return { earlyData: null, error }; } } function isValidUUID(uuid) { const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; return uuidRegex.test(uuid); } var WS_READY_STATE_OPEN = 1; var WS_READY_STATE_CLOSING = 2; function safeCloseWebSocket(socket) { try { if (socket.readyState === WS_READY_STATE_OPEN || socket.readyState === WS_READY_STATE_CLOSING) { socket.close(); } } catch (error) { console.error("safeCloseWebSocket error", error); } } var byteToHex = []; for (let i = 0; i < 256; ++i) { byteToHex.push((i + 256).toString(16).slice(1)); } function unsafeStringify(arr, offset = 0) { return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); } function stringify(arr, offset = 0) { const uuid = unsafeStringify(arr, offset); if (!isValidUUID(uuid)) { throw TypeError("Stringified UUID is invalid"); } return uuid; } async function handleUDPOutBound(webSocket, vlessResponseHeader, log) { let isVlessHeaderSent = false; const transformStream = new TransformStream({ start(controller) { }, transform(chunk, controller) { for (let index = 0; index < chunk.byteLength; ) { const lengthBuffer = chunk.slice(index, index + 2); const udpPakcetLength = new DataView(lengthBuffer).getUint16(0); const udpData = new Uint8Array(chunk.slice(index + 2, index + 2 + udpPakcetLength)); index = index + 2 + udpPakcetLength; controller.enqueue(udpData); } }, flush(controller) { } }); transformStream.readable.pipeTo( new WritableStream({ async write(chunk) { const resp = await fetch( dohURL, // dns server url { method: "POST", headers: { "content-type": "application/dns-message" }, body: chunk } ); const dnsQueryResult = await resp.arrayBuffer(); const udpSize = dnsQueryResult.byteLength; const udpSizeBuffer = new Uint8Array([udpSize >> 8 & 255, udpSize & 255]); if (webSocket.readyState === WS_READY_STATE_OPEN) { log(`doh success and dns message length is ${udpSize}`); if (isVlessHeaderSent) { webSocket.send(await new Blob([udpSizeBuffer, dnsQueryResult]).arrayBuffer()); } else { webSocket.send(await new Blob([vlessResponseHeader, udpSizeBuffer, dnsQueryResult]).arrayBuffer()); isVlessHeaderSent = true; } } } }) ).catch((error) => { log("dns udp has error" + error); }); const writer = transformStream.writable.getWriter(); return { /** * * @param {Uint8Array} chunk */ write(chunk) { writer.write(chunk); } }; } var generateKeyPair = () => { const base64Encode = (array) => btoa(String.fromCharCode.apply(null, array)); let privateKey = import_tweetnacl.default.randomBytes(32); privateKey[0] &= 248; privateKey[31] &= 127; privateKey[31] |= 64; let publicKey = import_tweetnacl.default.scalarMult.base(privateKey); const publicKeyBase64 = base64Encode(publicKey); const privateKeyBase64 = base64Encode(privateKey); return { publicKey: publicKeyBase64, privateKey: privateKeyBase64 }; }; function generateRemark(index, port, address, cleanIPs, protocol, configType) { let remark = ""; let addressType; const type = configType ? ` ${configType}` : ""; cleanIPs.includes(address) ? addressType = "Clean IP" : addressType = isDomain(address) ? "Domain" : isIPv4(address) ? "IPv4" : isIPv6(address) ? "IPv6" : ""; return `\u{1F4A6} ${index} - ${protocol}${type} - ${addressType} : ${port}`; } function isDomain(address) { const domainPattern = /^(?!\-)(?:[A-Za-z0-9\-]{1,63}\.?)+[A-Za-z]{2,}$/; return domainPattern.test(address); } function isIPv4(address) { const ipv4Pattern = /^(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/; return ipv4Pattern.test(address); } function isIPv6(address) { const ipv6Pattern = /^\[(?:(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}|(?:[a-fA-F0-9]{1,4}:){1,7}:|::(?:[a-fA-F0-9]{1,4}:){0,7}|(?:[a-fA-F0-9]{1,4}:){1,6}:[a-fA-F0-9]{1,4}|(?:[a-fA-F0-9]{1,4}:){1,5}(?::[a-fA-F0-9]{1,4}){1,2}|(?:[a-fA-F0-9]{1,4}:){1,4}(?::[a-fA-F0-9]{1,4}){1,3}|(?:[a-fA-F0-9]{1,4}:){1,3}(?::[a-fA-F0-9]{1,4}){1,4}|(?:[a-fA-F0-9]{1,4}:){1,2}(?::[a-fA-F0-9]{1,4}){1,5}|[a-fA-F0-9]{1,4}:(?::[a-fA-F0-9]{1,4}){1,6})\]$/; return ipv6Pattern.test(address); } function base64ToDecimal(base64) { const binaryString = atob(base64); const hexString = Array.from(binaryString).map((char) => char.charCodeAt(0).toString(16).padStart(2, "0")).join(""); const decimalArray = hexString.match(/.{2}/g).map((hex) => parseInt(hex, 16)); return decimalArray; } async function getDataset(env) { let proxySettings, warpConfigs; if (typeof env.bpb !== "object") { return { kvNotFound: true, proxySettings: null, warpConfigs: null }; } try { proxySettings = await env.bpb.get("proxySettings", { type: "json" }); warpConfigs = await env.bpb.get("warpConfigs", { type: "json" }); } catch (error) { console.log(error); throw new Error(`An error occurred while getting KV - ${error}`); } if (!proxySettings) { proxySettings = await updateDataset(env); const { error, configs } = await fetchWgConfig(env, proxySettings); if (error) throw new Error(`An error occurred while getting Warp configs - ${error}`); warpConfigs = configs; } if (panelVersion !== proxySettings.panelVersion) proxySettings = await updateDataset(env); return { kvNotFound: false, proxySettings, warpConfigs }; } async function updateDataset(env, newSettings, resetSettings) { let currentSettings; if (!resetSettings) { try { currentSettings = await env.bpb.get("proxySettings", { type: "json" }); } catch (error) { console.log(error); throw new Error(`An error occurred while getting current KV settings - ${error}`); } } else { await env.bpb.delete("warpConfigs"); } const validateField = (field) => { const fieldValue = newSettings?.get(field); if (fieldValue === void 0) return null; if (fieldValue === "true") return true; if (fieldValue === "false") return false; return fieldValue; }; const remoteDNS = validateField("remoteDNS") ?? currentSettings?.remoteDNS ?? "https://8.8.8.8/dns-query"; const url = new URL(remoteDNS); const remoteDNSServer = url.hostname; const isServerDomain = isDomain(remoteDNSServer); let resolvedRemoteDNS; if (isServerDomain) { try { const resolvedDomain = await resolveDNS(remoteDNSServer); resolvedRemoteDNS = { server: remoteDNSServer, staticIPs: [...resolvedDomain.ipv4, ...resolvedDomain.ipv6] }; } catch (error) { console.log(error); throw new Error(`An error occurred while resolving remote DNS server, please try agian! - ${error}`); } } const proxySettings = { remoteDNS, resolvedRemoteDNS: resolvedRemoteDNS ?? {}, localDNS: validateField("localDNS") ?? currentSettings?.localDNS ?? "8.8.8.8", vlessTrojanFakeDNS: validateField("vlessTrojanFakeDNS") ?? currentSettings?.vlessTrojanFakeDNS ?? false, proxyIP: validateField("proxyIP")?.trim() ?? currentSettings?.proxyIP ?? "", outProxy: validateField("outProxy") ?? currentSettings?.outProxy ?? "", outProxyParams: extractChainProxyParams(validateField("outProxy")) ?? currentSettings?.outProxyParams ?? "", cleanIPs: validateField("cleanIPs")?.replaceAll(" ", "") ?? currentSettings?.cleanIPs ?? "", enableIPv6: validateField("enableIPv6") ?? currentSettings?.enableIPv6 ?? true, customCdnAddrs: validateField("customCdnAddrs")?.replaceAll(" ", "") ?? currentSettings?.customCdnAddrs ?? "", customCdnHost: validateField("customCdnHost")?.trim() ?? currentSettings?.customCdnHost ?? "", customCdnSni: validateField("customCdnSni")?.trim() ?? currentSettings?.customCdnSni ?? "", bestVLESSTrojanInterval: validateField("bestVLESSTrojanInterval") ?? currentSettings?.bestVLESSTrojanInterval ?? "30", vlessConfigs: validateField("vlessConfigs") ?? currentSettings?.vlessConfigs ?? true, trojanConfigs: validateField("trojanConfigs") ?? currentSettings?.trojanConfigs ?? false, ports: validateField("ports")?.split(",") ?? currentSettings?.ports ?? ["443"], lengthMin: validateField("fragmentLengthMin") ?? currentSettings?.lengthMin ?? "100", lengthMax: validateField("fragmentLengthMax") ?? currentSettings?.lengthMax ?? "200", intervalMin: validateField("fragmentIntervalMin") ?? currentSettings?.intervalMin ?? "1", intervalMax: validateField("fragmentIntervalMax") ?? currentSettings?.intervalMax ?? "1", fragmentPackets: validateField("fragmentPackets") ?? currentSettings?.fragmentPackets ?? "tlshello", bypassLAN: validateField("bypass-lan") ?? currentSettings?.bypassLAN ?? false, bypassIran: validateField("bypass-iran") ?? currentSettings?.bypassIran ?? false, bypassChina: validateField("bypass-china") ?? currentSettings?.bypassChina ?? false, bypassRussia: validateField("bypass-russia") ?? currentSettings?.bypassRussia ?? false, blockAds: validateField("block-ads") ?? currentSettings?.blockAds ?? false, blockPorn: validateField("block-porn") ?? currentSettings?.blockPorn ?? false, blockUDP443: validateField("block-udp-443") ?? currentSettings?.blockUDP443 ?? false, warpEndpoints: validateField("warpEndpoints")?.replaceAll(" ", "") ?? currentSettings?.warpEndpoints ?? "engage.cloudflareclient.com:2408", warpFakeDNS: validateField("warpFakeDNS") ?? currentSettings?.warpFakeDNS ?? false, warpPlusLicense: validateField("warpPlusLicense") ?? currentSettings?.warpPlusLicense ?? "", bestWarpInterval: validateField("bestWarpInterval") ?? currentSettings?.bestWarpInterval ?? "30", hiddifyNoiseMode: validateField("hiddifyNoiseMode") ?? currentSettings?.hiddifyNoiseMode ?? "m4", nikaNGNoiseMode: validateField("nikaNGNoiseMode") ?? currentSettings?.nikaNGNoiseMode ?? "quic", noiseCountMin: validateField("noiseCountMin") ?? currentSettings?.noiseCountMin ?? "10", noiseCountMax: validateField("noiseCountMax") ?? currentSettings?.noiseCountMax ?? "15", noiseSizeMin: validateField("noiseSizeMin") ?? currentSettings?.noiseSizeMin ?? "5", noiseSizeMax: validateField("noiseSizeMax") ?? currentSettings?.noiseSizeMax ?? "10", noiseDelayMin: validateField("noiseDelayMin") ?? currentSettings?.noiseDelayMin ?? "1", noiseDelayMax: validateField("noiseDelayMax") ?? currentSettings?.noiseDelayMax ?? "1", panelVersion }; try { await env.bpb.put("proxySettings", JSON.stringify(proxySettings)); } catch (error) { console.log(error); throw new Error(`An error occurred while updating KV - ${error}`); } return proxySettings; } function randomUpperCase(str) { let result = ""; for (let i = 0; i < str.length; i++) { result += Math.random() < 0.5 ? str[i].toUpperCase() : str[i]; } return result; } function getRandomPath(length) { let result = ""; const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; const charactersLength = characters.length; for (let i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } async function resolveDNS(domain) { const dohURLv4 = `${dohURL}?name=${encodeURIComponent(domain)}&type=A`; const dohURLv6 = `${dohURL}?name=${encodeURIComponent(domain)}&type=AAAA`; try { const [ipv4Response, ipv6Response] = await Promise.all([ fetch(dohURLv4, { headers: { accept: "application/dns-json" } }), fetch(dohURLv6, { headers: { accept: "application/dns-json" } }) ]); const ipv4Addresses = await ipv4Response.json(); const ipv6Addresses = await ipv6Response.json(); const ipv4 = ipv4Addresses.Answer ? ipv4Addresses.Answer.map((record) => record.data) : []; const ipv6 = ipv6Addresses.Answer ? ipv6Addresses.Answer.map((record) => record.data) : []; return { ipv4, ipv6 }; } catch (error) { console.error("Error resolving DNS:", error); throw new Error(`An error occurred while resolving DNS - ${error}`); } } async function getConfigAddresses(hostName, cleanIPs, enableIPv6) { const resolved = await resolveDNS(hostName); const defaultIPv6 = enableIPv6 ? resolved.ipv6.map((ip) => `[${ip}]`) : []; return [ hostName, "www.speedtest.net", ...resolved.ipv4, ...defaultIPv6, ...cleanIPs ? cleanIPs.split(",") : [] ]; } async function generateJWTToken(secretKey) { const secret = new TextEncoder().encode(secretKey); return await new SignJWT({ userID }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime("24h").sign(secret); } function generateSecretKey() { const key = import_tweetnacl.default.randomBytes(32); return Array.from(key, (byte) => byte.toString(16).padStart(2, "0")).join(""); } async function Authenticate(request, env) { try { const secretKey = await env.bpb.get("secretKey"); const secret = new TextEncoder().encode(secretKey); const cookie = request.headers.get("Cookie")?.match(/(^|;\s*)jwtToken=([^;]*)/); const token = cookie ? cookie[2] : null; if (!token) { console.log("Unauthorized: Token not available!"); return false; } const { payload } = await jwtVerify(token, secret); console.log(`Successfully logined, User ID: ${payload.userID}`); return true; } catch (error) { console.log(error); return false; } } function renderHomePage(proxySettings, hostName, isPassSet) { const { remoteDNS, localDNS, vlessTrojanFakeDNS, proxyIP: proxyIP2, outProxy, cleanIPs, enableIPv6, customCdnAddrs, customCdnHost, customCdnSni, bestVLESSTrojanInterval, vlessConfigs, trojanConfigs, ports, lengthMin, lengthMax, intervalMin, intervalMax, fragmentPackets, warpEndpoints, warpFakeDNS, warpPlusLicense, bestWarpInterval, hiddifyNoiseMode, nikaNGNoiseMode, noiseCountMin, noiseCountMax, noiseSizeMin, noiseSizeMax, noiseDelayMin, noiseDelayMax, bypassLAN, bypassIran, bypassChina, bypassRussia, blockAds, blockPorn, blockUDP443 } = proxySettings; const isWarpPlus = warpPlusLicense ? true : false; let activeProtocols = (vlessConfigs ? 1 : 0) + (trojanConfigs ? 1 : 0); let httpPortsBlock = "", httpsPortsBlock = ""; const allPorts = [...hostName.includes("workers.dev") ? defaultHttpPorts : [], ...defaultHttpsPorts]; allPorts.forEach((port) => { let id = `port-${port}`; const isChecked = ports.includes(port) ? "checked" : ""; let portBlock = `
`; defaultHttpsPorts.includes(port) ? httpsPortsBlock += portBlock : httpPortsBlock += portBlock; }); const html = ` BPB Panel ${panelVersion} Collapsible Sections

BPB Panel ${panelVersion} \u{1F4A6}

VLESS / TROJAN \u2699\uFE0F

${!httpPortsBlock ? "" : ``}
Config type Ports
TLS
${httpsPortsBlock}
Non TLS
${httpPortsBlock}

FRAGMENT \u2699\uFE0F

-
-

WARP GENERAL \u2699\uFE0F

WARP PRO \u2699\uFE0F

-
-
-

ROUTING RULES \u2699\uFE0F


NORMAL SUB \u{1F517}

Application Subscription
verified v2rayNG
verified NikaNG
verified MahsaNG
verified v2rayN
verified v2rayN-PRO
verified Shadowrocket
verified Streisand
verified Hiddify
verified Nekoray (Xray)
verified Nekobox
verified Nekoray (Sing-Box)
verified Karing

FULL NORMAL SUB \u{1F517}

Application Subscription
verified v2rayNG
verified NikaNG
verified MahsaNG
verified v2rayN
verified v2rayN-PRO
verified Streisand
verified Sing-box
verified Clash Meta
verified Clash Verge
verified v2rayN
verified FlClash
verified Stash

FRAGMENT SUB \u26D3\uFE0F

Application Subscription
verified v2rayNG
verified NikaNG
verified MahsaNG
verified v2rayN
verified v2rayN-PRO
verified Streisand
verified Hiddify

WARP SUB \u{1F517}

Application Subscription
verified v2rayNG
verified v2rayN
verified Streisand
verified Hiddify
verified Singbox
verified Clash Meta
verified Clash Verge
verified v2rayN
verified FlClash
verified Stash

WARP PRO SUB \u{1F517}

Application Subscription
verified NikaNG
verified MahsaNG
verified v2rayN-PRO
verified Hiddify