@crossauth/backend 0.0.39 → 0.0.41

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,19 +1,19 @@
1
1
  var Ae = Object.defineProperty;
2
2
  var Ie = (S, s, e) => s in S ? Ae(S, s, { enumerable: !0, configurable: !0, writable: !0, value: e }) : S[s] = e;
3
3
  var h = (S, s, e) => Ie(S, typeof s != "symbol" ? s + "" : s, e);
4
- import { CrossauthError as o, ErrorCode as l, UserState as E, CrossauthLogger as u, j as f, OAuthFlows as b, KeyPrefix as U, OAuthTokenConsumerBase as Pe, OAuthClientBase as Ke } from "@crossauth/common";
4
+ import { CrossauthError as o, ErrorCode as l, UserState as E, CrossauthLogger as u, j as f, OAuthFlows as U, KeyPrefix as b, OAuthTokenConsumerBase as Pe, OAuthClientBase as Ke } from "@crossauth/common";
5
5
  import { PrismaClient as ce, Prisma as X } from "@prisma/client";
6
6
  import ye from "@mbakereth/ldapjs";
7
- import { timingSafeEqual as he, randomBytes as ue, randomUUID as Fe, createHash as Oe, pbkdf2 as Ne, createHmac as ie, createCipheriv as Re, createDecipheriv as De, randomInt as ee } from "node:crypto";
7
+ import { timingSafeEqual as he, randomBytes as ue, randomUUID as Oe, createHash as Fe, pbkdf2 as Ne, createHmac as se, createCipheriv as De, createDecipheriv as Re, randomInt as te } from "node:crypto";
8
8
  import { promisify as xe } from "node:util";
9
9
  import W from "nunjucks";
10
10
  import Ee from "nodemailer";
11
11
  import Be from "twilio";
12
- import Le from "qrcode";
12
+ import ze from "qrcode";
13
13
  import { authenticator as fe } from "otplib";
14
- import se from "jsonwebtoken";
15
- import { createPublicKey as ze } from "crypto";
16
- import te from "node:fs";
14
+ import ee from "jsonwebtoken";
15
+ import re from "node:fs";
16
+ import { createPublicKey as Le } from "crypto";
17
17
  import * as He from "jose";
18
18
  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 || {});
19
19
  function je(S, s) {
@@ -98,7 +98,7 @@ class L {
98
98
  return s.normalize("NFD").replace(new RegExp("\\p{Diacritic}", "gu"), "").toLowerCase();
99
99
  }
100
100
  }
101
- class x {
101
+ class z {
102
102
  /**
103
103
  * Returns an object decoded from the data field as a JSON string
104
104
  * @param data the JSON string to decode
@@ -413,7 +413,7 @@ class G extends L {
413
413
  }
414
414
  }
415
415
  }
416
- class kt extends x {
416
+ class Et extends z {
417
417
  /**
418
418
  * Constructor with user storage object to use plus optional parameters.
419
419
  *
@@ -683,7 +683,7 @@ class kt extends x {
683
683
  }
684
684
  }
685
685
  }
686
- class Et extends me {
686
+ class bt extends me {
687
687
  /**
688
688
  * Constructor with user storage object to use plus optional parameters.
689
689
  *
@@ -778,7 +778,7 @@ class Et extends me {
778
778
  }
779
779
  if (i) {
780
780
  for (let d = 0; d < i.length; ++d)
781
- if (!b.isValidFlow(i[d])) throw new o(l.InvalidOAuthFlow, "Invalid flow " + i[d]);
781
+ if (!U.isValidFlow(i[d])) throw new o(l.InvalidOAuthFlow, "Invalid flow " + i[d]);
782
782
  }
783
783
  try {
784
784
  c = await t[this.clientTable].create({
@@ -865,7 +865,7 @@ class Et extends me {
865
865
  }
866
866
  if (i) {
867
867
  for (let a = 0; a < i.length; ++a)
868
- if (!b.isValidFlow(i[a])) throw new o(l.InvalidOAuthFlow, "Redirect Uri's may not contain page fragments");
868
+ if (!U.isValidFlow(i[a])) throw new o(l.InvalidOAuthFlow, "Redirect Uri's may not contain page fragments");
869
869
  }
870
870
  try {
871
871
  let a = { ...e };
@@ -946,7 +946,7 @@ class Et extends me {
946
946
  }
947
947
  }
948
948
  }
949
- class bt extends we {
949
+ class Ut extends we {
950
950
  /**
951
951
  * Constructor with user storage object to use plus optional parameters.
952
952
  *
@@ -1011,7 +1011,7 @@ class bt extends we {
1011
1011
  }
1012
1012
  }
1013
1013
  }
1014
- class Ut extends L {
1014
+ class At extends L {
1015
1015
  /**
1016
1016
  * Creates a InMemoryUserStorage object, optionally overriding defaults.
1017
1017
  * @param options see {@link InMemoryUserStorageOptions}
@@ -1157,7 +1157,7 @@ class Ut extends L {
1157
1157
  return i;
1158
1158
  }
1159
1159
  }
1160
- class At extends x {
1160
+ class It extends z {
1161
1161
  /**
1162
1162
  * Constructor
1163
1163
  */
@@ -1310,7 +1310,7 @@ class At extends x {
1310
1310
  this.deleteDataInternal(i, t) && (r.data = JSON.stringify(i));
1311
1311
  }
1312
1312
  }
1313
- class It extends me {
1313
+ class Pt extends me {
1314
1314
  /**
1315
1315
  * Constructor
1316
1316
  */
@@ -1401,7 +1401,7 @@ class It extends me {
1401
1401
  return a;
1402
1402
  }
1403
1403
  }
1404
- class Pt extends we {
1404
+ class Kt extends we {
1405
1405
  /**
1406
1406
  * Constructor
1407
1407
  */
@@ -1903,7 +1903,7 @@ class Y extends L {
1903
1903
  }
1904
1904
  }
1905
1905
  }
1906
- class qe extends x {
1906
+ class qe extends z {
1907
1907
  /**
1908
1908
  * Constructor with user storage object to use plus optional parameters.
1909
1909
  *
@@ -2216,10 +2216,10 @@ class We extends me {
2216
2216
  t && r && (p = `where c.${t} = ` + d.nextParameter(), w.push(r)), i !== null && i == null || (p == "" ? p = "where " : p += " and ", i == null ? p += "userid is null" : (p += `${this.useridForeignKeyColumn} = ` + d.nextParameter(), w.push(i))), n && (a || (a = 0), a = Number(a), n = Number(n), C == "" ? C = "where " : C += " and ", C += ` c.client_id in (select client_id from ${this.clientTable} limit ${n} offset ${a})`, p == "" ? p = "where " : p += " and ", p += ` c.client_id in (select client_id from ${this.clientTable} limit ${n} offset ${a})`), y += C, v += p;
2217
2217
  let T = y + " union " + v + " order by client_id";
2218
2218
  const k = await e.execute(T, w);
2219
- let A;
2220
- for (let z of k)
2221
- (!A || z.client_id != A.client_id) && (A && c.push(A), A = this.makeClient(z), A.valid_flow = [], A.redirect_uri = []), z.uri && A.redirect_uri.push(z.uri), z.flow && A.valid_flow.push(z.flow);
2222
- return A && c.push(A), c;
2219
+ let P;
2220
+ for (let H of k)
2221
+ (!P || H.client_id != P.client_id) && (P && c.push(P), P = this.makeClient(H), P.valid_flow = [], P.redirect_uri = []), H.uri && P.redirect_uri.push(H.uri), H.flow && P.valid_flow.push(H.flow);
2222
+ return P && c.push(P), c;
2223
2223
  }
2224
2224
  /**
2225
2225
  * Saves a key in the session table.
@@ -2253,7 +2253,7 @@ class We extends me {
2253
2253
  }
2254
2254
  if (i) {
2255
2255
  for (let p = 0; p < i.length; ++p)
2256
- if (!b.isValidFlow(i[p])) throw new o(l.InvalidOAuthFlow, "Invalid flow " + i[p]);
2256
+ if (!U.isValidFlow(i[p])) throw new o(l.InvalidOAuthFlow, "Invalid flow " + i[p]);
2257
2257
  }
2258
2258
  let c = [], d = [], w = [], y = this.dbPool.parameters();
2259
2259
  try {
@@ -2338,7 +2338,7 @@ class We extends me {
2338
2338
  }
2339
2339
  if (i) {
2340
2340
  for (let T = 0; T < i.length; ++T)
2341
- if (!b.isValidFlow(i[T])) throw new o(l.InvalidOAuthFlow, "Redirect Uri's may not contain page fragments");
2341
+ if (!U.isValidFlow(i[T])) throw new o(l.InvalidOAuthFlow, "Redirect Uri's may not contain page fragments");
2342
2342
  }
2343
2343
  if (!t.client_id) throw new o(l.InvalidClientId, "No client ig given");
2344
2344
  let { client_id: a, redirect_uri: n, valid_flow: c, ...d } = t;
@@ -2488,7 +2488,7 @@ class Qe extends Ge {
2488
2488
  return "$" + this.nextParam++;
2489
2489
  }
2490
2490
  }
2491
- class Kt extends Y {
2491
+ class Ot extends Y {
2492
2492
  /**
2493
2493
  * Creates a PostgresUserStorage object, optionally overriding defaults.
2494
2494
  * @param pgPool the instance of the Posrgres client.
@@ -2508,7 +2508,7 @@ class Ft extends qe {
2508
2508
  super(new de(s), e);
2509
2509
  }
2510
2510
  }
2511
- class Ot extends We {
2511
+ class Nt extends We {
2512
2512
  /**
2513
2513
  * Creates a PostgresOAuthClientStorage object, optionally overriding defaults.
2514
2514
  * @param pgPool the instance of the Posrgres client.
@@ -2518,7 +2518,7 @@ class Ot extends We {
2518
2518
  super(new de(s), e);
2519
2519
  }
2520
2520
  }
2521
- class Nt extends Je {
2521
+ class Dt extends Je {
2522
2522
  /**
2523
2523
  * Creates a PostgresOAuthClientStorage object, optionally overriding defaults.
2524
2524
  * @param pgPool the instance of the Posrgres client.
@@ -2528,7 +2528,7 @@ class Nt extends Je {
2528
2528
  super(new de(s), e);
2529
2529
  }
2530
2530
  }
2531
- class re {
2531
+ class ie {
2532
2532
  // overridden when registered to backend
2533
2533
  /**
2534
2534
  * Constructor.
@@ -2555,7 +2555,7 @@ class re {
2555
2555
  return !0;
2556
2556
  }
2557
2557
  }
2558
- class be extends re {
2558
+ class be extends ie {
2559
2559
  /** @returns `password` */
2560
2560
  secretNames() {
2561
2561
  return ["password"];
@@ -2686,7 +2686,7 @@ const Ce = process.env.PBKDF2_DIGEST || "sha256", Se = Number(process.env.PBKDF2
2686
2686
  * Creates a UUID
2687
2687
  */
2688
2688
  static uuid() {
2689
- return Fe();
2689
+ return Oe();
2690
2690
  }
2691
2691
  /**
2692
2692
  * Standard hash using SHA256 (not PBKDF2 or HMAC)
@@ -2704,7 +2704,7 @@ const Ce = process.env.PBKDF2_DIGEST || "sha256", Se = Number(process.env.PBKDF2
2704
2704
  * @returns the string containing the hash
2705
2705
  */
2706
2706
  static sha256(s) {
2707
- return Oe("sha256").update(s).digest("base64url");
2707
+ return Fe("sha256").update(s).digest("base64url");
2708
2708
  }
2709
2709
  /**
2710
2710
  * Hashes a password and returns it as a base64 or base64url encoded string
@@ -2759,7 +2759,7 @@ const Ce = process.env.PBKDF2_DIGEST || "sha256", Se = Number(process.env.PBKDF2
2759
2759
  * @returns Base64-url encoded hash
2760
2760
  */
2761
2761
  static sign(s, e, t, r) {
2762
- const i = q.signableToken(s, t, r), a = ie(ae, e);
2762
+ const i = q.signableToken(s, t, r), a = se(ae, e);
2763
2763
  return i + "." + a.update(i).digest("base64url");
2764
2764
  }
2765
2765
  /**
@@ -2772,7 +2772,7 @@ const Ce = process.env.PBKDF2_DIGEST || "sha256", Se = Number(process.env.PBKDF2
2772
2772
  * @returns Base64-url encoded hash
2773
2773
  */
2774
2774
  static signSecureToken(s, e) {
2775
- const t = ie(ae, e);
2775
+ const t = se(ae, e);
2776
2776
  return s + "." + t.update(s).digest("base64url");
2777
2777
  }
2778
2778
  /**
@@ -2791,7 +2791,7 @@ const Ce = process.env.PBKDF2_DIGEST || "sha256", Se = Number(process.env.PBKDF2
2791
2791
  const i = r[0], a = r[1], n = JSON.parse(Buffer.from(i, "base64url").toString());
2792
2792
  if (t && n.t + t * 1e3 > (/* @__PURE__ */ new Date()).getTime())
2793
2793
  throw new o(l.Expired);
2794
- const d = ie(ae, e).update(i).digest("base64url");
2794
+ const d = se(ae, e).update(i).digest("base64url");
2795
2795
  if (d.length != a.length)
2796
2796
  throw new o(l.InvalidKey, "Signature does not match payload");
2797
2797
  if (!he(Buffer.from(d), Buffer.from(a)))
@@ -2811,7 +2811,7 @@ const Ce = process.env.PBKDF2_DIGEST || "sha256", Se = Number(process.env.PBKDF2
2811
2811
  static unsignSecureToken(s, e) {
2812
2812
  const t = s.split(".");
2813
2813
  if (t.length != 2) throw new o(l.InvalidKey);
2814
- const r = t[0], i = t[1], a = r, c = ie(ae, e).update(r).digest("base64url");
2814
+ const r = t[0], i = t[1], a = r, c = se(ae, e).update(r).digest("base64url");
2815
2815
  if (c.length != i.length)
2816
2816
  throw new o(l.InvalidKey, "Signature does not match payload");
2817
2817
  if (!he(Buffer.from(c), Buffer.from(i)))
@@ -2838,7 +2838,7 @@ const Ce = process.env.PBKDF2_DIGEST || "sha256", Se = Number(process.env.PBKDF2
2838
2838
  static symmetricEncrypt(s, e, t = void 0) {
2839
2839
  t || (t = ue(16));
2840
2840
  let r = Buffer.from(e, "base64url");
2841
- var i = Re("aes-256-cbc", r, t);
2841
+ var i = De("aes-256-cbc", r, t);
2842
2842
  let a = i.update(s);
2843
2843
  return a = Buffer.concat([a, i.final()]), t.toString("base64url") + "." + a.toString("base64url");
2844
2844
  }
@@ -2854,7 +2854,7 @@ const Ce = process.env.PBKDF2_DIGEST || "sha256", Se = Number(process.env.PBKDF2
2854
2854
  const r = s.split(".");
2855
2855
  if (r.length != 2) throw new o(l.InvalidHash, "Not AES-256-CBC ciphertext");
2856
2856
  let i = Buffer.from(r[0], "base64url"), a = Buffer.from(r[1], "base64url");
2857
- var n = De("aes-256-cbc", t, i);
2857
+ var n = Re("aes-256-cbc", t, i);
2858
2858
  let c = n.update(a);
2859
2859
  return c = Buffer.concat([c, n.final()]), c.toString();
2860
2860
  }
@@ -3028,7 +3028,7 @@ const le = class le extends be {
3028
3028
  };
3029
3029
  h(le, "NoPassword", "********");
3030
3030
  let ve = le;
3031
- class Z extends re {
3031
+ class Z extends ie {
3032
3032
  /**
3033
3033
  * Constructor
3034
3034
  *
@@ -3094,7 +3094,7 @@ class Z extends re {
3094
3094
  l.Configuration,
3095
3095
  "Please set factorName on EmailAuthenticator before using"
3096
3096
  );
3097
- const t = Z.zeroPad(ee(999999), 6), r = e.email ? e.email : e.username;
3097
+ const t = Z.zeroPad(te(999999), 6), r = e.email ? e.email : e.username;
3098
3098
  Z.validateEmail(r);
3099
3099
  const i = /* @__PURE__ */ new Date(), a = new Date(i.getTime() + 1e3 * this.emailAuthenticatorTokenExpires).getTime(), n = {
3100
3100
  username: e.username,
@@ -3119,7 +3119,7 @@ class Z extends re {
3119
3119
  * @returns
3120
3120
  */
3121
3121
  async reprepareConfiguration(e, t) {
3122
- const r = x.decodeData(t.data)["2fa"], i = Z.zeroPad(ee(999999), 6), a = /* @__PURE__ */ new Date(), n = new Date(a.getTime() + 1e3 * this.emailAuthenticatorTokenExpires).getTime(), c = this.sendToken(r.email, i);
3122
+ const r = z.decodeData(t.data)["2fa"], i = Z.zeroPad(te(999999), 6), a = /* @__PURE__ */ new Date(), n = new Date(a.getTime() + 1e3 * this.emailAuthenticatorTokenExpires).getTime(), c = this.sendToken(r.email, i);
3123
3123
  return u.logger.info(f({
3124
3124
  msg: "Sent factor otp email",
3125
3125
  emailMessageId: c,
@@ -3164,7 +3164,7 @@ class Z extends re {
3164
3164
  * @returns `otp` and `expiry` as a Unix time (number).
3165
3165
  */
3166
3166
  async createOneTimeSecrets(e) {
3167
- const t = Z.zeroPad(ee(999999), 6), r = /* @__PURE__ */ new Date(), i = new Date(r.getTime() + 1e3 * this.emailAuthenticatorTokenExpires).getTime(), a = e.email || e.username, n = this.sendToken(a, t);
3167
+ const t = Z.zeroPad(te(999999), 6), r = /* @__PURE__ */ new Date(), i = new Date(r.getTime() + 1e3 * this.emailAuthenticatorTokenExpires).getTime(), a = e.email || e.username, n = this.sendToken(a, t);
3168
3168
  return u.logger.info(f({
3169
3169
  msg: "Sent factor otp email",
3170
3170
  emailMessageId: n,
@@ -3244,7 +3244,7 @@ class Z extends re {
3244
3244
  return Array(+(r > 0 && r)).join("0") + e;
3245
3245
  }
3246
3246
  }
3247
- class Q extends re {
3247
+ class Q extends ie {
3248
3248
  /**
3249
3249
  * Constructor
3250
3250
  * @param options see {@link SmsAuthenticatorOptions}
@@ -3283,7 +3283,7 @@ class Q extends re {
3283
3283
  l.Configuration,
3284
3284
  "Please set factorName on SmsAuthenticator before using"
3285
3285
  );
3286
- const t = Q.zeroPad(ee(999999), 6), r = e.phone;
3286
+ const t = Q.zeroPad(te(999999), 6), r = e.phone;
3287
3287
  Q.validatePhone(r);
3288
3288
  const i = /* @__PURE__ */ new Date(), a = new Date(i.getTime() + 1e3 * this.smsAuthenticatorTokenExpires).getTime(), n = {
3289
3289
  username: e.username,
@@ -3310,7 +3310,7 @@ class Q extends re {
3310
3310
  * @returns
3311
3311
  */
3312
3312
  async reprepareConfiguration(e, t) {
3313
- const r = x.decodeData(t.data)["2fa"], i = Q.zeroPad(ee(999999), 6), a = /* @__PURE__ */ new Date(), n = new Date(a.getTime() + 1e3 * this.smsAuthenticatorTokenExpires).getTime(), c = this.sendSms(r.phone, i);
3313
+ const r = z.decodeData(t.data)["2fa"], i = Q.zeroPad(te(999999), 6), a = /* @__PURE__ */ new Date(), n = new Date(a.getTime() + 1e3 * this.smsAuthenticatorTokenExpires).getTime(), c = this.sendSms(r.phone, i);
3314
3314
  return u.logger.info(f({
3315
3315
  msg: "Sent factor otp sms",
3316
3316
  smsMessageId: c,
@@ -3354,7 +3354,7 @@ class Q extends re {
3354
3354
  * @returns `otp` and `expiry` as a Unix time (number).
3355
3355
  */
3356
3356
  async createOneTimeSecrets(e) {
3357
- const t = Q.zeroPad(ee(999999), 6), r = /* @__PURE__ */ new Date(), i = new Date(r.getTime() + 1e3 * this.smsAuthenticatorTokenExpires).getTime(), a = e.phone, n = this.sendSms(a, t);
3357
+ const t = Q.zeroPad(te(999999), 6), r = /* @__PURE__ */ new Date(), i = new Date(r.getTime() + 1e3 * this.smsAuthenticatorTokenExpires).getTime(), a = e.phone, n = this.sendSms(a, t);
3358
3358
  return u.logger.info(f({
3359
3359
  msg: "Sent factor otp sms",
3360
3360
  smsMessageId: n,
@@ -3474,7 +3474,7 @@ class Ue extends Q {
3474
3474
  return (await Be(this.accountSid, this.authToken).messages.create(r)).sid;
3475
3475
  }
3476
3476
  }
3477
- class Rt extends re {
3477
+ class Rt extends ie {
3478
3478
  /**
3479
3479
  * Constructor
3480
3480
  *
@@ -3529,7 +3529,7 @@ class Rt extends re {
3529
3529
  * @returns
3530
3530
  */
3531
3531
  async reprepareConfiguration(e, t) {
3532
- const r = x.decodeData(t.data)["2fa"], i = this.code, a = /* @__PURE__ */ new Date(), n = new Date(a.getTime() + 1e3 * 60).getTime();
3532
+ const r = z.decodeData(t.data)["2fa"], i = this.code, a = /* @__PURE__ */ new Date(), n = new Date(a.getTime() + 1e3 * 60).getTime();
3533
3533
  return {
3534
3534
  userData: { factor2: r.factor2, otp: i },
3535
3535
  secrets: {},
@@ -3635,7 +3635,7 @@ class Rt extends re {
3635
3635
  return Array(+(r > 0 && r)).join("0") + e;
3636
3636
  }
3637
3637
  }
3638
- class Dt extends be {
3638
+ class xt extends be {
3639
3639
  /**
3640
3640
  * Create a new authenticator.
3641
3641
  *
@@ -3736,7 +3736,7 @@ class Dt extends be {
3736
3736
  async reprepareConfiguration(e, t) {
3737
3737
  }
3738
3738
  }
3739
- class xt extends re {
3739
+ class Bt extends ie {
3740
3740
  /**
3741
3741
  * Constructor
3742
3742
  * @param appName this forms part of the QR code that users scan into
@@ -3763,7 +3763,7 @@ class xt extends re {
3763
3763
  async createSecret(e, t) {
3764
3764
  t || (t = fe.generateSecret());
3765
3765
  let r = "";
3766
- return await Le.toDataURL(fe.keyuri(e, this.appName, t)).then((i) => {
3766
+ return await ze.toDataURL(fe.keyuri(e, this.appName, t)).then((i) => {
3767
3767
  r = i;
3768
3768
  }).catch((i) => {
3769
3769
  throw u.logger.debug(f({ err: i })), new o(
@@ -3773,7 +3773,7 @@ class xt extends re {
3773
3773
  }), { qrUrl: r, secret: t };
3774
3774
  }
3775
3775
  async getSecretFromSession(e, t) {
3776
- let r = x.decodeData(t.data);
3776
+ let r = z.decodeData(t.data);
3777
3777
  if (r && r["2fa"] && (r = r["2fa"]), !("totpsecret" in r))
3778
3778
  throw new o(
3779
3779
  l.Unauthorized,
@@ -3917,7 +3917,7 @@ class xt extends re {
3917
3917
  }
3918
3918
  }
3919
3919
  const ne = 16;
3920
- class R {
3920
+ class D {
3921
3921
  /**
3922
3922
  * Construct a new EmailVerifier.
3923
3923
  *
@@ -3964,24 +3964,24 @@ class R {
3964
3964
  * correct prefix for inserting into storage.
3965
3965
  */
3966
3966
  static hashEmailVerificationToken(s) {
3967
- return U.emailVerificationToken + _.hash(s);
3967
+ return b.emailVerificationToken + _.hash(s);
3968
3968
  }
3969
3969
  /**
3970
3970
  * Produces a hash of the given password reset token with the
3971
3971
  * correct prefix for inserting into storage.
3972
3972
  */
3973
3973
  static hashPasswordResetToken(s) {
3974
- return U.passwordResetToken + _.hash(s);
3974
+ return b.passwordResetToken + _.hash(s);
3975
3975
  }
3976
3976
  async createAndSaveEmailVerificationToken(s, e = "") {
3977
3977
  let r = 0;
3978
3978
  const i = /* @__PURE__ */ new Date(), a = new Date(i.getTime() + 1e3 * this.verifyEmailExpires);
3979
3979
  for (; r < 10; ) {
3980
- let n = _.randomValue(ne), c = R.hashEmailVerificationToken(n);
3980
+ let n = _.randomValue(ne), c = D.hashEmailVerificationToken(n);
3981
3981
  try {
3982
3982
  return await this.keyStorage.saveKey(s, c, i, a, e), n;
3983
3983
  } catch {
3984
- n = _.randomValue(ne), c = R.hashEmailVerificationToken(n), r++;
3984
+ n = _.randomValue(ne), c = D.hashEmailVerificationToken(n), r++;
3985
3985
  }
3986
3986
  }
3987
3987
  throw new o(l.Connection, "failed creating a unique key");
@@ -4022,7 +4022,7 @@ class R {
4022
4022
  "Either emailVerificationTextBody or emailVerificationHtmlBody must be set to send email verification emails"
4023
4023
  );
4024
4024
  let { user: r } = await this.userStorage.getUserById(s, { skipEmailVerifiedCheck: !0 }), i = e;
4025
- i != "" ? R.validateEmail(i) : (i = r.email ?? r.username, i || (i = r.username), R.validateEmail(i)), R.validateEmail(i);
4025
+ i != "" ? D.validateEmail(i) : (i = r.email ?? r.username, i || (i = r.username), D.validateEmail(i)), D.validateEmail(i);
4026
4026
  const a = await this.createAndSaveEmailVerificationToken(s, e), n = await this._sendEmailVerificationToken(a, i, t);
4027
4027
  u.logger.info(f({ msg: "Sent email verification email", emailMessageId: n, email: i }));
4028
4028
  }
@@ -4042,20 +4042,20 @@ class R {
4042
4042
  * address the user is validating
4043
4043
  */
4044
4044
  async verifyEmailVerificationToken(s) {
4045
- const e = R.hashEmailVerificationToken(s);
4045
+ const e = D.hashEmailVerificationToken(s);
4046
4046
  let t = await this.keyStorage.getKey(e);
4047
4047
  try {
4048
4048
  if (!t.userid || !t.expires) throw new o(l.InvalidKey);
4049
4049
  const { user: r } = await this.userStorage.getUserById(t.userid, { skipEmailVerifiedCheck: !0 });
4050
4050
  let i = (r.email ?? r.username).toLowerCase();
4051
- if (i || (i = r.username.toLowerCase()), R.validateEmail(i), (/* @__PURE__ */ new Date()).getTime() > t.expires.getTime()) throw new o(l.Expired);
4051
+ if (i || (i = r.username.toLowerCase()), D.validateEmail(i), (/* @__PURE__ */ new Date()).getTime() > t.expires.getTime()) throw new o(l.Expired);
4052
4052
  return { userid: t.userid, newEmail: t.data ?? "" };
4053
4053
  } finally {
4054
4054
  }
4055
4055
  }
4056
4056
  async deleteEmailVerificationToken(s) {
4057
4057
  try {
4058
- const e = R.hashEmailVerificationToken(s);
4058
+ const e = D.hashEmailVerificationToken(s);
4059
4059
  await this.keyStorage.deleteKey(e);
4060
4060
  } catch (e) {
4061
4061
  const t = o.asCrossauthError(e);
@@ -4066,11 +4066,11 @@ class R {
4066
4066
  let t = 0;
4067
4067
  const r = /* @__PURE__ */ new Date(), i = new Date(r.getTime() + 1e3 * this.passwordResetExpires);
4068
4068
  for (; t < 10; ) {
4069
- let a = _.randomValue(ne), n = R.hashPasswordResetToken(a);
4069
+ let a = _.randomValue(ne), n = D.hashPasswordResetToken(a);
4070
4070
  try {
4071
4071
  return await this.keyStorage.saveKey(s, n, r, i), a;
4072
4072
  } catch {
4073
- a = _.randomValue(ne), n = R.hashPasswordResetToken(a), t++;
4073
+ a = _.randomValue(ne), n = D.hashPasswordResetToken(a), t++;
4074
4074
  }
4075
4075
  }
4076
4076
  throw new o(l.Connection, "failed creating a unique key");
@@ -4090,7 +4090,7 @@ class R {
4090
4090
  * @returns the user that the token is for
4091
4091
  */
4092
4092
  async verifyPasswordResetToken(s) {
4093
- const e = R.hashPasswordResetToken(s);
4093
+ const e = D.hashPasswordResetToken(s);
4094
4094
  u.logger.debug("verifyPasswordResetToken " + s + " " + e);
4095
4095
  let t = await this.keyStorage.getKey(e);
4096
4096
  if (!t.userid) throw new o(l.InvalidKey);
@@ -4139,7 +4139,7 @@ class R {
4139
4139
  if (!t && r.state != E.active && r.state != E.passwordResetNeeded && r.state != E.passwordAndFactor2ResetNeeded)
4140
4140
  throw new o(l.UserNotActive);
4141
4141
  let i = (r.email ?? r.username).toLowerCase();
4142
- i || (i = r.username.toLowerCase()), R.validateEmail(i);
4142
+ i || (i = r.username.toLowerCase()), D.validateEmail(i);
4143
4143
  const a = await this.createAndSavePasswordResetToken(s), n = await this._sendPasswordResetToken(a, i, e);
4144
4144
  u.logger.info(f({ msg: "Sent password reset email", emailMessageId: n, email: i }));
4145
4145
  }
@@ -4161,11 +4161,11 @@ class R {
4161
4161
  * @param email the email to validate
4162
4162
  */
4163
4163
  static validateEmail(s) {
4164
- if (s == null || !R.isEmailValid(s)) throw new o(l.InvalidEmail);
4164
+ if (s == null || !D.isEmailValid(s)) throw new o(l.InvalidEmail);
4165
4165
  }
4166
4166
  }
4167
4167
  const _e = 16, ke = 16;
4168
- function Bt(S) {
4168
+ function zt(S) {
4169
4169
  return {
4170
4170
  ...S,
4171
4171
  path: S.path ?? "/"
@@ -4285,7 +4285,7 @@ class rt {
4285
4285
  }
4286
4286
  }
4287
4287
  }
4288
- class D {
4288
+ class R {
4289
4289
  /**
4290
4290
  * Constructor.
4291
4291
  *
@@ -4328,7 +4328,7 @@ class D {
4328
4328
  * @returns a base64-url-encoded string that can go into the storage
4329
4329
  */
4330
4330
  static hashSessionId(s) {
4331
- return U.session + _.hash(s);
4331
+ return b.session + _.hash(s);
4332
4332
  }
4333
4333
  /**
4334
4334
  * Creates a session key and saves in storage
@@ -4351,7 +4351,7 @@ class D {
4351
4351
  const a = /* @__PURE__ */ new Date();
4352
4352
  let n = this.expiry(a), c = !1;
4353
4353
  for (; r < 10 && !c; ) {
4354
- const d = D.hashSessionId(i);
4354
+ const d = R.hashSessionId(i);
4355
4355
  try {
4356
4356
  this.idleTimeout > 0 && s && (e = { ...e, lastActivity: /* @__PURE__ */ new Date() }), await this.keyStorage.saveKey(s, d, a, n, void 0, e), c = !0;
4357
4357
  } catch (w) {
@@ -4407,7 +4407,7 @@ class D {
4407
4407
  */
4408
4408
  async updateSessionKey(s) {
4409
4409
  if (!s.value) throw new o(l.InvalidKey, "No session when updating activity");
4410
- s.value = D.hashSessionId(s.value), await this.keyStorage.updateKey(s);
4410
+ s.value = R.hashSessionId(s.value), await this.keyStorage.updateKey(s);
4411
4411
  }
4412
4412
  /**
4413
4413
  * Unsigns a cookie and returns the original value.
@@ -4455,7 +4455,7 @@ class D {
4455
4455
  * `Expired` or `UserNotExist`.
4456
4456
  */
4457
4457
  async getSessionKey(s) {
4458
- const e = Date.now(), t = D.hashSessionId(s), r = await this.keyStorage.getKey(t);
4458
+ const e = Date.now(), t = R.hashSessionId(s), r = await this.keyStorage.getKey(t);
4459
4459
  if (r.value = s, r.expires && e > r.expires.getTime())
4460
4460
  throw u.logger.warn(f({ msg: "Session id in cookie expired in key storage", hashedSessionCookie: _.hash(s) })), new o(l.Expired);
4461
4461
  if (r.userid && this.idleTimeout > 0 && r.lastactive && e > r.lastactive.getTime() + this.idleTimeout * 1e3)
@@ -4470,7 +4470,7 @@ class D {
4470
4470
  * @param except if defined, don't delete this key
4471
4471
  */
4472
4472
  async deleteAllForUser(s, e) {
4473
- e && (e = D.hashSessionId(e)), await this.keyStorage.deleteAllForUser(s, U.session, e);
4473
+ e && (e = R.hashSessionId(e)), await this.keyStorage.deleteAllForUser(s, b.session, e);
4474
4474
  }
4475
4475
  }
4476
4476
  class Lt {
@@ -4495,9 +4495,9 @@ class Lt {
4495
4495
  t.userStorage && (this.userStorage = t.userStorage), this.keyStorage = s, this.authenticators = e;
4496
4496
  for (let r in this.authenticators)
4497
4497
  this.authenticators[r].factorName = r;
4498
- if (this.session = new D(this.keyStorage, { ...t == null ? void 0 : t.sessionCookieOptions, ...t ?? {} }), this.csrfTokens = new rt({ ...t == null ? void 0 : t.doubleSubmitCookieOptions, ...t ?? {} }), m("allowedFactor2", g.JsonArray, this, t, "ALLOWED_FACTOR2"), m("enableEmailVerification", g.Boolean, this, t, "ENABLE_EMAIL_VERIFICATION"), m("enablePasswordReset", g.Boolean, this, t, "ENABLE_PASSWORD_RESET"), this.emailTokenStorage = this.keyStorage, this.userStorage && (this.enableEmailVerification || this.enablePasswordReset)) {
4498
+ if (this.session = new R(this.keyStorage, { ...t == null ? void 0 : t.sessionCookieOptions, ...t ?? {} }), this.csrfTokens = new rt({ ...t == null ? void 0 : t.doubleSubmitCookieOptions, ...t ?? {} }), m("allowedFactor2", g.JsonArray, this, t, "ALLOWED_FACTOR2"), m("enableEmailVerification", g.Boolean, this, t, "ENABLE_EMAIL_VERIFICATION"), m("enablePasswordReset", g.Boolean, this, t, "ENABLE_PASSWORD_RESET"), this.emailTokenStorage = this.keyStorage, this.userStorage && (this.enableEmailVerification || this.enablePasswordReset)) {
4499
4499
  let r = this.keyStorage;
4500
- t.emailTokenStorage && (this.emailTokenStorage = t.emailTokenStorage), this.tokenEmailer = new R(this.userStorage, r, t);
4500
+ t.emailTokenStorage && (this.emailTokenStorage = t.emailTokenStorage), this.tokenEmailer = new D(this.userStorage, r, t);
4501
4501
  }
4502
4502
  }
4503
4503
  /**
@@ -4586,7 +4586,7 @@ class Lt {
4586
4586
  try {
4587
4587
  this.emailTokenStorage.deleteAllForUser(
4588
4588
  i.id,
4589
- U.passwordResetToken
4589
+ b.passwordResetToken
4590
4590
  );
4591
4591
  } catch (v) {
4592
4592
  u.logger.warn(f({ msg: "Couldn't delete password reset tokens while logging in", user: s })), u.logger.debug(f({ err: v }));
@@ -4626,7 +4626,7 @@ class Lt {
4626
4626
  */
4627
4627
  async logout(s) {
4628
4628
  const e = await this.session.getSessionKey(s);
4629
- return await this.keyStorage.deleteKey(D.hashSessionId(e.value));
4629
+ return await this.keyStorage.deleteKey(R.hashSessionId(e.value));
4630
4630
  }
4631
4631
  /**
4632
4632
  * Logs a user out from all sessions.
@@ -4774,8 +4774,8 @@ class Lt {
4774
4774
  * @param value new value to store
4775
4775
  */
4776
4776
  async updateSessionData(s, e, t) {
4777
- const r = D.hashSessionId(s);
4778
- u.logger.debug(f({ msg: `Updating session data value${e}`, hashedSessionCookie: _.hash(s) })), await this.keyStorage.updateData(r, e, t);
4777
+ const r = R.hashSessionId(s);
4778
+ u.logger.debug(f({ msg: `Updating session data value ${e}`, hashedSessionCookie: _.hash(s) })), await this.keyStorage.updateData(r, e, t);
4779
4779
  }
4780
4780
  /**
4781
4781
  * Update field sin the session data.
@@ -4786,7 +4786,7 @@ class Lt {
4786
4786
  * @param dataArray names and values.
4787
4787
  */
4788
4788
  async updateManySessionData(s, e) {
4789
- const t = D.hashSessionId(s);
4789
+ const t = R.hashSessionId(s);
4790
4790
  u.logger.debug(f({ msg: "Updating session data", hashedSessionCookie: _.hash(s) })), await this.keyStorage.updateManyData(t, e);
4791
4791
  }
4792
4792
  /**
@@ -4798,8 +4798,8 @@ class Lt {
4798
4798
  * @param name of the field.
4799
4799
  */
4800
4800
  async deleteSessionData(s, e) {
4801
- const t = D.hashSessionId(s);
4802
- u.logger.debug(f({ msg: `Updating session data value${e}`, hashedSessionCookie: _.hash(s) })), await this.keyStorage.deleteData(t, e);
4801
+ const t = R.hashSessionId(s);
4802
+ u.logger.debug(f({ msg: `Updating session data value ${e}`, hashedSessionCookie: _.hash(s) })), await this.keyStorage.deleteData(t, e);
4803
4803
  }
4804
4804
  /**
4805
4805
  * Deletes the given session ID from the key storage (not the cookie)
@@ -4807,7 +4807,7 @@ class Lt {
4807
4807
  * @param sessionId the session Id to delete
4808
4808
  */
4809
4809
  async deleteSession(s) {
4810
- return await this.keyStorage.deleteKey(D.hashSessionId(s));
4810
+ return await this.keyStorage.deleteKey(R.hashSessionId(s));
4811
4811
  }
4812
4812
  /**
4813
4813
  * Creates a new user, sending an email verification message if necessary.
@@ -4862,7 +4862,7 @@ class Lt {
4862
4862
  if (!this.authenticators[s.factor2]) throw new o(l.Configuration, "Two factor authentication not enabled for user");
4863
4863
  const a = await this.authenticators[s.factor2].prepareConfiguration(s), n = a == null ? {} : a.userData, c = a == null ? {} : a.sessionData, d = await this.authenticators[s.factor1].createPersistentSecrets(s.username, e, r);
4864
4864
  return s.state = "awaitingtwofactorsetup", await this.keyStorage.updateData(
4865
- D.hashSessionId(t),
4865
+ R.hashSessionId(t),
4866
4866
  "2fa",
4867
4867
  c
4868
4868
  ), { userid: (await this.userStorage.createUser(s, d)).id, userData: n };
@@ -4882,13 +4882,13 @@ class Lt {
4882
4882
  if (!this.authenticators[e]) throw new o(l.Configuration, "Two factor authentication not enabled for user");
4883
4883
  const i = await this.authenticators[e].prepareConfiguration(s), a = i == null ? {} : i.userData, n = i == null ? {} : i.sessionData;
4884
4884
  return n && (n.userData = a), await this.keyStorage.updateData(
4885
- D.hashSessionId(t),
4885
+ R.hashSessionId(t),
4886
4886
  "2fa",
4887
4887
  n
4888
4888
  ), a;
4889
4889
  }
4890
4890
  return await this.userStorage.updateUser({ id: s.id, factor2: e ?? "" }), await this.keyStorage.updateData(
4891
- D.hashSessionId(t),
4891
+ R.hashSessionId(t),
4892
4892
  "2fa",
4893
4893
  void 0
4894
4894
  ), {};
@@ -4908,7 +4908,7 @@ class Lt {
4908
4908
  */
4909
4909
  async repeatTwoFactorSignup(s) {
4910
4910
  if (!this.userStorage) throw new o(l.Configuration, "Cannot call repeatTwoFactorSignup if no user storage provided");
4911
- const e = (await this.dataForSessionId(s))["2fa"], t = e.username, r = e.factor2, i = D.hashSessionId(s), a = await this.keyStorage.getKey(i), c = await this.authenticators[r].reprepareConfiguration(t, a), d = c == null ? {} : c.userData, w = c == null ? {} : c.secrets, y = c == null ? {} : c.newSessionData;
4911
+ const e = (await this.dataForSessionId(s))["2fa"], t = e.username, r = e.factor2, i = R.hashSessionId(s), a = await this.keyStorage.getKey(i), c = await this.authenticators[r].reprepareConfiguration(t, a), d = c == null ? {} : c.userData, w = c == null ? {} : c.secrets, y = c == null ? {} : c.newSessionData;
4912
4912
  y && await this.keyStorage.updateData(i, "2fa", y);
4913
4913
  const { user: C } = await this.userStorage.getUserByUsername(t, { skipActiveCheck: !0, skipEmailVerifiedCheck: !0 });
4914
4914
  return { userid: C.id, userData: d, secrets: w };
@@ -4932,7 +4932,7 @@ class Lt {
4932
4932
  if (r && r.state != E.active && r.state != E.factor2ResetNeeded)
4933
4933
  throw new o(l.UserNotActive);
4934
4934
  if (!i) throw new o(l.InvalidKey, "Session key not found");
4935
- let a = x.decodeData(i.data)["2fa"];
4935
+ let a = z.decodeData(i.data)["2fa"];
4936
4936
  if (!(a != null && a.factor2) || !(a != null && a.username)) throw new o(l.Unauthorized, "Two factor authentication not initiated");
4937
4937
  let n = a.username;
4938
4938
  const c = this.authenticators[a.factor2];
@@ -4948,7 +4948,7 @@ class Lt {
4948
4948
  state: !y && this.enableEmailVerification ? "awaitingemailverification" : "active",
4949
4949
  factor2: a.factor2
4950
4950
  };
4951
- return c.secretNames().length > 0 ? await this.userStorage.updateUser(C, d) : await this.userStorage.updateUser(C), !y && t && this.enableEmailVerification && this.tokenEmailer && await ((v = this.tokenEmailer) == null ? void 0 : v.sendEmailVerificationToken(r.id, void 0)), await this.keyStorage.updateData(D.hashSessionId(i.value), "2fa", void 0), { ...r, ...C };
4951
+ return c.secretNames().length > 0 ? await this.userStorage.updateUser(C, d) : await this.userStorage.updateUser(C), !y && t && this.enableEmailVerification && this.tokenEmailer && await ((v = this.tokenEmailer) == null ? void 0 : v.sendEmailVerificationToken(r.id, void 0)), await this.keyStorage.updateData(R.hashSessionId(i.value), "2fa", void 0), { ...r, ...C };
4952
4952
  }
4953
4953
  /**
4954
4954
  * Initiates the two factor login process.
@@ -4979,7 +4979,7 @@ class Lt {
4979
4979
  async initiateTwoFactorPageVisit(s, e, t, r, i) {
4980
4980
  const n = await this.authenticators[s.factor2].createOneTimeSecrets(s);
4981
4981
  let c, d, w;
4982
- const y = D.hashSessionId(e);
4982
+ const y = R.hashSessionId(e);
4983
4983
  u.logger.debug("initiateTwoFactorPageVisit " + s.username + " " + e + " " + y);
4984
4984
  let C = { username: s.username, factor2: s.factor2, secrets: n, body: t, url: r };
4985
4985
  return i && (C["content-type"] = i), await this.keyStorage.updateData(y, "pre2fa", C), {
@@ -5001,14 +5001,14 @@ class Lt {
5001
5001
  if (!this.userStorage) throw new o(l.Configuration, "Cannot call completeTwoFactorPageVisit if no user storage provided");
5002
5002
  let { key: t } = await this.session.getUserForSessionId(e);
5003
5003
  if (!t) throw new o(l.InvalidKey, "Session key not found");
5004
- let r = x.decodeData(t.data);
5004
+ let r = z.decodeData(t.data);
5005
5005
  if (!("pre2fa" in r)) throw new o(l.Unauthorized, "Two factor authentication not initiated");
5006
5006
  const { secrets: i } = await this.userStorage.getUserByUsername(r.pre2fa.username), a = this.authenticators[r.pre2fa.factor2];
5007
5007
  if (!a) throw new o(l.Configuration, "Unrecognised second factor authentication");
5008
5008
  const n = {}, c = a.secretNames();
5009
5009
  for (let d in i)
5010
5010
  c.includes(d) && d in i && (n[d] = i[d]);
5011
- await a.authenticateUser(void 0, { ...n, ...r.pre2fa.secrets }, s), await this.keyStorage.updateData(D.hashSessionId(t.value), "pre2fa", void 0);
5011
+ await a.authenticateUser(void 0, { ...n, ...r.pre2fa.secrets }, s), await this.keyStorage.updateData(R.hashSessionId(t.value), "pre2fa", void 0);
5012
5012
  }
5013
5013
  /**
5014
5014
  * Cancels the 2FA that was previously initiated but not completed..
@@ -5022,9 +5022,9 @@ class Lt {
5022
5022
  async cancelTwoFactorPageVisit(s) {
5023
5023
  let { key: e } = await this.session.getUserForSessionId(s);
5024
5024
  if (!e) throw new o(l.InvalidKey, "Session key not found");
5025
- let t = x.decodeData(e.data);
5025
+ let t = z.decodeData(e.data);
5026
5026
  if (!("pre2fa" in t)) throw new o(l.Unauthorized, "Two factor authentication not initiated");
5027
- return await this.keyStorage.updateData(D.hashSessionId(e.value), "pre2fa", void 0), t.pre2fa;
5027
+ return await this.keyStorage.updateData(R.hashSessionId(e.value), "pre2fa", void 0), t.pre2fa;
5028
5028
  }
5029
5029
  /**
5030
5030
  * Performs the second factor authentication as the second step of the login
@@ -5047,20 +5047,20 @@ class Lt {
5047
5047
  if (!this.userStorage) throw new o(l.Configuration, "Cannot call completeTwoFactorLogin if no user storage provided");
5048
5048
  let { key: i } = await this.session.getUserForSessionId(e);
5049
5049
  if (!i || !i.data || i.data == "") throw new o(l.Unauthorized);
5050
- let a = x.decodeData(i.data)["2fa"], n = a.username, c = a.factor2;
5050
+ let a = z.decodeData(i.data)["2fa"], n = a.username, c = a.factor2;
5051
5051
  const { user: d, secrets: w } = await this.userStorage.getUserByUsername(n), y = this.authenticators[c];
5052
5052
  if (!y) throw new o(l.Configuration, "Second factor " + c + " not enabled");
5053
5053
  await y.authenticateUser(d, { ...w, ...a }, s);
5054
5054
  const C = await this.session.createSessionKey(d.id, t);
5055
- await this.keyStorage.deleteKey(D.hashSessionId(i.value));
5055
+ await this.keyStorage.deleteKey(R.hashSessionId(i.value));
5056
5056
  const v = this.session.makeCookie(C, r), p = this.csrfTokens.createCsrfToken(), T = this.csrfTokens.makeCsrfCookie(p), k = this.csrfTokens.makeCsrfFormOrHeaderToken(p);
5057
5057
  try {
5058
5058
  this.emailTokenStorage.deleteAllForUser(
5059
5059
  d.id,
5060
- U.passwordResetToken
5060
+ b.passwordResetToken
5061
5061
  );
5062
- } catch (A) {
5063
- u.logger.warn(f({ msg: "Couldn't delete password reset tokens while logging in", user: n })), u.logger.debug(f({ err: A }));
5062
+ } catch (P) {
5063
+ u.logger.warn(f({ msg: "Couldn't delete password reset tokens while logging in", user: n })), u.logger.debug(f({ err: P }));
5064
5064
  }
5065
5065
  return {
5066
5066
  sessionCookie: v,
@@ -5128,7 +5128,7 @@ class Lt {
5128
5128
  try {
5129
5129
  this.emailTokenStorage.deleteAllForUser(
5130
5130
  a.id,
5131
- U.passwordResetToken
5131
+ b.passwordResetToken
5132
5132
  );
5133
5133
  } catch (w) {
5134
5134
  u.logger.warn(f({ msg: "Couldn't delete password reset tokens while logging in", user: s })), u.logger.debug(f({ err: w }));
@@ -5153,14 +5153,14 @@ class Lt {
5153
5153
  d.userid = s.userid;
5154
5154
  let w = !1;
5155
5155
  if (a)
5156
- i = a, R.validateEmail(i), w = !0;
5156
+ i = a, D.validateEmail(i), w = !0;
5157
5157
  else if (n) {
5158
5158
  i = n;
5159
5159
  try {
5160
- R.validateEmail(s.username), w = !0;
5160
+ D.validateEmail(s.username), w = !0;
5161
5161
  } catch {
5162
5162
  }
5163
- w && R.validateEmail(i);
5163
+ w && D.validateEmail(i);
5164
5164
  }
5165
5165
  return !t && this.enableEmailVerification && w ? await ((y = this.tokenEmailer) == null ? void 0 : y.sendEmailVerificationToken(s.id, i)) : (a && (d.email = a), n && (d.username = n)), (e.state == E.passwordResetNeeded || e.state == E.passwordAndFactor2ResetNeeded) && await ((C = this.tokenEmailer) == null ? void 0 : C.sendPasswordResetToken(s.id, {}, r)), await this.userStorage.updateUser(d), {
5166
5166
  emailVerificationTokenSent: !t && this.enableEmailVerification && w,
@@ -5191,7 +5191,7 @@ class Lt {
5191
5191
  try {
5192
5192
  await this.emailTokenStorage.deleteAllForUser(
5193
5193
  i.id,
5194
- U.passwordResetToken
5194
+ b.passwordResetToken
5195
5195
  );
5196
5196
  } catch (c) {
5197
5197
  u.logger.warn(f({ msg: "Couldn't delete password reset tokens while logging in", user: i.username })), u.logger.debug(f({ err: c }));
@@ -5213,7 +5213,7 @@ class ge {
5213
5213
  /** The prefix to add to the hashed key in storage. Defaults to
5214
5214
  * {@link @crossauth/common!KeyPrefix}.apiKey
5215
5215
  */
5216
- h(this, "prefix", U.apiKey);
5216
+ h(this, "prefix", b.apiKey);
5217
5217
  /** The name of the speak in the Authorization header. Defaults to "ApiKey" */
5218
5218
  h(this, "authScheme", "ApiKey");
5219
5219
  this.apiKeyStorage = s, m("secret", g.String, this, e, "SECRET", !0), m("keyLength", g.String, this, e, "APIKEY_LENGTH"), m("prefix", g.String, this, e, "APIKEY_PREFIX"), m("authScheme", g.String, this, e, "APIKEY_AUTHSCHEME");
@@ -5241,7 +5241,7 @@ class ge {
5241
5241
  name: s,
5242
5242
  value: a,
5243
5243
  userid: e,
5244
- data: x.encodeData(t),
5244
+ data: z.encodeData(t),
5245
5245
  expires: c,
5246
5246
  created: n,
5247
5247
  ...i
@@ -5338,7 +5338,7 @@ class J {
5338
5338
  digest: this.oauthPbkdf2Digest
5339
5339
  })), e.forEach((y) => {
5340
5340
  J.validateUri(y);
5341
- }), t || (t = b.allFlows());
5341
+ }), t || (t = U.allFlows());
5342
5342
  const d = {
5343
5343
  client_id: a,
5344
5344
  client_secret: n,
@@ -5422,7 +5422,178 @@ class J {
5422
5422
  );
5423
5423
  }
5424
5424
  }
5425
- function at(S) {
5425
+ class at extends Pe {
5426
+ /**
5427
+ * Constructor
5428
+ *
5429
+ * @param options see {@link OAuthTokenConsumerOptions}
5430
+ */
5431
+ constructor(e, t = {}) {
5432
+ const r = {};
5433
+ m("jwtKeyType", g.String, r, t, "JWT_KEY_TYPE");
5434
+ super(e, { ...t, ...r });
5435
+ /**
5436
+ * Value passed to the constructor. The `aud` claim must match it
5437
+ */
5438
+ h(this, "audience");
5439
+ /**
5440
+ * Value passed to the constructor. If true, access tokens are saved
5441
+ * in storage,
5442
+ */
5443
+ h(this, "persistAccessToken", !1);
5444
+ h(this, "keyStorage");
5445
+ h(this, "jwtSecretKeyFile", "");
5446
+ h(this, "jwtPublicKeyFile", "");
5447
+ if (this.audience = e, m("authServerBaseUrl", g.String, this, t, "AUTH_SERVER_BASE_URL", !0), m("jwtSecretKeyFile", g.String, this, t, "JWT_SECRET_KEY_FILE"), m("jwtPublicKeyFile", g.String, this, t, "JWT_PUBLIC_KEY_FILE"), m("jwtSecretKey", g.String, this, t, "JWT_SECRET_KEY"), m("jwtPublicKey", g.String, this, t, "JWT_PUBLIC_KEY"), m("clockTolerance", g.Number, this, t, "OAUTH_CLOCK_TOLERANCE"), m("persistAccessToken", g.Boolean, this, t, "OAUTH_PERSIST_ACCESS_TOKEN"), this.keyStorage = t.keyStorage, this.jwtSecretKey || this.jwtSecretKeyFile) {
5448
+ if (this.jwtPublicKey || this.jwtPublicKeyFile)
5449
+ throw new o(
5450
+ l.Configuration,
5451
+ "Cannot specify symmetric and public/private JWT keys"
5452
+ );
5453
+ if (this.jwtSecretKey && this.jwtSecretKeyFile)
5454
+ throw new o(
5455
+ l.Configuration,
5456
+ "Cannot specify symmetric key and file"
5457
+ );
5458
+ this.jwtSecretKeyFile && (this.jwtSecretKey = re.readFileSync(this.jwtSecretKeyFile, "utf8"));
5459
+ } else if (this.jwtPublicKey || this.jwtPublicKeyFile) {
5460
+ if (this.jwtPublicKeyFile && this.jwtPublicKey)
5461
+ throw new o(
5462
+ l.Configuration,
5463
+ "Cannot specify both public key and public key file"
5464
+ );
5465
+ this.jwtPublicKeyFile && (this.jwtPublicKey = re.readFileSync(this.jwtPublicKeyFile, "utf8"));
5466
+ }
5467
+ }
5468
+ /**
5469
+ * Uses {@link Crypto.hash} to hash the given string.
5470
+ *
5471
+ * @param plaintext the string to hash
5472
+ * @returns Base64-url-encoded hash
5473
+ */
5474
+ async hash(e) {
5475
+ return _.hash(e);
5476
+ }
5477
+ /**
5478
+ * If the given token is valid, the paylaod is returned. Otherwise
5479
+ * undefined is returned.
5480
+ *
5481
+ * The signature must be valid, the expiry must not have passed and,
5482
+ * if `tokenType` is defined,. the `type` claim in the payload must
5483
+ * match it.
5484
+ *
5485
+ * Doesn't throw exceptions.
5486
+ *
5487
+ * @param token The token to validate
5488
+ * @param tokenType If defined, the `type` claim in the payload must
5489
+ * match this value
5490
+ */
5491
+ async tokenAuthorized(e, t, r) {
5492
+ var a;
5493
+ const i = await super.tokenAuthorized(e, t, r);
5494
+ if (i && t == "access" && this.persistAccessToken && this.keyStorage)
5495
+ try {
5496
+ const n = b.accessToken + _.hash(i.jti ? i.jti : i.sid ? i.sid : ""), c = await this.keyStorage.getKey(n), d = /* @__PURE__ */ new Date();
5497
+ if (c.expires && ((a = c.expires) == null ? void 0 : a.getTime()) < d.getTime()) {
5498
+ u.logger.error(f({ msg: "Access token expired in storage but not in JWT" }));
5499
+ return;
5500
+ }
5501
+ } catch (n) {
5502
+ u.logger.warn(f({
5503
+ msg: "Couldn't get token from database - is it valid?",
5504
+ hashedAccessToken: _.hash(i.jti ? i.jti : i.sid ? i.sid : "")
5505
+ })), u.logger.debug(f({ err: n }));
5506
+ return;
5507
+ }
5508
+ return i;
5509
+ }
5510
+ }
5511
+ class nt extends Ke {
5512
+ /**
5513
+ * Constructor
5514
+ * @param authServerBaseUrl bsae URI for the authorization server
5515
+ * expected to issue access tokens. If the `iss` field in a JWT
5516
+ * does not match this, it is rejected.
5517
+ * @param options See {@link OAuthClientOptions}
5518
+ */
5519
+ constructor(e, t) {
5520
+ const r = {
5521
+ client_id: ""
5522
+ };
5523
+ m("client_id", g.String, r, t, "OAUTH_CLIENT_ID", !0);
5524
+ super({
5525
+ authServerBaseUrl: e,
5526
+ tokenConsumer: new at(
5527
+ r.client_id,
5528
+ {
5529
+ audience: r.client_id,
5530
+ authServerBaseUrl: e,
5531
+ ...t
5532
+ }
5533
+ ),
5534
+ ...t
5535
+ });
5536
+ h(this, "deviceAuthorizationUrl", "device_authorization");
5537
+ h(this, "userCreationType", "idToken");
5538
+ h(this, "userMatchField", "username");
5539
+ h(this, "idTokenMatchField", "sub");
5540
+ h(this, "userCreationFn");
5541
+ h(this, "userStorage");
5542
+ this.client_id = r.client_id;
5543
+ let i = {};
5544
+ if (m("stateLength", g.String, this, t, "OAUTH_STATE_LENGTH"), m("verifierLength", g.String, this, t, "OAUTH_VERIFIER_LENGTH"), m("client_secret", g.String, i, t, "OAUTH_CLIENT_SECRET"), m("codeChallengeMethod", g.String, this, t, "OAUTH_CODE_CHALLENGE_METHOD"), m("deviceAuthorizationUrl", g.String, this, t, "OAUTH_DEVICE_AUTHORIZATION_URL"), m("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), m("userCreationType", g.String, this, t, "OAUTH_USER_CREATION_TYPE"), m("userMatchField", g.String, this, t, "OAUTH_USER_MATCH_FIELD"), m("idTokenMatchField", g.String, this, t, "OAUTH_IDTOKEN_MaTCH_FIELD"), this.userCreationType == "merge" ? this.userCreationFn = ot : this.userCreationType == "embed" ? this.userCreationFn = lt : t.userCreationFn && this.userCreationType == "custom" ? this.userCreationFn = t.userCreationFn : this.userCreationFn = ct, t.userStorage && (this.userStorage = t.userStorage), m("oauthPostType", g.String, this, t, "OAUTH_POST_TYPE"), m("oauthUseUserInfoEndpoint", g.Boolean, this, t, "OAUTH_USE_USER_INFO_ENDPOINT"), m("oauthAuthorizeRedirect", g.String, this, t, "OAUTH_AUTHORIZE_REDIRECT"), this.oauthPostType != "json" && this.oauthPostType != "form")
5545
+ throw new o(l.Configuration, "oauthPostType must be json or form");
5546
+ }
5547
+ /**
5548
+ * Uses {@link @crossauth/backend!Crypto.randomValue} to create a random string
5549
+ * @param length the length of the random array of bytes before
5550
+ * base64-url-encoding
5551
+ * @returns the Base64-URL-encoded random string
5552
+ */
5553
+ randomValue(e) {
5554
+ return _.randomValue(e);
5555
+ }
5556
+ /**
5557
+ * Uses {@link @crossauth/backend!Crypto.sha256} to create hash a string using SHA256
5558
+ * @param plaintext the text to hash
5559
+ * @returns the Base64-URL-encoded hash
5560
+ */
5561
+ async sha256(e) {
5562
+ return _.sha256(e);
5563
+ }
5564
+ }
5565
+ async function ot(S, s, e, t) {
5566
+ if (!s) throw new o(l.Configuration, "userCreationType set to merge but no user storage set");
5567
+ try {
5568
+ let r;
5569
+ return e == "username" ? r = await s.getUserByUsername(S[t]) : e == "username" ? r = await s.getUserByEmail(S[t]) : r = await s.getUserBy(e, S[t]), { ...S, ...r.user };
5570
+ } catch (r) {
5571
+ const i = o.asCrossauthError(r);
5572
+ if (i.code == l.UserNotExist || i.code == l.UserNotActive)
5573
+ return;
5574
+ throw u.logger.error(f({ err: r })), r;
5575
+ }
5576
+ }
5577
+ async function lt(S, s, e, t) {
5578
+ if (!s) throw new o(l.Configuration, "userCreationType set to embed but no user storage set");
5579
+ try {
5580
+ let r;
5581
+ return e == "username" ? r = await s.getUserByUsername(S[t]) : e == "username" ? r = await s.getUserByEmail(S[t]) : r = await s.getUserBy(e, S[t]), { ...r.user, idToken: S };
5582
+ } catch (r) {
5583
+ const i = o.asCrossauthError(r);
5584
+ if (i.code == l.UserNotExist || i.code == l.UserNotActive)
5585
+ return;
5586
+ throw u.logger.error({ err: r }), r;
5587
+ }
5588
+ }
5589
+ async function ct(S, s, e, t) {
5590
+ return {
5591
+ id: S.userid ?? S.sub,
5592
+ username: S.sub,
5593
+ state: S.state ?? "active"
5594
+ };
5595
+ }
5596
+ function dt(S) {
5426
5597
  switch (S) {
5427
5598
  case "HS256":
5428
5599
  case "HS384":
@@ -5444,7 +5615,7 @@ function at(S) {
5444
5615
  "Invalid JWT signing algorithm " + S
5445
5616
  );
5446
5617
  }
5447
- class zt {
5618
+ class Ht {
5448
5619
  /**
5449
5620
  * Constructor
5450
5621
  *
@@ -5495,6 +5666,15 @@ class zt {
5495
5666
  h(this, "validScopes", []);
5496
5667
  h(this, "idTokenClaims", {});
5497
5668
  h(this, "accessTokenClaims", {});
5669
+ ///// Upstream AUth server config
5670
+ /**
5671
+ * The OAuth client to the upstream authz server if configured
5672
+ */
5673
+ h(this, "upstreamClient");
5674
+ /**
5675
+ * The OAuth client to the upstream authz server if configured
5676
+ */
5677
+ h(this, "upstreamClientOptions");
5498
5678
  // device code
5499
5679
  h(this, "userCodeExpiry", 60 * 5);
5500
5680
  h(this, "userCodeThrottle", 1500);
@@ -5521,7 +5701,9 @@ class zt {
5521
5701
  "userCodeDashEvery must be a number or null"
5522
5702
  );
5523
5703
  }
5524
- if (m("deviceCodeVerificationUri", g.String, this, r, "DEVICECODE_VERIFICATION_URI"), this.validFlows.length == 1 && this.validFlows[0] == b.All && (this.validFlows = b.allFlows()), this.jwtAlgorithmChecked = at(this.jwtAlgorithm), this.jwtSecretKey || this.jwtSecretKeyFile) {
5704
+ if (m("deviceCodeVerificationUri", g.String, this, r, "DEVICECODE_VERIFICATION_URI"), r.upstreamClient && (this.upstreamClientOptions = r.upstreamClient, this.upstreamClient = new nt(r.upstreamClient.authServerBaseUrl, r.upstreamClient.options), !r.upstreamClient.options.redirect_uri))
5705
+ throw new o(l.Configuration, "Must define redirect_uri in upstreamClient options");
5706
+ if (this.validFlows.length == 1 && this.validFlows[0] == U.All && (this.validFlows = U.allFlows()), this.jwtAlgorithmChecked = dt(this.jwtAlgorithm), this.jwtSecretKey || this.jwtSecretKeyFile) {
5525
5707
  if (this.jwtPublicKey || this.jwtPublicKeyFile || this.jwtPrivateKey || this.jwtPrivateKeyFile)
5526
5708
  throw new o(
5527
5709
  l.Configuration,
@@ -5532,14 +5714,14 @@ class zt {
5532
5714
  l.Configuration,
5533
5715
  "Cannot specify symmetric key and file"
5534
5716
  );
5535
- this.jwtSecretKeyFile && (this.jwtSecretKey = te.readFileSync(this.jwtSecretKeyFile, "utf8"));
5717
+ this.jwtSecretKeyFile && (this.jwtSecretKey = re.readFileSync(this.jwtSecretKeyFile, "utf8"));
5536
5718
  } else if ((this.jwtPrivateKey || this.jwtPrivateKeyFile) && (this.jwtPublicKey || this.jwtPublicKeyFile)) {
5537
5719
  if (this.jwtPrivateKeyFile && this.jwtPrivateKey)
5538
5720
  throw new o(
5539
5721
  l.Configuration,
5540
5722
  "Cannot specify both private key and private key file"
5541
5723
  );
5542
- if (this.jwtPrivateKeyFile && (this.jwtPrivateKey = te.readFileSync(
5724
+ if (this.jwtPrivateKeyFile && (this.jwtPrivateKey = re.readFileSync(
5543
5725
  this.jwtPrivateKeyFile,
5544
5726
  "utf8"
5545
5727
  )), this.jwtPublicKeyFile && this.jwtPublicKey)
@@ -5547,7 +5729,7 @@ class zt {
5547
5729
  l.Configuration,
5548
5730
  "Cannot specify both public key and public key file"
5549
5731
  );
5550
- this.jwtPublicKeyFile && (this.jwtPublicKey = te.readFileSync(
5732
+ this.jwtPublicKeyFile && (this.jwtPublicKey = re.readFileSync(
5551
5733
  this.jwtPublicKeyFile,
5552
5734
  "utf8"
5553
5735
  ));
@@ -5561,7 +5743,7 @@ class zt {
5561
5743
  l.Configuration,
5562
5744
  "If setting jwtPublicKey or jwtPrivate key, must also set jwtKeyType"
5563
5745
  );
5564
- if (this.opaqueAccessToken && (this.persistAccessToken = !0), (this.validFlows.includes(b.Password) || this.validFlows.includes(b.PasswordMfa)) && (!this.userStorage || Object.keys(this.authenticators).length == 0))
5746
+ if (this.opaqueAccessToken && (this.persistAccessToken = !0), (this.validFlows.includes(U.Password) || this.validFlows.includes(U.PasswordMfa)) && (!this.userStorage || Object.keys(this.authenticators).length == 0))
5565
5747
  throw new o(
5566
5748
  l.Configuration,
5567
5749
  "If password flow or password MFA flow is enabled, userStorage and authenticators must be provided"
@@ -5711,21 +5893,21 @@ class zt {
5711
5893
  async authenticateClient(s, e, t) {
5712
5894
  let r = !1;
5713
5895
  switch (s) {
5714
- case b.AuthorizationCode:
5715
- case b.AuthorizationCodeWithPKCE:
5896
+ case U.AuthorizationCode:
5897
+ case U.AuthorizationCodeWithPKCE:
5716
5898
  r = e.confidential == !0 || e.client_secret != null || t != null;
5717
5899
  break;
5718
- case b.ClientCredentials:
5900
+ case U.ClientCredentials:
5719
5901
  r = !0;
5720
5902
  break;
5721
- case b.Password:
5722
- case b.PasswordMfa:
5903
+ case U.Password:
5904
+ case U.PasswordMfa:
5723
5905
  r = e.confidential == !0 || e.client_secret != null || t != null;
5724
5906
  break;
5725
- case b.RefreshToken:
5907
+ case U.RefreshToken:
5726
5908
  r = e.confidential == !0 || e.client_secret != null || t != null;
5727
5909
  break;
5728
- case b.DeviceCode:
5910
+ case U.DeviceCode:
5729
5911
  r = e.confidential == !0 || e.client_secret != null || t != null;
5730
5912
  break;
5731
5913
  }
@@ -5785,7 +5967,7 @@ class zt {
5785
5967
  otp: v,
5786
5968
  deviceCode: p
5787
5969
  }) {
5788
- var O, V, j;
5970
+ var F, $, M;
5789
5971
  const T = this.inferFlowFromPost(s, a);
5790
5972
  if (!T) return {
5791
5973
  error: "server_error",
@@ -5793,9 +5975,9 @@ class zt {
5793
5975
  };
5794
5976
  const k = await this.getClientById(e);
5795
5977
  if (!k.client) return k;
5796
- const A = k.client, z = await this.authenticateClient(T, A, i);
5797
- if (z.error) return z;
5798
- if (T == b.Password && !this.validFlows.includes(T) && !this.validFlows.includes(b.PasswordMfa))
5978
+ const P = k.client, H = await this.authenticateClient(T, P, i);
5979
+ if (H.error) return H;
5980
+ if (T == U.Password && !this.validFlows.includes(T) && !this.validFlows.includes(U.PasswordMfa))
5799
5981
  return {
5800
5982
  error: "access_denied",
5801
5983
  error_description: "Unsupported flow type " + T
@@ -5805,46 +5987,78 @@ class zt {
5805
5987
  error: "access_denied",
5806
5988
  error_description: "Unsupported flow type " + T
5807
5989
  };
5808
- if (A && !A.valid_flow.includes(T))
5990
+ if (P && !P.valid_flow.includes(T))
5809
5991
  return {
5810
5992
  error: "unauthorized_client",
5811
5993
  error_description: "Client does not support " + T
5812
5994
  };
5813
- let H = !1;
5814
- this.issueRefreshToken && T != b.RefreshToken && (H = !0), this.issueRefreshToken && T == b.RefreshToken && this.rollingRefreshToken && (H = !0);
5815
- let K;
5995
+ let j = !1;
5996
+ this.issueRefreshToken && T != U.RefreshToken && (j = !0), this.issueRefreshToken && T == U.RefreshToken && this.rollingRefreshToken && (j = !0);
5997
+ let O;
5816
5998
  if (s == "authorization_code")
5817
- return this.requireClientSecretOrChallenge && A && A.client_secret && !i && !a ? {
5999
+ return this.requireClientSecretOrChallenge && P && P.client_secret && !i && !a ? {
5818
6000
  error: "access_denied",
5819
6001
  error_description: "Must provide either a client secret or use PKCE"
5820
- } : A && A.client_secret && !i ? {
6002
+ } : P && P.client_secret && !i ? {
5821
6003
  error: "access_denied",
5822
6004
  error_description: "No client secret or code verifier provided for authorization coode flow"
5823
6005
  } : r ? await this.makeAccessToken({
5824
- client: A,
6006
+ client: P,
5825
6007
  code: r,
5826
6008
  client_secret: i,
5827
6009
  codeVerifier: a,
5828
- issueRefreshToken: H
6010
+ issueRefreshToken: j
5829
6011
  }) : {
5830
6012
  error: "access_denied",
5831
6013
  error_description: "No authorization code provided for authorization code flow"
5832
6014
  };
5833
6015
  if (s == "refresh_token") {
6016
+ if (this.upstreamClient && this.upstreamClientOptions) {
6017
+ if (!n)
6018
+ return {
6019
+ error: "invalid_request",
6020
+ error_description: "If executing the refresh token flow, must provide a refresh token"
6021
+ };
6022
+ let A = await this.upstreamClient.refreshTokenFlow(n);
6023
+ if (!A.access_token)
6024
+ return {
6025
+ error: "access_denied",
6026
+ error_description: "Didn't receive an access token"
6027
+ };
6028
+ let I = A.access_token;
6029
+ if (this.upstreamClientOptions.accessTokenIsJwt && (I = await this.upstreamClient.validateAccessToken(A.access_token, !1), !I))
6030
+ return {
6031
+ error: "access_denied",
6032
+ error_description: "Couldn't decode access token"
6033
+ };
6034
+ const x = await this.upstreamClientOptions.tokenMergeFn(I, A.id_payload, this.userStorage);
6035
+ if (x.authorized) {
6036
+ const B = await this.createTokensFromPayload(
6037
+ e,
6038
+ x.access_payload,
6039
+ x.id_payload
6040
+ );
6041
+ return A.access_token = B.access_token, A.id_token = B.id_token, A.id_payload = B.id_payload, A;
6042
+ } else
6043
+ return u.logger.warn(f({ msg: x.error_description })), {
6044
+ error: x.error,
6045
+ error_description: x.error_description
6046
+ };
6047
+ }
5834
6048
  const N = await this.getRefreshTokenData(n);
5835
6049
  if (!n || !N || !this.userStorage)
5836
6050
  return {
5837
6051
  error: "access_denied",
5838
6052
  error_description: "Refresh token is invalid"
5839
6053
  };
5840
- let P;
6054
+ let K;
5841
6055
  if (N.username)
5842
6056
  try {
5843
- const { user: F } = await ((O = this.userStorage) == null ? void 0 : O.getUserByUsername(N.username));
5844
- P = F;
5845
- } catch (F) {
6057
+ const { user: A } = await ((F = this.userStorage) == null ? void 0 : F.getUserByUsername(N.username));
6058
+ K = A;
6059
+ } catch (A) {
5846
6060
  return u.logger.error(f({
5847
- err: F,
6061
+ err: A,
5848
6062
  msg: "Couldn't get user for refresh token. Doesn't exist?",
5849
6063
  username: N.username
5850
6064
  })), {
@@ -5853,35 +6067,35 @@ class zt {
5853
6067
  };
5854
6068
  }
5855
6069
  try {
5856
- const F = U.refreshToken + _.hash(n);
5857
- await this.keyStorage.deleteKey(F);
5858
- } catch (F) {
5859
- const I = o.asCrossauthError(F);
5860
- u.logger.debug(f({ err: F })), u.logger.warn(f({ msg: "Cannot delete refresh token", cerr: I }));
6070
+ const A = b.refreshToken + _.hash(n);
6071
+ await this.keyStorage.deleteKey(A);
6072
+ } catch (A) {
6073
+ const I = o.asCrossauthError(A);
6074
+ u.logger.debug(f({ err: A })), u.logger.warn(f({ msg: "Cannot delete refresh token", cerr: I }));
5861
6075
  }
5862
6076
  return await this.makeAccessToken({
5863
- client: A,
6077
+ client: P,
5864
6078
  client_secret: i,
5865
6079
  codeVerifier: a,
5866
- issueRefreshToken: H,
6080
+ issueRefreshToken: j,
5867
6081
  scopes: N.scope,
5868
- user: P
6082
+ user: K
5869
6083
  });
5870
6084
  } else if (s == "client_credentials") {
5871
6085
  const {
5872
6086
  scopes: N,
5873
- error: P,
5874
- error_description: F
6087
+ error: K,
6088
+ error_description: A
5875
6089
  } = await this.validateAndPersistScope(e, t, void 0);
5876
- return P ? {
5877
- error: P,
5878
- error_description: F
6090
+ return K ? {
6091
+ error: K,
6092
+ error_description: A
5879
6093
  } : await this.makeAccessToken({
5880
- client: A,
6094
+ client: P,
5881
6095
  client_secret: i,
5882
6096
  codeVerifier: a,
5883
6097
  scopes: N,
5884
- issueRefreshToken: H
6098
+ issueRefreshToken: j
5885
6099
  });
5886
6100
  } else if (s == "password") {
5887
6101
  if (!c || !d)
@@ -5895,7 +6109,7 @@ class zt {
5895
6109
  error: "server_error",
5896
6110
  error_description: "Password authentication not configured"
5897
6111
  };
5898
- const { user: I, secrets: $ } = await this.userStorage.getUserByUsername(c), B = this.authenticators[I.factor1];
6112
+ const { user: I, secrets: x } = await this.userStorage.getUserByUsername(c), B = this.authenticators[I.factor1];
5899
6113
  if (!B || !B.secretNames().includes("password"))
5900
6114
  return {
5901
6115
  error: "access_denied",
@@ -5903,9 +6117,9 @@ class zt {
5903
6117
  };
5904
6118
  await B.authenticateUser(
5905
6119
  I,
5906
- $,
6120
+ x,
5907
6121
  { password: d }
5908
- ), K = I;
6122
+ ), O = I;
5909
6123
  } catch (I) {
5910
6124
  return u.logger.debug(f({ err: I })), {
5911
6125
  error: "access_denied",
@@ -5914,33 +6128,33 @@ class zt {
5914
6128
  }
5915
6129
  const {
5916
6130
  scopes: N,
5917
- error: P,
5918
- error_description: F
5919
- } = await this.validateAndPersistScope(e, t, K);
5920
- return P ? {
5921
- error: P,
5922
- error_description: F
5923
- } : K.factor2 ? this.allowedFactor2.length > 0 && (K.state == E.factor2ResetNeeded || !this.allowedFactor2.includes(K.factor2 ? K.factor2 : "none")) ? {
6131
+ error: K,
6132
+ error_description: A
6133
+ } = await this.validateAndPersistScope(e, t, O);
6134
+ return K ? {
6135
+ error: K,
6136
+ error_description: A
6137
+ } : O.factor2 ? this.allowedFactor2.length > 0 && (O.state == E.factor2ResetNeeded || !this.allowedFactor2.includes(O.factor2 ? O.factor2 : "none")) ? {
5924
6138
  error: "access_denied",
5925
6139
  error_description: "2FA method not allowed or needs to be reconfigured"
5926
- } : await this.createMfaRequest(K) : await this.makeAccessToken({
5927
- client: A,
6140
+ } : await this.createMfaRequest(O) : await this.makeAccessToken({
6141
+ client: P,
5928
6142
  client_secret: i,
5929
6143
  codeVerifier: a,
5930
6144
  scopes: N,
5931
- issueRefreshToken: H,
5932
- user: K
6145
+ issueRefreshToken: j,
6146
+ user: O
5933
6147
  });
5934
6148
  } else if (s == "http://auth0.com/oauth/grant-type/mfa-otp") {
5935
6149
  const {
5936
6150
  scopes: N,
5937
- error: P,
5938
- error_description: F
6151
+ error: K,
6152
+ error_description: A
5939
6153
  } = await this.validateAndPersistScope(e, t, void 0);
5940
- if (P)
6154
+ if (K)
5941
6155
  return {
5942
- error: P,
5943
- error_description: F
6156
+ error: K,
6157
+ error_description: A
5944
6158
  };
5945
6159
  if (!v)
5946
6160
  return {
@@ -5952,7 +6166,7 @@ class zt {
5952
6166
  error: "access_denied",
5953
6167
  error_description: "MFA token not provided"
5954
6168
  };
5955
- const I = await this.validateMfaToken(w), $ = U.mfaToken + _.hash(w);
6169
+ const I = await this.validateMfaToken(w), x = b.mfaToken + _.hash(w);
5956
6170
  if (!I.user || !I.key)
5957
6171
  return {
5958
6172
  error: "access_denied",
@@ -5965,45 +6179,45 @@ class zt {
5965
6179
  error_description: "MFA type is not supported for OAuth"
5966
6180
  };
5967
6181
  try {
5968
- const { secrets: M } = await this.userStorage.getUserById(I.user.id);
6182
+ const { secrets: V } = await this.userStorage.getUserById(I.user.id);
5969
6183
  await B.authenticateUser(
5970
6184
  I.user,
5971
- M,
6185
+ V,
5972
6186
  { otp: v }
5973
6187
  );
5974
- } catch (M) {
5975
- return u.logger.debug(f({ err: M })), {
6188
+ } catch (V) {
6189
+ return u.logger.debug(f({ err: V })), {
5976
6190
  error: "access_denied",
5977
6191
  error_description: "Invalid OTP"
5978
6192
  };
5979
6193
  }
5980
6194
  try {
5981
- await this.keyStorage.deleteKey($);
5982
- } catch (M) {
5983
- u.logger.debug(f({ err: M })), u.logger.warn(f({
5984
- cerr: M,
6195
+ await this.keyStorage.deleteKey(x);
6196
+ } catch (V) {
6197
+ u.logger.debug(f({ err: V })), u.logger.warn(f({
6198
+ cerr: V,
5985
6199
  msg: "Couldn't delete mfa token",
5986
6200
  hashedMfaToken: I.key.value
5987
6201
  }));
5988
6202
  }
5989
6203
  return await this.makeAccessToken({
5990
- client: A,
6204
+ client: P,
5991
6205
  client_secret: i,
5992
6206
  codeVerifier: a,
5993
6207
  scopes: N,
5994
- issueRefreshToken: H,
6208
+ issueRefreshToken: j,
5995
6209
  user: I.user
5996
6210
  });
5997
6211
  } else if (s == "http://auth0.com/oauth/grant-type/mfa-oob") {
5998
6212
  const {
5999
6213
  scopes: N,
6000
- error: P,
6001
- error_description: F
6214
+ error: K,
6215
+ error_description: A
6002
6216
  } = await this.validateAndPersistScope(e, t, void 0);
6003
- if (P)
6217
+ if (K)
6004
6218
  return {
6005
- error: P,
6006
- error_description: F
6219
+ error: K,
6220
+ error_description: A
6007
6221
  };
6008
6222
  if (!y || !C)
6009
6223
  return {
@@ -6021,27 +6235,27 @@ class zt {
6021
6235
  error: "access_denied",
6022
6236
  error_description: "Invalid MFA token"
6023
6237
  };
6024
- const $ = this.authenticators[I.user.factor2];
6025
- if (!$ || !this.userStorage)
6238
+ const x = this.authenticators[I.user.factor2];
6239
+ if (!x || !this.userStorage)
6026
6240
  return {
6027
6241
  error: "access_denied",
6028
6242
  error_description: "MFA type is not supported for OAuth"
6029
6243
  };
6030
6244
  try {
6031
- const { secrets: B } = await this.userStorage.getUserById(I.user.id), M = x.decodeData(I.key.data).omfa;
6032
- if (!M || !M.otp || !M.oobCode)
6245
+ const { secrets: B } = await this.userStorage.getUserById(I.user.id), V = z.decodeData(I.key.data).omfa;
6246
+ if (!V || !V.otp || !V.oobCode)
6033
6247
  return {
6034
6248
  error: "server_error",
6035
6249
  error_description: "Cannot retrieve email OTP"
6036
6250
  };
6037
- if (M.oobCode != y)
6251
+ if (V.oobCode != y)
6038
6252
  return {
6039
6253
  error: "access_denied",
6040
6254
  error_description: "Invalid OOB code"
6041
6255
  };
6042
- await $.authenticateUser(
6256
+ await x.authenticateUser(
6043
6257
  I.user,
6044
- { ...B, otp: M.otp, expiry: (V = I.key.expires) == null ? void 0 : V.getTime() },
6258
+ { ...B, otp: V.otp, expiry: ($ = I.key.expires) == null ? void 0 : $.getTime() },
6045
6259
  { otp: C }
6046
6260
  );
6047
6261
  } catch (B) {
@@ -6060,11 +6274,11 @@ class zt {
6060
6274
  }));
6061
6275
  }
6062
6276
  return await this.makeAccessToken({
6063
- client: A,
6277
+ client: P,
6064
6278
  client_secret: i,
6065
6279
  codeVerifier: a,
6066
6280
  scopes: N,
6067
- issueRefreshToken: H,
6281
+ issueRefreshToken: j,
6068
6282
  user: I.user
6069
6283
  });
6070
6284
  } else if (s == "urn:ietf:params:oauth:grant-type:device_code") {
@@ -6075,40 +6289,40 @@ class zt {
6075
6289
  };
6076
6290
  let N;
6077
6291
  try {
6078
- N = await this.keyStorage.getKey(U.deviceCode + p);
6079
- } catch (P) {
6080
- const F = o.asCrossauthError(P);
6081
- return u.logger.debug(f({ err: F })), u.logger.error(f({ msg: "Couldn't get device code", cerr: F })), {
6292
+ N = await this.keyStorage.getKey(b.deviceCode + p);
6293
+ } catch (K) {
6294
+ const A = o.asCrossauthError(K);
6295
+ return u.logger.debug(f({ err: A })), u.logger.error(f({ msg: "Couldn't get device code", cerr: A })), {
6082
6296
  error: "accerss_denied",
6083
6297
  error_description: "Invalid device code"
6084
6298
  };
6085
6299
  }
6086
6300
  try {
6087
- const P = JSON.parse(N.data ?? "{}"), F = (/* @__PURE__ */ new Date()).getTime();
6088
- if (N.expires && F > N.expires.getTime())
6301
+ const K = JSON.parse(N.data ?? "{}"), A = (/* @__PURE__ */ new Date()).getTime();
6302
+ if (N.expires && A > N.expires.getTime())
6089
6303
  return await this.deleteDeviceCode(p), {
6090
6304
  error: "expired_token",
6091
6305
  error_description: "Code has expired"
6092
6306
  };
6093
- if (P.ok != !0)
6307
+ if (K.ok != !0)
6094
6308
  return {
6095
6309
  error: "authorization_pending",
6096
6310
  error_description: "Waiting for user code to be entered"
6097
6311
  };
6098
6312
  {
6099
- let I = P.scope ? P.scope.split(" ") : void 0, $ = P.userid ? await ((j = this.userStorage) == null ? void 0 : j.getUserById(P.userid)) : void 0;
6313
+ let I = K.scope ? K.scope.split(" ") : void 0, x = K.userid ? await ((M = this.userStorage) == null ? void 0 : M.getUserById(K.userid)) : void 0;
6100
6314
  return await this.deleteDeviceCode(p), await this.makeAccessToken({
6101
- client: A,
6315
+ client: P,
6102
6316
  client_secret: i,
6103
6317
  codeVerifier: a,
6104
6318
  scopes: I,
6105
- issueRefreshToken: H,
6106
- user: $ == null ? void 0 : $.user
6319
+ issueRefreshToken: j,
6320
+ user: x == null ? void 0 : x.user
6107
6321
  });
6108
6322
  }
6109
- } catch (P) {
6110
- const F = o.asCrossauthError(P);
6111
- return u.logger.debug(f({ err: F })), u.logger.error(f({ msg: "Couldn't get device code", cerr: F })), await this.deleteDeviceCode(p), {
6323
+ } catch (K) {
6324
+ const A = o.asCrossauthError(K);
6325
+ return u.logger.debug(f({ err: A })), u.logger.error(f({ msg: "Couldn't get device code", cerr: A })), await this.deleteDeviceCode(p), {
6112
6326
  error: "accerss_denied",
6113
6327
  error_description: "Invalid device code"
6114
6328
  };
@@ -6121,7 +6335,7 @@ class zt {
6121
6335
  }
6122
6336
  async deleteDeviceCode(s) {
6123
6337
  try {
6124
- await this.keyStorage.deleteKey(U.deviceCode + s);
6338
+ await this.keyStorage.deleteKey(b.deviceCode + s);
6125
6339
  } catch (e) {
6126
6340
  const t = o.asCrossauthError(e);
6127
6341
  u.logger.debug(f({ err: t })), u.logger.error(f({ msg: "Couldn't delete device code", cerr: t }));
@@ -6129,7 +6343,7 @@ class zt {
6129
6343
  }
6130
6344
  async deleteUserCode(s) {
6131
6345
  try {
6132
- await this.keyStorage.deleteKey(U.userCode + s);
6346
+ await this.keyStorage.deleteKey(b.userCode + s);
6133
6347
  } catch (e) {
6134
6348
  const t = o.asCrossauthError(e);
6135
6349
  u.logger.debug(f({ err: t })), u.logger.error(f({ msg: "Couldn't delete user code", cerr: t }));
@@ -6165,7 +6379,7 @@ class zt {
6165
6379
  error_description: "Invalid deviceCodeVerificationUri"
6166
6380
  };
6167
6381
  }
6168
- const r = b.DeviceCode, i = await this.getClientById(s);
6382
+ const r = U.DeviceCode, i = await this.getClientById(s);
6169
6383
  if (!i.client) return i;
6170
6384
  const a = i.client, n = await this.authenticateClient(r, a, t);
6171
6385
  if (n.error) return n;
@@ -6187,7 +6401,7 @@ class zt {
6187
6401
  try {
6188
6402
  c = _.randomValue(this.deviceCodeLength), await this.keyStorage.saveKey(
6189
6403
  void 0,
6190
- U.deviceCode + c,
6404
+ b.deviceCode + c,
6191
6405
  w,
6192
6406
  C,
6193
6407
  JSON.stringify({ scope: e, client_id: s })
@@ -6206,7 +6420,7 @@ class zt {
6206
6420
  try {
6207
6421
  v = _.randomBase32(this.userCodeLength), await this.keyStorage.saveKey(
6208
6422
  void 0,
6209
- U.userCode + v,
6423
+ b.userCode + v,
6210
6424
  w,
6211
6425
  C,
6212
6426
  JSON.stringify({ deviceCode: c })
@@ -6251,7 +6465,7 @@ class zt {
6251
6465
  s = s.replace(/[ -]*/g, "");
6252
6466
  let t, r = {};
6253
6467
  try {
6254
- t = await this.keyStorage.getKey(U.userCode + s), r = JSON.parse((t == null ? void 0 : t.data) ?? "{}");
6468
+ t = await this.keyStorage.getKey(b.userCode + s), r = JSON.parse((t == null ? void 0 : t.data) ?? "{}");
6255
6469
  } catch {
6256
6470
  return {
6257
6471
  ok: !1,
@@ -6267,7 +6481,7 @@ class zt {
6267
6481
  };
6268
6482
  let i;
6269
6483
  try {
6270
- i = await this.keyStorage.getKey(U.deviceCode + r.deviceCode);
6484
+ i = await this.keyStorage.getKey(b.deviceCode + r.deviceCode);
6271
6485
  } catch (y) {
6272
6486
  const C = o.asCrossauthError(y);
6273
6487
  return u.logger.debug(f({ err: C })), u.logger.error(f({
@@ -6321,7 +6535,7 @@ class zt {
6321
6535
  [null]
6322
6536
  ), !d) {
6323
6537
  try {
6324
- e != null && e.id && await this.keyStorage.updateData(U.deviceCode + r.deviceCode, "userid", e.id);
6538
+ e != null && e.id && await this.keyStorage.updateData(b.deviceCode + r.deviceCode, "userid", e.id);
6325
6539
  } catch (y) {
6326
6540
  const C = o.asCrossauthError(y);
6327
6541
  return u.logger.debug(f({ err: C })), u.logger.warn(f({ msg: "Couldn't update user id on user code entry - deleting", cerr: C })), await this.deleteUserCode(s), await this.deleteDeviceCode(r.deviceCode), {
@@ -6339,7 +6553,7 @@ class zt {
6339
6553
  };
6340
6554
  }
6341
6555
  try {
6342
- 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);
6556
+ 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);
6343
6557
  } catch (y) {
6344
6558
  const C = o.asCrossauthError(y);
6345
6559
  return u.logger.debug(f({ err: C })), u.logger.warn(f({ msg: "Couldn't update status on user code entry - deleting", cerr: C })), await this.deleteUserCode(s), await this.deleteDeviceCode(r.deviceCode), {
@@ -6359,7 +6573,7 @@ class zt {
6359
6573
  s = s.replace(/[ -]*/g, "");
6360
6574
  let e, t = {};
6361
6575
  try {
6362
- e = await this.keyStorage.getKey(U.userCode + s), t = JSON.parse((e == null ? void 0 : e.data) ?? "{}");
6576
+ e = await this.keyStorage.getKey(b.userCode + s), t = JSON.parse((e == null ? void 0 : e.data) ?? "{}");
6363
6577
  } catch {
6364
6578
  return {
6365
6579
  ok: !1,
@@ -6375,7 +6589,7 @@ class zt {
6375
6589
  };
6376
6590
  let r;
6377
6591
  try {
6378
- r = await this.keyStorage.getKey(U.deviceCode + t.deviceCode);
6592
+ r = await this.keyStorage.getKey(b.deviceCode + t.deviceCode);
6379
6593
  } catch (n) {
6380
6594
  const c = o.asCrossauthError(n);
6381
6595
  return u.logger.debug(f({ err: c })), u.logger.error(f({
@@ -6402,7 +6616,7 @@ class zt {
6402
6616
  };
6403
6617
  }
6404
6618
  try {
6405
- await this.keyStorage.updateData(U.deviceCode + t.deviceCode, "ok", !0);
6619
+ await this.keyStorage.updateData(b.deviceCode + t.deviceCode, "ok", !0);
6406
6620
  } catch (n) {
6407
6621
  const c = o.asCrossauthError(n);
6408
6622
  return u.logger.debug(f({ err: c })), u.logger.warn(f({ msg: "Couldn't update status on user code entry - deleting", cerr: c })), await this.deleteUserCode(s), await this.deleteDeviceCode(t.deviceCode), {
@@ -6419,7 +6633,7 @@ class zt {
6419
6633
  };
6420
6634
  }
6421
6635
  async createMfaRequest(s) {
6422
- const e = _.randomValue(this.codeLength), t = U.mfaToken + _.hash(e), r = /* @__PURE__ */ new Date();
6636
+ const e = _.randomValue(this.codeLength), t = b.mfaToken + _.hash(e), r = /* @__PURE__ */ new Date();
6423
6637
  try {
6424
6638
  await this.keyStorage.saveKey(
6425
6639
  s.id,
@@ -6445,7 +6659,7 @@ class zt {
6445
6659
  var r;
6446
6660
  let e, t;
6447
6661
  try {
6448
- const i = U.mfaToken + _.hash(s);
6662
+ const i = b.mfaToken + _.hash(s);
6449
6663
  if (t = await this.keyStorage.getKey(i), !t.userid)
6450
6664
  return {
6451
6665
  error: "access_denied",
@@ -6473,7 +6687,7 @@ class zt {
6473
6687
  error_description: "Invalid MFA token"
6474
6688
  };
6475
6689
  try {
6476
- if (x.decodeData(t.data).omfaaid != e.factor2)
6690
+ if (z.decodeData(t.data).omfaaid != e.factor2)
6477
6691
  return {
6478
6692
  error: "access_denied",
6479
6693
  error_description: "authenticatorId not valid for user"
@@ -6530,7 +6744,7 @@ class zt {
6530
6744
  * @returns respond as defined by the Password MFA spec
6531
6745
  */
6532
6746
  async mfaChallengeEndpoint(s, e, t, r, i) {
6533
- const a = b.PasswordMfa, n = await this.getClientById(e);
6747
+ const a = U.PasswordMfa, n = await this.getClientById(e);
6534
6748
  if (!n.client) return n;
6535
6749
  const c = n.client, d = await this.authenticateClient(a, c, t);
6536
6750
  if (d.error) return d;
@@ -6587,9 +6801,9 @@ class zt {
6587
6801
  */
6588
6802
  inferFlowFromGet(s, e, t) {
6589
6803
  if (s == "code" && !e.includes("openid"))
6590
- return t ? b.AuthorizationCodeWithPKCE : b.AuthorizationCode;
6804
+ return t ? U.AuthorizationCodeWithPKCE : U.AuthorizationCode;
6591
6805
  if (e.includes("openid") && s == "code")
6592
- return t ? b.AuthorizationCodeWithPKCE : b.AuthorizationCode;
6806
+ return t ? U.AuthorizationCodeWithPKCE : U.AuthorizationCode;
6593
6807
  }
6594
6808
  /**
6595
6809
  * Returns the OAuth flow type that corresonds to the given
@@ -6600,19 +6814,19 @@ class zt {
6600
6814
  */
6601
6815
  inferFlowFromPost(s, e) {
6602
6816
  if (s == "authorization_code")
6603
- return e ? b.AuthorizationCodeWithPKCE : b.AuthorizationCode;
6817
+ return e ? U.AuthorizationCodeWithPKCE : U.AuthorizationCode;
6604
6818
  if (s == "client_credentials")
6605
- return b.ClientCredentials;
6819
+ return U.ClientCredentials;
6606
6820
  if (s == "refresh_token")
6607
- return b.RefreshToken;
6821
+ return U.RefreshToken;
6608
6822
  if (s == "urn:ietf:params:oauth:grant-type:device_code")
6609
- return b.DeviceCode;
6823
+ return U.DeviceCode;
6610
6824
  if (s == "password")
6611
- return b.Password;
6825
+ return U.Password;
6612
6826
  if (s == "http://auth0.com/oauth/grant-type/mfa-otp")
6613
- return b.PasswordMfa;
6827
+ return U.PasswordMfa;
6614
6828
  if (s == "http://auth0.com/oauth/grant-type/mfa-oob")
6615
- return b.PasswordMfa;
6829
+ return U.PasswordMfa;
6616
6830
  }
6617
6831
  async getAuthorizationCode(s, e, t, r, i, a, n) {
6618
6832
  if (i && (a || (a = "S256"), a != "S256" && a != "plain"))
@@ -6626,7 +6840,10 @@ class zt {
6626
6840
  error: "invalid_request",
6627
6841
  error_description: `The redirect uri ${e} is invalid`
6628
6842
  };
6629
- const d = /* @__PURE__ */ new Date(), w = this.authorizationCodeExpiry ? new Date(d.getTime() + this.authorizationCodeExpiry * 1e3 + this.clockTolerance * 1e3) : void 0, y = {};
6843
+ const d = /* @__PURE__ */ new Date(), w = this.authorizationCodeExpiry ? new Date(d.getTime() + this.authorizationCodeExpiry * 1e3 + this.clockTolerance * 1e3) : void 0, y = {
6844
+ client_id: s.client_id,
6845
+ redirect_uri: e
6846
+ };
6630
6847
  t && (y.scope = t), i && (y.challengeMethod = a, y.challenge = _.hash(i)), n && (y.username = n.username, y.id = n.id);
6631
6848
  const C = JSON.stringify(y);
6632
6849
  let v = !1, p = "";
@@ -6634,7 +6851,7 @@ class zt {
6634
6851
  try {
6635
6852
  p = _.randomValue(this.codeLength), await this.keyStorage.saveKey(
6636
6853
  void 0,
6637
- U.authorizationCode + _.hash(p),
6854
+ b.authorizationCode + _.hash(p),
6638
6855
  d,
6639
6856
  w,
6640
6857
  C
@@ -6649,6 +6866,30 @@ class zt {
6649
6866
  );
6650
6867
  return { code: p, state: r };
6651
6868
  }
6869
+ async getAuthorizationCodeData(s) {
6870
+ let e, t = {};
6871
+ try {
6872
+ e = await this.keyStorage.getKey(b.authorizationCode + _.hash(s)), t = z.decodeData(e.data);
6873
+ } catch (r) {
6874
+ u.logger.debug(f({ err: r }));
6875
+ return;
6876
+ }
6877
+ return t;
6878
+ }
6879
+ async deleteAuthorizationCodeData(s) {
6880
+ try {
6881
+ await this.keyStorage.deleteKey(b.authorizationCode + _.hash(s));
6882
+ } catch (e) {
6883
+ u.logger.warn(f({
6884
+ err: e,
6885
+ msg: "Couldn't delete authorization code from storage"
6886
+ }));
6887
+ }
6888
+ }
6889
+ async setAuthorizationCodeData(s, e) {
6890
+ const t = await this.keyStorage.getKey(b.authorizationCode + _.hash(s));
6891
+ t.data = JSON.stringify(e), this.keyStorage.updateKey(t);
6892
+ }
6652
6893
  /**
6653
6894
  * Create an access token
6654
6895
  */
@@ -6661,15 +6902,15 @@ class zt {
6661
6902
  issueRefreshToken: a = !1,
6662
6903
  user: n
6663
6904
  }) {
6664
- var z, H;
6905
+ var H, j;
6665
6906
  let c = !0;
6666
6907
  try {
6667
6908
  s.client_secret != null && (c = await _.passwordsEqual(
6668
6909
  t ?? "",
6669
6910
  s.client_secret ?? ""
6670
6911
  ));
6671
- } catch (K) {
6672
- return u.logger.error(f({ err: K })), { error: "server_error", error_description: "Couldn't validate client" };
6912
+ } catch (O) {
6913
+ return u.logger.error(f({ err: O })), { error: "server_error", error_description: "Couldn't validate client" };
6673
6914
  }
6674
6915
  if (!c) return {
6675
6916
  error: "access_denied",
@@ -6677,20 +6918,20 @@ class zt {
6677
6918
  };
6678
6919
  let d = {};
6679
6920
  if (e) {
6680
- let K;
6921
+ let O;
6681
6922
  try {
6682
- K = await this.keyStorage.getKey(U.authorizationCode + _.hash(e)), d = x.decodeData(K.data);
6683
- } catch (O) {
6684
- return u.logger.debug(f({ err: O })), {
6923
+ O = await this.keyStorage.getKey(b.authorizationCode + _.hash(e)), d = z.decodeData(O.data);
6924
+ } catch (F) {
6925
+ return u.logger.debug(f({ err: F })), {
6685
6926
  error: "access_denied",
6686
6927
  error_description: "Invalid or expired authorization code"
6687
6928
  };
6688
6929
  }
6689
6930
  try {
6690
- await this.keyStorage.deleteKey(K.value);
6691
- } catch (O) {
6931
+ await this.keyStorage.deleteKey(O.value);
6932
+ } catch (F) {
6692
6933
  u.logger.warn(f({
6693
- err: O,
6934
+ err: F,
6694
6935
  msg: "Couldn't delete authorization code from storatge",
6695
6936
  client_id: s == null ? void 0 : s.client_id
6696
6937
  }));
@@ -6703,8 +6944,8 @@ class zt {
6703
6944
  error_description: "Invalid code challenge/code challenge method method for authorization code"
6704
6945
  };
6705
6946
  if (d.challenge) {
6706
- const K = d.challengeMethod == "plain" ? r ?? "" : _.sha256(r ?? "");
6707
- if (_.hash(K) != d.challenge)
6947
+ const O = d.challengeMethod == "plain" ? r ?? "" : _.sha256(r ?? "");
6948
+ if (_.hash(O) != d.challenge)
6708
6949
  return {
6709
6950
  error: "access_denied",
6710
6951
  error_description: "Code verifier is incorrect"
@@ -6714,10 +6955,10 @@ class zt {
6714
6955
  let C;
6715
6956
  if ((i && i.includes("openid") || Object.keys(this.accessTokenClaims).length > 0) && this.userStorage && d.username)
6716
6957
  try {
6717
- const { user: K } = await this.userStorage.getUserByUsername(d.username);
6718
- n = K;
6719
- } catch (K) {
6720
- return u.logger.error(f({ err: K })), {
6958
+ const { user: O } = await this.userStorage.getUserByUsername(d.username);
6959
+ n = O;
6960
+ } catch (O) {
6961
+ return u.logger.error(f({ err: O })), {
6721
6962
  error: "server_error",
6722
6963
  error_description: "Couldn't load user data"
6723
6964
  };
@@ -6731,39 +6972,39 @@ class zt {
6731
6972
  type: "access"
6732
6973
  };
6733
6974
  p = this.addClaims(p, this.accessTokenClaims, i, n), i && (p.scope = i), this.accessTokenExpiry != null && (p.exp = y + this.accessTokenExpiry, C = new Date(w.getTime() + this.accessTokenExpiry * 1e3 + this.clockTolerance * 1e3)), this.audience && (p.aud = this.audience);
6734
- const T = await new Promise((K, O) => {
6735
- se.sign(
6975
+ const T = await new Promise((O, F) => {
6976
+ ee.sign(
6736
6977
  p,
6737
6978
  this.secretOrPrivateKey,
6738
6979
  { algorithm: this.jwtAlgorithmChecked, keyid: "1" },
6739
- (V, j) => {
6740
- j ? K(j) : O(V || new o(
6980
+ ($, M) => {
6981
+ M ? O(M) : F($ || new o(
6741
6982
  l.Unauthorized,
6742
6983
  "Couldn't create jwt"
6743
6984
  ));
6744
6985
  }
6745
6986
  );
6746
6987
  });
6747
- this.persistAccessToken && this.keyStorage && await ((z = this.keyStorage) == null ? void 0 : z.saveKey(
6988
+ this.persistAccessToken && this.keyStorage && await ((H = this.keyStorage) == null ? void 0 : H.saveKey(
6748
6989
  void 0,
6749
6990
  // to avoid user storage dependency, we don't set this
6750
- U.accessToken + _.hash(v),
6991
+ b.accessToken + _.hash(v),
6751
6992
  w,
6752
6993
  C
6753
6994
  ));
6754
6995
  let k;
6755
6996
  if (i && i.includes("openid")) {
6756
- const K = _.uuid();
6757
- let O = {
6997
+ const O = _.uuid();
6998
+ let F = {
6758
6999
  aud: s.client_id,
6759
- jti: K,
7000
+ jti: O,
6760
7001
  iat: y,
6761
7002
  iss: this.oauthIssuer,
6762
7003
  sub: d.username,
6763
7004
  type: "id"
6764
7005
  };
6765
- if (i.includes("email") && (n != null && n.email) && (O.email = n.email), i.includes("address") && n && "address" in n && (O.address = n.address), i.includes("phone") && n && "phone" in n && (O.phone = n.phone), i.includes("profile") && n)
6766
- for (let V of [
7006
+ 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)
7007
+ for (let $ of [
6767
7008
  "name",
6768
7009
  "family_name",
6769
7010
  "given_name",
@@ -6779,17 +7020,17 @@ class zt {
6779
7020
  "locale",
6780
7021
  "updated_at"
6781
7022
  ])
6782
- O[V] = n[V];
6783
- O = this.addClaims(O, this.idTokenClaims, i, n), O.scope = i, this.accessTokenExpiry != null && (O.exp = y + this.accessTokenExpiry), k = await new Promise((V, j) => {
6784
- se.sign(
6785
- O,
7023
+ F[$] = n[$];
7024
+ F = this.addClaims(F, this.idTokenClaims, i, n), F.scope = i, this.accessTokenExpiry != null && (F.exp = y + this.accessTokenExpiry), k = await new Promise(($, M) => {
7025
+ ee.sign(
7026
+ F,
6786
7027
  this.secretOrPrivateKey,
6787
7028
  {
6788
7029
  algorithm: this.jwtAlgorithmChecked,
6789
7030
  keyid: this.jwtKid
6790
7031
  },
6791
- (N, P) => {
6792
- P ? V(P) : j(N || new o(
7032
+ (N, K) => {
7033
+ K ? $(K) : M(N || new o(
6793
7034
  l.Unauthorized,
6794
7035
  "Couldn't create jwt"
6795
7036
  ));
@@ -6797,51 +7038,125 @@ class zt {
6797
7038
  );
6798
7039
  });
6799
7040
  }
6800
- let A;
7041
+ let P;
6801
7042
  if (a) {
6802
- const K = {
7043
+ const O = {
6803
7044
  username: d.username,
6804
7045
  client_id: s.client_id
6805
7046
  };
6806
- i && (K.scope = i);
6807
- let O;
6808
- const j = {
7047
+ i && (O.scope = i);
7048
+ let F;
7049
+ const M = {
6809
7050
  jti: _.uuid(),
6810
7051
  iat: y,
6811
7052
  iss: this.oauthIssuer,
6812
7053
  sub: d.username,
6813
7054
  type: "refresh"
6814
7055
  };
6815
- this.refreshTokenExpiry != null && (j.exp = y + this.refreshTokenExpiry, O = this.refreshTokenExpiry ? new Date(y + this.refreshTokenExpiry * 1e3 + this.clockTolerance * 1e3) : void 0), this.oauthIssuer && (j.aud = this.oauthIssuer), A = await new Promise((N, P) => {
6816
- se.sign(
6817
- j,
7056
+ this.refreshTokenExpiry != null && (M.exp = y + this.refreshTokenExpiry, F = this.refreshTokenExpiry ? new Date(y + this.refreshTokenExpiry * 1e3 + this.clockTolerance * 1e3) : void 0), this.oauthIssuer && (M.aud = this.oauthIssuer), P = await new Promise((N, K) => {
7057
+ ee.sign(
7058
+ M,
6818
7059
  this.secretOrPrivateKey,
6819
7060
  { algorithm: this.jwtAlgorithmChecked, keyid: "1" },
6820
- (F, I) => {
6821
- I ? N(I) : P(F || new o(
7061
+ (A, I) => {
7062
+ I ? N(I) : K(A || new o(
6822
7063
  l.Unauthorized,
6823
7064
  "Couldn't create jwt"
6824
7065
  ));
6825
7066
  }
6826
7067
  );
6827
- }), A && await ((H = this.keyStorage) == null ? void 0 : H.saveKey(
7068
+ }), P && await ((j = this.keyStorage) == null ? void 0 : j.saveKey(
6828
7069
  void 0,
6829
7070
  // to avoid user storage dependency
6830
- U.refreshToken + _.hash(A),
7071
+ b.refreshToken + _.hash(P),
6831
7072
  w,
6832
- O,
6833
- JSON.stringify(K)
7073
+ F,
7074
+ JSON.stringify(O)
6834
7075
  ));
6835
7076
  }
6836
7077
  return {
6837
7078
  access_token: T,
6838
7079
  id_token: k,
6839
- refresh_token: A,
7080
+ refresh_token: P,
6840
7081
  expires_in: this.accessTokenExpiry == null ? void 0 : this.accessTokenExpiry,
6841
7082
  token_type: "Bearer",
6842
7083
  scope: i ? i.join(" ") : void 0
6843
7084
  };
6844
7085
  }
7086
+ /**
7087
+ * Create an access token
7088
+ */
7089
+ async createTokensFromPayload(s, e, t) {
7090
+ var w;
7091
+ const r = /* @__PURE__ */ new Date(), i = Math.ceil(r.getTime() / 1e3);
7092
+ let a, n, c, d;
7093
+ if (e) {
7094
+ const y = _.uuid();
7095
+ let C = {
7096
+ ...e,
7097
+ jti: y,
7098
+ iat: i,
7099
+ iss: this.oauthIssuer,
7100
+ type: "access"
7101
+ };
7102
+ this.accessTokenExpiry != null && (C.exp = i + this.accessTokenExpiry, a = new Date(r.getTime() + this.accessTokenExpiry * 1e3 + this.clockTolerance * 1e3)), this.audience && (C.aud = this.audience), n = await new Promise((v, p) => {
7103
+ ee.sign(
7104
+ C,
7105
+ this.secretOrPrivateKey,
7106
+ { algorithm: this.jwtAlgorithmChecked, keyid: "1" },
7107
+ (T, k) => {
7108
+ k ? v(k) : p(T || new o(
7109
+ l.Unauthorized,
7110
+ "Couldn't create jwt"
7111
+ ));
7112
+ }
7113
+ );
7114
+ }), d = C, this.persistAccessToken && this.keyStorage && await ((w = this.keyStorage) == null ? void 0 : w.saveKey(
7115
+ void 0,
7116
+ // to avoid user storage dependency, we don't set this
7117
+ b.accessToken + _.hash(y),
7118
+ r,
7119
+ a
7120
+ ));
7121
+ }
7122
+ if (t != null) {
7123
+ const y = _.uuid();
7124
+ if (t = {
7125
+ ...t,
7126
+ aud: s,
7127
+ jti: y,
7128
+ iat: i,
7129
+ iss: this.oauthIssuer,
7130
+ type: "id"
7131
+ }, t) {
7132
+ const C = t;
7133
+ c = await new Promise((v, p) => {
7134
+ ee.sign(
7135
+ C,
7136
+ this.secretOrPrivateKey,
7137
+ {
7138
+ algorithm: this.jwtAlgorithmChecked,
7139
+ keyid: this.jwtKid
7140
+ },
7141
+ (T, k) => {
7142
+ k ? v(k) : p(T || new o(
7143
+ l.Unauthorized,
7144
+ "Couldn't create jwt"
7145
+ ));
7146
+ }
7147
+ );
7148
+ });
7149
+ }
7150
+ }
7151
+ return {
7152
+ access_token: n,
7153
+ id_token: c,
7154
+ access_payload: d,
7155
+ id_payload: t,
7156
+ expires_in: this.accessTokenExpiry == null ? void 0 : this.accessTokenExpiry,
7157
+ token_type: "Bearer"
7158
+ };
7159
+ }
6845
7160
  addClaims(s, e, t, r) {
6846
7161
  if (r) {
6847
7162
  if (t) {
@@ -6881,7 +7196,7 @@ class zt {
6881
7196
  */
6882
7197
  async validAuthorizationCode(s) {
6883
7198
  try {
6884
- const e = U.authorizationCode + _.hash(s);
7199
+ const e = b.authorizationCode + _.hash(s);
6885
7200
  return await this.keyStorage.getKey(e), !0;
6886
7201
  } catch (e) {
6887
7202
  return u.logger.debug(f({ err: e })), !1;
@@ -6895,7 +7210,7 @@ class zt {
6895
7210
  */
6896
7211
  async validRefreshToken(s) {
6897
7212
  try {
6898
- const e = U.refreshToken + _.hash(s);
7213
+ const e = b.refreshToken + _.hash(s);
6899
7214
  return await this.keyStorage.getKey(e), !0;
6900
7215
  } catch (e) {
6901
7216
  return u.logger.debug(f({ err: e })), !1;
@@ -6910,7 +7225,7 @@ class zt {
6910
7225
  async getRefreshTokenData(s) {
6911
7226
  if (s)
6912
7227
  try {
6913
- const e = U.refreshToken + _.hash(s), t = await this.keyStorage.getKey(e);
7228
+ const e = b.refreshToken + _.hash(s), t = await this.keyStorage.getKey(e);
6914
7229
  return JSON.parse(t.data || "{}");
6915
7230
  } catch (e) {
6916
7231
  u.logger.debug(f({ err: e }));
@@ -6944,7 +7259,7 @@ class zt {
6944
7259
  try {
6945
7260
  const e = await this.validateJwt(s, "access");
6946
7261
  if (this.persistAccessToken) {
6947
- const t = U.accessToken + _.hash(e.payload.jti);
7262
+ const t = b.accessToken + _.hash(e.payload.jti);
6948
7263
  await this.keyStorage.getKey(t);
6949
7264
  }
6950
7265
  return e;
@@ -6955,7 +7270,7 @@ class zt {
6955
7270
  }
6956
7271
  async validateJwt(s, e) {
6957
7272
  return new Promise((t, r) => {
6958
- se.verify(
7273
+ ee.verify(
6959
7274
  s,
6960
7275
  this.secretOrPublicKey,
6961
7276
  { clockTolerance: this.clockTolerance, complete: !0 },
@@ -7018,7 +7333,7 @@ class zt {
7018
7333
  */
7019
7334
  responseTypesSupported() {
7020
7335
  let s = [];
7021
- return (this.validFlows.includes(b.AuthorizationCode) || this.validFlows.includes(b.AuthorizationCodeWithPKCE) || this.validFlows.includes(b.OidcAuthorizationCode)) && s.push("code"), s;
7336
+ return (this.validFlows.includes(U.AuthorizationCode) || this.validFlows.includes(U.AuthorizationCodeWithPKCE) || this.validFlows.includes(U.OidcAuthorizationCode)) && s.push("code"), s;
7022
7337
  }
7023
7338
  /**
7024
7339
  * Returns an OIDC configuration object based on this authorization
@@ -7040,7 +7355,7 @@ class zt {
7040
7355
  }) {
7041
7356
  let i = [];
7042
7357
  this.validFlows.forEach((n) => {
7043
- const c = b.grantType(n);
7358
+ const c = U.grantType(n);
7044
7359
  c && (i = [...i, ...c]);
7045
7360
  });
7046
7361
  const a = [
@@ -7097,7 +7412,7 @@ class zt {
7097
7412
  jwks() {
7098
7413
  let s = [];
7099
7414
  if (this.jwtPublicKey) {
7100
- const e = ze(this.jwtPublicKey).export({ format: "jwk" });
7415
+ const e = Le(this.jwtPublicKey).export({ format: "jwk" });
7101
7416
  e.kid = "1", e.alg = this.jwtKeyType, s.push(e);
7102
7417
  }
7103
7418
  return { keys: s };
@@ -7137,177 +7452,6 @@ class zt {
7137
7452
  } : {};
7138
7453
  }
7139
7454
  }
7140
- class nt extends Pe {
7141
- /**
7142
- * Constructor
7143
- *
7144
- * @param options see {@link OAuthTokenConsumerOptions}
7145
- */
7146
- constructor(e, t = {}) {
7147
- const r = {};
7148
- m("jwtKeyType", g.String, r, t, "JWT_KEY_TYPE");
7149
- super(e, { ...t, ...r });
7150
- /**
7151
- * Value passed to the constructor. The `aud` claim must match it
7152
- */
7153
- h(this, "audience");
7154
- /**
7155
- * Value passed to the constructor. If true, access tokens are saved
7156
- * in storage,
7157
- */
7158
- h(this, "persistAccessToken", !1);
7159
- h(this, "keyStorage");
7160
- h(this, "jwtSecretKeyFile", "");
7161
- h(this, "jwtPublicKeyFile", "");
7162
- if (this.audience = e, m("authServerBaseUrl", g.String, this, t, "AUTH_SERVER_BASE_URL", !0), m("jwtSecretKeyFile", g.String, this, t, "JWT_SECRET_KEY_FILE"), m("jwtPublicKeyFile", g.String, this, t, "JWT_PUBLIC_KEY_FILE"), m("jwtSecretKey", g.String, this, t, "JWT_SECRET_KEY"), m("jwtPublicKey", g.String, this, t, "JWT_PUBLIC_KEY"), m("clockTolerance", g.Number, this, t, "OAUTH_CLOCK_TOLERANCE"), m("persistAccessToken", g.Boolean, this, t, "OAUTH_PERSIST_ACCESS_TOKEN"), this.keyStorage = t.keyStorage, this.jwtSecretKey || this.jwtSecretKeyFile) {
7163
- if (this.jwtPublicKey || this.jwtPublicKeyFile)
7164
- throw new o(
7165
- l.Configuration,
7166
- "Cannot specify symmetric and public/private JWT keys"
7167
- );
7168
- if (this.jwtSecretKey && this.jwtSecretKeyFile)
7169
- throw new o(
7170
- l.Configuration,
7171
- "Cannot specify symmetric key and file"
7172
- );
7173
- this.jwtSecretKeyFile && (this.jwtSecretKey = te.readFileSync(this.jwtSecretKeyFile, "utf8"));
7174
- } else if (this.jwtPublicKey || this.jwtPublicKeyFile) {
7175
- if (this.jwtPublicKeyFile && this.jwtPublicKey)
7176
- throw new o(
7177
- l.Configuration,
7178
- "Cannot specify both public key and public key file"
7179
- );
7180
- this.jwtPublicKeyFile && (this.jwtPublicKey = te.readFileSync(this.jwtPublicKeyFile, "utf8"));
7181
- }
7182
- }
7183
- /**
7184
- * Uses {@link Crypto.hash} to hash the given string.
7185
- *
7186
- * @param plaintext the string to hash
7187
- * @returns Base64-url-encoded hash
7188
- */
7189
- async hash(e) {
7190
- return _.hash(e);
7191
- }
7192
- /**
7193
- * If the given token is valid, the paylaod is returned. Otherwise
7194
- * undefined is returned.
7195
- *
7196
- * The signature must be valid, the expiry must not have passed and,
7197
- * if `tokenType` is defined,. the `type` claim in the payload must
7198
- * match it.
7199
- *
7200
- * Doesn't throw exceptions.
7201
- *
7202
- * @param token The token to validate
7203
- * @param tokenType If defined, the `type` claim in the payload must
7204
- * match this value
7205
- */
7206
- async tokenAuthorized(e, t) {
7207
- var i;
7208
- const r = await super.tokenAuthorized(e, t);
7209
- if (r && t == "access" && this.persistAccessToken && this.keyStorage)
7210
- try {
7211
- const a = U.accessToken + _.hash(r.jti ? r.jti : r.sid ? r.sid : ""), n = await this.keyStorage.getKey(a), c = /* @__PURE__ */ new Date();
7212
- if (n.expires && ((i = n.expires) == null ? void 0 : i.getTime()) < c.getTime()) {
7213
- u.logger.error(f({ msg: "Access token expired in storage but not in JWT" }));
7214
- return;
7215
- }
7216
- } catch (a) {
7217
- u.logger.warn(f({
7218
- msg: "Couldn't get token from database - is it valid?",
7219
- hashedAccessToken: _.hash(r.jti ? r.jti : r.sid ? r.sid : "")
7220
- })), u.logger.debug(f({ err: a }));
7221
- return;
7222
- }
7223
- return r;
7224
- }
7225
- }
7226
- class Ht extends Ke {
7227
- /**
7228
- * Constructor
7229
- * @param authServerBaseUrl bsae URI for the authorization server
7230
- * expected to issue access tokens. If the `iss` field in a JWT
7231
- * does not match this, it is rejected.
7232
- * @param options See {@link OAuthClientOptions}
7233
- */
7234
- constructor(e, t) {
7235
- const r = {
7236
- client_id: ""
7237
- };
7238
- m("client_id", g.String, r, t, "OAUTH_CLIENT_ID", !0);
7239
- super({
7240
- authServerBaseUrl: e,
7241
- tokenConsumer: new nt(
7242
- r.client_id,
7243
- {
7244
- audience: r.client_id,
7245
- authServerBaseUrl: e,
7246
- ...t
7247
- }
7248
- ),
7249
- ...t
7250
- });
7251
- h(this, "deviceAuthorizationUrl", "device_authorization");
7252
- h(this, "userCreationType", "idToken");
7253
- h(this, "userMatchField", "username");
7254
- h(this, "idTokenMatchField", "sub");
7255
- h(this, "userCreationFn");
7256
- h(this, "userStorage");
7257
- this.client_id = r.client_id;
7258
- let i = {};
7259
- if (m("stateLength", g.String, this, t, "OAUTH_STATE_LENGTH"), m("verifierLength", g.String, this, t, "OAUTH_VERIFIER_LENGTH"), m("client_secret", g.String, i, t, "OAUTH_CLIENT_SECRET"), m("codeChallengeMethod", g.String, this, t, "OAUTH_CODE_CHALLENGE_METHOD"), m("deviceAuthorizationUrl", g.String, this, t, "OAUTH_DEVICE_AUTHORIZATION_URL"), m("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), m("userCreationType", g.String, this, t, "OAUTH_USER_CREATION_TYPE"), m("userMatchField", g.String, this, t, "OAUTH_USER_MATCH_FIELD"), m("idTokenMatchField", g.String, this, t, "OAUTH_IDTOKEN_MaTCH_FIELD"), this.userCreationType == "merge" ? this.userCreationFn = ot : this.userCreationType == "embed" ? this.userCreationFn = lt : t.userCreationFn && this.userCreationType == "custom" ? this.userCreationFn = t.userCreationFn : this.userCreationFn = ct, t.userStorage && (this.userStorage = t.userStorage), m("oauthPostType", g.String, this, t, "OAUTH_POST_TYPE"), m("oauthUseUserInfoEndpoint", g.Boolean, this, t, "OAUTH_USE_USER_INFO_ENDPOINT"), m("oauthAuthorizeRedirect", g.String, this, t, "OAUTH_AUTHORIZE_REDIRECT"), this.oauthPostType != "json" && this.oauthPostType != "form")
7260
- throw new o(l.Configuration, "oauthPostType must be json or form");
7261
- }
7262
- /**
7263
- * Uses {@link @crossauth/backend!Crypto.randomValue} to create a random string
7264
- * @param length the length of the random array of bytes before
7265
- * base64-url-encoding
7266
- * @returns the Base64-URL-encoded random string
7267
- */
7268
- randomValue(e) {
7269
- return _.randomValue(e);
7270
- }
7271
- /**
7272
- * Uses {@link @crossauth/backend!Crypto.sha256} to create hash a string using SHA256
7273
- * @param plaintext the text to hash
7274
- * @returns the Base64-URL-encoded hash
7275
- */
7276
- async sha256(e) {
7277
- return _.sha256(e);
7278
- }
7279
- }
7280
- async function ot(S, s, e, t) {
7281
- if (!s) throw new o(l.Configuration, "userCreationType set to merge but no user storage set");
7282
- try {
7283
- let r;
7284
- return e == "username" ? r = await s.getUserByUsername(S[t]) : e == "username" ? r = await s.getUserByEmail(S[t]) : r = await s.getUserBy(e, S[t]), { ...S, ...r.user };
7285
- } catch (r) {
7286
- const i = o.asCrossauthError(r);
7287
- if (i.code == l.UserNotExist || i.code == l.UserNotActive)
7288
- return;
7289
- throw u.logger.error(f({ err: r })), r;
7290
- }
7291
- }
7292
- async function lt(S, s, e, t) {
7293
- if (!s) throw new o(l.Configuration, "userCreationType set to embed but no user storage set");
7294
- try {
7295
- let r;
7296
- return e == "username" ? r = await s.getUserByUsername(S[t]) : e == "username" ? r = await s.getUserByEmail(S[t]) : r = await s.getUserBy(e, S[t]), { ...r.user, idToken: S };
7297
- } catch (r) {
7298
- const i = o.asCrossauthError(r);
7299
- if (i.code == l.UserNotExist || i.code == l.UserNotActive)
7300
- return;
7301
- throw u.logger.error({ err: r }), r;
7302
- }
7303
- }
7304
- async function ct(S, s, e, t) {
7305
- return {
7306
- id: S.userid ?? S.sub,
7307
- username: S.sub,
7308
- state: S.state ?? "active"
7309
- };
7310
- }
7311
7455
  class jt {
7312
7456
  /**
7313
7457
  * Constructor
@@ -7352,43 +7496,43 @@ class jt {
7352
7496
  }
7353
7497
  export {
7354
7498
  ge as ApiKeyManager,
7355
- re as Authenticator,
7499
+ ie as Authenticator,
7356
7500
  _ as Crypto,
7357
7501
  rt as DoubleSubmitCsrfToken,
7358
7502
  Rt as DummyFactor2Authenticator,
7359
7503
  Z as EmailAuthenticator,
7360
- At as InMemoryKeyStorage,
7361
- Pt as InMemoryOAuthAuthorizationStorage,
7362
- It as InMemoryOAuthClientStorage,
7363
- Ut as InMemoryUserStorage,
7364
- x as KeyStorage,
7365
- Dt as LdapAuthenticator,
7504
+ It as InMemoryKeyStorage,
7505
+ Kt as InMemoryOAuthAuthorizationStorage,
7506
+ Pt as InMemoryOAuthClientStorage,
7507
+ At as InMemoryUserStorage,
7508
+ z as KeyStorage,
7509
+ xt as LdapAuthenticator,
7366
7510
  oe as LdapUserStorage,
7367
7511
  ve as LocalPasswordAuthenticator,
7368
- zt as OAuthAuthorizationServer,
7512
+ Ht as OAuthAuthorizationServer,
7369
7513
  we as OAuthAuthorizationStorage,
7370
- Ht as OAuthClientBackend,
7514
+ nt as OAuthClientBackend,
7371
7515
  J as OAuthClientManager,
7372
7516
  me as OAuthClientStorage,
7373
7517
  jt as OAuthResourceServer,
7374
- nt as OAuthTokenConsumer,
7518
+ at as OAuthTokenConsumer,
7375
7519
  g as ParamType,
7376
7520
  be as PasswordAuthenticator,
7377
7521
  Ft as PostgresKeyStorage,
7378
- Nt as PostgresOAuthAuthorizationStorage,
7379
- Ot as PostgresOAuthClientStorage,
7380
- Kt as PostgresUserStorage,
7381
- kt as PrismaKeyStorage,
7382
- bt as PrismaOAuthAuthorizationStorage,
7383
- Et as PrismaOAuthClientStorage,
7522
+ Dt as PostgresOAuthAuthorizationStorage,
7523
+ Nt as PostgresOAuthClientStorage,
7524
+ Ot as PostgresUserStorage,
7525
+ Et as PrismaKeyStorage,
7526
+ Ut as PrismaOAuthAuthorizationStorage,
7527
+ bt as PrismaOAuthClientStorage,
7384
7528
  G as PrismaUserStorage,
7385
- D as SessionCookie,
7529
+ R as SessionCookie,
7386
7530
  Lt as SessionManager,
7387
7531
  Q as SmsAuthenticator,
7388
- R as TokenEmailer,
7389
- xt as TotpAuthenticator,
7532
+ D as TokenEmailer,
7533
+ Bt as TotpAuthenticator,
7390
7534
  Ue as TwilioAuthenticator,
7391
7535
  L as UserStorage,
7392
7536
  m as setParameter,
7393
- Bt as toCookieSerializeOptions
7537
+ zt as toCookieSerializeOptions
7394
7538
  };