miqro 6.1.4 → 6.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/build/editor.bundle.js +10 -2
  2. package/build/esm/editor/components/editor.js +8 -0
  3. package/build/esm/editor/components/file-editor.js +1 -1
  4. package/build/esm/editor/components/highlight-text-area.js +2 -1
  5. package/build/esm/src/common/arguments.d.ts +7 -0
  6. package/build/esm/src/common/arguments.js +103 -2
  7. package/build/esm/src/common/help.d.ts +1 -1
  8. package/build/esm/src/common/help.js +4 -0
  9. package/build/esm/src/common/jwt.d.ts +49 -0
  10. package/build/esm/src/common/jwt.js +76 -0
  11. package/build/esm/src/inflate/inflate-sea.js +9 -8
  12. package/build/esm/src/inflate/setup-http.d.ts +1 -0
  13. package/build/esm/src/inflate/setup-http.js +8 -0
  14. package/build/esm/src/lib.d.ts +1 -1
  15. package/build/esm/src/lib.js +2 -2
  16. package/build/esm/src/main.js +4 -1
  17. package/build/esm/src/services/app.d.ts +5 -0
  18. package/build/esm/src/services/app.js +33 -7
  19. package/build/esm/src/services/globals.js +45 -1
  20. package/build/esm/src/services/utils/cluster-ws.d.ts +4 -2
  21. package/build/esm/src/services/utils/cluster-ws.js +10 -1
  22. package/build/esm/src/services/utils/server-interface.d.ts +4 -30
  23. package/build/esm/src/services/utils/server-interface.js +53 -64
  24. package/build/esm/src/services/utils/websocketmanager.d.ts +3 -0
  25. package/build/esm/src/services/utils/websocketmanager.js +8 -2
  26. package/build/esm/src/types.d.ts +85 -5
  27. package/build/lib.cjs +3026 -367
  28. package/editor/components/editor.tsx +8 -0
  29. package/editor/components/file-editor.tsx +1 -1
  30. package/editor/components/highlight-text-area.tsx +2 -1
  31. package/package.json +5 -4
  32. package/sea/install-nodejs.sh +1 -1
  33. package/sea/node.version.tag +1 -1
  34. package/sea/types.json +1 -1
  35. package/src/common/arguments.ts +118 -2
  36. package/src/common/help.ts +4 -0
  37. package/src/common/jwt.ts +85 -0
  38. package/src/inflate/inflate-sea.ts +9 -8
  39. package/src/inflate/setup-http.ts +9 -0
  40. package/src/lib.ts +2 -2
  41. package/src/main.ts +4 -1
  42. package/src/services/app.ts +38 -7
  43. package/src/services/globals.ts +45 -2
  44. package/src/services/utils/cluster-ws.ts +6 -1
  45. package/src/services/utils/server-interface.ts +53 -140
  46. package/src/services/utils/websocketmanager.ts +10 -2
  47. package/src/types/browser.globals.d.ts +0 -8
  48. package/src/types/cookie.d.ts +2 -0
  49. package/src/types/jose.d.ts +2 -0
  50. package/src/types/jsx.globals.d.ts +1 -0
  51. package/src/types/miqro.d.ts +101 -2
  52. package/src/types/server.globals.d.ts +4 -29
  53. package/src/types.ts +87 -5
package/build/lib.cjs CHANGED
@@ -55,7 +55,7 @@ var require_dist = __commonJS({
55
55
  const len = str.length;
56
56
  if (len < 2)
57
57
  return obj;
58
- const dec = options?.decode || decode;
58
+ const dec = options?.decode || decode2;
59
59
  let index = 0;
60
60
  do {
61
61
  const eqIdx = str.indexOf("=", index);
@@ -176,7 +176,7 @@ var require_dist = __commonJS({
176
176
  }
177
177
  return str;
178
178
  }
179
- function decode(str) {
179
+ function decode2(str) {
180
180
  if (str.indexOf("%") === -1)
181
181
  return str;
182
182
  try {
@@ -818,7 +818,7 @@ var require_showdown = __commonJS({
818
818
  };
819
819
  showdown2.helper.encodeEmailAddress = function(mail) {
820
820
  "use strict";
821
- var encode = [
821
+ var encode2 = [
822
822
  function(ch) {
823
823
  return "&#" + ch.charCodeAt(0) + ";";
824
824
  },
@@ -831,10 +831,10 @@ var require_showdown = __commonJS({
831
831
  ];
832
832
  mail = mail.replace(/./g, function(ch) {
833
833
  if (ch === "@") {
834
- ch = encode[Math.floor(Math.random() * 2)](ch);
834
+ ch = encode2[Math.floor(Math.random() * 2)](ch);
835
835
  } else {
836
836
  var r = Math.random();
837
- ch = r > 0.9 ? encode[2](ch) : r > 0.45 ? encode[1](ch) : encode[0](ch);
837
+ ch = r > 0.9 ? encode2[2](ch) : r > 0.45 ? encode2[1](ch) : encode2[0](ch);
838
838
  }
839
839
  return ch;
840
840
  });
@@ -4397,11 +4397,11 @@ __export(lib_exports2, {
4397
4397
  LoggerHandler: () => LoggerHandler,
4398
4398
  Miqro: () => Miqro,
4399
4399
  Router: () => Router,
4400
- ServerInterfaceImpl: () => ServerInterfaceImpl,
4401
4400
  ServerRequestHandler: () => ServerRequestHandler,
4402
4401
  WebSocketManager: () => WebSocketManager,
4403
4402
  appendAPIModule: () => appendAPIModule,
4404
4403
  assertGlobalTampered: () => assertGlobalTampered,
4404
+ createServerInterface: () => createServerInterface,
4405
4405
  initGlobals: () => initGlobals,
4406
4406
  migration: () => lib_exports
4407
4407
  });
@@ -4423,8 +4423,8 @@ var import_querystring = require("querystring");
4423
4423
 
4424
4424
  // node_modules/@miqro/parser/build/built-in-parsers.js
4425
4425
  var ParseOptionsError = class extends Error {
4426
- constructor(message = "BAD REQUEST", argAttr) {
4427
- super(message);
4426
+ constructor(message2 = "BAD REQUEST", argAttr) {
4427
+ super(message2);
4428
4428
  this.argAttr = argAttr;
4429
4429
  this.name = "ParseOptionsError";
4430
4430
  }
@@ -5190,9 +5190,9 @@ function TextParser(options) {
5190
5190
  }
5191
5191
  };
5192
5192
  }
5193
- function assertNotUndefined(arg, message) {
5193
+ function assertNotUndefined(arg, message2) {
5194
5194
  if (arg === void 0) {
5195
- throw new Error(message ? message : "arg undefined");
5195
+ throw new Error(message2 ? message2 : "arg undefined");
5196
5196
  }
5197
5197
  return arg;
5198
5198
  }
@@ -6099,28 +6099,28 @@ var Logger = class extends EventTarget {
6099
6099
  }
6100
6100
  }
6101
6101
  /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
6102
- debug(message, ...optionalParams) {
6103
- return this.write({ level: "debug", message, optionalParams, identifier: this.identifier, meta: [] });
6102
+ debug(message2, ...optionalParams) {
6103
+ return this.write({ level: "debug", message: message2, optionalParams, identifier: this.identifier, meta: [] });
6104
6104
  }
6105
6105
  /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
6106
- error(message, ...optionalParams) {
6107
- return this.write({ level: "error", message, optionalParams, identifier: this.identifier, meta: [] });
6106
+ error(message2, ...optionalParams) {
6107
+ return this.write({ level: "error", message: message2, optionalParams, identifier: this.identifier, meta: [] });
6108
6108
  }
6109
6109
  /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
6110
- info(message, ...optionalParams) {
6111
- return this.write({ level: "info", message, optionalParams, identifier: this.identifier, meta: [] });
6110
+ info(message2, ...optionalParams) {
6111
+ return this.write({ level: "info", message: message2, optionalParams, identifier: this.identifier, meta: [] });
6112
6112
  }
6113
6113
  /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
6114
- log(message, ...optionalParams) {
6115
- return this.write({ level: "info", message, optionalParams, identifier: this.identifier, meta: [] });
6114
+ log(message2, ...optionalParams) {
6115
+ return this.write({ level: "info", message: message2, optionalParams, identifier: this.identifier, meta: [] });
6116
6116
  }
6117
6117
  /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
6118
- trace(message, ...optionalParams) {
6119
- return this.write({ level: "trace", message, optionalParams, identifier: this.identifier, meta: [] });
6118
+ trace(message2, ...optionalParams) {
6119
+ return this.write({ level: "trace", message: message2, optionalParams, identifier: this.identifier, meta: [] });
6120
6120
  }
6121
6121
  /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
6122
- warn(message, ...optionalParams) {
6123
- return this.write({ level: "warn", message, optionalParams, identifier: this.identifier, meta: [] });
6122
+ warn(message2, ...optionalParams) {
6123
+ return this.write({ level: "warn", message: message2, optionalParams, identifier: this.identifier, meta: [] });
6124
6124
  }
6125
6125
  };
6126
6126
  var FILE_TRANSPORT_ENV_VARIABLE = "LOG_FILE";
@@ -6233,7 +6233,7 @@ var DEFAULT_LOGGER_TRANSPORTS = () => [
6233
6233
  ConsoleTransport(),
6234
6234
  FileTransport()
6235
6235
  ];
6236
- var DEFAULT_LOGGER_FORMATTER = ({ identifier, level, message, optionalParams }) => (0, import_node_util.format)(`${(/* @__PURE__ */ new Date()).toISOString()} ${process.pid} ${identifier ? `[${identifier}] ` : ""}${level !== "info" ? level === "error" || level === "warn" ? `[${level.toUpperCase()}] ` : `[${level}] ` : ""}${message}`, ...optionalParams);
6236
+ var DEFAULT_LOGGER_FORMATTER = ({ identifier, level, message: message2, optionalParams }) => (0, import_node_util.format)(`${(/* @__PURE__ */ new Date()).toISOString()} ${process.pid} ${identifier ? `[${identifier}] ` : ""}${level !== "info" ? level === "error" || level === "warn" ? `[${level.toUpperCase()}] ` : `[${level}] ` : ""}${message2}`, ...optionalParams);
6237
6237
  var LOG_LEVEL_MAP = {
6238
6238
  "none": 0,
6239
6239
  "error": 1,
@@ -6313,20 +6313,20 @@ function routerDefaultLoggerFactory(uuid, req) {
6313
6313
  return logger;
6314
6314
  }
6315
6315
  var BadRequestError = class extends Error {
6316
- constructor(message = "BAD REQUEST") {
6317
- super(message);
6316
+ constructor(message2 = "BAD REQUEST") {
6317
+ super(message2);
6318
6318
  this.name = "BadRequestError";
6319
6319
  }
6320
6320
  };
6321
6321
  var ForbiddenError = class extends Error {
6322
- constructor(message = "FORBIDDEN") {
6323
- super(message);
6322
+ constructor(message2 = "FORBIDDEN") {
6323
+ super(message2);
6324
6324
  this.name = "ForbiddenError";
6325
6325
  }
6326
6326
  };
6327
6327
  var UnAuthorizedError = class extends Error {
6328
- constructor(message = "UNAUTHORIZED") {
6329
- super(message);
6328
+ constructor(message2 = "UNAUTHORIZED") {
6329
+ super(message2);
6330
6330
  this.name = "UnAuthorizedError";
6331
6331
  }
6332
6332
  };
@@ -6424,6 +6424,7 @@ var getEnvVariable = (envName, defaults) => {
6424
6424
 
6425
6425
  // node_modules/@miqro/core/build/app.js
6426
6426
  var import_http2 = require("http");
6427
+ var import_https = require("https");
6427
6428
 
6428
6429
  // node_modules/@miqro/core/build/middleware/router.js
6429
6430
  var Router = class {
@@ -6748,7 +6749,8 @@ var App = class extends Router {
6748
6749
  console.error(loggerError);
6749
6750
  }
6750
6751
  };
6751
- this.httpServer = (0, import_http2.createServer)(this.serverOptions, this.listener);
6752
+ const createS = config && config.https ? import_https.createServer : import_http2.createServer;
6753
+ this.httpServer = createS(this.serverOptions, this.listener);
6752
6754
  this.httpServer.on("connection", (conn) => {
6753
6755
  const key = (0, import_crypto2.randomUUID)();
6754
6756
  this.connections[key] = conn;
@@ -8591,11 +8593,12 @@ var down = {
8591
8593
  // src/services/utils/cluster-ws.ts
8592
8594
  var ClusterWebSocketServer2MessageType = "$$$$ClusterWebSocketServer2Message$$$$$";
8593
8595
  var ClusterWebSocketServer2 = class extends WebSocketServer {
8594
- constructor(name, options) {
8596
+ constructor(name, path, logger, options) {
8595
8597
  super({
8596
8598
  ...options,
8597
8599
  validate: (req) => {
8598
8600
  if (this.options.maxConnections !== void 0 && this.clients.size + this.remoteClients.size >= this.options.maxConnections) {
8601
+ this.logger?.warn("[%s] max web socket connection reached! connection refused from [%s]", req.uuid, req.socket.remoteAddress);
8599
8602
  return false;
8600
8603
  } else {
8601
8604
  return options.validate ? options.validate(req) : true;
@@ -8612,6 +8615,8 @@ var ClusterWebSocketServer2 = class extends WebSocketServer {
8612
8615
  errorMessage: error2.message
8613
8616
  });
8614
8617
  }
8618
+ this.logger?.error("[%s] error from (%s) error [%s]", req.uuid, req.req.socket.remoteAddress, error2);
8619
+ this.logger?.error(error2);
8615
8620
  if (options.onError) {
8616
8621
  options.onError(req, error2);
8617
8622
  }
@@ -8626,6 +8631,7 @@ var ClusterWebSocketServer2 = class extends WebSocketServer {
8626
8631
  clientUUID: req.uuid
8627
8632
  });
8628
8633
  }
8634
+ this.logger?.log("[%s] new web socket connection from (%s)", req.uuid, req.req.socket.remoteAddress);
8629
8635
  if (options.onConnection) {
8630
8636
  options.onConnection(req);
8631
8637
  }
@@ -8640,12 +8646,15 @@ var ClusterWebSocketServer2 = class extends WebSocketServer {
8640
8646
  clientUUID: req.uuid
8641
8647
  });
8642
8648
  }
8649
+ this.logger?.log("[%s] [%s] web socket disconnection from (%s)", req.uuid, this.path, req.req.socket.remoteAddress);
8643
8650
  if (options.onDisconnect) {
8644
8651
  options.onDisconnect(req);
8645
8652
  }
8646
8653
  }
8647
8654
  });
8648
8655
  this.name = name;
8656
+ this.path = path;
8657
+ this.logger = logger;
8649
8658
  this.listener = async (data) => {
8650
8659
  try {
8651
8660
  const msg = data;
@@ -9046,10 +9055,12 @@ var WebSocketManager = class {
9046
9055
  logger = null;
9047
9056
  name;
9048
9057
  avoidLogSocket;
9058
+ loggerProvider;
9049
9059
  constructor(options) {
9050
9060
  this.onUpgrade = this.onUpgrade.bind(this);
9051
9061
  this.logger = options && options.logger ? options.logger : null;
9052
9062
  this.name = options && options.name ? options.name : "WebSocketManager";
9063
+ this.loggerProvider = options.loggerProvider;
9053
9064
  this.avoidLogSocket = options && options.avoidLogSocket ? options.avoidLogSocket : false;
9054
9065
  }
9055
9066
  deleteWS(path) {
@@ -9074,7 +9085,9 @@ var WebSocketManager = class {
9074
9085
  throw new Error(`ws on path ${wsConfig.path} already setup!`);
9075
9086
  }
9076
9087
  this.logger?.debug("setting up websocket on [%s]", wsConfig.path);
9077
- const server2 = new ClusterWebSocketServer2(wsConfig.path, wsConfig);
9088
+ const identifier = wsConfig.path.replaceAll("/", "_").toUpperCase();
9089
+ const logger = this.loggerProvider && identifier.length >= 0 ? this.loggerProvider.getLogger(identifier.substring(identifier.charAt(0) === "_" ? 1 : 0)) : this.logger;
9090
+ const server2 = new ClusterWebSocketServer2(this.name + wsConfig.path, wsConfig.path, logger, wsConfig);
9078
9091
  this.runningGlobalWSMap.set(wsConfig.path, server2);
9079
9092
  }
9080
9093
  }
@@ -9092,7 +9105,9 @@ var WebSocketManager = class {
9092
9105
  throw new Error(`ws on path ${wsConfig.path} already setup!`);
9093
9106
  }
9094
9107
  this.logger?.debug("setting up websocket on [%s]", wsConfig.path);
9095
- const server2 = new ClusterWebSocketServer2(this.name + wsConfig.path, wsConfig);
9108
+ const identifier = wsConfig.path.replaceAll("/", "_").toUpperCase();
9109
+ const logger = this.loggerProvider && identifier.length >= 0 ? this.loggerProvider.getLogger(identifier.substring(identifier.charAt(0) === "_" ? 1 : 0)) : this.logger;
9110
+ const server2 = new ClusterWebSocketServer2(this.name + wsConfig.path, wsConfig.path, logger, wsConfig);
9096
9111
  this.runningGlobalWSMap.set(wsConfig.path, server2);
9097
9112
  }
9098
9113
  }
@@ -9233,7 +9248,7 @@ var DBManager = class {
9233
9248
  // src/services/utils/log.ts
9234
9249
  var import_node_util2 = require("node:util");
9235
9250
  var DEFAULT_ENV_NAME2 = "LOG_LEVEL";
9236
- var DEFAULT_FORMATTER = ({ identifier, level, message, optionalParams }) => (0, import_node_util2.format)(`${(/* @__PURE__ */ new Date()).toISOString()} PID[${process.pid}] ${identifier ? `[${identifier}] ` : ""}${level !== "info" ? level === "error" || level === "warn" ? `[${level.toUpperCase()}] ` : `[${level}] ` : ""}${message}`, ...optionalParams);
9251
+ var DEFAULT_FORMATTER = ({ identifier, level, message: message2, optionalParams }) => (0, import_node_util2.format)(`${(/* @__PURE__ */ new Date()).toISOString()} PID[${process.pid}] ${identifier ? `[${identifier}] ` : ""}${level !== "info" ? level === "error" || level === "warn" ? `[${level.toUpperCase()}] ` : `[${level}] ` : ""}${message2}`, ...optionalParams);
9237
9252
  var LogProvider = class {
9238
9253
  options;
9239
9254
  constructor(options) {
@@ -9392,13 +9407,13 @@ var CONTENT_TYPE_MAP = {
9392
9407
 
9393
9408
  // node_modules/@miqro/jsx/build/esm/vdom/log.js
9394
9409
  var debugLogEnabled = false;
9395
- function debug(runtime, message, ...args) {
9410
+ function debug(runtime, message2, ...args) {
9396
9411
  if (debugLogEnabled) {
9397
- runtime.consoleLog(message, ...args);
9412
+ runtime.consoleLog(message2, ...args);
9398
9413
  }
9399
9414
  }
9400
- function error(runtime, message, ...args) {
9401
- runtime.consoleError(message, ...args);
9415
+ function error(runtime, message2, ...args) {
9416
+ runtime.consoleError(message2, ...args);
9402
9417
  }
9403
9418
  function enableDebugLog() {
9404
9419
  debugLogEnabled = true;
@@ -9795,21 +9810,21 @@ function getDefaultOptions() {
9795
9810
 
9796
9811
  // node_modules/@miqro/jsx/build/esm/jsx.js
9797
9812
  var Fragment = Symbol("Fragment");
9798
- function createElement(tag, attributes, ...children) {
9799
- if (!tag) {
9800
- throw new Error(`cannot call createElement with [${String(tag)}] `);
9813
+ function createElement(tag2, attributes, ...children) {
9814
+ if (!tag2) {
9815
+ throw new Error(`cannot call createElement with [${String(tag2)}] `);
9801
9816
  }
9802
- const isFragment = tag === Fragment;
9803
- const fAsFragment = typeof tag === "string" || isFragment ? getDefaultOptions().asFragment : tag.asFragment !== void 0 ? tag.asFragment : getDefaultOptions().asFragment;
9804
- const tagName = typeof tag === "string" ? tag : isFragment ? "Fragment" : `${!tag.name ? "no-name" : tag.name}-component`.toLowerCase();
9817
+ const isFragment = tag2 === Fragment;
9818
+ const fAsFragment = typeof tag2 === "string" || isFragment ? getDefaultOptions().asFragment : tag2.asFragment !== void 0 ? tag2.asFragment : getDefaultOptions().asFragment;
9819
+ const tagName = typeof tag2 === "string" ? tag2 : isFragment ? "Fragment" : `${!tag2.name ? "no-name" : tag2.name}-component`.toLowerCase();
9805
9820
  return isFragment ? {
9806
9821
  type: "Fragment",
9807
9822
  children
9808
- } : typeof tag === "function" ? {
9823
+ } : typeof tag2 === "function" ? {
9809
9824
  type: fAsFragment ? "FragmentComponent" : "Component",
9810
9825
  tagName: !fAsFragment ? tagName : void 0,
9811
9826
  props: attributes ? attributes : /* @__PURE__ */ Object.create(null),
9812
- func: tag,
9827
+ func: tag2,
9813
9828
  children
9814
9829
  } : {
9815
9830
  type: "Element",
@@ -11194,7 +11209,7 @@ var DEFAULT_BUILD_DIR = (0, import_os.tmpdir)();
11194
11209
 
11195
11210
  // src/common/jsx.ts
11196
11211
  var import_node_path5 = require("node:path");
11197
- var import_node_crypto3 = require("node:crypto");
11212
+ var import_node_crypto4 = require("node:crypto");
11198
11213
  var import_node_fs6 = require("node:fs");
11199
11214
  var import_node_process3 = require("node:process");
11200
11215
 
@@ -11556,6 +11571,7 @@ async function esBuild(options, logger) {
11556
11571
  }
11557
11572
 
11558
11573
  // src/services/globals.ts
11574
+ var import_node_cluster2 = __toESM(require("node:cluster"), 1);
11559
11575
  var import_node_assert = require("node:assert");
11560
11576
 
11561
11577
  // src/inflate/md.ts
@@ -11592,263 +11608,2881 @@ var CLEAR_JSX_CACHE = (process.env["CLEAR_JSX_CACHE"] !== void 0 ? process.env["
11592
11608
  var EDITOR_CONFIG_KEY = "$$editor$$";
11593
11609
  var HOT_RELOAD_PATH = "/hot-reload";
11594
11610
 
11595
- // src/services/globals.ts
11596
- var globalJSX = Object.freeze({
11597
- createElement: (...args) => {
11598
- const ret = createElement(...args);
11599
- ret.toString = () => jsx2HTML(ret);
11600
- return ret;
11601
- },
11602
- Fragment,
11603
- enableDebugLog
11604
- });
11605
- var globaljsx = Object.freeze({
11606
- useContext,
11607
- useRuntime,
11608
- createContext,
11609
- useState,
11610
- useEffect,
11611
- useQuery,
11612
- useRef,
11613
- useElement,
11614
- useRefresh,
11615
- Link,
11616
- Router: Router2,
11617
- usePathname,
11618
- define: function define2() {
11611
+ // node_modules/jose/dist/webapi/lib/buffer_utils.js
11612
+ var encoder = new TextEncoder();
11613
+ var decoder = new TextDecoder();
11614
+ var MAX_INT32 = 2 ** 32;
11615
+ function concat(...buffers) {
11616
+ const size = buffers.reduce((acc, { length }) => acc + length, 0);
11617
+ const buf = new Uint8Array(size);
11618
+ let i = 0;
11619
+ for (const buffer of buffers) {
11620
+ buf.set(buffer, i);
11621
+ i += buffer.length;
11619
11622
  }
11620
- });
11621
- var globalWindow = Object.freeze({
11622
- addEventListener: function define3() {
11623
+ return buf;
11624
+ }
11625
+ function writeUInt32BE(buf, value, offset) {
11626
+ if (value < 0 || value >= MAX_INT32) {
11627
+ throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);
11623
11628
  }
11624
- });
11625
- var globalServer = Object.freeze({
11626
- middleware: Object.freeze({
11627
- buffer: ReadBuffer,
11628
- url: URLEncodedParser,
11629
- json: JSONParser,
11630
- text: TextParser,
11631
- cors: CORS,
11632
- session: SessionHandler
11633
- }),
11634
- encodeHTML: HTMLEncode,
11635
- inflateMDtoHTML: inflateMD2HTML
11636
- });
11637
- function browserJSXGlobals(inFile, jsxPath = false, useExport = true) {
11638
- const PRE = `import { enableDebugLog, useRuntime, Link, usePathname, createContext, useContext, useElement, useRefresh, useQuery, define, Router, useState, useEffect, useRef, createElement, Fragment } from "${jsxPath}";
11639
- globalThis.JSX = Object.freeze({
11640
- createElement,
11641
- Fragment,
11642
- enableDebugLog
11643
- });
11644
-
11645
- globalThis.newParser = () => new Parser();
11646
- globalThis.jsx = Object.freeze({
11647
- define,
11648
- useRuntime,
11649
- createContext,
11650
- useContext,
11651
- useState,
11652
- useEffect,
11653
- useQuery,
11654
- useRef,
11655
- useElement,
11656
- useRefresh,
11657
- usePathname,
11658
- Link,
11659
- Router
11660
- });`;
11661
- return `${jsxPath ? PRE : ""}
11662
- ${useExport ? `export * from "${inFile}";import * as lib from "${inFile}";export default lib.default;` : `import * as lib from "${inFile}"`}`;
11629
+ buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset);
11663
11630
  }
11664
- function initGlobals() {
11665
- globalThis.server = globalServer;
11666
- globalThis.JSX = globalJSX;
11667
- globalThis.jsx = globaljsx;
11668
- globalThis.window = globalWindow;
11631
+ function uint64be(value) {
11632
+ const high = Math.floor(value / MAX_INT32);
11633
+ const low = value % MAX_INT32;
11634
+ const buf = new Uint8Array(8);
11635
+ writeUInt32BE(buf, high, 0);
11636
+ writeUInt32BE(buf, low, 4);
11637
+ return buf;
11669
11638
  }
11670
- function assertGlobalTampered() {
11671
- try {
11672
- (0, import_node_assert.strictEqual)(globalThis.JSX, globalJSX, "globalThis.JSX tamperered");
11673
- (0, import_node_assert.strictEqual)(globalThis.server, globalServer, "globalThis.server tamperered");
11674
- (0, import_node_assert.strictEqual)(globalThis.jsx, globaljsx, "globalThis.jsx tamperered");
11675
- (0, import_node_assert.strictEqual)(globalThis.window, globalWindow, "globalThis.window tamperered");
11676
- } catch (e) {
11677
- console.error(e);
11678
- process.exit(EXIT_CODES.GLOBALS_ALTERED);
11679
- }
11639
+ function uint32be(value) {
11640
+ const buf = new Uint8Array(4);
11641
+ writeUInt32BE(buf, value);
11642
+ return buf;
11680
11643
  }
11681
11644
 
11682
- // src/common/jsx.ts
11683
- var jsxJSBuffer = null;
11684
- var jsxJSBufferChecksumPromise = null;
11685
- async function initJSXJS(logger) {
11686
- jsxJSBuffer = jsxJSBuffer ? jsxJSBuffer : Buffer.from(getAsset("jsx.dom.js"));
11687
- jsxJSBufferChecksumPromise = jsxJSBufferChecksumPromise ? jsxJSBufferChecksumPromise : calculateChecksumFromBuffer(jsxJSBuffer);
11688
- return initAsset(logger, getJSXJSPath(), jsxJSBuffer, true, jsxJSBufferChecksumPromise, false);
11645
+ // node_modules/jose/dist/webapi/lib/base64.js
11646
+ function encodeBase64(input) {
11647
+ if (Uint8Array.prototype.toBase64) {
11648
+ return input.toBase64();
11649
+ }
11650
+ const CHUNK_SIZE = 32768;
11651
+ const arr = [];
11652
+ for (let i = 0; i < input.length; i += CHUNK_SIZE) {
11653
+ arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
11654
+ }
11655
+ return btoa(arr.join(""));
11689
11656
  }
11690
- var parser2 = new Parser();
11691
- var DEFAULT_ESOPTION = {
11692
- platform: "neutral",
11693
- bundle: true,
11694
- jsxFactory: "JSX.createElement",
11695
- jsxFragment: "JSX.Fragment"
11696
- };
11697
- async function inflateJSX(inFile, options) {
11698
- const tmpBuildDir = (0, import_node_path5.resolve)(JSX_TMP_DIR, String(process.pid), "build", Date.now() + "-" + (0, import_node_crypto3.randomUUID)());
11699
- const inFileTmp = (0, import_node_path5.resolve)(tmpBuildDir, (0, import_node_path5.basename)(inFile) + ".mjs");
11700
- const jsxJSPath = getJSXJSPath();
11701
- const logger = options.logger;
11657
+ function decodeBase64(encoded) {
11658
+ if (Uint8Array.fromBase64) {
11659
+ return Uint8Array.fromBase64(encoded);
11660
+ }
11661
+ const binary = atob(encoded);
11662
+ const bytes = new Uint8Array(binary.length);
11663
+ for (let i = 0; i < binary.length; i++) {
11664
+ bytes[i] = binary.charCodeAt(i);
11665
+ }
11666
+ return bytes;
11667
+ }
11668
+
11669
+ // node_modules/jose/dist/webapi/util/base64url.js
11670
+ function decode(input) {
11671
+ if (Uint8Array.fromBase64) {
11672
+ return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
11673
+ alphabet: "base64url"
11674
+ });
11675
+ }
11676
+ let encoded = input;
11677
+ if (encoded instanceof Uint8Array) {
11678
+ encoded = decoder.decode(encoded);
11679
+ }
11680
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "");
11702
11681
  try {
11703
- if (!options.embemedJSX) {
11704
- (0, import_node_fs6.mkdirSync)(tmpBuildDir, {
11705
- recursive: true
11706
- });
11707
- (0, import_node_fs6.writeFileSync)(inFileTmp, browserJSXGlobals(inFile, false, options.useExport));
11708
- logger?.trace("inflating [%s] from [%s]. to change the import folder set JSX_TMP", (0, import_node_path5.relative)((0, import_node_process3.cwd)(), inFile), (0, import_node_path5.dirname)((0, import_node_path5.relative)(JSX_TMP_DIR, inFileTmp)));
11709
- const { outputFiles: [{ contents }] } = await esBuild({
11710
- ...DEFAULT_ESOPTION,
11711
- entryPoints: [inFileTmp],
11712
- minify: options.minify
11713
- });
11714
- if (CLEAR_JSX_CACHE) {
11715
- logger?.trace("clearing cache at [%s] to change this behaivor set CLEAR_JSX_CACHE to 0", tmpBuildDir);
11716
- (0, import_node_fs6.unlinkSync)(inFileTmp);
11717
- (0, import_node_fs6.rmdirSync)(tmpBuildDir);
11718
- }
11719
- return contents;
11720
- } else {
11721
- (0, import_node_fs6.mkdirSync)(tmpBuildDir, {
11722
- recursive: true
11723
- });
11724
- (0, import_node_fs6.writeFileSync)(inFileTmp, browserJSXGlobals(inFile, jsxJSPath));
11725
- logger?.trace("inflating [%s] from [%s] with jsx.js embedded. to change the import folder set JSX_TMP", (0, import_node_path5.relative)((0, import_node_process3.cwd)(), inFile), (0, import_node_path5.dirname)((0, import_node_path5.relative)(JSX_TMP_DIR, inFileTmp)));
11726
- const { outputFiles: [{ contents }] } = await esBuild({
11727
- ...DEFAULT_ESOPTION,
11728
- entryPoints: [inFileTmp],
11729
- minify: options.minify
11730
- });
11731
- if (CLEAR_JSX_CACHE) {
11732
- logger?.trace("clearing cache at [%s] to change this behaivor set CLEAR_JSX_CACHE to 0", tmpBuildDir);
11733
- (0, import_node_fs6.unlinkSync)(inFileTmp);
11734
- (0, import_node_fs6.rmdirSync)(tmpBuildDir);
11735
- }
11736
- return contents;
11737
- }
11738
- } catch (e) {
11739
- logger?.error("error with: " + inFile);
11740
- logger?.error(e);
11741
- if (options.embemedJSX) {
11742
- if (CLEAR_JSX_CACHE) {
11743
- logger?.trace("clearing cache at [%s] to change this behaivor set CLEAR_JSX_CACHE to 0", tmpBuildDir);
11744
- (0, import_node_fs6.unlinkSync)(inFileTmp);
11745
- (0, import_node_fs6.rmdirSync)(tmpBuildDir);
11746
- } else {
11747
- logger?.error("error with: %s", inFileTmp);
11748
- logger?.trace("NOT clearing cache. to change this behaivor set CLEAR_JSX_CACHE to 1", tmpBuildDir);
11749
- }
11750
- }
11751
- throw e;
11682
+ return decodeBase64(encoded);
11683
+ } catch {
11684
+ throw new TypeError("The input to be decoded is not correctly encoded.");
11752
11685
  }
11753
11686
  }
11754
- var APIOptionsSchema = {
11755
- type: "object?",
11756
- properties: {
11757
- basePath: "string?",
11758
- path: "string?|string[]?",
11759
- method: "string?|string[]?",
11760
- parser: {
11761
- type: "object?",
11762
- properties: {
11763
- parse: "function"
11764
- },
11765
- mode: "add_extra"
11766
- },
11767
- middleware: "function[]!?",
11768
- session: {
11769
- type: "object?|function?",
11770
- properties: SessionHandlerOptionsSchema.properties
11771
- },
11772
- ...RouteOptionsSchema.properties
11687
+ function encode(input) {
11688
+ let unencoded = input;
11689
+ if (typeof unencoded === "string") {
11690
+ unencoded = encoder.encode(unencoded);
11691
+ }
11692
+ if (Uint8Array.prototype.toBase64) {
11693
+ return unencoded.toBase64({ alphabet: "base64url", omitPadding: true });
11694
+ }
11695
+ return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
11696
+ }
11697
+
11698
+ // node_modules/jose/dist/webapi/util/errors.js
11699
+ var JOSEError = class extends Error {
11700
+ static code = "ERR_JOSE_GENERIC";
11701
+ code = "ERR_JOSE_GENERIC";
11702
+ constructor(message2, options) {
11703
+ super(message2, options);
11704
+ this.name = this.constructor.name;
11705
+ Error.captureStackTrace?.(this, this.constructor);
11773
11706
  }
11774
- //mode:"add_extra"
11775
11707
  };
11776
- var HTMLModuleSchema = {
11777
- type: "object",
11778
- properties: {
11779
- default: {
11780
- type: "function|object"
11781
- },
11782
- apiOptions: APIOptionsSchema
11708
+ var JWTClaimValidationFailed = class extends JOSEError {
11709
+ static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
11710
+ code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
11711
+ claim;
11712
+ reason;
11713
+ payload;
11714
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
11715
+ super(message2, { cause: { claim, reason, payload } });
11716
+ this.claim = claim;
11717
+ this.reason = reason;
11718
+ this.payload = payload;
11783
11719
  }
11784
- //mode:"add_extra"
11785
11720
  };
11786
- var JSONModuleSchema = {
11787
- type: "object",
11788
- properties: {
11789
- default: {
11790
- type: "function|object|string"
11791
- },
11792
- apiOptions: APIOptionsSchema
11721
+ var JWTExpired = class extends JOSEError {
11722
+ static code = "ERR_JWT_EXPIRED";
11723
+ code = "ERR_JWT_EXPIRED";
11724
+ claim;
11725
+ reason;
11726
+ payload;
11727
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
11728
+ super(message2, { cause: { claim, reason, payload } });
11729
+ this.claim = claim;
11730
+ this.reason = reason;
11731
+ this.payload = payload;
11793
11732
  }
11794
- //mode:"add_extra"
11795
11733
  };
11796
- var MigrationSchema = {
11797
- type: "object",
11798
- properties: {
11799
- up: "function",
11800
- down: "function"
11801
- },
11802
- mode: "add_extra"
11734
+ var JOSEAlgNotAllowed = class extends JOSEError {
11735
+ static code = "ERR_JOSE_ALG_NOT_ALLOWED";
11736
+ code = "ERR_JOSE_ALG_NOT_ALLOWED";
11803
11737
  };
11804
- var CORSOptionsSchema = {
11805
- type: "object",
11806
- properties: {
11807
- origins: "string[]?|string?",
11808
- validate: "function?",
11809
- methods: "string?",
11810
- preflightContinue: "boolean?"
11811
- }
11812
- //mode:"add_extra"
11738
+ var JOSENotSupported = class extends JOSEError {
11739
+ static code = "ERR_JOSE_NOT_SUPPORTED";
11740
+ code = "ERR_JOSE_NOT_SUPPORTED";
11813
11741
  };
11814
- var WSConfigSchema = {
11815
- type: "object",
11816
- properties: {
11817
- path: "string",
11818
- disabled: "boolean?",
11819
- maxConnections: "number?",
11820
- validate: "function?",
11821
- onConnection: "function?",
11822
- onMessage: "function?",
11823
- onDisconnect: "function?"
11742
+ var JWEDecryptionFailed = class extends JOSEError {
11743
+ static code = "ERR_JWE_DECRYPTION_FAILED";
11744
+ code = "ERR_JWE_DECRYPTION_FAILED";
11745
+ constructor(message2 = "decryption operation failed", options) {
11746
+ super(message2, options);
11824
11747
  }
11825
- //mode:"add_extra"
11826
11748
  };
11827
- var DBConfigSchema = {
11828
- type: "object",
11829
- properties: {
11830
- url: "string?",
11831
- disabled: "boolean?",
11832
- storage: "string?",
11833
- dialect: "string?",
11834
- name: "string"
11835
- }
11836
- //mode:"add_extra"
11749
+ var JWEInvalid = class extends JOSEError {
11750
+ static code = "ERR_JWE_INVALID";
11751
+ code = "ERR_JWE_INVALID";
11837
11752
  };
11838
- var ServerConfigSchema = {
11839
- type: "object",
11840
- properties: {
11841
- preload: "function?",
11842
- unload: "function?",
11843
- stop: "function?",
11844
- start: "function?",
11845
- load: "function?"
11753
+ var JWSInvalid = class extends JOSEError {
11754
+ static code = "ERR_JWS_INVALID";
11755
+ code = "ERR_JWS_INVALID";
11756
+ };
11757
+ var JWTInvalid = class extends JOSEError {
11758
+ static code = "ERR_JWT_INVALID";
11759
+ code = "ERR_JWT_INVALID";
11760
+ };
11761
+ var JWSSignatureVerificationFailed = class extends JOSEError {
11762
+ static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
11763
+ code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
11764
+ constructor(message2 = "signature verification failed", options) {
11765
+ super(message2, options);
11846
11766
  }
11847
- //mode:"add_extra"
11848
11767
  };
11849
- var LogConfigSchema = {
11850
- type: "object",
11851
- properties: {
11768
+
11769
+ // node_modules/jose/dist/webapi/lib/iv.js
11770
+ function bitLength(alg) {
11771
+ switch (alg) {
11772
+ case "A128GCM":
11773
+ case "A128GCMKW":
11774
+ case "A192GCM":
11775
+ case "A192GCMKW":
11776
+ case "A256GCM":
11777
+ case "A256GCMKW":
11778
+ return 96;
11779
+ case "A128CBC-HS256":
11780
+ case "A192CBC-HS384":
11781
+ case "A256CBC-HS512":
11782
+ return 128;
11783
+ default:
11784
+ throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
11785
+ }
11786
+ }
11787
+ var iv_default = (alg) => crypto.getRandomValues(new Uint8Array(bitLength(alg) >> 3));
11788
+
11789
+ // node_modules/jose/dist/webapi/lib/check_iv_length.js
11790
+ var check_iv_length_default = (enc, iv) => {
11791
+ if (iv.length << 3 !== bitLength(enc)) {
11792
+ throw new JWEInvalid("Invalid Initialization Vector length");
11793
+ }
11794
+ };
11795
+
11796
+ // node_modules/jose/dist/webapi/lib/check_cek_length.js
11797
+ var check_cek_length_default = (cek, expected) => {
11798
+ const actual = cek.byteLength << 3;
11799
+ if (actual !== expected) {
11800
+ throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
11801
+ }
11802
+ };
11803
+
11804
+ // node_modules/jose/dist/webapi/lib/crypto_key.js
11805
+ function unusable(name, prop = "algorithm.name") {
11806
+ return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
11807
+ }
11808
+ function isAlgorithm(algorithm, name) {
11809
+ return algorithm.name === name;
11810
+ }
11811
+ function getHashLength(hash) {
11812
+ return parseInt(hash.name.slice(4), 10);
11813
+ }
11814
+ function getNamedCurve(alg) {
11815
+ switch (alg) {
11816
+ case "ES256":
11817
+ return "P-256";
11818
+ case "ES384":
11819
+ return "P-384";
11820
+ case "ES512":
11821
+ return "P-521";
11822
+ default:
11823
+ throw new Error("unreachable");
11824
+ }
11825
+ }
11826
+ function checkUsage(key, usage2) {
11827
+ if (usage2 && !key.usages.includes(usage2)) {
11828
+ throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage2}.`);
11829
+ }
11830
+ }
11831
+ function checkSigCryptoKey(key, alg, usage2) {
11832
+ switch (alg) {
11833
+ case "HS256":
11834
+ case "HS384":
11835
+ case "HS512": {
11836
+ if (!isAlgorithm(key.algorithm, "HMAC"))
11837
+ throw unusable("HMAC");
11838
+ const expected = parseInt(alg.slice(2), 10);
11839
+ const actual = getHashLength(key.algorithm.hash);
11840
+ if (actual !== expected)
11841
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
11842
+ break;
11843
+ }
11844
+ case "RS256":
11845
+ case "RS384":
11846
+ case "RS512": {
11847
+ if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5"))
11848
+ throw unusable("RSASSA-PKCS1-v1_5");
11849
+ const expected = parseInt(alg.slice(2), 10);
11850
+ const actual = getHashLength(key.algorithm.hash);
11851
+ if (actual !== expected)
11852
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
11853
+ break;
11854
+ }
11855
+ case "PS256":
11856
+ case "PS384":
11857
+ case "PS512": {
11858
+ if (!isAlgorithm(key.algorithm, "RSA-PSS"))
11859
+ throw unusable("RSA-PSS");
11860
+ const expected = parseInt(alg.slice(2), 10);
11861
+ const actual = getHashLength(key.algorithm.hash);
11862
+ if (actual !== expected)
11863
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
11864
+ break;
11865
+ }
11866
+ case "Ed25519":
11867
+ case "EdDSA": {
11868
+ if (!isAlgorithm(key.algorithm, "Ed25519"))
11869
+ throw unusable("Ed25519");
11870
+ break;
11871
+ }
11872
+ case "ES256":
11873
+ case "ES384":
11874
+ case "ES512": {
11875
+ if (!isAlgorithm(key.algorithm, "ECDSA"))
11876
+ throw unusable("ECDSA");
11877
+ const expected = getNamedCurve(alg);
11878
+ const actual = key.algorithm.namedCurve;
11879
+ if (actual !== expected)
11880
+ throw unusable(expected, "algorithm.namedCurve");
11881
+ break;
11882
+ }
11883
+ default:
11884
+ throw new TypeError("CryptoKey does not support this operation");
11885
+ }
11886
+ checkUsage(key, usage2);
11887
+ }
11888
+ function checkEncCryptoKey(key, alg, usage2) {
11889
+ switch (alg) {
11890
+ case "A128GCM":
11891
+ case "A192GCM":
11892
+ case "A256GCM": {
11893
+ if (!isAlgorithm(key.algorithm, "AES-GCM"))
11894
+ throw unusable("AES-GCM");
11895
+ const expected = parseInt(alg.slice(1, 4), 10);
11896
+ const actual = key.algorithm.length;
11897
+ if (actual !== expected)
11898
+ throw unusable(expected, "algorithm.length");
11899
+ break;
11900
+ }
11901
+ case "A128KW":
11902
+ case "A192KW":
11903
+ case "A256KW": {
11904
+ if (!isAlgorithm(key.algorithm, "AES-KW"))
11905
+ throw unusable("AES-KW");
11906
+ const expected = parseInt(alg.slice(1, 4), 10);
11907
+ const actual = key.algorithm.length;
11908
+ if (actual !== expected)
11909
+ throw unusable(expected, "algorithm.length");
11910
+ break;
11911
+ }
11912
+ case "ECDH": {
11913
+ switch (key.algorithm.name) {
11914
+ case "ECDH":
11915
+ case "X25519":
11916
+ break;
11917
+ default:
11918
+ throw unusable("ECDH or X25519");
11919
+ }
11920
+ break;
11921
+ }
11922
+ case "PBES2-HS256+A128KW":
11923
+ case "PBES2-HS384+A192KW":
11924
+ case "PBES2-HS512+A256KW":
11925
+ if (!isAlgorithm(key.algorithm, "PBKDF2"))
11926
+ throw unusable("PBKDF2");
11927
+ break;
11928
+ case "RSA-OAEP":
11929
+ case "RSA-OAEP-256":
11930
+ case "RSA-OAEP-384":
11931
+ case "RSA-OAEP-512": {
11932
+ if (!isAlgorithm(key.algorithm, "RSA-OAEP"))
11933
+ throw unusable("RSA-OAEP");
11934
+ const expected = parseInt(alg.slice(9), 10) || 1;
11935
+ const actual = getHashLength(key.algorithm.hash);
11936
+ if (actual !== expected)
11937
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
11938
+ break;
11939
+ }
11940
+ default:
11941
+ throw new TypeError("CryptoKey does not support this operation");
11942
+ }
11943
+ checkUsage(key, usage2);
11944
+ }
11945
+
11946
+ // node_modules/jose/dist/webapi/lib/invalid_key_input.js
11947
+ function message(msg, actual, ...types) {
11948
+ types = types.filter(Boolean);
11949
+ if (types.length > 2) {
11950
+ const last = types.pop();
11951
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
11952
+ } else if (types.length === 2) {
11953
+ msg += `one of type ${types[0]} or ${types[1]}.`;
11954
+ } else {
11955
+ msg += `of type ${types[0]}.`;
11956
+ }
11957
+ if (actual == null) {
11958
+ msg += ` Received ${actual}`;
11959
+ } else if (typeof actual === "function" && actual.name) {
11960
+ msg += ` Received function ${actual.name}`;
11961
+ } else if (typeof actual === "object" && actual != null) {
11962
+ if (actual.constructor?.name) {
11963
+ msg += ` Received an instance of ${actual.constructor.name}`;
11964
+ }
11965
+ }
11966
+ return msg;
11967
+ }
11968
+ var invalid_key_input_default = (actual, ...types) => {
11969
+ return message("Key must be ", actual, ...types);
11970
+ };
11971
+ function withAlg(alg, actual, ...types) {
11972
+ return message(`Key for the ${alg} algorithm must be `, actual, ...types);
11973
+ }
11974
+
11975
+ // node_modules/jose/dist/webapi/lib/is_key_like.js
11976
+ function assertCryptoKey(key) {
11977
+ if (!isCryptoKey(key)) {
11978
+ throw new Error("CryptoKey instance expected");
11979
+ }
11980
+ }
11981
+ function isCryptoKey(key) {
11982
+ return key?.[Symbol.toStringTag] === "CryptoKey";
11983
+ }
11984
+ function isKeyObject(key) {
11985
+ return key?.[Symbol.toStringTag] === "KeyObject";
11986
+ }
11987
+ var is_key_like_default = (key) => {
11988
+ return isCryptoKey(key) || isKeyObject(key);
11989
+ };
11990
+
11991
+ // node_modules/jose/dist/webapi/lib/decrypt.js
11992
+ async function timingSafeEqual(a, b) {
11993
+ if (!(a instanceof Uint8Array)) {
11994
+ throw new TypeError("First argument must be a buffer");
11995
+ }
11996
+ if (!(b instanceof Uint8Array)) {
11997
+ throw new TypeError("Second argument must be a buffer");
11998
+ }
11999
+ const algorithm = { name: "HMAC", hash: "SHA-256" };
12000
+ const key = await crypto.subtle.generateKey(algorithm, false, ["sign"]);
12001
+ const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, a));
12002
+ const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, b));
12003
+ let out = 0;
12004
+ let i = -1;
12005
+ while (++i < 32) {
12006
+ out |= aHmac[i] ^ bHmac[i];
12007
+ }
12008
+ return out === 0;
12009
+ }
12010
+ async function cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad) {
12011
+ if (!(cek instanceof Uint8Array)) {
12012
+ throw new TypeError(invalid_key_input_default(cek, "Uint8Array"));
12013
+ }
12014
+ const keySize = parseInt(enc.slice(1, 4), 10);
12015
+ const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["decrypt"]);
12016
+ const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
12017
+ hash: `SHA-${keySize << 1}`,
12018
+ name: "HMAC"
12019
+ }, false, ["sign"]);
12020
+ const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
12021
+ const expectedTag = new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3));
12022
+ let macCheckPassed;
12023
+ try {
12024
+ macCheckPassed = await timingSafeEqual(tag2, expectedTag);
12025
+ } catch {
12026
+ }
12027
+ if (!macCheckPassed) {
12028
+ throw new JWEDecryptionFailed();
12029
+ }
12030
+ let plaintext;
12031
+ try {
12032
+ plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: "AES-CBC" }, encKey, ciphertext));
12033
+ } catch {
12034
+ }
12035
+ if (!plaintext) {
12036
+ throw new JWEDecryptionFailed();
12037
+ }
12038
+ return plaintext;
12039
+ }
12040
+ async function gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad) {
12041
+ let encKey;
12042
+ if (cek instanceof Uint8Array) {
12043
+ encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]);
12044
+ } else {
12045
+ checkEncCryptoKey(cek, enc, "decrypt");
12046
+ encKey = cek;
12047
+ }
12048
+ try {
12049
+ return new Uint8Array(await crypto.subtle.decrypt({
12050
+ additionalData: aad,
12051
+ iv,
12052
+ name: "AES-GCM",
12053
+ tagLength: 128
12054
+ }, encKey, concat(ciphertext, tag2)));
12055
+ } catch {
12056
+ throw new JWEDecryptionFailed();
12057
+ }
12058
+ }
12059
+ var decrypt_default = async (enc, cek, ciphertext, iv, tag2, aad) => {
12060
+ if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
12061
+ throw new TypeError(invalid_key_input_default(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
12062
+ }
12063
+ if (!iv) {
12064
+ throw new JWEInvalid("JWE Initialization Vector missing");
12065
+ }
12066
+ if (!tag2) {
12067
+ throw new JWEInvalid("JWE Authentication Tag missing");
12068
+ }
12069
+ check_iv_length_default(enc, iv);
12070
+ switch (enc) {
12071
+ case "A128CBC-HS256":
12072
+ case "A192CBC-HS384":
12073
+ case "A256CBC-HS512":
12074
+ if (cek instanceof Uint8Array)
12075
+ check_cek_length_default(cek, parseInt(enc.slice(-3), 10));
12076
+ return cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad);
12077
+ case "A128GCM":
12078
+ case "A192GCM":
12079
+ case "A256GCM":
12080
+ if (cek instanceof Uint8Array)
12081
+ check_cek_length_default(cek, parseInt(enc.slice(1, 4), 10));
12082
+ return gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad);
12083
+ default:
12084
+ throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm");
12085
+ }
12086
+ };
12087
+
12088
+ // node_modules/jose/dist/webapi/lib/is_disjoint.js
12089
+ var is_disjoint_default = (...headers) => {
12090
+ const sources = headers.filter(Boolean);
12091
+ if (sources.length === 0 || sources.length === 1) {
12092
+ return true;
12093
+ }
12094
+ let acc;
12095
+ for (const header of sources) {
12096
+ const parameters = Object.keys(header);
12097
+ if (!acc || acc.size === 0) {
12098
+ acc = new Set(parameters);
12099
+ continue;
12100
+ }
12101
+ for (const parameter of parameters) {
12102
+ if (acc.has(parameter)) {
12103
+ return false;
12104
+ }
12105
+ acc.add(parameter);
12106
+ }
12107
+ }
12108
+ return true;
12109
+ };
12110
+
12111
+ // node_modules/jose/dist/webapi/lib/is_object.js
12112
+ function isObjectLike(value) {
12113
+ return typeof value === "object" && value !== null;
12114
+ }
12115
+ var is_object_default = (input) => {
12116
+ if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
12117
+ return false;
12118
+ }
12119
+ if (Object.getPrototypeOf(input) === null) {
12120
+ return true;
12121
+ }
12122
+ let proto = input;
12123
+ while (Object.getPrototypeOf(proto) !== null) {
12124
+ proto = Object.getPrototypeOf(proto);
12125
+ }
12126
+ return Object.getPrototypeOf(input) === proto;
12127
+ };
12128
+
12129
+ // node_modules/jose/dist/webapi/lib/aeskw.js
12130
+ function checkKeySize(key, alg) {
12131
+ if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) {
12132
+ throw new TypeError(`Invalid key size for alg: ${alg}`);
12133
+ }
12134
+ }
12135
+ function getCryptoKey(key, alg, usage2) {
12136
+ if (key instanceof Uint8Array) {
12137
+ return crypto.subtle.importKey("raw", key, "AES-KW", true, [usage2]);
12138
+ }
12139
+ checkEncCryptoKey(key, alg, usage2);
12140
+ return key;
12141
+ }
12142
+ async function wrap(alg, key, cek) {
12143
+ const cryptoKey = await getCryptoKey(key, alg, "wrapKey");
12144
+ checkKeySize(cryptoKey, alg);
12145
+ const cryptoKeyCek = await crypto.subtle.importKey("raw", cek, { hash: "SHA-256", name: "HMAC" }, true, ["sign"]);
12146
+ return new Uint8Array(await crypto.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW"));
12147
+ }
12148
+ async function unwrap(alg, key, encryptedKey) {
12149
+ const cryptoKey = await getCryptoKey(key, alg, "unwrapKey");
12150
+ checkKeySize(cryptoKey, alg);
12151
+ const cryptoKeyCek = await crypto.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", { hash: "SHA-256", name: "HMAC" }, true, ["sign"]);
12152
+ return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek));
12153
+ }
12154
+
12155
+ // node_modules/jose/dist/webapi/lib/digest.js
12156
+ var digest_default = async (algorithm, data) => {
12157
+ const subtleDigest = `SHA-${algorithm.slice(-3)}`;
12158
+ return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
12159
+ };
12160
+
12161
+ // node_modules/jose/dist/webapi/lib/ecdhes.js
12162
+ function lengthAndInput(input) {
12163
+ return concat(uint32be(input.length), input);
12164
+ }
12165
+ async function concatKdf(secret, bits, value) {
12166
+ const iterations = Math.ceil((bits >> 3) / 32);
12167
+ const res = new Uint8Array(iterations * 32);
12168
+ for (let iter = 0; iter < iterations; iter++) {
12169
+ const buf = new Uint8Array(4 + secret.length + value.length);
12170
+ buf.set(uint32be(iter + 1));
12171
+ buf.set(secret, 4);
12172
+ buf.set(value, 4 + secret.length);
12173
+ res.set(await digest_default("sha256", buf), iter * 32);
12174
+ }
12175
+ return res.slice(0, bits >> 3);
12176
+ }
12177
+ async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) {
12178
+ checkEncCryptoKey(publicKey, "ECDH");
12179
+ checkEncCryptoKey(privateKey, "ECDH", "deriveBits");
12180
+ const value = concat(lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength));
12181
+ let length;
12182
+ if (publicKey.algorithm.name === "X25519") {
12183
+ length = 256;
12184
+ } else {
12185
+ length = Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3;
12186
+ }
12187
+ const sharedSecret = new Uint8Array(await crypto.subtle.deriveBits({
12188
+ name: publicKey.algorithm.name,
12189
+ public: publicKey
12190
+ }, privateKey, length));
12191
+ return concatKdf(sharedSecret, keyLength, value);
12192
+ }
12193
+ function allowed(key) {
12194
+ switch (key.algorithm.namedCurve) {
12195
+ case "P-256":
12196
+ case "P-384":
12197
+ case "P-521":
12198
+ return true;
12199
+ default:
12200
+ return key.algorithm.name === "X25519";
12201
+ }
12202
+ }
12203
+
12204
+ // node_modules/jose/dist/webapi/lib/pbes2kw.js
12205
+ function getCryptoKey2(key, alg) {
12206
+ if (key instanceof Uint8Array) {
12207
+ return crypto.subtle.importKey("raw", key, "PBKDF2", false, ["deriveBits"]);
12208
+ }
12209
+ checkEncCryptoKey(key, alg, "deriveBits");
12210
+ return key;
12211
+ }
12212
+ var concatSalt = (alg, p2sInput) => concat(encoder.encode(alg), new Uint8Array([0]), p2sInput);
12213
+ async function deriveKey2(p2s, alg, p2c, key) {
12214
+ if (!(p2s instanceof Uint8Array) || p2s.length < 8) {
12215
+ throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets");
12216
+ }
12217
+ const salt = concatSalt(alg, p2s);
12218
+ const keylen = parseInt(alg.slice(13, 16), 10);
12219
+ const subtleAlg = {
12220
+ hash: `SHA-${alg.slice(8, 11)}`,
12221
+ iterations: p2c,
12222
+ name: "PBKDF2",
12223
+ salt
12224
+ };
12225
+ const cryptoKey = await getCryptoKey2(key, alg);
12226
+ return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));
12227
+ }
12228
+ async function wrap2(alg, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) {
12229
+ const derived = await deriveKey2(p2s, alg, p2c, key);
12230
+ const encryptedKey = await wrap(alg.slice(-6), derived, cek);
12231
+ return { encryptedKey, p2c, p2s: encode(p2s) };
12232
+ }
12233
+ async function unwrap2(alg, key, encryptedKey, p2c, p2s) {
12234
+ const derived = await deriveKey2(p2s, alg, p2c, key);
12235
+ return unwrap(alg.slice(-6), derived, encryptedKey);
12236
+ }
12237
+
12238
+ // node_modules/jose/dist/webapi/lib/check_key_length.js
12239
+ var check_key_length_default = (alg, key) => {
12240
+ if (alg.startsWith("RS") || alg.startsWith("PS")) {
12241
+ const { modulusLength } = key.algorithm;
12242
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
12243
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
12244
+ }
12245
+ }
12246
+ };
12247
+
12248
+ // node_modules/jose/dist/webapi/lib/rsaes.js
12249
+ var subtleAlgorithm = (alg) => {
12250
+ switch (alg) {
12251
+ case "RSA-OAEP":
12252
+ case "RSA-OAEP-256":
12253
+ case "RSA-OAEP-384":
12254
+ case "RSA-OAEP-512":
12255
+ return "RSA-OAEP";
12256
+ default:
12257
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
12258
+ }
12259
+ };
12260
+ async function encrypt(alg, key, cek) {
12261
+ checkEncCryptoKey(key, alg, "encrypt");
12262
+ check_key_length_default(alg, key);
12263
+ return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek));
12264
+ }
12265
+ async function decrypt(alg, key, encryptedKey) {
12266
+ checkEncCryptoKey(key, alg, "decrypt");
12267
+ check_key_length_default(alg, key);
12268
+ return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey));
12269
+ }
12270
+
12271
+ // node_modules/jose/dist/webapi/lib/cek.js
12272
+ function bitLength2(alg) {
12273
+ switch (alg) {
12274
+ case "A128GCM":
12275
+ return 128;
12276
+ case "A192GCM":
12277
+ return 192;
12278
+ case "A256GCM":
12279
+ case "A128CBC-HS256":
12280
+ return 256;
12281
+ case "A192CBC-HS384":
12282
+ return 384;
12283
+ case "A256CBC-HS512":
12284
+ return 512;
12285
+ default:
12286
+ throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
12287
+ }
12288
+ }
12289
+ var cek_default = (alg) => crypto.getRandomValues(new Uint8Array(bitLength2(alg) >> 3));
12290
+
12291
+ // node_modules/jose/dist/webapi/lib/jwk_to_key.js
12292
+ function subtleMapping(jwk) {
12293
+ let algorithm;
12294
+ let keyUsages;
12295
+ switch (jwk.kty) {
12296
+ case "RSA": {
12297
+ switch (jwk.alg) {
12298
+ case "PS256":
12299
+ case "PS384":
12300
+ case "PS512":
12301
+ algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` };
12302
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
12303
+ break;
12304
+ case "RS256":
12305
+ case "RS384":
12306
+ case "RS512":
12307
+ algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` };
12308
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
12309
+ break;
12310
+ case "RSA-OAEP":
12311
+ case "RSA-OAEP-256":
12312
+ case "RSA-OAEP-384":
12313
+ case "RSA-OAEP-512":
12314
+ algorithm = {
12315
+ name: "RSA-OAEP",
12316
+ hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
12317
+ };
12318
+ keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
12319
+ break;
12320
+ default:
12321
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
12322
+ }
12323
+ break;
12324
+ }
12325
+ case "EC": {
12326
+ switch (jwk.alg) {
12327
+ case "ES256":
12328
+ algorithm = { name: "ECDSA", namedCurve: "P-256" };
12329
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
12330
+ break;
12331
+ case "ES384":
12332
+ algorithm = { name: "ECDSA", namedCurve: "P-384" };
12333
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
12334
+ break;
12335
+ case "ES512":
12336
+ algorithm = { name: "ECDSA", namedCurve: "P-521" };
12337
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
12338
+ break;
12339
+ case "ECDH-ES":
12340
+ case "ECDH-ES+A128KW":
12341
+ case "ECDH-ES+A192KW":
12342
+ case "ECDH-ES+A256KW":
12343
+ algorithm = { name: "ECDH", namedCurve: jwk.crv };
12344
+ keyUsages = jwk.d ? ["deriveBits"] : [];
12345
+ break;
12346
+ default:
12347
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
12348
+ }
12349
+ break;
12350
+ }
12351
+ case "OKP": {
12352
+ switch (jwk.alg) {
12353
+ case "Ed25519":
12354
+ case "EdDSA":
12355
+ algorithm = { name: "Ed25519" };
12356
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
12357
+ break;
12358
+ case "ECDH-ES":
12359
+ case "ECDH-ES+A128KW":
12360
+ case "ECDH-ES+A192KW":
12361
+ case "ECDH-ES+A256KW":
12362
+ algorithm = { name: jwk.crv };
12363
+ keyUsages = jwk.d ? ["deriveBits"] : [];
12364
+ break;
12365
+ default:
12366
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
12367
+ }
12368
+ break;
12369
+ }
12370
+ default:
12371
+ throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
12372
+ }
12373
+ return { algorithm, keyUsages };
12374
+ }
12375
+ var jwk_to_key_default = async (jwk) => {
12376
+ if (!jwk.alg) {
12377
+ throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
12378
+ }
12379
+ const { algorithm, keyUsages } = subtleMapping(jwk);
12380
+ const keyData = { ...jwk };
12381
+ delete keyData.alg;
12382
+ delete keyData.use;
12383
+ return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d ? false : true), jwk.key_ops ?? keyUsages);
12384
+ };
12385
+
12386
+ // node_modules/jose/dist/webapi/key/import.js
12387
+ async function importJWK(jwk, alg, options) {
12388
+ if (!is_object_default(jwk)) {
12389
+ throw new TypeError("JWK must be an object");
12390
+ }
12391
+ let ext;
12392
+ alg ??= jwk.alg;
12393
+ ext ??= options?.extractable ?? jwk.ext;
12394
+ switch (jwk.kty) {
12395
+ case "oct":
12396
+ if (typeof jwk.k !== "string" || !jwk.k) {
12397
+ throw new TypeError('missing "k" (Key Value) Parameter value');
12398
+ }
12399
+ return decode(jwk.k);
12400
+ case "RSA":
12401
+ if ("oth" in jwk && jwk.oth !== void 0) {
12402
+ throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
12403
+ }
12404
+ case "EC":
12405
+ case "OKP":
12406
+ return jwk_to_key_default({ ...jwk, alg, ext });
12407
+ default:
12408
+ throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
12409
+ }
12410
+ }
12411
+
12412
+ // node_modules/jose/dist/webapi/lib/encrypt.js
12413
+ async function cbcEncrypt(enc, plaintext, cek, iv, aad) {
12414
+ if (!(cek instanceof Uint8Array)) {
12415
+ throw new TypeError(invalid_key_input_default(cek, "Uint8Array"));
12416
+ }
12417
+ const keySize = parseInt(enc.slice(1, 4), 10);
12418
+ const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["encrypt"]);
12419
+ const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
12420
+ hash: `SHA-${keySize << 1}`,
12421
+ name: "HMAC"
12422
+ }, false, ["sign"]);
12423
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
12424
+ iv,
12425
+ name: "AES-CBC"
12426
+ }, encKey, plaintext));
12427
+ const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
12428
+ const tag2 = new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3));
12429
+ return { ciphertext, tag: tag2, iv };
12430
+ }
12431
+ async function gcmEncrypt(enc, plaintext, cek, iv, aad) {
12432
+ let encKey;
12433
+ if (cek instanceof Uint8Array) {
12434
+ encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]);
12435
+ } else {
12436
+ checkEncCryptoKey(cek, enc, "encrypt");
12437
+ encKey = cek;
12438
+ }
12439
+ const encrypted = new Uint8Array(await crypto.subtle.encrypt({
12440
+ additionalData: aad,
12441
+ iv,
12442
+ name: "AES-GCM",
12443
+ tagLength: 128
12444
+ }, encKey, plaintext));
12445
+ const tag2 = encrypted.slice(-16);
12446
+ const ciphertext = encrypted.slice(0, -16);
12447
+ return { ciphertext, tag: tag2, iv };
12448
+ }
12449
+ var encrypt_default = async (enc, plaintext, cek, iv, aad) => {
12450
+ if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
12451
+ throw new TypeError(invalid_key_input_default(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
12452
+ }
12453
+ if (iv) {
12454
+ check_iv_length_default(enc, iv);
12455
+ } else {
12456
+ iv = iv_default(enc);
12457
+ }
12458
+ switch (enc) {
12459
+ case "A128CBC-HS256":
12460
+ case "A192CBC-HS384":
12461
+ case "A256CBC-HS512":
12462
+ if (cek instanceof Uint8Array) {
12463
+ check_cek_length_default(cek, parseInt(enc.slice(-3), 10));
12464
+ }
12465
+ return cbcEncrypt(enc, plaintext, cek, iv, aad);
12466
+ case "A128GCM":
12467
+ case "A192GCM":
12468
+ case "A256GCM":
12469
+ if (cek instanceof Uint8Array) {
12470
+ check_cek_length_default(cek, parseInt(enc.slice(1, 4), 10));
12471
+ }
12472
+ return gcmEncrypt(enc, plaintext, cek, iv, aad);
12473
+ default:
12474
+ throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm");
12475
+ }
12476
+ };
12477
+
12478
+ // node_modules/jose/dist/webapi/lib/aesgcmkw.js
12479
+ async function wrap3(alg, key, cek, iv) {
12480
+ const jweAlgorithm = alg.slice(0, 7);
12481
+ const wrapped = await encrypt_default(jweAlgorithm, cek, key, iv, new Uint8Array(0));
12482
+ return {
12483
+ encryptedKey: wrapped.ciphertext,
12484
+ iv: encode(wrapped.iv),
12485
+ tag: encode(wrapped.tag)
12486
+ };
12487
+ }
12488
+ async function unwrap3(alg, key, encryptedKey, iv, tag2) {
12489
+ const jweAlgorithm = alg.slice(0, 7);
12490
+ return decrypt_default(jweAlgorithm, key, encryptedKey, iv, tag2, new Uint8Array(0));
12491
+ }
12492
+
12493
+ // node_modules/jose/dist/webapi/lib/decrypt_key_management.js
12494
+ var decrypt_key_management_default = async (alg, key, encryptedKey, joseHeader, options) => {
12495
+ switch (alg) {
12496
+ case "dir": {
12497
+ if (encryptedKey !== void 0)
12498
+ throw new JWEInvalid("Encountered unexpected JWE Encrypted Key");
12499
+ return key;
12500
+ }
12501
+ case "ECDH-ES":
12502
+ if (encryptedKey !== void 0)
12503
+ throw new JWEInvalid("Encountered unexpected JWE Encrypted Key");
12504
+ case "ECDH-ES+A128KW":
12505
+ case "ECDH-ES+A192KW":
12506
+ case "ECDH-ES+A256KW": {
12507
+ if (!is_object_default(joseHeader.epk))
12508
+ throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);
12509
+ assertCryptoKey(key);
12510
+ if (!allowed(key))
12511
+ throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
12512
+ const epk = await importJWK(joseHeader.epk, alg);
12513
+ assertCryptoKey(epk);
12514
+ let partyUInfo;
12515
+ let partyVInfo;
12516
+ if (joseHeader.apu !== void 0) {
12517
+ if (typeof joseHeader.apu !== "string")
12518
+ throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);
12519
+ try {
12520
+ partyUInfo = decode(joseHeader.apu);
12521
+ } catch {
12522
+ throw new JWEInvalid("Failed to base64url decode the apu");
12523
+ }
12524
+ }
12525
+ if (joseHeader.apv !== void 0) {
12526
+ if (typeof joseHeader.apv !== "string")
12527
+ throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);
12528
+ try {
12529
+ partyVInfo = decode(joseHeader.apv);
12530
+ } catch {
12531
+ throw new JWEInvalid("Failed to base64url decode the apv");
12532
+ }
12533
+ }
12534
+ const sharedSecret = await deriveKey(epk, key, alg === "ECDH-ES" ? joseHeader.enc : alg, alg === "ECDH-ES" ? bitLength2(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);
12535
+ if (alg === "ECDH-ES")
12536
+ return sharedSecret;
12537
+ if (encryptedKey === void 0)
12538
+ throw new JWEInvalid("JWE Encrypted Key missing");
12539
+ return unwrap(alg.slice(-6), sharedSecret, encryptedKey);
12540
+ }
12541
+ case "RSA-OAEP":
12542
+ case "RSA-OAEP-256":
12543
+ case "RSA-OAEP-384":
12544
+ case "RSA-OAEP-512": {
12545
+ if (encryptedKey === void 0)
12546
+ throw new JWEInvalid("JWE Encrypted Key missing");
12547
+ assertCryptoKey(key);
12548
+ return decrypt(alg, key, encryptedKey);
12549
+ }
12550
+ case "PBES2-HS256+A128KW":
12551
+ case "PBES2-HS384+A192KW":
12552
+ case "PBES2-HS512+A256KW": {
12553
+ if (encryptedKey === void 0)
12554
+ throw new JWEInvalid("JWE Encrypted Key missing");
12555
+ if (typeof joseHeader.p2c !== "number")
12556
+ throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);
12557
+ const p2cLimit = options?.maxPBES2Count || 1e4;
12558
+ if (joseHeader.p2c > p2cLimit)
12559
+ throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);
12560
+ if (typeof joseHeader.p2s !== "string")
12561
+ throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);
12562
+ let p2s;
12563
+ try {
12564
+ p2s = decode(joseHeader.p2s);
12565
+ } catch {
12566
+ throw new JWEInvalid("Failed to base64url decode the p2s");
12567
+ }
12568
+ return unwrap2(alg, key, encryptedKey, joseHeader.p2c, p2s);
12569
+ }
12570
+ case "A128KW":
12571
+ case "A192KW":
12572
+ case "A256KW": {
12573
+ if (encryptedKey === void 0)
12574
+ throw new JWEInvalid("JWE Encrypted Key missing");
12575
+ return unwrap(alg, key, encryptedKey);
12576
+ }
12577
+ case "A128GCMKW":
12578
+ case "A192GCMKW":
12579
+ case "A256GCMKW": {
12580
+ if (encryptedKey === void 0)
12581
+ throw new JWEInvalid("JWE Encrypted Key missing");
12582
+ if (typeof joseHeader.iv !== "string")
12583
+ throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`);
12584
+ if (typeof joseHeader.tag !== "string")
12585
+ throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`);
12586
+ let iv;
12587
+ try {
12588
+ iv = decode(joseHeader.iv);
12589
+ } catch {
12590
+ throw new JWEInvalid("Failed to base64url decode the iv");
12591
+ }
12592
+ let tag2;
12593
+ try {
12594
+ tag2 = decode(joseHeader.tag);
12595
+ } catch {
12596
+ throw new JWEInvalid("Failed to base64url decode the tag");
12597
+ }
12598
+ return unwrap3(alg, key, encryptedKey, iv, tag2);
12599
+ }
12600
+ default: {
12601
+ throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
12602
+ }
12603
+ }
12604
+ };
12605
+
12606
+ // node_modules/jose/dist/webapi/lib/validate_crit.js
12607
+ var validate_crit_default = (Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) => {
12608
+ if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) {
12609
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
12610
+ }
12611
+ if (!protectedHeader || protectedHeader.crit === void 0) {
12612
+ return /* @__PURE__ */ new Set();
12613
+ }
12614
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
12615
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
12616
+ }
12617
+ let recognized;
12618
+ if (recognizedOption !== void 0) {
12619
+ recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
12620
+ } else {
12621
+ recognized = recognizedDefault;
12622
+ }
12623
+ for (const parameter of protectedHeader.crit) {
12624
+ if (!recognized.has(parameter)) {
12625
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
12626
+ }
12627
+ if (joseHeader[parameter] === void 0) {
12628
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
12629
+ }
12630
+ if (recognized.get(parameter) && protectedHeader[parameter] === void 0) {
12631
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
12632
+ }
12633
+ }
12634
+ return new Set(protectedHeader.crit);
12635
+ };
12636
+
12637
+ // node_modules/jose/dist/webapi/lib/validate_algorithms.js
12638
+ var validate_algorithms_default = (option, algorithms) => {
12639
+ if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
12640
+ throw new TypeError(`"${option}" option must be an array of strings`);
12641
+ }
12642
+ if (!algorithms) {
12643
+ return void 0;
12644
+ }
12645
+ return new Set(algorithms);
12646
+ };
12647
+
12648
+ // node_modules/jose/dist/webapi/lib/is_jwk.js
12649
+ function isJWK(key) {
12650
+ return is_object_default(key) && typeof key.kty === "string";
12651
+ }
12652
+ function isPrivateJWK(key) {
12653
+ return key.kty !== "oct" && typeof key.d === "string";
12654
+ }
12655
+ function isPublicJWK(key) {
12656
+ return key.kty !== "oct" && typeof key.d === "undefined";
12657
+ }
12658
+ function isSecretJWK(key) {
12659
+ return key.kty === "oct" && typeof key.k === "string";
12660
+ }
12661
+
12662
+ // node_modules/jose/dist/webapi/lib/normalize_key.js
12663
+ var cache;
12664
+ var handleJWK = async (key, jwk, alg, freeze = false) => {
12665
+ cache ||= /* @__PURE__ */ new WeakMap();
12666
+ let cached = cache.get(key);
12667
+ if (cached?.[alg]) {
12668
+ return cached[alg];
12669
+ }
12670
+ const cryptoKey = await jwk_to_key_default({ ...jwk, alg });
12671
+ if (freeze)
12672
+ Object.freeze(key);
12673
+ if (!cached) {
12674
+ cache.set(key, { [alg]: cryptoKey });
12675
+ } else {
12676
+ cached[alg] = cryptoKey;
12677
+ }
12678
+ return cryptoKey;
12679
+ };
12680
+ var handleKeyObject = (keyObject, alg) => {
12681
+ cache ||= /* @__PURE__ */ new WeakMap();
12682
+ let cached = cache.get(keyObject);
12683
+ if (cached?.[alg]) {
12684
+ return cached[alg];
12685
+ }
12686
+ const isPublic = keyObject.type === "public";
12687
+ const extractable = isPublic ? true : false;
12688
+ let cryptoKey;
12689
+ if (keyObject.asymmetricKeyType === "x25519") {
12690
+ switch (alg) {
12691
+ case "ECDH-ES":
12692
+ case "ECDH-ES+A128KW":
12693
+ case "ECDH-ES+A192KW":
12694
+ case "ECDH-ES+A256KW":
12695
+ break;
12696
+ default:
12697
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
12698
+ }
12699
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
12700
+ }
12701
+ if (keyObject.asymmetricKeyType === "ed25519") {
12702
+ if (alg !== "EdDSA" && alg !== "Ed25519") {
12703
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
12704
+ }
12705
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
12706
+ isPublic ? "verify" : "sign"
12707
+ ]);
12708
+ }
12709
+ if (keyObject.asymmetricKeyType === "rsa") {
12710
+ let hash;
12711
+ switch (alg) {
12712
+ case "RSA-OAEP":
12713
+ hash = "SHA-1";
12714
+ break;
12715
+ case "RS256":
12716
+ case "PS256":
12717
+ case "RSA-OAEP-256":
12718
+ hash = "SHA-256";
12719
+ break;
12720
+ case "RS384":
12721
+ case "PS384":
12722
+ case "RSA-OAEP-384":
12723
+ hash = "SHA-384";
12724
+ break;
12725
+ case "RS512":
12726
+ case "PS512":
12727
+ case "RSA-OAEP-512":
12728
+ hash = "SHA-512";
12729
+ break;
12730
+ default:
12731
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
12732
+ }
12733
+ if (alg.startsWith("RSA-OAEP")) {
12734
+ return keyObject.toCryptoKey({
12735
+ name: "RSA-OAEP",
12736
+ hash
12737
+ }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
12738
+ }
12739
+ cryptoKey = keyObject.toCryptoKey({
12740
+ name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
12741
+ hash
12742
+ }, extractable, [isPublic ? "verify" : "sign"]);
12743
+ }
12744
+ if (keyObject.asymmetricKeyType === "ec") {
12745
+ const nist = /* @__PURE__ */ new Map([
12746
+ ["prime256v1", "P-256"],
12747
+ ["secp384r1", "P-384"],
12748
+ ["secp521r1", "P-521"]
12749
+ ]);
12750
+ const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
12751
+ if (!namedCurve) {
12752
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
12753
+ }
12754
+ if (alg === "ES256" && namedCurve === "P-256") {
12755
+ cryptoKey = keyObject.toCryptoKey({
12756
+ name: "ECDSA",
12757
+ namedCurve
12758
+ }, extractable, [isPublic ? "verify" : "sign"]);
12759
+ }
12760
+ if (alg === "ES384" && namedCurve === "P-384") {
12761
+ cryptoKey = keyObject.toCryptoKey({
12762
+ name: "ECDSA",
12763
+ namedCurve
12764
+ }, extractable, [isPublic ? "verify" : "sign"]);
12765
+ }
12766
+ if (alg === "ES512" && namedCurve === "P-521") {
12767
+ cryptoKey = keyObject.toCryptoKey({
12768
+ name: "ECDSA",
12769
+ namedCurve
12770
+ }, extractable, [isPublic ? "verify" : "sign"]);
12771
+ }
12772
+ if (alg.startsWith("ECDH-ES")) {
12773
+ cryptoKey = keyObject.toCryptoKey({
12774
+ name: "ECDH",
12775
+ namedCurve
12776
+ }, extractable, isPublic ? [] : ["deriveBits"]);
12777
+ }
12778
+ }
12779
+ if (!cryptoKey) {
12780
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
12781
+ }
12782
+ if (!cached) {
12783
+ cache.set(keyObject, { [alg]: cryptoKey });
12784
+ } else {
12785
+ cached[alg] = cryptoKey;
12786
+ }
12787
+ return cryptoKey;
12788
+ };
12789
+ var normalize_key_default = async (key, alg) => {
12790
+ if (key instanceof Uint8Array) {
12791
+ return key;
12792
+ }
12793
+ if (isCryptoKey(key)) {
12794
+ return key;
12795
+ }
12796
+ if (isKeyObject(key)) {
12797
+ if (key.type === "secret") {
12798
+ return key.export();
12799
+ }
12800
+ if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") {
12801
+ try {
12802
+ return handleKeyObject(key, alg);
12803
+ } catch (err) {
12804
+ if (err instanceof TypeError) {
12805
+ throw err;
12806
+ }
12807
+ }
12808
+ }
12809
+ let jwk = key.export({ format: "jwk" });
12810
+ return handleJWK(key, jwk, alg);
12811
+ }
12812
+ if (isJWK(key)) {
12813
+ if (key.k) {
12814
+ return decode(key.k);
12815
+ }
12816
+ return handleJWK(key, key, alg, true);
12817
+ }
12818
+ throw new Error("unreachable");
12819
+ };
12820
+
12821
+ // node_modules/jose/dist/webapi/lib/check_key_type.js
12822
+ var tag = (key) => key?.[Symbol.toStringTag];
12823
+ var jwkMatchesOp = (alg, key, usage2) => {
12824
+ if (key.use !== void 0) {
12825
+ let expected;
12826
+ switch (usage2) {
12827
+ case "sign":
12828
+ case "verify":
12829
+ expected = "sig";
12830
+ break;
12831
+ case "encrypt":
12832
+ case "decrypt":
12833
+ expected = "enc";
12834
+ break;
12835
+ }
12836
+ if (key.use !== expected) {
12837
+ throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
12838
+ }
12839
+ }
12840
+ if (key.alg !== void 0 && key.alg !== alg) {
12841
+ throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
12842
+ }
12843
+ if (Array.isArray(key.key_ops)) {
12844
+ let expectedKeyOp;
12845
+ switch (true) {
12846
+ case (usage2 === "sign" || usage2 === "verify"):
12847
+ case alg === "dir":
12848
+ case alg.includes("CBC-HS"):
12849
+ expectedKeyOp = usage2;
12850
+ break;
12851
+ case alg.startsWith("PBES2"):
12852
+ expectedKeyOp = "deriveBits";
12853
+ break;
12854
+ case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
12855
+ if (!alg.includes("GCM") && alg.endsWith("KW")) {
12856
+ expectedKeyOp = usage2 === "encrypt" ? "wrapKey" : "unwrapKey";
12857
+ } else {
12858
+ expectedKeyOp = usage2;
12859
+ }
12860
+ break;
12861
+ case (usage2 === "encrypt" && alg.startsWith("RSA")):
12862
+ expectedKeyOp = "wrapKey";
12863
+ break;
12864
+ case usage2 === "decrypt":
12865
+ expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
12866
+ break;
12867
+ }
12868
+ if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {
12869
+ throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
12870
+ }
12871
+ }
12872
+ return true;
12873
+ };
12874
+ var symmetricTypeCheck = (alg, key, usage2) => {
12875
+ if (key instanceof Uint8Array)
12876
+ return;
12877
+ if (isJWK(key)) {
12878
+ if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage2))
12879
+ return;
12880
+ 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`);
12881
+ }
12882
+ if (!is_key_like_default(key)) {
12883
+ throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
12884
+ }
12885
+ if (key.type !== "secret") {
12886
+ throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
12887
+ }
12888
+ };
12889
+ var asymmetricTypeCheck = (alg, key, usage2) => {
12890
+ if (isJWK(key)) {
12891
+ switch (usage2) {
12892
+ case "decrypt":
12893
+ case "sign":
12894
+ if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage2))
12895
+ return;
12896
+ throw new TypeError(`JSON Web Key for this operation be a private JWK`);
12897
+ case "encrypt":
12898
+ case "verify":
12899
+ if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage2))
12900
+ return;
12901
+ throw new TypeError(`JSON Web Key for this operation be a public JWK`);
12902
+ }
12903
+ }
12904
+ if (!is_key_like_default(key)) {
12905
+ throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
12906
+ }
12907
+ if (key.type === "secret") {
12908
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
12909
+ }
12910
+ if (key.type === "public") {
12911
+ switch (usage2) {
12912
+ case "sign":
12913
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
12914
+ case "decrypt":
12915
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
12916
+ default:
12917
+ break;
12918
+ }
12919
+ }
12920
+ if (key.type === "private") {
12921
+ switch (usage2) {
12922
+ case "verify":
12923
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
12924
+ case "encrypt":
12925
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
12926
+ default:
12927
+ break;
12928
+ }
12929
+ }
12930
+ };
12931
+ var check_key_type_default = (alg, key, usage2) => {
12932
+ const symmetric = alg.startsWith("HS") || alg === "dir" || alg.startsWith("PBES2") || /^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(alg) || /^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(alg);
12933
+ if (symmetric) {
12934
+ symmetricTypeCheck(alg, key, usage2);
12935
+ } else {
12936
+ asymmetricTypeCheck(alg, key, usage2);
12937
+ }
12938
+ };
12939
+
12940
+ // node_modules/jose/dist/webapi/jwe/flattened/decrypt.js
12941
+ async function flattenedDecrypt(jwe, key, options) {
12942
+ if (!is_object_default(jwe)) {
12943
+ throw new JWEInvalid("Flattened JWE must be an object");
12944
+ }
12945
+ if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) {
12946
+ throw new JWEInvalid("JOSE Header missing");
12947
+ }
12948
+ if (jwe.iv !== void 0 && typeof jwe.iv !== "string") {
12949
+ throw new JWEInvalid("JWE Initialization Vector incorrect type");
12950
+ }
12951
+ if (typeof jwe.ciphertext !== "string") {
12952
+ throw new JWEInvalid("JWE Ciphertext missing or incorrect type");
12953
+ }
12954
+ if (jwe.tag !== void 0 && typeof jwe.tag !== "string") {
12955
+ throw new JWEInvalid("JWE Authentication Tag incorrect type");
12956
+ }
12957
+ if (jwe.protected !== void 0 && typeof jwe.protected !== "string") {
12958
+ throw new JWEInvalid("JWE Protected Header incorrect type");
12959
+ }
12960
+ if (jwe.encrypted_key !== void 0 && typeof jwe.encrypted_key !== "string") {
12961
+ throw new JWEInvalid("JWE Encrypted Key incorrect type");
12962
+ }
12963
+ if (jwe.aad !== void 0 && typeof jwe.aad !== "string") {
12964
+ throw new JWEInvalid("JWE AAD incorrect type");
12965
+ }
12966
+ if (jwe.header !== void 0 && !is_object_default(jwe.header)) {
12967
+ throw new JWEInvalid("JWE Shared Unprotected Header incorrect type");
12968
+ }
12969
+ if (jwe.unprotected !== void 0 && !is_object_default(jwe.unprotected)) {
12970
+ throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");
12971
+ }
12972
+ let parsedProt;
12973
+ if (jwe.protected) {
12974
+ try {
12975
+ const protectedHeader2 = decode(jwe.protected);
12976
+ parsedProt = JSON.parse(decoder.decode(protectedHeader2));
12977
+ } catch {
12978
+ throw new JWEInvalid("JWE Protected Header is invalid");
12979
+ }
12980
+ }
12981
+ if (!is_disjoint_default(parsedProt, jwe.header, jwe.unprotected)) {
12982
+ throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");
12983
+ }
12984
+ const joseHeader = {
12985
+ ...parsedProt,
12986
+ ...jwe.header,
12987
+ ...jwe.unprotected
12988
+ };
12989
+ validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, parsedProt, joseHeader);
12990
+ if (joseHeader.zip !== void 0) {
12991
+ throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
12992
+ }
12993
+ const { alg, enc } = joseHeader;
12994
+ if (typeof alg !== "string" || !alg) {
12995
+ throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header");
12996
+ }
12997
+ if (typeof enc !== "string" || !enc) {
12998
+ throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");
12999
+ }
13000
+ const keyManagementAlgorithms = options && validate_algorithms_default("keyManagementAlgorithms", options.keyManagementAlgorithms);
13001
+ const contentEncryptionAlgorithms = options && validate_algorithms_default("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms);
13002
+ if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg) || !keyManagementAlgorithms && alg.startsWith("PBES2")) {
13003
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
13004
+ }
13005
+ if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
13006
+ throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');
13007
+ }
13008
+ let encryptedKey;
13009
+ if (jwe.encrypted_key !== void 0) {
13010
+ try {
13011
+ encryptedKey = decode(jwe.encrypted_key);
13012
+ } catch {
13013
+ throw new JWEInvalid("Failed to base64url decode the encrypted_key");
13014
+ }
13015
+ }
13016
+ let resolvedKey = false;
13017
+ if (typeof key === "function") {
13018
+ key = await key(parsedProt, jwe);
13019
+ resolvedKey = true;
13020
+ }
13021
+ check_key_type_default(alg === "dir" ? enc : alg, key, "decrypt");
13022
+ const k = await normalize_key_default(key, alg);
13023
+ let cek;
13024
+ try {
13025
+ cek = await decrypt_key_management_default(alg, k, encryptedKey, joseHeader, options);
13026
+ } catch (err) {
13027
+ if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) {
13028
+ throw err;
13029
+ }
13030
+ cek = cek_default(enc);
13031
+ }
13032
+ let iv;
13033
+ let tag2;
13034
+ if (jwe.iv !== void 0) {
13035
+ try {
13036
+ iv = decode(jwe.iv);
13037
+ } catch {
13038
+ throw new JWEInvalid("Failed to base64url decode the iv");
13039
+ }
13040
+ }
13041
+ if (jwe.tag !== void 0) {
13042
+ try {
13043
+ tag2 = decode(jwe.tag);
13044
+ } catch {
13045
+ throw new JWEInvalid("Failed to base64url decode the tag");
13046
+ }
13047
+ }
13048
+ const protectedHeader = encoder.encode(jwe.protected ?? "");
13049
+ let additionalData;
13050
+ if (jwe.aad !== void 0) {
13051
+ additionalData = concat(protectedHeader, encoder.encode("."), encoder.encode(jwe.aad));
13052
+ } else {
13053
+ additionalData = protectedHeader;
13054
+ }
13055
+ let ciphertext;
13056
+ try {
13057
+ ciphertext = decode(jwe.ciphertext);
13058
+ } catch {
13059
+ throw new JWEInvalid("Failed to base64url decode the ciphertext");
13060
+ }
13061
+ const plaintext = await decrypt_default(enc, cek, ciphertext, iv, tag2, additionalData);
13062
+ const result = { plaintext };
13063
+ if (jwe.protected !== void 0) {
13064
+ result.protectedHeader = parsedProt;
13065
+ }
13066
+ if (jwe.aad !== void 0) {
13067
+ try {
13068
+ result.additionalAuthenticatedData = decode(jwe.aad);
13069
+ } catch {
13070
+ throw new JWEInvalid("Failed to base64url decode the aad");
13071
+ }
13072
+ }
13073
+ if (jwe.unprotected !== void 0) {
13074
+ result.sharedUnprotectedHeader = jwe.unprotected;
13075
+ }
13076
+ if (jwe.header !== void 0) {
13077
+ result.unprotectedHeader = jwe.header;
13078
+ }
13079
+ if (resolvedKey) {
13080
+ return { ...result, key: k };
13081
+ }
13082
+ return result;
13083
+ }
13084
+
13085
+ // node_modules/jose/dist/webapi/jwe/compact/decrypt.js
13086
+ async function compactDecrypt(jwe, key, options) {
13087
+ if (jwe instanceof Uint8Array) {
13088
+ jwe = decoder.decode(jwe);
13089
+ }
13090
+ if (typeof jwe !== "string") {
13091
+ throw new JWEInvalid("Compact JWE must be a string or Uint8Array");
13092
+ }
13093
+ const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag2, length } = jwe.split(".");
13094
+ if (length !== 5) {
13095
+ throw new JWEInvalid("Invalid Compact JWE");
13096
+ }
13097
+ const decrypted = await flattenedDecrypt({
13098
+ ciphertext,
13099
+ iv: iv || void 0,
13100
+ protected: protectedHeader,
13101
+ tag: tag2 || void 0,
13102
+ encrypted_key: encryptedKey || void 0
13103
+ }, key, options);
13104
+ const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader };
13105
+ if (typeof key === "function") {
13106
+ return { ...result, key: decrypted.key };
13107
+ }
13108
+ return result;
13109
+ }
13110
+
13111
+ // node_modules/jose/dist/webapi/lib/private_symbols.js
13112
+ var unprotected = Symbol();
13113
+
13114
+ // node_modules/jose/dist/webapi/lib/key_to_jwk.js
13115
+ async function keyToJWK(key) {
13116
+ if (isKeyObject(key)) {
13117
+ if (key.type === "secret") {
13118
+ key = key.export();
13119
+ } else {
13120
+ return key.export({ format: "jwk" });
13121
+ }
13122
+ }
13123
+ if (key instanceof Uint8Array) {
13124
+ return {
13125
+ kty: "oct",
13126
+ k: encode(key)
13127
+ };
13128
+ }
13129
+ if (!isCryptoKey(key)) {
13130
+ throw new TypeError(invalid_key_input_default(key, "CryptoKey", "KeyObject", "Uint8Array"));
13131
+ }
13132
+ if (!key.extractable) {
13133
+ throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
13134
+ }
13135
+ const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey("jwk", key);
13136
+ return jwk;
13137
+ }
13138
+
13139
+ // node_modules/jose/dist/webapi/key/export.js
13140
+ async function exportJWK(key) {
13141
+ return keyToJWK(key);
13142
+ }
13143
+
13144
+ // node_modules/jose/dist/webapi/lib/encrypt_key_management.js
13145
+ var encrypt_key_management_default = async (alg, enc, key, providedCek, providedParameters = {}) => {
13146
+ let encryptedKey;
13147
+ let parameters;
13148
+ let cek;
13149
+ switch (alg) {
13150
+ case "dir": {
13151
+ cek = key;
13152
+ break;
13153
+ }
13154
+ case "ECDH-ES":
13155
+ case "ECDH-ES+A128KW":
13156
+ case "ECDH-ES+A192KW":
13157
+ case "ECDH-ES+A256KW": {
13158
+ assertCryptoKey(key);
13159
+ if (!allowed(key)) {
13160
+ throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
13161
+ }
13162
+ const { apu, apv } = providedParameters;
13163
+ let ephemeralKey;
13164
+ if (providedParameters.epk) {
13165
+ ephemeralKey = await normalize_key_default(providedParameters.epk, alg);
13166
+ } else {
13167
+ ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ["deriveBits"])).privateKey;
13168
+ }
13169
+ const { x, y, crv, kty } = await exportJWK(ephemeralKey);
13170
+ const sharedSecret = await deriveKey(key, ephemeralKey, alg === "ECDH-ES" ? enc : alg, alg === "ECDH-ES" ? bitLength2(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);
13171
+ parameters = { epk: { x, crv, kty } };
13172
+ if (kty === "EC")
13173
+ parameters.epk.y = y;
13174
+ if (apu)
13175
+ parameters.apu = encode(apu);
13176
+ if (apv)
13177
+ parameters.apv = encode(apv);
13178
+ if (alg === "ECDH-ES") {
13179
+ cek = sharedSecret;
13180
+ break;
13181
+ }
13182
+ cek = providedCek || cek_default(enc);
13183
+ const kwAlg = alg.slice(-6);
13184
+ encryptedKey = await wrap(kwAlg, sharedSecret, cek);
13185
+ break;
13186
+ }
13187
+ case "RSA-OAEP":
13188
+ case "RSA-OAEP-256":
13189
+ case "RSA-OAEP-384":
13190
+ case "RSA-OAEP-512": {
13191
+ cek = providedCek || cek_default(enc);
13192
+ assertCryptoKey(key);
13193
+ encryptedKey = await encrypt(alg, key, cek);
13194
+ break;
13195
+ }
13196
+ case "PBES2-HS256+A128KW":
13197
+ case "PBES2-HS384+A192KW":
13198
+ case "PBES2-HS512+A256KW": {
13199
+ cek = providedCek || cek_default(enc);
13200
+ const { p2c, p2s } = providedParameters;
13201
+ ({ encryptedKey, ...parameters } = await wrap2(alg, key, cek, p2c, p2s));
13202
+ break;
13203
+ }
13204
+ case "A128KW":
13205
+ case "A192KW":
13206
+ case "A256KW": {
13207
+ cek = providedCek || cek_default(enc);
13208
+ encryptedKey = await wrap(alg, key, cek);
13209
+ break;
13210
+ }
13211
+ case "A128GCMKW":
13212
+ case "A192GCMKW":
13213
+ case "A256GCMKW": {
13214
+ cek = providedCek || cek_default(enc);
13215
+ const { iv } = providedParameters;
13216
+ ({ encryptedKey, ...parameters } = await wrap3(alg, key, cek, iv));
13217
+ break;
13218
+ }
13219
+ default: {
13220
+ throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
13221
+ }
13222
+ }
13223
+ return { cek, encryptedKey, parameters };
13224
+ };
13225
+
13226
+ // node_modules/jose/dist/webapi/jwe/flattened/encrypt.js
13227
+ var FlattenedEncrypt = class {
13228
+ #plaintext;
13229
+ #protectedHeader;
13230
+ #sharedUnprotectedHeader;
13231
+ #unprotectedHeader;
13232
+ #aad;
13233
+ #cek;
13234
+ #iv;
13235
+ #keyManagementParameters;
13236
+ constructor(plaintext) {
13237
+ if (!(plaintext instanceof Uint8Array)) {
13238
+ throw new TypeError("plaintext must be an instance of Uint8Array");
13239
+ }
13240
+ this.#plaintext = plaintext;
13241
+ }
13242
+ setKeyManagementParameters(parameters) {
13243
+ if (this.#keyManagementParameters) {
13244
+ throw new TypeError("setKeyManagementParameters can only be called once");
13245
+ }
13246
+ this.#keyManagementParameters = parameters;
13247
+ return this;
13248
+ }
13249
+ setProtectedHeader(protectedHeader) {
13250
+ if (this.#protectedHeader) {
13251
+ throw new TypeError("setProtectedHeader can only be called once");
13252
+ }
13253
+ this.#protectedHeader = protectedHeader;
13254
+ return this;
13255
+ }
13256
+ setSharedUnprotectedHeader(sharedUnprotectedHeader) {
13257
+ if (this.#sharedUnprotectedHeader) {
13258
+ throw new TypeError("setSharedUnprotectedHeader can only be called once");
13259
+ }
13260
+ this.#sharedUnprotectedHeader = sharedUnprotectedHeader;
13261
+ return this;
13262
+ }
13263
+ setUnprotectedHeader(unprotectedHeader) {
13264
+ if (this.#unprotectedHeader) {
13265
+ throw new TypeError("setUnprotectedHeader can only be called once");
13266
+ }
13267
+ this.#unprotectedHeader = unprotectedHeader;
13268
+ return this;
13269
+ }
13270
+ setAdditionalAuthenticatedData(aad) {
13271
+ this.#aad = aad;
13272
+ return this;
13273
+ }
13274
+ setContentEncryptionKey(cek) {
13275
+ if (this.#cek) {
13276
+ throw new TypeError("setContentEncryptionKey can only be called once");
13277
+ }
13278
+ this.#cek = cek;
13279
+ return this;
13280
+ }
13281
+ setInitializationVector(iv) {
13282
+ if (this.#iv) {
13283
+ throw new TypeError("setInitializationVector can only be called once");
13284
+ }
13285
+ this.#iv = iv;
13286
+ return this;
13287
+ }
13288
+ async encrypt(key, options) {
13289
+ if (!this.#protectedHeader && !this.#unprotectedHeader && !this.#sharedUnprotectedHeader) {
13290
+ throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");
13291
+ }
13292
+ if (!is_disjoint_default(this.#protectedHeader, this.#unprotectedHeader, this.#sharedUnprotectedHeader)) {
13293
+ throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
13294
+ }
13295
+ const joseHeader = {
13296
+ ...this.#protectedHeader,
13297
+ ...this.#unprotectedHeader,
13298
+ ...this.#sharedUnprotectedHeader
13299
+ };
13300
+ validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, this.#protectedHeader, joseHeader);
13301
+ if (joseHeader.zip !== void 0) {
13302
+ throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
13303
+ }
13304
+ const { alg, enc } = joseHeader;
13305
+ if (typeof alg !== "string" || !alg) {
13306
+ throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
13307
+ }
13308
+ if (typeof enc !== "string" || !enc) {
13309
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
13310
+ }
13311
+ let encryptedKey;
13312
+ if (this.#cek && (alg === "dir" || alg === "ECDH-ES")) {
13313
+ throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`);
13314
+ }
13315
+ check_key_type_default(alg === "dir" ? enc : alg, key, "encrypt");
13316
+ let cek;
13317
+ {
13318
+ let parameters;
13319
+ const k = await normalize_key_default(key, alg);
13320
+ ({ cek, encryptedKey, parameters } = await encrypt_key_management_default(alg, enc, k, this.#cek, this.#keyManagementParameters));
13321
+ if (parameters) {
13322
+ if (options && unprotected in options) {
13323
+ if (!this.#unprotectedHeader) {
13324
+ this.setUnprotectedHeader(parameters);
13325
+ } else {
13326
+ this.#unprotectedHeader = { ...this.#unprotectedHeader, ...parameters };
13327
+ }
13328
+ } else if (!this.#protectedHeader) {
13329
+ this.setProtectedHeader(parameters);
13330
+ } else {
13331
+ this.#protectedHeader = { ...this.#protectedHeader, ...parameters };
13332
+ }
13333
+ }
13334
+ }
13335
+ let additionalData;
13336
+ let protectedHeader;
13337
+ let aadMember;
13338
+ if (this.#protectedHeader) {
13339
+ protectedHeader = encoder.encode(encode(JSON.stringify(this.#protectedHeader)));
13340
+ } else {
13341
+ protectedHeader = encoder.encode("");
13342
+ }
13343
+ if (this.#aad) {
13344
+ aadMember = encode(this.#aad);
13345
+ additionalData = concat(protectedHeader, encoder.encode("."), encoder.encode(aadMember));
13346
+ } else {
13347
+ additionalData = protectedHeader;
13348
+ }
13349
+ const { ciphertext, tag: tag2, iv } = await encrypt_default(enc, this.#plaintext, cek, this.#iv, additionalData);
13350
+ const jwe = {
13351
+ ciphertext: encode(ciphertext)
13352
+ };
13353
+ if (iv) {
13354
+ jwe.iv = encode(iv);
13355
+ }
13356
+ if (tag2) {
13357
+ jwe.tag = encode(tag2);
13358
+ }
13359
+ if (encryptedKey) {
13360
+ jwe.encrypted_key = encode(encryptedKey);
13361
+ }
13362
+ if (aadMember) {
13363
+ jwe.aad = aadMember;
13364
+ }
13365
+ if (this.#protectedHeader) {
13366
+ jwe.protected = decoder.decode(protectedHeader);
13367
+ }
13368
+ if (this.#sharedUnprotectedHeader) {
13369
+ jwe.unprotected = this.#sharedUnprotectedHeader;
13370
+ }
13371
+ if (this.#unprotectedHeader) {
13372
+ jwe.header = this.#unprotectedHeader;
13373
+ }
13374
+ return jwe;
13375
+ }
13376
+ };
13377
+
13378
+ // node_modules/jose/dist/webapi/lib/subtle_dsa.js
13379
+ var subtle_dsa_default = (alg, algorithm) => {
13380
+ const hash = `SHA-${alg.slice(-3)}`;
13381
+ switch (alg) {
13382
+ case "HS256":
13383
+ case "HS384":
13384
+ case "HS512":
13385
+ return { hash, name: "HMAC" };
13386
+ case "PS256":
13387
+ case "PS384":
13388
+ case "PS512":
13389
+ return { hash, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 };
13390
+ case "RS256":
13391
+ case "RS384":
13392
+ case "RS512":
13393
+ return { hash, name: "RSASSA-PKCS1-v1_5" };
13394
+ case "ES256":
13395
+ case "ES384":
13396
+ case "ES512":
13397
+ return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve };
13398
+ case "Ed25519":
13399
+ case "EdDSA":
13400
+ return { name: "Ed25519" };
13401
+ default:
13402
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
13403
+ }
13404
+ };
13405
+
13406
+ // node_modules/jose/dist/webapi/lib/get_sign_verify_key.js
13407
+ var get_sign_verify_key_default = async (alg, key, usage2) => {
13408
+ if (key instanceof Uint8Array) {
13409
+ if (!alg.startsWith("HS")) {
13410
+ throw new TypeError(invalid_key_input_default(key, "CryptoKey", "KeyObject", "JSON Web Key"));
13411
+ }
13412
+ return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage2]);
13413
+ }
13414
+ checkSigCryptoKey(key, alg, usage2);
13415
+ return key;
13416
+ };
13417
+
13418
+ // node_modules/jose/dist/webapi/lib/verify.js
13419
+ var verify_default = async (alg, key, signature, data) => {
13420
+ const cryptoKey = await get_sign_verify_key_default(alg, key, "verify");
13421
+ check_key_length_default(alg, cryptoKey);
13422
+ const algorithm = subtle_dsa_default(alg, cryptoKey.algorithm);
13423
+ try {
13424
+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
13425
+ } catch {
13426
+ return false;
13427
+ }
13428
+ };
13429
+
13430
+ // node_modules/jose/dist/webapi/jws/flattened/verify.js
13431
+ async function flattenedVerify(jws, key, options) {
13432
+ if (!is_object_default(jws)) {
13433
+ throw new JWSInvalid("Flattened JWS must be an object");
13434
+ }
13435
+ if (jws.protected === void 0 && jws.header === void 0) {
13436
+ throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
13437
+ }
13438
+ if (jws.protected !== void 0 && typeof jws.protected !== "string") {
13439
+ throw new JWSInvalid("JWS Protected Header incorrect type");
13440
+ }
13441
+ if (jws.payload === void 0) {
13442
+ throw new JWSInvalid("JWS Payload missing");
13443
+ }
13444
+ if (typeof jws.signature !== "string") {
13445
+ throw new JWSInvalid("JWS Signature missing or incorrect type");
13446
+ }
13447
+ if (jws.header !== void 0 && !is_object_default(jws.header)) {
13448
+ throw new JWSInvalid("JWS Unprotected Header incorrect type");
13449
+ }
13450
+ let parsedProt = {};
13451
+ if (jws.protected) {
13452
+ try {
13453
+ const protectedHeader = decode(jws.protected);
13454
+ parsedProt = JSON.parse(decoder.decode(protectedHeader));
13455
+ } catch {
13456
+ throw new JWSInvalid("JWS Protected Header is invalid");
13457
+ }
13458
+ }
13459
+ if (!is_disjoint_default(parsedProt, jws.header)) {
13460
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
13461
+ }
13462
+ const joseHeader = {
13463
+ ...parsedProt,
13464
+ ...jws.header
13465
+ };
13466
+ const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
13467
+ let b64 = true;
13468
+ if (extensions.has("b64")) {
13469
+ b64 = parsedProt.b64;
13470
+ if (typeof b64 !== "boolean") {
13471
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
13472
+ }
13473
+ }
13474
+ const { alg } = joseHeader;
13475
+ if (typeof alg !== "string" || !alg) {
13476
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
13477
+ }
13478
+ const algorithms = options && validate_algorithms_default("algorithms", options.algorithms);
13479
+ if (algorithms && !algorithms.has(alg)) {
13480
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
13481
+ }
13482
+ if (b64) {
13483
+ if (typeof jws.payload !== "string") {
13484
+ throw new JWSInvalid("JWS Payload must be a string");
13485
+ }
13486
+ } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) {
13487
+ throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
13488
+ }
13489
+ let resolvedKey = false;
13490
+ if (typeof key === "function") {
13491
+ key = await key(parsedProt, jws);
13492
+ resolvedKey = true;
13493
+ }
13494
+ check_key_type_default(alg, key, "verify");
13495
+ const data = concat(encoder.encode(jws.protected ?? ""), encoder.encode("."), typeof jws.payload === "string" ? encoder.encode(jws.payload) : jws.payload);
13496
+ let signature;
13497
+ try {
13498
+ signature = decode(jws.signature);
13499
+ } catch {
13500
+ throw new JWSInvalid("Failed to base64url decode the signature");
13501
+ }
13502
+ const k = await normalize_key_default(key, alg);
13503
+ const verified = await verify_default(alg, k, signature, data);
13504
+ if (!verified) {
13505
+ throw new JWSSignatureVerificationFailed();
13506
+ }
13507
+ let payload;
13508
+ if (b64) {
13509
+ try {
13510
+ payload = decode(jws.payload);
13511
+ } catch {
13512
+ throw new JWSInvalid("Failed to base64url decode the payload");
13513
+ }
13514
+ } else if (typeof jws.payload === "string") {
13515
+ payload = encoder.encode(jws.payload);
13516
+ } else {
13517
+ payload = jws.payload;
13518
+ }
13519
+ const result = { payload };
13520
+ if (jws.protected !== void 0) {
13521
+ result.protectedHeader = parsedProt;
13522
+ }
13523
+ if (jws.header !== void 0) {
13524
+ result.unprotectedHeader = jws.header;
13525
+ }
13526
+ if (resolvedKey) {
13527
+ return { ...result, key: k };
13528
+ }
13529
+ return result;
13530
+ }
13531
+
13532
+ // node_modules/jose/dist/webapi/jws/compact/verify.js
13533
+ async function compactVerify(jws, key, options) {
13534
+ if (jws instanceof Uint8Array) {
13535
+ jws = decoder.decode(jws);
13536
+ }
13537
+ if (typeof jws !== "string") {
13538
+ throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
13539
+ }
13540
+ const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
13541
+ if (length !== 3) {
13542
+ throw new JWSInvalid("Invalid Compact JWS");
13543
+ }
13544
+ const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);
13545
+ const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
13546
+ if (typeof key === "function") {
13547
+ return { ...result, key: verified.key };
13548
+ }
13549
+ return result;
13550
+ }
13551
+
13552
+ // node_modules/jose/dist/webapi/lib/epoch.js
13553
+ var epoch_default = (date) => Math.floor(date.getTime() / 1e3);
13554
+
13555
+ // node_modules/jose/dist/webapi/lib/secs.js
13556
+ var minute = 60;
13557
+ var hour = minute * 60;
13558
+ var day = hour * 24;
13559
+ var week = day * 7;
13560
+ var year = day * 365.25;
13561
+ 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;
13562
+ var secs_default = (str) => {
13563
+ const matched = REGEX.exec(str);
13564
+ if (!matched || matched[4] && matched[1]) {
13565
+ throw new TypeError("Invalid time period format");
13566
+ }
13567
+ const value = parseFloat(matched[2]);
13568
+ const unit = matched[3].toLowerCase();
13569
+ let numericDate;
13570
+ switch (unit) {
13571
+ case "sec":
13572
+ case "secs":
13573
+ case "second":
13574
+ case "seconds":
13575
+ case "s":
13576
+ numericDate = Math.round(value);
13577
+ break;
13578
+ case "minute":
13579
+ case "minutes":
13580
+ case "min":
13581
+ case "mins":
13582
+ case "m":
13583
+ numericDate = Math.round(value * minute);
13584
+ break;
13585
+ case "hour":
13586
+ case "hours":
13587
+ case "hr":
13588
+ case "hrs":
13589
+ case "h":
13590
+ numericDate = Math.round(value * hour);
13591
+ break;
13592
+ case "day":
13593
+ case "days":
13594
+ case "d":
13595
+ numericDate = Math.round(value * day);
13596
+ break;
13597
+ case "week":
13598
+ case "weeks":
13599
+ case "w":
13600
+ numericDate = Math.round(value * week);
13601
+ break;
13602
+ default:
13603
+ numericDate = Math.round(value * year);
13604
+ break;
13605
+ }
13606
+ if (matched[1] === "-" || matched[4] === "ago") {
13607
+ return -numericDate;
13608
+ }
13609
+ return numericDate;
13610
+ };
13611
+
13612
+ // node_modules/jose/dist/webapi/lib/jwt_claims_set.js
13613
+ function validateInput(label, input) {
13614
+ if (!Number.isFinite(input)) {
13615
+ throw new TypeError(`Invalid ${label} input`);
13616
+ }
13617
+ return input;
13618
+ }
13619
+ var normalizeTyp = (value) => {
13620
+ if (value.includes("/")) {
13621
+ return value.toLowerCase();
13622
+ }
13623
+ return `application/${value.toLowerCase()}`;
13624
+ };
13625
+ var checkAudiencePresence = (audPayload, audOption) => {
13626
+ if (typeof audPayload === "string") {
13627
+ return audOption.includes(audPayload);
13628
+ }
13629
+ if (Array.isArray(audPayload)) {
13630
+ return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
13631
+ }
13632
+ return false;
13633
+ };
13634
+ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
13635
+ let payload;
13636
+ try {
13637
+ payload = JSON.parse(decoder.decode(encodedPayload));
13638
+ } catch {
13639
+ }
13640
+ if (!is_object_default(payload)) {
13641
+ throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
13642
+ }
13643
+ const { typ } = options;
13644
+ if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
13645
+ throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed");
13646
+ }
13647
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
13648
+ const presenceCheck = [...requiredClaims];
13649
+ if (maxTokenAge !== void 0)
13650
+ presenceCheck.push("iat");
13651
+ if (audience !== void 0)
13652
+ presenceCheck.push("aud");
13653
+ if (subject !== void 0)
13654
+ presenceCheck.push("sub");
13655
+ if (issuer !== void 0)
13656
+ presenceCheck.push("iss");
13657
+ for (const claim of new Set(presenceCheck.reverse())) {
13658
+ if (!(claim in payload)) {
13659
+ throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
13660
+ }
13661
+ }
13662
+ if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
13663
+ throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed");
13664
+ }
13665
+ if (subject && payload.sub !== subject) {
13666
+ throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed");
13667
+ }
13668
+ if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) {
13669
+ throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed");
13670
+ }
13671
+ let tolerance;
13672
+ switch (typeof options.clockTolerance) {
13673
+ case "string":
13674
+ tolerance = secs_default(options.clockTolerance);
13675
+ break;
13676
+ case "number":
13677
+ tolerance = options.clockTolerance;
13678
+ break;
13679
+ case "undefined":
13680
+ tolerance = 0;
13681
+ break;
13682
+ default:
13683
+ throw new TypeError("Invalid clockTolerance option type");
13684
+ }
13685
+ const { currentDate } = options;
13686
+ const now = epoch_default(currentDate || /* @__PURE__ */ new Date());
13687
+ if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") {
13688
+ throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid");
13689
+ }
13690
+ if (payload.nbf !== void 0) {
13691
+ if (typeof payload.nbf !== "number") {
13692
+ throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid");
13693
+ }
13694
+ if (payload.nbf > now + tolerance) {
13695
+ throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed");
13696
+ }
13697
+ }
13698
+ if (payload.exp !== void 0) {
13699
+ if (typeof payload.exp !== "number") {
13700
+ throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid");
13701
+ }
13702
+ if (payload.exp <= now - tolerance) {
13703
+ throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed");
13704
+ }
13705
+ }
13706
+ if (maxTokenAge) {
13707
+ const age = now - payload.iat;
13708
+ const max = typeof maxTokenAge === "number" ? maxTokenAge : secs_default(maxTokenAge);
13709
+ if (age - tolerance > max) {
13710
+ throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed");
13711
+ }
13712
+ if (age < 0 - tolerance) {
13713
+ throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed");
13714
+ }
13715
+ }
13716
+ return payload;
13717
+ }
13718
+ var JWTClaimsBuilder = class {
13719
+ #payload;
13720
+ constructor(payload) {
13721
+ if (!is_object_default(payload)) {
13722
+ throw new TypeError("JWT Claims Set MUST be an object");
13723
+ }
13724
+ this.#payload = structuredClone(payload);
13725
+ }
13726
+ data() {
13727
+ return encoder.encode(JSON.stringify(this.#payload));
13728
+ }
13729
+ get iss() {
13730
+ return this.#payload.iss;
13731
+ }
13732
+ set iss(value) {
13733
+ this.#payload.iss = value;
13734
+ }
13735
+ get sub() {
13736
+ return this.#payload.sub;
13737
+ }
13738
+ set sub(value) {
13739
+ this.#payload.sub = value;
13740
+ }
13741
+ get aud() {
13742
+ return this.#payload.aud;
13743
+ }
13744
+ set aud(value) {
13745
+ this.#payload.aud = value;
13746
+ }
13747
+ set jti(value) {
13748
+ this.#payload.jti = value;
13749
+ }
13750
+ set nbf(value) {
13751
+ if (typeof value === "number") {
13752
+ this.#payload.nbf = validateInput("setNotBefore", value);
13753
+ } else if (value instanceof Date) {
13754
+ this.#payload.nbf = validateInput("setNotBefore", epoch_default(value));
13755
+ } else {
13756
+ this.#payload.nbf = epoch_default(/* @__PURE__ */ new Date()) + secs_default(value);
13757
+ }
13758
+ }
13759
+ set exp(value) {
13760
+ if (typeof value === "number") {
13761
+ this.#payload.exp = validateInput("setExpirationTime", value);
13762
+ } else if (value instanceof Date) {
13763
+ this.#payload.exp = validateInput("setExpirationTime", epoch_default(value));
13764
+ } else {
13765
+ this.#payload.exp = epoch_default(/* @__PURE__ */ new Date()) + secs_default(value);
13766
+ }
13767
+ }
13768
+ set iat(value) {
13769
+ if (typeof value === "undefined") {
13770
+ this.#payload.iat = epoch_default(/* @__PURE__ */ new Date());
13771
+ } else if (value instanceof Date) {
13772
+ this.#payload.iat = validateInput("setIssuedAt", epoch_default(value));
13773
+ } else if (typeof value === "string") {
13774
+ this.#payload.iat = validateInput("setIssuedAt", epoch_default(/* @__PURE__ */ new Date()) + secs_default(value));
13775
+ } else {
13776
+ this.#payload.iat = validateInput("setIssuedAt", value);
13777
+ }
13778
+ }
13779
+ };
13780
+
13781
+ // node_modules/jose/dist/webapi/jwt/verify.js
13782
+ async function jwtVerify(jwt, key, options) {
13783
+ const verified = await compactVerify(jwt, key, options);
13784
+ if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) {
13785
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
13786
+ }
13787
+ const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
13788
+ const result = { payload, protectedHeader: verified.protectedHeader };
13789
+ if (typeof key === "function") {
13790
+ return { ...result, key: verified.key };
13791
+ }
13792
+ return result;
13793
+ }
13794
+
13795
+ // node_modules/jose/dist/webapi/jwt/decrypt.js
13796
+ async function jwtDecrypt(jwt, key, options) {
13797
+ const decrypted = await compactDecrypt(jwt, key, options);
13798
+ const payload = validateClaimsSet(decrypted.protectedHeader, decrypted.plaintext, options);
13799
+ const { protectedHeader } = decrypted;
13800
+ if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload.iss) {
13801
+ throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, "iss", "mismatch");
13802
+ }
13803
+ if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload.sub) {
13804
+ throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, "sub", "mismatch");
13805
+ }
13806
+ if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) {
13807
+ throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, "aud", "mismatch");
13808
+ }
13809
+ const result = { payload, protectedHeader };
13810
+ if (typeof key === "function") {
13811
+ return { ...result, key: decrypted.key };
13812
+ }
13813
+ return result;
13814
+ }
13815
+
13816
+ // node_modules/jose/dist/webapi/jwe/compact/encrypt.js
13817
+ var CompactEncrypt = class {
13818
+ #flattened;
13819
+ constructor(plaintext) {
13820
+ this.#flattened = new FlattenedEncrypt(plaintext);
13821
+ }
13822
+ setContentEncryptionKey(cek) {
13823
+ this.#flattened.setContentEncryptionKey(cek);
13824
+ return this;
13825
+ }
13826
+ setInitializationVector(iv) {
13827
+ this.#flattened.setInitializationVector(iv);
13828
+ return this;
13829
+ }
13830
+ setProtectedHeader(protectedHeader) {
13831
+ this.#flattened.setProtectedHeader(protectedHeader);
13832
+ return this;
13833
+ }
13834
+ setKeyManagementParameters(parameters) {
13835
+ this.#flattened.setKeyManagementParameters(parameters);
13836
+ return this;
13837
+ }
13838
+ async encrypt(key, options) {
13839
+ const jwe = await this.#flattened.encrypt(key, options);
13840
+ return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join(".");
13841
+ }
13842
+ };
13843
+
13844
+ // node_modules/jose/dist/webapi/lib/sign.js
13845
+ var sign_default = async (alg, key, data) => {
13846
+ const cryptoKey = await get_sign_verify_key_default(alg, key, "sign");
13847
+ check_key_length_default(alg, cryptoKey);
13848
+ const signature = await crypto.subtle.sign(subtle_dsa_default(alg, cryptoKey.algorithm), cryptoKey, data);
13849
+ return new Uint8Array(signature);
13850
+ };
13851
+
13852
+ // node_modules/jose/dist/webapi/jws/flattened/sign.js
13853
+ var FlattenedSign = class {
13854
+ #payload;
13855
+ #protectedHeader;
13856
+ #unprotectedHeader;
13857
+ constructor(payload) {
13858
+ if (!(payload instanceof Uint8Array)) {
13859
+ throw new TypeError("payload must be an instance of Uint8Array");
13860
+ }
13861
+ this.#payload = payload;
13862
+ }
13863
+ setProtectedHeader(protectedHeader) {
13864
+ if (this.#protectedHeader) {
13865
+ throw new TypeError("setProtectedHeader can only be called once");
13866
+ }
13867
+ this.#protectedHeader = protectedHeader;
13868
+ return this;
13869
+ }
13870
+ setUnprotectedHeader(unprotectedHeader) {
13871
+ if (this.#unprotectedHeader) {
13872
+ throw new TypeError("setUnprotectedHeader can only be called once");
13873
+ }
13874
+ this.#unprotectedHeader = unprotectedHeader;
13875
+ return this;
13876
+ }
13877
+ async sign(key, options) {
13878
+ if (!this.#protectedHeader && !this.#unprotectedHeader) {
13879
+ throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
13880
+ }
13881
+ if (!is_disjoint_default(this.#protectedHeader, this.#unprotectedHeader)) {
13882
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
13883
+ }
13884
+ const joseHeader = {
13885
+ ...this.#protectedHeader,
13886
+ ...this.#unprotectedHeader
13887
+ };
13888
+ const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader);
13889
+ let b64 = true;
13890
+ if (extensions.has("b64")) {
13891
+ b64 = this.#protectedHeader.b64;
13892
+ if (typeof b64 !== "boolean") {
13893
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
13894
+ }
13895
+ }
13896
+ const { alg } = joseHeader;
13897
+ if (typeof alg !== "string" || !alg) {
13898
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
13899
+ }
13900
+ check_key_type_default(alg, key, "sign");
13901
+ let payload = this.#payload;
13902
+ if (b64) {
13903
+ payload = encoder.encode(encode(payload));
13904
+ }
13905
+ let protectedHeader;
13906
+ if (this.#protectedHeader) {
13907
+ protectedHeader = encoder.encode(encode(JSON.stringify(this.#protectedHeader)));
13908
+ } else {
13909
+ protectedHeader = encoder.encode("");
13910
+ }
13911
+ const data = concat(protectedHeader, encoder.encode("."), payload);
13912
+ const k = await normalize_key_default(key, alg);
13913
+ const signature = await sign_default(alg, k, data);
13914
+ const jws = {
13915
+ signature: encode(signature),
13916
+ payload: ""
13917
+ };
13918
+ if (b64) {
13919
+ jws.payload = decoder.decode(payload);
13920
+ }
13921
+ if (this.#unprotectedHeader) {
13922
+ jws.header = this.#unprotectedHeader;
13923
+ }
13924
+ if (this.#protectedHeader) {
13925
+ jws.protected = decoder.decode(protectedHeader);
13926
+ }
13927
+ return jws;
13928
+ }
13929
+ };
13930
+
13931
+ // node_modules/jose/dist/webapi/jws/compact/sign.js
13932
+ var CompactSign = class {
13933
+ #flattened;
13934
+ constructor(payload) {
13935
+ this.#flattened = new FlattenedSign(payload);
13936
+ }
13937
+ setProtectedHeader(protectedHeader) {
13938
+ this.#flattened.setProtectedHeader(protectedHeader);
13939
+ return this;
13940
+ }
13941
+ async sign(key, options) {
13942
+ const jws = await this.#flattened.sign(key, options);
13943
+ if (jws.payload === void 0) {
13944
+ throw new TypeError("use the flattened module for creating JWS with b64: false");
13945
+ }
13946
+ return `${jws.protected}.${jws.payload}.${jws.signature}`;
13947
+ }
13948
+ };
13949
+
13950
+ // node_modules/jose/dist/webapi/jwt/sign.js
13951
+ var SignJWT = class {
13952
+ #protectedHeader;
13953
+ #jwt;
13954
+ constructor(payload = {}) {
13955
+ this.#jwt = new JWTClaimsBuilder(payload);
13956
+ }
13957
+ setIssuer(issuer) {
13958
+ this.#jwt.iss = issuer;
13959
+ return this;
13960
+ }
13961
+ setSubject(subject) {
13962
+ this.#jwt.sub = subject;
13963
+ return this;
13964
+ }
13965
+ setAudience(audience) {
13966
+ this.#jwt.aud = audience;
13967
+ return this;
13968
+ }
13969
+ setJti(jwtId) {
13970
+ this.#jwt.jti = jwtId;
13971
+ return this;
13972
+ }
13973
+ setNotBefore(input) {
13974
+ this.#jwt.nbf = input;
13975
+ return this;
13976
+ }
13977
+ setExpirationTime(input) {
13978
+ this.#jwt.exp = input;
13979
+ return this;
13980
+ }
13981
+ setIssuedAt(input) {
13982
+ this.#jwt.iat = input;
13983
+ return this;
13984
+ }
13985
+ setProtectedHeader(protectedHeader) {
13986
+ this.#protectedHeader = protectedHeader;
13987
+ return this;
13988
+ }
13989
+ async sign(key, options) {
13990
+ const sig = new CompactSign(this.#jwt.data());
13991
+ sig.setProtectedHeader(this.#protectedHeader);
13992
+ if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes("b64") && this.#protectedHeader.b64 === false) {
13993
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
13994
+ }
13995
+ return sig.sign(key, options);
13996
+ }
13997
+ };
13998
+
13999
+ // node_modules/jose/dist/webapi/jwt/encrypt.js
14000
+ var EncryptJWT = class {
14001
+ #cek;
14002
+ #iv;
14003
+ #keyManagementParameters;
14004
+ #protectedHeader;
14005
+ #replicateIssuerAsHeader;
14006
+ #replicateSubjectAsHeader;
14007
+ #replicateAudienceAsHeader;
14008
+ #jwt;
14009
+ constructor(payload = {}) {
14010
+ this.#jwt = new JWTClaimsBuilder(payload);
14011
+ }
14012
+ setIssuer(issuer) {
14013
+ this.#jwt.iss = issuer;
14014
+ return this;
14015
+ }
14016
+ setSubject(subject) {
14017
+ this.#jwt.sub = subject;
14018
+ return this;
14019
+ }
14020
+ setAudience(audience) {
14021
+ this.#jwt.aud = audience;
14022
+ return this;
14023
+ }
14024
+ setJti(jwtId) {
14025
+ this.#jwt.jti = jwtId;
14026
+ return this;
14027
+ }
14028
+ setNotBefore(input) {
14029
+ this.#jwt.nbf = input;
14030
+ return this;
14031
+ }
14032
+ setExpirationTime(input) {
14033
+ this.#jwt.exp = input;
14034
+ return this;
14035
+ }
14036
+ setIssuedAt(input) {
14037
+ this.#jwt.iat = input;
14038
+ return this;
14039
+ }
14040
+ setProtectedHeader(protectedHeader) {
14041
+ if (this.#protectedHeader) {
14042
+ throw new TypeError("setProtectedHeader can only be called once");
14043
+ }
14044
+ this.#protectedHeader = protectedHeader;
14045
+ return this;
14046
+ }
14047
+ setKeyManagementParameters(parameters) {
14048
+ if (this.#keyManagementParameters) {
14049
+ throw new TypeError("setKeyManagementParameters can only be called once");
14050
+ }
14051
+ this.#keyManagementParameters = parameters;
14052
+ return this;
14053
+ }
14054
+ setContentEncryptionKey(cek) {
14055
+ if (this.#cek) {
14056
+ throw new TypeError("setContentEncryptionKey can only be called once");
14057
+ }
14058
+ this.#cek = cek;
14059
+ return this;
14060
+ }
14061
+ setInitializationVector(iv) {
14062
+ if (this.#iv) {
14063
+ throw new TypeError("setInitializationVector can only be called once");
14064
+ }
14065
+ this.#iv = iv;
14066
+ return this;
14067
+ }
14068
+ replicateIssuerAsHeader() {
14069
+ this.#replicateIssuerAsHeader = true;
14070
+ return this;
14071
+ }
14072
+ replicateSubjectAsHeader() {
14073
+ this.#replicateSubjectAsHeader = true;
14074
+ return this;
14075
+ }
14076
+ replicateAudienceAsHeader() {
14077
+ this.#replicateAudienceAsHeader = true;
14078
+ return this;
14079
+ }
14080
+ async encrypt(key, options) {
14081
+ const enc = new CompactEncrypt(this.#jwt.data());
14082
+ if (this.#protectedHeader && (this.#replicateIssuerAsHeader || this.#replicateSubjectAsHeader || this.#replicateAudienceAsHeader)) {
14083
+ this.#protectedHeader = {
14084
+ ...this.#protectedHeader,
14085
+ iss: this.#replicateIssuerAsHeader ? this.#jwt.iss : void 0,
14086
+ sub: this.#replicateSubjectAsHeader ? this.#jwt.sub : void 0,
14087
+ aud: this.#replicateAudienceAsHeader ? this.#jwt.aud : void 0
14088
+ };
14089
+ }
14090
+ enc.setProtectedHeader(this.#protectedHeader);
14091
+ if (this.#iv) {
14092
+ enc.setInitializationVector(this.#iv);
14093
+ }
14094
+ if (this.#cek) {
14095
+ enc.setContentEncryptionKey(this.#cek);
14096
+ }
14097
+ if (this.#keyManagementParameters) {
14098
+ enc.setKeyManagementParameters(this.#keyManagementParameters);
14099
+ }
14100
+ return enc.encrypt(key, options);
14101
+ }
14102
+ };
14103
+
14104
+ // node_modules/jose/dist/webapi/util/decode_protected_header.js
14105
+ function decodeProtectedHeader(token) {
14106
+ let protectedB64u;
14107
+ if (typeof token === "string") {
14108
+ const parts = token.split(".");
14109
+ if (parts.length === 3 || parts.length === 5) {
14110
+ ;
14111
+ [protectedB64u] = parts;
14112
+ }
14113
+ } else if (typeof token === "object" && token) {
14114
+ if ("protected" in token) {
14115
+ protectedB64u = token.protected;
14116
+ } else {
14117
+ throw new TypeError("Token does not contain a Protected Header");
14118
+ }
14119
+ }
14120
+ try {
14121
+ if (typeof protectedB64u !== "string" || !protectedB64u) {
14122
+ throw new Error();
14123
+ }
14124
+ const result = JSON.parse(decoder.decode(decode(protectedB64u)));
14125
+ if (!is_object_default(result)) {
14126
+ throw new Error();
14127
+ }
14128
+ return result;
14129
+ } catch {
14130
+ throw new TypeError("Invalid Token or Protected Header formatting");
14131
+ }
14132
+ }
14133
+
14134
+ // node_modules/jose/dist/webapi/util/decode_jwt.js
14135
+ function decodeJwt(jwt) {
14136
+ if (typeof jwt !== "string")
14137
+ throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
14138
+ const { 1: payload, length } = jwt.split(".");
14139
+ if (length === 5)
14140
+ throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
14141
+ if (length !== 3)
14142
+ throw new JWTInvalid("Invalid JWT");
14143
+ if (!payload)
14144
+ throw new JWTInvalid("JWTs must contain a payload");
14145
+ let decoded;
14146
+ try {
14147
+ decoded = decode(payload);
14148
+ } catch {
14149
+ throw new JWTInvalid("Failed to base64url decode the payload");
14150
+ }
14151
+ let result;
14152
+ try {
14153
+ result = JSON.parse(decoder.decode(decoded));
14154
+ } catch {
14155
+ throw new JWTInvalid("Failed to parse the decoded payload as JSON");
14156
+ }
14157
+ if (!is_object_default(result))
14158
+ throw new JWTInvalid("Invalid JWT Claims Set");
14159
+ return result;
14160
+ }
14161
+
14162
+ // src/common/jwt.ts
14163
+ async function encryptJWT(payload, secret, options) {
14164
+ const en = new EncryptJWT(payload).setProtectedHeader({
14165
+ alg: options?.alg ? options?.alg : "dir",
14166
+ enc: options?.enc ? options?.enc : "A128CBC-HS256"
14167
+ }).setIssuedAt(options?.iat).setIssuer(options?.iss ? options?.iss : "urn:example:issuer").setAudience(options?.aud ? options?.aud : "urn:example:audience").setExpirationTime(options?.exp ? options?.exp : "2h");
14168
+ return await en.encrypt(secret, options?.options);
14169
+ }
14170
+ async function decryptJWT(jwt, secret, options) {
14171
+ return await jwtDecrypt(jwt, secret, options);
14172
+ }
14173
+ async function verifyJWT(jwt, secret, options) {
14174
+ return await jwtVerify(jwt, secret, options);
14175
+ }
14176
+ async function signJWT(payload, secret, options) {
14177
+ const sign = new SignJWT(payload).setProtectedHeader({
14178
+ alg: options?.alg ? options?.alg : "HS256"
14179
+ }).setIssuedAt(options?.iat).setIssuer(options?.iss ? options?.iss : "urn:example:issuer").setAudience(options?.aud ? options?.aud : "urn:example:audience").setExpirationTime(options?.exp ? options?.exp : "2h");
14180
+ return sign.sign(secret, options?.options);
14181
+ }
14182
+ function decodeProtectedHeaderJWT(token) {
14183
+ return decodeProtectedHeader(token);
14184
+ }
14185
+ function decodeJWT(jwt) {
14186
+ return decodeJwt(jwt);
14187
+ }
14188
+
14189
+ // src/services/globals.ts
14190
+ var import_node_crypto3 = require("node:crypto");
14191
+ var globalJSX = Object.freeze({
14192
+ createElement: (...args) => {
14193
+ const ret = createElement(...args);
14194
+ ret.toString = () => jsx2HTML(ret);
14195
+ return ret;
14196
+ },
14197
+ Fragment,
14198
+ enableDebugLog
14199
+ });
14200
+ var globaljsx = Object.freeze({
14201
+ useContext,
14202
+ useRuntime,
14203
+ createContext,
14204
+ useState,
14205
+ useEffect,
14206
+ useQuery,
14207
+ useRef,
14208
+ useElement,
14209
+ useRefresh,
14210
+ Link,
14211
+ Router: Router2,
14212
+ usePathname,
14213
+ define: function define2() {
14214
+ }
14215
+ });
14216
+ var globalWindow = Object.freeze({
14217
+ addEventListener: function define3() {
14218
+ }
14219
+ });
14220
+ var globalServer = Object.freeze({
14221
+ middleware: Object.freeze({
14222
+ buffer: ReadBuffer,
14223
+ url: URLEncodedParser,
14224
+ json: JSONParser,
14225
+ text: TextParser,
14226
+ cors: CORS,
14227
+ session: SessionHandler
14228
+ }),
14229
+ encodeHTML: HTMLEncode,
14230
+ inflateMDtoHTML: inflateMD2HTML,
14231
+ createSecretKey: import_node_crypto3.createSecretKey,
14232
+ newParser() {
14233
+ return new Parser();
14234
+ },
14235
+ newClusterCache(name, logger) {
14236
+ return new ClusterCache(name, logger);
14237
+ },
14238
+ newLocalCache(name, logger) {
14239
+ return new LocalCache(name, logger);
14240
+ },
14241
+ getWorkerNumber() {
14242
+ return import_node_cluster2.default.isPrimary || process.env["CLUSTER_NODE_NUMBER"] === void 0 ? 0 : parseInt(process.env["CLUSTER_NODE_NUMBER"], 10);
14243
+ },
14244
+ getWorkerCount() {
14245
+ return import_node_cluster2.default.isPrimary || process.env["CLUSTER_NODE_NUMBER"] === void 0 || process.env["CLUSTER_COUNT"] === void 0 ? 1 : parseInt(process.env["CLUSTER_COUNT"], 10);
14246
+ },
14247
+ isPrimaryWorker() {
14248
+ return import_node_cluster2.default.isPrimary || process.env["CLUSTER_NODE_NUMBER"] === "0";
14249
+ },
14250
+ jwt: {
14251
+ decode(jwt) {
14252
+ return decodeJWT(jwt);
14253
+ },
14254
+ decodeProtectedHeader(token) {
14255
+ return decodeProtectedHeaderJWT(token);
14256
+ },
14257
+ decrypt(jwt, secret, options) {
14258
+ return decryptJWT(jwt, secret, options);
14259
+ },
14260
+ encrypt(payload, secret, options) {
14261
+ return encryptJWT(payload, secret, options);
14262
+ },
14263
+ sign(payload, secret, options) {
14264
+ return signJWT(payload, secret, options);
14265
+ },
14266
+ verify(jwt, secret, options) {
14267
+ return verifyJWT(jwt, secret, options);
14268
+ }
14269
+ }
14270
+ });
14271
+ function browserJSXGlobals(inFile, jsxPath = false, useExport = true) {
14272
+ const PRE = `import { enableDebugLog, useRuntime, Link, usePathname, createContext, useContext, useElement, useRefresh, useQuery, define, Router, useState, useEffect, useRef, createElement, Fragment } from "${jsxPath}";
14273
+ globalThis.JSX = Object.freeze({
14274
+ createElement,
14275
+ Fragment,
14276
+ enableDebugLog
14277
+ });
14278
+
14279
+ globalThis.newParser = () => new Parser();
14280
+ globalThis.jsx = Object.freeze({
14281
+ define,
14282
+ useRuntime,
14283
+ createContext,
14284
+ useContext,
14285
+ useState,
14286
+ useEffect,
14287
+ useQuery,
14288
+ useRef,
14289
+ useElement,
14290
+ useRefresh,
14291
+ usePathname,
14292
+ Link,
14293
+ Router
14294
+ });`;
14295
+ return `${jsxPath ? PRE : ""}
14296
+ ${useExport ? `export * from "${inFile}";import * as lib from "${inFile}";export default lib.default;` : `import * as lib from "${inFile}"`}`;
14297
+ }
14298
+ function initGlobals() {
14299
+ globalThis.server = globalServer;
14300
+ globalThis.JSX = globalJSX;
14301
+ globalThis.jsx = globaljsx;
14302
+ globalThis.window = globalWindow;
14303
+ }
14304
+ function assertGlobalTampered() {
14305
+ try {
14306
+ (0, import_node_assert.strictEqual)(globalThis.JSX, globalJSX, "globalThis.JSX tamperered");
14307
+ (0, import_node_assert.strictEqual)(globalThis.server, globalServer, "globalThis.server tamperered");
14308
+ (0, import_node_assert.strictEqual)(globalThis.jsx, globaljsx, "globalThis.jsx tamperered");
14309
+ (0, import_node_assert.strictEqual)(globalThis.window, globalWindow, "globalThis.window tamperered");
14310
+ } catch (e) {
14311
+ console.error(e);
14312
+ process.exit(EXIT_CODES.GLOBALS_ALTERED);
14313
+ }
14314
+ }
14315
+
14316
+ // src/common/jsx.ts
14317
+ var jsxJSBuffer = null;
14318
+ var jsxJSBufferChecksumPromise = null;
14319
+ async function initJSXJS(logger) {
14320
+ jsxJSBuffer = jsxJSBuffer ? jsxJSBuffer : Buffer.from(getAsset("jsx.dom.js"));
14321
+ jsxJSBufferChecksumPromise = jsxJSBufferChecksumPromise ? jsxJSBufferChecksumPromise : calculateChecksumFromBuffer(jsxJSBuffer);
14322
+ return initAsset(logger, getJSXJSPath(), jsxJSBuffer, true, jsxJSBufferChecksumPromise, false);
14323
+ }
14324
+ var parser2 = new Parser();
14325
+ var DEFAULT_ESOPTION = {
14326
+ platform: "neutral",
14327
+ bundle: true,
14328
+ jsxFactory: "JSX.createElement",
14329
+ jsxFragment: "JSX.Fragment"
14330
+ };
14331
+ async function inflateJSX(inFile, options) {
14332
+ const tmpBuildDir = (0, import_node_path5.resolve)(JSX_TMP_DIR, String(process.pid), "build", Date.now() + "-" + (0, import_node_crypto4.randomUUID)());
14333
+ const inFileTmp = (0, import_node_path5.resolve)(tmpBuildDir, (0, import_node_path5.basename)(inFile) + ".mjs");
14334
+ const jsxJSPath = getJSXJSPath();
14335
+ const logger = options.logger;
14336
+ try {
14337
+ if (!options.embemedJSX) {
14338
+ (0, import_node_fs6.mkdirSync)(tmpBuildDir, {
14339
+ recursive: true
14340
+ });
14341
+ (0, import_node_fs6.writeFileSync)(inFileTmp, browserJSXGlobals(inFile, false, options.useExport));
14342
+ logger?.trace("inflating [%s] from [%s]. to change the import folder set JSX_TMP", (0, import_node_path5.relative)((0, import_node_process3.cwd)(), inFile), (0, import_node_path5.dirname)((0, import_node_path5.relative)(JSX_TMP_DIR, inFileTmp)));
14343
+ const { outputFiles: [{ contents }] } = await esBuild({
14344
+ ...DEFAULT_ESOPTION,
14345
+ entryPoints: [inFileTmp],
14346
+ minify: options.minify
14347
+ });
14348
+ if (CLEAR_JSX_CACHE) {
14349
+ logger?.trace("clearing cache at [%s] to change this behaivor set CLEAR_JSX_CACHE to 0", tmpBuildDir);
14350
+ (0, import_node_fs6.unlinkSync)(inFileTmp);
14351
+ (0, import_node_fs6.rmdirSync)(tmpBuildDir);
14352
+ }
14353
+ return contents;
14354
+ } else {
14355
+ (0, import_node_fs6.mkdirSync)(tmpBuildDir, {
14356
+ recursive: true
14357
+ });
14358
+ (0, import_node_fs6.writeFileSync)(inFileTmp, browserJSXGlobals(inFile, jsxJSPath));
14359
+ logger?.trace("inflating [%s] from [%s] with jsx.js embedded. to change the import folder set JSX_TMP", (0, import_node_path5.relative)((0, import_node_process3.cwd)(), inFile), (0, import_node_path5.dirname)((0, import_node_path5.relative)(JSX_TMP_DIR, inFileTmp)));
14360
+ const { outputFiles: [{ contents }] } = await esBuild({
14361
+ ...DEFAULT_ESOPTION,
14362
+ entryPoints: [inFileTmp],
14363
+ minify: options.minify
14364
+ });
14365
+ if (CLEAR_JSX_CACHE) {
14366
+ logger?.trace("clearing cache at [%s] to change this behaivor set CLEAR_JSX_CACHE to 0", tmpBuildDir);
14367
+ (0, import_node_fs6.unlinkSync)(inFileTmp);
14368
+ (0, import_node_fs6.rmdirSync)(tmpBuildDir);
14369
+ }
14370
+ return contents;
14371
+ }
14372
+ } catch (e) {
14373
+ logger?.error("error with: " + inFile);
14374
+ logger?.error(e);
14375
+ if (options.embemedJSX) {
14376
+ if (CLEAR_JSX_CACHE) {
14377
+ logger?.trace("clearing cache at [%s] to change this behaivor set CLEAR_JSX_CACHE to 0", tmpBuildDir);
14378
+ (0, import_node_fs6.unlinkSync)(inFileTmp);
14379
+ (0, import_node_fs6.rmdirSync)(tmpBuildDir);
14380
+ } else {
14381
+ logger?.error("error with: %s", inFileTmp);
14382
+ logger?.trace("NOT clearing cache. to change this behaivor set CLEAR_JSX_CACHE to 1", tmpBuildDir);
14383
+ }
14384
+ }
14385
+ throw e;
14386
+ }
14387
+ }
14388
+ var APIOptionsSchema = {
14389
+ type: "object?",
14390
+ properties: {
14391
+ basePath: "string?",
14392
+ path: "string?|string[]?",
14393
+ method: "string?|string[]?",
14394
+ parser: {
14395
+ type: "object?",
14396
+ properties: {
14397
+ parse: "function"
14398
+ },
14399
+ mode: "add_extra"
14400
+ },
14401
+ middleware: "function[]!?",
14402
+ session: {
14403
+ type: "object?|function?",
14404
+ properties: SessionHandlerOptionsSchema.properties
14405
+ },
14406
+ ...RouteOptionsSchema.properties
14407
+ }
14408
+ //mode:"add_extra"
14409
+ };
14410
+ var HTMLModuleSchema = {
14411
+ type: "object",
14412
+ properties: {
14413
+ default: {
14414
+ type: "function|object"
14415
+ },
14416
+ apiOptions: APIOptionsSchema
14417
+ }
14418
+ //mode:"add_extra"
14419
+ };
14420
+ var JSONModuleSchema = {
14421
+ type: "object",
14422
+ properties: {
14423
+ default: {
14424
+ type: "function|object|string"
14425
+ },
14426
+ apiOptions: APIOptionsSchema
14427
+ }
14428
+ //mode:"add_extra"
14429
+ };
14430
+ var MigrationSchema = {
14431
+ type: "object",
14432
+ properties: {
14433
+ up: "function",
14434
+ down: "function"
14435
+ },
14436
+ mode: "add_extra"
14437
+ };
14438
+ var CORSOptionsSchema = {
14439
+ type: "object",
14440
+ properties: {
14441
+ origins: "string[]?|string?",
14442
+ validate: "function?",
14443
+ methods: "string?",
14444
+ preflightContinue: "boolean?"
14445
+ }
14446
+ //mode:"add_extra"
14447
+ };
14448
+ var WSConfigSchema = {
14449
+ type: "object",
14450
+ properties: {
14451
+ path: "string",
14452
+ disabled: "boolean?",
14453
+ maxConnections: "number?",
14454
+ validate: "function?",
14455
+ onConnection: "function?",
14456
+ onMessage: "function?",
14457
+ onDisconnect: "function?"
14458
+ }
14459
+ //mode:"add_extra"
14460
+ };
14461
+ var DBConfigSchema = {
14462
+ type: "object",
14463
+ properties: {
14464
+ url: "string?",
14465
+ disabled: "boolean?",
14466
+ storage: "string?",
14467
+ dialect: "string?",
14468
+ name: "string"
14469
+ }
14470
+ //mode:"add_extra"
14471
+ };
14472
+ var ServerConfigSchema = {
14473
+ type: "object",
14474
+ properties: {
14475
+ preload: "function?",
14476
+ unload: "function?",
14477
+ stop: "function?",
14478
+ start: "function?",
14479
+ load: "function?"
14480
+ }
14481
+ //mode:"add_extra"
14482
+ };
14483
+ var LogConfigSchema = {
14484
+ type: "object",
14485
+ properties: {
11852
14486
  level: {
11853
14487
  type: "enum?",
11854
14488
  enumValues: ["error", "warn", "info", "debug", "trace", "none"]
@@ -12029,7 +14663,7 @@ async function importJSXFile(inFile, logger) {
12029
14663
  useExport: true,
12030
14664
  logger
12031
14665
  });
12032
- const tmpBuildDir = (0, import_node_path5.resolve)(JSX_TMP_DIR, String(process.pid), "import", Date.now() + "-" + (0, import_node_crypto3.randomUUID)());
14666
+ const tmpBuildDir = (0, import_node_path5.resolve)(JSX_TMP_DIR, String(process.pid), "import", Date.now() + "-" + (0, import_node_crypto4.randomUUID)());
12033
14667
  const inFileTmp = (0, import_node_path5.resolve)(tmpBuildDir, (0, import_node_path5.basename)(inFile) + ".mjs");
12034
14668
  (0, import_node_fs6.mkdirSync)(tmpBuildDir, {
12035
14669
  recursive: true
@@ -12394,6 +15028,7 @@ function createStaticRoute(service, logger, router, dir, file, inflateDir, route
12394
15028
  path: normalizePath(path)
12395
15029
  }],
12396
15030
  service,
15031
+ filePath: file.filePath,
12397
15032
  previewMethod: "html"
12398
15033
  };
12399
15034
  if (inflateDir) {
@@ -12473,6 +15108,7 @@ async function createRouterFromDirectory(server2, hotreload, service, logger, di
12473
15108
  routeFileMap[file.filePath] = {
12474
15109
  routes,
12475
15110
  service,
15111
+ filePath: file.filePath,
12476
15112
  previewMethod: "api"
12477
15113
  };
12478
15114
  const inflatedCode = inflateDir ? await inflateJSX(file.filePath, {
@@ -12502,6 +15138,7 @@ async function createRouterFromDirectory(server2, hotreload, service, logger, di
12502
15138
  routeFileMap[file.filePath] = {
12503
15139
  routes,
12504
15140
  service,
15141
+ filePath: file.filePath,
12505
15142
  previewMethod: "html"
12506
15143
  };
12507
15144
  for (const r of routes) {
@@ -12552,6 +15189,7 @@ async function createRouterFromDirectory(server2, hotreload, service, logger, di
12552
15189
  const routes = getRoutes((0, import_node_path12.join)("/", (0, import_node_path12.dirname)((0, import_node_path12.relative)(dir, file.filePath))), file.subName + ".html", module2.apiOptions);
12553
15190
  routeFileMap[file.filePath] = {
12554
15191
  routes,
15192
+ filePath: file.filePath,
12555
15193
  service,
12556
15194
  previewMethod: "html"
12557
15195
  };
@@ -12617,6 +15255,7 @@ async function createRouterFromDirectory(server2, hotreload, service, logger, di
12617
15255
  method: "GET",
12618
15256
  path
12619
15257
  }],
15258
+ filePath: file.filePath,
12620
15259
  service,
12621
15260
  previewMethod: "html"
12622
15261
  };
@@ -12666,6 +15305,7 @@ async function createRouterFromDirectory(server2, hotreload, service, logger, di
12666
15305
  path
12667
15306
  }],
12668
15307
  service,
15308
+ filePath: file.filePath,
12669
15309
  previewMethod: "html"
12670
15310
  };
12671
15311
  if (inflateDir) {
@@ -12723,6 +15363,7 @@ async function createRouterFromDirectory(server2, hotreload, service, logger, di
12723
15363
  method: "GET",
12724
15364
  path
12725
15365
  }],
15366
+ filePath: file.filePath,
12726
15367
  service,
12727
15368
  previewMethod: "html"
12728
15369
  };
@@ -12774,6 +15415,7 @@ async function createRouterFromDirectory(server2, hotreload, service, logger, di
12774
15415
  path
12775
15416
  }],
12776
15417
  service,
15418
+ filePath: file.filePath,
12777
15419
  previewMethod: "html"
12778
15420
  };
12779
15421
  if (inflateDir) {
@@ -12950,22 +15592,22 @@ async function inflateAppForSea(logger, inflateDir, services) {
12950
15592
  writeFile(
12951
15593
  logger,
12952
15594
  (0, import_node_path14.join)(inflateDir, "sea", "app.cjs"),
12953
- `const { ServerInterfaceImpl, ServerRequestHandler, WebSocketManager, initGlobals, DBManager, App, LoggerHandler, LogProvider, LocalCache, ClusterCache } = require("./lib.cjs");
15595
+ `const { createServerInterface, ServerRequestHandler, WebSocketManager, initGlobals, DBManager, App, LoggerHandler, LogProvider, LocalCache, ClusterCache } = require("./lib.cjs");
12954
15596
 
12955
15597
  async function main() {
12956
15598
  const PORT = process.env["PORT"] ? process.env["PORT"] : 8080;
12957
- const logProvider = new LogProvider();
15599
+ const loggerProvider = new LogProvider();
12958
15600
  const localCache = new LocalCache();
12959
15601
  const cache = new ClusterCache();
12960
15602
  const webSocketManager = new WebSocketManager();
12961
15603
  const dbManager = new DBManager();
12962
15604
  await initGlobals();
12963
- const serverInterface = new ServerInterfaceImpl({
15605
+ const serverInterface = createServerInterface({
12964
15606
  cache,
12965
15607
  localCache,
12966
- logProvider,
15608
+ loggerProvider,
12967
15609
  wsManager: webSocketManager,
12968
- logger: logProvider.getLogger("server"),
15610
+ logger: loggerProvider.getLogger("server"),
12969
15611
  dbManager,
12970
15612
  port: PORT
12971
15613
  });
@@ -13019,9 +15661,10 @@ ${getMiddlewareConfigPath(servicePath) ? `
13019
15661
  }
13020
15662
  }` : ""}
13021
15663
  ${Object.keys(serviceRouteFileMap).map((filePath) => serviceRouteFileMap[filePath]).filter((data) => data.previewMethod === "api").map((data) => data.routes.map((r) => {
13022
- const rPath = r.inflatePath;
15664
+ const rPath = (0, import_node_path14.join)((0, import_node_path14.relative)((0, import_node_process10.cwd)(), (0, import_node_path14.dirname)(data.filePath)), (0, import_node_path14.basename)(data.filePath));
13023
15665
  if (rPath) {
13024
- const apiInflatedPath = (0, import_node_path14.join)("..", "..", service, "http", rPath + ".api.js");
15666
+ const rPathExt = (0, import_node_path14.extname)(rPath);
15667
+ const apiInflatedPath = (0, import_node_path14.join)("..", "..", rPath.substring(0, rPath.length - rPathExt.length) + ".js");
13025
15668
  return ` await appendAPIModule(router, "../../${service}/http", "./${apiInflatedPath}", (await import("./${apiInflatedPath}")).default);`;
13026
15669
  } else {
13027
15670
  return "";
@@ -13526,15 +16169,15 @@ var ws_default = {
13526
16169
  path: LOG_SOCKET_PATH,
13527
16170
  validate(req) {
13528
16171
  const admin = req.editor;
13529
- const cache = admin ? admin.getCache() : req.server.cache;
13530
- const KEY = cache.get("AUTH_KEY");
16172
+ const cache2 = admin ? admin.getCache() : req.server.cache;
16173
+ const KEY = cache2.get("AUTH_KEY");
13531
16174
  const cookieToken = req.cookies["auth"];
13532
16175
  return cookieToken === KEY ? true : false;
13533
16176
  }
13534
16177
  };
13535
16178
 
13536
16179
  // editor/server.ts
13537
- var import_node_crypto4 = require("node:crypto");
16180
+ var import_node_crypto5 = require("node:crypto");
13538
16181
  init_constants();
13539
16182
  var import_node_fs17 = require("node:fs");
13540
16183
  var import_node_path18 = require("node:path");
@@ -13585,28 +16228,28 @@ var ADMIN_EDITOR_BROWSER_OPEN_KEY = "ADMIN_EDITOR_BROWSER_OPEN_KEY$$";
13585
16228
  var server_default = {
13586
16229
  preload: (serverInterface, adminInterface) => {
13587
16230
  if (serverInterface?.isPrimaryWorker()) {
13588
- const cache = adminInterface ? adminInterface.getCache() : serverInterface.cache;
13589
- if (!cache.has(ADMIN_EDITOR_AUTH_KEY)) {
16231
+ const cache2 = adminInterface ? adminInterface.getCache() : serverInterface.cache;
16232
+ if (!cache2.has(ADMIN_EDITOR_AUTH_KEY)) {
13590
16233
  const adminKEYPath = (0, import_node_path18.resolve)(".admin_key");
13591
16234
  if ((0, import_node_fs17.existsSync)(adminKEYPath)) {
13592
16235
  serverInterface.logger.warn("loading static ADMIN_KEY from [%s]", (0, import_node_path18.relative)(process.cwd(), adminKEYPath));
13593
- cache.set(ADMIN_EDITOR_AUTH_KEY, (0, import_node_fs17.readFileSync)(adminKEYPath).toString().trim());
16236
+ cache2.set(ADMIN_EDITOR_AUTH_KEY, (0, import_node_fs17.readFileSync)(adminKEYPath).toString().trim());
13594
16237
  } else {
13595
- cache.set(ADMIN_EDITOR_AUTH_KEY, (0, import_node_crypto4.randomUUID)());
16238
+ cache2.set(ADMIN_EDITOR_AUTH_KEY, (0, import_node_crypto5.randomUUID)());
13596
16239
  }
13597
16240
  }
13598
16241
  }
13599
16242
  },
13600
16243
  start: (serverInterface, adminInterface) => {
13601
- const cache = adminInterface ? adminInterface.getCache() : serverInterface.cache;
13602
- if (!cache.has(ADMIN_EDITOR_BROWSER_OPEN_KEY)) {
13603
- const KEY = cache.get(ADMIN_EDITOR_AUTH_KEY);
16244
+ const cache2 = adminInterface ? adminInterface.getCache() : serverInterface.cache;
16245
+ if (!cache2.has(ADMIN_EDITOR_BROWSER_OPEN_KEY)) {
16246
+ const KEY = cache2.get(ADMIN_EDITOR_AUTH_KEY);
13604
16247
  const adminPath = `${BASEEDITOR_PATH}?${ADMIN_EDITOR_AUTH_QUERY}=${KEY}`;
13605
16248
  if (serverInterface?.isPrimaryWorker()) {
13606
16249
  serverInterface.logger.log("\n\n ADMIN_EDITOR\n\n %s\n\n", adminPath);
13607
16250
  }
13608
16251
  if (serverInterface.isPrimaryWorker()) {
13609
- cache.set(ADMIN_EDITOR_BROWSER_OPEN_KEY, true);
16252
+ cache2.set(ADMIN_EDITOR_BROWSER_OPEN_KEY, true);
13610
16253
  try {
13611
16254
  serverInterface.openBrowser(`${BASEEDITOR_PATH}?${ADMIN_EDITOR_AUTH_QUERY}=${KEY}`);
13612
16255
  } catch (e) {
@@ -13917,47 +16560,30 @@ async function inflateDBMigrations(logger, service, dbName, inflateDir, errors)
13917
16560
  }
13918
16561
 
13919
16562
  // src/services/utils/server-interface.ts
13920
- var import_node_cluster2 = __toESM(require("node:cluster"), 1);
13921
16563
  var import_node_child_process2 = require("node:child_process");
13922
- var ServerInterfaceImpl = class {
13923
- cache;
13924
- localCache;
13925
- logger;
13926
- port;
13927
- db;
13928
- ws;
13929
- loggerProvider;
13930
- openBrowser;
13931
- constructor(options) {
13932
- this.cache = options.cache;
13933
- this.localCache = options.localCache;
13934
- this.logger = options.logger ? options.logger : options.loggerProvider ? options.loggerProvider.getLogger("server") : void 0;
13935
- this.port = options.port;
13936
- const dbManager = options.dbManager;
13937
- const wsManager = options.wsManager;
13938
- this.loggerProvider = options.loggerProvider;
13939
- const app = options.app;
13940
- this.openBrowser = (path) => {
13941
- const PORT2 = this.port;
13942
- const URL2 = `http://localhost${PORT2 ? `:${PORT2}` : ""}${path}`;
13943
- const DEFAULT_OPEN = process.platform === "win32" ? "explorer" : process.platform === "darwin" ? "open" : "xdg-open";
13944
- const OPEN = app.options.browser !== void 0 && String(app.options.browser).toUpperCase() !== "TRUE" && String(app.options.browser).toUpperCase() !== "1" ? String(app.options.browser).toUpperCase() !== "0" && String(app.options.browser).toUpperCase() !== "FALSE" && String(app.options.browser).toUpperCase() !== "NONE" && app.options.browser ? app.options.browser : false : process.env["BROWSER"] ? process.env["BROWSER"] === "none" ? false : process.env["BROWSER"] : DEFAULT_OPEN;
13945
- if (OPEN) {
13946
- const openCMD = `${OPEN} "${URL2}"`;
13947
- this.logger?.info("opening browser with [%s]", openCMD);
13948
- (0, import_node_child_process2.execSync)(openCMD);
13949
- } else {
13950
- this.logger?.warn("ignoring browser [%s]", OPEN);
13951
- }
13952
- };
13953
- this.db = Object.freeze({
13954
- get: (name) => {
13955
- return dbManager.getDB(name);
16564
+ function createServerInterface(options) {
16565
+ initGlobals();
16566
+ return Object.freeze({
16567
+ cache: options.cache,
16568
+ localCache: options.localCache,
16569
+ logger: options.logger,
16570
+ reload() {
16571
+ return options?.app?.reload();
16572
+ },
16573
+ restart() {
16574
+ return options?.app?.restart();
16575
+ },
16576
+ stop() {
16577
+ return options?.app?.stop();
16578
+ },
16579
+ db: {
16580
+ get(name) {
16581
+ return options.dbManager.getDB(name);
13956
16582
  },
13957
- getMigrations: () => {
13958
- if (app?.inflated) {
16583
+ getMigrations() {
16584
+ if (options.app?.inflated) {
13959
16585
  const ret = [];
13960
- for (const d of app?.inflated.dbList) {
16586
+ for (const d of options.app?.inflated.dbList) {
13961
16587
  ret.push(...d.migrations.map((m) => {
13962
16588
  return {
13963
16589
  name: m.name,
@@ -13970,32 +16596,37 @@ var ServerInterfaceImpl = class {
13970
16596
  }
13971
16597
  return [];
13972
16598
  },
13973
- migrate: (options2) => {
13974
- return app?.migrate(options2);
16599
+ migrate(migrateOptions) {
16600
+ return options?.app?.migrate(migrateOptions);
13975
16601
  }
13976
- });
13977
- this.ws = Object.freeze({
16602
+ },
16603
+ ws: {
13978
16604
  get: (name) => {
13979
- return wsManager?.getWS(name);
16605
+ return options?.webSocketManager?.getWS(name);
13980
16606
  },
13981
16607
  disconnectAll: (path) => {
13982
- return wsManager?.disconnectAllButLOGSocket();
16608
+ return options?.webSocketManager?.disconnectAllButLOGSocket();
13983
16609
  }
13984
- });
13985
- }
13986
- getWorkerNumber() {
13987
- return import_node_cluster2.default.isPrimary || process.env["CLUSTER_NODE_NUMBER"] === void 0 ? 0 : parseInt(process.env["CLUSTER_NODE_NUMBER"], 10);
13988
- }
13989
- getWorkerCount() {
13990
- return import_node_cluster2.default.isPrimary || process.env["CLUSTER_NODE_NUMBER"] === void 0 || process.env["CLUSTER_COUNT"] === void 0 ? 1 : parseInt(process.env["CLUSTER_COUNT"], 10);
13991
- }
13992
- isPrimaryWorker() {
13993
- return import_node_cluster2.default.isPrimary || process.env["CLUSTER_NODE_NUMBER"] === "0";
13994
- }
13995
- getLogger(identifier, options) {
13996
- return this.loggerProvider?.getLogger(identifier, options);
13997
- }
13998
- };
16610
+ },
16611
+ openBrowser(path) {
16612
+ const PORT2 = options.port;
16613
+ const URL2 = `http://localhost${PORT2 ? `:${PORT2}` : ""}${path}`;
16614
+ const DEFAULT_OPEN = process.platform === "win32" ? "explorer" : process.platform === "darwin" ? "open" : "xdg-open";
16615
+ const OPEN = options?.app?.options.browser !== void 0 && String(options?.app?.options.browser).toUpperCase() !== "TRUE" && String(options?.app?.options.browser).toUpperCase() !== "1" ? String(options?.app.options.browser).toUpperCase() !== "0" && String(options?.app?.options.browser).toUpperCase() !== "FALSE" && String(options?.app?.options.browser).toUpperCase() !== "NONE" && options?.app?.options.browser ? options?.app.options.browser : false : process.env["BROWSER"] ? process.env["BROWSER"] === "none" ? false : process.env["BROWSER"] : DEFAULT_OPEN;
16616
+ if (OPEN) {
16617
+ const openCMD = `${OPEN} "${URL2}"`;
16618
+ options?.logger?.info("opening browser with [%s]", openCMD);
16619
+ (0, import_node_child_process2.execSync)(openCMD);
16620
+ } else {
16621
+ options?.logger?.warn("ignoring browser [%s]", OPEN);
16622
+ }
16623
+ },
16624
+ getLogger(identifier, loggerOptions) {
16625
+ return options?.loggerProvider?.getLogger(identifier, loggerOptions);
16626
+ },
16627
+ ...server
16628
+ });
16629
+ }
13999
16630
 
14000
16631
  // src/common/arguments.ts
14001
16632
  var import_node_fs26 = require("node:fs");
@@ -14026,7 +16657,10 @@ var MiqroJSONSchema = {
14026
16657
  inflateDir: "string?",
14027
16658
  browser: "boolean?|string?",
14028
16659
  logFile: "boolean?|string?",
14029
- editor: "boolean?"
16660
+ editor: "boolean?",
16661
+ https: "boolean?",
16662
+ serverOptions: "any?",
16663
+ httpsRedirect: "number?"
14030
16664
  }
14031
16665
  };
14032
16666
  function importMiqroJSON(inFile) {
@@ -14154,6 +16788,7 @@ var Miqro = class _Miqro {
14154
16788
  status = "stopped";
14155
16789
  options;
14156
16790
  server = null;
16791
+ httpsRedirectServer = null;
14157
16792
  cache;
14158
16793
  localCache;
14159
16794
  webSocketManager;
@@ -14202,6 +16837,7 @@ var Miqro = class _Miqro {
14202
16837
  this.localCache = new LocalCache(`MiqroApplicationLocalCache[${this.options.name}]`, this.logger);
14203
16838
  this.webSocketManager = new WebSocketManager({
14204
16839
  logger: this.logger,
16840
+ loggerProvider: this.loggerProvider,
14205
16841
  name: `MiqroApplicationWebsocketManager[${this.options.name}]`,
14206
16842
  avoidLogSocket: this.options.editor
14207
16843
  });
@@ -14210,11 +16846,11 @@ var Miqro = class _Miqro {
14210
16846
  loggerProvider: this.loggerProvider,
14211
16847
  logger: this.logger
14212
16848
  });
14213
- this.serverInterface = new ServerInterfaceImpl({
16849
+ this.serverInterface = createServerInterface({
14214
16850
  cache: this.cache,
14215
- localCache: this.localCache,
14216
16851
  dbManager: this.dbManager,
14217
- wsManager: this.webSocketManager,
16852
+ localCache: this.localCache,
16853
+ webSocketManager: this.webSocketManager,
14218
16854
  app: this,
14219
16855
  logger: this.logger,
14220
16856
  loggerProvider: this.loggerProvider,
@@ -14434,6 +17070,7 @@ var Miqro = class _Miqro {
14434
17070
  this.logger?.debug(" ==start==");
14435
17071
  this.status = "starting";
14436
17072
  this.server = void 0;
17073
+ this.httpsRedirectServer = void 0;
14437
17074
  this.connect();
14438
17075
  await this.dbManager.connectAll();
14439
17076
  this.server = new App({
@@ -14441,8 +17078,17 @@ var Miqro = class _Miqro {
14441
17078
  req.server = this.serverInterface;
14442
17079
  return this.webSocketManager.onUpgrade(req, socket, head);
14443
17080
  },
14444
- loggerFactory: this.loggerProvider.requestLoggerFactory
17081
+ loggerFactory: this.loggerProvider.requestLoggerFactory,
17082
+ serverOptions: this.options?.serverOptions,
17083
+ https: this.options?.https
14445
17084
  });
17085
+ if (this.options?.httpRedirect) {
17086
+ this.httpsRedirectServer = new App();
17087
+ this.httpsRedirectServer.use(async (req, res) => {
17088
+ const hostname = req.headers.host.split(":").length > 1 ? req.headers.host.split(":")[0] : req.headers.host;
17089
+ return await res.redirect("https://" + hostname + ":" + this.options.port + req.url);
17090
+ });
17091
+ }
14446
17092
  this.webSocketManager.replaceALLWS(this.inflated.wsConfigList);
14447
17093
  reloadInflatedRouter(this);
14448
17094
  await notifiyServerConfig(this.logger, this.serverInterface, this.adminInterface, this.inflated.serverConfigMap, "load");
@@ -14459,10 +17105,18 @@ var Miqro = class _Miqro {
14459
17105
  }
14460
17106
  this.logger?.trace("calling listen on [%s]", this.options.port);
14461
17107
  await this.server.listen(this.options.port);
17108
+ if (this.options?.httpRedirect) {
17109
+ await this.httpsRedirectServer.listen(this.options.httpRedirect);
17110
+ }
17111
+ if (this.options?.httpRedirect && this.logger && (import_node_cluster3.default.isPrimary || process.env["CLUSTER_NODE_NUMBER"] === "0")) {
17112
+ this.logger?.log(" ==listening on [http][%s] for [https][%s] redirection==", this.options?.httpRedirect, this.options.port);
17113
+ } else if (this.options?.httpRedirect) {
17114
+ this.logger?.debug(" ==listening on [http][%s] for [https][%s] redirection==", this.options?.httpRedirect, this.options.port);
17115
+ }
14462
17116
  if (this.logger && (import_node_cluster3.default.isPrimary || process.env["CLUSTER_NODE_NUMBER"] === "0")) {
14463
- this.logger?.log(" ==listening on [%s]==", this.options.port);
17117
+ this.logger?.log(" ==listening on [%s][%s]==", this.options.https ? "https" : "http", this.options.port);
14464
17118
  } else {
14465
- this.logger?.debug(" ==listening on [%s]==", this.options.port);
17119
+ this.logger?.debug(" ==listening on [%s][%s]==", this.options.https ? "https" : "http", this.options.port);
14466
17120
  }
14467
17121
  await notifiyServerConfig(this.logger, this.serverInterface, this.adminInterface, this.inflated.serverConfigMap, "start");
14468
17122
  if (this.options.hotreload && (import_node_cluster3.default.isPrimary || process.env["CLUSTER_NODE_NUMBER"] === "0")) {
@@ -14482,7 +17136,9 @@ var Miqro = class _Miqro {
14482
17136
  this.watcher = null;
14483
17137
  }
14484
17138
  const server2 = this.server;
17139
+ const httpsRedirectServer = this.httpsRedirectServer;
14485
17140
  this.server = null;
17141
+ this.httpsRedirectServer = null;
14486
17142
  this.disconnect();
14487
17143
  this.logger?.debug(" ==stop==");
14488
17144
  this.logger?.debug("clear running server routes");
@@ -14492,6 +17148,9 @@ var Miqro = class _Miqro {
14492
17148
  const pD = this.dbManager.deleteAll();
14493
17149
  notifiyServerConfigSync(this, "unload");
14494
17150
  this.logger?.debug("stopping");
17151
+ if (httpsRedirectServer) {
17152
+ await httpsRedirectServer.close();
17153
+ }
14495
17154
  const p = server2.close();
14496
17155
  await p;
14497
17156
  await pD;
@@ -14652,11 +17311,11 @@ async function appendAPIModule(router, dir, filePath, module2) {
14652
17311
  LoggerHandler,
14653
17312
  Miqro,
14654
17313
  Router,
14655
- ServerInterfaceImpl,
14656
17314
  ServerRequestHandler,
14657
17315
  WebSocketManager,
14658
17316
  appendAPIModule,
14659
17317
  assertGlobalTampered,
17318
+ createServerInterface,
14660
17319
  initGlobals,
14661
17320
  migration
14662
17321
  });