From 6829536bff3cfbab83e210a232fc4b8dadb6f68d Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Sat, 26 Oct 2024 08:58:52 +0000 Subject: [PATCH] Automated build: update _worker.js --- _worker.js | 11121 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 11121 insertions(+) create mode 100644 _worker.js diff --git a/_worker.js b/_worker.js new file mode 100644 index 000000000..34d4bcade --- /dev/null +++ b/_worker.js @@ -0,0 +1,11121 @@ +function __cf_cjs(esm) { + const cjs = 'default' in esm ? esm.default : {}; + for (const [k, v] of Object.entries(esm)) { + if (k !== 'default') { + Object.defineProperty(cjs, k, { + enumerable: true, + value: v, + }); + } + } + return cjs; +} +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 __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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 __esm = (fn2, res) => function __init() { + return fn2 && (res = (0, fn2[__getOwnPropNames(fn2)[0]])(fn2 = 0)), res; +}; +var __commonJS = (cb, mod) => function __require2() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/_virtual_unenv_global_polyfill-clear$immediate.js +var init_virtual_unenv_global_polyfill_clear_immediate = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/_virtual_unenv_global_polyfill-clear$immediate.js"() { + init_cloudflare(); + globalThis.clearImmediate = clearImmediateFallback; + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/_internal/utils.mjs +function createNotImplementedError(name) { + return new Error(`[unenv] ${name} is not implemented yet!`); +} +function notImplemented(name) { + const fn2 = /* @__PURE__ */ __name(() => { + throw createNotImplementedError(name); + }, "fn"); + return Object.assign(fn2, { __unenv__: true }); +} +function notImplementedClass(name) { + return class { + __unenv__ = true; + constructor() { + throw new Error(`[unenv] ${name} is not implemented yet!`); + } + }; +} +var init_utils = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/_internal/utils.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + __name(createNotImplementedError, "createNotImplementedError"); + __name(notImplemented, "notImplemented"); + __name(notImplementedClass, "notImplementedClass"); + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/mock/noop.mjs +var noop_default; +var init_noop = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/mock/noop.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + noop_default = Object.assign(() => { + }, { __unenv__: true }); + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/timers/internal/immediate.mjs +var Immediate; +var init_immediate = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/timers/internal/immediate.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + Immediate = class { + _onImmediate; + _timeout; + constructor(callback, args) { + this._onImmediate = callback; + if ("setTimeout" in globalThis) { + this._timeout = setTimeout(callback, 0, ...args); + } else { + callback(...args); + } + } + ref() { + this._timeout?.ref(); + return this; + } + unref() { + this._timeout?.unref(); + return this; + } + hasRef() { + return this._timeout?.hasRef() ?? false; + } + [Symbol.dispose]() { + if ("clearTimeout" in globalThis) { + clearTimeout(this._timeout); + } + } + }; + __name(Immediate, "Immediate"); + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/timers/internal/set-immediate.mjs +function setImmediateFallbackPromises(value) { + return new Promise((res) => { + res(value); + }); +} +function setImmediateFallback(callback, ...args) { + return new Immediate(callback, args); +} +function clearImmediateFallback(immediate) { + immediate?.[Symbol.dispose](); +} +var init_set_immediate = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/timers/internal/set-immediate.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + init_immediate(); + __name(setImmediateFallbackPromises, "setImmediateFallbackPromises"); + __name(setImmediateFallback, "setImmediateFallback"); + setImmediateFallback.__promisify__ = setImmediateFallbackPromises; + __name(clearImmediateFallback, "clearImmediateFallback"); + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/timers/$cloudflare.mjs +var init_cloudflare = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/timers/$cloudflare.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + init_set_immediate(); + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/_virtual_unenv_global_polyfill-set$immediate.js +var init_virtual_unenv_global_polyfill_set_immediate = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/_virtual_unenv_global_polyfill-set$immediate.js"() { + init_cloudflare(); + globalThis.setImmediate = setImmediateFallback; + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/mock/proxy.mjs +function createMock(name, overrides = {}) { + fn.prototype.name = name; + const props = {}; + return new Proxy(fn, { + get(_target, prop) { + if (prop === "caller") { + return null; + } + if (prop === "__createMock__") { + return createMock; + } + if (prop === "__unenv__") { + return true; + } + if (prop in overrides) { + return overrides[prop]; + } + return props[prop] = props[prop] || createMock(`${name}.${prop.toString()}`); + }, + apply(_target, _this, _args) { + return createMock(`${name}()`); + }, + construct(_target, _args, _newT) { + return createMock(`[${name}]`); + }, + // @ts-ignore (ES6-only - removed in ES7) + // https://github.com/tc39/ecma262/issues/161 + enumerate() { + return []; + } + }); +} +var fn, proxy_default; +var init_proxy = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/mock/proxy.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + fn = /* @__PURE__ */ __name(function() { + }, "fn"); + __name(createMock, "createMock"); + proxy_default = createMock("mock"); + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/console/index.mjs +import { Writable } from "node:stream"; +var _console, _ignoreErrors, _stderr, _stdout, log, info, trace, debug, table, error, warn, createTask, assert, clear, count, countReset, dir, dirxml, group, groupEnd, groupCollapsed, profile, profileEnd, time, timeEnd, timeLog, timeStamp, Console; +var init_console = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/console/index.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + init_proxy(); + init_noop(); + init_utils(); + init_proxy(); + init_noop(); + _console = globalThis.console; + _ignoreErrors = true; + _stderr = new Writable(); + _stdout = new Writable(); + log = _console?.log ?? noop_default; + info = _console?.info ?? log; + trace = _console?.trace ?? info; + debug = _console?.debug ?? log; + table = _console?.table ?? log; + error = _console?.error ?? log; + warn = _console?.warn ?? error; + createTask = _console?.createTask ?? notImplemented("console.createTask"); + assert = notImplemented("console.assert"); + clear = _console?.clear ?? noop_default; + count = _console?.count ?? noop_default; + countReset = _console?.countReset ?? noop_default; + dir = _console?.dir ?? noop_default; + dirxml = _console?.dirxml ?? noop_default; + group = _console?.group ?? noop_default; + groupEnd = _console?.groupEnd ?? noop_default; + groupCollapsed = _console?.groupCollapsed ?? noop_default; + profile = _console?.profile ?? noop_default; + profileEnd = _console?.profileEnd ?? noop_default; + time = _console?.time ?? noop_default; + timeEnd = _console?.timeEnd ?? noop_default; + timeLog = _console?.timeLog ?? noop_default; + timeStamp = _console?.timeStamp ?? noop_default; + Console = _console?.Console ?? proxy_default.__createMock__("console.Console"); + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/console/$cloudflare.mjs +var workerdConsole, assert2, clear2, context, count2, countReset2, createTask2, debug2, dir2, dirxml2, error2, group2, groupCollapsed2, groupEnd2, info2, log2, profile2, profileEnd2, table2, time2, timeEnd2, timeLog2, timeStamp2, trace2, warn2, cloudflare_default; +var init_cloudflare2 = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/console/$cloudflare.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + init_console(); + workerdConsole = globalThis["console"]; + ({ + assert: assert2, + clear: clear2, + context: ( + // @ts-expect-error undocumented public API + context + ), + count: count2, + countReset: countReset2, + createTask: ( + // @ts-expect-error undocumented public API + createTask2 + ), + debug: debug2, + dir: dir2, + dirxml: dirxml2, + error: error2, + group: group2, + groupCollapsed: groupCollapsed2, + groupEnd: groupEnd2, + info: info2, + log: log2, + profile: profile2, + profileEnd: profileEnd2, + table: table2, + time: time2, + timeEnd: timeEnd2, + timeLog: timeLog2, + timeStamp: timeStamp2, + trace: trace2, + warn: warn2 + } = workerdConsole); + Object.assign(workerdConsole, { + Console, + _ignoreErrors, + _stderr, + _stderrErrorHandler: noop_default, + _stdout, + _stdoutErrorHandler: noop_default, + _times: proxy_default + }); + cloudflare_default = workerdConsole; + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/_virtual_unenv_global_polyfill-console.js +var init_virtual_unenv_global_polyfill_console = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/_virtual_unenv_global_polyfill-console.js"() { + init_cloudflare2(); + globalThis.console = cloudflare_default; + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/web/performance/_entry.mjs +var _supportedEntryTypes, _PerformanceEntry, PerformanceEntry, _PerformanceMark, PerformanceMark, _PerformanceMeasure, PerformanceMeasure, _PerformanceResourceTiming, PerformanceResourceTiming; +var init_entry = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/web/performance/_entry.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + _supportedEntryTypes = [ + "event", + // PerformanceEntry + "mark", + // PerformanceMark + "measure", + // PerformanceMeasure + "resource" + // PerformanceResourceTiming + ]; + _PerformanceEntry = class { + __unenv__ = true; + detail; + entryType = "event"; + name; + startTime; + constructor(name, options) { + this.name = name; + this.startTime = options?.startTime || performance.now(); + this.detail = options?.detail; + } + get duration() { + return performance.now() - this.startTime; + } + toJSON() { + return { + name: this.name, + entryType: this.entryType, + startTime: this.startTime, + duration: this.duration, + detail: this.detail + }; + } + }; + __name(_PerformanceEntry, "_PerformanceEntry"); + PerformanceEntry = globalThis.PerformanceEntry || _PerformanceEntry; + _PerformanceMark = class extends _PerformanceEntry { + entryType = "mark"; + }; + __name(_PerformanceMark, "_PerformanceMark"); + PerformanceMark = globalThis.PerformanceMark || _PerformanceMark; + _PerformanceMeasure = class extends _PerformanceEntry { + entryType = "measure"; + }; + __name(_PerformanceMeasure, "_PerformanceMeasure"); + PerformanceMeasure = globalThis.PerformanceMeasure || _PerformanceMeasure; + _PerformanceResourceTiming = class extends _PerformanceEntry { + entryType = "resource"; + serverTiming = []; + connectEnd = 0; + connectStart = 0; + decodedBodySize = 0; + domainLookupEnd = 0; + domainLookupStart = 0; + encodedBodySize = 0; + fetchStart = 0; + initiatorType = ""; + name = ""; + nextHopProtocol = ""; + redirectEnd = 0; + redirectStart = 0; + requestStart = 0; + responseEnd = 0; + responseStart = 0; + secureConnectionStart = 0; + startTime = 0; + transferSize = 0; + workerStart = 0; + }; + __name(_PerformanceResourceTiming, "_PerformanceResourceTiming"); + PerformanceResourceTiming = globalThis.PerformanceResourceTiming || _PerformanceResourceTiming; + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/web/performance/_performance.mjs +var _timeOrigin, _Performance, Performance, performance2; +var init_performance = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/web/performance/_performance.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + init_utils(); + init_proxy(); + init_entry(); + _timeOrigin = Date.now(); + _Performance = class { + __unenv__ = true; + timeOrigin = _timeOrigin; + eventCounts = /* @__PURE__ */ new Map(); + _entries = []; + _resourceTimingBufferSize = 0; + navigation = proxy_default.__createMock__("PerformanceNavigation"); + timing = proxy_default.__createMock__("PerformanceTiming"); + onresourcetimingbufferfull = null; + now() { + if (globalThis?.performance?.now && this.timeOrigin === _timeOrigin) { + return globalThis.performance.now(); + } + return Date.now() - this.timeOrigin; + } + clearMarks(markName) { + this._entries = markName ? this._entries.filter((e) => e.name !== markName) : this._entries.filter((e) => e.entryType !== "mark"); + } + clearMeasures(measureName) { + this._entries = measureName ? this._entries.filter((e) => e.name !== measureName) : this._entries.filter((e) => e.entryType !== "measure"); + } + clearResourceTimings() { + this._entries = this._entries.filter( + (e) => e.entryType !== "resource" || e.entryType !== "navigation" + ); + } + getEntries() { + return this._entries; + } + getEntriesByName(name, type) { + return this._entries.filter( + (e) => e.name === name && (!type || e.entryType === type) + ); + } + getEntriesByType(type) { + return this._entries.filter( + (e) => e.entryType === type + ); + } + mark(name, options) { + const entry = new _PerformanceMark(name, options); + this._entries.push(entry); + return entry; + } + measure(measureName, startOrMeasureOptions, endMark) { + let start; + let end; + if (typeof startOrMeasureOptions === "string") { + start = this.getEntriesByName(startOrMeasureOptions, "mark")[0]?.startTime; + end = this.getEntriesByName(endMark, "mark")[0]?.startTime; + } else { + start = Number.parseFloat(startOrMeasureOptions?.start) || performance2.now(); + end = Number.parseFloat(startOrMeasureOptions?.end) || performance2.now(); + } + const entry = new _PerformanceMeasure(measureName, { + startTime: start, + detail: { start, end } + }); + this._entries.push(entry); + return entry; + } + setResourceTimingBufferSize(maxSize) { + this._resourceTimingBufferSize = maxSize; + } + toJSON() { + return this; + } + addEventListener(type, listener, options) { + throw createNotImplementedError("Performance.addEventListener"); + } + removeEventListener(type, listener, options) { + throw createNotImplementedError("Performance.removeEventListener"); + } + dispatchEvent(event) { + throw createNotImplementedError("Performance.dispatchEvent"); + } + }; + __name(_Performance, "_Performance"); + Performance = globalThis.Performance || _Performance; + performance2 = globalThis.performance || new Performance(); + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/web/performance/_observer.mjs +var _PerformanceObserver, PerformanceObserver, _PerformanceObserverEntryList, PerformanceObserverEntryList; +var init_observer = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/web/performance/_observer.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + init_utils(); + init_entry(); + _PerformanceObserver = class { + __unenv__ = true; + _callback = null; + constructor(callback) { + this._callback = callback; + } + takeRecords() { + return []; + } + disconnect() { + throw createNotImplementedError("PerformanceObserver.disconnect"); + } + observe(options) { + throw createNotImplementedError("PerformanceObserver.observe"); + } + }; + __name(_PerformanceObserver, "_PerformanceObserver"); + __publicField(_PerformanceObserver, "supportedEntryTypes", _supportedEntryTypes); + PerformanceObserver = globalThis.PerformanceObserver || _PerformanceObserver; + _PerformanceObserverEntryList = class { + __unenv__ = true; + getEntries() { + return []; + } + getEntriesByName(_name, _type) { + return []; + } + getEntriesByType(type) { + return []; + } + }; + __name(_PerformanceObserverEntryList, "_PerformanceObserverEntryList"); + PerformanceObserverEntryList = globalThis.PerformanceObserverEntryList || _PerformanceObserverEntryList; + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/web/performance/index.mjs +var init_performance2 = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/web/performance/index.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + init_performance(); + init_observer(); + init_entry(); + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/polyfill/global-this.mjs +function getGlobal() { + if (typeof globalThis !== "undefined") { + return globalThis; + } + if (typeof self !== "undefined") { + return self; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof global !== "undefined") { + return global; + } + return {}; +} +var global_this_default; +var init_global_this = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/polyfill/global-this.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + __name(getGlobal, "getGlobal"); + global_this_default = getGlobal(); + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/polyfill/performance.mjs +var performance_default; +var init_performance3 = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/polyfill/performance.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + init_performance2(); + init_global_this(); + global_this_default.performance = global_this_default.performance || performance2; + global_this_default.Performance = global_this_default.Performance || Performance; + global_this_default.PerformanceEntry = global_this_default.PerformanceEntry || PerformanceEntry; + global_this_default.PerformanceMark = global_this_default.PerformanceMark || PerformanceMark; + global_this_default.PerformanceMeasure = global_this_default.PerformanceMeasure || PerformanceMeasure; + global_this_default.PerformanceObserver = global_this_default.PerformanceObserver || PerformanceObserver; + global_this_default.PerformanceObserverEntryList = global_this_default.PerformanceObserverEntryList || PerformanceObserverEntryList; + global_this_default.PerformanceResourceTiming = global_this_default.PerformanceResourceTiming || PerformanceResourceTiming; + performance_default = global_this_default.performance; + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/_virtual_unenv_global_polyfill-performance.js +var init_virtual_unenv_global_polyfill_performance = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/_virtual_unenv_global_polyfill-performance.js"() { + init_performance3(); + globalThis.performance = performance_default; + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/mock/empty.mjs +var empty_default; +var init_empty = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/mock/empty.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + empty_default = Object.freeze( + Object.create(null, { + __unenv__: { get: () => true } + }) + ); + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/process/internal/env.mjs +var _envShim, _processEnv, _getEnv, env; +var init_env = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/process/internal/env.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + _envShim = /* @__PURE__ */ Object.create(null); + _processEnv = globalThis.process?.env; + _getEnv = /* @__PURE__ */ __name((useShim) => _processEnv || globalThis.__env__ || (useShim ? _envShim : globalThis), "_getEnv"); + env = new Proxy(_envShim, { + get(_, prop) { + const env22 = _getEnv(); + return env22[prop] ?? _envShim[prop]; + }, + has(_, prop) { + const env22 = _getEnv(); + return prop in env22 || prop in _envShim; + }, + set(_, prop, value) { + const env22 = _getEnv(true); + env22[prop] = value; + return true; + }, + deleteProperty(_, prop) { + const env22 = _getEnv(true); + delete env22[prop]; + return true; + }, + ownKeys() { + const env22 = _getEnv(); + return Object.keys(env22); + } + }); + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/process/internal/time.mjs +function _createNextTickWithTimeout() { + let queue = []; + let draining = false; + let currentQueue; + let queueIndex = -1; + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length > 0) { + queue = [...currentQueue, ...queue]; + } else { + queueIndex = -1; + } + if (queue.length > 0) { + drainQueue(); + } + } + __name(cleanUpNextTick, "cleanUpNextTick"); + function drainQueue() { + if (draining) { + return; + } + const timeout = setTimeout(cleanUpNextTick); + draining = true; + let len = queue.length; + while (len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex](); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = void 0; + draining = false; + clearTimeout(timeout); + } + __name(drainQueue, "drainQueue"); + const nextTick22 = /* @__PURE__ */ __name((cb, ...args) => { + queue.push(cb.bind(void 0, ...args)); + if (queue.length === 1 && !draining) { + setTimeout(drainQueue); + } + }, "nextTick2"); + return nextTick22; +} +var hrtime, nextTick; +var init_time = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/process/internal/time.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + hrtime = Object.assign( + /* @__PURE__ */ __name(function hrtime2(startTime) { + const now = Date.now(); + const seconds = Math.trunc(now / 1e3); + const nanos = now % 1e3 * 1e6; + if (startTime) { + let diffSeconds = seconds - startTime[0]; + let diffNanos = nanos - startTime[0]; + if (diffNanos < 0) { + diffSeconds = diffSeconds - 1; + diffNanos = 1e9 + diffNanos; + } + return [diffSeconds, diffNanos]; + } + return [seconds, nanos]; + }, "hrtime2"), + { + bigint: /* @__PURE__ */ __name(function bigint() { + return BigInt(Date.now() * 1e6); + }, "bigint") + } + ); + nextTick = globalThis.queueMicrotask ? (cb, ...args) => { + globalThis.queueMicrotask(cb.bind(void 0, ...args)); + } : _createNextTickWithTimeout(); + __name(_createNextTickWithTimeout, "_createNextTickWithTimeout"); + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/process/internal/process.mjs +function noop() { + return process2; +} +var title, argv, version, versions, on, addListener, once, off, removeListener, removeAllListeners, emit, prependListener, prependOnceListener, listeners, listenerCount, binding, _cwd, cwd, chdir, umask, getegid, geteuid, getgid, getuid, getgroups, getBuiltinModule, abort, allowedNodeEnvironmentFlags, arch, argv0, config, connected, constrainedMemory, availableMemory, cpuUsage, debugPort, dlopen, disconnect, emitWarning, eventNames, execArgv, execPath, exit, features, getActiveResourcesInfo, getMaxListeners, kill, memoryUsage, pid, platform, ppid, rawListeners, release, report, resourceUsage, setegid, seteuid, setgid, setgroups, setuid, setMaxListeners, setSourceMapsEnabled, stdout, stderr, stdin, traceDeprecation, uptime, exitCode, setUncaughtExceptionCaptureCallback, hasUncaughtExceptionCaptureCallback, sourceMapsEnabled, loadEnvFile, mainModule, permission, channel, throwDeprecation, assert3, openStdin, _debugEnd, _debugProcess, _fatalException, _getActiveHandles, _getActiveRequests, _kill, _preload_modules, _rawDebug, _startProfilerIdleNotifier, _stopProfilerIdleNotifier, _tickCallback, _linkedBinding, domain, initgroups, moduleLoadList, reallyExit, _exiting, _events, _eventsCount, _maxListeners, process2; +var init_process = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/process/internal/process.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + init_proxy(); + init_empty(); + init_utils(); + init_env(); + init_time(); + init_time(); + title = "unenv"; + argv = []; + version = ""; + versions = { + ares: "", + http_parser: "", + icu: "", + modules: "", + node: "", + openssl: "", + uv: "", + v8: "", + zlib: "" + }; + __name(noop, "noop"); + on = noop; + addListener = noop; + once = noop; + off = noop; + removeListener = noop; + removeAllListeners = noop; + emit = /* @__PURE__ */ __name(function emit2(event) { + if (event === "message" || event === "multipleResolves") { + return process2; + } + return false; + }, "emit2"); + prependListener = noop; + prependOnceListener = noop; + listeners = /* @__PURE__ */ __name(function(name) { + return []; + }, "listeners"); + listenerCount = /* @__PURE__ */ __name(() => 0, "listenerCount"); + binding = /* @__PURE__ */ __name(function(name) { + throw new Error("[unenv] process.binding is not supported"); + }, "binding"); + _cwd = "/"; + cwd = /* @__PURE__ */ __name(function cwd2() { + return _cwd; + }, "cwd2"); + chdir = /* @__PURE__ */ __name(function chdir2(dir3) { + _cwd = dir3; + }, "chdir2"); + umask = /* @__PURE__ */ __name(function umask2() { + return 0; + }, "umask2"); + getegid = /* @__PURE__ */ __name(function getegid2() { + return 1e3; + }, "getegid2"); + geteuid = /* @__PURE__ */ __name(function geteuid2() { + return 1e3; + }, "geteuid2"); + getgid = /* @__PURE__ */ __name(function getgid2() { + return 1e3; + }, "getgid2"); + getuid = /* @__PURE__ */ __name(function getuid2() { + return 1e3; + }, "getuid2"); + getgroups = /* @__PURE__ */ __name(function getgroups2() { + return []; + }, "getgroups2"); + getBuiltinModule = /* @__PURE__ */ __name((_name) => void 0, "getBuiltinModule"); + abort = notImplemented("process.abort"); + allowedNodeEnvironmentFlags = /* @__PURE__ */ new Set(); + arch = ""; + argv0 = ""; + config = empty_default; + connected = false; + constrainedMemory = /* @__PURE__ */ __name(() => 0, "constrainedMemory"); + availableMemory = /* @__PURE__ */ __name(() => 0, "availableMemory"); + cpuUsage = notImplemented("process.cpuUsage"); + debugPort = 0; + dlopen = notImplemented("process.dlopen"); + disconnect = noop; + emitWarning = noop; + eventNames = notImplemented("process.eventNames"); + execArgv = []; + execPath = ""; + exit = notImplemented("process.exit"); + features = /* @__PURE__ */ Object.create({ + inspector: void 0, + debug: void 0, + uv: void 0, + ipv6: void 0, + tls_alpn: void 0, + tls_sni: void 0, + tls_ocsp: void 0, + tls: void 0, + cached_builtins: void 0 + }); + getActiveResourcesInfo = /* @__PURE__ */ __name(() => [], "getActiveResourcesInfo"); + getMaxListeners = notImplemented( + "process.getMaxListeners" + ); + kill = notImplemented("process.kill"); + memoryUsage = Object.assign( + () => ({ + arrayBuffers: 0, + rss: 0, + external: 0, + heapTotal: 0, + heapUsed: 0 + }), + { rss: () => 0 } + ); + pid = 1e3; + platform = ""; + ppid = 1e3; + rawListeners = notImplemented( + "process.rawListeners" + ); + release = /* @__PURE__ */ Object.create({ + name: "", + lts: "", + sourceUrl: void 0, + headersUrl: void 0 + }); + report = /* @__PURE__ */ Object.create({ + compact: void 0, + directory: void 0, + filename: void 0, + getReport: notImplemented("process.report.getReport"), + reportOnFatalError: void 0, + reportOnSignal: void 0, + reportOnUncaughtException: void 0, + signal: void 0, + writeReport: notImplemented("process.report.writeReport") + }); + resourceUsage = notImplemented( + "process.resourceUsage" + ); + setegid = notImplemented("process.setegid"); + seteuid = notImplemented("process.seteuid"); + setgid = notImplemented("process.setgid"); + setgroups = notImplemented("process.setgroups"); + setuid = notImplemented("process.setuid"); + setMaxListeners = notImplemented( + "process.setMaxListeners" + ); + setSourceMapsEnabled = notImplemented("process.setSourceMapsEnabled"); + stdout = proxy_default.__createMock__("process.stdout"); + stderr = proxy_default.__createMock__("process.stderr"); + stdin = proxy_default.__createMock__("process.stdin"); + traceDeprecation = false; + uptime = /* @__PURE__ */ __name(() => 0, "uptime"); + exitCode = 0; + setUncaughtExceptionCaptureCallback = notImplemented("process.setUncaughtExceptionCaptureCallback"); + hasUncaughtExceptionCaptureCallback = /* @__PURE__ */ __name(() => false, "hasUncaughtExceptionCaptureCallback"); + sourceMapsEnabled = false; + loadEnvFile = notImplemented( + "process.loadEnvFile" + ); + mainModule = void 0; + permission = { + has: () => false + }; + channel = { + ref() { + }, + unref() { + } + }; + throwDeprecation = false; + assert3 = notImplemented("process.assert"); + openStdin = notImplemented("process.openStdin"); + _debugEnd = notImplemented("process._debugEnd"); + _debugProcess = notImplemented("process._debugProcess"); + _fatalException = notImplemented("process._fatalException"); + _getActiveHandles = notImplemented("process._getActiveHandles"); + _getActiveRequests = notImplemented("process._getActiveRequests"); + _kill = notImplemented("process._kill"); + _preload_modules = []; + _rawDebug = notImplemented("process._rawDebug"); + _startProfilerIdleNotifier = notImplemented( + "process._startProfilerIdleNotifier" + ); + _stopProfilerIdleNotifier = notImplemented( + "process.__stopProfilerIdleNotifier" + ); + _tickCallback = notImplemented("process._tickCallback"); + _linkedBinding = notImplemented("process._linkedBinding"); + domain = proxy_default.__createMock__("process.domain"); + initgroups = notImplemented("process.initgroups"); + moduleLoadList = []; + reallyExit = noop; + _exiting = false; + _events = []; + _eventsCount = 0; + _maxListeners = 0; + process2 = { + // @ts-expect-error + _events, + _eventsCount, + _exiting, + _maxListeners, + _debugEnd, + _debugProcess, + _fatalException, + _getActiveHandles, + _getActiveRequests, + _kill, + _preload_modules, + _rawDebug, + _startProfilerIdleNotifier, + _stopProfilerIdleNotifier, + _tickCallback, + domain, + initgroups, + moduleLoadList, + reallyExit, + exitCode, + abort, + addListener, + allowedNodeEnvironmentFlags, + hasUncaughtExceptionCaptureCallback, + setUncaughtExceptionCaptureCallback, + loadEnvFile, + sourceMapsEnabled, + throwDeprecation, + mainModule, + permission, + channel, + arch, + argv, + argv0, + assert: assert3, + binding, + chdir, + config, + connected, + constrainedMemory, + availableMemory, + cpuUsage, + cwd, + debugPort, + dlopen, + disconnect, + emit, + emitWarning, + env, + eventNames, + execArgv, + execPath, + exit, + features, + getBuiltinModule, + getegid, + geteuid, + getgid, + getgroups, + getuid, + getActiveResourcesInfo, + getMaxListeners, + hrtime, + kill, + listeners, + listenerCount, + memoryUsage, + nextTick, + on, + off, + once, + openStdin, + pid, + platform, + ppid, + prependListener, + prependOnceListener, + rawListeners, + release, + removeAllListeners, + removeListener, + report, + resourceUsage, + setegid, + seteuid, + setgid, + setgroups, + setuid, + setMaxListeners, + setSourceMapsEnabled, + stderr, + stdin, + stdout, + title, + traceDeprecation, + umask, + uptime, + version, + versions + }; + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/process/$cloudflare.mjs +var unpatchedGlobalThisProcess, getBuiltinModule2, workerdProcess, env2, nextTick2, _process, cloudflare_default2; +var init_cloudflare3 = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/process/$cloudflare.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + init_process(); + unpatchedGlobalThisProcess = globalThis["process"]; + getBuiltinModule2 = unpatchedGlobalThisProcess.getBuiltinModule; + workerdProcess = getBuiltinModule2("node:process"); + ({ env: env2, nextTick: nextTick2 } = workerdProcess); + _process = { + /** + * manually unroll unenv-polyfilled-symbols to make it tree-shakeable + */ + // @ts-expect-error (not typed) + _debugEnd, + _debugProcess, + _events, + _eventsCount, + _exiting, + _fatalException, + _getActiveHandles, + _getActiveRequests, + _kill, + _linkedBinding, + _maxListeners, + _preload_modules, + _rawDebug, + _startProfilerIdleNotifier, + _stopProfilerIdleNotifier, + _tickCallback, + abort, + addListener, + allowedNodeEnvironmentFlags, + arch, + argv, + argv0, + assert: assert3, + availableMemory, + binding, + chdir, + config, + constrainedMemory, + cpuUsage, + cwd, + debugPort, + dlopen, + domain, + emit, + emitWarning, + eventNames, + execArgv, + execPath, + exit, + exitCode, + features, + getActiveResourcesInfo, + getMaxListeners, + getegid, + geteuid, + getgid, + getgroups, + getuid, + hasUncaughtExceptionCaptureCallback, + hrtime, + initgroups, + kill, + listenerCount, + listeners, + loadEnvFile, + memoryUsage, + moduleLoadList, + off, + on, + once, + openStdin, + pid, + platform, + ppid, + prependListener, + prependOnceListener, + rawListeners, + reallyExit, + release, + removeAllListeners, + removeListener, + report, + resourceUsage, + setMaxListeners, + setSourceMapsEnabled, + setUncaughtExceptionCaptureCallback, + setegid, + seteuid, + setgid, + setgroups, + setuid, + sourceMapsEnabled, + stderr, + stdin, + stdout, + title, + umask, + uptime, + version, + versions, + /** + * manually unroll workerd-polyfilled-symbols to make it tree-shakeable + */ + env: env2, + getBuiltinModule: getBuiltinModule2, + nextTick: nextTick2 + }; + cloudflare_default2 = _process; + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/_virtual_unenv_global_polyfill-process.js +var init_virtual_unenv_global_polyfill_process = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/_virtual_unenv_global_polyfill-process.js"() { + init_cloudflare3(); + globalThis.process = cloudflare_default2; + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/crypto/internal/web.mjs +var web_exports = {}; +__export(web_exports, { + getRandomValues: () => getRandomValues, + randomUUID: () => randomUUID, + subtle: () => subtle +}); +var subtle, randomUUID, getRandomValues; +var init_web = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/crypto/internal/web.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + subtle = globalThis.crypto?.subtle; + randomUUID = /* @__PURE__ */ __name(() => { + return globalThis.crypto?.randomUUID(); + }, "randomUUID"); + getRandomValues = /* @__PURE__ */ __name((array) => { + return globalThis.crypto?.getRandomValues(array); + }, "getRandomValues"); + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/crypto/internal/node.mjs +var node_exports = {}; +__export(node_exports, { + Certificate: () => Certificate, + Cipher: () => Cipher, + Cipheriv: () => Cipheriv, + Decipher: () => Decipher, + Decipheriv: () => Decipheriv, + DiffieHellman: () => DiffieHellman, + DiffieHellmanGroup: () => DiffieHellmanGroup, + ECDH: () => ECDH, + Hash: () => Hash, + Hmac: () => Hmac, + KeyObject: () => KeyObject, + Sign: () => Sign, + Verify: () => Verify, + X509Certificate: () => X509Certificate, + checkPrime: () => checkPrime, + checkPrimeSync: () => checkPrimeSync, + constants: () => constants, + createCipher: () => createCipher, + createCipheriv: () => createCipheriv, + createDecipher: () => createDecipher, + createDecipheriv: () => createDecipheriv, + createDiffieHellman: () => createDiffieHellman, + createDiffieHellmanGroup: () => createDiffieHellmanGroup, + createECDH: () => createECDH, + createHash: () => createHash, + createHmac: () => createHmac, + createPrivateKey: () => createPrivateKey, + createPublicKey: () => createPublicKey, + createSecretKey: () => createSecretKey, + createSign: () => createSign, + createVerify: () => createVerify, + diffieHellman: () => diffieHellman, + fips: () => fips, + generateKey: () => generateKey, + generateKeyPair: () => generateKeyPair, + generateKeyPairSync: () => generateKeyPairSync, + generateKeySync: () => generateKeySync, + generatePrime: () => generatePrime, + generatePrimeSync: () => generatePrimeSync, + getCipherInfo: () => getCipherInfo, + getCiphers: () => getCiphers, + getCurves: () => getCurves, + getDiffieHellman: () => getDiffieHellman, + getFips: () => getFips, + getHashes: () => getHashes, + hash: () => hash, + hkdf: () => hkdf, + hkdfSync: () => hkdfSync, + pbkdf2: () => pbkdf2, + pbkdf2Sync: () => pbkdf2Sync, + privateDecrypt: () => privateDecrypt, + privateEncrypt: () => privateEncrypt, + pseudoRandomBytes: () => pseudoRandomBytes, + publicDecrypt: () => publicDecrypt, + publicEncrypt: () => publicEncrypt, + randomBytes: () => randomBytes, + randomFill: () => randomFill, + randomFillSync: () => randomFillSync, + randomInt: () => randomInt, + scrypt: () => scrypt, + scryptSync: () => scryptSync, + secureHeapUsed: () => secureHeapUsed, + setEngine: () => setEngine, + setFips: () => setFips, + sign: () => sign, + timingSafeEqual: () => timingSafeEqual, + verify: () => verify, + webcrypto: () => webcrypto +}); +var MAX_RANDOM_VALUE_BYTES, webcrypto, randomBytes, fips, constants, checkPrime, checkPrimeSync, createCipher, createDecipher, pseudoRandomBytes, createCipheriv, createDecipheriv, createDiffieHellman, createDiffieHellmanGroup, createECDH, createHash, createHmac, createPrivateKey, createPublicKey, createSecretKey, createSign, createVerify, diffieHellman, generatePrime, generatePrimeSync, getCiphers, getCipherInfo, getCurves, getDiffieHellman, getHashes, hkdf, hkdfSync, pbkdf2, pbkdf2Sync, generateKeyPair, generateKeyPairSync, generateKey, generateKeySync, privateDecrypt, privateEncrypt, publicDecrypt, publicEncrypt, randomFill, randomFillSync, randomInt, scrypt, scryptSync, sign, setEngine, timingSafeEqual, getFips, setFips, verify, secureHeapUsed, hash, Certificate, Cipher, Cipheriv, Decipher, Decipheriv, DiffieHellman, DiffieHellmanGroup, ECDH, Hash, Hmac, KeyObject, Sign, Verify, X509Certificate; +var init_node = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/crypto/internal/node.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + init_utils(); + init_web(); + MAX_RANDOM_VALUE_BYTES = 65536; + webcrypto = new Proxy( + globalThis.crypto, + { + get(_, key) { + if (key === "CryptoKey") { + return globalThis.CryptoKey; + } + if (typeof globalThis.crypto[key] === "function") { + return globalThis.crypto[key].bind(globalThis.crypto); + } + return globalThis.crypto[key]; + } + } + ); + randomBytes = /* @__PURE__ */ __name((size, cb) => { + const bytes = Buffer.alloc(size, 0, void 0); + for (let generated = 0; generated < size; generated += MAX_RANDOM_VALUE_BYTES) { + getRandomValues( + Uint8Array.prototype.slice.call( + bytes, + generated, + generated + MAX_RANDOM_VALUE_BYTES + ) + ); + } + if (typeof cb === "function") { + cb(null, bytes); + return void 0; + } + return bytes; + }, "randomBytes"); + fips = false; + constants = {}; + checkPrime = notImplemented("crypto.checkPrime"); + checkPrimeSync = notImplemented( + "crypto.checkPrimeSync" + ); + createCipher = notImplemented("crypto.createCipher"); + createDecipher = notImplemented("crypto.createDecipher"); + pseudoRandomBytes = notImplemented("crypto.pseudoRandomBytes"); + createCipheriv = notImplemented( + "crypto.createCipheriv" + ); + createDecipheriv = notImplemented("crypto.createDecipheriv"); + createDiffieHellman = notImplemented("crypto.createDiffieHellman"); + createDiffieHellmanGroup = notImplemented("crypto.createDiffieHellmanGroup"); + createECDH = notImplemented("crypto.createECDH"); + createHash = notImplemented("crypto.createHash"); + createHmac = notImplemented("crypto.createHmac"); + createPrivateKey = notImplemented("crypto.createPrivateKey"); + createPublicKey = notImplemented("crypto.createPublicKey"); + createSecretKey = notImplemented("crypto.createSecretKey"); + createSign = notImplemented("crypto.createSign"); + createVerify = notImplemented( + "crypto.createVerify" + ); + diffieHellman = notImplemented( + "crypto.diffieHellman" + ); + generatePrime = notImplemented( + "crypto.generatePrime" + ); + generatePrimeSync = notImplemented("crypto.generatePrimeSync"); + getCiphers = notImplemented("crypto.getCiphers"); + getCipherInfo = notImplemented( + "crypto.getCipherInfo" + ); + getCurves = notImplemented("crypto.getCurves"); + getDiffieHellman = notImplemented("crypto.getDiffieHellman"); + getHashes = notImplemented("crypto.getHashes"); + hkdf = notImplemented("crypto.hkdf"); + hkdfSync = notImplemented("crypto.hkdfSync"); + pbkdf2 = notImplemented("crypto.pbkdf2"); + pbkdf2Sync = notImplemented("crypto.pbkdf2Sync"); + generateKeyPair = notImplemented("crypto.generateKeyPair"); + generateKeyPairSync = notImplemented("crypto.generateKeyPairSync"); + generateKey = notImplemented("crypto.generateKey"); + generateKeySync = notImplemented("crypto.generateKeySync"); + privateDecrypt = notImplemented( + "crypto.privateDecrypt" + ); + privateEncrypt = notImplemented( + "crypto.privateEncrypt" + ); + publicDecrypt = notImplemented( + "crypto.publicDecrypt" + ); + publicEncrypt = notImplemented( + "crypto.publicEncrypt" + ); + randomFill = notImplemented("crypto.randomFill"); + randomFillSync = notImplemented( + "crypto.randomFillSync" + ); + randomInt = notImplemented("crypto.randomInt"); + scrypt = notImplemented("crypto.scrypt"); + scryptSync = notImplemented("crypto.scryptSync"); + sign = notImplemented("crypto.sign"); + setEngine = notImplemented("crypto.setEngine"); + timingSafeEqual = notImplemented("crypto.timingSafeEqual"); + getFips = notImplemented("crypto.getFips"); + setFips = notImplemented("crypto.setFips"); + verify = notImplemented("crypto.verify"); + secureHeapUsed = notImplemented( + "crypto.secureHeapUsed" + ); + hash = notImplemented("crypto.hash"); + Certificate = notImplementedClass( + "crypto.Certificate" + ); + Cipher = notImplementedClass( + "crypto.Cipher" + ); + Cipheriv = notImplementedClass( + "crypto.Cipheriv" + // @ts-expect-error not typed yet + ); + Decipher = notImplementedClass( + "crypto.Decipher" + ); + Decipheriv = notImplementedClass( + "crypto.Decipheriv" + // @ts-expect-error not typed yet + ); + DiffieHellman = notImplementedClass( + "crypto.DiffieHellman" + ); + DiffieHellmanGroup = notImplementedClass( + "crypto.DiffieHellmanGroup" + ); + ECDH = notImplementedClass( + "crypto.ECDH" + ); + Hash = notImplementedClass( + "crypto.Hash" + ); + Hmac = notImplementedClass( + "crypto.Hmac" + ); + KeyObject = notImplementedClass( + "crypto.KeyObject" + ); + Sign = notImplementedClass( + "crypto.Sign" + ); + Verify = notImplementedClass( + "crypto.Verify" + ); + X509Certificate = notImplementedClass( + "crypto.X509Certificate" + ); + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/crypto/internal/constants.mjs +var constants2, constants_default; +var init_constants = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/crypto/internal/constants.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + constants2 = { + ALPN_ENABLED: 1, + // Node.js v18 only + DH_CHECK_P_NOT_PRIME: 1, + DH_CHECK_P_NOT_SAFE_PRIME: 2, + DH_NOT_SUITABLE_GENERATOR: 8, + DH_UNABLE_TO_CHECK_GENERATOR: 4, + ENGINE_METHOD_ALL: 65535, + ENGINE_METHOD_CIPHERS: 64, + ENGINE_METHOD_DH: 4, + ENGINE_METHOD_DIGESTS: 128, + ENGINE_METHOD_DSA: 2, + ENGINE_METHOD_EC: 2048, + ENGINE_METHOD_NONE: 0, + ENGINE_METHOD_PKEY_ASN1_METHS: 1024, + ENGINE_METHOD_PKEY_METHS: 512, + ENGINE_METHOD_RAND: 8, + ENGINE_METHOD_RSA: 1, + OPENSSL_VERSION_NUMBER: 0, + // explicitly set to 0 to avoid version misdetection + POINT_CONVERSION_COMPRESSED: 2, + POINT_CONVERSION_HYBRID: 6, + POINT_CONVERSION_UNCOMPRESSED: 4, + RSA_NO_PADDING: 3, + RSA_PKCS1_OAEP_PADDING: 4, + RSA_PKCS1_PADDING: 1, + RSA_PKCS1_PSS_PADDING: 6, + RSA_PSS_SALTLEN_AUTO: -2, + RSA_PSS_SALTLEN_DIGEST: -1, + RSA_PSS_SALTLEN_MAX_SIGN: -2, + RSA_X931_PADDING: 5, + SSL_OP_ALL: 2147485776, + SSL_OP_ALLOW_NO_DHE_KEX: 1024, + SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: 262144, + SSL_OP_CIPHER_SERVER_PREFERENCE: 4194304, + SSL_OP_CISCO_ANYCONNECT: 32768, + SSL_OP_COOKIE_EXCHANGE: 8192, + SSL_OP_CRYPTOPRO_TLSEXT_BUG: 2147483648, + SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: 2048, + SSL_OP_EPHEMERAL_RSA: 0, + // Node.js v18 only + SSL_OP_LEGACY_SERVER_CONNECT: 4, + SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: 0, + // Node.js v18 only + SSL_OP_MICROSOFT_SESS_ID_BUG: 0, + // Node.js v18 only + SSL_OP_MSIE_SSLV2_RSA_PADDING: 0, + // Node.js v18 only + SSL_OP_NETSCAPE_CA_DN_BUG: 0, + // Node.js v18 only + SSL_OP_NETSCAPE_CHALLENGE_BUG: 0, + // Node.js v18 only + SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: 0, + // Node.js v18 only + SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: 0, + // Node.js v18 only + SSL_OP_NO_COMPRESSION: 131072, + SSL_OP_NO_ENCRYPT_THEN_MAC: 524288, + SSL_OP_NO_QUERY_MTU: 4096, + SSL_OP_NO_RENEGOTIATION: 1073741824, + SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: 65536, + SSL_OP_NO_SSLv2: 0, + SSL_OP_NO_SSLv3: 33554432, + SSL_OP_NO_TICKET: 16384, + SSL_OP_NO_TLSv1_1: 268435456, + SSL_OP_NO_TLSv1_2: 134217728, + SSL_OP_NO_TLSv1_3: 536870912, + SSL_OP_NO_TLSv1: 67108864, + SSL_OP_PKCS1_CHECK_1: 0, + // Node.js v18 only + SSL_OP_PKCS1_CHECK_2: 0, + // Node.js v18 only + SSL_OP_PRIORITIZE_CHACHA: 2097152, + SSL_OP_SINGLE_DH_USE: 0, + // Node.js v18 only + SSL_OP_SINGLE_ECDH_USE: 0, + // Node.js v18 only + SSL_OP_SSLEAY_080_CLIENT_DH_BUG: 0, + // Node.js v18 only + SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: 0, + // Node.js v18 only + SSL_OP_TLS_BLOCK_PADDING_BUG: 0, + // Node.js v18 only + SSL_OP_TLS_D5_BUG: 0, + // Node.js v18 only + SSL_OP_TLS_ROLLBACK_BUG: 8388608, + TLS1_1_VERSION: 0, + // explicitly set to 0 to avoid version misdetection + TLS1_2_VERSION: 0, + // explicitly set to 0 to avoid version misdetection + TLS1_3_VERSION: 0, + // explicitly set to 0 to avoid version misdetection + TLS1_VERSION: 0, + // explicitly set to 0 to avoid version misdetection + defaultCoreCipherList: "", + // explicitly set to "" to avoid version misdetection + get defaultCipherList() { + return constants2.defaultCoreCipherList; + }, + set defaultCipherList(_ignored) { + } + }; + constants_default = constants2; + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/crypto/index.mjs +var crypto_default; +var init_crypto = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/crypto/index.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + init_web(); + init_node(); + init_constants(); + init_web(); + init_node(); + init_constants(); + crypto_default = { + ...web_exports, + ...node_exports, + // @ts-expect-error @types/node is out of date - this is a bug in typings + constants: constants_default + }; + } +}); + +// ../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/crypto/$cloudflare.mjs +var workerdCrypto, Certificate2, DiffieHellman2, DiffieHellmanGroup2, Hash2, Hmac2, KeyObject2, X509Certificate2, checkPrime2, checkPrimeSync2, createDiffieHellman2, createDiffieHellmanGroup2, createHash2, createHmac2, createPrivateKey2, createPublicKey2, createSecretKey2, generateKey2, generateKeyPair2, generateKeyPairSync2, generateKeySync2, generatePrime2, generatePrimeSync2, getCiphers2, getCurves2, getDiffieHellman2, getFips2, getHashes2, hkdf2, hkdfSync2, pbkdf22, pbkdf2Sync2, randomBytes2, randomFill2, randomFillSync2, randomInt2, randomUUID2, scrypt2, scryptSync2, secureHeapUsed2, setEngine2, setFips2, subtle2, timingSafeEqual2, getRandomValues2, webcrypto2, fips2, cloudflare_default3; +var init_cloudflare4 = __esm({ + "../../../../../opt/hostedtoolcache/node/18.20.4/x64/lib/node_modules/wrangler/node_modules/unenv/runtime/node/crypto/$cloudflare.mjs"() { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + init_crypto(); + init_crypto(); + workerdCrypto = process.getBuiltinModule("node:crypto"); + ({ + Certificate: Certificate2, + DiffieHellman: DiffieHellman2, + DiffieHellmanGroup: DiffieHellmanGroup2, + Hash: Hash2, + Hmac: Hmac2, + KeyObject: KeyObject2, + X509Certificate: X509Certificate2, + checkPrime: checkPrime2, + checkPrimeSync: checkPrimeSync2, + createDiffieHellman: createDiffieHellman2, + createDiffieHellmanGroup: createDiffieHellmanGroup2, + createHash: createHash2, + createHmac: createHmac2, + createPrivateKey: createPrivateKey2, + createPublicKey: createPublicKey2, + createSecretKey: createSecretKey2, + generateKey: generateKey2, + generateKeyPair: generateKeyPair2, + generateKeyPairSync: generateKeyPairSync2, + generateKeySync: generateKeySync2, + generatePrime: generatePrime2, + generatePrimeSync: generatePrimeSync2, + getCiphers: getCiphers2, + getCurves: getCurves2, + getDiffieHellman: getDiffieHellman2, + getFips: getFips2, + getHashes: getHashes2, + hkdf: hkdf2, + hkdfSync: hkdfSync2, + pbkdf2: pbkdf22, + pbkdf2Sync: pbkdf2Sync2, + randomBytes: randomBytes2, + randomFill: randomFill2, + randomFillSync: randomFillSync2, + randomInt: randomInt2, + randomUUID: randomUUID2, + scrypt: scrypt2, + scryptSync: scryptSync2, + secureHeapUsed: secureHeapUsed2, + setEngine: setEngine2, + setFips: setFips2, + subtle: subtle2, + timingSafeEqual: timingSafeEqual2 + } = workerdCrypto); + getRandomValues2 = workerdCrypto.getRandomValues.bind( + workerdCrypto.webcrypto + ); + webcrypto2 = { + CryptoKey: webcrypto.CryptoKey, + getRandomValues: getRandomValues2, + randomUUID: randomUUID2, + subtle: subtle2 + }; + fips2 = workerdCrypto.fips; + cloudflare_default3 = { + /** + * manually unroll unenv-polyfilled-symbols to make it tree-shakeable + */ + Certificate: Certificate2, + Cipher, + Cipheriv, + Decipher, + Decipheriv, + ECDH, + Sign, + Verify, + X509Certificate: X509Certificate2, + // @ts-expect-error @types/node is out of date - this is a bug in typings + constants: constants_default, + createCipheriv, + createDecipheriv, + createECDH, + createSign, + createVerify, + diffieHellman, + getCipherInfo, + hash, + privateDecrypt, + privateEncrypt, + publicDecrypt, + publicEncrypt, + scrypt: scrypt2, + scryptSync: scryptSync2, + sign, + verify, + // default-only export from unenv + createCipher, + createDecipher, + pseudoRandomBytes, + /** + * manually unroll workerd-polyfilled-symbols to make it tree-shakeable + */ + DiffieHellman: DiffieHellman2, + DiffieHellmanGroup: DiffieHellmanGroup2, + Hash: Hash2, + Hmac: Hmac2, + KeyObject: KeyObject2, + checkPrime: checkPrime2, + checkPrimeSync: checkPrimeSync2, + createDiffieHellman: createDiffieHellman2, + createDiffieHellmanGroup: createDiffieHellmanGroup2, + createHash: createHash2, + createHmac: createHmac2, + createPrivateKey: createPrivateKey2, + createPublicKey: createPublicKey2, + createSecretKey: createSecretKey2, + generateKey: generateKey2, + generateKeyPair: generateKeyPair2, + generateKeyPairSync: generateKeyPairSync2, + generateKeySync: generateKeySync2, + generatePrime: generatePrime2, + generatePrimeSync: generatePrimeSync2, + getCiphers: getCiphers2, + getCurves: getCurves2, + getDiffieHellman: getDiffieHellman2, + getFips: getFips2, + getHashes: getHashes2, + getRandomValues: getRandomValues2, + hkdf: hkdf2, + hkdfSync: hkdfSync2, + pbkdf2: pbkdf22, + pbkdf2Sync: pbkdf2Sync2, + randomBytes: randomBytes2, + randomFill: randomFill2, + randomFillSync: randomFillSync2, + randomInt: randomInt2, + randomUUID: randomUUID2, + secureHeapUsed: secureHeapUsed2, + setEngine: setEngine2, + setFips: setFips2, + subtle: subtle2, + timingSafeEqual: timingSafeEqual2, + // default-only export from workerd + fips: fips2, + // special-cased deep merged symbols + webcrypto: webcrypto2 + }; + } +}); + +// node-built-in-modules:crypto +var require_crypto = __commonJS({ + "node-built-in-modules:crypto"(exports, module) { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + init_cloudflare4(); + module.exports = cloudflare_default3; + } +}); + +// node_modules/tweetnacl/nacl-fast.js +var require_nacl_fast = __commonJS({ + "node_modules/tweetnacl/nacl-fast.js"(exports, module) { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + (function(nacl2) { + "use strict"; + var gf = /* @__PURE__ */ __name(function(init) { + var i, r = new Float64Array(16); + if (init) + for (i = 0; i < init.length; i++) + r[i] = init[i]; + return r; + }, "gf"); + var randombytes = /* @__PURE__ */ __name(function() { + throw new Error("no PRNG"); + }, "randombytes"); + 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; + } + __name(ts64, "ts64"); + 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; + } + __name(vn, "vn"); + function crypto_verify_16(x, xi, y, yi) { + return vn(x, xi, y, yi, 16); + } + __name(crypto_verify_16, "crypto_verify_16"); + function crypto_verify_32(x, xi, y, yi) { + return vn(x, xi, y, yi, 32); + } + __name(crypto_verify_32, "crypto_verify_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; + } + __name(core_salsa20, "core_salsa20"); + 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; + } + __name(core_hsalsa20, "core_hsalsa20"); + function crypto_core_salsa20(out, inp, k, c) { + core_salsa20(out, inp, k, c); + } + __name(crypto_core_salsa20, "crypto_core_salsa20"); + function crypto_core_hsalsa20(out, inp, k, c) { + core_hsalsa20(out, inp, k, c); + } + __name(crypto_core_hsalsa20, "crypto_core_hsalsa20"); + 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; + } + __name(crypto_stream_salsa20_xor, "crypto_stream_salsa20_xor"); + 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; + } + __name(crypto_stream_salsa20, "crypto_stream_salsa20"); + 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); + } + __name(crypto_stream, "crypto_stream"); + 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); + } + __name(crypto_stream_xor, "crypto_stream_xor"); + var poly1305 = /* @__PURE__ */ __name(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"); + 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; + } + __name(crypto_onetimeauth, "crypto_onetimeauth"); + 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); + } + __name(crypto_onetimeauth_verify, "crypto_onetimeauth_verify"); + 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; + } + __name(crypto_secretbox, "crypto_secretbox"); + 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; + } + __name(crypto_secretbox_open, "crypto_secretbox_open"); + function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) + r[i] = a[i] | 0; + } + __name(set25519, "set25519"); + 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); + } + __name(car25519, "car25519"); + 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; + } + } + __name(sel25519, "sel25519"); + 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; + } + } + __name(pack25519, "pack25519"); + 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); + } + __name(neq25519, "neq25519"); + function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; + } + __name(par25519, "par25519"); + 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; + } + __name(unpack25519, "unpack25519"); + function A(o, a, b) { + for (var i = 0; i < 16; i++) + o[i] = a[i] + b[i]; + } + __name(A, "A"); + function Z(o, a, b) { + for (var i = 0; i < 16; i++) + o[i] = a[i] - b[i]; + } + __name(Z, "Z"); + 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; + } + __name(M, "M"); + function S(o, a) { + M(o, a, a); + } + __name(S, "S"); + 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]; + } + __name(inv25519, "inv25519"); + 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]; + } + __name(pow2523, "pow2523"); + 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; + } + __name(crypto_scalarmult, "crypto_scalarmult"); + function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); + } + __name(crypto_scalarmult_base, "crypto_scalarmult_base"); + function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); + } + __name(crypto_box_keypair, "crypto_box_keypair"); + 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); + } + __name(crypto_box_beforenm, "crypto_box_beforenm"); + 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); + } + __name(crypto_box, "crypto_box"); + 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); + } + __name(crypto_box_open, "crypto_box_open"); + 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; + } + __name(crypto_hashblocks_hl, "crypto_hashblocks_hl"); + 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; + } + __name(crypto_hash, "crypto_hash"); + 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); + } + __name(add, "add"); + function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); + } + } + __name(cswap, "cswap"); + 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; + } + __name(pack, "pack"); + 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); + } + } + __name(scalarmult, "scalarmult"); + 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); + } + __name(scalarbase, "scalarbase"); + 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; + } + __name(crypto_sign_keypair, "crypto_sign_keypair"); + 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; + } + } + __name(modL, "modL"); + 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); + } + __name(reduce, "reduce"); + 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; + } + __name(crypto_sign, "crypto_sign"); + 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; + } + __name(unpackneg, "unpackneg"); + 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; + } + __name(crypto_sign_open, "crypto_sign_open"); + 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"); + } + __name(checkLengths, "checkLengths"); + 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"); + } + __name(checkBoxLengths, "checkBoxLengths"); + function checkArrayTypes() { + for (var i = 0; i < arguments.length; i++) { + if (!(arguments[i] instanceof Uint8Array)) + throw new TypeError("unexpected type, use Uint8Array"); + } + } + __name(checkArrayTypes, "checkArrayTypes"); + function cleanup(arr) { + for (var i = 0; i < arr.length; i++) + arr[i] = 0; + } + __name(cleanup, "cleanup"); + 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(fn2) { + randombytes = fn2; + }; + (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 || {}); + } +}); + +// node-built-in-modules:buffer +import libDefault from "buffer"; +var require_buffer = __commonJS({ + "node-built-in-modules:buffer"(exports, module) { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + module.exports = libDefault; + } +}); + +// node_modules/js-sha256/src/sha256.js +var require_sha256 = __commonJS({ + "node_modules/js-sha256/src/sha256.js"(exports, module) { + init_virtual_unenv_global_polyfill_process(); + init_virtual_unenv_global_polyfill_performance(); + init_virtual_unenv_global_polyfill_console(); + init_virtual_unenv_global_polyfill_set_immediate(); + init_virtual_unenv_global_polyfill_clear_immediate(); + (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 = /* @__PURE__ */ __name(function(outputType, is224) { + return function(message2) { + return new Sha256(is224, true).update(message2)[outputType](); + }; + }, "createOutputMethod"); + var createMethod = /* @__PURE__ */ __name(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; + }, "createMethod"); + var nodeWrap = /* @__PURE__ */ __name(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 = /* @__PURE__ */ __name(function(message2) { + return new Buffer2(message2); + }, "bufferFrom"); + } + var nodeMethod = /* @__PURE__ */ __name(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); + } + }, "nodeMethod"); + return nodeMethod; + }, "nodeWrap"); + var createHmacOutputMethod = /* @__PURE__ */ __name(function(outputType, is224) { + return function(key, message2) { + return new HmacSha256(key, is224, true).update(message2)[outputType](); + }; + }, "createHmacOutputMethod"); + var createHmacMethod = /* @__PURE__ */ __name(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; + }, "createHmacMethod"); + 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; + } + __name(Sha256, "Sha256"); + 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; + } + __name(HmacSha256, "HmacSha256"); + 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 +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +var import_tweetnacl = __toESM(require_nacl_fast()); +var import_js_sha256 = __toESM(require_sha256()); +import { connect } from "cloudflare:sockets"; + +// node_modules/jose/dist/browser/index.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); + +// node_modules/jose/dist/browser/runtime/base64url.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); + +// node_modules/jose/dist/browser/lib/buffer_utils.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); + +// node_modules/jose/dist/browser/runtime/webcrypto.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +var webcrypto_default = crypto; +var isCryptoKey = /* @__PURE__ */ __name((key) => key instanceof CryptoKey, "isCryptoKey"); + +// 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; +} +__name(concat, "concat"); + +// node_modules/jose/dist/browser/runtime/base64url.js +var encodeBase64 = /* @__PURE__ */ __name((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("")); +}, "encodeBase64"); +var encode = /* @__PURE__ */ __name((input) => { + return encodeBase64(input).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); +}, "encode"); +var decodeBase64 = /* @__PURE__ */ __name((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; +}, "decodeBase64"); +var decode = /* @__PURE__ */ __name((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."); + } +}, "decode"); + +// node_modules/jose/dist/browser/util/errors.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +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); + } +}; +__name(JOSEError, "JOSEError"); +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; + } +}; +__name(JWTClaimValidationFailed, "JWTClaimValidationFailed"); +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; + } +}; +__name(JWTExpired, "JWTExpired"); +JWTExpired.code = "ERR_JWT_EXPIRED"; +var JOSEAlgNotAllowed = class extends JOSEError { + constructor() { + super(...arguments); + this.code = "ERR_JOSE_ALG_NOT_ALLOWED"; + } +}; +__name(JOSEAlgNotAllowed, "JOSEAlgNotAllowed"); +JOSEAlgNotAllowed.code = "ERR_JOSE_ALG_NOT_ALLOWED"; +var JOSENotSupported = class extends JOSEError { + constructor() { + super(...arguments); + this.code = "ERR_JOSE_NOT_SUPPORTED"; + } +}; +__name(JOSENotSupported, "JOSENotSupported"); +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"; + } +}; +__name(JWEDecryptionFailed, "JWEDecryptionFailed"); +JWEDecryptionFailed.code = "ERR_JWE_DECRYPTION_FAILED"; +var JWEInvalid = class extends JOSEError { + constructor() { + super(...arguments); + this.code = "ERR_JWE_INVALID"; + } +}; +__name(JWEInvalid, "JWEInvalid"); +JWEInvalid.code = "ERR_JWE_INVALID"; +var JWSInvalid = class extends JOSEError { + constructor() { + super(...arguments); + this.code = "ERR_JWS_INVALID"; + } +}; +__name(JWSInvalid, "JWSInvalid"); +JWSInvalid.code = "ERR_JWS_INVALID"; +var JWTInvalid = class extends JOSEError { + constructor() { + super(...arguments); + this.code = "ERR_JWT_INVALID"; + } +}; +__name(JWTInvalid, "JWTInvalid"); +JWTInvalid.code = "ERR_JWT_INVALID"; +var JWKInvalid = class extends JOSEError { + constructor() { + super(...arguments); + this.code = "ERR_JWK_INVALID"; + } +}; +__name(JWKInvalid, "JWKInvalid"); +JWKInvalid.code = "ERR_JWK_INVALID"; +var JWKSInvalid = class extends JOSEError { + constructor() { + super(...arguments); + this.code = "ERR_JWKS_INVALID"; + } +}; +__name(JWKSInvalid, "JWKSInvalid"); +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"; + } +}; +__name(JWKSNoMatchingKey, "JWKSNoMatchingKey"); +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"; + } +}; +__name(JWKSMultipleMatchingKeys, "JWKSMultipleMatchingKeys"); +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"; + } +}; +__name(JWKSTimeout, "JWKSTimeout"); +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"; + } +}; +__name(JWSSignatureVerificationFailed, "JWSSignatureVerificationFailed"); +JWSSignatureVerificationFailed.code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; + +// node_modules/jose/dist/browser/lib/crypto_key.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +function unusable(name, prop = "algorithm.name") { + return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); +} +__name(unusable, "unusable"); +function isAlgorithm(algorithm, name) { + return algorithm.name === name; +} +__name(isAlgorithm, "isAlgorithm"); +function getHashLength(hash2) { + return parseInt(hash2.name.slice(4), 10); +} +__name(getHashLength, "getHashLength"); +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"); + } +} +__name(getNamedCurve, "getNamedCurve"); +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); + } +} +__name(checkUsage, "checkUsage"); +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); +} +__name(checkSigCryptoKey, "checkSigCryptoKey"); + +// node_modules/jose/dist/browser/lib/invalid_key_input.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +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; +} +__name(message, "message"); +var invalid_key_input_default = /* @__PURE__ */ __name((actual, ...types2) => { + return message("Key must be ", actual, ...types2); +}, "default"); +function withAlg(alg, actual, ...types2) { + return message(`Key for the ${alg} algorithm must be `, actual, ...types2); +} +__name(withAlg, "withAlg"); + +// node_modules/jose/dist/browser/runtime/is_key_like.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +var is_key_like_default = /* @__PURE__ */ __name((key) => { + if (isCryptoKey(key)) { + return true; + } + return key?.[Symbol.toStringTag] === "KeyObject"; +}, "default"); +var types = ["CryptoKey"]; + +// node_modules/jose/dist/browser/lib/is_disjoint.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +var isDisjoint = /* @__PURE__ */ __name((...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; +}, "isDisjoint"); +var is_disjoint_default = isDisjoint; + +// node_modules/jose/dist/browser/lib/is_object.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +function isObjectLike(value) { + return typeof value === "object" && value !== null; +} +__name(isObjectLike, "isObjectLike"); +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; +} +__name(isObject, "isObject"); + +// node_modules/jose/dist/browser/runtime/check_key_length.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +var check_key_length_default = /* @__PURE__ */ __name((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`); + } + } +}, "default"); + +// node_modules/jose/dist/browser/runtime/normalize_key.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); + +// node_modules/jose/dist/browser/lib/is_jwk.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +function isJWK(key) { + return isObject(key) && typeof key.kty === "string"; +} +__name(isJWK, "isJWK"); +function isPrivateJWK(key) { + return key.kty !== "oct" && typeof key.d === "string"; +} +__name(isPrivateJWK, "isPrivateJWK"); +function isPublicJWK(key) { + return key.kty !== "oct" && typeof key.d === "undefined"; +} +__name(isPublicJWK, "isPublicJWK"); +function isSecretJWK(key) { + return isJWK(key) && key.kty === "oct" && typeof key.k === "string"; +} +__name(isSecretJWK, "isSecretJWK"); + +// node_modules/jose/dist/browser/runtime/jwk_to_key.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +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 }; +} +__name(subtleMapping, "subtleMapping"); +var parse = /* @__PURE__ */ __name(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); +}, "parse"); +var jwk_to_key_default = parse; + +// node_modules/jose/dist/browser/runtime/normalize_key.js +var exportKeyValue = /* @__PURE__ */ __name((k) => decode(k), "exportKeyValue"); +var privCache; +var pubCache; +var isKeyObject = /* @__PURE__ */ __name((key) => { + return key?.[Symbol.toStringTag] === "KeyObject"; +}, "isKeyObject"); +var importAndCache = /* @__PURE__ */ __name(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; +}, "importAndCache"); +var normalizePublicKey = /* @__PURE__ */ __name((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; +}, "normalizePublicKey"); +var normalizePrivateKey = /* @__PURE__ */ __name((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; +}, "normalizePrivateKey"); +var normalize_key_default = { normalizePublicKey, normalizePrivateKey }; + +// node_modules/jose/dist/browser/key/import.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +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'); + } +} +__name(importJWK, "importJWK"); + +// node_modules/jose/dist/browser/lib/check_key_type.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +var tag = /* @__PURE__ */ __name((key) => key?.[Symbol.toStringTag], "tag"); +var jwkMatchesOp = /* @__PURE__ */ __name((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; +}, "jwkMatchesOp"); +var symmetricTypeCheck = /* @__PURE__ */ __name((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"`); + } +}, "symmetricTypeCheck"); +var asymmetricTypeCheck = /* @__PURE__ */ __name((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"`); + } +}, "asymmetricTypeCheck"); +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); + } +} +__name(checkKeyType, "checkKeyType"); +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 +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +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); +} +__name(validateCrit, "validateCrit"); +var validate_crit_default = validateCrit; + +// node_modules/jose/dist/browser/lib/validate_algorithms.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +var validateAlgorithms = /* @__PURE__ */ __name((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); +}, "validateAlgorithms"); +var validate_algorithms_default = validateAlgorithms; + +// node_modules/jose/dist/browser/jws/compact/verify.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); + +// node_modules/jose/dist/browser/jws/flattened/verify.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); + +// node_modules/jose/dist/browser/runtime/verify.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); + +// node_modules/jose/dist/browser/runtime/subtle_dsa.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +function subtleDsa(alg, algorithm) { + const hash2 = `SHA-${alg.slice(-3)}`; + switch (alg) { + case "HS256": + case "HS384": + case "HS512": + return { hash: hash2, name: "HMAC" }; + case "PS256": + case "PS384": + case "PS512": + return { hash: hash2, name: "RSA-PSS", saltLength: alg.slice(-3) >> 3 }; + case "RS256": + case "RS384": + case "RS512": + return { hash: hash2, name: "RSASSA-PKCS1-v1_5" }; + case "ES256": + case "ES384": + case "ES512": + return { hash: hash2, 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`); + } +} +__name(subtleDsa, "subtleDsa"); + +// node_modules/jose/dist/browser/runtime/get_sign_verify_key.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +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")); +} +__name(getCryptoKey, "getCryptoKey"); + +// node_modules/jose/dist/browser/runtime/verify.js +var verify2 = /* @__PURE__ */ __name(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; + } +}, "verify"); +var verify_default = verify2; + +// 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; +} +__name(flattenedVerify, "flattenedVerify"); + +// 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; +} +__name(compactVerify, "compactVerify"); + +// node_modules/jose/dist/browser/jwt/verify.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); + +// node_modules/jose/dist/browser/lib/jwt_claims_set.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); + +// node_modules/jose/dist/browser/lib/epoch.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +var epoch_default = /* @__PURE__ */ __name((date) => Math.floor(date.getTime() / 1e3), "default"); + +// node_modules/jose/dist/browser/lib/secs.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +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 = /* @__PURE__ */ __name((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; +}, "default"); + +// node_modules/jose/dist/browser/lib/jwt_claims_set.js +var normalizeTyp = /* @__PURE__ */ __name((value) => value.toLowerCase().replace(/^application\//, ""), "normalizeTyp"); +var checkAudiencePresence = /* @__PURE__ */ __name((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; +}, "checkAudiencePresence"); +var jwt_claims_set_default = /* @__PURE__ */ __name((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; +}, "default"); + +// 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; +} +__name(jwtVerify, "jwtVerify"); + +// node_modules/jose/dist/browser/jws/compact/sign.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); + +// node_modules/jose/dist/browser/jws/flattened/sign.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); + +// node_modules/jose/dist/browser/runtime/sign.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +var sign2 = /* @__PURE__ */ __name(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); +}, "sign"); +var sign_default = sign2; + +// 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; + } +}; +__name(FlattenedSign, "FlattenedSign"); + +// 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}`; + } +}; +__name(CompactSign, "CompactSign"); + +// node_modules/jose/dist/browser/jwt/sign.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); + +// node_modules/jose/dist/browser/jwt/produce.js +init_virtual_unenv_global_polyfill_process(); +init_virtual_unenv_global_polyfill_performance(); +init_virtual_unenv_global_polyfill_console(); +init_virtual_unenv_global_polyfill_set_immediate(); +init_virtual_unenv_global_polyfill_clear_immediate(); +function validateInput(label, input) { + if (!Number.isFinite(input)) { + throw new TypeError(`Invalid ${label} input`); + } + return input; +} +__name(validateInput, "validateInput"); +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; + } +}; +__name(ProduceJWT, "ProduceJWT"); + +// 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); + } +}; +__name(SignJWT, "SignJWT"); + +// 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.1"; +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, env3) { + try { + userID = env3.UUID || userID; + proxyIP = env3.PROXYIP || proxyIP; + dohURL = env3.DNS_RESOLVER_URL || dohURL; + trojanPassword = env3.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(env3); + 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 "/update-warp": + const Auth = await Authenticate(request, env3); + if (!Auth) + return new Response("Unauthorized", { status: 401 }); + if (request.method === "POST") { + try { + const { error: warpPlusError } = await fetchWgConfig(env3, settings); + if (warpPlusError) { + return new Response(warpPlusError, { status: 400 }); + } else { + return new Response("Warp configs updated successfully", { status: 200 }); + } + } catch (error3) { + console.log(error3); + return new Response(`An error occurred while updating Warp configs! - ${error3}`, { status: 500 }); + } + } else { + return new Response("Unsupported request", { status: 405 }); + } + case `/sub/${userID}`: + if (client === "sfa") { + const BestPingSFA = await getSingBoxCustomConfig(env3, 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(env3, 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(env3, 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(env3, settings, host, client, true) : await getXrayCustomConfigs(env3, 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 isAuth = await Authenticate(request, env3); + 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(env3, null, true) : await updateDataset(env3, formData); + return new Response("Success", { status: 200 }); + } + const pwd = await env3.bpb.get("pwd"); + if (pwd && !isAuth) + return Response.redirect(`${url.origin}/login`, 302); + const isPassSet = pwd?.length >= 8; + const homePage = renderHomePage(request, 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", + "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate", + "CDN-Cache-Control": "no-store" + } + }); + case "/login": + if (typeof env3.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, env3); + if (loginAuth) + return Response.redirect(`${url.origin}/panel`, 302); + let secretKey = await env3.bpb.get("secretKey"); + if (!secretKey) { + secretKey = generateSecretKey(); + await env3.bpb.put("secretKey", secretKey); + } + if (request.method === "POST") { + const password = await request.text(); + const savedPass = await env3.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 env3.bpb.get("pwd"); + let passAuth = await Authenticate(request, env3); + 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 env3.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 log3 = /* @__PURE__ */ __name((info3, event) => { + console.log(`[${address}:${portWithRandomLog}] ${info3}`, event || ""); + }, "log"); + const earlyDataHeader = request.headers.get("sec-websocket-protocol") || ""; + const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log3); + 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, log3); + udpStreamWrite = write; + udpStreamWrite(rawClientData); + return; + } + handleTCPOutBound( + request, + remoteSocketWapper, + addressRemote, + portRemote, + rawClientData, + webSocket, + vlessResponseHeader, + log3 + ); + }, + close() { + log3(`readableWebSocketStream is close`); + }, + abort(reason) { + log3(`readableWebSocketStream is abort`, JSON.stringify(reason)); + } + }) + ).catch((err) => { + log3("readableWebSocketStream pipeTo error", err); + }); + return new Response(null, { + status: 101, + // @ts-ignore + webSocket: client + }); +} +__name(vlessOverWSHandler, "vlessOverWSHandler"); +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 (error3) { + console.error("Error:", error3); + return false; + } +} +__name(checkUuidInApiResponse, "checkUuidInApiResponse"); +async function trojanOverWSHandler(request) { + const webSocketPair = new WebSocketPair(); + const [client, webSocket] = Object.values(webSocketPair); + webSocket.accept(); + let address = ""; + let portWithRandomLog = ""; + const log3 = /* @__PURE__ */ __name((info3, event) => { + console.log(`[${address}:${portWithRandomLog}] ${info3}`, event || ""); + }, "log"); + const earlyDataHeader = request.headers.get("sec-websocket-protocol") || ""; + const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log3); + 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, log3); + }, + close() { + log3(`readableWebSocketStream is closed`); + }, + abort(reason) { + log3(`readableWebSocketStream is aborted`, JSON.stringify(reason)); + } + }) + ).catch((err) => { + log3("readableWebSocketStream pipeTo error", err); + }); + return new Response(null, { + status: 101, + // @ts-ignore + webSocket: client + }); +} +__name(trojanOverWSHandler, "trojanOverWSHandler"); +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) + }; +} +__name(parseTrojanHeader, "parseTrojanHeader"); +async function handleTCPOutBound(request, remoteSocket, addressRemote, portRemote, rawClientData, webSocket, vlessResponseHeader, log3) { + 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; + log3(`connected to ${address}:${port}`); + const writer = tcpSocket2.writable.getWriter(); + await writer.write(rawClientData); + writer.releaseLock(); + return tcpSocket2; + } + __name(connectAndWrite, "connectAndWrite"); + 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((error3) => { + console.log("retry tcpSocket closed error", error3); + }).finally(() => { + safeCloseWebSocket(webSocket); + }); + vlessResponseHeader ? vlessRemoteSocketToWS(tcpSocket2, webSocket, vlessResponseHeader, null, log3) : trojanRemoteSocketToWS(tcpSocket2, webSocket, null, log3); + } + __name(retry, "retry"); + const tcpSocket = await connectAndWrite(addressRemote, portRemote); + vlessResponseHeader ? vlessRemoteSocketToWS(tcpSocket, webSocket, vlessResponseHeader, retry, log3) : trojanRemoteSocketToWS(tcpSocket, webSocket, retry, log3); +} +__name(handleTCPOutBound, "handleTCPOutBound"); +function makeReadableWebSocketStream(webSocketServer, earlyDataHeader, log3) { + 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) => { + log3("webSocketServer has error"); + controller.error(err); + }); + const { earlyData, error: error3 } = base64ToArrayBuffer(earlyDataHeader); + if (error3) { + controller.error(error3); + } else if (earlyData) { + controller.enqueue(earlyData); + } + }, + pull(controller) { + }, + cancel(reason) { + if (readableStreamCancel) { + return; + } + log3(`ReadableStream was canceled, due to ${reason}`); + readableStreamCancel = true; + safeCloseWebSocket(webSocketServer); + } + }); + return stream; +} +__name(makeReadableWebSocketStream, "makeReadableWebSocketStream"); +async function processVlessHeader(vlessBuffer, userID2) { + if (vlessBuffer.byteLength < 24) { + return { + hasError: true, + message: "invalid data" + }; + } + const version2 = 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: version2, + isUDP + }; +} +__name(processVlessHeader, "processVlessHeader"); +async function vlessRemoteSocketToWS(remoteSocket, webSocket, vlessResponseHeader, retry, log3) { + 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() { + log3(`remoteConnection!.readable is close with hasIncomingData is ${hasIncomingData}`); + }, + abort(reason) { + console.error(`remoteConnection!.readable abort`, reason); + } + }) + ).catch((error3) => { + console.error(`vlessRemoteSocketToWS has exception `, error3.stack || error3); + safeCloseWebSocket(webSocket); + }); + if (hasIncomingData === false && retry) { + log3(`retry`); + retry(); + } +} +__name(vlessRemoteSocketToWS, "vlessRemoteSocketToWS"); +async function trojanRemoteSocketToWS(remoteSocket, webSocket, retry, log3) { + 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() { + log3(`remoteSocket.readable is closed, hasIncomingData: ${hasIncomingData}`); + }, + abort(reason) { + console.error("remoteSocket.readable abort", reason); + } + }) + ).catch((error3) => { + console.error(`trojanRemoteSocketToWS error:`, error3.stack || error3); + safeCloseWebSocket(webSocket); + }); + if (hasIncomingData === false && retry) { + log3(`retry`); + retry(); + } +} +__name(trojanRemoteSocketToWS, "trojanRemoteSocketToWS"); +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 (error3) { + return { earlyData: null, error: error3 }; + } +} +__name(base64ToArrayBuffer, "base64ToArrayBuffer"); +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); +} +__name(isValidUUID, "isValidUUID"); +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 (error3) { + console.error("safeCloseWebSocket error", error3); + } +} +__name(safeCloseWebSocket, "safeCloseWebSocket"); +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(); +} +__name(unsafeStringify, "unsafeStringify"); +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); + if (!isValidUUID(uuid)) { + throw TypeError("Stringified UUID is invalid"); + } + return uuid; +} +__name(stringify, "stringify"); +async function handleUDPOutBound(webSocket, vlessResponseHeader, log3) { + 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) { + log3(`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((error3) => { + log3("dns udp has error" + error3); + }); + const writer = transformStream.writable.getWriter(); + return { + /** + * + * @param {Uint8Array} chunk + */ + write(chunk) { + writer.write(chunk); + } + }; +} +__name(handleUDPOutBound, "handleUDPOutBound"); +var generateKeyPair3 = /* @__PURE__ */ __name(() => { + const base64Encode = /* @__PURE__ */ __name((array) => btoa(String.fromCharCode.apply(null, array)), "base64Encode"); + 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 }; +}, "generateKeyPair"); +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}`; +} +__name(generateRemark, "generateRemark"); +function isDomain(address) { + const domainPattern = /^(?!\-)(?:[A-Za-z0-9\-]{1,63}\.)+[A-Za-z]{2,}$/; + return domainPattern.test(address); +} +__name(isDomain, "isDomain"); +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); +} +__name(isIPv4, "isIPv4"); +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); +} +__name(isIPv6, "isIPv6"); +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; +} +__name(base64ToDecimal, "base64ToDecimal"); +async function getDataset(env3) { + let proxySettings, warpConfigs; + if (typeof env3.bpb !== "object") { + return { kvNotFound: true, proxySettings: null, warpConfigs: null }; + } + try { + proxySettings = await env3.bpb.get("proxySettings", { type: "json" }); + warpConfigs = await env3.bpb.get("warpConfigs", { type: "json" }); + } catch (error3) { + console.log(error3); + throw new Error(`An error occurred while getting KV - ${error3}`); + } + if (!proxySettings) { + proxySettings = await updateDataset(env3); + const { error: error3, configs } = await fetchWgConfig(env3, proxySettings); + if (error3) + throw new Error(`An error occurred while getting Warp configs - ${error3}`); + warpConfigs = configs; + } + if (panelVersion !== proxySettings.panelVersion) + proxySettings = await updateDataset(env3); + return { kvNotFound: false, proxySettings, warpConfigs }; +} +__name(getDataset, "getDataset"); +async function updateDataset(env3, newSettings, resetSettings) { + let currentSettings; + if (!resetSettings) { + try { + currentSettings = await env3.bpb.get("proxySettings", { type: "json" }); + } catch (error3) { + console.log(error3); + throw new Error(`An error occurred while getting current KV settings - ${error3}`); + } + } else { + await env3.bpb.delete("warpConfigs"); + } + const validateField = /* @__PURE__ */ __name((field) => { + const fieldValue = newSettings?.get(field); + if (fieldValue === void 0) + return null; + if (fieldValue === "true") + return true; + if (fieldValue === "false") + return false; + return fieldValue; + }, "validateField"); + const remoteDNS = validateField("remoteDNS") ?? currentSettings?.remoteDNS ?? "https://8.8.8.8/dns-query"; + const enableIPv6 = validateField("enableIPv6") ?? currentSettings?.enableIPv6 ?? true; + 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: enableIPv6 ? [...resolvedDomain.ipv4, ...resolvedDomain.ipv6] : resolvedDomain.ipv4 + }; + } catch (error3) { + console.log(error3); + throw new Error(`An error occurred while resolving remote DNS server, please try agian! - ${error3}`); + } + } + const proxySettings = { + remoteDNS, + 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, + 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, + warpEnableIPv6: validateField("warpEnableIPv6") ?? currentSettings?.warpEnableIPv6 ?? true, + 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 env3.bpb.put("proxySettings", JSON.stringify(proxySettings)); + } catch (error3) { + console.log(error3); + throw new Error(`An error occurred while updating KV - ${error3}`); + } + return proxySettings; +} +__name(updateDataset, "updateDataset"); +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; +} +__name(randomUpperCase, "randomUpperCase"); +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; +} +__name(getRandomPath, "getRandomPath"); +async function resolveDNS(domain2) { + const dohURLv4 = `${dohURL}?name=${encodeURIComponent(domain2)}&type=A`; + const dohURLv6 = `${dohURL}?name=${encodeURIComponent(domain2)}&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 (error3) { + console.error("Error resolving DNS:", error3); + throw new Error(`An error occurred while resolving DNS - ${error3}`); + } +} +__name(resolveDNS, "resolveDNS"); +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(",") : [] + ]; +} +__name(getConfigAddresses, "getConfigAddresses"); +async function generateJWTToken(secretKey) { + const secret = new TextEncoder().encode(secretKey); + return await new SignJWT({ userID }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime("24h").sign(secret); +} +__name(generateJWTToken, "generateJWTToken"); +function generateSecretKey() { + const key = import_tweetnacl.default.randomBytes(32); + return Array.from(key, (byte) => byte.toString(16).padStart(2, "0")).join(""); +} +__name(generateSecretKey, "generateSecretKey"); +async function Authenticate(request, env3) { + try { + const secretKey = await env3.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 authenticated, User ID: ${payload.userID}`); + return true; + } catch (error3) { + console.log(error3); + return false; + } +} +__name(Authenticate, "Authenticate"); +function renderHomePage(request, 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, + warpEnableIPv6, + 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]; + let regionNames = new Intl.DisplayNames(["en"], { type: "region" }); + const cfCountry = regionNames.of(request.cf.country); + allPorts.forEach((port) => { + const id = `port-${port}`; + const isChecked = ports.includes(port) ? "checked" : ""; + const portBlock = ` +
+ + +
`; + defaultHttpsPorts.includes(port) ? httpsPortsBlock += portBlock : httpPortsBlock += portBlock; + }); + return ` + + + + + + BPB Panel ${panelVersion} + + + Collapsible Sections + + + +

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

+
+
+
+

VLESS / TROJAN \u2699\uFE0F

+
+ + +
+
+ + +
+
+ +
+ +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + + + +
+
+ +
+ +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+
+
+ + + + + + + + + + ${!httpPortsBlock ? "" : ` + + + `} +
Config typePorts
TLS +
${httpsPortsBlock}
+
Non TLS +
${httpPortsBlock}
+
+
+
+
+

FRAGMENT \u2699\uFE0F

+
+ +
+ + - + +
+
+
+ +
+ + - + +
+
+
+ +
+ +
+
+
+
+

WARP GENERAL \u2699\uFE0F

+
+ + +
+
+ + +
+
+ +
+ +
+
+
+ +
+ +
+
+
+ + +
+
+ + +
+
+ + +
+
+
+

WARP PRO \u2699\uFE0F

+
+ + +
+
+ + +
+
+ +
+ + - + +
+
+
+ +
+ + - + +
+
+
+ +
+ + - + +
+
+
+
+

ROUTING RULES \u2699\uFE0F

+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+
+
+ + +
+
+
+
+

NORMAL SUB \u{1F517}

+
+ + + + + + + + + + + + + +
ApplicationSubscription
+
+ 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}

+
+ + + + + + + + + + + + + + + + + +
ApplicationSubscription
+
+ 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

+
+ + + + + + + + + + + + + +
ApplicationSubscription
+
+ verified + v2rayNG +
+
+ verified + NikaNG +
+
+ verified + MahsaNG +
+
+ verified + v2rayN +
+
+ verified + v2rayN-PRO +
+
+ verified + Streisand +
+
+ + +
+
+ verified + Hiddify +
+
+ + +
+
+

WARP SUB \u{1F517}

+
+ + + + + + + + + + + + + + + + + +
ApplicationSubscription
+
+ 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}

+
+ + + + + + + + + + + + + +
ApplicationSubscription
+
+ verified + NikaNG +
+
+ verified + MahsaNG +
+
+ verified + v2rayN-PRO +
+
+ + +
+
+ verified + Hiddify +
+
+ + +
+
+ +
+ +
+
+

YOUR IP \u{1F4A1}

+
+ + + + + + + + + + + + + + + + + + + + + + +
TargetYour IPCountryCityISP
Cloudflare${request.headers.get("cf-connecting-ip") || "Not found!"}${cfCountry || "Not found!"}${request.cf.city || "Not found!"}${request.cf.asOrganization || "Not found!"}
Others
+
+
+ +
+ +