@crossauth/backend 1.1.2 → 1.1.3

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.
package/dist/index.js CHANGED
@@ -1,25 +1,25 @@
1
- var Oe = Object.defineProperty;
2
- var Ke = (S, a, e) => a in S ? Oe(S, a, { enumerable: !0, configurable: !0, writable: !0, value: e }) : S[a] = e;
3
- var u = (S, a, e) => Ke(S, typeof a != "symbol" ? a + "" : a, e);
4
- import { CrossauthError as o, ErrorCode as l, CrossauthLogger as h, j as m, UserState as k, OAuthFlows as U, KeyPrefix as b, OAuthTokenConsumerBase as Fe, OAuthClientBase as Ne } from "@crossauth/common";
5
- import * as De from "node:path";
6
- import { fileURLToPath as xe } from "node:url";
7
- import * as G from "@prisma/client/runtime/client";
8
- import { PrismaBetterSqlite3 as de } from "@prisma/adapter-better-sqlite3";
9
- import Se from "@mbakereth/ldapjs";
10
- import { timingSafeEqual as me, randomBytes as fe, randomUUID as Re, createHash as Be, pbkdf2 as ze, createHmac as se, createCipheriv as Le, createDecipheriv as je, randomInt as re } from "node:crypto";
11
- import { promisify as He } from "node:util";
12
- import W from "nunjucks";
13
- import Ae from "nodemailer";
14
- import Ve from "twilio";
15
- import Me from "qrcode";
16
- import { authenticator as ge } from "otplib";
17
- import te from "jsonwebtoken";
18
- import ie from "node:fs";
19
- import { createPublicKey as $e } from "crypto";
20
- import * as qe from "jose";
1
+ var ze = Object.defineProperty;
2
+ var Le = (S, a, e) => a in S ? ze(S, a, { enumerable: !0, configurable: !0, writable: !0, value: e }) : S[a] = e;
3
+ var u = (S, a, e) => Le(S, typeof a != "symbol" ? a + "" : a, e);
4
+ import { CrossauthError as o, ErrorCode as l, CrossauthLogger as h, j as m, UserState as E, OAuthFlows as I, KeyPrefix as U, OAuthTokenConsumerBase as je, OAuthClientBase as He } from "@crossauth/common";
5
+ import * as Ve from "node:path";
6
+ import { fileURLToPath as Me } from "node:url";
7
+ import * as re from "@prisma/client/runtime/client";
8
+ import { PrismaBetterSqlite3 as ye } from "@prisma/adapter-better-sqlite3";
9
+ import Ue from "@mbakereth/ldapjs";
10
+ import { timingSafeEqual as Se, randomBytes as Te, randomUUID as $e, createHash as qe, pbkdf2 as We, createHmac as he, createCipheriv as Je, createDecipheriv as Ye, randomInt as ce } from "node:crypto";
11
+ import { promisify as Ge } from "node:util";
12
+ import Z from "nunjucks";
13
+ import xe from "nodemailer";
14
+ import Ze from "twilio";
15
+ import Xe from "qrcode";
16
+ import { authenticator as _e } from "otplib";
17
+ import ae from "jsonwebtoken";
18
+ import ue from "node:fs";
19
+ import { createPublicKey as Qe } from "crypto";
20
+ import * as et from "jose";
21
21
  var g = /* @__PURE__ */ ((S) => (S[S.String = 0] = "String", S[S.Number = 1] = "Number", S[S.Boolean = 2] = "Boolean", S[S.Json = 3] = "Json", S[S.JsonArray = 4] = "JsonArray", S))(g || {});
22
- function We(S, a) {
22
+ function tt(S, a) {
23
23
  let e = S.split("."), t = a;
24
24
  for (let r in e) {
25
25
  const i = e[r];
@@ -28,7 +28,7 @@ function We(S, a) {
28
28
  }
29
29
  return t;
30
30
  }
31
- function Te(S, a) {
31
+ function Ae(S, a) {
32
32
  let e = S.split("."), t = a;
33
33
  for (let r in e) {
34
34
  const i = e[r];
@@ -37,11 +37,11 @@ function Te(S, a) {
37
37
  }
38
38
  return !0;
39
39
  }
40
- function Je(S, a, e) {
41
- const t = We(a, e);
40
+ function rt(S, a, e) {
41
+ const t = tt(a, e);
42
42
  S[a.replace(".", "_")] = t;
43
43
  }
44
- function Ye(S, a, e, t) {
44
+ function it(S, a, e, t) {
45
45
  var i;
46
46
  const r = a.replace(".", "_");
47
47
  switch (e) {
@@ -64,11 +64,11 @@ function Ye(S, a, e, t) {
64
64
  }
65
65
  function w(S, a, e, t, r, i = !1) {
66
66
  const s = "CROSSAUTH_" + r;
67
- if (i && !Te(S, t) && !(s && s in process.env))
67
+ if (i && !Ae(S, t) && !(s && s in process.env))
68
68
  throw new o(l.Configuration, S + " is required");
69
- Te(S, t) ? Je(e, S, t) : r && s in process.env && process.env[s] != null && Ye(e, S, a, s);
69
+ Ae(S, t) ? rt(e, S, t) : r && s in process.env && process.env[s] != null && it(e, S, a, s);
70
70
  }
71
- class L {
71
+ class q {
72
72
  /**
73
73
  * Constructor
74
74
  * @param options See {@link UserStorageOptions}
@@ -101,7 +101,7 @@ class L {
101
101
  return a.normalize("NFD").replace(new RegExp("\\p{Diacritic}", "gu"), "").toLowerCase();
102
102
  }
103
103
  }
104
- class z {
104
+ class V {
105
105
  /**
106
106
  * Returns an object decoded from the data field as a JSON string
107
107
  * @param data the JSON string to decode
@@ -153,7 +153,7 @@ class z {
153
153
  return e in a ? (delete a[e], !0) : !1;
154
154
  }
155
155
  }
156
- class ye {
156
+ class ve {
157
157
  /**
158
158
  * Constructor
159
159
  * @param _options see {@link OAuthClientStorageOptions}
@@ -161,7 +161,7 @@ class ye {
161
161
  constructor(a = {}) {
162
162
  }
163
163
  }
164
- class pe {
164
+ class Ee {
165
165
  /**
166
166
  * Constructor
167
167
  * @param _options see {@link OAuthAuthorizationStorageOptions}
@@ -169,7 +169,7 @@ class pe {
169
169
  constructor(a = {}) {
170
170
  }
171
171
  }
172
- const Ce = {
172
+ const be = {
173
173
  previewFeatures: [],
174
174
  clientVersion: "7.2.0",
175
175
  engineVersion: "0c8ef2ce45c83248ab3df073180d5eda9e8be7a3",
@@ -306,31 +306,31 @@ model OAuthAuthorization {
306
306
  types: {}
307
307
  }
308
308
  };
309
- Ce.runtimeDataModel = JSON.parse('{"models":{"User":{"fields":[{"name":"id","kind":"scalar","type":"Int"},{"name":"username","kind":"scalar","type":"String"},{"name":"username_normalized","kind":"scalar","type":"String"},{"name":"email","kind":"scalar","type":"String"},{"name":"email_normalized","kind":"scalar","type":"String"},{"name":"phone","kind":"scalar","type":"String"},{"name":"state","kind":"scalar","type":"String"},{"name":"factor1","kind":"scalar","type":"String"},{"name":"factor2","kind":"scalar","type":"String"},{"name":"dummyfield","kind":"scalar","type":"String"},{"name":"session","kind":"object","type":"Key","relationName":"KeyToUser"},{"name":"apiKey","kind":"object","type":"ApiKey","relationName":"ApiKeyToUser"},{"name":"secrets","kind":"object","type":"UserSecrets","relationName":"UserToUserSecrets"},{"name":"authorization","kind":"object","type":"OAuthAuthorization","relationName":"OAuthAuthorizationToUser"},{"name":"oauthClients","kind":"object","type":"OAuthClient","relationName":"OAuthClientToUser"}],"dbName":null},"UserSecrets":{"fields":[{"name":"userid","kind":"scalar","type":"Int"},{"name":"password","kind":"scalar","type":"String"},{"name":"totpsecret","kind":"scalar","type":"String"},{"name":"user","kind":"object","type":"User","relationName":"UserToUserSecrets"}],"dbName":null},"Key":{"fields":[{"name":"id","kind":"scalar","type":"Int"},{"name":"value","kind":"scalar","type":"String"},{"name":"userid","kind":"scalar","type":"Int"},{"name":"created","kind":"scalar","type":"DateTime"},{"name":"expires","kind":"scalar","type":"DateTime"},{"name":"lastactive","kind":"scalar","type":"DateTime"},{"name":"data","kind":"scalar","type":"String"},{"name":"user","kind":"object","type":"User","relationName":"KeyToUser"}],"dbName":null},"ApiKey":{"fields":[{"name":"id","kind":"scalar","type":"Int"},{"name":"name","kind":"scalar","type":"String"},{"name":"value","kind":"scalar","type":"String"},{"name":"userid","kind":"scalar","type":"Int"},{"name":"created","kind":"scalar","type":"DateTime"},{"name":"expires","kind":"scalar","type":"DateTime"},{"name":"data","kind":"scalar","type":"String"},{"name":"user","kind":"object","type":"User","relationName":"ApiKeyToUser"}],"dbName":null},"OAuthClient":{"fields":[{"name":"client_id","kind":"scalar","type":"String"},{"name":"confidential","kind":"scalar","type":"Boolean"},{"name":"client_name","kind":"scalar","type":"String"},{"name":"client_secret","kind":"scalar","type":"String"},{"name":"userid","kind":"scalar","type":"Int"},{"name":"redirect_uri","kind":"object","type":"OAuthClientRedirectUri","relationName":"OAuthClientToOAuthClientRedirectUri"},{"name":"authorization","kind":"object","type":"OAuthAuthorization","relationName":"OAuthAuthorizationToOAuthClient"},{"name":"valid_flow","kind":"object","type":"OAuthClientValidFlow","relationName":"OAuthClientToOAuthClientValidFlow"},{"name":"user","kind":"object","type":"User","relationName":"OAuthClientToUser"}],"dbName":null},"OAuthClientRedirectUri":{"fields":[{"name":"id","kind":"scalar","type":"Int"},{"name":"client_id","kind":"scalar","type":"String"},{"name":"uri","kind":"scalar","type":"String"},{"name":"client","kind":"object","type":"OAuthClient","relationName":"OAuthClientToOAuthClientRedirectUri"}],"dbName":null},"OAuthClientValidFlow":{"fields":[{"name":"id","kind":"scalar","type":"Int"},{"name":"client_id","kind":"scalar","type":"String"},{"name":"flow","kind":"scalar","type":"String"},{"name":"client","kind":"object","type":"OAuthClient","relationName":"OAuthClientToOAuthClientValidFlow"}],"dbName":null},"OAuthAuthorization":{"fields":[{"name":"id","kind":"scalar","type":"Int"},{"name":"client_id","kind":"scalar","type":"String"},{"name":"userid","kind":"scalar","type":"Int"},{"name":"user","kind":"object","type":"User","relationName":"OAuthAuthorizationToUser"},{"name":"scope","kind":"scalar","type":"String"},{"name":"Client","kind":"object","type":"OAuthClient","relationName":"OAuthAuthorizationToOAuthClient"}],"dbName":null}},"enums":{},"types":{}}');
310
- async function Ge(S) {
309
+ be.runtimeDataModel = JSON.parse('{"models":{"User":{"fields":[{"name":"id","kind":"scalar","type":"Int"},{"name":"username","kind":"scalar","type":"String"},{"name":"username_normalized","kind":"scalar","type":"String"},{"name":"email","kind":"scalar","type":"String"},{"name":"email_normalized","kind":"scalar","type":"String"},{"name":"phone","kind":"scalar","type":"String"},{"name":"state","kind":"scalar","type":"String"},{"name":"factor1","kind":"scalar","type":"String"},{"name":"factor2","kind":"scalar","type":"String"},{"name":"dummyfield","kind":"scalar","type":"String"},{"name":"session","kind":"object","type":"Key","relationName":"KeyToUser"},{"name":"apiKey","kind":"object","type":"ApiKey","relationName":"ApiKeyToUser"},{"name":"secrets","kind":"object","type":"UserSecrets","relationName":"UserToUserSecrets"},{"name":"authorization","kind":"object","type":"OAuthAuthorization","relationName":"OAuthAuthorizationToUser"},{"name":"oauthClients","kind":"object","type":"OAuthClient","relationName":"OAuthClientToUser"}],"dbName":null},"UserSecrets":{"fields":[{"name":"userid","kind":"scalar","type":"Int"},{"name":"password","kind":"scalar","type":"String"},{"name":"totpsecret","kind":"scalar","type":"String"},{"name":"user","kind":"object","type":"User","relationName":"UserToUserSecrets"}],"dbName":null},"Key":{"fields":[{"name":"id","kind":"scalar","type":"Int"},{"name":"value","kind":"scalar","type":"String"},{"name":"userid","kind":"scalar","type":"Int"},{"name":"created","kind":"scalar","type":"DateTime"},{"name":"expires","kind":"scalar","type":"DateTime"},{"name":"lastactive","kind":"scalar","type":"DateTime"},{"name":"data","kind":"scalar","type":"String"},{"name":"user","kind":"object","type":"User","relationName":"KeyToUser"}],"dbName":null},"ApiKey":{"fields":[{"name":"id","kind":"scalar","type":"Int"},{"name":"name","kind":"scalar","type":"String"},{"name":"value","kind":"scalar","type":"String"},{"name":"userid","kind":"scalar","type":"Int"},{"name":"created","kind":"scalar","type":"DateTime"},{"name":"expires","kind":"scalar","type":"DateTime"},{"name":"data","kind":"scalar","type":"String"},{"name":"user","kind":"object","type":"User","relationName":"ApiKeyToUser"}],"dbName":null},"OAuthClient":{"fields":[{"name":"client_id","kind":"scalar","type":"String"},{"name":"confidential","kind":"scalar","type":"Boolean"},{"name":"client_name","kind":"scalar","type":"String"},{"name":"client_secret","kind":"scalar","type":"String"},{"name":"userid","kind":"scalar","type":"Int"},{"name":"redirect_uri","kind":"object","type":"OAuthClientRedirectUri","relationName":"OAuthClientToOAuthClientRedirectUri"},{"name":"authorization","kind":"object","type":"OAuthAuthorization","relationName":"OAuthAuthorizationToOAuthClient"},{"name":"valid_flow","kind":"object","type":"OAuthClientValidFlow","relationName":"OAuthClientToOAuthClientValidFlow"},{"name":"user","kind":"object","type":"User","relationName":"OAuthClientToUser"}],"dbName":null},"OAuthClientRedirectUri":{"fields":[{"name":"id","kind":"scalar","type":"Int"},{"name":"client_id","kind":"scalar","type":"String"},{"name":"uri","kind":"scalar","type":"String"},{"name":"client","kind":"object","type":"OAuthClient","relationName":"OAuthClientToOAuthClientRedirectUri"}],"dbName":null},"OAuthClientValidFlow":{"fields":[{"name":"id","kind":"scalar","type":"Int"},{"name":"client_id","kind":"scalar","type":"String"},{"name":"flow","kind":"scalar","type":"String"},{"name":"client","kind":"object","type":"OAuthClient","relationName":"OAuthClientToOAuthClientValidFlow"}],"dbName":null},"OAuthAuthorization":{"fields":[{"name":"id","kind":"scalar","type":"Int"},{"name":"client_id","kind":"scalar","type":"String"},{"name":"userid","kind":"scalar","type":"Int"},{"name":"user","kind":"object","type":"User","relationName":"OAuthAuthorizationToUser"},{"name":"scope","kind":"scalar","type":"String"},{"name":"Client","kind":"object","type":"OAuthClient","relationName":"OAuthAuthorizationToOAuthClient"}],"dbName":null}},"enums":{},"types":{}}');
310
+ async function at(S) {
311
311
  const { Buffer: a } = await import("node:buffer"), e = a.from(S, "base64");
312
312
  return new WebAssembly.Module(e);
313
313
  }
314
- Ce.compilerWasm = {
314
+ be.compilerWasm = {
315
315
  getRuntime: async () => await import("@prisma/client/runtime/query_compiler_bg.sqlite.mjs"),
316
316
  getQueryCompilerWasmModule: async () => {
317
317
  const { wasm: S } = await import("@prisma/client/runtime/query_compiler_bg.sqlite.wasm-base64.mjs");
318
- return await Ge(S);
318
+ return await at(S);
319
319
  }
320
320
  };
321
- function Ze() {
322
- return G.getPrismaClient(Ce);
321
+ function st() {
322
+ return re.getPrismaClient(be);
323
323
  }
324
- const Q = G.PrismaClientKnownRequestError;
325
- G.Extensions.getExtensionContext;
326
- G.NullTypes.DbNull, G.NullTypes.JsonNull, G.NullTypes.AnyNull;
327
- G.makeStrictEnum({
324
+ const oe = re.PrismaClientKnownRequestError;
325
+ re.Extensions.getExtensionContext;
326
+ re.NullTypes.DbNull, re.NullTypes.JsonNull, re.NullTypes.AnyNull;
327
+ re.makeStrictEnum({
328
328
  Serializable: "Serializable"
329
329
  });
330
- G.Extensions.defineExtension;
331
- globalThis.__dirname = De.dirname(xe(import.meta.url));
332
- const ue = Ze();
333
- class Z extends L {
330
+ re.Extensions.defineExtension;
331
+ globalThis.__dirname = Ve.dirname(Me(import.meta.url));
332
+ const pe = st();
333
+ class se extends q {
334
334
  /**
335
335
  * Creates a PrismaUserStorage object, optionally overriding defaults.
336
336
  * @param options see {@link PrismaUserStorageOptions}
@@ -350,8 +350,8 @@ class Z extends L {
350
350
  }), e && e.prismaClient)
351
351
  this.prismaClient = e.prismaClient;
352
352
  else {
353
- const t = `${process.env.DATABASE_URL}`, r = new de({ url: t });
354
- this.prismaClient = new ue({ adapter: r });
353
+ const t = `${process.env.DATABASE_URL}`, r = new ye({ url: t });
354
+ this.prismaClient = new pe({ adapter: r });
355
355
  }
356
356
  }
357
357
  async getUser(e, t, r) {
@@ -368,17 +368,17 @@ class Z extends L {
368
368
  typeof c == "object" && (c == null ? void 0 : c.constructor.name) == "PrismaClientInitializationError" ? (h.logger.debug(m({ err: c })), h.logger.error(m({ cerr: c })), i = new o(l.Connection, "Couldn't connect to database server")) : typeof c == "object" && (c == null ? void 0 : c.constructor.name) == "PrismaClientInitializationError" ? (h.logger.debug(m({ err: c })), h.logger.error(m({ cerr: c })), i = new o(l.Connection, "Received error from database")) : i = new o(l.UserNotExist);
369
369
  }
370
370
  if (i) throw i;
371
- if ((r == null ? void 0 : r.skipActiveCheck) != !0 && s.state == k.awaitingTwoFactorSetup)
371
+ if ((r == null ? void 0 : r.skipActiveCheck) != !0 && s.state == E.awaitingTwoFactorSetup)
372
372
  throw h.logger.debug(m({ msg: "2FA setup is not complete" })), new o(l.TwoFactorIncomplete);
373
- if ((r == null ? void 0 : r.skipActiveCheck) != !0 && s.state == k.disabled)
373
+ if ((r == null ? void 0 : r.skipActiveCheck) != !0 && s.state == E.disabled)
374
374
  throw h.logger.debug(m({ msg: "User is deactivated" })), new o(l.UserNotActive);
375
- if ((r == null ? void 0 : r.skipEmailVerifiedCheck) != !0 && s.state == k.awaitingEmailVerification)
375
+ if ((r == null ? void 0 : r.skipEmailVerifiedCheck) != !0 && s.state == E.awaitingEmailVerification)
376
376
  throw h.logger.debug(m({ msg: "User has not verified email" })), new o(l.EmailNotVerified);
377
- if ((r == null ? void 0 : r.skipActiveCheck) != !0 && s.state == k.passwordChangeNeeded)
377
+ if ((r == null ? void 0 : r.skipActiveCheck) != !0 && s.state == E.passwordChangeNeeded)
378
378
  throw h.logger.debug(m({ msg: "User must change password" })), new o(l.PasswordChangeNeeded);
379
- if ((r == null ? void 0 : r.skipActiveCheck) != !0 && (s.state == k.passwordResetNeeded || s.state == k.passwordAndFactor2ResetNeeded))
379
+ if ((r == null ? void 0 : r.skipActiveCheck) != !0 && (s.state == E.passwordResetNeeded || s.state == E.passwordAndFactor2ResetNeeded))
380
380
  throw h.logger.debug(m({ msg: "User must reset password" })), new o(l.PasswordResetNeeded);
381
- if ((r == null ? void 0 : r.skipActiveCheck) != !0 && s.state == k.factor2ResetNeeded)
381
+ if ((r == null ? void 0 : r.skipActiveCheck) != !0 && s.state == E.factor2ResetNeeded)
382
382
  throw h.logger.debug(m({ msg: "2FA reset required" })), new o(l.Factor2ResetNeeded);
383
383
  const n = s.secrets || {};
384
384
  return s.secrets && (delete n[this.useridForeignKeyColumn], delete s.secrets), { user: { ...s, id: s[this.idColumn] }, secrets: { userid: s[this.idColumn], ...n } };
@@ -391,7 +391,7 @@ class Z extends L {
391
391
  */
392
392
  async getUserByUsername(e, t) {
393
393
  if (this.normalizeUsername) {
394
- const r = Z.normalize(e);
394
+ const r = se.normalize(e);
395
395
  return this.getUser("username_normalized", r, t);
396
396
  } else {
397
397
  const r = e;
@@ -420,7 +420,7 @@ class Z extends L {
420
420
  */
421
421
  async getUserByEmail(e, t) {
422
422
  if (this.normalizeEmail) {
423
- const r = Z.normalize(e);
423
+ const r = se.normalize(e);
424
424
  return this.getUser("email_normalized", r, t);
425
425
  } else {
426
426
  const r = e;
@@ -458,7 +458,7 @@ class Z extends L {
458
458
  t && !t.userid && (t = { ...t, userid: e[this.idColumn] });
459
459
  try {
460
460
  let { id: r, ...i } = e, { userid: s, ...n } = t ?? {};
461
- "email" in i && i.email && this.normalizeEmail && (i = { email_normalized: Z.normalize(i.email), ...i }), "username" in i && i.username && this.normalizeUsername && (i = { username_normalized: Z.normalize(i.username), ...i }), t ? await this.prismaClient.$transaction(async (c) => {
461
+ "email" in i && i.email && this.normalizeEmail && (i = { email_normalized: se.normalize(i.email), ...i }), "username" in i && i.username && this.normalizeUsername && (i = { username_normalized: se.normalize(i.username), ...i }), t ? await this.prismaClient.$transaction(async (c) => {
462
462
  let d = {};
463
463
  try {
464
464
  d = await c[this.userSecretsTable].findUniqueOrThrow({
@@ -510,7 +510,7 @@ class Z extends L {
510
510
  if (t && !t.password) throw new o(l.PasswordFormat, "Password required when creating user");
511
511
  let i, s = "", n = "";
512
512
  try {
513
- "email" in e && e.email && this.normalizeEmail && (n = Z.normalize(e.email)), "username" in e && e.username && this.normalizeUsername && (s = Z.normalize(e.username));
513
+ "email" in e && e.email && this.normalizeEmail && (n = se.normalize(e.email)), "username" in e && e.username && this.normalizeUsername && (s = se.normalize(e.username));
514
514
  let c = {
515
515
  ...e
516
516
  };
@@ -532,7 +532,7 @@ class Z extends L {
532
532
  data: c
533
533
  });
534
534
  } catch (c) {
535
- h.logger.debug(m({ err: c })), r = new o(l.Connection, "Error creating user"), (c instanceof Q || c instanceof Object && "code" in c) && c.code === "P2002" && (r = new o(l.UserExists));
535
+ h.logger.debug(m({ err: c })), r = new o(l.Connection, "Error creating user"), (c instanceof oe || c instanceof Object && "code" in c) && c.code === "P2002" && (r = new o(l.UserExists));
536
536
  }
537
537
  if (r)
538
538
  throw r;
@@ -598,7 +598,7 @@ class Z extends L {
598
598
  }
599
599
  }
600
600
  }
601
- class Ft extends z {
601
+ class Lt extends V {
602
602
  /**
603
603
  * Constructor with user storage object to use plus optional parameters.
604
604
  *
@@ -611,8 +611,8 @@ class Ft extends z {
611
611
  u(this, "transactionTimeout", 5e3);
612
612
  u(this, "useridForeignKeyColumn", "userid");
613
613
  if (w("transactionTimeout", g.Number, this, e, "TRANSACTION_TIMEOUT"), w("useridForeignKeyColumn", g.Number, this, e, "USER_ID_FOREIGN_KEY_COLUMN"), e.keyTable && (this.keyTable = e.keyTable), e.prismaClient == null) {
614
- const t = `${process.env.DATABASE_URL}`, r = new de({ url: t });
615
- this.prismaClient = new ue({ adapter: r });
614
+ const t = `${process.env.DATABASE_URL}`, r = new ye({ url: t });
615
+ this.prismaClient = new pe({ adapter: r });
616
616
  } else
617
617
  this.prismaClient = e.prismaClient;
618
618
  }
@@ -669,7 +669,7 @@ class Ft extends z {
669
669
  data: d
670
670
  });
671
671
  } catch (d) {
672
- d instanceof Q || d instanceof Object && "code" in d ? d.code == "P2002" ? (h.logger.warn(m({ msg: "Attempt to create key that already exists. Stack trace follows" })), h.logger.debug(m({ err: d })), c = new o(l.KeyExists)) : (h.logger.debug(m({ err: d })), c = new o(l.Connection, "Error saving key")) : (h.logger.debug(m({ err: d })), c = new o(l.Connection, "Error saving key"));
672
+ d instanceof oe || d instanceof Object && "code" in d ? d.code == "P2002" ? (h.logger.warn(m({ msg: "Attempt to create key that already exists. Stack trace follows" })), h.logger.debug(m({ err: d })), c = new o(l.KeyExists)) : (h.logger.debug(m({ err: d })), c = new o(l.Connection, "Error saving key")) : (h.logger.debug(m({ err: d })), c = new o(l.Connection, "Error saving key"));
673
673
  }
674
674
  if (c)
675
675
  throw c;
@@ -872,7 +872,7 @@ class Ft extends z {
872
872
  }
873
873
  }
874
874
  }
875
- class Nt extends ye {
875
+ class jt extends ve {
876
876
  /**
877
877
  * Constructor with user storage object to use plus optional parameters.
878
878
  *
@@ -889,8 +889,8 @@ class Nt extends ye {
889
889
  u(this, "updateMode", "DeleteAndInsert");
890
890
  u(this, "useridForeignKeyColumn", "userid");
891
891
  if (w("clientTable", g.String, this, e, "OAUTH_CLIENT_TABLE"), w("redirectUriTable", g.String, this, e, "OAUTH_REDIRECTURI_TABLE"), w("validFlowTable", g.String, this, e, "OAUTH_VALID_FLOW_TABLE"), w("transactionTimeout", g.Number, this, e, "TRANSACTION_TIMEOUT"), w("updateMode", g.String, this, e, "OAUTHCLIENT_UPDATE_MODE"), w("useridForeignKeyColumn", g.String, this, e, "USER_ID_FOREIGN_KEY_COLUMN"), e.prismaClient == null) {
892
- const t = `${process.env.DATABASE_URL}`, r = new de({ url: t });
893
- this.prismaClient = new ue({ adapter: r });
892
+ const t = `${process.env.DATABASE_URL}`, r = new ye({ url: t });
893
+ this.prismaClient = new pe({ adapter: r });
894
894
  } else
895
895
  this.prismaClient = e.prismaClient;
896
896
  }
@@ -916,8 +916,8 @@ class Nt extends ye {
916
916
  ...d,
917
917
  userid: C,
918
918
  client_secret: d.client_secret ?? void 0,
919
- redirect_uri: f.map((v) => v.uri),
920
- valid_flow: y.map((v) => v.flow)
919
+ redirect_uri: f.map((_) => _.uri),
920
+ valid_flow: y.map((_) => _.flow)
921
921
  }];
922
922
  } else {
923
923
  const d = await r[this.clientTable].findMany({
@@ -929,8 +929,8 @@ class Nt extends ye {
929
929
  });
930
930
  for (let f of d) {
931
931
  const y = f.redirect_uri, C = f.valid_flow;
932
- let v = f[this.useridForeignKeyColumn];
933
- v == null && (v = void 0), f.userid = v, this.useridForeignKeyColumn != "userid" && delete f[this.useridForeignKeyColumn], f.client_secret = f.client_secret ?? void 0, f.redirect_uri = y.map((p) => p.uri), f.valid_flow = C.map((p) => p.flow);
932
+ let _ = f[this.useridForeignKeyColumn];
933
+ _ == null && (_ = void 0), f.userid = _, this.useridForeignKeyColumn != "userid" && delete f[this.useridForeignKeyColumn], f.client_secret = f.client_secret ?? void 0, f.redirect_uri = y.map((p) => p.uri), f.valid_flow = C.map((p) => p.flow);
934
934
  }
935
935
  return d;
936
936
  }
@@ -973,14 +973,14 @@ class Nt extends ye {
973
973
  }
974
974
  if (i) {
975
975
  for (let d = 0; d < i.length; ++d)
976
- if (!U.isValidFlow(i[d])) throw new o(l.InvalidOAuthFlow, "Invalid flow " + i[d]);
976
+ if (!I.isValidFlow(i[d])) throw new o(l.InvalidOAuthFlow, "Invalid flow " + i[d]);
977
977
  }
978
978
  try {
979
979
  c = await t[this.clientTable].create({
980
980
  data: n
981
981
  });
982
982
  } catch (d) {
983
- throw d instanceof Q || d instanceof Object && "code" in d ? d.code == "P2002" ? (h.logger.debug(m({ err: d })), new o(l.ClientExists, "Attempt to create an OAuth client with a client_id that already exists. Maximum attempts failed")) : (h.logger.debug(m({ err: d })), new o(l.Connection, "Error saving OAuth client")) : (h.logger.debug(m({ err: d })), new o(l.Connection, "Error saving OAuth client"));
983
+ throw d instanceof oe || d instanceof Object && "code" in d ? d.code == "P2002" ? (h.logger.debug(m({ err: d })), new o(l.ClientExists, "Attempt to create an OAuth client with a client_id that already exists. Maximum attempts failed")) : (h.logger.debug(m({ err: d })), new o(l.Connection, "Error saving OAuth client")) : (h.logger.debug(m({ err: d })), new o(l.Connection, "Error saving OAuth client"));
984
984
  }
985
985
  if (!c)
986
986
  throw h.logger.error(m({ msg: "Attempt to create key that already exists. Stack trace follows" })), new o(l.KeyExists);
@@ -994,7 +994,7 @@ class Nt extends ye {
994
994
  }
995
995
  });
996
996
  } catch (d) {
997
- throw d instanceof Q || d instanceof Object && "code" in d ? d.code == "P2002" ? (h.logger.debug(m({ err: d })), new o(l.InvalidRedirectUri, "Attempt to create an OAuth client with a redirect uri that already belongs to another client")) : (h.logger.debug(m({ err: d })), new o(l.Connection, "Error saving OAuth client")) : (h.logger.debug(m({ err: d })), new o(l.Connection, "Error saving OAuth client"));
997
+ throw d instanceof oe || d instanceof Object && "code" in d ? d.code == "P2002" ? (h.logger.debug(m({ err: d })), new o(l.InvalidRedirectUri, "Attempt to create an OAuth client with a redirect uri that already belongs to another client")) : (h.logger.debug(m({ err: d })), new o(l.Connection, "Error saving OAuth client")) : (h.logger.debug(m({ err: d })), new o(l.Connection, "Error saving OAuth client"));
998
998
  }
999
999
  if (i)
1000
1000
  try {
@@ -1006,7 +1006,7 @@ class Nt extends ye {
1006
1006
  }
1007
1007
  });
1008
1008
  } catch (d) {
1009
- throw d instanceof Q || d instanceof Object && "code" in d ? (h.logger.debug(m({ err: d })), new o(l.Connection, "Error saving OAuth client")) : (h.logger.debug(m({ err: d })), new o(l.Connection, "Error saving OAuth client"));
1009
+ throw d instanceof oe || d instanceof Object && "code" in d ? (h.logger.debug(m({ err: d })), new o(l.Connection, "Error saving OAuth client")) : (h.logger.debug(m({ err: d })), new o(l.Connection, "Error saving OAuth client"));
1010
1010
  }
1011
1011
  return { ...c, redirect_uri: r, valid_flow: i };
1012
1012
  }
@@ -1060,7 +1060,7 @@ class Nt extends ye {
1060
1060
  }
1061
1061
  if (i) {
1062
1062
  for (let s = 0; s < i.length; ++s)
1063
- if (!U.isValidFlow(i[s])) throw new o(l.InvalidOAuthFlow, "Redirect Uri's may not contain page fragments");
1063
+ if (!I.isValidFlow(i[s])) throw new o(l.InvalidOAuthFlow, "Redirect Uri's may not contain page fragments");
1064
1064
  }
1065
1065
  try {
1066
1066
  let s = { ...e };
@@ -1088,7 +1088,7 @@ class Nt extends ye {
1088
1088
  }
1089
1089
  });
1090
1090
  } catch (s) {
1091
- throw s instanceof Q || s instanceof Object && "code" in s ? s.code == "P2002" ? (h.logger.debug(m({ err: s })), new o(l.KeyExists, "Attempt to update an OAuth client with a redirect Uri that already belongs to another client")) : (h.logger.debug(m({ err: s })), new o(l.Connection, "Error updating client")) : (h.logger.debug(m({ err: s })), new o(l.Connection, "Error updating client"));
1091
+ throw s instanceof oe || s instanceof Object && "code" in s ? s.code == "P2002" ? (h.logger.debug(m({ err: s })), new o(l.KeyExists, "Attempt to update an OAuth client with a redirect Uri that already belongs to another client")) : (h.logger.debug(m({ err: s })), new o(l.Connection, "Error updating client")) : (h.logger.debug(m({ err: s })), new o(l.Connection, "Error updating client"));
1092
1092
  }
1093
1093
  if (i != null)
1094
1094
  try {
@@ -1105,7 +1105,7 @@ class Nt extends ye {
1105
1105
  }
1106
1106
  });
1107
1107
  } catch (s) {
1108
- throw s instanceof Q || s instanceof Object && "code" in s ? (h.logger.debug(m({ err: s })), new o(l.Connection, "Error updating client")) : (h.logger.debug(m({ err: s })), new o(l.Connection, "Error updating client"));
1108
+ throw s instanceof oe || s instanceof Object && "code" in s ? (h.logger.debug(m({ err: s })), new o(l.Connection, "Error updating client")) : (h.logger.debug(m({ err: s })), new o(l.Connection, "Error updating client"));
1109
1109
  }
1110
1110
  }
1111
1111
  async updateClientWithTransaction_deleteAndInsert(e, t) {
@@ -1141,7 +1141,7 @@ class Nt extends ye {
1141
1141
  }
1142
1142
  }
1143
1143
  }
1144
- class Dt extends pe {
1144
+ class Ht extends Ee {
1145
1145
  /**
1146
1146
  * Constructor with user storage object to use plus optional parameters.
1147
1147
  *
@@ -1155,8 +1155,8 @@ class Dt extends pe {
1155
1155
  u(this, "transactionTimeout", 5e3);
1156
1156
  u(this, "useridForeignKeyColumn", "userid");
1157
1157
  if (w("authorizationTable", g.String, this, e, "OAUTH_AUTHORIZATION_TABLE"), w("transactionTimeout", g.Number, this, e, "TRANSACTION_TIMEOUT"), w("useridForeignKeyColumn", g.String, this, e, "USER_ID_FOREIGN_KEY_COLUMN"), e.prismaClient == null) {
1158
- const t = `${process.env.DATABASE_URL}`, r = new de({ url: t });
1159
- this.prismaClient = new ue({ adapter: r });
1158
+ const t = `${process.env.DATABASE_URL}`, r = new ye({ url: t });
1159
+ this.prismaClient = new pe({ adapter: r });
1160
1160
  } else
1161
1161
  this.prismaClient = e.prismaClient;
1162
1162
  }
@@ -1210,7 +1210,7 @@ class Dt extends pe {
1210
1210
  }
1211
1211
  }
1212
1212
  }
1213
- class xt extends L {
1213
+ class Vt extends q {
1214
1214
  /**
1215
1215
  * Creates a InMemoryUserStorage object, optionally overriding defaults.
1216
1216
  * @param options see {@link InMemoryUserStorageOptions}
@@ -1229,9 +1229,9 @@ class xt extends L {
1229
1229
  */
1230
1230
  async createUser(e, t) {
1231
1231
  let r = "username", i = "email";
1232
- if (this.normalizeUsername && (r = "username_normalized", e.username_normalized = L.normalize(e.username), e.username_normalized in this.usersByUsername))
1232
+ if (this.normalizeUsername && (r = "username_normalized", e.username_normalized = q.normalize(e.username), e.username_normalized in this.usersByUsername))
1233
1233
  throw new o(l.UserExists);
1234
- if ("email" in e && e.email && this.normalizeEmail && (i = "email_normalized", e.email_normalized = L.normalize(e.email), e.email_normalized in this.getUserByEmail))
1234
+ if ("email" in e && e.email && this.normalizeEmail && (i = "email_normalized", e.email_normalized = q.normalize(e.email), e.email_normalized in this.getUserByEmail))
1235
1235
  throw new o(l.UserExists);
1236
1236
  const s = { id: e.username, ...e };
1237
1237
  return this.usersByUsername[e[r]] = s, this.secretsByUsername[e[r]] = t ?? {}, "email" in e && e.email && (this.usersByEmail[e[i]] = s), "email" in e && e.email && (this.secretsByEmail[e[i]] = t ?? {}), { id: e.username, ...e };
@@ -1244,21 +1244,21 @@ class xt extends L {
1244
1244
  * @throws {@link @crossauth/common!CrossauthError } with {@link @crossauth/common!ErrorCode } set to either `UserNotExist`.
1245
1245
  */
1246
1246
  async getUserByUsername(e, t) {
1247
- const r = this.normalizeUsername ? L.normalize(e) : e;
1247
+ const r = this.normalizeUsername ? q.normalize(e) : e;
1248
1248
  if (r in this.usersByUsername) {
1249
1249
  const i = this.usersByUsername[r];
1250
1250
  if (!i) throw new o(l.UserNotExist);
1251
- if ((t == null ? void 0 : t.skipActiveCheck) != !0 && i.state == k.passwordChangeNeeded)
1251
+ if ((t == null ? void 0 : t.skipActiveCheck) != !0 && i.state == E.passwordChangeNeeded)
1252
1252
  throw h.logger.debug(m({ msg: "Password change required" })), new o(l.PasswordChangeNeeded);
1253
- if ((t == null ? void 0 : t.skipActiveCheck) != !0 && (i.state == k.passwordResetNeeded || i.state == k.passwordAndFactor2ResetNeeded))
1253
+ if ((t == null ? void 0 : t.skipActiveCheck) != !0 && (i.state == E.passwordResetNeeded || i.state == E.passwordAndFactor2ResetNeeded))
1254
1254
  throw h.logger.debug(m({ msg: "Password reset required" })), new o(l.PasswordResetNeeded);
1255
- if ((t == null ? void 0 : t.skipActiveCheck) != !0 && i.state == k.factor2ResetNeeded)
1255
+ if ((t == null ? void 0 : t.skipActiveCheck) != !0 && i.state == E.factor2ResetNeeded)
1256
1256
  throw h.logger.debug(m({ msg: "2FA reset required" })), new o(l.Factor2ResetNeeded);
1257
- if ((t == null ? void 0 : t.skipActiveCheck) != !0 && i.state == k.awaitingTwoFactorSetup)
1257
+ if ((t == null ? void 0 : t.skipActiveCheck) != !0 && i.state == E.awaitingTwoFactorSetup)
1258
1258
  throw h.logger.debug(m({ msg: "2FA setup is not complete" })), new o(l.TwoFactorIncomplete);
1259
- if ((t == null ? void 0 : t.skipEmailVerifiedCheck) != !0 && i.state == k.awaitingEmailVerification)
1259
+ if ((t == null ? void 0 : t.skipEmailVerifiedCheck) != !0 && i.state == E.awaitingEmailVerification)
1260
1260
  throw h.logger.debug(m({ msg: "User email not verified" })), new o(l.EmailNotVerified);
1261
- if ((t == null ? void 0 : t.skipActiveCheck) != !0 && i.state == k.disabled)
1261
+ if ((t == null ? void 0 : t.skipActiveCheck) != !0 && i.state == E.disabled)
1262
1262
  throw h.logger.debug(m({ msg: "User is deactivated" })), new o(l.UserNotActive);
1263
1263
  const s = this.secretsByUsername[r];
1264
1264
  return { user: { ...i }, secrets: { userid: i.id, ...s } };
@@ -1273,7 +1273,7 @@ class xt extends L {
1273
1273
  * @throws {@link @crossauth/common!CrossauthError } with {@link @crossauth/common!ErrorCode } set to either `UserNotExist`.
1274
1274
  */
1275
1275
  async getUserByEmail(e, t) {
1276
- const r = this.normalizeEmail ? L.normalize(e) : e;
1276
+ const r = this.normalizeEmail ? q.normalize(e) : e;
1277
1277
  if (r in this.usersByEmail) {
1278
1278
  const i = this.usersByEmail[r];
1279
1279
  if (!i) throw new o(l.UserNotExist);
@@ -1317,7 +1317,7 @@ class xt extends L {
1317
1317
  */
1318
1318
  async updateUser(e, t) {
1319
1319
  let r = { ...e }, i = "username";
1320
- if ("username" in r && r.username && this.normalizeUsername ? (r.username_normalized = L.normalize(r.username), i = "username_normalized") : "id" in r && r.id && this.normalizeUsername && (r.username_normalized = L.normalize(String(r.id)), i = "username_normalized"), "email" in r && r.email && this.normalizeEmail && (r.email_normalized = L.normalize(r.email)), r[i] && r[i] in this.usersByUsername) {
1320
+ if ("username" in r && r.username && this.normalizeUsername ? (r.username_normalized = q.normalize(r.username), i = "username_normalized") : "id" in r && r.id && this.normalizeUsername && (r.username_normalized = q.normalize(String(r.id)), i = "username_normalized"), "email" in r && r.email && this.normalizeEmail && (r.email_normalized = q.normalize(r.email)), r[i] && r[i] in this.usersByUsername) {
1321
1321
  for (let s in r)
1322
1322
  this.usersByUsername[r[i]][s] = r[s];
1323
1323
  t && (this.secretsByUsername[r[i]] = {
@@ -1331,11 +1331,11 @@ class xt extends L {
1331
1331
  * @param username username of user to delete
1332
1332
  */
1333
1333
  async deleteUserByUsername(e) {
1334
- const t = this.normalizeUsername ? L.normalize(String(e)) : e;
1334
+ const t = this.normalizeUsername ? q.normalize(String(e)) : e;
1335
1335
  if (t in this.usersByUsername) {
1336
1336
  const r = this.usersByUsername[t];
1337
1337
  delete this.usersByUsername[t], delete this.secretsByUsername[t];
1338
- const i = this.normalizeEmail ? L.normalize(String(r.email)) : r.email;
1338
+ const i = this.normalizeEmail ? q.normalize(String(r.email)) : r.email;
1339
1339
  i && i in this.usersByEmail && (delete this.usersByEmail[i], delete this.secretsByEmail[i]);
1340
1340
  }
1341
1341
  }
@@ -1357,7 +1357,7 @@ class xt extends L {
1357
1357
  return i;
1358
1358
  }
1359
1359
  }
1360
- class Rt extends z {
1360
+ class Mt extends V {
1361
1361
  /**
1362
1362
  * Constructor
1363
1363
  */
@@ -1510,7 +1510,7 @@ class Rt extends z {
1510
1510
  this.deleteDataInternal(i, t) && (r.data = JSON.stringify(i));
1511
1511
  }
1512
1512
  }
1513
- class Bt extends ye {
1513
+ class $t extends ve {
1514
1514
  /**
1515
1515
  * Constructor
1516
1516
  */
@@ -1601,7 +1601,7 @@ class Bt extends ye {
1601
1601
  return s;
1602
1602
  }
1603
1603
  }
1604
- class zt extends pe {
1604
+ class qt extends Ee {
1605
1605
  /**
1606
1606
  * Constructor
1607
1607
  */
@@ -1636,10 +1636,10 @@ class zt extends pe {
1636
1636
  this.byClient[e] = [...r];
1637
1637
  }
1638
1638
  }
1639
- function Xe(S, a) {
1639
+ function nt(S, a) {
1640
1640
  return { username: Array.isArray(a.uid) ? a.uid[0] : a.uid, state: "active", ...S };
1641
1641
  }
1642
- class le extends L {
1642
+ class ge extends q {
1643
1643
  /**
1644
1644
  * Constructor.
1645
1645
  * @param localStorage the underlying storage where users are kept (without passwords)
@@ -1651,7 +1651,7 @@ class le extends L {
1651
1651
  u(this, "ldapUrls", []);
1652
1652
  u(this, "ldapUserSearchBase", "");
1653
1653
  u(this, "ldapUsernameAttribute", "cn");
1654
- u(this, "createUserFn", Xe);
1654
+ u(this, "createUserFn", nt);
1655
1655
  this.localStorage = e, w("ldapUrls", g.JsonArray, this, t, "LDAP_URL", !0), w("ldapUserSearchBase", g.String, this, t, "LDAP_USER_SEARCH_BASE"), w("ldapUsernameAttribute", g.String, this, t, "LDAP_USENAME_ATTRIBUTE"), t.createUserFn && (this.createUserFn = t.createUserFn);
1656
1656
  }
1657
1657
  /**
@@ -1746,20 +1746,20 @@ class le extends L {
1746
1746
  async getLdapUser(e, t) {
1747
1747
  let r;
1748
1748
  try {
1749
- const i = le.sanitizeLdapDnForSearch(e), s = [this.ldapUsernameAttribute + "=" + i, this.ldapUserSearchBase].join(",");
1749
+ const i = ge.sanitizeLdapDnForSearch(e), s = [this.ldapUsernameAttribute + "=" + i, this.ldapUserSearchBase].join(",");
1750
1750
  if (!t) throw new o(l.PasswordInvalid);
1751
1751
  return h.logger.debug(m({ msg: "LDAP search " + s })), r = await this.ldapBind(s, t), await this.searchUser(r, s);
1752
1752
  } catch (i) {
1753
1753
  h.logger.debug(m({ err: i }));
1754
1754
  const s = o.asCrossauthError(i);
1755
- throw i instanceof Se.InvalidCredentialsError ? new o(l.UsernameOrPasswordInvalid) : s.code != l.UnknownError ? s : new o(l.Connection, "LDAP error getting user");
1755
+ throw i instanceof Ue.InvalidCredentialsError ? new o(l.UsernameOrPasswordInvalid) : s.code != l.UnknownError ? s : new o(l.Connection, "LDAP error getting user");
1756
1756
  }
1757
1757
  }
1758
1758
  // bind and return the ldap client
1759
1759
  // from https://github.com/shaozi/ldap-authentication/blob/master/index.js
1760
1760
  ldapBind(e, t) {
1761
1761
  return new Promise((r, i) => {
1762
- let s = Se.createClient({ url: this.ldapUrls });
1762
+ let s = Ue.createClient({ url: this.ldapUrls });
1763
1763
  s.on("connect", function() {
1764
1764
  s.bind(e, t, function(n) {
1765
1765
  if (n) {
@@ -1797,7 +1797,7 @@ class le extends L {
1797
1797
  return;
1798
1798
  }
1799
1799
  d.on("searchEntry", function(y) {
1800
- f = le.searchResultToUser(y.pojo);
1800
+ f = ge.searchResultToUser(y.pojo);
1801
1801
  }), d.on("error", function(y) {
1802
1802
  s(y), e.unbind();
1803
1803
  }), d.on("end", function(y) {
@@ -1827,10 +1827,10 @@ class le extends L {
1827
1827
  * @returns a sanitized dn
1828
1828
  */
1829
1829
  static sanitizeLdapDnForSearch(e) {
1830
- return le.sanitizeLdapDn(e).replace("*", "*").replace("(", "(").replace(")", ")");
1830
+ return ge.sanitizeLdapDn(e).replace("*", "*").replace("(", "(").replace(")", ")");
1831
1831
  }
1832
1832
  }
1833
- class Y extends L {
1833
+ class te extends q {
1834
1834
  /**
1835
1835
  * Creates a DbUserStorage object, optionally overriding defaults.
1836
1836
  * @param dbPool the instance of the Posrgres client.
@@ -1865,7 +1865,7 @@ class Y extends L {
1865
1865
  * @throws CrossauthException with ErrorCode either `UserNotExist` or whatever pg throws
1866
1866
  */
1867
1867
  async getUserByUsername(e, t) {
1868
- const r = this.normalizeUsername ? Y.normalize(e) : e;
1868
+ const r = this.normalizeUsername ? te.normalize(e) : e;
1869
1869
  return await this.getUser("username_normalized", r, t);
1870
1870
  }
1871
1871
  /**
@@ -1878,7 +1878,7 @@ class Y extends L {
1878
1878
  * @throws {@link @crossauth/common!CrossauthError } with {@link @crossauth/common!ErrorCode } set to either `UserNotExist` or whatever pg throwsa.
1879
1879
  */
1880
1880
  async getUserByEmail(e, t) {
1881
- const r = this.normalizeEmail ? Y.normalize(e) : e;
1881
+ const r = this.normalizeEmail ? te.normalize(e) : e;
1882
1882
  return this.getUser("email_normalized", r, t);
1883
1883
  }
1884
1884
  /**
@@ -1899,33 +1899,33 @@ class Y extends L {
1899
1899
  let d = `select * from ${this.userTable} where ${e} = ` + c.nextParameter(), f = await i.execute(d, [t]);
1900
1900
  if (f.length == 0)
1901
1901
  throw new o(l.UserNotExist);
1902
- let y, C, v;
1902
+ let y, C, _;
1903
1903
  if (this.idColumn in f[0]) y = f[0][this.idColumn];
1904
1904
  else throw new o(l.Configuration, "ID column " + this.idColumn + " not present in user table");
1905
1905
  if ("username" in f[0]) C = f[0].username;
1906
1906
  else throw new o(l.Configuration, "username column " + this.idColumn + " not present in user table");
1907
- if ("state" in f[0]) v = f[0].state;
1907
+ if ("state" in f[0]) _ = f[0].state;
1908
1908
  else throw new o(l.Configuration, "state column " + this.idColumn + " not present in user table");
1909
1909
  if (s = {
1910
1910
  ...f[0],
1911
1911
  id: y,
1912
1912
  username: C,
1913
- state: v
1913
+ state: _
1914
1914
  }, !s) throw new o(l.UserNotExist);
1915
1915
  if (c = this.dbPool.parameters(), d = `select * from ${this.userSecretsTable} where ${this.useridForeignKeyColumn} = ` + c.nextParameter(), f = await i.execute(d, [s.id]), f.length == 0)
1916
1916
  throw new o(l.UserNotExist);
1917
1917
  if (f.length > 0 ? n = { userid: s.id, ...f[0] } : n = { userid: s.id }, !n) throw new o(l.UserNotExist);
1918
- if (this.useridForeignKeyColumn != "userid" && this.useridForeignKeyColumn in n && delete n[this.useridForeignKeyColumn], await i.commit(), (r == null ? void 0 : r.skipActiveCheck) != !0 && s.state == k.awaitingTwoFactorSetup)
1918
+ if (this.useridForeignKeyColumn != "userid" && this.useridForeignKeyColumn in n && delete n[this.useridForeignKeyColumn], await i.commit(), (r == null ? void 0 : r.skipActiveCheck) != !0 && s.state == E.awaitingTwoFactorSetup)
1919
1919
  throw h.logger.debug(m({ msg: "2FA setup is not complete" })), new o(l.TwoFactorIncomplete);
1920
- if ((r == null ? void 0 : r.skipActiveCheck) != !0 && s.state == k.disabled)
1920
+ if ((r == null ? void 0 : r.skipActiveCheck) != !0 && s.state == E.disabled)
1921
1921
  throw h.logger.debug(m({ msg: "User is deactivated" })), new o(l.UserNotActive);
1922
- if ((r == null ? void 0 : r.skipEmailVerifiedCheck) != !0 && s.state == k.awaitingEmailVerification)
1922
+ if ((r == null ? void 0 : r.skipEmailVerifiedCheck) != !0 && s.state == E.awaitingEmailVerification)
1923
1923
  throw h.logger.debug(m({ msg: "User has not verified email" })), new o(l.EmailNotVerified);
1924
- if ((r == null ? void 0 : r.skipActiveCheck) != !0 && s.state == k.passwordChangeNeeded)
1924
+ if ((r == null ? void 0 : r.skipActiveCheck) != !0 && s.state == E.passwordChangeNeeded)
1925
1925
  throw h.logger.debug(m({ msg: "User must change password" })), new o(l.PasswordChangeNeeded);
1926
- if ((r == null ? void 0 : r.skipActiveCheck) != !0 && (s.state == k.passwordResetNeeded || s.state == k.passwordAndFactor2ResetNeeded))
1926
+ if ((r == null ? void 0 : r.skipActiveCheck) != !0 && (s.state == E.passwordResetNeeded || s.state == E.passwordAndFactor2ResetNeeded))
1927
1927
  throw h.logger.debug(m({ msg: "User must reset password" })), new o(l.PasswordResetNeeded);
1928
- if ((r == null ? void 0 : r.skipActiveCheck) != !0 && s.state == k.factor2ResetNeeded)
1928
+ if ((r == null ? void 0 : r.skipActiveCheck) != !0 && s.state == E.factor2ResetNeeded)
1929
1929
  throw h.logger.debug(m({ msg: "2FA reset required" })), new o(l.Factor2ResetNeeded);
1930
1930
  return { user: s, secrets: n };
1931
1931
  } catch (d) {
@@ -1949,20 +1949,20 @@ class Y extends L {
1949
1949
  if (y.length == 0)
1950
1950
  throw new o(l.UserNotExist);
1951
1951
  for (let C of y) {
1952
- let v, p, T;
1953
- if (this.idColumn in C) v = C[this.idColumn];
1952
+ let _, p, T;
1953
+ if (this.idColumn in C) _ = C[this.idColumn];
1954
1954
  else throw new o(l.Configuration, "ID column " + this.idColumn + " not present in user table");
1955
1955
  if ("username" in C) p = C.username;
1956
1956
  else throw new o(l.Configuration, "username column " + this.idColumn + " not present in user table");
1957
1957
  if ("state" in C) T = C.state;
1958
1958
  else throw new o(l.Configuration, "state column " + this.idColumn + " not present in user table");
1959
- let E = {
1959
+ let v = {
1960
1960
  ...C,
1961
- id: v,
1961
+ id: _,
1962
1962
  username: p,
1963
1963
  state: T
1964
1964
  };
1965
- i.push(E);
1965
+ i.push(v);
1966
1966
  }
1967
1967
  return i;
1968
1968
  } catch (f) {
@@ -1990,15 +1990,15 @@ class Y extends L {
1990
1990
  if ((await r.execute(s, [e.id])).length == 0)
1991
1991
  throw new o(l.UserNotExist);
1992
1992
  let c = { ...e }, d = t ? { ...t } : void 0;
1993
- "email" in c && c.email && (c = { email_normalized: this.normalizeEmail ? Y.normalize(c.email) : c.email, ...c }), "username" in c && c.username && (c = { username_normalized: this.normalizeUsername ? Y.normalize(c.username) : c.username, ...c }), i = this.dbPool.parameters();
1993
+ "email" in c && c.email && (c = { email_normalized: this.normalizeEmail ? te.normalize(c.email) : c.email, ...c }), "username" in c && c.username && (c = { username_normalized: this.normalizeUsername ? te.normalize(c.username) : c.username, ...c }), i = this.dbPool.parameters();
1994
1994
  let f = [], y = [];
1995
1995
  for (let C in c)
1996
1996
  c[C] != null && C != "id" && (f.push(C + "= " + i.nextParameter()), y.push(c[C]));
1997
1997
  if (f.length > 0) {
1998
1998
  let C = f.join(", ");
1999
1999
  y.push(e.id);
2000
- let v = `update ${this.userTable} set ${C} where ${this.idColumn} = ` + i.nextParameter();
2001
- await r.execute(v, y);
2000
+ let _ = `update ${this.userTable} set ${C} where ${this.idColumn} = ` + i.nextParameter();
2001
+ await r.execute(_, y);
2002
2002
  }
2003
2003
  if (t) {
2004
2004
  f = [], y = [], i = this.dbPool.parameters();
@@ -2007,8 +2007,8 @@ class Y extends L {
2007
2007
  if (f.length > 0) {
2008
2008
  let C = f.join(", ");
2009
2009
  y.push(e.id);
2010
- let v = `update ${this.userSecretsTable} set ${C} where userid = ` + i.nextParameter();
2011
- await r.execute(v, y);
2010
+ let _ = `update ${this.userSecretsTable} set ${C} where userid = ` + i.nextParameter();
2011
+ await r.execute(_, y);
2012
2012
  }
2013
2013
  }
2014
2014
  await r.commit();
@@ -2035,28 +2035,28 @@ class Y extends L {
2035
2035
  try {
2036
2036
  await r.startTransaction();
2037
2037
  let s = { ...e }, n = t ? { ...t } : void 0;
2038
- "email" in s && s.email && (s = { email_normalized: this.normalizeEmail ? Y.normalize(s.email) : s.email, ...s }), "username" in s && s.username && (s = { username_normalized: this.normalizeUsername ? Y.normalize(s.username) : s.username, ...s });
2038
+ "email" in s && s.email && (s = { email_normalized: this.normalizeEmail ? te.normalize(s.email) : s.email, ...s }), "username" in s && s.username && (s = { username_normalized: this.normalizeUsername ? te.normalize(s.username) : s.username, ...s });
2039
2039
  let c = [], d = [], f = [];
2040
2040
  const y = this.dbPool.parameters();
2041
- for (let v in s)
2042
- s[v] != null && v != "id" && (c.push(v), d.push(y.nextParameter()), f.push(s[v]));
2041
+ for (let _ in s)
2042
+ s[_] != null && _ != "id" && (c.push(_), d.push(y.nextParameter()), f.push(s[_]));
2043
2043
  if (c.length > 0) {
2044
- let v = c.join(", "), p = d.join(", ");
2045
- const T = `insert into ${this.userTable} (${v}) values (${p}) returning ${this.idColumn}`, E = await r.execute(T, f);
2046
- if (E.length == 0 || !E[0][this.idColumn]) throw new o(l.Connection, "Couldn't create user");
2047
- i = E[0][this.idColumn];
2044
+ let _ = c.join(", "), p = d.join(", ");
2045
+ const T = `insert into ${this.userTable} (${_}) values (${p}) returning ${this.idColumn}`, v = await r.execute(T, f);
2046
+ if (v.length == 0 || !v[0][this.idColumn]) throw new o(l.Connection, "Couldn't create user");
2047
+ i = v[0][this.idColumn];
2048
2048
  }
2049
2049
  if (!i) throw new o(l.Connection, "Couldn't create user");
2050
2050
  if (t) {
2051
2051
  c = [], d = [], f = [];
2052
- const v = this.dbPool.parameters();
2053
- c.push("userid"), d.push(v.nextParameter()), f.push(i);
2052
+ const _ = this.dbPool.parameters();
2053
+ c.push("userid"), d.push(_.nextParameter()), f.push(i);
2054
2054
  for (let p in n)
2055
- n[p] != null && p != "userid" && (c.push(p), d.push(v.nextParameter()), f.push(n[p]));
2055
+ n[p] != null && p != "userid" && (c.push(p), d.push(_.nextParameter()), f.push(n[p]));
2056
2056
  if (c.length > 0) {
2057
2057
  let p = c.join(", "), T = d.join(", ");
2058
- const E = `insert into ${this.userSecretsTable} (${p}) values (${T})`;
2059
- h.logger.debug(m({ msg: "Executing query", query: E })), await r.execute(E, f);
2058
+ const v = `insert into ${this.userSecretsTable} (${p}) values (${T})`;
2059
+ h.logger.debug(m({ msg: "Executing query", query: v })), await r.execute(v, f);
2060
2060
  }
2061
2061
  }
2062
2062
  return await r.commit(), (await this.getUserById(i)).user;
@@ -2103,7 +2103,7 @@ class Y extends L {
2103
2103
  }
2104
2104
  }
2105
2105
  }
2106
- class Qe extends z {
2106
+ class ot extends V {
2107
2107
  /**
2108
2108
  * Constructor with user storage object to use plus optional parameters.
2109
2109
  *
@@ -2163,18 +2163,18 @@ class Qe extends z {
2163
2163
  */
2164
2164
  async saveKey(e, t, r, i, s, n = {}) {
2165
2165
  let c, d = [this.useridForeignKeyColumn, "value", "created", "expires", "data"], f = this.dbPool.parameters(), y = [];
2166
- for (let E = 0; E < 5; ++E)
2166
+ for (let v = 0; v < 5; ++v)
2167
2167
  y.push(f.nextParameter());
2168
2168
  let C = [e ?? null, t, r, i ?? null, s ?? ""];
2169
- for (let E in n)
2170
- d.push(E), y.push(f.nextParameter()), C.push(n[E]);
2171
- let v = d.join(", "), p = y.join(", ");
2169
+ for (let v in n)
2170
+ d.push(v), y.push(f.nextParameter()), C.push(n[v]);
2171
+ let _ = d.join(", "), p = y.join(", ");
2172
2172
  const T = await this.dbPool.connect();
2173
2173
  try {
2174
- const E = `insert into ${this.keyTable} (${v}) values (${p})`;
2175
- await T.execute(E, C);
2176
- } catch (E) {
2177
- o.asCrossauthError(E).code == l.ConstraintViolation ? (h.logger.warn(m({ msg: "Attempt to create key that already exists. Stack trace follows" })), h.logger.debug(m({ err: E })), c = new o(l.KeyExists)) : (h.logger.debug(m({ err: E })), c = new o(l.Connection, "Error saving key"));
2174
+ const v = `insert into ${this.keyTable} (${_}) values (${p})`;
2175
+ await T.execute(v, C);
2176
+ } catch (v) {
2177
+ o.asCrossauthError(v).code == l.ConstraintViolation ? (h.logger.warn(m({ msg: "Attempt to create key that already exists. Stack trace follows" })), h.logger.debug(m({ err: v })), c = new o(l.KeyExists)) : (h.logger.debug(m({ err: v })), c = new o(l.Connection, "Error saving key"));
2178
2178
  } finally {
2179
2179
  T.release();
2180
2180
  }
@@ -2354,7 +2354,7 @@ class Qe extends z {
2354
2354
  }
2355
2355
  }
2356
2356
  }
2357
- class et extends ye {
2357
+ class lt extends ve {
2358
2358
  /**
2359
2359
  * Constructor with user storage object to use plus optional parameters.
2360
2360
  *
@@ -2412,14 +2412,14 @@ class et extends ye {
2412
2412
  async getClientWithTransaction(e, t, r, i, s, n) {
2413
2413
  let c = [], d = this.dbPool.parameters(), f = [], y = `select c.*, r.uri as uri, null as flow from ${this.clientTable} as c left join ${this.redirectUriTable} r on c.client_id = r.client_id `, C = "";
2414
2414
  t && r && (C = `where c.${t} = ` + d.nextParameter(), f.push(r)), i !== null && i == null || (C == "" ? C = "where " : C += " and ", i == null ? C += "userid is null" : (C += `${this.useridForeignKeyColumn} = ` + d.nextParameter(), f.push(i)));
2415
- let v = `select c.*, null as uri, f.flow as flow from ${this.clientTable} as c left join ${this.validFlowTable} f on c.client_id = f.client_id `, p = "";
2416
- t && r && (p = `where c.${t} = ` + d.nextParameter(), f.push(r)), i !== null && i == null || (p == "" ? p = "where " : p += " and ", i == null ? p += "userid is null" : (p += `${this.useridForeignKeyColumn} = ` + d.nextParameter(), f.push(i))), n && (s || (s = 0), s = Number(s), n = Number(n), C == "" ? C = "where " : C += " and ", C += ` c.client_id in (select client_id from ${this.clientTable} limit ${n} offset ${s})`, p == "" ? p = "where " : p += " and ", p += ` c.client_id in (select client_id from ${this.clientTable} limit ${n} offset ${s})`), y += C, v += p;
2417
- let T = y + " union " + v + " order by client_id";
2418
- const E = await e.execute(T, f);
2419
- let A;
2420
- for (let j of E)
2421
- (!A || j.client_id != A.client_id) && (A && c.push(A), A = this.makeClient(j), A.valid_flow = [], A.redirect_uri = []), j.uri && A.redirect_uri.push(j.uri), j.flow && A.valid_flow.push(j.flow);
2422
- return A && c.push(A), c;
2415
+ let _ = `select c.*, null as uri, f.flow as flow from ${this.clientTable} as c left join ${this.validFlowTable} f on c.client_id = f.client_id `, p = "";
2416
+ t && r && (p = `where c.${t} = ` + d.nextParameter(), f.push(r)), i !== null && i == null || (p == "" ? p = "where " : p += " and ", i == null ? p += "userid is null" : (p += `${this.useridForeignKeyColumn} = ` + d.nextParameter(), f.push(i))), n && (s || (s = 0), s = Number(s), n = Number(n), C == "" ? C = "where " : C += " and ", C += ` c.client_id in (select client_id from ${this.clientTable} limit ${n} offset ${s})`, p == "" ? p = "where " : p += " and ", p += ` c.client_id in (select client_id from ${this.clientTable} limit ${n} offset ${s})`), y += C, _ += p;
2417
+ let T = y + " union " + _ + " order by client_id";
2418
+ const v = await e.execute(T, f);
2419
+ let b;
2420
+ for (let M of v)
2421
+ (!b || M.client_id != b.client_id) && (b && c.push(b), b = this.makeClient(M), b.valid_flow = [], b.redirect_uri = []), M.uri && b.redirect_uri.push(M.uri), M.flow && b.valid_flow.push(M.flow);
2422
+ return b && c.push(b), c;
2423
2423
  }
2424
2424
  /**
2425
2425
  * Saves a key in the session table.
@@ -2453,7 +2453,7 @@ class et extends ye {
2453
2453
  }
2454
2454
  if (i) {
2455
2455
  for (let p = 0; p < i.length; ++p)
2456
- if (!U.isValidFlow(i[p])) throw new o(l.InvalidOAuthFlow, "Invalid flow " + i[p]);
2456
+ if (!I.isValidFlow(i[p])) throw new o(l.InvalidOAuthFlow, "Invalid flow " + i[p]);
2457
2457
  }
2458
2458
  let c = [], d = [], f = [], y = this.dbPool.parameters();
2459
2459
  try {
@@ -2461,8 +2461,8 @@ class et extends ye {
2461
2461
  c.push(p), d.push(y.nextParameter()), f.push(n[p]);
2462
2462
  if (c.length > 0) {
2463
2463
  let p = c.join(", "), T = d.join(", ");
2464
- const E = `insert into ${this.clientTable} (${p}) values (${T})`;
2465
- await e.execute(E, f);
2464
+ const v = `insert into ${this.clientTable} (${p}) values (${T})`;
2465
+ await e.execute(v, f);
2466
2466
  }
2467
2467
  } catch (p) {
2468
2468
  throw typeof p == "object" && p != null && "code" in p && typeof p.code == "string" && (p.code.startsWith("22") || p.code.startsWith("23")) ? (h.logger.debug(m({ err: p })), new o(l.InvalidClientId, "Attempt to create an OAuth client with a client_id that already exists. Maximum attempts failed")) : (h.logger.debug(m({ err: p })), new o(l.Connection, "Error saving OAuth client"));
@@ -2470,20 +2470,20 @@ class et extends ye {
2470
2470
  let C = await this.getClientWithTransaction(e, "client_id", t.client_id, t.userid);
2471
2471
  if (C.length == 0)
2472
2472
  throw h.logger.error(m({ msg: "Attempt to create key that already exists. Stack trace follows" })), new o(l.KeyExists);
2473
- let v = C[0];
2473
+ let _ = C[0];
2474
2474
  if (r)
2475
2475
  for (let p = 0; p < r.length; ++p) {
2476
2476
  f = [], y = this.dbPool.parameters();
2477
2477
  let T = `insert into ${this.redirectUriTable} (client_id, uri) values (` + y.nextParameter() + ", " + y.nextParameter() + ")";
2478
- f.push(v.client_id), f.push(r[p]), await e.execute(T, f);
2478
+ f.push(_.client_id), f.push(r[p]), await e.execute(T, f);
2479
2479
  }
2480
2480
  if (i)
2481
2481
  for (let p = 0; p < i.length; ++p) {
2482
2482
  f = [], y = this.dbPool.parameters();
2483
2483
  let T = `insert into ${this.validFlowTable} (client_id, flow) values (` + y.nextParameter() + ", " + y.nextParameter() + ")";
2484
- f.push(v.client_id), f.push(i[p]), await e.execute(T, f);
2484
+ f.push(_.client_id), f.push(i[p]), await e.execute(T, f);
2485
2485
  }
2486
- return { ...v, redirect_uri: r, valid_flow: i };
2486
+ return { ..._, redirect_uri: r, valid_flow: i };
2487
2487
  }
2488
2488
  /**
2489
2489
  *
@@ -2538,32 +2538,32 @@ class et extends ye {
2538
2538
  }
2539
2539
  if (i) {
2540
2540
  for (let T = 0; T < i.length; ++T)
2541
- if (!U.isValidFlow(i[T])) throw new o(l.InvalidOAuthFlow, "Redirect Uri's may not contain page fragments");
2541
+ if (!I.isValidFlow(i[T])) throw new o(l.InvalidOAuthFlow, "Redirect Uri's may not contain page fragments");
2542
2542
  }
2543
2543
  if (!t.client_id) throw new o(l.InvalidClientId, "No client ig given");
2544
2544
  let { client_id: s, redirect_uri: n, valid_flow: c, ...d } = t;
2545
2545
  n || (n = []), c || (c = []);
2546
2546
  let f = this.dbPool.parameters(), y = `delete from ${this.redirectUriTable} where client_id = ` + f.nextParameter();
2547
2547
  await e.execute(y, [t.client_id]), f = this.dbPool.parameters(), y = `delete from ${this.validFlowTable} where client_id = ` + f.nextParameter(), await e.execute(y, [t.client_id]);
2548
- let C = [], v = [], p = [];
2548
+ let C = [], _ = [], p = [];
2549
2549
  f = this.dbPool.parameters(), y = `delete from ${this.validFlowTable} where client_id = ` + f.nextParameter();
2550
2550
  for (let T in d)
2551
- C.push(T), v.push(f.nextParameter()), p.push(d[T]);
2551
+ C.push(T), _.push(f.nextParameter()), p.push(d[T]);
2552
2552
  if (C.length > 0) {
2553
- let T = C.join(", "), E = v.join(", ");
2554
- y = `update ${this.clientTable} set (${T}) values (${E})`, await e.execute(y, p);
2553
+ let T = C.join(", "), v = _.join(", ");
2554
+ y = `update ${this.clientTable} set (${T}) values (${v})`, await e.execute(y, p);
2555
2555
  }
2556
2556
  if (n)
2557
2557
  for (let T = 0; T < n.length; ++T) {
2558
2558
  p = [], f = this.dbPool.parameters();
2559
- let E = `insert into ${this.redirectUriTable} (client_id, uri) values (` + f.nextParameter() + ", " + f.nextParameter() + ")";
2560
- p.push(t.client_id), p.push(n[T]), await e.execute(E, p);
2559
+ let v = `insert into ${this.redirectUriTable} (client_id, uri) values (` + f.nextParameter() + ", " + f.nextParameter() + ")";
2560
+ p.push(t.client_id), p.push(n[T]), await e.execute(v, p);
2561
2561
  }
2562
2562
  if (c)
2563
2563
  for (let T = 0; T < c.length; ++T) {
2564
2564
  p = [], f = this.dbPool.parameters();
2565
- let E = `insert into ${this.validFlowTable} (client_id, flow) values (` + f.nextParameter() + ", " + f.nextParameter() + ")";
2566
- p.push(t.client_id), p.push(c[T]), await e.execute(E, p);
2565
+ let v = `insert into ${this.validFlowTable} (client_id, flow) values (` + f.nextParameter() + ", " + f.nextParameter() + ")";
2566
+ p.push(t.client_id), p.push(c[T]), await e.execute(v, p);
2567
2567
  }
2568
2568
  }
2569
2569
  async getClients(e, t, r) {
@@ -2579,7 +2579,7 @@ class et extends ye {
2579
2579
  }
2580
2580
  }
2581
2581
  }
2582
- class tt extends pe {
2582
+ class ct extends Ee {
2583
2583
  /**
2584
2584
  * Constructor with user storage object to use plus optional parameters.
2585
2585
  *
@@ -2620,17 +2620,17 @@ class tt extends pe {
2620
2620
  }
2621
2621
  }
2622
2622
  }
2623
- class rt {
2623
+ class dt {
2624
2624
  constructor() {
2625
2625
  }
2626
2626
  }
2627
- class it {
2627
+ class ut {
2628
2628
  constructor() {
2629
2629
  }
2630
2630
  }
2631
- class at {
2631
+ class ht {
2632
2632
  }
2633
- class he extends rt {
2633
+ class Ce extends dt {
2634
2634
  constructor(e) {
2635
2635
  super();
2636
2636
  u(this, "pgPool");
@@ -2638,13 +2638,13 @@ class he extends rt {
2638
2638
  }
2639
2639
  async connect() {
2640
2640
  const e = await this.pgPool.connect();
2641
- return h.logger.debug(m({ msg: "DB connect" })), new st(e);
2641
+ return h.logger.debug(m({ msg: "DB connect" })), new mt(e);
2642
2642
  }
2643
2643
  parameters() {
2644
- return new nt();
2644
+ return new ft();
2645
2645
  }
2646
2646
  }
2647
- class st extends at {
2647
+ class mt extends ht {
2648
2648
  constructor(e) {
2649
2649
  super();
2650
2650
  u(this, "pgClient");
@@ -2679,7 +2679,7 @@ class st extends at {
2679
2679
  h.logger.debug(m({ msg: "DB rollback" })), await this.pgClient.query("ROLLBACK");
2680
2680
  }
2681
2681
  }
2682
- class nt extends it {
2682
+ class ft extends ut {
2683
2683
  constructor() {
2684
2684
  super();
2685
2685
  u(this, "nextParam", 1);
@@ -2688,47 +2688,47 @@ class nt extends it {
2688
2688
  return "$" + this.nextParam++;
2689
2689
  }
2690
2690
  }
2691
- class Lt extends Y {
2691
+ class Wt extends te {
2692
2692
  /**
2693
2693
  * Creates a PostgresUserStorage object, optionally overriding defaults.
2694
2694
  * @param pgPool the instance of the Posrgres client.
2695
2695
  * @param options see {@link PostgresUserStorageOptions}.
2696
2696
  */
2697
2697
  constructor(a, e = {}) {
2698
- super(new he(a), e);
2698
+ super(new Ce(a), e);
2699
2699
  }
2700
2700
  }
2701
- class jt extends Qe {
2701
+ class Jt extends ot {
2702
2702
  /**
2703
2703
  * Creates a PostgresKeyStorage object, optionally overriding defaults.
2704
2704
  * @param pgPool the instance of the Posrgres client.
2705
2705
  * @param options see {@link PostgresKeyStorageOptions}.
2706
2706
  */
2707
2707
  constructor(a, e = {}) {
2708
- super(new he(a), e);
2708
+ super(new Ce(a), e);
2709
2709
  }
2710
2710
  }
2711
- class Ht extends et {
2711
+ class Yt extends lt {
2712
2712
  /**
2713
2713
  * Creates a PostgresOAuthClientStorage object, optionally overriding defaults.
2714
2714
  * @param pgPool the instance of the Posrgres client.
2715
2715
  * @param options see {@link PostgresOAuthClientStorageOptions}.
2716
2716
  */
2717
2717
  constructor(a, e = {}) {
2718
- super(new he(a), e);
2718
+ super(new Ce(a), e);
2719
2719
  }
2720
2720
  }
2721
- class Vt extends tt {
2721
+ class Gt extends ct {
2722
2722
  /**
2723
2723
  * Creates a PostgresOAuthClientStorage object, optionally overriding defaults.
2724
2724
  * @param pgPool the instance of the Posrgres client.
2725
2725
  * @param options see {@link PostgresOAuthAuthorizationStorageOptions}.
2726
2726
  */
2727
2727
  constructor(a, e = {}) {
2728
- super(new he(a), e);
2728
+ super(new Ce(a), e);
2729
2729
  }
2730
2730
  }
2731
- class ae {
2731
+ class de {
2732
2732
  // overridden when registered to backend
2733
2733
  /**
2734
2734
  * Constructor.
@@ -2755,7 +2755,7 @@ class ae {
2755
2755
  return !0;
2756
2756
  }
2757
2757
  }
2758
- class Ie extends ae {
2758
+ class Re extends de {
2759
2759
  /** @returns `password` */
2760
2760
  secretNames() {
2761
2761
  return ["password"];
@@ -2773,7 +2773,7 @@ class Ie extends ae {
2773
2773
  return "none";
2774
2774
  }
2775
2775
  }
2776
- const ve = process.env.PBKDF2_DIGEST || "sha256", _e = Number(process.env.PBKDF2_ITERATIONS || 6e5), ke = Number(process.env.PBKDF2_KEYLENGTH || 32), ot = Number(process.env.PBKDF2_KEYLENGTH || 16), ne = "sha256", q = class q {
2776
+ const Ie = process.env.PBKDF2_DIGEST || "sha256", Pe = Number(process.env.PBKDF2_ITERATIONS || 6e5), Oe = Number(process.env.PBKDF2_KEYLENGTH || 32), gt = Number(process.env.PBKDF2_KEYLENGTH || 16), me = "sha256", G = class G {
2777
2777
  /**
2778
2778
  * Returns true if the plaintext password, when hashed, equals the one in the hash, using
2779
2779
  * it's hasher settings
@@ -2783,7 +2783,7 @@ const ve = process.env.PBKDF2_DIGEST || "sha256", _e = Number(process.env.PBKDF2
2783
2783
  * @returns true if they are equal, false otherwise
2784
2784
  */
2785
2785
  static async passwordsEqual(a, e, t) {
2786
- let r = q.decodePasswordHash(e), i = await q.passwordHash(a, {
2786
+ let r = G.decodePasswordHash(e), i = await G.passwordHash(a, {
2787
2787
  salt: r.salt,
2788
2788
  encode: !1,
2789
2789
  secret: r.useSecret ? t : void 0,
@@ -2793,7 +2793,7 @@ const ve = process.env.PBKDF2_DIGEST || "sha256", _e = Number(process.env.PBKDF2
2793
2793
  });
2794
2794
  if (i.length != r.hashedPassword.length)
2795
2795
  throw new o(l.PasswordInvalid);
2796
- return me(Buffer.from(i), Buffer.from(r.hashedPassword));
2796
+ return Se(Buffer.from(i), Buffer.from(r.hashedPassword));
2797
2797
  }
2798
2798
  /**
2799
2799
  * Decodes a string from base64 to UTF-89
@@ -2861,7 +2861,7 @@ const ve = process.env.PBKDF2_DIGEST || "sha256", _e = Number(process.env.PBKDF2
2861
2861
  * @returns random salt as a base64 encoded string
2862
2862
  */
2863
2863
  static randomSalt() {
2864
- return q.randomValue(ot);
2864
+ return G.randomValue(gt);
2865
2865
  }
2866
2866
  /**
2867
2867
  * Creates a random string encoded as in base64url
@@ -2869,7 +2869,7 @@ const ve = process.env.PBKDF2_DIGEST || "sha256", _e = Number(process.env.PBKDF2
2869
2869
  * @returns the random value as a string. Number of bytes will be greater as it is base64 encoded.
2870
2870
  */
2871
2871
  static randomValue(a) {
2872
- return fe(a).toString("base64url");
2872
+ return Te(a).toString("base64url");
2873
2873
  }
2874
2874
  // not real base32 - omits 1,i,0,o
2875
2875
  /**
@@ -2879,14 +2879,14 @@ const ve = process.env.PBKDF2_DIGEST || "sha256", _e = Number(process.env.PBKDF2
2879
2879
  */
2880
2880
  static randomBase32(a, e) {
2881
2881
  var i;
2882
- const r = [...fe(a)].map((s) => q.Base32[s % 32]).join("");
2882
+ const r = [...Te(a)].map((s) => G.Base32[s % 32]).join("");
2883
2883
  return e ? ((i = r.match(/(.{1,4})/g)) == null ? void 0 : i.join("-")) ?? r : r;
2884
2884
  }
2885
2885
  /**
2886
2886
  * Creates a UUID
2887
2887
  */
2888
2888
  static uuid() {
2889
- return Re();
2889
+ return $e();
2890
2890
  }
2891
2891
  /**
2892
2892
  * Standard hash using SHA256 (not PBKDF2 or HMAC)
@@ -2904,7 +2904,7 @@ const ve = process.env.PBKDF2_DIGEST || "sha256", _e = Number(process.env.PBKDF2
2904
2904
  * @returns the string containing the hash
2905
2905
  */
2906
2906
  static sha256(a) {
2907
- return Be("sha256").update(a).digest("base64url");
2907
+ return qe("sha256").update(a).digest("base64url");
2908
2908
  }
2909
2909
  /**
2910
2910
  * Hashes a password and returns it as a base64 or base64url encoded string
@@ -2917,23 +2917,23 @@ const ve = process.env.PBKDF2_DIGEST || "sha256", _e = Number(process.env.PBKDF2
2917
2917
  */
2918
2918
  static async passwordHash(a, e = {}) {
2919
2919
  let { salt: t, secret: r, encode: i } = { ...e };
2920
- t || (t = q.randomSalt());
2920
+ t || (t = G.randomSalt());
2921
2921
  let s = r != null, n = s ? t + "!" + r : t;
2922
2922
  i == null && (i = !1);
2923
- let f = (await He(ze)(
2923
+ let f = (await Ge(We)(
2924
2924
  a,
2925
2925
  n,
2926
- e.iterations ?? _e,
2927
- e.keyLen ?? ke,
2928
- e.digest ?? ve
2926
+ e.iterations ?? Pe,
2927
+ e.keyLen ?? Oe,
2928
+ e.digest ?? Ie
2929
2929
  )).toString("base64url");
2930
2930
  return i && (f = this.encodePasswordHash(
2931
2931
  f,
2932
2932
  t,
2933
2933
  s,
2934
- e.iterations ?? _e,
2935
- e.keyLen ?? ke,
2936
- e.digest ?? ve
2934
+ e.iterations ?? Pe,
2935
+ e.keyLen ?? Oe,
2936
+ e.digest ?? Ie
2937
2937
  )), f;
2938
2938
  }
2939
2939
  /**
@@ -2946,7 +2946,7 @@ const ve = process.env.PBKDF2_DIGEST || "sha256", _e = Number(process.env.PBKDF2
2946
2946
  * @returns a Base64-URL-encoded string that can be hashed.
2947
2947
  */
2948
2948
  static signableToken(a, e, t) {
2949
- return e == null && (e = q.randomSalt()), t || (t = (/* @__PURE__ */ new Date()).getTime()), Buffer.from(JSON.stringify({ ...a, t, s: e })).toString("base64url");
2949
+ return e == null && (e = G.randomSalt()), t || (t = (/* @__PURE__ */ new Date()).getTime()), Buffer.from(JSON.stringify({ ...a, t, s: e })).toString("base64url");
2950
2950
  }
2951
2951
  /**
2952
2952
  * Signs a JSON payload by creating a hash, using a secret and
@@ -2959,7 +2959,7 @@ const ve = process.env.PBKDF2_DIGEST || "sha256", _e = Number(process.env.PBKDF2
2959
2959
  * @returns Base64-url encoded hash
2960
2960
  */
2961
2961
  static sign(a, e, t, r) {
2962
- const i = q.signableToken(a, t, r), s = se(ne, e);
2962
+ const i = G.signableToken(a, t, r), s = he(me, e);
2963
2963
  return i + "." + s.update(i).digest("base64url");
2964
2964
  }
2965
2965
  /**
@@ -2972,7 +2972,7 @@ const ve = process.env.PBKDF2_DIGEST || "sha256", _e = Number(process.env.PBKDF2
2972
2972
  * @returns Base64-url encoded hash
2973
2973
  */
2974
2974
  static signSecureToken(a, e) {
2975
- const t = se(ne, e);
2975
+ const t = he(me, e);
2976
2976
  return a + "." + t.update(a).digest("base64url");
2977
2977
  }
2978
2978
  /**
@@ -2991,10 +2991,10 @@ const ve = process.env.PBKDF2_DIGEST || "sha256", _e = Number(process.env.PBKDF2
2991
2991
  const i = r[0], s = r[1], n = JSON.parse(Buffer.from(i, "base64url").toString());
2992
2992
  if (t && n.t + t * 1e3 > (/* @__PURE__ */ new Date()).getTime())
2993
2993
  throw new o(l.Expired);
2994
- const d = se(ne, e).update(i).digest("base64url");
2994
+ const d = he(me, e).update(i).digest("base64url");
2995
2995
  if (d.length != s.length)
2996
2996
  throw new o(l.InvalidKey, "Signature does not match payload");
2997
- if (!me(Buffer.from(d), Buffer.from(s)))
2997
+ if (!Se(Buffer.from(d), Buffer.from(s)))
2998
2998
  throw new o(l.InvalidKey, "Signature does not match payload");
2999
2999
  return n;
3000
3000
  }
@@ -3011,10 +3011,10 @@ const ve = process.env.PBKDF2_DIGEST || "sha256", _e = Number(process.env.PBKDF2
3011
3011
  static unsignSecureToken(a, e) {
3012
3012
  const t = a.split(".");
3013
3013
  if (t.length != 2) throw new o(l.InvalidKey);
3014
- const r = t[0], i = t[1], s = r, c = se(ne, e).update(r).digest("base64url");
3014
+ const r = t[0], i = t[1], s = r, c = he(me, e).update(r).digest("base64url");
3015
3015
  if (c.length != i.length)
3016
3016
  throw new o(l.InvalidKey, "Signature does not match payload");
3017
- if (!me(Buffer.from(c), Buffer.from(i)))
3017
+ if (!Se(Buffer.from(c), Buffer.from(i)))
3018
3018
  throw new o(l.InvalidKey, "Signature does not match payload");
3019
3019
  return s;
3020
3020
  }
@@ -3036,9 +3036,9 @@ const ve = process.env.PBKDF2_DIGEST || "sha256", _e = Number(process.env.PBKDF2
3036
3036
  * @returns Encrypted text Base64-url encoded.
3037
3037
  */
3038
3038
  static symmetricEncrypt(a, e, t = void 0) {
3039
- t || (t = fe(16));
3039
+ t || (t = Te(16));
3040
3040
  let r = Buffer.from(e, "base64url");
3041
- var i = Le("aes-256-cbc", r, t);
3041
+ var i = Je("aes-256-cbc", r, t);
3042
3042
  let s = i.update(a);
3043
3043
  return s = Buffer.concat([s, i.final()]), t.toString("base64url") + "." + s.toString("base64url");
3044
3044
  }
@@ -3054,14 +3054,14 @@ const ve = process.env.PBKDF2_DIGEST || "sha256", _e = Number(process.env.PBKDF2
3054
3054
  const r = a.split(".");
3055
3055
  if (r.length != 2) throw new o(l.InvalidHash, "Not AES-256-CBC ciphertext");
3056
3056
  let i = Buffer.from(r[0], "base64url"), s = Buffer.from(r[1], "base64url");
3057
- var n = je("aes-256-cbc", t, i);
3057
+ var n = Ye("aes-256-cbc", t, i);
3058
3058
  let c = n.update(s);
3059
3059
  return c = Buffer.concat([c, n.final()]), c.toString();
3060
3060
  }
3061
3061
  };
3062
- u(q, "Base32", "ABCDEFGHJKLMNPQRSTUVWXYZ23456789".split(""));
3063
- let _ = q;
3064
- function lt(S) {
3062
+ u(G, "Base32", "ABCDEFGHJKLMNPQRSTUVWXYZ23456789".split(""));
3063
+ let k = G;
3064
+ function wt(S) {
3065
3065
  let a = [];
3066
3066
  if (!S.password) a.push("Password not provided");
3067
3067
  else {
@@ -3070,7 +3070,7 @@ function lt(S) {
3070
3070
  }
3071
3071
  return a;
3072
3072
  }
3073
- const ce = class ce extends Ie {
3073
+ const we = class we extends Re {
3074
3074
  /**
3075
3075
  * Create a new authenticator.
3076
3076
  *
@@ -3093,7 +3093,7 @@ const ce = class ce extends Ie {
3093
3093
  /** See {@link LocalPasswordAuthenticatorOptions.pbkdf2KeyLength} */
3094
3094
  u(this, "pbkdf2KeyLength", 32);
3095
3095
  /** See {@link LocalPasswordAuthenticatorOptions.validatePasswordFn} */
3096
- u(this, "validatePasswordFn", lt);
3096
+ u(this, "validatePasswordFn", wt);
3097
3097
  w("secret", g.String, this, t, "HASHER_SECRET"), w("enableSecretForPasswordHash", g.Boolean, this, t, "ENABLE_SECRET_FOR_PASSWORDS"), w("pbkdf2Digest", g.String, this, t, "PASSWORD_PBKDF2_DIGEST"), w("pbkdf2Iterations", g.String, this, t, "PASSWORD_PBKDF2_ITERATIONS"), w("pbkdf2SaltLength", g.String, this, t, "PASSWORD_PBKDF2_SALTLENGTH"), w("pbkdf2KeyLength", g.String, this, t, "PASSWORD_PBKDF2_KEYLENGTH"), t.validatePasswordFn && (this.validatePasswordFn = t.validatePasswordFn);
3098
3098
  }
3099
3099
  /**
@@ -3114,11 +3114,11 @@ const ce = class ce extends Ie {
3114
3114
  async authenticateUser(e, t, r) {
3115
3115
  if (!r.password) throw new o(l.PasswordInvalid, "Password not provided");
3116
3116
  if (!t.password) throw new o(l.PasswordInvalid);
3117
- if (!await _.passwordsEqual(r.password, t.password, this.secret))
3117
+ if (!await k.passwordsEqual(r.password, t.password, this.secret))
3118
3118
  throw h.logger.debug(m({ msg: "Invalid password hash", user: e.username })), new o(l.PasswordInvalid);
3119
- if (e.state == k.awaitingTwoFactorSetup) throw new o(l.TwoFactorIncomplete);
3120
- if (e.state == k.awaitingEmailVerification) throw new o(l.EmailNotVerified);
3121
- if (e.state == k.disabled) throw new o(l.UserNotActive);
3119
+ if (e.state == E.awaitingTwoFactorSetup) throw new o(l.TwoFactorIncomplete);
3120
+ if (e.state == E.awaitingEmailVerification) throw new o(l.EmailNotVerified);
3121
+ if (e.state == E.disabled) throw new o(l.UserNotActive);
3122
3122
  }
3123
3123
  /**
3124
3124
  * Calls the implementor-provided `validatePasswordFn`
@@ -3144,7 +3144,7 @@ const ce = class ce extends Ie {
3144
3144
  * @returns the encoded hash string.
3145
3145
  */
3146
3146
  async createPasswordHash(e, t, r = !0) {
3147
- return await _.passwordHash(e, {
3147
+ return await k.passwordHash(e, {
3148
3148
  salt: t,
3149
3149
  encode: r,
3150
3150
  secret: this.enableSecretForPasswords ? this.secret : void 0,
@@ -3169,7 +3169,7 @@ const ce = class ce extends Ie {
3169
3169
  * @returns true if match, false otherwise
3170
3170
  */
3171
3171
  async passwordMatchesHash(e, t, r) {
3172
- return t == ce.NoPassword ? !1 : await _.passwordsEqual(e, t, r);
3172
+ return t == we.NoPassword ? !1 : await k.passwordsEqual(e, t, r);
3173
3173
  }
3174
3174
  /**
3175
3175
  * This will return p hash of the passed password.
@@ -3226,9 +3226,9 @@ const ce = class ce extends Ie {
3226
3226
  async reprepareConfiguration(e, t) {
3227
3227
  }
3228
3228
  };
3229
- u(ce, "NoPassword", "********");
3230
- let Ee = ce;
3231
- class X extends ae {
3229
+ u(we, "NoPassword", "********");
3230
+ let Ke = we;
3231
+ class ne extends de {
3232
3232
  /**
3233
3233
  * Constructor
3234
3234
  *
@@ -3248,7 +3248,7 @@ class X extends ae {
3248
3248
  u(this, "smtpPassword");
3249
3249
  u(this, "emailAuthenticatorTokenExpires", 60 * 5);
3250
3250
  u(this, "render");
3251
- w("views", g.String, this, e, "VIEWS"), w("emailAuthenticatorTextBody", g.String, this, e, "EMAIL_AUTHENTICATOR_TEXT_BODY"), w("emailAuthenticatorHtmlBody", g.String, this, e, "EMAIL_AUTHENTICATOR_HTML_BODY"), w("emailAuthenticatorSubject", g.String, this, e, "EMAIL_AUTHENTICATOR_SUBJECT"), w("emailFrom", g.String, this, e, "EMAIL_FROM", !0), w("smtpHost", g.String, this, e, "SMTP_HOST", !0), w("smtpPort", g.Number, this, e, "SMTP_PORT"), w("smtpUsername", g.String, this, e, "SMTP_USERNAME"), w("smtpPassword", g.String, this, e, "SMTP_PASSWORD"), w("smtpUseTls", g.Boolean, this, e, "SMTP_USE_TLS"), w("emailAuthenticatorTokenExpires", g.Number, this, e, "EMAIL_AUTHENTICATOR_TOKEN_EXPIRES"), e.render ? this.render = e.render : W.configure(this.views, { autoescape: !0 });
3251
+ w("views", g.String, this, e, "VIEWS"), w("emailAuthenticatorTextBody", g.String, this, e, "EMAIL_AUTHENTICATOR_TEXT_BODY"), w("emailAuthenticatorHtmlBody", g.String, this, e, "EMAIL_AUTHENTICATOR_HTML_BODY"), w("emailAuthenticatorSubject", g.String, this, e, "EMAIL_AUTHENTICATOR_SUBJECT"), w("emailFrom", g.String, this, e, "EMAIL_FROM", !0), w("smtpHost", g.String, this, e, "SMTP_HOST", !0), w("smtpPort", g.Number, this, e, "SMTP_PORT"), w("smtpUsername", g.String, this, e, "SMTP_USERNAME"), w("smtpPassword", g.String, this, e, "SMTP_PASSWORD"), w("smtpUseTls", g.Boolean, this, e, "SMTP_USE_TLS"), w("emailAuthenticatorTokenExpires", g.Number, this, e, "EMAIL_AUTHENTICATOR_TOKEN_EXPIRES"), e.render ? this.render = e.render : Z.configure(this.views, { autoescape: !0 });
3252
3252
  }
3253
3253
  /**
3254
3254
  * Used by the OAuth password_mfa grant type.
@@ -3264,7 +3264,7 @@ class X extends ae {
3264
3264
  }
3265
3265
  createEmailer() {
3266
3266
  let e = {};
3267
- return this.smtpUsername && (e.user = this.smtpUsername), this.smtpPassword && (e.pass = this.smtpPassword), Ae.createTransport({
3267
+ return this.smtpUsername && (e.user = this.smtpUsername), this.smtpPassword && (e.pass = this.smtpPassword), xe.createTransport({
3268
3268
  host: this.smtpHost,
3269
3269
  port: this.smtpPort,
3270
3270
  secure: this.smtpUseTls,
@@ -3272,13 +3272,13 @@ class X extends ae {
3272
3272
  });
3273
3273
  }
3274
3274
  async sendToken(e, t) {
3275
- X.validateEmail(e), this.smtpUsername && this.smtpUsername, this.smtpPassword && this.smtpPassword;
3275
+ ne.validateEmail(e), this.smtpUsername && this.smtpUsername, this.smtpPassword && this.smtpPassword;
3276
3276
  let r = {
3277
3277
  from: this.emailFrom,
3278
3278
  to: e,
3279
3279
  subject: this.emailAuthenticatorSubject
3280
3280
  }, i = { otp: t };
3281
- return this.emailAuthenticatorTextBody && (r.text = this.render ? this.render(this.emailAuthenticatorTextBody, i) : W.render(this.emailAuthenticatorTextBody, i)), this.emailAuthenticatorHtmlBody && (r.html = this.render ? this.render(this.emailAuthenticatorHtmlBody, i) : W.render(this.emailAuthenticatorHtmlBody, i)), (await this.createEmailer().sendMail(r)).messageId;
3281
+ return this.emailAuthenticatorTextBody && (r.text = this.render ? this.render(this.emailAuthenticatorTextBody, i) : Z.render(this.emailAuthenticatorTextBody, i)), this.emailAuthenticatorHtmlBody && (r.html = this.render ? this.render(this.emailAuthenticatorHtmlBody, i) : Z.render(this.emailAuthenticatorHtmlBody, i)), (await this.createEmailer().sendMail(r)).messageId;
3282
3282
  }
3283
3283
  /**
3284
3284
  * Creates and emails the one-time code
@@ -3294,8 +3294,8 @@ class X extends ae {
3294
3294
  l.Configuration,
3295
3295
  "Please set factorName on EmailAuthenticator before using"
3296
3296
  );
3297
- const t = X.zeroPad(re(999999), 6), r = e.email ? e.email : e.username;
3298
- X.validateEmail(r);
3297
+ const t = ne.zeroPad(ce(999999), 6), r = e.email ? e.email : e.username;
3298
+ ne.validateEmail(r);
3299
3299
  const i = /* @__PURE__ */ new Date(), s = new Date(i.getTime() + 1e3 * this.emailAuthenticatorTokenExpires).getTime(), n = {
3300
3300
  username: e.username,
3301
3301
  email: r,
@@ -3320,7 +3320,7 @@ class X extends ae {
3320
3320
  * @returns
3321
3321
  */
3322
3322
  async reprepareConfiguration(e, t) {
3323
- const r = z.decodeData(t.data)["2fa"], i = X.zeroPad(re(999999), 6), s = /* @__PURE__ */ new Date(), n = new Date(s.getTime() + 1e3 * this.emailAuthenticatorTokenExpires).getTime(), c = this.sendToken(r.email, i);
3323
+ const r = V.decodeData(t.data)["2fa"], i = ne.zeroPad(ce(999999), 6), s = /* @__PURE__ */ new Date(), n = new Date(s.getTime() + 1e3 * this.emailAuthenticatorTokenExpires).getTime(), c = this.sendToken(r.email, i);
3324
3324
  return h.logger.info(m({
3325
3325
  msg: "Sent factor otp email",
3326
3326
  emailMessageId: c,
@@ -3365,7 +3365,7 @@ class X extends ae {
3365
3365
  * @returns `otp` and `expiry` as a Unix time (number).
3366
3366
  */
3367
3367
  async createOneTimeSecrets(e) {
3368
- const t = X.zeroPad(re(999999), 6), r = /* @__PURE__ */ new Date(), i = new Date(r.getTime() + 1e3 * this.emailAuthenticatorTokenExpires).getTime(), s = e.email || e.username, n = this.sendToken(s, t);
3368
+ const t = ne.zeroPad(ce(999999), 6), r = /* @__PURE__ */ new Date(), i = new Date(r.getTime() + 1e3 * this.emailAuthenticatorTokenExpires).getTime(), s = e.email || e.username, n = this.sendToken(s, t);
3369
3369
  return h.logger.info(m({
3370
3370
  msg: "Sent factor otp email",
3371
3371
  emailMessageId: n,
@@ -3431,7 +3431,7 @@ class X extends ae {
3431
3431
  * @throws {@link @crossauth/common!CrossauthError} with {@link @crossauth/common!ErrorCode} `InvalidEmail`.
3432
3432
  */
3433
3433
  static validateEmail(e) {
3434
- if (e == null || !X.isEmailValid(e))
3434
+ if (e == null || !ne.isEmailValid(e))
3435
3435
  throw new o(l.InvalidEmail);
3436
3436
  }
3437
3437
  /**
@@ -3445,7 +3445,7 @@ class X extends ae {
3445
3445
  return Array(+(r > 0 && r)).join("0") + e;
3446
3446
  }
3447
3447
  }
3448
- class ee extends ae {
3448
+ class le extends de {
3449
3449
  /**
3450
3450
  * Constructor
3451
3451
  * @param options see {@link SmsAuthenticatorOptions}
@@ -3457,7 +3457,7 @@ class ee extends ae {
3457
3457
  u(this, "smsAuthenticatorFrom", "");
3458
3458
  u(this, "smsAuthenticatorTokenExpires", 60 * 5);
3459
3459
  u(this, "render");
3460
- w("views", g.String, this, e, "VIEWS"), w("smsAuthenticatorBody", g.String, this, e, "SMS_AUTHENTICATOR_BODY"), w("smsAuthenticatorFrom", g.String, this, e, "SMS_AUTHENTICATOR_FROM", !0), w("smsAuthenticatorTokenExpires", g.Number, this, e, "SMS_AUTHENTICATOR_TOKEN_EXPIRES"), e.render ? this.render = e.render : W.configure(this.views, { autoescape: !0 });
3460
+ w("views", g.String, this, e, "VIEWS"), w("smsAuthenticatorBody", g.String, this, e, "SMS_AUTHENTICATOR_BODY"), w("smsAuthenticatorFrom", g.String, this, e, "SMS_AUTHENTICATOR_FROM", !0), w("smsAuthenticatorTokenExpires", g.Number, this, e, "SMS_AUTHENTICATOR_TOKEN_EXPIRES"), e.render ? this.render = e.render : Z.configure(this.views, { autoescape: !0 });
3461
3461
  }
3462
3462
  /**
3463
3463
  * Used by the OAuth password_mfa grant type.
@@ -3484,8 +3484,8 @@ class ee extends ae {
3484
3484
  l.Configuration,
3485
3485
  "Please set factorName on SmsAuthenticator before using"
3486
3486
  );
3487
- const t = ee.zeroPad(re(999999), 6), r = e.phone;
3488
- ee.validatePhone(r);
3487
+ const t = le.zeroPad(ce(999999), 6), r = e.phone;
3488
+ le.validatePhone(r);
3489
3489
  const i = /* @__PURE__ */ new Date(), s = new Date(i.getTime() + 1e3 * this.smsAuthenticatorTokenExpires).getTime(), n = {
3490
3490
  username: e.username,
3491
3491
  phone: r,
@@ -3498,7 +3498,7 @@ class ee extends ae {
3498
3498
  otp: t
3499
3499
  };
3500
3500
  let d = { otp: t };
3501
- const f = this.render ? this.render(this.smsAuthenticatorBody, d) : W.render(this.smsAuthenticatorBody, d), y = this.sendSms(r, f);
3501
+ const f = this.render ? this.render(this.smsAuthenticatorBody, d) : Z.render(this.smsAuthenticatorBody, d), y = this.sendSms(r, f);
3502
3502
  return h.logger.info(m({
3503
3503
  msg: "Sent factor otp sms",
3504
3504
  smsMessageId: y,
@@ -3512,7 +3512,7 @@ class ee extends ae {
3512
3512
  * @returns
3513
3513
  */
3514
3514
  async reprepareConfiguration(e, t) {
3515
- const r = z.decodeData(t.data)["2fa"], i = ee.zeroPad(re(999999), 6), s = /* @__PURE__ */ new Date(), n = new Date(s.getTime() + 1e3 * this.smsAuthenticatorTokenExpires).getTime(), c = this.sendSms(r.phone, i);
3515
+ const r = V.decodeData(t.data)["2fa"], i = le.zeroPad(ce(999999), 6), s = /* @__PURE__ */ new Date(), n = new Date(s.getTime() + 1e3 * this.smsAuthenticatorTokenExpires).getTime(), c = this.sendSms(r.phone, i);
3516
3516
  return h.logger.info(m({
3517
3517
  msg: "Sent factor otp sms",
3518
3518
  smsMessageId: c,
@@ -3556,7 +3556,7 @@ class ee extends ae {
3556
3556
  * @returns `otp` and `expiry` as a Unix time (number).
3557
3557
  */
3558
3558
  async createOneTimeSecrets(e) {
3559
- const t = ee.zeroPad(re(999999), 6), r = /* @__PURE__ */ new Date(), i = new Date(r.getTime() + 1e3 * this.smsAuthenticatorTokenExpires).getTime(), s = e.phone, n = this.sendSms(s, t);
3559
+ const t = le.zeroPad(ce(999999), 6), r = /* @__PURE__ */ new Date(), i = new Date(r.getTime() + 1e3 * this.smsAuthenticatorTokenExpires).getTime(), s = e.phone, n = this.sendSms(s, t);
3560
3560
  return h.logger.info(m({
3561
3561
  msg: "Sent factor otp sms",
3562
3562
  smsMessageId: n,
@@ -3624,7 +3624,7 @@ class ee extends ae {
3624
3624
  * {@link @crossauth/common!ErrorCode} `InvalidPhoneNumber`.
3625
3625
  */
3626
3626
  static validatePhone(e) {
3627
- if (e == null || !ee.isPhoneValid(e))
3627
+ if (e == null || !le.isPhoneValid(e))
3628
3628
  throw new o(l.InvalidPhoneNumber);
3629
3629
  }
3630
3630
  /**
@@ -3638,7 +3638,7 @@ class ee extends ae {
3638
3638
  return Array(+(r > 0 && r)).join("0") + e;
3639
3639
  }
3640
3640
  }
3641
- class Pe extends ee {
3641
+ class Be extends le {
3642
3642
  /**
3643
3643
  * Constructor
3644
3644
  *
@@ -3667,16 +3667,16 @@ class Pe extends ee {
3667
3667
  * @returns the send message ID
3668
3668
  */
3669
3669
  async sendSms(e, t) {
3670
- Pe.validatePhone(e);
3670
+ Be.validatePhone(e);
3671
3671
  let r = {
3672
3672
  from: this.smsAuthenticatorFrom,
3673
3673
  to: e,
3674
3674
  body: t
3675
3675
  };
3676
- return (await Ve(this.accountSid, this.authToken).messages.create(r)).sid;
3676
+ return (await Ze(this.accountSid, this.authToken).messages.create(r)).sid;
3677
3677
  }
3678
3678
  }
3679
- class Mt extends ae {
3679
+ class Zt extends de {
3680
3680
  /**
3681
3681
  * Constructor
3682
3682
  *
@@ -3731,7 +3731,7 @@ class Mt extends ae {
3731
3731
  * @returns
3732
3732
  */
3733
3733
  async reprepareConfiguration(e, t) {
3734
- const r = z.decodeData(t.data)["2fa"], i = this.code, s = /* @__PURE__ */ new Date(), n = new Date(s.getTime() + 1e3 * 60).getTime();
3734
+ const r = V.decodeData(t.data)["2fa"], i = this.code, s = /* @__PURE__ */ new Date(), n = new Date(s.getTime() + 1e3 * 60).getTime();
3735
3735
  return {
3736
3736
  userData: { factor2: r.factor2, otp: i },
3737
3737
  secrets: {},
@@ -3837,7 +3837,7 @@ class Mt extends ae {
3837
3837
  return Array(+(r > 0 && r)).join("0") + e;
3838
3838
  }
3839
3839
  }
3840
- class $t extends Ie {
3840
+ class Xt extends Re {
3841
3841
  /**
3842
3842
  * Create a new authenticator.
3843
3843
  *
@@ -3873,9 +3873,9 @@ class $t extends Ie {
3873
3873
  }
3874
3874
  else
3875
3875
  i = (await this.ldapStorage.getUserByUsername(e.username)).user;
3876
- if (i.state == k.awaitingTwoFactorSetup) throw new o(l.TwoFactorIncomplete);
3877
- if (i.state == k.awaitingEmailVerification) throw new o(l.EmailNotVerified);
3878
- if (i.state == k.disabled) throw new o(l.UserNotActive);
3876
+ if (i.state == E.awaitingTwoFactorSetup) throw new o(l.TwoFactorIncomplete);
3877
+ if (i.state == E.awaitingEmailVerification) throw new o(l.EmailNotVerified);
3878
+ if (i.state == E.disabled) throw new o(l.UserNotActive);
3879
3879
  } catch (s) {
3880
3880
  throw h.logger.debug(m({ err: s })), s;
3881
3881
  }
@@ -3938,7 +3938,7 @@ class $t extends Ie {
3938
3938
  async reprepareConfiguration(e, t) {
3939
3939
  }
3940
3940
  }
3941
- class qt extends ae {
3941
+ class Qt extends de {
3942
3942
  /**
3943
3943
  * Constructor
3944
3944
  * @param appName this forms part of the QR code that users scan into
@@ -3963,9 +3963,9 @@ class qt extends ae {
3963
3963
  return "none";
3964
3964
  }
3965
3965
  async createSecret(e, t) {
3966
- t || (t = ge.generateSecret());
3966
+ t || (t = _e.generateSecret());
3967
3967
  let r = "";
3968
- return await Me.toDataURL(ge.keyuri(e, this.appName, t)).then((i) => {
3968
+ return await Xe.toDataURL(_e.keyuri(e, this.appName, t)).then((i) => {
3969
3969
  r = i;
3970
3970
  }).catch((i) => {
3971
3971
  throw h.logger.debug(m({ err: i })), new o(
@@ -3975,7 +3975,7 @@ class qt extends ae {
3975
3975
  }), { qrUrl: r, secret: t };
3976
3976
  }
3977
3977
  async getSecretFromSession(e, t) {
3978
- let r = z.decodeData(t.data);
3978
+ let r = V.decodeData(t.data);
3979
3979
  if (r && r["2fa"] && (r = r["2fa"]), !("totpsecret" in r))
3980
3980
  throw new o(
3981
3981
  l.Unauthorized,
@@ -4048,7 +4048,7 @@ class qt extends ae {
4048
4048
  "TOTP secret or code not given"
4049
4049
  );
4050
4050
  const i = r.otp, s = t.totpsecret;
4051
- if (!ge.check(i, s))
4051
+ if (!_e.check(i, s))
4052
4052
  throw new o(
4053
4053
  l.InvalidToken,
4054
4054
  "Invalid TOTP code"
@@ -4118,8 +4118,112 @@ class qt extends ae {
4118
4118
  return !1;
4119
4119
  }
4120
4120
  }
4121
- const oe = 16;
4122
- class D {
4121
+ class er extends de {
4122
+ /** @returns empty array */
4123
+ secretNames() {
4124
+ return [];
4125
+ }
4126
+ /** @returns an empty array */
4127
+ transientSecretNames() {
4128
+ return [];
4129
+ }
4130
+ /** @returns `none` */
4131
+ mfaType() {
4132
+ return "none";
4133
+ }
4134
+ /** @returns `none` */
4135
+ mfaChannel() {
4136
+ return "none";
4137
+ }
4138
+ /**
4139
+ * Create a new authenticator.
4140
+ *
4141
+ * See crypto.pbkdf2 for more information on the optional parameters.
4142
+ *
4143
+ * @param _userStorage ignored
4144
+ * @param options see {@link LocalPasswordAuthenticatorOptions}
4145
+ */
4146
+ constructor(a, e = {}) {
4147
+ super({ friendlyName: "OIDC", ...e });
4148
+ }
4149
+ /**
4150
+ * Authenticates the user, returning a the user as a {@link User} object.
4151
+ *
4152
+ * If you set `extraFields` when constructing the {@link UserStorage} instance passed to the constructor,
4153
+ * these will be included in the returned User object. `hashedPassword`, if present in the User object,
4154
+ * will be removed.
4155
+ *
4156
+ * @param user the `username` field should contain the username
4157
+ * @param secrets from the `UserSecrets` table. `password` is expected to be present
4158
+ * @param params the user input. `password` is expected to be present
4159
+ * @throws {@link @crossauth/common!CrossauthError} with
4160
+ * {@link @crossauth/common!ErrorCode} of `Connection`,
4161
+ * `UserNotExist`or `PasswordInvalid`, `TwoFactorIncomplete`,
4162
+ * `EmailNotVerified` or `UserNotActive`.
4163
+ */
4164
+ async authenticateUser(a, e, t) {
4165
+ throw new o(l.PasswordInvalid, "Please use OpenID Connect to log in");
4166
+ }
4167
+ /**
4168
+ * This will return p hash of the passed password.
4169
+ * @param _username ignored
4170
+ * @param params expected to contain `password`
4171
+ * @param repeatParams if defined, this is expected to also contain
4172
+ * `password` and is checked to match the one in `params`
4173
+ * @returns the newly created password in the `password` field.
4174
+ */
4175
+ async createPersistentSecrets(a, e, t) {
4176
+ return {};
4177
+ }
4178
+ /**
4179
+ * Does nothing for this class.
4180
+ */
4181
+ async createOneTimeSecrets(a) {
4182
+ return {};
4183
+ }
4184
+ /**
4185
+ * @returns true - this class can create users
4186
+ */
4187
+ canCreateUser() {
4188
+ return !0;
4189
+ }
4190
+ /**
4191
+ * @returns true - this class can update users
4192
+ */
4193
+ canUpdateUser() {
4194
+ return !0;
4195
+ }
4196
+ /**
4197
+ * @returns true - users can update secrets
4198
+ */
4199
+ canUpdateSecrets() {
4200
+ return !0;
4201
+ }
4202
+ /**
4203
+ * @returns false, if email verification is enabled, it should be for this authenticator too
4204
+ */
4205
+ skipEmailVerificationOnSignup() {
4206
+ return !1;
4207
+ }
4208
+ /**
4209
+ * Does nothing for this class.
4210
+ */
4211
+ async prepareConfiguration(a) {
4212
+ }
4213
+ /**
4214
+ * Does nothing for this class.
4215
+ */
4216
+ async reprepareConfiguration(a, e) {
4217
+ }
4218
+ /**
4219
+ * Does nothing for this class
4220
+ */
4221
+ validateSecrets(a) {
4222
+ return [];
4223
+ }
4224
+ }
4225
+ const fe = 16;
4226
+ class L {
4123
4227
  /**
4124
4228
  * Construct a new EmailVerifier.
4125
4229
  *
@@ -4150,11 +4254,11 @@ class D {
4150
4254
  u(this, "verifyEmailExpires", 60 * 60 * 24);
4151
4255
  u(this, "passwordResetExpires", 60 * 60 * 24);
4152
4256
  u(this, "render");
4153
- this.userStorage = a, this.keyStorage = e, w("siteUrl", g.String, this, t, "SITE_URL", !0), w("prefix", g.String, this, t, "PREFIX"), w("views", g.String, this, t, "VIEWS"), w("emailVerificationTextBody", g.String, this, t, "EMAIL_VERIFICATION_TEXT_BODY"), w("emailVerificationHtmlBody", g.String, this, t, "EMAIL_VERIFICATION_HTML_BODY"), w("emailVerificationSubject", g.String, this, t, "EMAIL_VERIFICATION_SUBJECT"), w("passwordResetTextBody", g.String, this, t, "PASSWORD_RESET_TEXT_BODY"), w("passwordResetHtmlBody", g.String, this, t, "PASSWORD_RESET_HTML_BODY"), w("passwordResetSubject", g.String, this, t, "PASSWORD_RESET_SUBJECT"), w("emailFrom", g.String, this, t, "EMAIL_FROM", !0), w("smtpHost", g.String, this, t, "SMTP_HOST", !0), w("smtpPort", g.Number, this, t, "SMTP_PORT"), w("smtpUsername", g.String, this, t, "SMTP_USERNAME"), w("smtpPassword", g.String, this, t, "SMTP_PASSWORD"), w("smtpUseTls", g.Boolean, this, t, "SMTP_USE_TLS"), w("verifyEmailExpires", g.Boolean, this, t, "VERIFY_EMAIL_EXPIRES"), w("passwordResetExpires", g.String, this, t, "PASSWORD_RESET_EXPIRES"), t.render ? this.render = t.render : W.configure(this.views, { autoescape: !0 });
4257
+ this.userStorage = a, this.keyStorage = e, w("siteUrl", g.String, this, t, "SITE_URL", !0), w("prefix", g.String, this, t, "PREFIX"), w("views", g.String, this, t, "VIEWS"), w("emailVerificationTextBody", g.String, this, t, "EMAIL_VERIFICATION_TEXT_BODY"), w("emailVerificationHtmlBody", g.String, this, t, "EMAIL_VERIFICATION_HTML_BODY"), w("emailVerificationSubject", g.String, this, t, "EMAIL_VERIFICATION_SUBJECT"), w("passwordResetTextBody", g.String, this, t, "PASSWORD_RESET_TEXT_BODY"), w("passwordResetHtmlBody", g.String, this, t, "PASSWORD_RESET_HTML_BODY"), w("passwordResetSubject", g.String, this, t, "PASSWORD_RESET_SUBJECT"), w("emailFrom", g.String, this, t, "EMAIL_FROM", !0), w("smtpHost", g.String, this, t, "SMTP_HOST", !0), w("smtpPort", g.Number, this, t, "SMTP_PORT"), w("smtpUsername", g.String, this, t, "SMTP_USERNAME"), w("smtpPassword", g.String, this, t, "SMTP_PASSWORD"), w("smtpUseTls", g.Boolean, this, t, "SMTP_USE_TLS"), w("verifyEmailExpires", g.Boolean, this, t, "VERIFY_EMAIL_EXPIRES"), w("passwordResetExpires", g.String, this, t, "PASSWORD_RESET_EXPIRES"), t.render ? this.render = t.render : Z.configure(this.views, { autoescape: !0 });
4154
4258
  }
4155
4259
  createEmailer() {
4156
4260
  let a = {};
4157
- return this.smtpUsername && (a.user = this.smtpUsername), this.smtpPassword && (a.pass = this.smtpPassword), Ae.createTransport({
4261
+ return this.smtpUsername && (a.user = this.smtpUsername), this.smtpPassword && (a.pass = this.smtpPassword), xe.createTransport({
4158
4262
  host: this.smtpHost,
4159
4263
  port: this.smtpPort,
4160
4264
  secure: this.smtpUseTls,
@@ -4166,24 +4270,24 @@ class D {
4166
4270
  * correct prefix for inserting into storage.
4167
4271
  */
4168
4272
  static hashEmailVerificationToken(a) {
4169
- return b.emailVerificationToken + _.hash(a);
4273
+ return U.emailVerificationToken + k.hash(a);
4170
4274
  }
4171
4275
  /**
4172
4276
  * Produces a hash of the given password reset token with the
4173
4277
  * correct prefix for inserting into storage.
4174
4278
  */
4175
4279
  static hashPasswordResetToken(a) {
4176
- return b.passwordResetToken + _.hash(a);
4280
+ return U.passwordResetToken + k.hash(a);
4177
4281
  }
4178
4282
  async createAndSaveEmailVerificationToken(a, e = "") {
4179
4283
  let r = 0;
4180
4284
  const i = /* @__PURE__ */ new Date(), s = new Date(i.getTime() + 1e3 * this.verifyEmailExpires);
4181
4285
  for (; r < 10; ) {
4182
- let n = _.randomValue(oe), c = D.hashEmailVerificationToken(n);
4286
+ let n = k.randomValue(fe), c = L.hashEmailVerificationToken(n);
4183
4287
  try {
4184
4288
  return await this.keyStorage.saveKey(a, c, i, s, e), n;
4185
4289
  } catch {
4186
- n = _.randomValue(oe), c = D.hashEmailVerificationToken(n), r++;
4290
+ n = k.randomValue(fe), c = L.hashEmailVerificationToken(n), r++;
4187
4291
  }
4188
4292
  }
4189
4293
  throw new o(l.Connection, "failed creating a unique key");
@@ -4198,7 +4302,7 @@ class D {
4198
4302
  to: e,
4199
4303
  subject: this.emailVerificationSubject
4200
4304
  }, i = { token: a, siteUrl: this.siteUrl, prefix: this.prefix };
4201
- return t && (i = { ...i, ...t }), this.emailVerificationTextBody && (r.text = this.render ? this.render(this.emailVerificationTextBody, i) : W.render(this.emailVerificationTextBody, i)), this.emailVerificationHtmlBody && (r.html = this.render ? this.render(this.emailVerificationHtmlBody, i) : W.render(this.emailVerificationHtmlBody, i)), (await this.createEmailer().sendMail(r)).messageId;
4305
+ return t && (i = { ...i, ...t }), this.emailVerificationTextBody && (r.text = this.render ? this.render(this.emailVerificationTextBody, i) : Z.render(this.emailVerificationTextBody, i)), this.emailVerificationHtmlBody && (r.html = this.render ? this.render(this.emailVerificationHtmlBody, i) : Z.render(this.emailVerificationHtmlBody, i)), (await this.createEmailer().sendMail(r)).messageId;
4202
4306
  }
4203
4307
  /**
4204
4308
  * Send an email verification email using the Nunjucks templates.
@@ -4224,7 +4328,7 @@ class D {
4224
4328
  "Either emailVerificationTextBody or emailVerificationHtmlBody must be set to send email verification emails"
4225
4329
  );
4226
4330
  let { user: r } = await this.userStorage.getUserById(a, { skipEmailVerifiedCheck: !0 }), i = e;
4227
- i != "" ? D.validateEmail(i) : (i = r.email ?? r.username, i || (i = r.username), D.validateEmail(i)), D.validateEmail(i);
4331
+ i != "" ? L.validateEmail(i) : (i = r.email ?? r.username, i || (i = r.username), L.validateEmail(i)), L.validateEmail(i);
4228
4332
  const s = await this.createAndSaveEmailVerificationToken(a, e), n = await this._sendEmailVerificationToken(s, i, t);
4229
4333
  h.logger.info(m({ msg: "Sent email verification email", emailMessageId: n, email: i }));
4230
4334
  }
@@ -4244,20 +4348,20 @@ class D {
4244
4348
  * address the user is validating
4245
4349
  */
4246
4350
  async verifyEmailVerificationToken(a) {
4247
- const e = D.hashEmailVerificationToken(a);
4351
+ const e = L.hashEmailVerificationToken(a);
4248
4352
  let t = await this.keyStorage.getKey(e);
4249
4353
  try {
4250
4354
  if (!t.userid || !t.expires) throw new o(l.InvalidKey);
4251
4355
  const { user: r } = await this.userStorage.getUserById(t.userid, { skipEmailVerifiedCheck: !0 });
4252
4356
  let i = (r.email ?? r.username).toLowerCase();
4253
- if (i || (i = r.username.toLowerCase()), D.validateEmail(i), (/* @__PURE__ */ new Date()).getTime() > t.expires.getTime()) throw new o(l.Expired);
4357
+ if (i || (i = r.username.toLowerCase()), L.validateEmail(i), (/* @__PURE__ */ new Date()).getTime() > t.expires.getTime()) throw new o(l.Expired);
4254
4358
  return { userid: t.userid, newEmail: t.data ?? "" };
4255
4359
  } finally {
4256
4360
  }
4257
4361
  }
4258
4362
  async deleteEmailVerificationToken(a) {
4259
4363
  try {
4260
- const e = D.hashEmailVerificationToken(a);
4364
+ const e = L.hashEmailVerificationToken(a);
4261
4365
  await this.keyStorage.deleteKey(e);
4262
4366
  } catch (e) {
4263
4367
  const t = o.asCrossauthError(e);
@@ -4268,11 +4372,11 @@ class D {
4268
4372
  let t = 0;
4269
4373
  const r = /* @__PURE__ */ new Date(), i = new Date(r.getTime() + 1e3 * this.passwordResetExpires);
4270
4374
  for (; t < 10; ) {
4271
- let s = _.randomValue(oe), n = D.hashPasswordResetToken(s);
4375
+ let s = k.randomValue(fe), n = L.hashPasswordResetToken(s);
4272
4376
  try {
4273
4377
  return await this.keyStorage.saveKey(a, n, r, i), s;
4274
4378
  } catch {
4275
- s = _.randomValue(oe), n = D.hashPasswordResetToken(s), t++;
4379
+ s = k.randomValue(fe), n = L.hashPasswordResetToken(s), t++;
4276
4380
  }
4277
4381
  }
4278
4382
  throw new o(l.Connection, "failed creating a unique key");
@@ -4292,7 +4396,7 @@ class D {
4292
4396
  * @returns the user that the token is for
4293
4397
  */
4294
4398
  async verifyPasswordResetToken(a) {
4295
- const e = D.hashPasswordResetToken(a);
4399
+ const e = L.hashPasswordResetToken(a);
4296
4400
  h.logger.debug("verifyPasswordResetToken " + a + " " + e);
4297
4401
  let t = await this.keyStorage.getKey(e);
4298
4402
  if (!t.userid) throw new o(l.InvalidKey);
@@ -4301,7 +4405,7 @@ class D {
4301
4405
  t.userid,
4302
4406
  { skipActiveCheck: !0 }
4303
4407
  );
4304
- if (r.state != k.active && r.state != k.passwordResetNeeded && r.state != k.passwordAndFactor2ResetNeeded)
4408
+ if (r.state != E.active && r.state != E.passwordResetNeeded && r.state != E.passwordAndFactor2ResetNeeded)
4305
4409
  throw new o(l.UserNotActive);
4306
4410
  if ((/* @__PURE__ */ new Date()).getTime() > t.expires.getTime()) throw new o(l.Expired);
4307
4411
  return r;
@@ -4321,7 +4425,7 @@ class D {
4321
4425
  to: e,
4322
4426
  subject: this.passwordResetSubject
4323
4427
  }, i = { token: a, siteUrl: this.siteUrl, prefix: this.prefix };
4324
- return t && (i = { ...i, ...t }), this.passwordResetTextBody && (r.text = this.render ? this.render(this.passwordResetTextBody, i) : W.render(this.passwordResetTextBody, i)), this.passwordResetHtmlBody && (r.html = this.render ? this.render(this.passwordResetHtmlBody, i) : W.render(this.passwordResetHtmlBody, i)), (await this.createEmailer().sendMail(r)).messageId;
4428
+ return t && (i = { ...i, ...t }), this.passwordResetTextBody && (r.text = this.render ? this.render(this.passwordResetTextBody, i) : Z.render(this.passwordResetTextBody, i)), this.passwordResetHtmlBody && (r.html = this.render ? this.render(this.passwordResetHtmlBody, i) : Z.render(this.passwordResetHtmlBody, i)), (await this.createEmailer().sendMail(r)).messageId;
4325
4429
  }
4326
4430
  /**
4327
4431
  * Send a password reset token email using the Nunjucks templates
@@ -4338,10 +4442,10 @@ class D {
4338
4442
  let { user: r } = await this.userStorage.getUserById(a, {
4339
4443
  skipActiveCheck: !0
4340
4444
  });
4341
- if (!t && r.state != k.active && r.state != k.passwordResetNeeded && r.state != k.passwordAndFactor2ResetNeeded)
4445
+ if (!t && r.state != E.active && r.state != E.passwordResetNeeded && r.state != E.passwordAndFactor2ResetNeeded)
4342
4446
  throw new o(l.UserNotActive);
4343
4447
  let i = (r.email ?? r.username).toLowerCase();
4344
- i || (i = r.username.toLowerCase()), D.validateEmail(i);
4448
+ i || (i = r.username.toLowerCase()), L.validateEmail(i);
4345
4449
  const s = await this.createAndSavePasswordResetToken(a), n = await this._sendPasswordResetToken(s, i, e);
4346
4450
  h.logger.info(m({ msg: "Sent password reset email", emailMessageId: n, email: i }));
4347
4451
  }
@@ -4363,17 +4467,17 @@ class D {
4363
4467
  * @param email the email to validate
4364
4468
  */
4365
4469
  static validateEmail(a) {
4366
- if (a == null || !D.isEmailValid(a)) throw new o(l.InvalidEmail);
4470
+ if (a == null || !L.isEmailValid(a)) throw new o(l.InvalidEmail);
4367
4471
  }
4368
4472
  }
4369
- const be = 16, Ue = 16;
4370
- function Wt(S) {
4473
+ const Fe = 16, Ne = 16;
4474
+ function tr(S) {
4371
4475
  return {
4372
4476
  ...S,
4373
4477
  path: S.path ?? "/"
4374
4478
  };
4375
4479
  }
4376
- class ct {
4480
+ class yt {
4377
4481
  /**
4378
4482
  * Constructor.
4379
4483
  *
@@ -4404,7 +4508,7 @@ class ct {
4404
4508
  * @returns a random CSRF token.
4405
4509
  */
4406
4510
  createCsrfToken() {
4407
- return _.randomValue(be);
4511
+ return k.randomValue(Fe);
4408
4512
  }
4409
4513
  /**
4410
4514
  * Returns a {@link Cookie } object with the given session key.
@@ -4413,7 +4517,7 @@ class ct {
4413
4517
  * @returns a {@link Cookie } object,
4414
4518
  */
4415
4519
  makeCsrfCookie(a) {
4416
- const e = _.signSecureToken(a, this.secret);
4520
+ const e = k.signSecureToken(a, this.secret);
4417
4521
  let t = {};
4418
4522
  return this.domain && (t.domain = this.domain), this.path && (t.path = this.path), t.sameSite = this.sameSite, this.httpOnly && (t.httpOnly = this.httpOnly), this.secure && (t.secure = this.secure), {
4419
4523
  name: this.cookieName,
@@ -4425,7 +4529,7 @@ class ct {
4425
4529
  return this.maskCsrfToken(a);
4426
4530
  }
4427
4531
  unsignCookie(a) {
4428
- return _.unsignSecureToken(a, this.secret);
4532
+ return k.unsignSecureToken(a, this.secret);
4429
4533
  }
4430
4534
  /**
4431
4535
  * Takes a session ID and creates a string representation of the cookie (value of the HTTP `Cookie` header).
@@ -4438,14 +4542,14 @@ class ct {
4438
4542
  return this.domain && (e += "; " + this.domain), this.path && (e += "; " + this.path), this.httpOnly && (e += "; httpOnly"), this.secure && (e += "; secure"), e;
4439
4543
  }
4440
4544
  maskCsrfToken(a) {
4441
- const e = _.randomValue(be), t = _.xor(a, e);
4545
+ const e = k.randomValue(Fe), t = k.xor(a, e);
4442
4546
  return e + "." + t;
4443
4547
  }
4444
4548
  unmaskCsrfToken(a) {
4445
4549
  const e = a.split(".");
4446
4550
  if (e.length != 2) throw new o(l.InvalidCsrf, "CSRF token in header or form not in correct format");
4447
4551
  const t = e[0], r = e[1];
4448
- return _.xor(r, t);
4552
+ return k.xor(r, t);
4449
4553
  }
4450
4554
  /**
4451
4555
  * Validates the passed CSRF token.
@@ -4462,12 +4566,12 @@ class ct {
4462
4566
  const t = this.unmaskCsrfToken(e);
4463
4567
  let r;
4464
4568
  try {
4465
- r = _.unsignSecureToken(a, this.secret);
4569
+ r = k.unsignSecureToken(a, this.secret);
4466
4570
  } catch (i) {
4467
4571
  throw h.logger.error(m({ err: i })), new o(l.InvalidCsrf, "Invalid CSRF cookie");
4468
4572
  }
4469
4573
  if (r != t)
4470
- throw h.logger.warn(m({ msg: "Invalid CSRF token received - form/header value does not match", csrfCookieHash: _.hash(a) })), new o(l.InvalidCsrf);
4574
+ throw h.logger.warn(m({ msg: "Invalid CSRF token received - form/header value does not match", csrfCookieHash: k.hash(a) })), new o(l.InvalidCsrf);
4471
4575
  }
4472
4576
  /**
4473
4577
  * Validates the passed CSRF cookie (doesn't check it matches the token, just that the cookie is valid).
@@ -4481,13 +4585,13 @@ class ct {
4481
4585
  */
4482
4586
  validateCsrfCookie(a) {
4483
4587
  try {
4484
- return _.unsignSecureToken(a, this.secret);
4588
+ return k.unsignSecureToken(a, this.secret);
4485
4589
  } catch (e) {
4486
4590
  throw h.logger.error(m({ err: e })), new o(l.InvalidCsrf, "Invalid CSRF cookie");
4487
4591
  }
4488
4592
  }
4489
4593
  }
4490
- class x {
4594
+ class j {
4491
4595
  /**
4492
4596
  * Constructor.
4493
4597
  *
@@ -4530,7 +4634,7 @@ class x {
4530
4634
  * @returns a base64-url-encoded string that can go into the storage
4531
4635
  */
4532
4636
  static hashSessionId(a) {
4533
- return b.session + _.hash(a);
4637
+ return U.session + k.hash(a);
4534
4638
  }
4535
4639
  /**
4536
4640
  * Creates a session key and saves in storage
@@ -4549,17 +4653,17 @@ class x {
4549
4653
  * attempts exceeded trying to create a unique session id
4550
4654
  */
4551
4655
  async createSessionKey(a, e = {}) {
4552
- let r = 0, i = _.randomValue(Ue);
4656
+ let r = 0, i = k.randomValue(Ne);
4553
4657
  const s = /* @__PURE__ */ new Date();
4554
4658
  let n = this.expiry(s), c = !1;
4555
4659
  for (; r < 10 && !c; ) {
4556
- const d = x.hashSessionId(i);
4660
+ const d = j.hashSessionId(i);
4557
4661
  try {
4558
4662
  this.idleTimeout > 0 && a && (e = { ...e, lastActivity: /* @__PURE__ */ new Date() }), await this.keyStorage.saveKey(a, d, s, n, void 0, e), c = !0;
4559
4663
  } catch (f) {
4560
4664
  let y = o.asCrossauthError(f);
4561
4665
  if (y.code == l.KeyExists || y.code == l.InvalidKey) {
4562
- if (r++, i = _.randomValue(Ue), r > 10)
4666
+ if (r++, i = k.randomValue(Ne), r > 10)
4563
4667
  throw h.logger.error(m({ msg: "Max attempts exceeded trying to create session ID" })), new o(l.KeyExists);
4564
4668
  } else
4565
4669
  throw h.logger.debug(m({ err: f })), f;
@@ -4582,7 +4686,7 @@ class x {
4582
4686
  * @returns a {@link Cookie } object,
4583
4687
  */
4584
4688
  makeCookie(a, e) {
4585
- let t = _.signSecureToken(a.value, this.secret), r = {};
4689
+ let t = k.signSecureToken(a.value, this.secret), r = {};
4586
4690
  return e == null && (e = this.persist), this.domain && (r.domain = this.domain), a.expires && e && (r.expires = a.expires), this.path && (r.path = this.path), r.sameSite = this.sameSite, this.httpOnly && (r.httpOnly = this.httpOnly), this.secure && (r.secure = this.secure), {
4587
4691
  name: this.cookieName,
4588
4692
  value: t,
@@ -4609,7 +4713,7 @@ class x {
4609
4713
  */
4610
4714
  async updateSessionKey(a) {
4611
4715
  if (!a.value) throw new o(l.InvalidKey, "No session when updating activity");
4612
- a.value = x.hashSessionId(a.value), await this.keyStorage.updateKey(a);
4716
+ a.value = j.hashSessionId(a.value), await this.keyStorage.updateKey(a);
4613
4717
  }
4614
4718
  /**
4615
4719
  * Unsigns a cookie and returns the original value.
@@ -4619,7 +4723,7 @@ class x {
4619
4723
  * is invalid.
4620
4724
  */
4621
4725
  unsignCookie(a) {
4622
- return _.unsignSecureToken(a, this.secret);
4726
+ return k.unsignSecureToken(a, this.secret);
4623
4727
  }
4624
4728
  /**
4625
4729
  * Returns the user matching the given session key in session storage, or throws an exception.
@@ -4657,13 +4761,13 @@ class x {
4657
4761
  * `Expired` or `UserNotExist`.
4658
4762
  */
4659
4763
  async getSessionKey(a) {
4660
- const e = Date.now(), t = x.hashSessionId(a), r = await this.keyStorage.getKey(t);
4764
+ const e = Date.now(), t = j.hashSessionId(a), r = await this.keyStorage.getKey(t);
4661
4765
  if (r.value = a, r.expires && e > r.expires.getTime())
4662
- throw h.logger.warn(m({ msg: "Session id in cookie expired in key storage", hashedSessionCookie: _.hash(a) })), new o(l.Expired);
4766
+ throw h.logger.warn(m({ msg: "Session id in cookie expired in key storage", hashedSessionCookie: k.hash(a) })), new o(l.Expired);
4663
4767
  if (r.userid && this.idleTimeout > 0 && r.lastactive && e > r.lastactive.getTime() + this.idleTimeout * 1e3)
4664
- throw h.logger.warn(m({ msg: "Session cookie with expired idle time received", hashedSessionCookie: _.hash(a) })), new o(l.Expired);
4768
+ throw h.logger.warn(m({ msg: "Session cookie with expired idle time received", hashedSessionCookie: k.hash(a) })), new o(l.Expired);
4665
4769
  if (this.filterFunction && !this.filterFunction(r))
4666
- throw h.logger.warn(m({ msg: "Filter function on session id in cookie failed", hashedSessionCookie: _.hash(a) })), new o(l.InvalidKey);
4770
+ throw h.logger.warn(m({ msg: "Filter function on session id in cookie failed", hashedSessionCookie: k.hash(a) })), new o(l.InvalidKey);
4667
4771
  return r;
4668
4772
  }
4669
4773
  /**
@@ -4672,10 +4776,10 @@ class x {
4672
4776
  * @param except if defined, don't delete this key
4673
4777
  */
4674
4778
  async deleteAllForUser(a, e) {
4675
- e && (e = x.hashSessionId(e)), await this.keyStorage.deleteAllForUser(a, b.session, e);
4779
+ e && (e = j.hashSessionId(e)), await this.keyStorage.deleteAllForUser(a, U.session, e);
4676
4780
  }
4677
4781
  }
4678
- class Jt {
4782
+ class rr {
4679
4783
  /**
4680
4784
  * Constructor
4681
4785
  * @param keyStorage the {@link KeyStorage} instance to use, eg {@link PrismaKeyStorage}.
@@ -4697,9 +4801,9 @@ class Jt {
4697
4801
  t.userStorage && (this.userStorage = t.userStorage), this.keyStorage = a, this.authenticators = e;
4698
4802
  for (let r in this.authenticators)
4699
4803
  this.authenticators[r].factorName = r;
4700
- if (this.session = new x(this.keyStorage, { ...t == null ? void 0 : t.sessionCookieOptions, ...t ?? {} }), this.csrfTokens = new ct({ ...t == null ? void 0 : t.doubleSubmitCookieOptions, ...t ?? {} }), w("allowedFactor2", g.JsonArray, this, t, "ALLOWED_FACTOR2"), w("enableEmailVerification", g.Boolean, this, t, "ENABLE_EMAIL_VERIFICATION"), w("enablePasswordReset", g.Boolean, this, t, "ENABLE_PASSWORD_RESET"), this.emailTokenStorage = this.keyStorage, this.userStorage && (this.enableEmailVerification || this.enablePasswordReset)) {
4804
+ if (this.session = new j(this.keyStorage, { ...t == null ? void 0 : t.sessionCookieOptions, ...t ?? {} }), this.csrfTokens = new yt({ ...t == null ? void 0 : t.doubleSubmitCookieOptions, ...t ?? {} }), w("allowedFactor2", g.JsonArray, this, t, "ALLOWED_FACTOR2"), w("enableEmailVerification", g.Boolean, this, t, "ENABLE_EMAIL_VERIFICATION"), w("enablePasswordReset", g.Boolean, this, t, "ENABLE_PASSWORD_RESET"), this.emailTokenStorage = this.keyStorage, this.userStorage && (this.enableEmailVerification || this.enablePasswordReset)) {
4701
4805
  let r = this.keyStorage;
4702
- t.emailTokenStorage && (this.emailTokenStorage = t.emailTokenStorage), this.tokenEmailer = new D(this.userStorage, r, t);
4806
+ t.emailTokenStorage && (this.emailTokenStorage = t.emailTokenStorage), this.tokenEmailer = new L(this.userStorage, r, t);
4703
4807
  }
4704
4808
  }
4705
4809
  /**
@@ -4759,40 +4863,40 @@ class Jt {
4759
4863
  if (i)
4760
4864
  n = (await this.userStorage.getUserByUsername(i.username, { skipActiveCheck: !0, skipEmailVerifiedCheck: !0 })).secrets;
4761
4865
  else {
4762
- let v = { username: "", state: "active" };
4866
+ let _ = { username: "", state: "active" };
4763
4867
  try {
4764
4868
  let T = await this.userStorage.getUserByUsername(a, { skipActiveCheck: !0, skipEmailVerifiedCheck: !0 });
4765
- n = T.secrets, i = T.user, v = T.user;
4869
+ n = T.secrets, i = T.user, _ = T.user;
4766
4870
  } catch (T) {
4767
4871
  if (o.asCrossauthError(T).code == l.Connection) throw T;
4768
- for (let A in this.authenticators)
4769
- this.authenticators[A].requireUserEntry() || (v = { username: e.username, state: "active" }, c = A);
4872
+ for (let b in this.authenticators)
4873
+ this.authenticators[b].requireUserEntry() || (_ = { username: e.username, state: "active" }, c = b);
4770
4874
  }
4771
- if (v.username == "") throw new o(l.UserNotExist);
4772
- await this.authenticators[(i == null ? void 0 : i.factor1) ?? c].authenticateUser(v, n, e);
4875
+ if (_.username == "") throw new o(l.UserNotExist);
4876
+ await this.authenticators[(i == null ? void 0 : i.factor1) ?? c].authenticateUser(_, n, e);
4773
4877
  let p = await this.userStorage.getUserByUsername(a, { skipActiveCheck: !0, skipEmailVerifiedCheck: !0 });
4774
4878
  n = p.secrets, i = p.user;
4775
4879
  }
4776
4880
  let d;
4777
- if (i.state == k.passwordChangeNeeded)
4881
+ if (i.state == E.passwordChangeNeeded)
4778
4882
  d = (await this.createAnonymousSession({ data: JSON.stringify({ passwordchange: { username: i.username } }) })).sessionCookie;
4779
- else if (i.state == k.factor2ResetNeeded)
4883
+ else if (i.state == E.factor2ResetNeeded)
4780
4884
  d = (await this.createAnonymousSession({ data: JSON.stringify({ factor2change: { username: i.username } }) })).sessionCookie;
4781
4885
  else if (!s && i.factor2 && i.factor2 != "") {
4782
- const { sessionCookie: v } = await this.initiateTwoFactorLogin(i);
4783
- d = v;
4886
+ const { sessionCookie: _ } = await this.initiateTwoFactorLogin(i);
4887
+ d = _;
4784
4888
  } else {
4785
- const v = await this.session.createSessionKey(i.id, t);
4786
- d = this.session.makeCookie(v, r);
4889
+ const _ = await this.session.createSessionKey(i.id, t);
4890
+ d = this.session.makeCookie(_, r);
4787
4891
  }
4788
4892
  const f = this.csrfTokens.createCsrfToken(), y = this.csrfTokens.makeCsrfCookie(f), C = this.csrfTokens.makeCsrfFormOrHeaderToken(f);
4789
4893
  try {
4790
4894
  this.emailTokenStorage.deleteAllForUser(
4791
4895
  i.id,
4792
- b.passwordResetToken
4896
+ U.passwordResetToken
4793
4897
  );
4794
- } catch (v) {
4795
- h.logger.warn(m({ msg: "Couldn't delete password reset tokens while logging in", user: a })), h.logger.debug(m({ err: v }));
4898
+ } catch (_) {
4899
+ h.logger.warn(m({ msg: "Couldn't delete password reset tokens while logging in", user: a })), h.logger.debug(m({ err: _ }));
4796
4900
  }
4797
4901
  return {
4798
4902
  sessionCookie: d,
@@ -4829,7 +4933,7 @@ class Jt {
4829
4933
  */
4830
4934
  async logout(a) {
4831
4935
  const e = await this.session.getSessionKey(a);
4832
- return await this.keyStorage.deleteKey(x.hashSessionId(e.value));
4936
+ return await this.keyStorage.deleteKey(j.hashSessionId(e.value));
4833
4937
  }
4834
4938
  /**
4835
4939
  * Logs a user out from all sessions.
@@ -4977,8 +5081,8 @@ class Jt {
4977
5081
  * @param value new value to store
4978
5082
  */
4979
5083
  async updateSessionData(a, e, t) {
4980
- const r = x.hashSessionId(a);
4981
- h.logger.debug(m({ msg: `Updating session data value ${e}`, hashedSessionCookie: _.hash(a) })), await this.keyStorage.updateData(r, e, t);
5084
+ const r = j.hashSessionId(a);
5085
+ h.logger.debug(m({ msg: `Updating session data value ${e}`, hashedSessionCookie: k.hash(a) })), await this.keyStorage.updateData(r, e, t);
4982
5086
  }
4983
5087
  /**
4984
5088
  * Update field sin the session data.
@@ -4989,8 +5093,8 @@ class Jt {
4989
5093
  * @param dataArray names and values.
4990
5094
  */
4991
5095
  async updateManySessionData(a, e) {
4992
- const t = x.hashSessionId(a);
4993
- h.logger.debug(m({ msg: "Updating session data", hashedSessionCookie: _.hash(a) })), await this.keyStorage.updateManyData(t, e);
5096
+ const t = j.hashSessionId(a);
5097
+ h.logger.debug(m({ msg: "Updating session data", hashedSessionCookie: k.hash(a) })), await this.keyStorage.updateManyData(t, e);
4994
5098
  }
4995
5099
  /**
4996
5100
  * Deletes a field from the session data.
@@ -5001,8 +5105,8 @@ class Jt {
5001
5105
  * @param name of the field.
5002
5106
  */
5003
5107
  async deleteSessionData(a, e) {
5004
- const t = x.hashSessionId(a);
5005
- h.logger.debug(m({ msg: `Updating session data value ${e}`, hashedSessionCookie: _.hash(a) })), await this.keyStorage.deleteData(t, e);
5108
+ const t = j.hashSessionId(a);
5109
+ h.logger.debug(m({ msg: `Updating session data value ${e}`, hashedSessionCookie: k.hash(a) })), await this.keyStorage.deleteData(t, e);
5006
5110
  }
5007
5111
  /**
5008
5112
  * Deletes the given session ID from the key storage (not the cookie)
@@ -5010,7 +5114,7 @@ class Jt {
5010
5114
  * @param sessionId the session Id to delete
5011
5115
  */
5012
5116
  async deleteSession(a) {
5013
- return await this.keyStorage.deleteKey(x.hashSessionId(a));
5117
+ return await this.keyStorage.deleteKey(j.hashSessionId(a));
5014
5118
  }
5015
5119
  /**
5016
5120
  * Creates a new user, sending an email verification message if necessary.
@@ -5064,8 +5168,8 @@ class Jt {
5064
5168
  if (!this.authenticators[a.factor1]) throw new o(l.Configuration, "Authenticator cannot create users");
5065
5169
  if (!this.authenticators[a.factor2]) throw new o(l.Configuration, "Two factor authentication not enabled for user");
5066
5170
  const i = this.authenticators[a.factor2], s = await i.prepareConfiguration(a), n = s == null ? {} : s.userData, c = s == null ? {} : s.sessionData, d = await this.authenticators[a.factor1].createPersistentSecrets(a.username, e, r);
5067
- return this.enableEmailVerification && !i.skipEmailVerificationOnSignup() ? a.state = k.awaitingTwoFactorSetupAndEmailVerification : a.state = k.awaitingTwoFactorSetup, await this.keyStorage.updateData(
5068
- x.hashSessionId(t),
5171
+ return this.enableEmailVerification && !i.skipEmailVerificationOnSignup() ? a.state = E.awaitingTwoFactorSetupAndEmailVerification : a.state = E.awaitingTwoFactorSetup, await this.keyStorage.updateData(
5172
+ j.hashSessionId(t),
5069
5173
  "2fa",
5070
5174
  c
5071
5175
  ), { userid: (await this.userStorage.createUser(a, d)).id, userData: n };
@@ -5085,13 +5189,13 @@ class Jt {
5085
5189
  if (!this.authenticators[e]) throw new o(l.Configuration, "Two factor authentication not enabled for user");
5086
5190
  const i = await this.authenticators[e].prepareConfiguration(a), s = i == null ? {} : i.userData, n = i == null ? {} : i.sessionData;
5087
5191
  return n && (n.userData = s), await this.keyStorage.updateData(
5088
- x.hashSessionId(t),
5192
+ j.hashSessionId(t),
5089
5193
  "2fa",
5090
5194
  n
5091
5195
  ), s;
5092
5196
  }
5093
5197
  return await this.userStorage.updateUser({ id: a.id, factor2: e ?? "" }), await this.keyStorage.updateData(
5094
- x.hashSessionId(t),
5198
+ j.hashSessionId(t),
5095
5199
  "2fa",
5096
5200
  void 0
5097
5201
  ), {};
@@ -5111,7 +5215,7 @@ class Jt {
5111
5215
  */
5112
5216
  async repeatTwoFactorSignup(a) {
5113
5217
  if (!this.userStorage) throw new o(l.Configuration, "Cannot call repeatTwoFactorSignup if no user storage provided");
5114
- const e = (await this.dataForSessionId(a))["2fa"], t = e.username, r = e.factor2, i = x.hashSessionId(a), s = await this.keyStorage.getKey(i), c = await this.authenticators[r].reprepareConfiguration(t, s), d = c == null ? {} : c.userData, f = c == null ? {} : c.secrets, y = c == null ? {} : c.newSessionData;
5218
+ const e = (await this.dataForSessionId(a))["2fa"], t = e.username, r = e.factor2, i = j.hashSessionId(a), s = await this.keyStorage.getKey(i), c = await this.authenticators[r].reprepareConfiguration(t, s), d = c == null ? {} : c.userData, f = c == null ? {} : c.secrets, y = c == null ? {} : c.newSessionData;
5115
5219
  y && await this.keyStorage.updateData(i, "2fa", y);
5116
5220
  const { user: C } = await this.userStorage.getUserByUsername(t, { skipActiveCheck: !0, skipEmailVerifiedCheck: !0 });
5117
5221
  return { userid: C.id, userData: d, secrets: f };
@@ -5132,26 +5236,26 @@ class Jt {
5132
5236
  let { user: t, key: r } = await this.session.getUserForSessionId(e, {
5133
5237
  skipActiveCheck: !0
5134
5238
  });
5135
- if (t && t.state != k.active && t.state != k.factor2ResetNeeded)
5239
+ if (t && t.state != E.active && t.state != E.factor2ResetNeeded)
5136
5240
  throw new o(l.UserNotActive);
5137
5241
  if (!r) throw new o(l.InvalidKey, "Session key not found");
5138
- let i = z.decodeData(r.data)["2fa"];
5242
+ let i = V.decodeData(r.data)["2fa"];
5139
5243
  if (!(i != null && i.factor2) || !(i != null && i.username)) throw new o(l.Unauthorized, "Two factor authentication not initiated");
5140
5244
  let s = i.username;
5141
5245
  const n = this.authenticators[i.factor2];
5142
5246
  if (!n) throw new o(l.Configuration, "Unrecognised second factor authentication");
5143
5247
  const c = {}, d = n.secretNames();
5144
- for (let v in i)
5145
- d.includes(v) && (c[v] = i[v]);
5248
+ for (let _ in i)
5249
+ d.includes(_) && (c[_] = i[_]);
5146
5250
  if (await n.authenticateUser(void 0, i, a), t || (t = (await this.userStorage.getUserByUsername(s, { skipActiveCheck: !0, skipEmailVerifiedCheck: !0 })).user), !t) throw new o(l.UserNotExist, "Couldn't fetch user");
5147
- let f = k.active;
5148
- t.state == k.awaitingTwoFactorSetupAndEmailVerification && (f = k.awaitingEmailVerification);
5251
+ let f = E.active;
5252
+ t.state == E.awaitingTwoFactorSetupAndEmailVerification && (f = E.awaitingEmailVerification);
5149
5253
  const y = {
5150
5254
  id: t.id,
5151
5255
  state: f,
5152
5256
  factor2: i.factor2
5153
5257
  };
5154
- return n.secretNames().length > 0 ? await this.userStorage.updateUser(y, c) : await this.userStorage.updateUser(y), f == k.awaitingEmailVerification && this.tokenEmailer && await ((C = this.tokenEmailer) == null ? void 0 : C.sendEmailVerificationToken(t.id, void 0)), await this.keyStorage.updateData(x.hashSessionId(r.value), "2fa", void 0), { ...t, ...y };
5258
+ return n.secretNames().length > 0 ? await this.userStorage.updateUser(y, c) : await this.userStorage.updateUser(y), f == E.awaitingEmailVerification && this.tokenEmailer && await ((C = this.tokenEmailer) == null ? void 0 : C.sendEmailVerificationToken(t.id, void 0)), await this.keyStorage.updateData(j.hashSessionId(r.value), "2fa", void 0), { ...t, ...y };
5155
5259
  }
5156
5260
  /**
5157
5261
  * Initiates the two factor login process.
@@ -5182,7 +5286,7 @@ class Jt {
5182
5286
  async initiateTwoFactorPageVisit(a, e, t, r, i) {
5183
5287
  const n = await this.authenticators[a.factor2].createOneTimeSecrets(a);
5184
5288
  let c, d, f;
5185
- const y = x.hashSessionId(e);
5289
+ const y = j.hashSessionId(e);
5186
5290
  h.logger.debug("initiateTwoFactorPageVisit " + a.username + " " + e + " " + y);
5187
5291
  let C = { username: a.username, factor2: a.factor2, secrets: n, body: t, url: r };
5188
5292
  return i && (C["content-type"] = i), await this.keyStorage.updateData(y, "pre2fa", C), {
@@ -5204,14 +5308,14 @@ class Jt {
5204
5308
  if (!this.userStorage) throw new o(l.Configuration, "Cannot call completeTwoFactorPageVisit if no user storage provided");
5205
5309
  let { key: t } = await this.session.getUserForSessionId(e);
5206
5310
  if (!t) throw new o(l.InvalidKey, "Session key not found");
5207
- let r = z.decodeData(t.data);
5311
+ let r = V.decodeData(t.data);
5208
5312
  if (!("pre2fa" in r)) throw new o(l.Unauthorized, "Two factor authentication not initiated");
5209
5313
  const { secrets: i } = await this.userStorage.getUserByUsername(r.pre2fa.username), s = this.authenticators[r.pre2fa.factor2];
5210
5314
  if (!s) throw new o(l.Configuration, "Unrecognised second factor authentication");
5211
5315
  const n = {}, c = s.secretNames();
5212
5316
  for (let d in i)
5213
5317
  c.includes(d) && d in i && (n[d] = i[d]);
5214
- await s.authenticateUser(void 0, { ...n, ...r.pre2fa.secrets }, a), await this.keyStorage.updateData(x.hashSessionId(t.value), "pre2fa", void 0);
5318
+ await s.authenticateUser(void 0, { ...n, ...r.pre2fa.secrets }, a), await this.keyStorage.updateData(j.hashSessionId(t.value), "pre2fa", void 0);
5215
5319
  }
5216
5320
  /**
5217
5321
  * Cancels the 2FA that was previously initiated but not completed..
@@ -5225,9 +5329,9 @@ class Jt {
5225
5329
  async cancelTwoFactorPageVisit(a) {
5226
5330
  let { key: e } = await this.session.getUserForSessionId(a);
5227
5331
  if (!e) throw new o(l.InvalidSession, "Session key not found");
5228
- let t = z.decodeData(e.data);
5332
+ let t = V.decodeData(e.data);
5229
5333
  if (!("pre2fa" in t)) throw new o(l.Unauthorized, "Two factor authentication not initiated");
5230
- return await this.keyStorage.updateData(x.hashSessionId(e.value), "pre2fa", void 0), t.pre2fa;
5334
+ return await this.keyStorage.updateData(j.hashSessionId(e.value), "pre2fa", void 0), t.pre2fa;
5231
5335
  }
5232
5336
  /**
5233
5337
  * Performs the second factor authentication as the second step of the login
@@ -5250,25 +5354,25 @@ class Jt {
5250
5354
  if (!this.userStorage) throw new o(l.Configuration, "Cannot call completeTwoFactorLogin if no user storage provided");
5251
5355
  let { key: i } = await this.session.getUserForSessionId(e);
5252
5356
  if (!i || !i.data || i.data == "") throw new o(l.Unauthorized);
5253
- let s = z.decodeData(i.data)["2fa"], n = s.username, c = s.factor2;
5357
+ let s = V.decodeData(i.data)["2fa"], n = s.username, c = s.factor2;
5254
5358
  const { user: d, secrets: f } = await this.userStorage.getUserByUsername(n), y = this.authenticators[c];
5255
5359
  if (!y) throw new o(l.Configuration, "Second factor " + c + " not enabled");
5256
5360
  await y.authenticateUser(d, { ...f, ...s }, a);
5257
5361
  const C = await this.session.createSessionKey(d.id, t);
5258
- await this.keyStorage.deleteKey(x.hashSessionId(i.value));
5259
- const v = this.session.makeCookie(C, r), p = this.csrfTokens.createCsrfToken(), T = this.csrfTokens.makeCsrfCookie(p), E = this.csrfTokens.makeCsrfFormOrHeaderToken(p);
5362
+ await this.keyStorage.deleteKey(j.hashSessionId(i.value));
5363
+ const _ = this.session.makeCookie(C, r), p = this.csrfTokens.createCsrfToken(), T = this.csrfTokens.makeCsrfCookie(p), v = this.csrfTokens.makeCsrfFormOrHeaderToken(p);
5260
5364
  try {
5261
5365
  this.emailTokenStorage.deleteAllForUser(
5262
5366
  d.id,
5263
- b.passwordResetToken
5367
+ U.passwordResetToken
5264
5368
  );
5265
- } catch (A) {
5266
- h.logger.warn(m({ msg: "Couldn't delete password reset tokens while logging in", user: n })), h.logger.debug(m({ err: A }));
5369
+ } catch (b) {
5370
+ h.logger.warn(m({ msg: "Couldn't delete password reset tokens while logging in", user: n })), h.logger.debug(m({ err: b }));
5267
5371
  }
5268
5372
  return {
5269
- sessionCookie: v,
5373
+ sessionCookie: _,
5270
5374
  csrfCookie: T,
5271
- csrfFormOrHeaderValue: E,
5375
+ csrfFormOrHeaderValue: v,
5272
5376
  user: d
5273
5377
  };
5274
5378
  }
@@ -5282,7 +5386,7 @@ class Jt {
5282
5386
  const { user: e } = await this.userStorage.getUserByEmail(a, {
5283
5387
  skipActiveCheck: !0
5284
5388
  });
5285
- if (e.state != k.active && e.state != k.passwordResetNeeded && e.state != k.passwordAndFactor2ResetNeeded)
5389
+ if (e.state != E.active && e.state != E.passwordResetNeeded && e.state != E.passwordAndFactor2ResetNeeded)
5286
5390
  throw new o(l.UserNotActive);
5287
5391
  await ((t = this.tokenEmailer) == null ? void 0 : t.sendPasswordResetToken(e.id));
5288
5392
  }
@@ -5331,7 +5435,7 @@ class Jt {
5331
5435
  try {
5332
5436
  await this.emailTokenStorage.deleteAllForUser(
5333
5437
  s.id,
5334
- b.passwordResetToken
5438
+ U.passwordResetToken
5335
5439
  );
5336
5440
  } catch (f) {
5337
5441
  h.logger.warn(m({ msg: "Couldn't delete password reset tokens while logging in", user: a })), h.logger.debug(m({ err: f }));
@@ -5356,18 +5460,18 @@ class Jt {
5356
5460
  d.userid = a.userid, d.id = a.id;
5357
5461
  let f = !1;
5358
5462
  if (s)
5359
- i = s, D.validateEmail(i), f = !0;
5463
+ i = s, L.validateEmail(i), f = !0;
5360
5464
  else if (n) {
5361
5465
  i = n;
5362
5466
  try {
5363
- D.validateEmail(a.username), f = !0;
5467
+ L.validateEmail(a.username), f = !0;
5364
5468
  } catch {
5365
5469
  }
5366
- f && D.validateEmail(i);
5470
+ f && L.validateEmail(i);
5367
5471
  }
5368
- return !t && this.enableEmailVerification && f ? await ((y = this.tokenEmailer) == null ? void 0 : y.sendEmailVerificationToken(a.id, i)) : (s && (d.email = s), n && (d.username = n)), (e.state == k.passwordResetNeeded || e.state == k.passwordAndFactor2ResetNeeded) && await ((C = this.tokenEmailer) == null ? void 0 : C.sendPasswordResetToken(a.id, {}, r)), await this.userStorage.updateUser(d), {
5472
+ return !t && this.enableEmailVerification && f ? await ((y = this.tokenEmailer) == null ? void 0 : y.sendEmailVerificationToken(a.id, i)) : (s && (d.email = s), n && (d.username = n)), (e.state == E.passwordResetNeeded || e.state == E.passwordAndFactor2ResetNeeded) && await ((C = this.tokenEmailer) == null ? void 0 : C.sendPasswordResetToken(a.id, {}, r)), await this.userStorage.updateUser(d), {
5369
5473
  emailVerificationTokenSent: !t && this.enableEmailVerification && f,
5370
- passwordResetTokenSent: e.state == k.passwordResetNeeded || e.state == k.passwordAndFactor2ResetNeeded
5474
+ passwordResetTokenSent: e.state == E.passwordResetNeeded || e.state == E.passwordAndFactor2ResetNeeded
5371
5475
  };
5372
5476
  }
5373
5477
  /**
@@ -5386,7 +5490,7 @@ class Jt {
5386
5490
  if (h.logger.debug(m({ msg: "resetSecret" })), !this.tokenEmailer) throw new o(l.Configuration, "Password reset not enabled");
5387
5491
  const i = await this.userForPasswordResetToken(a), s = e == 1 ? i.factor1 : i.factor2;
5388
5492
  if (!this.tokenEmailer) throw new o(l.Configuration);
5389
- let n = i.state == k.passwordAndFactor2ResetNeeded ? k.factor2ResetNeeded : k.active;
5493
+ let n = i.state == E.passwordAndFactor2ResetNeeded ? E.factor2ResetNeeded : E.active;
5390
5494
  await this.userStorage.updateUser(
5391
5495
  { id: i.id, state: n },
5392
5496
  await this.authenticators[s].createPersistentSecrets(i.username, t, r)
@@ -5394,7 +5498,7 @@ class Jt {
5394
5498
  try {
5395
5499
  await this.emailTokenStorage.deleteAllForUser(
5396
5500
  i.id,
5397
- b.passwordResetToken
5501
+ U.passwordResetToken
5398
5502
  );
5399
5503
  } catch (c) {
5400
5504
  h.logger.warn(m({ msg: "Couldn't delete password reset tokens while logging in", user: i.username })), h.logger.debug(m({ err: c }));
@@ -5402,7 +5506,7 @@ class Jt {
5402
5506
  return { ...i, state: n };
5403
5507
  }
5404
5508
  }
5405
- class we {
5509
+ class ke {
5406
5510
  /**
5407
5511
  * Constructor.
5408
5512
  *
@@ -5416,7 +5520,7 @@ class we {
5416
5520
  /** The prefix to add to the hashed key in storage. Defaults to
5417
5521
  * {@link @crossauth/common!KeyPrefix}.apiKey
5418
5522
  */
5419
- u(this, "prefix", b.apiKey);
5523
+ u(this, "prefix", U.apiKey);
5420
5524
  /** The name of the speak in the Authorization header. Defaults to "ApiKey" */
5421
5525
  u(this, "authScheme", "ApiKey");
5422
5526
  this.apiKeyStorage = a, w("secret", g.String, this, e, "SECRET", !0), w("keyLength", g.String, this, e, "APIKEY_LENGTH"), w("prefix", g.String, this, e, "APIKEY_PREFIX"), w("authScheme", g.String, this, e, "APIKEY_AUTHSCHEME");
@@ -5440,11 +5544,11 @@ class we {
5440
5544
  * Authorization header (with the signature appended.)
5441
5545
  */
5442
5546
  async createKey(a, e, t, r, i) {
5443
- const s = _.randomValue(this.keyLength), n = /* @__PURE__ */ new Date(), c = r ? new Date(n.getTime() + r * 1e3) : void 0, d = we.hashApiKeyValue(s), f = {
5547
+ const s = k.randomValue(this.keyLength), n = /* @__PURE__ */ new Date(), c = r ? new Date(n.getTime() + r * 1e3) : void 0, d = ke.hashApiKeyValue(s), f = {
5444
5548
  name: a,
5445
5549
  value: s,
5446
5550
  userid: e,
5447
- data: z.encodeData(t),
5551
+ data: V.encodeData(t),
5448
5552
  expires: c,
5449
5553
  created: n,
5450
5554
  ...i
@@ -5461,7 +5565,7 @@ class we {
5461
5565
  return { key: f, token: y };
5462
5566
  }
5463
5567
  static hashApiKeyValue(a) {
5464
- return _.hash(a);
5568
+ return k.hash(a);
5465
5569
  }
5466
5570
  /**
5467
5571
  * Returns the hash of the bearer value from the Authorization header.
@@ -5472,20 +5576,20 @@ class we {
5472
5576
  * @returns a hash of the value (without the prefix).
5473
5577
  */
5474
5578
  static hashSignedApiKeyValue(a) {
5475
- return _.hash(a.split(".")[0]);
5579
+ return k.hash(a.split(".")[0]);
5476
5580
  }
5477
5581
  unsignApiKeyValue(a) {
5478
- return _.unsign(a, this.secret).v;
5582
+ return k.unsign(a, this.secret).v;
5479
5583
  }
5480
5584
  signApiKeyValue(a) {
5481
- return _.sign({ v: a }, this.secret);
5585
+ return k.sign({ v: a }, this.secret);
5482
5586
  }
5483
5587
  async getKey(a) {
5484
5588
  if (this.authScheme != "" && a.startsWith(this.authScheme + " ")) {
5485
5589
  const i = new RegExp(`^${this.authScheme} `);
5486
5590
  a = a.replace(i, "");
5487
5591
  }
5488
- const e = this.unsignApiKeyValue(a), t = we.hashApiKeyValue(e), r = await this.apiKeyStorage.getKey(this.prefix + t);
5592
+ const e = this.unsignApiKeyValue(a), t = ke.hashApiKeyValue(e), r = await this.apiKeyStorage.getKey(this.prefix + t);
5489
5593
  if (!("name" in r)) throw new o(l.InvalidKey, "Not a valid API key");
5490
5594
  return { ...r, name: r.name };
5491
5595
  }
@@ -5502,8 +5606,8 @@ class we {
5502
5606
  return await this.getKey(e[1]);
5503
5607
  }
5504
5608
  }
5505
- const dt = 16, ut = 32;
5506
- class J {
5609
+ const pt = 16, Ct = 32;
5610
+ class Q {
5507
5611
  /**
5508
5612
  * Constructor
5509
5613
  * @param options See {@link OAuthClientManagerOptions}
@@ -5532,16 +5636,16 @@ class J {
5532
5636
  * will be populated.
5533
5637
  */
5534
5638
  async createClient(a, e, t, r = !0, i) {
5535
- const s = J.randomClientId();
5639
+ const s = Q.randomClientId();
5536
5640
  let n, c;
5537
- r && (c = J.randomClientSecret(), n = await _.passwordHash(c, {
5641
+ r && (c = Q.randomClientSecret(), n = await k.passwordHash(c, {
5538
5642
  encode: !0,
5539
5643
  iterations: this.oauthPbkdf2Iterations,
5540
5644
  keyLen: this.oauthPbkdf2KeyLength,
5541
5645
  digest: this.oauthPbkdf2Digest
5542
5646
  })), e.forEach((y) => {
5543
- J.validateUri(y);
5544
- }), t || (t = U.allFlows());
5647
+ Q.validateUri(y);
5648
+ }), t || (t = I.allFlows());
5545
5649
  const d = {
5546
5650
  client_id: s,
5547
5651
  client_secret: n,
@@ -5560,7 +5664,7 @@ class J {
5560
5664
  if (y == 4) {
5561
5665
  if (o.asCrossauthError(C).code != l.ClientExists) throw C;
5562
5666
  } else
5563
- d.client_id = J.randomClientId();
5667
+ d.client_id = Q.randomClientId();
5564
5668
  }
5565
5669
  if (!f) throw new o(l.ClientExists);
5566
5670
  return f.client_secret && c && (f.client_secret = c), f;
@@ -5577,13 +5681,13 @@ class J {
5577
5681
  async updateClient(a, e, t = !1) {
5578
5682
  const r = await this.clientStorage.getClientById(a);
5579
5683
  let i = !1, s;
5580
- e.confidential === !0 && !r.confidential || e.confidential === !0 && t ? (s = J.randomClientSecret(), e.client_secret = await _.passwordHash(s, {
5684
+ e.confidential === !0 && !r.confidential || e.confidential === !0 && t ? (s = Q.randomClientSecret(), e.client_secret = await k.passwordHash(s, {
5581
5685
  encode: !0,
5582
5686
  iterations: this.oauthPbkdf2Iterations,
5583
5687
  keyLen: this.oauthPbkdf2KeyLength,
5584
5688
  digest: this.oauthPbkdf2Digest
5585
5689
  }), i = !0) : e.confidential === !1 && (e.client_secret = null), e.redirect_uri && e.redirect_uri.forEach((c) => {
5586
- J.validateUri(c);
5690
+ Q.validateUri(c);
5587
5691
  }), e.client_id = a, await this.clientStorage.updateClient(e);
5588
5692
  const n = await this.clientStorage.getClientById(a);
5589
5693
  return s && (n.client_secret = s), { client: n, newSecret: i };
@@ -5592,13 +5696,13 @@ class J {
5592
5696
  * Create a random OAuth client id
5593
5697
  */
5594
5698
  static randomClientId() {
5595
- return _.randomValue(dt);
5699
+ return k.randomValue(pt);
5596
5700
  }
5597
5701
  /**
5598
5702
  * Create a random OAuth client secret
5599
5703
  */
5600
5704
  static randomClientSecret() {
5601
- return _.randomValue(ut);
5705
+ return k.randomValue(Ct);
5602
5706
  }
5603
5707
  /** If the passed redirect URI is not in the set of valid ones,
5604
5708
  * throw {@link @crossauth/common!CrossauthError} with
@@ -5625,7 +5729,7 @@ class J {
5625
5729
  );
5626
5730
  }
5627
5731
  }
5628
- class ht extends Fe {
5732
+ class St extends je {
5629
5733
  /**
5630
5734
  * Constructor
5631
5735
  *
@@ -5658,14 +5762,14 @@ class ht extends Fe {
5658
5762
  l.Configuration,
5659
5763
  "Cannot specify symmetric key and file"
5660
5764
  );
5661
- this.jwtSecretKeyFile && (this.jwtSecretKey = ie.readFileSync(this.jwtSecretKeyFile, "utf8"));
5765
+ this.jwtSecretKeyFile && (this.jwtSecretKey = ue.readFileSync(this.jwtSecretKeyFile, "utf8"));
5662
5766
  } else if (this.jwtPublicKey || this.jwtPublicKeyFile) {
5663
5767
  if (this.jwtPublicKeyFile && this.jwtPublicKey)
5664
5768
  throw new o(
5665
5769
  l.Configuration,
5666
5770
  "Cannot specify both public key and public key file"
5667
5771
  );
5668
- this.jwtPublicKeyFile && (this.jwtPublicKey = ie.readFileSync(this.jwtPublicKeyFile, "utf8"));
5772
+ this.jwtPublicKeyFile && (this.jwtPublicKey = ue.readFileSync(this.jwtPublicKeyFile, "utf8"));
5669
5773
  }
5670
5774
  }
5671
5775
  /**
@@ -5675,7 +5779,7 @@ class ht extends Fe {
5675
5779
  * @returns Base64-url-encoded hash
5676
5780
  */
5677
5781
  async hash(e) {
5678
- return _.hash(e);
5782
+ return k.hash(e);
5679
5783
  }
5680
5784
  /**
5681
5785
  * If the given token is valid, the paylaod is returned. Otherwise
@@ -5696,7 +5800,7 @@ class ht extends Fe {
5696
5800
  const i = await super.tokenAuthorized(e, t, r);
5697
5801
  if (i && t == "access" && this.persistAccessToken && this.keyStorage)
5698
5802
  try {
5699
- const n = b.accessToken + _.hash(i.jti ? i.jti : i.sid ? i.sid : ""), c = await this.keyStorage.getKey(n), d = /* @__PURE__ */ new Date();
5803
+ const n = U.accessToken + k.hash(i.jti ? i.jti : i.sid ? i.sid : ""), c = await this.keyStorage.getKey(n), d = /* @__PURE__ */ new Date();
5700
5804
  if (c.expires && ((s = c.expires) == null ? void 0 : s.getTime()) < d.getTime()) {
5701
5805
  h.logger.error(m({ msg: "Access token expired in storage but not in JWT" }));
5702
5806
  return;
@@ -5704,14 +5808,14 @@ class ht extends Fe {
5704
5808
  } catch (n) {
5705
5809
  h.logger.warn(m({
5706
5810
  msg: "Couldn't get token from database - is it valid?",
5707
- hashedAccessToken: _.hash(i.jti ? i.jti : i.sid ? i.sid : "")
5811
+ hashedAccessToken: k.hash(i.jti ? i.jti : i.sid ? i.sid : "")
5708
5812
  })), h.logger.debug(m({ err: n }));
5709
5813
  return;
5710
5814
  }
5711
5815
  return i;
5712
5816
  }
5713
5817
  }
5714
- class mt extends Ne {
5818
+ class De extends He {
5715
5819
  /**
5716
5820
  * Constructor
5717
5821
  * @param authServerBaseUrl bsae URI for the authorization server
@@ -5723,10 +5827,10 @@ class mt extends Ne {
5723
5827
  const r = {
5724
5828
  client_id: ""
5725
5829
  };
5726
- w("client_id", g.String, r, t, "OAUTH_CLIENT_ID", !0);
5830
+ console.log("constructor", t), w("client_id", g.String, r, t, "OAUTH_CLIENT_ID", !0);
5727
5831
  super({
5728
5832
  authServerBaseUrl: e,
5729
- tokenConsumer: new ht(
5833
+ tokenConsumer: new St(
5730
5834
  r.client_id,
5731
5835
  {
5732
5836
  audience: r.client_id,
@@ -5744,7 +5848,7 @@ class mt extends Ne {
5744
5848
  u(this, "userStorage");
5745
5849
  this.client_id = r.client_id;
5746
5850
  let i = {};
5747
- if (w("stateLength", g.String, this, t, "OAUTH_STATE_LENGTH"), w("verifierLength", g.String, this, t, "OAUTH_VERIFIER_LENGTH"), w("client_secret", g.String, i, t, "OAUTH_CLIENT_SECRET"), w("codeChallengeMethod", g.String, this, t, "OAUTH_CODE_CHALLENGE_METHOD"), w("deviceAuthorizationUrl", g.String, this, t, "OAUTH_DEVICE_AUTHORIZATION_URL"), w("oauthLogFetch", g.Boolean, this, t, "OAUTH_LOG_FETCH"), this.deviceAuthorizationUrl.startsWith("/") && (this.deviceAuthorizationUrl = this.deviceAuthorizationUrl.substring(1)), i.client_secret && (this.client_secret = i.client_secret), w("userCreationType", g.String, this, t, "OAUTH_USER_CREATION_TYPE"), w("userMatchField", g.String, this, t, "OAUTH_USER_MATCH_FIELD"), w("idTokenMatchField", g.String, this, t, "OAUTH_IDTOKEN_MaTCH_FIELD"), this.userCreationType == "merge" ? this.userCreationFn = ft : this.userCreationType == "embed" ? this.userCreationFn = gt : t.userCreationFn && this.userCreationType == "custom" ? this.userCreationFn = t.userCreationFn : this.userCreationFn = wt, t.userStorage && (this.userStorage = t.userStorage), w("oauthPostType", g.String, this, t, "OAUTH_POST_TYPE"), w("oauthUseUserInfoEndpoint", g.Boolean, this, t, "OAUTH_USE_USER_INFO_ENDPOINT"), w("oauthAuthorizeRedirect", g.String, this, t, "OAUTH_AUTHORIZE_REDIRECT"), this.oauthPostType != "json" && this.oauthPostType != "form")
5851
+ if (w("stateLength", g.String, this, t, "OAUTH_STATE_LENGTH"), w("verifierLength", g.String, this, t, "OAUTH_VERIFIER_LENGTH"), w("client_secret", g.String, i, t, "OAUTH_CLIENT_SECRET"), w("codeChallengeMethod", g.String, this, t, "OAUTH_CODE_CHALLENGE_METHOD"), w("deviceAuthorizationUrl", g.String, this, t, "OAUTH_DEVICE_AUTHORIZATION_URL"), w("oauthLogFetch", g.Boolean, this, t, "OAUTH_LOG_FETCH"), this.deviceAuthorizationUrl.startsWith("/") && (this.deviceAuthorizationUrl = this.deviceAuthorizationUrl.substring(1)), i.client_secret && (this.client_secret = i.client_secret), w("userCreationType", g.String, this, t, "OAUTH_USER_CREATION_TYPE"), w("userMatchField", g.String, this, t, "OAUTH_USER_MATCH_FIELD"), w("idTokenMatchField", g.String, this, t, "OAUTH_IDTOKEN_MaTCH_FIELD"), this.userCreationType == "merge" ? this.userCreationFn = Tt : this.userCreationType == "embed" ? this.userCreationFn = _t : t.userCreationFn && this.userCreationType == "custom" ? this.userCreationFn = t.userCreationFn : this.userCreationFn = kt, t.userStorage && (this.userStorage = t.userStorage), w("oauthPostType", g.String, this, t, "OAUTH_POST_TYPE"), w("oauthUseUserInfoEndpoint", g.Boolean, this, t, "OAUTH_USE_USER_INFO_ENDPOINT"), w("oauthAuthorizeRedirect", g.String, this, t, "OAUTH_AUTHORIZE_REDIRECT"), this.oauthPostType != "json" && this.oauthPostType != "form")
5748
5852
  throw new o(l.Configuration, "oauthPostType must be json or form");
5749
5853
  }
5750
5854
  /**
@@ -5754,7 +5858,7 @@ class mt extends Ne {
5754
5858
  * @returns the Base64-URL-encoded random string
5755
5859
  */
5756
5860
  randomValue(e) {
5757
- return _.randomValue(e);
5861
+ return k.randomValue(e);
5758
5862
  }
5759
5863
  /**
5760
5864
  * Uses {@link @crossauth/backend!Crypto.sha256} to create hash a string using SHA256
@@ -5762,10 +5866,10 @@ class mt extends Ne {
5762
5866
  * @returns the Base64-URL-encoded hash
5763
5867
  */
5764
5868
  async sha256(e) {
5765
- return _.sha256(e);
5869
+ return k.sha256(e);
5766
5870
  }
5767
5871
  }
5768
- async function ft(S, a, e, t) {
5872
+ async function Tt(S, a, e, t) {
5769
5873
  if (!a) throw new o(l.Configuration, "userCreationType set to merge but no user storage set");
5770
5874
  try {
5771
5875
  let r;
@@ -5777,7 +5881,7 @@ async function ft(S, a, e, t) {
5777
5881
  throw h.logger.error(m({ err: r })), r;
5778
5882
  }
5779
5883
  }
5780
- async function gt(S, a, e, t) {
5884
+ async function _t(S, a, e, t) {
5781
5885
  if (!a) throw new o(l.Configuration, "userCreationType set to embed but no user storage set");
5782
5886
  try {
5783
5887
  let r;
@@ -5789,14 +5893,15 @@ async function gt(S, a, e, t) {
5789
5893
  throw h.logger.error({ err: r }), r;
5790
5894
  }
5791
5895
  }
5792
- async function wt(S, a, e, t) {
5896
+ async function kt(S, a, e, t) {
5793
5897
  return {
5898
+ ...S,
5794
5899
  id: S.userid ?? S.sub,
5795
5900
  username: S.sub,
5796
5901
  state: S.state ?? "active"
5797
5902
  };
5798
5903
  }
5799
- function yt(S) {
5904
+ function vt(S) {
5800
5905
  switch (S) {
5801
5906
  case "HS256":
5802
5907
  case "HS384":
@@ -5818,7 +5923,7 @@ function yt(S) {
5818
5923
  "Invalid JWT signing algorithm " + S
5819
5924
  );
5820
5925
  }
5821
- class Yt {
5926
+ class ir {
5822
5927
  /**
5823
5928
  * Constructor
5824
5929
  *
@@ -5878,6 +5983,14 @@ class Yt {
5878
5983
  * The OAuth client to the upstream authz server if configured
5879
5984
  */
5880
5985
  u(this, "upstreamClientOptions");
5986
+ /**
5987
+ * Same as upstreamClient but for case where there is more than one
5988
+ */
5989
+ u(this, "upstreamClients");
5990
+ /**
5991
+ * Same as upstreamClientOptions but for case where there is more than one
5992
+ */
5993
+ u(this, "upstreamClientOptionss");
5881
5994
  // device code
5882
5995
  u(this, "userCodeExpiry", 60 * 5);
5883
5996
  u(this, "userCodeThrottle", 1500);
@@ -5891,7 +6004,7 @@ class Yt {
5891
6004
  u(this, "validFlows", ["all"]);
5892
6005
  /** Set from options. See {@link OAuthAuthorizationServerOptions.allowedFactor2} */
5893
6006
  u(this, "allowedFactor2", []);
5894
- this.clientStorage = a, this.keyStorage = e, this.userStorage = r.userStorage, this.authStorage = r.authStorage, t && (this.authenticators = t), this.clientManager = new J({ clientStorage: a, ...r }), w("authServerBaseUrl", g.String, this, r, "AUTH_SERVER_BASE_URL", !0), w("oauthIssuer", g.String, this, r, "OAUTH_ISSUER"), this.oauthIssuer || (this.oauthIssuer = this.authServerBaseUrl), w("audience", g.String, this, r, "OAUTH_AUDIENCE"), w("oauthPbkdf2Iterations", g.String, this, r, "OAUTH_PBKDF2_ITERATIONS"), w("requireClientSecretOrChallenge", g.Boolean, this, r, "OAUTH_REQUIRE_CLIENT_SECRET_OR_CHALLENGE"), w("jwtAlgorithm", g.String, this, r, "JWT_ALGORITHM"), w("codeLength", g.Number, this, r, "OAUTH_CODE_LENGTH"), w("jwtKeyType", g.String, this, r, "JWT_KEY_TYPE"), w("jwtSecretKeyFile", g.String, this, r, "JWT_SECRET_KEY_FILE"), w("jwtPublicKeyFile", g.String, this, r, "JWT_PUBLIC_KEY_FILE"), w("jwtPrivateKeyFile", g.String, this, r, "JWT_PRIVATE_KEY_FILE"), w("jwtSecretKey", g.String, this, r, "JWT_SECRET_KEY"), w("jwtPublicKey", g.String, this, r, "JWT_PUBLIC_KEY"), w("jwtPrivateKey", g.String, this, r, "JWT_PRIVATE_KEY"), w("jwtKid", g.String, this, r, "JWT_KID"), w("persistAccessToken", g.String, this, r, "OAUTH_PERSIST_ACCESS_TOKEN"), w("issueRefreshToken", g.String, this, r, "OAUTH_ISSUE_REFRESH_TOKEN"), w("opaqueAccessToken", g.String, this, r, "OAUTH_OPAQUE_ACCESS_TOKEN"), w("accessTokenExpiry", g.Number, this, r, "OAUTH_ACCESS_TOKEN_EXPIRY"), w("refreshTokenExpiry", g.Number, this, r, "OAUTH_REFRESH_TOKEN_EXPIRY"), w("rollingRefreshToken", g.Boolean, this, r, "OAUTH_ROLLING_REFRESH_TOKEN"), w("authorizationCodeExpiry", g.Number, this, r, "OAUTH_AUTHORIZATION_CODE_EXPIRY"), w("mfaTokenExpiry", g.Number, this, r, "OAUTH_MFA_TOKEN_EXPIRY"), w("clockTolerance", g.Number, this, r, "OAUTH_CLOCK_TOLERANCE"), w("validateScopes", g.Boolean, this, r, "OAUTH_VALIDATE_SCOPES"), w("emptyScopeIsValid", g.Boolean, this, r, "OAUTH_EMPTY_SCOPE_VALID"), w("validScopes", g.JsonArray, this, r, "OAUTH_VALID_SCOPES"), w("validFlows", g.JsonArray, this, r, "OAUTH_validFlows"), w("idTokenClaims", g.Json, this, r, "OAUTH_ID_TOKEN_CLAIMS"), w("accessTokenClaims", g.Json, this, r, "OAUTH_ACCESS_TOKEN_CLAIMS"), w("allowedFactor2", g.JsonArray, this, r, "ALLOWED_FACTOR2"), w("userCodeExpiry", g.Number, this, r, "DEVICECODE_USERCODE_EXPIRY"), w("userCodeThrottle", g.Number, this, r, "DEVICECODE_USERCODE_THROTTLE"), w("deviceCodePollInterval", g.Number, this, r, "DEVICECODE_POLL_INTERVAL"), w("deviceCodeLength", g.Number, this, r, "DEVICECODE_LENGTH"), w("userCodeLength", g.Number, this, r, "DEVICECODE_USERCODE_LENGTH");
6007
+ this.clientStorage = a, this.keyStorage = e, this.userStorage = r.userStorage, this.authStorage = r.authStorage, t && (this.authenticators = t), this.clientManager = new Q({ clientStorage: a, ...r }), w("authServerBaseUrl", g.String, this, r, "AUTH_SERVER_BASE_URL", !0), w("oauthIssuer", g.String, this, r, "OAUTH_ISSUER"), this.oauthIssuer || (this.oauthIssuer = this.authServerBaseUrl), w("audience", g.String, this, r, "OAUTH_AUDIENCE"), w("oauthPbkdf2Iterations", g.String, this, r, "OAUTH_PBKDF2_ITERATIONS"), w("requireClientSecretOrChallenge", g.Boolean, this, r, "OAUTH_REQUIRE_CLIENT_SECRET_OR_CHALLENGE"), w("jwtAlgorithm", g.String, this, r, "JWT_ALGORITHM"), w("codeLength", g.Number, this, r, "OAUTH_CODE_LENGTH"), w("jwtKeyType", g.String, this, r, "JWT_KEY_TYPE"), w("jwtSecretKeyFile", g.String, this, r, "JWT_SECRET_KEY_FILE"), w("jwtPublicKeyFile", g.String, this, r, "JWT_PUBLIC_KEY_FILE"), w("jwtPrivateKeyFile", g.String, this, r, "JWT_PRIVATE_KEY_FILE"), w("jwtSecretKey", g.String, this, r, "JWT_SECRET_KEY"), w("jwtPublicKey", g.String, this, r, "JWT_PUBLIC_KEY"), w("jwtPrivateKey", g.String, this, r, "JWT_PRIVATE_KEY"), w("jwtKid", g.String, this, r, "JWT_KID"), w("persistAccessToken", g.String, this, r, "OAUTH_PERSIST_ACCESS_TOKEN"), w("issueRefreshToken", g.String, this, r, "OAUTH_ISSUE_REFRESH_TOKEN"), w("opaqueAccessToken", g.String, this, r, "OAUTH_OPAQUE_ACCESS_TOKEN"), w("accessTokenExpiry", g.Number, this, r, "OAUTH_ACCESS_TOKEN_EXPIRY"), w("refreshTokenExpiry", g.Number, this, r, "OAUTH_REFRESH_TOKEN_EXPIRY"), w("rollingRefreshToken", g.Boolean, this, r, "OAUTH_ROLLING_REFRESH_TOKEN"), w("authorizationCodeExpiry", g.Number, this, r, "OAUTH_AUTHORIZATION_CODE_EXPIRY"), w("mfaTokenExpiry", g.Number, this, r, "OAUTH_MFA_TOKEN_EXPIRY"), w("clockTolerance", g.Number, this, r, "OAUTH_CLOCK_TOLERANCE"), w("validateScopes", g.Boolean, this, r, "OAUTH_VALIDATE_SCOPES"), w("emptyScopeIsValid", g.Boolean, this, r, "OAUTH_EMPTY_SCOPE_VALID"), w("validScopes", g.JsonArray, this, r, "OAUTH_VALID_SCOPES"), w("validFlows", g.JsonArray, this, r, "OAUTH_validFlows"), w("idTokenClaims", g.Json, this, r, "OAUTH_ID_TOKEN_CLAIMS"), w("accessTokenClaims", g.Json, this, r, "OAUTH_ACCESS_TOKEN_CLAIMS"), w("allowedFactor2", g.JsonArray, this, r, "ALLOWED_FACTOR2"), w("userCodeExpiry", g.Number, this, r, "DEVICECODE_USERCODE_EXPIRY"), w("userCodeThrottle", g.Number, this, r, "DEVICECODE_USERCODE_THROTTLE"), w("deviceCodePollInterval", g.Number, this, r, "DEVICECODE_POLL_INTERVAL"), w("deviceCodeLength", g.Number, this, r, "DEVICECODE_LENGTH"), w("userCodeLength", g.Number, this, r, "DEVICECODE_USERCODE_LENGTH");
5895
6008
  let i = {};
5896
6009
  if (w("userCodeDashEvery", g.String, i, r, "DEVICECODE_USERCODE_DASH_EVERY"), i.userCodeDashEvery)
5897
6010
  if (i.userCodeDashEvery == "" || i.userCodeDashEvery.toLowerCase() == "null") this.userCodeDashEvery = null;
@@ -5904,9 +6017,23 @@ class Yt {
5904
6017
  "userCodeDashEvery must be a number or null"
5905
6018
  );
5906
6019
  }
5907
- if (w("deviceCodeVerificationUri", g.String, this, r, "DEVICECODE_VERIFICATION_URI"), r.upstreamClient && (this.upstreamClientOptions = r.upstreamClient, this.upstreamClient = new mt(r.upstreamClient.authServerBaseUrl, r.upstreamClient.options), !r.upstreamClient.options.redirect_uri))
5908
- throw new o(l.Configuration, "Must define redirect_uri in upstreamClient options");
5909
- if (this.validFlows.length == 1 && this.validFlows[0] == U.All && (this.validFlows = U.allFlows()), this.jwtAlgorithmChecked = yt(this.jwtAlgorithm), this.jwtSecretKey || this.jwtSecretKeyFile) {
6020
+ if (w("deviceCodeVerificationUri", g.String, this, r, "DEVICECODE_VERIFICATION_URI"), r.upstreamClient) {
6021
+ if (this.upstreamClientOptions = r.upstreamClient, this.upstreamClient = new De(r.upstreamClient.authServerBaseUrl, r.upstreamClient.options), !r.upstreamClient.options.redirect_uri)
6022
+ throw new o(l.Configuration, "Must define redirect_uri in upstreamClient options");
6023
+ } else if (r.upstreamClients) {
6024
+ this.upstreamClientOptionss = r.upstreamClients, this.upstreamClients = {};
6025
+ let s;
6026
+ for (let n in this.upstreamClientOptionss) {
6027
+ let c = this.upstreamClientOptionss[n];
6028
+ if (!s)
6029
+ s = c.sessionDataName;
6030
+ else if (c.sessionDataName != s)
6031
+ throw new o(l.Configuration, "If defining multiple upstream clients, session data name must be the same for each");
6032
+ if (this.upstreamClients[n] = new De(c.authServerBaseUrl, c.options), !c.options.redirect_uri)
6033
+ throw new o(l.Configuration, "Must define redirect_uri in each upstreamClients options");
6034
+ }
6035
+ }
6036
+ if (this.validFlows.length == 1 && this.validFlows[0] == I.All && (this.validFlows = I.allFlows()), this.jwtAlgorithmChecked = vt(this.jwtAlgorithm), this.jwtSecretKey || this.jwtSecretKeyFile) {
5910
6037
  if (this.jwtPublicKey || this.jwtPublicKeyFile || this.jwtPrivateKey || this.jwtPrivateKeyFile)
5911
6038
  throw new o(
5912
6039
  l.Configuration,
@@ -5917,14 +6044,14 @@ class Yt {
5917
6044
  l.Configuration,
5918
6045
  "Cannot specify symmetric key and file"
5919
6046
  );
5920
- this.jwtSecretKeyFile && (this.jwtSecretKey = ie.readFileSync(this.jwtSecretKeyFile, "utf8"));
6047
+ this.jwtSecretKeyFile && (this.jwtSecretKey = ue.readFileSync(this.jwtSecretKeyFile, "utf8"));
5921
6048
  } else if ((this.jwtPrivateKey || this.jwtPrivateKeyFile) && (this.jwtPublicKey || this.jwtPublicKeyFile)) {
5922
6049
  if (this.jwtPrivateKeyFile && this.jwtPrivateKey)
5923
6050
  throw new o(
5924
6051
  l.Configuration,
5925
6052
  "Cannot specify both private key and private key file"
5926
6053
  );
5927
- if (this.jwtPrivateKeyFile && (this.jwtPrivateKey = ie.readFileSync(
6054
+ if (this.jwtPrivateKeyFile && (this.jwtPrivateKey = ue.readFileSync(
5928
6055
  this.jwtPrivateKeyFile,
5929
6056
  "utf8"
5930
6057
  )), this.jwtPublicKeyFile && this.jwtPublicKey)
@@ -5932,7 +6059,7 @@ class Yt {
5932
6059
  l.Configuration,
5933
6060
  "Cannot specify both public key and public key file"
5934
6061
  );
5935
- this.jwtPublicKeyFile && (this.jwtPublicKey = ie.readFileSync(
6062
+ this.jwtPublicKeyFile && (this.jwtPublicKey = ue.readFileSync(
5936
6063
  this.jwtPublicKeyFile,
5937
6064
  "utf8"
5938
6065
  ));
@@ -5946,7 +6073,7 @@ class Yt {
5946
6073
  l.Configuration,
5947
6074
  "If setting jwtPublicKey or jwtPrivate key, must also set jwtKeyType"
5948
6075
  );
5949
- if (this.opaqueAccessToken && (this.persistAccessToken = !0), (this.validFlows.includes(U.Password) || this.validFlows.includes(U.PasswordMfa)) && (!this.userStorage || Object.keys(this.authenticators).length == 0))
6076
+ if (this.opaqueAccessToken && (this.persistAccessToken = !0), (this.validFlows.includes(I.Password) || this.validFlows.includes(I.PasswordMfa)) && (!this.userStorage || Object.keys(this.authenticators).length == 0))
5950
6077
  throw new o(
5951
6078
  l.Configuration,
5952
6079
  "If password flow or password MFA flow is enabled, userStorage and authenticators must be provided"
@@ -5995,11 +6122,11 @@ class Yt {
5995
6122
  const {
5996
6123
  scopes: y,
5997
6124
  error: C,
5998
- error_description: v
6125
+ error_description: _
5999
6126
  } = await this.validateAndPersistScope(e, r, c);
6000
6127
  if (C) return {
6001
6128
  error: C,
6002
- error_description: v
6129
+ error_description: _
6003
6130
  };
6004
6131
  const p = this.inferFlowFromGet(a, y || [], s);
6005
6132
  if (!p || !this.validFlows.includes(p))
@@ -6096,21 +6223,21 @@ class Yt {
6096
6223
  async authenticateClient(a, e, t) {
6097
6224
  let r = !1;
6098
6225
  switch (a) {
6099
- case U.AuthorizationCode:
6100
- case U.AuthorizationCodeWithPKCE:
6226
+ case I.AuthorizationCode:
6227
+ case I.AuthorizationCodeWithPKCE:
6101
6228
  r = e.confidential == !0 || e.client_secret != null || t != null;
6102
6229
  break;
6103
- case U.ClientCredentials:
6230
+ case I.ClientCredentials:
6104
6231
  r = !0;
6105
6232
  break;
6106
- case U.Password:
6107
- case U.PasswordMfa:
6233
+ case I.Password:
6234
+ case I.PasswordMfa:
6108
6235
  r = e.confidential == !0 || e.client_secret != null || t != null;
6109
6236
  break;
6110
- case U.RefreshToken:
6237
+ case I.RefreshToken:
6111
6238
  r = e.confidential == !0 || e.client_secret != null || t != null;
6112
6239
  break;
6113
- case U.DeviceCode:
6240
+ case I.DeviceCode:
6114
6241
  r = e.confidential == !0 || e.client_secret != null || t != null;
6115
6242
  break;
6116
6243
  }
@@ -6120,7 +6247,7 @@ class Yt {
6120
6247
  } : r && (!t || !e.client_secret) ? {
6121
6248
  error: "access_denied",
6122
6249
  error_description: "Client is confidential but either secret not passed or is missing in database"
6123
- } : r && !await _.passwordsEqual(
6250
+ } : r && !await k.passwordsEqual(
6124
6251
  t ?? "",
6125
6252
  e.client_secret ?? ""
6126
6253
  ) ? {
@@ -6167,20 +6294,20 @@ class Yt {
6167
6294
  mfaToken: f,
6168
6295
  oobCode: y,
6169
6296
  bindingCode: C,
6170
- otp: v,
6297
+ otp: _,
6171
6298
  deviceCode: p
6172
6299
  }) {
6173
- var F, $, V;
6300
+ var R, Y, W, ie;
6174
6301
  const T = this.inferFlowFromPost(a, s);
6175
6302
  if (!T) return {
6176
6303
  error: "server_error",
6177
6304
  error_description: "Unable to determine OAuth flow type"
6178
6305
  };
6179
- const E = await this.getClientById(e);
6180
- if (!E.client) return E;
6181
- const A = E.client, j = await this.authenticateClient(T, A, i);
6182
- if (j.error) return j;
6183
- if (T == U.Password && !this.validFlows.includes(T) && !this.validFlows.includes(U.PasswordMfa))
6306
+ const v = await this.getClientById(e);
6307
+ if (!v.client) return v;
6308
+ const b = v.client, M = await this.authenticateClient(T, b, i);
6309
+ if (M.error) return M;
6310
+ if (T == I.Password && !this.validFlows.includes(T) && !this.validFlows.includes(I.PasswordMfa))
6184
6311
  return {
6185
6312
  error: "access_denied",
6186
6313
  error_description: "Unsupported flow type " + T
@@ -6190,115 +6317,244 @@ class Yt {
6190
6317
  error: "access_denied",
6191
6318
  error_description: "Unsupported flow type " + T
6192
6319
  };
6193
- if (A && !A.valid_flow.includes(T))
6320
+ if (b && !b.valid_flow.includes(T))
6194
6321
  return {
6195
6322
  error: "unauthorized_client",
6196
6323
  error_description: "Client does not support " + T
6197
6324
  };
6198
- let H = !1;
6199
- this.issueRefreshToken && T != U.RefreshToken && (H = !0), this.issueRefreshToken && T == U.RefreshToken && this.rollingRefreshToken && (H = !0);
6200
- let K;
6325
+ let $ = !1;
6326
+ this.issueRefreshToken && T != I.RefreshToken && ($ = !0), this.issueRefreshToken && T == I.RefreshToken && this.rollingRefreshToken && ($ = !0);
6327
+ let N;
6201
6328
  if (a == "authorization_code")
6202
- return this.requireClientSecretOrChallenge && A && A.client_secret && !i && !s ? {
6329
+ return this.requireClientSecretOrChallenge && b && b.client_secret && !i && !s ? {
6203
6330
  error: "access_denied",
6204
6331
  error_description: "Must provide either a client secret or use PKCE"
6205
- } : A && A.client_secret && !i ? {
6332
+ } : b && b.client_secret && !i ? {
6206
6333
  error: "access_denied",
6207
6334
  error_description: "No client secret or code verifier provided for authorization coode flow"
6208
6335
  } : r ? await this.makeAccessToken({
6209
- client: A,
6336
+ client: b,
6210
6337
  code: r,
6211
6338
  client_secret: i,
6212
6339
  codeVerifier: s,
6213
- issueRefreshToken: H
6340
+ issueRefreshToken: $
6214
6341
  }) : {
6215
6342
  error: "access_denied",
6216
6343
  error_description: "No authorization code provided for authorization code flow"
6217
6344
  };
6218
6345
  if (a == "refresh_token") {
6219
- if (this.upstreamClient && this.upstreamClientOptions) {
6220
- if (!n)
6221
- return {
6222
- error: "invalid_request",
6223
- error_description: "If executing the refresh token flow, must provide a refresh token"
6224
- };
6225
- let I = await this.upstreamClient.refreshTokenFlow(n);
6226
- if (!I.access_token)
6227
- return {
6228
- error: "access_denied",
6229
- error_description: "Didn't receive an access token"
6230
- };
6231
- let P = I.access_token;
6232
- if (this.upstreamClientOptions.accessTokenIsJwt && (P = await this.upstreamClient.validateAccessToken(I.access_token, !1), !P))
6233
- return {
6234
- error: "access_denied",
6235
- error_description: "Couldn't decode access token"
6236
- };
6237
- const R = await this.upstreamClientOptions.tokenMergeFn(P, I.id_payload, this.userStorage);
6238
- if (R.authorized) {
6239
- const B = await this.createTokensFromPayload(
6240
- e,
6241
- R.access_payload,
6242
- R.id_payload
6243
- );
6244
- return I.access_token = B.access_token, I.id_token = B.id_token, I.id_payload = B.id_payload, I;
6245
- } else
6246
- return h.logger.warn(m({ msg: R.error_description })), {
6247
- error: R.error,
6248
- error_description: R.error_description
6249
- };
6346
+ let K = this.upstreamClient, P = this.upstreamClientOptions, D, O, F;
6347
+ if (this.upstreamClient && this.upstreamClientOptions && (K = this.upstreamClient, P = this.upstreamClientOptions, O = ""), this.upstreamClients && this.upstreamClientOptionss) {
6348
+ let A = n == null ? void 0 : n.split(":", 2);
6349
+ if ((A == null ? void 0 : A.length) == 2) {
6350
+ let x = A[0];
6351
+ if (x in this.upstreamClients)
6352
+ K = this.upstreamClients[x], P = this.upstreamClientOptionss[x], O = A[0], D = A[1];
6353
+ else
6354
+ return {
6355
+ error: "access_denied",
6356
+ error_description: "Refresh token is invalid"
6357
+ };
6358
+ } else {
6359
+ if (F = await this.getRefreshTokenData(n), !n || !F || !this.userStorage)
6360
+ return h.logger.warn(m({ msg: "Received refresh token that is not for upstream client but also has not data" })), {
6361
+ error: "access_denied",
6362
+ error_description: "Refresh token is invalid"
6363
+ };
6364
+ D = F.upstreamRefreshToken, O = F.upstreamLabel, O && (K = this.upstreamClients[O], P = this.upstreamClientOptionss[O]);
6365
+ }
6250
6366
  }
6251
- const N = await this.getRefreshTokenData(n);
6252
- if (!n || !N || !this.userStorage)
6367
+ if (n)
6368
+ if (h.logger.debug(m({ msg: "token endpoint: refresh token flow" })), F && D && K && P) {
6369
+ let A;
6370
+ if (F.username)
6371
+ try {
6372
+ const H = await ((R = this.userStorage) == null ? void 0 : R.getUserByUsername(F.username));
6373
+ A = H == null ? void 0 : H.user;
6374
+ } catch (H) {
6375
+ return h.logger.error(m({
6376
+ err: H,
6377
+ msg: "Couldn't get user for refresh token. Doesn't exist?",
6378
+ username: F.username
6379
+ })), {
6380
+ error: "access_denied",
6381
+ error_description: "Refresh token is invalid"
6382
+ };
6383
+ }
6384
+ let x = F.scope;
6385
+ try {
6386
+ const H = U.refreshToken + k.hash(n);
6387
+ await this.keyStorage.deleteKey(H);
6388
+ } catch (H) {
6389
+ const J = o.asCrossauthError(H);
6390
+ h.logger.debug(m({ err: H })), h.logger.warn(m({ msg: "Cannot delete refresh token", cerr: J }));
6391
+ }
6392
+ h.logger.debug(m({ msg: "token endpoint: refresh token flow: refreshing from upstream client" }));
6393
+ let B = await K.refreshTokenFlow(D);
6394
+ if (!B.access_token)
6395
+ return {
6396
+ error: "access_denied",
6397
+ error_description: "Didn't receive an access token"
6398
+ };
6399
+ let X = B.access_token;
6400
+ if (P.accessTokenIsJwt && (X = await K.validateAccessToken(B.access_token, !1), !X))
6401
+ return {
6402
+ error: "access_denied",
6403
+ error_description: "Couldn't decode access token"
6404
+ };
6405
+ const z = await P.tokenMergeFn(X, B.id_payload, this.userStorage);
6406
+ if (z.authorized) {
6407
+ const H = await this.createTokensFromPayload(
6408
+ e,
6409
+ typeof z.access_payload == "string" ? void 0 : z.access_payload,
6410
+ z.id_payload
6411
+ );
6412
+ B.access_token = H.access_token, B.id_token = H.id_token, B.id_payload = H.id_payload, D = B.refresh_token;
6413
+ const J = await this.createTokensFromPayload(
6414
+ e,
6415
+ typeof z.access_payload == "string" ? void 0 : z.access_payload,
6416
+ z.id_payload
6417
+ );
6418
+ let ee = await this.createRefreshToken(b, {
6419
+ upstreamRefreshToken: D,
6420
+ upstreamLabel: O,
6421
+ scopes: x,
6422
+ username: A == null ? void 0 : A.username
6423
+ });
6424
+ return {
6425
+ access_token: J.access_token,
6426
+ id_token: J.id_token,
6427
+ refresh_token: ee,
6428
+ expires_in: B.expires_in ?? (this.accessTokenExpiry == null ? void 0 : this.accessTokenExpiry),
6429
+ token_type: "Bearer",
6430
+ scope: x
6431
+ };
6432
+ } else
6433
+ return h.logger.warn(m({ msg: z.error_description })), {
6434
+ error: z.error,
6435
+ error_description: z.error_description
6436
+ };
6437
+ } else if (D && K && P) {
6438
+ let A = await K.refreshTokenFlow(D);
6439
+ if (!A.access_token)
6440
+ return {
6441
+ error: "access_denied",
6442
+ error_description: "Didn't receive an access token"
6443
+ };
6444
+ let x = A.access_token;
6445
+ if (P.accessTokenIsJwt && (x = await K.validateAccessToken(A.access_token, !1), !x))
6446
+ return {
6447
+ error: "access_denied",
6448
+ error_description: "Couldn't decode access token"
6449
+ };
6450
+ const B = await P.tokenMergeFn(x, A.id_payload, this.userStorage);
6451
+ if (B.authorized) {
6452
+ const X = await this.createTokensFromPayload(
6453
+ e,
6454
+ typeof B.access_payload == "string" ? void 0 : B.access_payload,
6455
+ B.id_payload
6456
+ );
6457
+ return A.access_token = X.access_token, A.id_token = X.id_token, A.id_payload = X.id_payload, A;
6458
+ } else
6459
+ return h.logger.warn(m({ msg: B.error_description })), {
6460
+ error: B.error,
6461
+ error_description: B.error_description
6462
+ };
6463
+ } else {
6464
+ if (F = await this.getRefreshTokenData(n), !n || !F || !this.userStorage)
6465
+ return {
6466
+ error: "access_denied",
6467
+ error_description: "Refresh token is invalid"
6468
+ };
6469
+ let A = F.upstreamAccessToken, x = F.upstreamIdToken, B;
6470
+ if (F.username)
6471
+ try {
6472
+ const { user: z } = await ((Y = this.userStorage) == null ? void 0 : Y.getUserByUsername(F.username));
6473
+ B = z;
6474
+ } catch (z) {
6475
+ return h.logger.error(m({
6476
+ err: z,
6477
+ msg: "Couldn't get user for refresh token. Doesn't exist?",
6478
+ username: F.username
6479
+ })), {
6480
+ error: "access_denied",
6481
+ error_description: "Refresh token is invalid"
6482
+ };
6483
+ }
6484
+ let X = F.scopes;
6485
+ try {
6486
+ const z = U.refreshToken + k.hash(n);
6487
+ await this.keyStorage.deleteKey(z);
6488
+ } catch (z) {
6489
+ const H = o.asCrossauthError(z);
6490
+ h.logger.debug(m({ err: z })), h.logger.warn(m({ msg: "Cannot delete refresh token", cerr: H }));
6491
+ }
6492
+ if (A && P && K) {
6493
+ let z = A;
6494
+ if (P.accessTokenIsJwt) {
6495
+ let ee = await K.validateAccessToken(A, !1);
6496
+ if (ee) z = ee;
6497
+ else
6498
+ return {
6499
+ error: "access_denied",
6500
+ error_description: "Couldn't decode access token"
6501
+ };
6502
+ }
6503
+ let H = await this.createRefreshToken(b, {
6504
+ upstreamAccessToken: A,
6505
+ upstreamIdToken: x,
6506
+ upstreamLabel: O,
6507
+ scopes: X,
6508
+ username: B == null ? void 0 : B.username
6509
+ });
6510
+ const J = await P.tokenMergeFn(z, x, this.userStorage);
6511
+ if (J.authorized) {
6512
+ const ee = await this.createTokensFromPayload(
6513
+ e,
6514
+ typeof J.access_payload == "string" ? void 0 : J.access_payload,
6515
+ J.id_payload
6516
+ );
6517
+ return {
6518
+ access_token: ee.access_token,
6519
+ id_token: ee.id_token,
6520
+ id_payload: ee.id_payload,
6521
+ refresh_token: H
6522
+ };
6523
+ } else
6524
+ return h.logger.warn(m({ msg: J.error_description })), {
6525
+ error: J.error,
6526
+ error_description: J.error_description
6527
+ };
6528
+ } else
6529
+ return await this.makeAccessToken({
6530
+ client: b,
6531
+ client_secret: i,
6532
+ codeVerifier: s,
6533
+ issueRefreshToken: $,
6534
+ scopes: F.scope,
6535
+ user: B
6536
+ });
6537
+ }
6538
+ else
6253
6539
  return {
6254
6540
  error: "access_denied",
6255
6541
  error_description: "Refresh token is invalid"
6256
6542
  };
6257
- let O;
6258
- if (N.username)
6259
- try {
6260
- const { user: I } = await ((F = this.userStorage) == null ? void 0 : F.getUserByUsername(N.username));
6261
- O = I;
6262
- } catch (I) {
6263
- return h.logger.error(m({
6264
- err: I,
6265
- msg: "Couldn't get user for refresh token. Doesn't exist?",
6266
- username: N.username
6267
- })), {
6268
- error: "access_denied",
6269
- error_description: "Refresh token is invalid"
6270
- };
6271
- }
6272
- try {
6273
- const I = b.refreshToken + _.hash(n);
6274
- await this.keyStorage.deleteKey(I);
6275
- } catch (I) {
6276
- const P = o.asCrossauthError(I);
6277
- h.logger.debug(m({ err: I })), h.logger.warn(m({ msg: "Cannot delete refresh token", cerr: P }));
6278
- }
6279
- return await this.makeAccessToken({
6280
- client: A,
6281
- client_secret: i,
6282
- codeVerifier: s,
6283
- issueRefreshToken: H,
6284
- scopes: N.scope,
6285
- user: O
6286
- });
6287
6543
  } else if (a == "client_credentials") {
6288
6544
  const {
6289
- scopes: N,
6290
- error: O,
6291
- error_description: I
6545
+ scopes: K,
6546
+ error: P,
6547
+ error_description: D
6292
6548
  } = await this.validateAndPersistScope(e, t, void 0);
6293
- return O ? {
6294
- error: O,
6295
- error_description: I
6549
+ return P ? {
6550
+ error: P,
6551
+ error_description: D
6296
6552
  } : await this.makeAccessToken({
6297
- client: A,
6553
+ client: b,
6298
6554
  client_secret: i,
6299
6555
  codeVerifier: s,
6300
- scopes: N,
6301
- issueRefreshToken: H
6556
+ scopes: K,
6557
+ issueRefreshToken: $
6302
6558
  });
6303
6559
  } else if (a == "password") {
6304
6560
  if (!c || !d)
@@ -6312,54 +6568,54 @@ class Yt {
6312
6568
  error: "server_error",
6313
6569
  error_description: "Password authentication not configured"
6314
6570
  };
6315
- const { user: P, secrets: R } = await this.userStorage.getUserByUsername(c), B = this.authenticators[P.factor1];
6316
- if (!B || !B.secretNames().includes("password"))
6571
+ const { user: O, secrets: F } = await this.userStorage.getUserByUsername(c), A = this.authenticators[O.factor1];
6572
+ if (!A || !A.secretNames().includes("password"))
6317
6573
  return {
6318
6574
  error: "access_denied",
6319
6575
  error_description: "Password flow used but factor 1 authenticator does not accept passwords"
6320
6576
  };
6321
- await B.authenticateUser(
6322
- P,
6323
- R,
6577
+ await A.authenticateUser(
6578
+ O,
6579
+ F,
6324
6580
  { password: d }
6325
- ), K = P;
6326
- } catch (P) {
6327
- return h.logger.debug(m({ err: P })), {
6581
+ ), N = O;
6582
+ } catch (O) {
6583
+ return h.logger.debug(m({ err: O })), {
6328
6584
  error: "access_denied",
6329
6585
  error_description: "Username and/or password do not match"
6330
6586
  };
6331
6587
  }
6332
6588
  const {
6333
- scopes: N,
6334
- error: O,
6335
- error_description: I
6336
- } = await this.validateAndPersistScope(e, t, K);
6337
- return O ? {
6338
- error: O,
6339
- error_description: I
6340
- } : K.factor2 ? this.allowedFactor2.length > 0 && (K.state == k.factor2ResetNeeded || !this.allowedFactor2.includes(K.factor2 ? K.factor2 : "none")) ? {
6589
+ scopes: K,
6590
+ error: P,
6591
+ error_description: D
6592
+ } = await this.validateAndPersistScope(e, t, N);
6593
+ return P ? {
6594
+ error: P,
6595
+ error_description: D
6596
+ } : N.factor2 ? this.allowedFactor2.length > 0 && (N.state == E.factor2ResetNeeded || !this.allowedFactor2.includes(N.factor2 ? N.factor2 : "none")) ? {
6341
6597
  error: "access_denied",
6342
6598
  error_description: "2FA method not allowed or needs to be reconfigured"
6343
- } : await this.createMfaRequest(K) : await this.makeAccessToken({
6344
- client: A,
6599
+ } : await this.createMfaRequest(N) : await this.makeAccessToken({
6600
+ client: b,
6345
6601
  client_secret: i,
6346
6602
  codeVerifier: s,
6347
- scopes: N,
6348
- issueRefreshToken: H,
6349
- user: K
6603
+ scopes: K,
6604
+ issueRefreshToken: $,
6605
+ user: N
6350
6606
  });
6351
6607
  } else if (a == "http://auth0.com/oauth/grant-type/mfa-otp") {
6352
6608
  const {
6353
- scopes: N,
6354
- error: O,
6355
- error_description: I
6609
+ scopes: K,
6610
+ error: P,
6611
+ error_description: D
6356
6612
  } = await this.validateAndPersistScope(e, t, void 0);
6357
- if (O)
6613
+ if (P)
6358
6614
  return {
6359
- error: O,
6360
- error_description: I
6615
+ error: P,
6616
+ error_description: D
6361
6617
  };
6362
- if (!v)
6618
+ if (!_)
6363
6619
  return {
6364
6620
  error: "access_denied",
6365
6621
  error_description: "OTP not provided"
@@ -6369,58 +6625,58 @@ class Yt {
6369
6625
  error: "access_denied",
6370
6626
  error_description: "MFA token not provided"
6371
6627
  };
6372
- const P = await this.validateMfaToken(f), R = b.mfaToken + _.hash(f);
6373
- if (!P.user || !P.key)
6628
+ const O = await this.validateMfaToken(f), F = U.mfaToken + k.hash(f);
6629
+ if (!O.user || !O.key)
6374
6630
  return {
6375
6631
  error: "access_denied",
6376
6632
  error_description: "Invalid MFA token"
6377
6633
  };
6378
- const B = this.authenticators[P.user.factor2];
6379
- if (!B || !this.userStorage)
6634
+ const A = this.authenticators[O.user.factor2];
6635
+ if (!A || !this.userStorage)
6380
6636
  return {
6381
6637
  error: "access_denied",
6382
6638
  error_description: "MFA type is not supported for OAuth"
6383
6639
  };
6384
6640
  try {
6385
- const { secrets: M } = await this.userStorage.getUserById(P.user.id);
6386
- await B.authenticateUser(
6387
- P.user,
6388
- M,
6389
- { otp: v }
6641
+ const { secrets: x } = await this.userStorage.getUserById(O.user.id);
6642
+ await A.authenticateUser(
6643
+ O.user,
6644
+ x,
6645
+ { otp: _ }
6390
6646
  );
6391
- } catch (M) {
6392
- return h.logger.debug(m({ err: M })), {
6647
+ } catch (x) {
6648
+ return h.logger.debug(m({ err: x })), {
6393
6649
  error: "access_denied",
6394
6650
  error_description: "Invalid OTP"
6395
6651
  };
6396
6652
  }
6397
6653
  try {
6398
- await this.keyStorage.deleteKey(R);
6399
- } catch (M) {
6400
- h.logger.debug(m({ err: M })), h.logger.warn(m({
6401
- cerr: M,
6654
+ await this.keyStorage.deleteKey(F);
6655
+ } catch (x) {
6656
+ h.logger.debug(m({ err: x })), h.logger.warn(m({
6657
+ cerr: x,
6402
6658
  msg: "Couldn't delete mfa token",
6403
- hashedMfaToken: P.key.value
6659
+ hashedMfaToken: O.key.value
6404
6660
  }));
6405
6661
  }
6406
6662
  return await this.makeAccessToken({
6407
- client: A,
6663
+ client: b,
6408
6664
  client_secret: i,
6409
6665
  codeVerifier: s,
6410
- scopes: N,
6411
- issueRefreshToken: H,
6412
- user: P.user
6666
+ scopes: K,
6667
+ issueRefreshToken: $,
6668
+ user: O.user
6413
6669
  });
6414
6670
  } else if (a == "http://auth0.com/oauth/grant-type/mfa-oob") {
6415
6671
  const {
6416
- scopes: N,
6417
- error: O,
6418
- error_description: I
6672
+ scopes: K,
6673
+ error: P,
6674
+ error_description: D
6419
6675
  } = await this.validateAndPersistScope(e, t, void 0);
6420
- if (O)
6676
+ if (P)
6421
6677
  return {
6422
- error: O,
6423
- error_description: I
6678
+ error: P,
6679
+ error_description: D
6424
6680
  };
6425
6681
  if (!y || !C)
6426
6682
  return {
@@ -6432,57 +6688,57 @@ class Yt {
6432
6688
  error: "access_denied",
6433
6689
  error_description: "MFA token not provided"
6434
6690
  };
6435
- const P = await this.validateMfaToken(f);
6436
- if (!P.user || !P.key)
6691
+ const O = await this.validateMfaToken(f);
6692
+ if (!O.user || !O.key)
6437
6693
  return {
6438
6694
  error: "access_denied",
6439
6695
  error_description: "Invalid MFA token"
6440
6696
  };
6441
- const R = this.authenticators[P.user.factor2];
6442
- if (!R || !this.userStorage)
6697
+ const F = this.authenticators[O.user.factor2];
6698
+ if (!F || !this.userStorage)
6443
6699
  return {
6444
6700
  error: "access_denied",
6445
6701
  error_description: "MFA type is not supported for OAuth"
6446
6702
  };
6447
6703
  try {
6448
- const { secrets: B } = await this.userStorage.getUserById(P.user.id), M = z.decodeData(P.key.data).omfa;
6449
- if (!M || !M.otp || !M.oobCode)
6704
+ const { secrets: A } = await this.userStorage.getUserById(O.user.id), x = V.decodeData(O.key.data).omfa;
6705
+ if (!x || !x.otp || !x.oobCode)
6450
6706
  return {
6451
6707
  error: "server_error",
6452
6708
  error_description: "Cannot retrieve email OTP"
6453
6709
  };
6454
- if (M.oobCode != y)
6710
+ if (x.oobCode != y)
6455
6711
  return {
6456
6712
  error: "access_denied",
6457
6713
  error_description: "Invalid OOB code"
6458
6714
  };
6459
- await R.authenticateUser(
6460
- P.user,
6461
- { ...B, otp: M.otp, expiry: ($ = P.key.expires) == null ? void 0 : $.getTime() },
6715
+ await F.authenticateUser(
6716
+ O.user,
6717
+ { ...A, otp: x.otp, expiry: (W = O.key.expires) == null ? void 0 : W.getTime() },
6462
6718
  { otp: C }
6463
6719
  );
6464
- } catch (B) {
6465
- return h.logger.debug(m({ err: B })), {
6720
+ } catch (A) {
6721
+ return h.logger.debug(m({ err: A })), {
6466
6722
  error: "access_denied",
6467
6723
  error_description: "Invalid OTP"
6468
6724
  };
6469
6725
  }
6470
6726
  try {
6471
- await this.keyStorage.deleteKey(P.key.value);
6472
- } catch (B) {
6473
- h.logger.debug(m({ err: B })), h.logger.warn(m({
6474
- cerr: B,
6727
+ await this.keyStorage.deleteKey(O.key.value);
6728
+ } catch (A) {
6729
+ h.logger.debug(m({ err: A })), h.logger.warn(m({
6730
+ cerr: A,
6475
6731
  msg: "Couldn't delete mfa token",
6476
- hashedMfaToken: P.key.value
6732
+ hashedMfaToken: O.key.value
6477
6733
  }));
6478
6734
  }
6479
6735
  return await this.makeAccessToken({
6480
- client: A,
6736
+ client: b,
6481
6737
  client_secret: i,
6482
6738
  codeVerifier: s,
6483
- scopes: N,
6484
- issueRefreshToken: H,
6485
- user: P.user
6739
+ scopes: K,
6740
+ issueRefreshToken: $,
6741
+ user: O.user
6486
6742
  });
6487
6743
  } else if (a == "urn:ietf:params:oauth:grant-type:device_code") {
6488
6744
  if (!p)
@@ -6490,42 +6746,42 @@ class Yt {
6490
6746
  error: "invalid_request",
6491
6747
  error_description: "No device code given"
6492
6748
  };
6493
- let N;
6749
+ let K;
6494
6750
  try {
6495
- N = await this.keyStorage.getKey(b.deviceCode + p);
6496
- } catch (O) {
6497
- const I = o.asCrossauthError(O);
6498
- return h.logger.debug(m({ err: I })), h.logger.error(m({ msg: "Couldn't get device code", cerr: I })), {
6751
+ K = await this.keyStorage.getKey(U.deviceCode + p);
6752
+ } catch (P) {
6753
+ const D = o.asCrossauthError(P);
6754
+ return h.logger.debug(m({ err: D })), h.logger.error(m({ msg: "Couldn't get device code", cerr: D })), {
6499
6755
  error: "accerss_denied",
6500
6756
  error_description: "Invalid device code"
6501
6757
  };
6502
6758
  }
6503
6759
  try {
6504
- const O = JSON.parse(N.data ?? "{}"), I = (/* @__PURE__ */ new Date()).getTime();
6505
- if (N.expires && I > N.expires.getTime())
6760
+ const P = JSON.parse(K.data ?? "{}"), D = (/* @__PURE__ */ new Date()).getTime();
6761
+ if (K.expires && D > K.expires.getTime())
6506
6762
  return await this.deleteDeviceCode(p), {
6507
6763
  error: "expired_token",
6508
6764
  error_description: "Code has expired"
6509
6765
  };
6510
- if (O.ok != !0)
6766
+ if (P.ok != !0)
6511
6767
  return {
6512
6768
  error: "authorization_pending",
6513
6769
  error_description: "Waiting for user code to be entered"
6514
6770
  };
6515
6771
  {
6516
- let P = O.scope ? O.scope.split(" ") : void 0, R = O.userid ? await ((V = this.userStorage) == null ? void 0 : V.getUserById(O.userid)) : void 0;
6772
+ let O = P.scope ? P.scope.split(" ") : void 0, F = P.userid ? await ((ie = this.userStorage) == null ? void 0 : ie.getUserById(P.userid)) : void 0;
6517
6773
  return await this.deleteDeviceCode(p), await this.makeAccessToken({
6518
- client: A,
6774
+ client: b,
6519
6775
  client_secret: i,
6520
6776
  codeVerifier: s,
6521
- scopes: P,
6522
- issueRefreshToken: H,
6523
- user: R == null ? void 0 : R.user
6777
+ scopes: O,
6778
+ issueRefreshToken: $,
6779
+ user: F == null ? void 0 : F.user
6524
6780
  });
6525
6781
  }
6526
- } catch (O) {
6527
- const I = o.asCrossauthError(O);
6528
- return h.logger.debug(m({ err: I })), h.logger.error(m({ msg: "Couldn't get device code", cerr: I })), await this.deleteDeviceCode(p), {
6782
+ } catch (P) {
6783
+ const D = o.asCrossauthError(P);
6784
+ return h.logger.debug(m({ err: D })), h.logger.error(m({ msg: "Couldn't get device code", cerr: D })), await this.deleteDeviceCode(p), {
6529
6785
  error: "accerss_denied",
6530
6786
  error_description: "Invalid device code"
6531
6787
  };
@@ -6538,7 +6794,7 @@ class Yt {
6538
6794
  }
6539
6795
  async deleteDeviceCode(a) {
6540
6796
  try {
6541
- await this.keyStorage.deleteKey(b.deviceCode + a);
6797
+ await this.keyStorage.deleteKey(U.deviceCode + a);
6542
6798
  } catch (e) {
6543
6799
  const t = o.asCrossauthError(e);
6544
6800
  h.logger.debug(m({ err: t })), h.logger.error(m({ msg: "Couldn't delete device code", cerr: t }));
@@ -6546,7 +6802,7 @@ class Yt {
6546
6802
  }
6547
6803
  async deleteUserCode(a) {
6548
6804
  try {
6549
- await this.keyStorage.deleteKey(b.userCode + a);
6805
+ await this.keyStorage.deleteKey(U.userCode + a);
6550
6806
  } catch (e) {
6551
6807
  const t = o.asCrossauthError(e);
6552
6808
  h.logger.debug(m({ err: t })), h.logger.error(m({ msg: "Couldn't delete user code", cerr: t }));
@@ -6582,7 +6838,7 @@ class Yt {
6582
6838
  error_description: "Invalid deviceCodeVerificationUri"
6583
6839
  };
6584
6840
  }
6585
- const r = U.DeviceCode, i = await this.getClientById(a);
6841
+ const r = I.DeviceCode, i = await this.getClientById(a);
6586
6842
  if (!i.client) return i;
6587
6843
  const s = i.client, n = await this.authenticateClient(r, s, t);
6588
6844
  if (n.error) return n;
@@ -6592,19 +6848,19 @@ class Yt {
6592
6848
  error_description: "Unsupported flow type " + r
6593
6849
  };
6594
6850
  if (e) {
6595
- const { error: T, errorDescription: E } = this.validateScope(e);
6851
+ const { error: T, errorDescription: v } = this.validateScope(e);
6596
6852
  if (T) return {
6597
6853
  error: T,
6598
- error_description: E
6854
+ error_description: v
6599
6855
  };
6600
6856
  }
6601
6857
  let c, d = !1;
6602
6858
  const f = /* @__PURE__ */ new Date(), y = this.userCodeExpiry, C = new Date(f.getTime() + this.userCodeExpiry * 1e3 + this.clockTolerance * 1e3);
6603
6859
  for (let T = 0; T < 10 && !d; ++T)
6604
6860
  try {
6605
- c = _.randomValue(this.deviceCodeLength), await this.keyStorage.saveKey(
6861
+ c = k.randomValue(this.deviceCodeLength), await this.keyStorage.saveKey(
6606
6862
  void 0,
6607
- b.deviceCode + c,
6863
+ U.deviceCode + c,
6608
6864
  f,
6609
6865
  C,
6610
6866
  JSON.stringify({ scope: e, client_id: a })
@@ -6617,13 +6873,13 @@ class Yt {
6617
6873
  error: "server_error",
6618
6874
  error_description: "Couldn't create device code"
6619
6875
  };
6620
- let v;
6876
+ let _;
6621
6877
  d = !1;
6622
6878
  for (let T = 0; T < 10 && !d; ++T)
6623
6879
  try {
6624
- v = _.randomBase32(this.userCodeLength), await this.keyStorage.saveKey(
6880
+ _ = k.randomBase32(this.userCodeLength), await this.keyStorage.saveKey(
6625
6881
  void 0,
6626
- b.userCode + v,
6882
+ U.userCode + _,
6627
6883
  f,
6628
6884
  C,
6629
6885
  JSON.stringify({ deviceCode: c })
@@ -6631,20 +6887,20 @@ class Yt {
6631
6887
  } catch {
6632
6888
  h.logger.debug(m({ msg: `Attempt number${T} at creating a unique authozation code failed` }));
6633
6889
  }
6634
- if (!d || !v)
6890
+ if (!d || !_)
6635
6891
  return await this.deleteDeviceCode(c), {
6636
6892
  error: "server_error",
6637
6893
  error_description: "Couldn't create device code"
6638
6894
  };
6639
- if (v && this.userCodeDashEvery) {
6895
+ if (_ && this.userCodeDashEvery) {
6640
6896
  const T = new RegExp(String.raw`(.{1,${this.userCodeDashEvery}})`, "g");
6641
- v = (p = v.match(T)) == null ? void 0 : p.join("-");
6897
+ _ = (p = _.match(T)) == null ? void 0 : p.join("-");
6642
6898
  }
6643
6899
  return {
6644
6900
  device_code: c,
6645
- user_code: v,
6901
+ user_code: _,
6646
6902
  verification_uri: this.deviceCodeVerificationUri,
6647
- verification_uri_complete: this.deviceCodeVerificationUri + "?user_code=" + v,
6903
+ verification_uri_complete: this.deviceCodeVerificationUri + "?user_code=" + _,
6648
6904
  expires_in: y,
6649
6905
  interval: this.deviceCodePollInterval
6650
6906
  };
@@ -6668,7 +6924,7 @@ class Yt {
6668
6924
  a = a.replace(/[ -]*/g, "");
6669
6925
  let t, r = {};
6670
6926
  try {
6671
- t = await this.keyStorage.getKey(b.userCode + a), r = JSON.parse((t == null ? void 0 : t.data) ?? "{}");
6927
+ t = await this.keyStorage.getKey(U.userCode + a), r = JSON.parse((t == null ? void 0 : t.data) ?? "{}");
6672
6928
  } catch {
6673
6929
  return {
6674
6930
  ok: !1,
@@ -6677,20 +6933,20 @@ class Yt {
6677
6933
  };
6678
6934
  }
6679
6935
  if (!r.deviceCode)
6680
- return h.logger.error(m({ msg: "No device code for user code", userCodeHash: _.hash(a) })), await this.deleteUserCode(a), {
6936
+ return h.logger.error(m({ msg: "No device code for user code", userCodeHash: k.hash(a) })), await this.deleteUserCode(a), {
6681
6937
  ok: !1,
6682
6938
  error: "server_error",
6683
6939
  error_description: "No device code for user code"
6684
6940
  };
6685
6941
  let i;
6686
6942
  try {
6687
- i = await this.keyStorage.getKey(b.deviceCode + r.deviceCode);
6943
+ i = await this.keyStorage.getKey(U.deviceCode + r.deviceCode);
6688
6944
  } catch (y) {
6689
6945
  const C = o.asCrossauthError(y);
6690
6946
  return h.logger.debug(m({ err: C })), h.logger.error(m({
6691
6947
  msg: "Invalid device code for user code",
6692
- userCodeHash: _.hash(a),
6693
- deviceCodeHash: _.hash(r.deviceCode),
6948
+ userCodeHash: k.hash(a),
6949
+ deviceCodeHash: k.hash(r.deviceCode),
6694
6950
  cerr: C
6695
6951
  })), await this.deleteUserCode(a), {
6696
6952
  ok: !1,
@@ -6738,7 +6994,7 @@ class Yt {
6738
6994
  [null]
6739
6995
  ), !d) {
6740
6996
  try {
6741
- e != null && e.id && await this.keyStorage.updateData(b.deviceCode + r.deviceCode, "userid", e.id);
6997
+ e != null && e.id && await this.keyStorage.updateData(U.deviceCode + r.deviceCode, "userid", e.id);
6742
6998
  } catch (y) {
6743
6999
  const C = o.asCrossauthError(y);
6744
7000
  return h.logger.debug(m({ err: C })), h.logger.warn(m({ msg: "Couldn't update user id on user code entry - deleting", cerr: C })), await this.deleteUserCode(a), await this.deleteDeviceCode(r.deviceCode), {
@@ -6756,7 +7012,7 @@ class Yt {
6756
7012
  };
6757
7013
  }
6758
7014
  try {
6759
- e != null && e.id && await this.keyStorage.updateData(b.deviceCode + r.deviceCode, "userid", e.id), await this.keyStorage.updateData(b.deviceCode + r.deviceCode, "ok", !0);
7015
+ e != null && e.id && await this.keyStorage.updateData(U.deviceCode + r.deviceCode, "userid", e.id), await this.keyStorage.updateData(U.deviceCode + r.deviceCode, "ok", !0);
6760
7016
  } catch (y) {
6761
7017
  const C = o.asCrossauthError(y);
6762
7018
  return h.logger.debug(m({ err: C })), h.logger.warn(m({ msg: "Couldn't update status on user code entry - deleting", cerr: C })), await this.deleteUserCode(a), await this.deleteDeviceCode(r.deviceCode), {
@@ -6776,7 +7032,7 @@ class Yt {
6776
7032
  a = a.replace(/[ -]*/g, "");
6777
7033
  let e, t = {};
6778
7034
  try {
6779
- e = await this.keyStorage.getKey(b.userCode + a), t = JSON.parse((e == null ? void 0 : e.data) ?? "{}");
7035
+ e = await this.keyStorage.getKey(U.userCode + a), t = JSON.parse((e == null ? void 0 : e.data) ?? "{}");
6780
7036
  } catch {
6781
7037
  return {
6782
7038
  ok: !1,
@@ -6785,20 +7041,20 @@ class Yt {
6785
7041
  };
6786
7042
  }
6787
7043
  if (!t.deviceCode)
6788
- return h.logger.error(m({ msg: "No device code for user code", userCodeHash: _.hash(a) })), await this.deleteUserCode(a), {
7044
+ return h.logger.error(m({ msg: "No device code for user code", userCodeHash: k.hash(a) })), await this.deleteUserCode(a), {
6789
7045
  ok: !1,
6790
7046
  error: "server_error",
6791
7047
  error_description: "No device code for user code"
6792
7048
  };
6793
7049
  let r;
6794
7050
  try {
6795
- r = await this.keyStorage.getKey(b.deviceCode + t.deviceCode);
7051
+ r = await this.keyStorage.getKey(U.deviceCode + t.deviceCode);
6796
7052
  } catch (n) {
6797
7053
  const c = o.asCrossauthError(n);
6798
7054
  return h.logger.debug(m({ err: c })), h.logger.error(m({
6799
7055
  msg: "Invalid device code for user code",
6800
- userCodeHash: _.hash(a),
6801
- deviceCodeHash: _.hash(t.deviceCode),
7056
+ userCodeHash: k.hash(a),
7057
+ deviceCodeHash: k.hash(t.deviceCode),
6802
7058
  cerr: c
6803
7059
  })), await this.deleteUserCode(a), {
6804
7060
  ok: !1,
@@ -6819,7 +7075,7 @@ class Yt {
6819
7075
  };
6820
7076
  }
6821
7077
  try {
6822
- await this.keyStorage.updateData(b.deviceCode + t.deviceCode, "ok", !0);
7078
+ await this.keyStorage.updateData(U.deviceCode + t.deviceCode, "ok", !0);
6823
7079
  } catch (n) {
6824
7080
  const c = o.asCrossauthError(n);
6825
7081
  return h.logger.debug(m({ err: c })), h.logger.warn(m({ msg: "Couldn't update status on user code entry - deleting", cerr: c })), await this.deleteUserCode(a), await this.deleteDeviceCode(t.deviceCode), {
@@ -6836,7 +7092,7 @@ class Yt {
6836
7092
  };
6837
7093
  }
6838
7094
  async createMfaRequest(a) {
6839
- const e = _.randomValue(this.codeLength), t = b.mfaToken + _.hash(e), r = /* @__PURE__ */ new Date();
7095
+ const e = k.randomValue(this.codeLength), t = U.mfaToken + k.hash(e), r = /* @__PURE__ */ new Date();
6840
7096
  try {
6841
7097
  await this.keyStorage.saveKey(
6842
7098
  a.id,
@@ -6862,7 +7118,7 @@ class Yt {
6862
7118
  var r;
6863
7119
  let e, t;
6864
7120
  try {
6865
- const i = b.mfaToken + _.hash(a);
7121
+ const i = U.mfaToken + k.hash(a);
6866
7122
  if (t = await this.keyStorage.getKey(i), !t.userid)
6867
7123
  return {
6868
7124
  error: "access_denied",
@@ -6890,7 +7146,7 @@ class Yt {
6890
7146
  error_description: "Invalid MFA token"
6891
7147
  };
6892
7148
  try {
6893
- if (z.decodeData(t.data).omfaaid != e.factor2)
7149
+ if (V.decodeData(t.data).omfaaid != e.factor2)
6894
7150
  return {
6895
7151
  error: "access_denied",
6896
7152
  error_description: "authenticatorId not valid for user"
@@ -6947,7 +7203,7 @@ class Yt {
6947
7203
  * @returns respond as defined by the Password MFA spec
6948
7204
  */
6949
7205
  async mfaChallengeEndpoint(a, e, t, r, i) {
6950
- const s = U.PasswordMfa, n = await this.getClientById(e);
7206
+ const s = I.PasswordMfa, n = await this.getClientById(e);
6951
7207
  if (!n.client) return n;
6952
7208
  const c = n.client, d = await this.authenticateClient(s, c, t);
6953
7209
  if (d.error) return d;
@@ -6965,7 +7221,7 @@ class Yt {
6965
7221
  };
6966
7222
  let y = {};
6967
7223
  r == "oob" && (y = {
6968
- oobCode: _.randomValue(this.codeLength)
7224
+ oobCode: k.randomValue(this.codeLength)
6969
7225
  });
6970
7226
  try {
6971
7227
  const C = this.authenticators[f.user.factor2];
@@ -6974,11 +7230,11 @@ class Yt {
6974
7230
  l.Configuration,
6975
7231
  "User's authenticator has not been loaded"
6976
7232
  );
6977
- const v = await C.createOneTimeSecrets(f.user);
7233
+ const _ = await C.createOneTimeSecrets(f.user);
6978
7234
  await this.keyStorage.updateData(
6979
7235
  f.key.value,
6980
7236
  "omfa",
6981
- { ...y, ...v }
7237
+ { ...y, ..._ }
6982
7238
  );
6983
7239
  } catch (C) {
6984
7240
  return h.logger.debug(m({ err: C })), {
@@ -7004,9 +7260,9 @@ class Yt {
7004
7260
  */
7005
7261
  inferFlowFromGet(a, e, t) {
7006
7262
  if (a == "code" && !e.includes("openid"))
7007
- return t ? U.AuthorizationCodeWithPKCE : U.AuthorizationCode;
7263
+ return t ? I.AuthorizationCodeWithPKCE : I.AuthorizationCode;
7008
7264
  if (e.includes("openid") && a == "code")
7009
- return t ? U.AuthorizationCodeWithPKCE : U.AuthorizationCode;
7265
+ return t ? I.AuthorizationCodeWithPKCE : I.AuthorizationCode;
7010
7266
  }
7011
7267
  /**
7012
7268
  * Returns the OAuth flow type that corresonds to the given
@@ -7017,19 +7273,19 @@ class Yt {
7017
7273
  */
7018
7274
  inferFlowFromPost(a, e) {
7019
7275
  if (a == "authorization_code")
7020
- return e ? U.AuthorizationCodeWithPKCE : U.AuthorizationCode;
7276
+ return e ? I.AuthorizationCodeWithPKCE : I.AuthorizationCode;
7021
7277
  if (a == "client_credentials")
7022
- return U.ClientCredentials;
7278
+ return I.ClientCredentials;
7023
7279
  if (a == "refresh_token")
7024
- return U.RefreshToken;
7280
+ return I.RefreshToken;
7025
7281
  if (a == "urn:ietf:params:oauth:grant-type:device_code")
7026
- return U.DeviceCode;
7282
+ return I.DeviceCode;
7027
7283
  if (a == "password")
7028
- return U.Password;
7284
+ return I.Password;
7029
7285
  if (a == "http://auth0.com/oauth/grant-type/mfa-otp")
7030
- return U.PasswordMfa;
7286
+ return I.PasswordMfa;
7031
7287
  if (a == "http://auth0.com/oauth/grant-type/mfa-oob")
7032
- return U.PasswordMfa;
7288
+ return I.PasswordMfa;
7033
7289
  }
7034
7290
  async getAuthorizationCode(a, e, t, r, i, s, n) {
7035
7291
  if (i && (s || (s = "S256"), s != "S256" && s != "plain"))
@@ -7038,7 +7294,7 @@ class Yt {
7038
7294
  error_description: "Code challenge method must be S256 or plain"
7039
7295
  };
7040
7296
  const c = e;
7041
- if (J.validateUri(c), this.requireRedirectUriRegistration && !a.redirect_uri.includes(c))
7297
+ if (Q.validateUri(c), this.requireRedirectUriRegistration && !a.redirect_uri.includes(c))
7042
7298
  return {
7043
7299
  error: "invalid_request",
7044
7300
  error_description: `The redirect uri ${e} is invalid`
@@ -7047,22 +7303,22 @@ class Yt {
7047
7303
  client_id: a.client_id,
7048
7304
  redirect_uri: e
7049
7305
  };
7050
- t && (y.scope = t), i && (y.challengeMethod = s, y.challenge = _.hash(i)), n && (y.username = n.username, y.id = n.id);
7306
+ t && (y.scope = t), i && (y.challengeMethod = s, y.challenge = k.hash(i)), n && (y.username = n.username, y.id = n.id);
7051
7307
  const C = JSON.stringify(y);
7052
- let v = !1, p = "";
7053
- for (let T = 0; T < 10 && !v; ++T)
7308
+ let _ = !1, p = "";
7309
+ for (let T = 0; T < 10 && !_; ++T)
7054
7310
  try {
7055
- p = _.randomValue(this.codeLength), await this.keyStorage.saveKey(
7311
+ p = k.randomValue(this.codeLength), await this.keyStorage.saveKey(
7056
7312
  void 0,
7057
- b.authorizationCode + _.hash(p),
7313
+ U.authorizationCode + k.hash(p),
7058
7314
  d,
7059
7315
  f,
7060
7316
  C
7061
- ), v = !0;
7317
+ ), _ = !0;
7062
7318
  } catch {
7063
7319
  h.logger.debug(m({ msg: `Attempt number${T} at creating a unique authozation code failed` }));
7064
7320
  }
7065
- if (!v)
7321
+ if (!_)
7066
7322
  throw new o(
7067
7323
  l.KeyExists,
7068
7324
  "Couldn't create a authorization code"
@@ -7072,7 +7328,7 @@ class Yt {
7072
7328
  async getAuthorizationCodeData(a) {
7073
7329
  let e, t = {};
7074
7330
  try {
7075
- e = await this.keyStorage.getKey(b.authorizationCode + _.hash(a)), t = z.decodeData(e.data);
7331
+ e = await this.keyStorage.getKey(U.authorizationCode + k.hash(a)), t = V.decodeData(e.data);
7076
7332
  } catch (r) {
7077
7333
  h.logger.debug(m({ err: r }));
7078
7334
  return;
@@ -7081,7 +7337,7 @@ class Yt {
7081
7337
  }
7082
7338
  async deleteAuthorizationCodeData(a) {
7083
7339
  try {
7084
- await this.keyStorage.deleteKey(b.authorizationCode + _.hash(a));
7340
+ await this.keyStorage.deleteKey(U.authorizationCode + k.hash(a));
7085
7341
  } catch (e) {
7086
7342
  h.logger.warn(m({
7087
7343
  err: e,
@@ -7090,7 +7346,7 @@ class Yt {
7090
7346
  }
7091
7347
  }
7092
7348
  async setAuthorizationCodeData(a, e) {
7093
- const t = await this.keyStorage.getKey(b.authorizationCode + _.hash(a));
7349
+ const t = await this.keyStorage.getKey(U.authorizationCode + k.hash(a));
7094
7350
  t.data = JSON.stringify(e), this.keyStorage.updateKey(t);
7095
7351
  }
7096
7352
  /**
@@ -7105,15 +7361,15 @@ class Yt {
7105
7361
  issueRefreshToken: s = !1,
7106
7362
  user: n
7107
7363
  }) {
7108
- var j, H;
7364
+ var M, $;
7109
7365
  let c = !0;
7110
7366
  try {
7111
- a.client_secret != null && (c = await _.passwordsEqual(
7367
+ a.client_secret != null && (c = await k.passwordsEqual(
7112
7368
  t ?? "",
7113
7369
  a.client_secret ?? ""
7114
7370
  ));
7115
- } catch (K) {
7116
- return h.logger.error(m({ err: K })), { error: "server_error", error_description: "Couldn't validate client" };
7371
+ } catch (N) {
7372
+ return h.logger.error(m({ err: N })), { error: "server_error", error_description: "Couldn't validate client" };
7117
7373
  }
7118
7374
  if (!c) return {
7119
7375
  error: "access_denied",
@@ -7121,20 +7377,20 @@ class Yt {
7121
7377
  };
7122
7378
  let d = {};
7123
7379
  if (e) {
7124
- let K;
7380
+ let N;
7125
7381
  try {
7126
- K = await this.keyStorage.getKey(b.authorizationCode + _.hash(e)), d = z.decodeData(K.data);
7127
- } catch (F) {
7128
- return h.logger.debug(m({ err: F })), {
7382
+ N = await this.keyStorage.getKey(U.authorizationCode + k.hash(e)), d = V.decodeData(N.data);
7383
+ } catch (R) {
7384
+ return h.logger.debug(m({ err: R })), {
7129
7385
  error: "access_denied",
7130
7386
  error_description: "Invalid or expired authorization code"
7131
7387
  };
7132
7388
  }
7133
7389
  try {
7134
- await this.keyStorage.deleteKey(K.value);
7135
- } catch (F) {
7390
+ await this.keyStorage.deleteKey(N.value);
7391
+ } catch (R) {
7136
7392
  h.logger.warn(m({
7137
- err: F,
7393
+ err: R,
7138
7394
  msg: "Couldn't delete authorization code from storatge",
7139
7395
  client_id: a == null ? void 0 : a.client_id
7140
7396
  }));
@@ -7147,8 +7403,8 @@ class Yt {
7147
7403
  error_description: "Invalid code challenge/code challenge method method for authorization code"
7148
7404
  };
7149
7405
  if (d.challenge) {
7150
- const K = d.challengeMethod == "plain" ? r ?? "" : _.sha256(r ?? "");
7151
- if (_.hash(K) != d.challenge)
7406
+ const N = d.challengeMethod == "plain" ? r ?? "" : k.sha256(r ?? "");
7407
+ if (k.hash(N) != d.challenge)
7152
7408
  return {
7153
7409
  error: "access_denied",
7154
7410
  error_description: "Code verifier is incorrect"
@@ -7158,56 +7414,56 @@ class Yt {
7158
7414
  let C;
7159
7415
  if ((i && i.includes("openid") || Object.keys(this.accessTokenClaims).length > 0) && this.userStorage && d.username)
7160
7416
  try {
7161
- const { user: K } = await this.userStorage.getUserByUsername(d.username);
7162
- n = K;
7163
- } catch (K) {
7164
- return h.logger.error(m({ err: K })), {
7417
+ const { user: N } = await this.userStorage.getUserByUsername(d.username);
7418
+ n = N;
7419
+ } catch (N) {
7420
+ return h.logger.error(m({ err: N })), {
7165
7421
  error: "server_error",
7166
7422
  error_description: "Couldn't load user data"
7167
7423
  };
7168
7424
  }
7169
- const v = _.uuid();
7425
+ const _ = k.uuid();
7170
7426
  let p = {
7171
- jti: v,
7427
+ jti: _,
7172
7428
  iat: y,
7173
7429
  iss: this.oauthIssuer,
7174
7430
  sub: d.username,
7175
7431
  type: "access"
7176
7432
  };
7177
7433
  p = this.addClaims(p, this.accessTokenClaims, i, n), i && (p.scope = i), this.accessTokenExpiry != null && (p.exp = y + this.accessTokenExpiry, C = new Date(f.getTime() + this.accessTokenExpiry * 1e3 + this.clockTolerance * 1e3)), this.audience && (p.aud = this.audience);
7178
- const T = await new Promise((K, F) => {
7179
- te.sign(
7434
+ const T = await new Promise((N, R) => {
7435
+ ae.sign(
7180
7436
  p,
7181
7437
  this.secretOrPrivateKey,
7182
7438
  { algorithm: this.jwtAlgorithmChecked, keyid: "1" },
7183
- ($, V) => {
7184
- V ? K(V) : F($ || new o(
7439
+ (Y, W) => {
7440
+ W ? N(W) : R(Y || new o(
7185
7441
  l.Unauthorized,
7186
7442
  "Couldn't create jwt"
7187
7443
  ));
7188
7444
  }
7189
7445
  );
7190
7446
  });
7191
- this.persistAccessToken && this.keyStorage && await ((j = this.keyStorage) == null ? void 0 : j.saveKey(
7447
+ this.persistAccessToken && this.keyStorage && await ((M = this.keyStorage) == null ? void 0 : M.saveKey(
7192
7448
  void 0,
7193
7449
  // to avoid user storage dependency, we don't set this
7194
- b.accessToken + _.hash(v),
7450
+ U.accessToken + k.hash(_),
7195
7451
  f,
7196
7452
  C
7197
7453
  ));
7198
- let E;
7454
+ let v;
7199
7455
  if (i && i.includes("openid")) {
7200
- const K = _.uuid();
7201
- let F = {
7456
+ const N = k.uuid();
7457
+ let R = {
7202
7458
  aud: a.client_id,
7203
- jti: K,
7459
+ jti: N,
7204
7460
  iat: y,
7205
7461
  iss: this.oauthIssuer,
7206
7462
  sub: d.username,
7207
7463
  type: "id"
7208
7464
  };
7209
- if (i.includes("email") && (n != null && n.email) && (F.email = n.email), i.includes("address") && n && "address" in n && (F.address = n.address), i.includes("phone") && n && "phone" in n && (F.phone = n.phone), i.includes("profile") && n)
7210
- for (let $ of [
7465
+ if (i.includes("email") && (n != null && n.email) && (R.email = n.email), i.includes("address") && n && "address" in n && (R.address = n.address), i.includes("phone") && n && "phone" in n && (R.phone = n.phone), i.includes("profile") && n)
7466
+ for (let Y of [
7211
7467
  "name",
7212
7468
  "family_name",
7213
7469
  "given_name",
@@ -7223,17 +7479,17 @@ class Yt {
7223
7479
  "locale",
7224
7480
  "updated_at"
7225
7481
  ])
7226
- F[$] = n[$];
7227
- F = this.addClaims(F, this.idTokenClaims, i, n), F.scope = i, this.accessTokenExpiry != null && (F.exp = y + this.accessTokenExpiry), E = await new Promise(($, V) => {
7228
- te.sign(
7229
- F,
7482
+ R[Y] = n[Y];
7483
+ R = this.addClaims(R, this.idTokenClaims, i, n), R.scope = i, this.accessTokenExpiry != null && (R.exp = y + this.accessTokenExpiry), v = await new Promise((Y, W) => {
7484
+ ae.sign(
7485
+ R,
7230
7486
  this.secretOrPrivateKey,
7231
7487
  {
7232
7488
  algorithm: this.jwtAlgorithmChecked,
7233
7489
  keyid: this.jwtKid
7234
7490
  },
7235
- (N, O) => {
7236
- O ? $(O) : V(N || new o(
7491
+ (ie, K) => {
7492
+ K ? Y(K) : W(ie || new o(
7237
7493
  l.Unauthorized,
7238
7494
  "Couldn't create jwt"
7239
7495
  ));
@@ -7241,51 +7497,97 @@ class Yt {
7241
7497
  );
7242
7498
  });
7243
7499
  }
7244
- let A;
7500
+ let b;
7245
7501
  if (s) {
7246
- const K = {
7502
+ const N = {
7247
7503
  username: d.username,
7248
7504
  client_id: a.client_id
7249
7505
  };
7250
- i && (K.scope = i);
7251
- let F;
7252
- const V = {
7253
- jti: _.uuid(),
7506
+ i && (N.scope = i);
7507
+ let R;
7508
+ const W = {
7509
+ jti: k.uuid(),
7254
7510
  iat: y,
7255
7511
  iss: this.oauthIssuer,
7256
7512
  sub: d.username,
7257
7513
  type: "refresh"
7258
7514
  };
7259
- this.refreshTokenExpiry != null && (V.exp = y + this.refreshTokenExpiry, F = this.refreshTokenExpiry ? new Date(y + this.refreshTokenExpiry * 1e3 + this.clockTolerance * 1e3) : void 0), this.oauthIssuer && (V.aud = this.oauthIssuer), A = await new Promise((N, O) => {
7260
- te.sign(
7261
- V,
7515
+ this.refreshTokenExpiry != null && (W.exp = y + this.refreshTokenExpiry, R = this.refreshTokenExpiry ? new Date(y + this.refreshTokenExpiry * 1e3 + this.clockTolerance * 1e3) : void 0), this.oauthIssuer && (W.aud = this.oauthIssuer), b = await new Promise((ie, K) => {
7516
+ ae.sign(
7517
+ W,
7262
7518
  this.secretOrPrivateKey,
7263
7519
  { algorithm: this.jwtAlgorithmChecked, keyid: "1" },
7264
- (I, P) => {
7265
- P ? N(P) : O(I || new o(
7520
+ (P, D) => {
7521
+ D ? ie(D) : K(P || new o(
7266
7522
  l.Unauthorized,
7267
7523
  "Couldn't create jwt"
7268
7524
  ));
7269
7525
  }
7270
7526
  );
7271
- }), A && await ((H = this.keyStorage) == null ? void 0 : H.saveKey(
7527
+ }), b && await (($ = this.keyStorage) == null ? void 0 : $.saveKey(
7272
7528
  void 0,
7273
7529
  // to avoid user storage dependency
7274
- b.refreshToken + _.hash(A),
7530
+ U.refreshToken + k.hash(b),
7275
7531
  f,
7276
- F,
7277
- JSON.stringify(K)
7532
+ R,
7533
+ JSON.stringify(N)
7278
7534
  ));
7279
7535
  }
7280
7536
  return {
7281
7537
  access_token: T,
7282
- id_token: E,
7283
- refresh_token: A,
7538
+ id_token: v,
7539
+ refresh_token: b,
7284
7540
  expires_in: this.accessTokenExpiry == null ? void 0 : this.accessTokenExpiry,
7285
7541
  token_type: "Bearer",
7286
7542
  scope: i ? i.join(" ") : void 0
7287
7543
  };
7288
7544
  }
7545
+ async createRefreshToken(a, {
7546
+ upstreamRefreshToken: e,
7547
+ upstreamLabel: t,
7548
+ scopes: r,
7549
+ username: i,
7550
+ upstreamAccessToken: s,
7551
+ upstreamIdToken: n
7552
+ }) {
7553
+ var T;
7554
+ const c = /* @__PURE__ */ new Date(), d = Math.ceil(c.getTime() / 1e3);
7555
+ let f;
7556
+ const y = {
7557
+ username: i,
7558
+ client_id: a.client_id
7559
+ };
7560
+ r && (y.scope = r), e && (y.upstreamRefreshToken = e, y.upstreamLabel = t);
7561
+ let C;
7562
+ const p = {
7563
+ jti: k.uuid(),
7564
+ iat: d,
7565
+ iss: this.oauthIssuer,
7566
+ sub: i,
7567
+ type: "refresh"
7568
+ };
7569
+ if (this.refreshTokenExpiry != null && (p.exp = d + this.refreshTokenExpiry, C = this.refreshTokenExpiry ? new Date(d + this.refreshTokenExpiry * 1e3 + this.clockTolerance * 1e3) : void 0), this.oauthIssuer && (p.aud = this.oauthIssuer), f = await new Promise((v, b) => {
7570
+ ae.sign(
7571
+ p,
7572
+ this.secretOrPrivateKey,
7573
+ { algorithm: this.jwtAlgorithmChecked, keyid: "1" },
7574
+ (M, $) => {
7575
+ $ ? v($) : b(M || new o(
7576
+ l.Unauthorized,
7577
+ "Couldn't create jwt"
7578
+ ));
7579
+ }
7580
+ );
7581
+ }), f)
7582
+ return f && await ((T = this.keyStorage) == null ? void 0 : T.saveKey(
7583
+ void 0,
7584
+ // to avoid user storage dependency
7585
+ U.refreshToken + k.hash(f),
7586
+ c,
7587
+ C,
7588
+ JSON.stringify(y)
7589
+ )), f;
7590
+ }
7289
7591
  /**
7290
7592
  * Create an access token
7291
7593
  */
@@ -7294,7 +7596,7 @@ class Yt {
7294
7596
  const r = /* @__PURE__ */ new Date(), i = Math.ceil(r.getTime() / 1e3);
7295
7597
  let s, n, c, d;
7296
7598
  if (e) {
7297
- const y = _.uuid();
7599
+ const y = k.uuid();
7298
7600
  let C = {
7299
7601
  ...e,
7300
7602
  jti: y,
@@ -7302,13 +7604,13 @@ class Yt {
7302
7604
  iss: this.oauthIssuer,
7303
7605
  type: "access"
7304
7606
  };
7305
- this.accessTokenExpiry != null && (C.exp = i + this.accessTokenExpiry, s = new Date(r.getTime() + this.accessTokenExpiry * 1e3 + this.clockTolerance * 1e3)), this.audience && (C.aud = this.audience), n = await new Promise((v, p) => {
7306
- te.sign(
7607
+ this.accessTokenExpiry != null && (C.exp = i + this.accessTokenExpiry, s = new Date(r.getTime() + this.accessTokenExpiry * 1e3 + this.clockTolerance * 1e3)), this.audience && (C.aud = this.audience), n = await new Promise((_, p) => {
7608
+ ae.sign(
7307
7609
  C,
7308
7610
  this.secretOrPrivateKey,
7309
7611
  { algorithm: this.jwtAlgorithmChecked, keyid: "1" },
7310
- (T, E) => {
7311
- E ? v(E) : p(T || new o(
7612
+ (T, v) => {
7613
+ v ? _(v) : p(T || new o(
7312
7614
  l.Unauthorized,
7313
7615
  "Couldn't create jwt"
7314
7616
  ));
@@ -7317,13 +7619,13 @@ class Yt {
7317
7619
  }), d = C, this.persistAccessToken && this.keyStorage && await ((f = this.keyStorage) == null ? void 0 : f.saveKey(
7318
7620
  void 0,
7319
7621
  // to avoid user storage dependency, we don't set this
7320
- b.accessToken + _.hash(y),
7622
+ U.accessToken + k.hash(y),
7321
7623
  r,
7322
7624
  s
7323
7625
  ));
7324
7626
  }
7325
7627
  if (t != null) {
7326
- const y = _.uuid();
7628
+ const y = k.uuid();
7327
7629
  if (t = {
7328
7630
  ...t,
7329
7631
  aud: a,
@@ -7333,16 +7635,16 @@ class Yt {
7333
7635
  type: "id"
7334
7636
  }, t) {
7335
7637
  const C = t;
7336
- c = await new Promise((v, p) => {
7337
- te.sign(
7638
+ c = await new Promise((_, p) => {
7639
+ ae.sign(
7338
7640
  C,
7339
7641
  this.secretOrPrivateKey,
7340
7642
  {
7341
7643
  algorithm: this.jwtAlgorithmChecked,
7342
7644
  keyid: this.jwtKid
7343
7645
  },
7344
- (T, E) => {
7345
- E ? v(E) : p(T || new o(
7646
+ (T, v) => {
7647
+ v ? _(v) : p(T || new o(
7346
7648
  l.Unauthorized,
7347
7649
  "Couldn't create jwt"
7348
7650
  ));
@@ -7399,7 +7701,7 @@ class Yt {
7399
7701
  */
7400
7702
  async validAuthorizationCode(a) {
7401
7703
  try {
7402
- const e = b.authorizationCode + _.hash(a);
7704
+ const e = U.authorizationCode + k.hash(a);
7403
7705
  return await this.keyStorage.getKey(e), !0;
7404
7706
  } catch (e) {
7405
7707
  return h.logger.debug(m({ err: e })), !1;
@@ -7413,7 +7715,7 @@ class Yt {
7413
7715
  */
7414
7716
  async validRefreshToken(a) {
7415
7717
  try {
7416
- const e = b.refreshToken + _.hash(a);
7718
+ const e = U.refreshToken + k.hash(a);
7417
7719
  return await this.keyStorage.getKey(e), !0;
7418
7720
  } catch (e) {
7419
7721
  return h.logger.debug(m({ err: e })), !1;
@@ -7428,7 +7730,7 @@ class Yt {
7428
7730
  async getRefreshTokenData(a) {
7429
7731
  if (a)
7430
7732
  try {
7431
- const e = b.refreshToken + _.hash(a), t = await this.keyStorage.getKey(e);
7733
+ const e = U.refreshToken + k.hash(a), t = await this.keyStorage.getKey(e);
7432
7734
  return JSON.parse(t.data || "{}");
7433
7735
  } catch (e) {
7434
7736
  h.logger.debug(m({ err: e }));
@@ -7462,7 +7764,7 @@ class Yt {
7462
7764
  try {
7463
7765
  const e = await this.validateJwt(a, "access");
7464
7766
  if (this.persistAccessToken) {
7465
- const t = b.accessToken + _.hash(e.payload.jti);
7767
+ const t = U.accessToken + k.hash(e.payload.jti);
7466
7768
  await this.keyStorage.getKey(t);
7467
7769
  }
7468
7770
  return e;
@@ -7473,7 +7775,7 @@ class Yt {
7473
7775
  }
7474
7776
  async validateJwt(a, e) {
7475
7777
  return new Promise((t, r) => {
7476
- te.verify(
7778
+ ae.verify(
7477
7779
  a,
7478
7780
  this.secretOrPublicKey,
7479
7781
  { clockTolerance: this.clockTolerance, complete: !0 },
@@ -7536,7 +7838,7 @@ class Yt {
7536
7838
  */
7537
7839
  responseTypesSupported() {
7538
7840
  let a = [];
7539
- return (this.validFlows.includes(U.AuthorizationCode) || this.validFlows.includes(U.AuthorizationCodeWithPKCE) || this.validFlows.includes(U.OidcAuthorizationCode)) && a.push("code"), a;
7841
+ return (this.validFlows.includes(I.AuthorizationCode) || this.validFlows.includes(I.AuthorizationCodeWithPKCE) || this.validFlows.includes(I.OidcAuthorizationCode)) && a.push("code"), a;
7540
7842
  }
7541
7843
  /**
7542
7844
  * Returns an OIDC configuration object based on this authorization
@@ -7558,7 +7860,7 @@ class Yt {
7558
7860
  }) {
7559
7861
  let i = [];
7560
7862
  this.validFlows.forEach((n) => {
7561
- const c = U.grantType(n);
7863
+ const c = I.grantType(n);
7562
7864
  c && (i = [...i, ...c]);
7563
7865
  });
7564
7866
  const s = [
@@ -7615,7 +7917,7 @@ class Yt {
7615
7917
  jwks() {
7616
7918
  let a = [];
7617
7919
  if (this.jwtPublicKey) {
7618
- const e = $e(this.jwtPublicKey).export({ format: "jwk" });
7920
+ const e = Qe(this.jwtPublicKey).export({ format: "jwk" });
7619
7921
  e.kid = "1", e.alg = this.jwtKeyType, a.push(e);
7620
7922
  }
7621
7923
  return { keys: a };
@@ -7655,7 +7957,7 @@ class Yt {
7655
7957
  } : {};
7656
7958
  }
7657
7959
  }
7658
- class Gt {
7960
+ class ar {
7659
7961
  /**
7660
7962
  * Constructor
7661
7963
  * @param tokenConsumers one or more consumers that will process
@@ -7686,7 +7988,7 @@ class Gt {
7686
7988
  */
7687
7989
  async accessTokenAuthorized(a) {
7688
7990
  try {
7689
- const e = qe.decodeJwt(a);
7991
+ const e = et.decodeJwt(a);
7690
7992
  for (let t of this.tokenConsumers)
7691
7993
  if (e.iss == t.authServerBaseUrl && (e.aud == t.audience || e.aud == null && t.audience == ""))
7692
7994
  return await t.tokenAuthorized(a, "access");
@@ -7698,44 +8000,45 @@ class Gt {
7698
8000
  }
7699
8001
  }
7700
8002
  export {
7701
- we as ApiKeyManager,
7702
- ae as Authenticator,
7703
- _ as Crypto,
7704
- ct as DoubleSubmitCsrfToken,
7705
- Mt as DummyFactor2Authenticator,
7706
- X as EmailAuthenticator,
7707
- Rt as InMemoryKeyStorage,
7708
- zt as InMemoryOAuthAuthorizationStorage,
7709
- Bt as InMemoryOAuthClientStorage,
7710
- xt as InMemoryUserStorage,
7711
- z as KeyStorage,
7712
- $t as LdapAuthenticator,
7713
- le as LdapUserStorage,
7714
- Ee as LocalPasswordAuthenticator,
7715
- Yt as OAuthAuthorizationServer,
7716
- pe as OAuthAuthorizationStorage,
7717
- mt as OAuthClientBackend,
7718
- J as OAuthClientManager,
7719
- ye as OAuthClientStorage,
7720
- Gt as OAuthResourceServer,
7721
- ht as OAuthTokenConsumer,
8003
+ ke as ApiKeyManager,
8004
+ de as Authenticator,
8005
+ k as Crypto,
8006
+ yt as DoubleSubmitCsrfToken,
8007
+ Zt as DummyFactor2Authenticator,
8008
+ ne as EmailAuthenticator,
8009
+ Mt as InMemoryKeyStorage,
8010
+ qt as InMemoryOAuthAuthorizationStorage,
8011
+ $t as InMemoryOAuthClientStorage,
8012
+ Vt as InMemoryUserStorage,
8013
+ V as KeyStorage,
8014
+ Xt as LdapAuthenticator,
8015
+ ge as LdapUserStorage,
8016
+ Ke as LocalPasswordAuthenticator,
8017
+ ir as OAuthAuthorizationServer,
8018
+ Ee as OAuthAuthorizationStorage,
8019
+ De as OAuthClientBackend,
8020
+ Q as OAuthClientManager,
8021
+ ve as OAuthClientStorage,
8022
+ ar as OAuthResourceServer,
8023
+ St as OAuthTokenConsumer,
8024
+ er as OidcAuthenticator,
7722
8025
  g as ParamType,
7723
- Ie as PasswordAuthenticator,
7724
- jt as PostgresKeyStorage,
7725
- Vt as PostgresOAuthAuthorizationStorage,
7726
- Ht as PostgresOAuthClientStorage,
7727
- Lt as PostgresUserStorage,
7728
- Ft as PrismaKeyStorage,
7729
- Dt as PrismaOAuthAuthorizationStorage,
7730
- Nt as PrismaOAuthClientStorage,
7731
- Z as PrismaUserStorage,
7732
- x as SessionCookie,
7733
- Jt as SessionManager,
7734
- ee as SmsAuthenticator,
7735
- D as TokenEmailer,
7736
- qt as TotpAuthenticator,
7737
- Pe as TwilioAuthenticator,
7738
- L as UserStorage,
8026
+ Re as PasswordAuthenticator,
8027
+ Jt as PostgresKeyStorage,
8028
+ Gt as PostgresOAuthAuthorizationStorage,
8029
+ Yt as PostgresOAuthClientStorage,
8030
+ Wt as PostgresUserStorage,
8031
+ Lt as PrismaKeyStorage,
8032
+ Ht as PrismaOAuthAuthorizationStorage,
8033
+ jt as PrismaOAuthClientStorage,
8034
+ se as PrismaUserStorage,
8035
+ j as SessionCookie,
8036
+ rr as SessionManager,
8037
+ le as SmsAuthenticator,
8038
+ L as TokenEmailer,
8039
+ Qt as TotpAuthenticator,
8040
+ Be as TwilioAuthenticator,
8041
+ q as UserStorage,
7739
8042
  w as setParameter,
7740
- Wt as toCookieSerializeOptions
8043
+ tr as toCookieSerializeOptions
7741
8044
  };