@crossauth/backend 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
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 U, KeyPrefix as b, OAuthTokenConsumerBase as Pe, OAuthClientBase as Ke } from "@crossauth/common";
4
+ import { CrossauthError as o, ErrorCode as l, CrossauthLogger as u, j as f, UserState as E, 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 Oe, createHash as Fe, pbkdf2 as Ne, createHmac as se, createCipheriv as De, createDecipheriv as Re, randomInt as te } 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 Re, createDecipheriv as De, 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";
@@ -187,6 +187,7 @@ class G extends L {
187
187
  }
188
188
  async getUser(e, t, r) {
189
189
  let i, a;
190
+ if (this.prismaClient || (i = new o(l.Connection)), i) throw i;
190
191
  try {
191
192
  a = await this.prismaClient[this.userTable].findUniqueOrThrow({
192
193
  where: {
@@ -194,10 +195,10 @@ class G extends L {
194
195
  },
195
196
  include: this.includesObject
196
197
  });
197
- } catch {
198
- i = new o(l.UserNotExist);
198
+ } catch (c) {
199
+ typeof c == "object" && (c == null ? void 0 : c.constructor.name) == "PrismaClientInitializationError" ? (u.logger.debug(f({ err: c })), u.logger.error(f({ cerr: c })), i = new o(l.Connection, "Couldn't connect to database server")) : typeof c == "object" && (c == null ? void 0 : c.constructor.name) == "PrismaClientInitializationError" ? (u.logger.debug(f({ err: c })), u.logger.error(f({ cerr: c })), i = new o(l.Connection, "Received error from database")) : i = new o(l.UserNotExist);
199
200
  }
200
- if (this.prismaClient || (i = new o(l.Connection)), i) throw i;
201
+ if (i) throw i;
201
202
  if ((r == null ? void 0 : r.skipActiveCheck) != !0 && a.state == E.awaitingTwoFactorSetup)
202
203
  throw u.logger.debug(f({ msg: "2FA setup is not complete" })), new o(l.TwoFactorIncomplete);
203
204
  if ((r == null ? void 0 : r.skipActiveCheck) != !0 && a.state == E.disabled)
@@ -220,8 +221,13 @@ class G extends L {
220
221
  * @throws {@link @crossauth/common!CrossauthError } with {@link @crossauth/common!ErrorCode } set to either `UserNotExist` or `Connection`.
221
222
  */
222
223
  async getUserByUsername(e, t) {
223
- const r = G.normalize(e);
224
- return this.getUser("username_normalized", r, t);
224
+ if (this.normalizeUsername) {
225
+ const r = G.normalize(e);
226
+ return this.getUser("username_normalized", r, t);
227
+ } else {
228
+ const r = e;
229
+ return this.getUser("username", r, t);
230
+ }
225
231
  }
226
232
  /**
227
233
  * Returns user matching the given field, or throws an exception.
@@ -244,8 +250,13 @@ class G extends L {
244
250
  * @throws {@link @crossauth/common!CrossauthError } with {@link @crossauth/common!ErrorCode } set to either `UserNotExist` or `Connection`.
245
251
  */
246
252
  async getUserByEmail(e, t) {
247
- const r = G.normalize(e);
248
- return this.getUser("email_normalized", r, t);
253
+ if (this.normalizeEmail) {
254
+ const r = G.normalize(e);
255
+ return this.getUser("email_normalized", r, t);
256
+ } else {
257
+ const r = e;
258
+ return this.getUser("email", r, t);
259
+ }
249
260
  }
250
261
  /**
251
262
  * Same as {@link getUserByUsername } but matching user ID,
@@ -278,7 +289,7 @@ class G extends L {
278
289
  t && !t.userid && (t = { ...t, userid: e[this.idColumn] });
279
290
  try {
280
291
  let { id: r, ...i } = e, { userid: a, ...n } = t ?? {};
281
- "email" in i && i.email && (i = { email_normalized: G.normalize(i.email), ...i }), "username" in i && i.username && (i = { username_normalized: G.normalize(i.username), ...i }), t ? await this.prismaClient.$transaction(async (c) => {
292
+ "email" in i && i.email && this.normalizeEmail && (i = { email_normalized: G.normalize(i.email), ...i }), "username" in i && i.username && this.normalizeUsername && (i = { username_normalized: G.normalize(i.username), ...i }), t ? await this.prismaClient.$transaction(async (c) => {
282
293
  let d = {};
283
294
  try {
284
295
  d = await c[this.userSecretsTable].findUniqueOrThrow({
@@ -313,7 +324,7 @@ class G extends L {
313
324
  data: i
314
325
  });
315
326
  } catch (r) {
316
- throw u.logger.debug(f({ err: r })), new o(l.Connection, "Error updating user");
327
+ throw console.log(r), u.logger.debug(f({ err: r })), new o(l.Connection, "Error updating user");
317
328
  }
318
329
  }
319
330
  /**
@@ -330,22 +341,26 @@ class G extends L {
330
341
  if (t && !t.password) throw new o(l.PasswordFormat, "Password required when creating user");
331
342
  let i, a = "", n = "";
332
343
  try {
333
- "email" in e && e.email && (n = G.normalize(e.email)), "username" in e && e.username && (a = G.normalize(e.username)), t ? i = await this.prismaClient[this.userTable].create({
334
- data: {
335
- ...e,
336
- email_normalized: n,
337
- username_normalized: a,
338
- secrets: {
339
- create: t
340
- }
341
- },
342
- include: { secrets: !0 }
343
- }) : i = await this.prismaClient[this.userTable].create({
344
- data: {
345
- ...e,
346
- email_normalized: n,
347
- username_normalized: a
344
+ "email" in e && e.email && this.normalizeEmail && (n = G.normalize(e.email)), "username" in e && e.username && this.normalizeUsername && (a = G.normalize(e.username));
345
+ let c = {
346
+ ...e
347
+ };
348
+ this.normalizeUsername && (c = {
349
+ ...c,
350
+ username_normalized: a
351
+ }), this.normalizeEmail && (c = {
352
+ ...c,
353
+ email_normalized: n
354
+ }), t ? (c = {
355
+ ...c,
356
+ secrets: {
357
+ create: t
348
358
  }
359
+ }, i = await this.prismaClient[this.userTable].create({
360
+ data: c,
361
+ include: { secrets: !0 }
362
+ })) : i = await this.prismaClient[this.userTable].create({
363
+ data: c
349
364
  });
350
365
  } catch (c) {
351
366
  u.logger.debug(f({ err: c })), r = new o(l.Connection, "Error creating user"), (c instanceof X.PrismaClientKnownRequestError || c instanceof Object && "code" in c) && c.code === "P2002" && (r = new o(l.UserExists));
@@ -398,18 +413,19 @@ class G extends L {
398
413
  async getUsers(e, t) {
399
414
  let r = {};
400
415
  e && (r.skip = e), t && (r.take = t);
416
+ let i = this.normalizeUsername ? "username_normalized" : "username";
401
417
  try {
402
418
  return await this.prismaClient[this.userTable].findMany({
403
419
  ...r,
404
420
  orderBy: [
405
421
  {
406
- username_normalized: "asc"
422
+ [i]: "asc"
407
423
  }
408
424
  ],
409
425
  include: this.includesObject
410
426
  });
411
- } catch (i) {
412
- throw u.logger.error(f({ err: i })), new o(l.Connection, "Couldn't select from user table");
427
+ } catch (a) {
428
+ throw u.logger.error(f({ err: a })), new o(l.Connection, "Couldn't select from user table");
413
429
  }
414
430
  }
415
431
  }
@@ -959,7 +975,7 @@ class Ut extends we {
959
975
  // PrismaClient;
960
976
  h(this, "transactionTimeout", 5e3);
961
977
  h(this, "useridForeignKeyColumn", "userid");
962
- m("authorizationTable", g.String, this, e, "OAUTH_CLIENT_TABLE"), m("transactionTimeout", g.Number, this, e, "TRANSACTION_TIMEOUT"), m("useridForeignKeyColumn", g.String, this, e, "USER_ID_FOREIGN_KEY_COLUMN"), e.prismaClient == null ? this.prismaClient = new ce() : this.prismaClient = e.prismaClient;
978
+ m("authorizationTable", g.String, this, e, "OAUTH_AUTHORIZATION_TABLE"), m("transactionTimeout", g.Number, this, e, "TRANSACTION_TIMEOUT"), m("useridForeignKeyColumn", g.String, this, e, "USER_ID_FOREIGN_KEY_COLUMN"), e.prismaClient == null ? this.prismaClient = new ce() : this.prismaClient = e.prismaClient;
963
979
  }
964
980
  async getAuthorizations(e, t) {
965
981
  try {
@@ -1029,12 +1045,13 @@ class At extends L {
1029
1045
  * @param secrets optionally, secrets to save
1030
1046
  */
1031
1047
  async createUser(e, t) {
1032
- if (e.username_normalized = L.normalize(e.username), e.username_normalized in this.usersByUsername)
1048
+ let r = "username", i = "email";
1049
+ if (this.normalizeUsername && (r = "username_normalized", e.username_normalized = L.normalize(e.username), e.username_normalized in this.usersByUsername))
1033
1050
  throw new o(l.UserExists);
1034
- if ("email" in e && e.email && (e.email_normalized = L.normalize(e.email), e.email_normalized in this.getUserByEmail))
1051
+ if ("email" in e && e.email && this.normalizeEmail && (i = "email_normalized", e.email_normalized = L.normalize(e.email), e.email_normalized in this.getUserByEmail))
1035
1052
  throw new o(l.UserExists);
1036
- const r = { id: e.username, ...e };
1037
- return this.usersByUsername[e.username_normalized] = r, this.secretsByUsername[e.username_normalized] = t ?? {}, "email" in e && e.email && (this.usersByEmail[e.email_normalized] = r), "email" in e && e.email && (this.secretsByEmail[e.email_normalized] = t ?? {}), { id: e.username, ...e };
1053
+ const a = { id: e.username, ...e };
1054
+ return this.usersByUsername[e[r]] = a, this.secretsByUsername[e[r]] = t ?? {}, "email" in e && e.email && (this.usersByEmail[e[i]] = a), "email" in e && e.email && (this.secretsByEmail[e[i]] = t ?? {}), { id: e.username, ...e };
1038
1055
  }
1039
1056
  /**
1040
1057
  * Returns a {@link User }and {@link UserSecrets } instance matching the given username, or throws an Exception.
@@ -1044,7 +1061,7 @@ class At extends L {
1044
1061
  * @throws {@link @crossauth/common!CrossauthError } with {@link @crossauth/common!ErrorCode } set to either `UserNotExist`.
1045
1062
  */
1046
1063
  async getUserByUsername(e, t) {
1047
- const r = L.normalize(e);
1064
+ const r = this.normalizeUsername ? L.normalize(e) : e;
1048
1065
  if (r in this.usersByUsername) {
1049
1066
  const i = this.usersByUsername[r];
1050
1067
  if (!i) throw new o(l.UserNotExist);
@@ -1073,7 +1090,7 @@ class At extends L {
1073
1090
  * @throws {@link @crossauth/common!CrossauthError } with {@link @crossauth/common!ErrorCode } set to either `UserNotExist`.
1074
1091
  */
1075
1092
  async getUserByEmail(e, t) {
1076
- const r = L.normalize(e);
1093
+ const r = this.normalizeEmail ? L.normalize(e) : e;
1077
1094
  if (r in this.usersByEmail) {
1078
1095
  const i = this.usersByEmail[r];
1079
1096
  if (!i) throw new o(l.UserNotExist);
@@ -1116,12 +1133,12 @@ class At extends L {
1116
1133
  * @param user the user to update. The id to update is taken from this obkect, which must be present. All other attributes are optional.
1117
1134
  */
1118
1135
  async updateUser(e, t) {
1119
- let r = { ...e };
1120
- if ("username" in r && r.username ? r.username_normalized = L.normalize(r.username) : "id" in r && r.id && (r.username_normalized = L.normalize(String(r.id))), "email" in r && r.email && (r.email_normalized = L.normalize(r.email)), r.username_normalized && r.username_normalized in this.usersByUsername) {
1121
- for (let i in r)
1122
- this.usersByUsername[r.username_normalized][i] = r[i];
1123
- t && (this.secretsByUsername[r.username_normalized] = {
1124
- ...this.secretsByUsername[r.username_normalized],
1136
+ let r = { ...e }, i = "username";
1137
+ if ("username" in r && r.username && this.normalizeUsername ? (r.username_normalized = L.normalize(r.username), i = "username_normalized") : "id" in r && r.id && this.normalizeUsername && (r.username_normalized = L.normalize(String(r.id)), i = "username_normalized"), "email" in r && r.email && this.normalizeEmail && (r.email_normalized = L.normalize(r.email)), r[i] && r[i] in this.usersByUsername) {
1138
+ for (let a in r)
1139
+ this.usersByUsername[r[i]][a] = r[a];
1140
+ t && (this.secretsByUsername[r[i]] = {
1141
+ ...this.secretsByUsername[r[i]],
1125
1142
  ...t
1126
1143
  });
1127
1144
  }
@@ -1131,12 +1148,12 @@ class At extends L {
1131
1148
  * @param username username of user to delete
1132
1149
  */
1133
1150
  async deleteUserByUsername(e) {
1134
- const t = L.normalize(String(e));
1151
+ const t = this.normalizeUsername ? L.normalize(String(e)) : e;
1135
1152
  if (t in this.usersByUsername) {
1136
1153
  const r = this.usersByUsername[t];
1137
1154
  delete this.usersByUsername[t], delete this.secretsByUsername[t];
1138
- const i = L.normalize(String(r.email));
1139
- i in this.usersByEmail && (delete this.usersByEmail[i], delete this.secretsByEmail[i]);
1155
+ const i = this.normalizeEmail ? L.normalize(String(r.email)) : r.email;
1156
+ i && i in this.usersByEmail && (delete this.usersByEmail[i], delete this.secretsByEmail[i]);
1140
1157
  }
1141
1158
  }
1142
1159
  /**
@@ -1546,7 +1563,7 @@ class oe extends L {
1546
1563
  async getLdapUser(e, t) {
1547
1564
  let r;
1548
1565
  try {
1549
- const i = oe.sanitizeLdapDnForSerach(e), a = [this.ldapUsernameAttribute + "=" + i, this.ldapUserSearchBase].join(",");
1566
+ const i = oe.sanitizeLdapDnForSearch(e), a = [this.ldapUsernameAttribute + "=" + i, this.ldapUserSearchBase].join(",");
1550
1567
  if (!t) throw new o(l.PasswordInvalid);
1551
1568
  return u.logger.debug(f({ msg: "LDAP search " + a })), r = await this.ldapBind(a, t), await this.searchUser(r, a);
1552
1569
  } catch (i) {
@@ -1626,7 +1643,7 @@ class oe extends L {
1626
1643
  * @param dn the dn to sanitise
1627
1644
  * @returns a sanitized dn
1628
1645
  */
1629
- static sanitizeLdapDnForSerach(e) {
1646
+ static sanitizeLdapDnForSearch(e) {
1630
1647
  return oe.sanitizeLdapDn(e).replace("*", "*").replace("(", "(").replace(")", ")");
1631
1648
  }
1632
1649
  }
@@ -2216,10 +2233,10 @@ class We extends me {
2216
2233
  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
2234
  let T = y + " union " + v + " order by client_id";
2218
2235
  const k = await e.execute(T, w);
2219
- let P;
2236
+ let A;
2220
2237
  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;
2238
+ (!A || H.client_id != A.client_id) && (A && c.push(A), A = this.makeClient(H), A.valid_flow = [], A.redirect_uri = []), H.uri && A.redirect_uri.push(H.uri), H.flow && A.valid_flow.push(H.flow);
2239
+ return A && c.push(A), c;
2223
2240
  }
2224
2241
  /**
2225
2242
  * Saves a key in the session table.
@@ -2518,7 +2535,7 @@ class Nt extends We {
2518
2535
  super(new de(s), e);
2519
2536
  }
2520
2537
  }
2521
- class Dt extends Je {
2538
+ class Rt extends Je {
2522
2539
  /**
2523
2540
  * Creates a PostgresOAuthClientStorage object, optionally overriding defaults.
2524
2541
  * @param pgPool the instance of the Posrgres client.
@@ -2838,7 +2855,7 @@ const Ce = process.env.PBKDF2_DIGEST || "sha256", Se = Number(process.env.PBKDF2
2838
2855
  static symmetricEncrypt(s, e, t = void 0) {
2839
2856
  t || (t = ue(16));
2840
2857
  let r = Buffer.from(e, "base64url");
2841
- var i = De("aes-256-cbc", r, t);
2858
+ var i = Re("aes-256-cbc", r, t);
2842
2859
  let a = i.update(s);
2843
2860
  return a = Buffer.concat([a, i.final()]), t.toString("base64url") + "." + a.toString("base64url");
2844
2861
  }
@@ -2854,7 +2871,7 @@ const Ce = process.env.PBKDF2_DIGEST || "sha256", Se = Number(process.env.PBKDF2
2854
2871
  const r = s.split(".");
2855
2872
  if (r.length != 2) throw new o(l.InvalidHash, "Not AES-256-CBC ciphertext");
2856
2873
  let i = Buffer.from(r[0], "base64url"), a = Buffer.from(r[1], "base64url");
2857
- var n = Re("aes-256-cbc", t, i);
2874
+ var n = De("aes-256-cbc", t, i);
2858
2875
  let c = n.update(a);
2859
2876
  return c = Buffer.concat([c, n.final()]), c.toString();
2860
2877
  }
@@ -2916,9 +2933,9 @@ const le = class le extends be {
2916
2933
  if (!t.password) throw new o(l.PasswordInvalid);
2917
2934
  if (!await _.passwordsEqual(r.password, t.password, this.secret))
2918
2935
  throw u.logger.debug(f({ msg: "Invalid password hash", user: e.username })), new o(l.PasswordInvalid);
2919
- if (e.state == "awaitingtwofactorsetup") throw new o(l.TwoFactorIncomplete);
2920
- if (e.state == "awaitingemailverification") throw new o(l.EmailNotVerified);
2921
- if (e.state == "deactivated") throw new o(l.UserNotActive);
2936
+ if (e.state == E.awaitingTwoFactorSetup) throw new o(l.TwoFactorIncomplete);
2937
+ if (e.state == E.awaitingEmailVerification) throw new o(l.EmailNotVerified);
2938
+ if (e.state == E.disabled) throw new o(l.UserNotActive);
2922
2939
  }
2923
2940
  /**
2924
2941
  * Calls the implementor-provided `validatePasswordFn`
@@ -2943,10 +2960,10 @@ const le = class le extends be {
2943
2960
  * @param salt the salt to use. If undefined, a random one will be generated.
2944
2961
  * @returns the encoded hash string.
2945
2962
  */
2946
- async createPasswordHash(e, t) {
2963
+ async createPasswordHash(e, t, r = !0) {
2947
2964
  return await _.passwordHash(e, {
2948
2965
  salt: t,
2949
- encode: !0,
2966
+ encode: r,
2950
2967
  secret: this.enableSecretForPasswords ? this.secret : void 0,
2951
2968
  iterations: this.pbkdf2Iterations,
2952
2969
  keyLen: this.pbkdf2KeyLength,
@@ -3035,7 +3052,7 @@ class Z extends ie {
3035
3052
  * @param options see {@link EmailAuthenticatorOptions}
3036
3053
  */
3037
3054
  constructor(e = {}) {
3038
- super({ friendlyName: "Email otp", ...e });
3055
+ super({ friendlyName: "Email OTP", ...e });
3039
3056
  h(this, "views", "views");
3040
3057
  h(this, "emailAuthenticatorTextBody", "emailauthenticationtextbody.njk");
3041
3058
  h(this, "emailAuthenticatorHtmlBody");
@@ -3104,6 +3121,7 @@ class Z extends ie {
3104
3121
  username: e.username,
3105
3122
  factor2: this.factorName,
3106
3123
  expiry: a,
3124
+ email: r,
3107
3125
  otp: t
3108
3126
  }, d = this.sendToken(r, t);
3109
3127
  return u.logger.info(f({
@@ -3293,6 +3311,7 @@ class Q extends ie {
3293
3311
  username: e.username,
3294
3312
  factor2: this.factorName,
3295
3313
  expiry: a,
3314
+ phone: r,
3296
3315
  otp: t
3297
3316
  };
3298
3317
  let d = { otp: t };
@@ -3474,7 +3493,7 @@ class Ue extends Q {
3474
3493
  return (await Be(this.accountSid, this.authToken).messages.create(r)).sid;
3475
3494
  }
3476
3495
  }
3477
- class Rt extends ie {
3496
+ class Dt extends ie {
3478
3497
  /**
3479
3498
  * Constructor
3480
3499
  *
@@ -3667,15 +3686,15 @@ class xt extends be {
3667
3686
  try {
3668
3687
  i = (await this.ldapStorage.getUserByUsername(e.username)).user, i.factor1 = this.ldapAutoCreateFactor1;
3669
3688
  } catch {
3670
- i = await this.ldapStorage.createUser({ factor1: this.ldapAutoCreateFactor1, ...e }, r);
3689
+ u.logger.debug(f({ msg: "Creating user", user: e.username })), i = await this.ldapStorage.createUser({ factor1: this.ldapAutoCreateFactor1, ...e }, r);
3671
3690
  }
3672
3691
  else
3673
3692
  i = (await this.ldapStorage.getUserByUsername(e.username)).user;
3674
- if (i.state == "awaitingtwofactorsetup") throw new o(l.TwoFactorIncomplete);
3675
- if (i.state == "awaitingemailverification") throw new o(l.EmailNotVerified);
3676
- if (i.state == "deactivated") throw new o(l.UserNotActive);
3693
+ if (i.state == E.awaitingTwoFactorSetup) throw new o(l.TwoFactorIncomplete);
3694
+ if (i.state == E.awaitingEmailVerification) throw new o(l.EmailNotVerified);
3695
+ if (i.state == E.disabled) throw new o(l.UserNotActive);
3677
3696
  } catch (a) {
3678
- throw console.log(a), u.logger.debug(f({ err: a })), a;
3697
+ throw u.logger.debug(f({ err: a })), a;
3679
3698
  }
3680
3699
  }
3681
3700
  /**
@@ -3917,7 +3936,7 @@ class Bt extends ie {
3917
3936
  }
3918
3937
  }
3919
3938
  const ne = 16;
3920
- class D {
3939
+ class R {
3921
3940
  /**
3922
3941
  * Construct a new EmailVerifier.
3923
3942
  *
@@ -3977,11 +3996,11 @@ class D {
3977
3996
  let r = 0;
3978
3997
  const i = /* @__PURE__ */ new Date(), a = new Date(i.getTime() + 1e3 * this.verifyEmailExpires);
3979
3998
  for (; r < 10; ) {
3980
- let n = _.randomValue(ne), c = D.hashEmailVerificationToken(n);
3999
+ let n = _.randomValue(ne), c = R.hashEmailVerificationToken(n);
3981
4000
  try {
3982
4001
  return await this.keyStorage.saveKey(s, c, i, a, e), n;
3983
4002
  } catch {
3984
- n = _.randomValue(ne), c = D.hashEmailVerificationToken(n), r++;
4003
+ n = _.randomValue(ne), c = R.hashEmailVerificationToken(n), r++;
3985
4004
  }
3986
4005
  }
3987
4006
  throw new o(l.Connection, "failed creating a unique key");
@@ -4022,7 +4041,7 @@ class D {
4022
4041
  "Either emailVerificationTextBody or emailVerificationHtmlBody must be set to send email verification emails"
4023
4042
  );
4024
4043
  let { user: r } = await this.userStorage.getUserById(s, { skipEmailVerifiedCheck: !0 }), i = e;
4025
- i != "" ? D.validateEmail(i) : (i = r.email ?? r.username, i || (i = r.username), D.validateEmail(i)), D.validateEmail(i);
4044
+ i != "" ? R.validateEmail(i) : (i = r.email ?? r.username, i || (i = r.username), R.validateEmail(i)), R.validateEmail(i);
4026
4045
  const a = await this.createAndSaveEmailVerificationToken(s, e), n = await this._sendEmailVerificationToken(a, i, t);
4027
4046
  u.logger.info(f({ msg: "Sent email verification email", emailMessageId: n, email: i }));
4028
4047
  }
@@ -4042,20 +4061,20 @@ class D {
4042
4061
  * address the user is validating
4043
4062
  */
4044
4063
  async verifyEmailVerificationToken(s) {
4045
- const e = D.hashEmailVerificationToken(s);
4064
+ const e = R.hashEmailVerificationToken(s);
4046
4065
  let t = await this.keyStorage.getKey(e);
4047
4066
  try {
4048
4067
  if (!t.userid || !t.expires) throw new o(l.InvalidKey);
4049
4068
  const { user: r } = await this.userStorage.getUserById(t.userid, { skipEmailVerifiedCheck: !0 });
4050
4069
  let i = (r.email ?? r.username).toLowerCase();
4051
- if (i || (i = r.username.toLowerCase()), D.validateEmail(i), (/* @__PURE__ */ new Date()).getTime() > t.expires.getTime()) throw new o(l.Expired);
4070
+ if (i || (i = r.username.toLowerCase()), R.validateEmail(i), (/* @__PURE__ */ new Date()).getTime() > t.expires.getTime()) throw new o(l.Expired);
4052
4071
  return { userid: t.userid, newEmail: t.data ?? "" };
4053
4072
  } finally {
4054
4073
  }
4055
4074
  }
4056
4075
  async deleteEmailVerificationToken(s) {
4057
4076
  try {
4058
- const e = D.hashEmailVerificationToken(s);
4077
+ const e = R.hashEmailVerificationToken(s);
4059
4078
  await this.keyStorage.deleteKey(e);
4060
4079
  } catch (e) {
4061
4080
  const t = o.asCrossauthError(e);
@@ -4066,11 +4085,11 @@ class D {
4066
4085
  let t = 0;
4067
4086
  const r = /* @__PURE__ */ new Date(), i = new Date(r.getTime() + 1e3 * this.passwordResetExpires);
4068
4087
  for (; t < 10; ) {
4069
- let a = _.randomValue(ne), n = D.hashPasswordResetToken(a);
4088
+ let a = _.randomValue(ne), n = R.hashPasswordResetToken(a);
4070
4089
  try {
4071
4090
  return await this.keyStorage.saveKey(s, n, r, i), a;
4072
4091
  } catch {
4073
- a = _.randomValue(ne), n = D.hashPasswordResetToken(a), t++;
4092
+ a = _.randomValue(ne), n = R.hashPasswordResetToken(a), t++;
4074
4093
  }
4075
4094
  }
4076
4095
  throw new o(l.Connection, "failed creating a unique key");
@@ -4090,7 +4109,7 @@ class D {
4090
4109
  * @returns the user that the token is for
4091
4110
  */
4092
4111
  async verifyPasswordResetToken(s) {
4093
- const e = D.hashPasswordResetToken(s);
4112
+ const e = R.hashPasswordResetToken(s);
4094
4113
  u.logger.debug("verifyPasswordResetToken " + s + " " + e);
4095
4114
  let t = await this.keyStorage.getKey(e);
4096
4115
  if (!t.userid) throw new o(l.InvalidKey);
@@ -4139,7 +4158,7 @@ class D {
4139
4158
  if (!t && r.state != E.active && r.state != E.passwordResetNeeded && r.state != E.passwordAndFactor2ResetNeeded)
4140
4159
  throw new o(l.UserNotActive);
4141
4160
  let i = (r.email ?? r.username).toLowerCase();
4142
- i || (i = r.username.toLowerCase()), D.validateEmail(i);
4161
+ i || (i = r.username.toLowerCase()), R.validateEmail(i);
4143
4162
  const a = await this.createAndSavePasswordResetToken(s), n = await this._sendPasswordResetToken(a, i, e);
4144
4163
  u.logger.info(f({ msg: "Sent password reset email", emailMessageId: n, email: i }));
4145
4164
  }
@@ -4161,7 +4180,7 @@ class D {
4161
4180
  * @param email the email to validate
4162
4181
  */
4163
4182
  static validateEmail(s) {
4164
- if (s == null || !D.isEmailValid(s)) throw new o(l.InvalidEmail);
4183
+ if (s == null || !R.isEmailValid(s)) throw new o(l.InvalidEmail);
4165
4184
  }
4166
4185
  }
4167
4186
  const _e = 16, ke = 16;
@@ -4285,7 +4304,7 @@ class rt {
4285
4304
  }
4286
4305
  }
4287
4306
  }
4288
- class R {
4307
+ class D {
4289
4308
  /**
4290
4309
  * Constructor.
4291
4310
  *
@@ -4351,7 +4370,7 @@ class R {
4351
4370
  const a = /* @__PURE__ */ new Date();
4352
4371
  let n = this.expiry(a), c = !1;
4353
4372
  for (; r < 10 && !c; ) {
4354
- const d = R.hashSessionId(i);
4373
+ const d = D.hashSessionId(i);
4355
4374
  try {
4356
4375
  this.idleTimeout > 0 && s && (e = { ...e, lastActivity: /* @__PURE__ */ new Date() }), await this.keyStorage.saveKey(s, d, a, n, void 0, e), c = !0;
4357
4376
  } catch (w) {
@@ -4407,7 +4426,7 @@ class R {
4407
4426
  */
4408
4427
  async updateSessionKey(s) {
4409
4428
  if (!s.value) throw new o(l.InvalidKey, "No session when updating activity");
4410
- s.value = R.hashSessionId(s.value), await this.keyStorage.updateKey(s);
4429
+ s.value = D.hashSessionId(s.value), await this.keyStorage.updateKey(s);
4411
4430
  }
4412
4431
  /**
4413
4432
  * Unsigns a cookie and returns the original value.
@@ -4455,7 +4474,7 @@ class R {
4455
4474
  * `Expired` or `UserNotExist`.
4456
4475
  */
4457
4476
  async getSessionKey(s) {
4458
- const e = Date.now(), t = R.hashSessionId(s), r = await this.keyStorage.getKey(t);
4477
+ const e = Date.now(), t = D.hashSessionId(s), r = await this.keyStorage.getKey(t);
4459
4478
  if (r.value = s, r.expires && e > r.expires.getTime())
4460
4479
  throw u.logger.warn(f({ msg: "Session id in cookie expired in key storage", hashedSessionCookie: _.hash(s) })), new o(l.Expired);
4461
4480
  if (r.userid && this.idleTimeout > 0 && r.lastactive && e > r.lastactive.getTime() + this.idleTimeout * 1e3)
@@ -4470,7 +4489,7 @@ class R {
4470
4489
  * @param except if defined, don't delete this key
4471
4490
  */
4472
4491
  async deleteAllForUser(s, e) {
4473
- e && (e = R.hashSessionId(e)), await this.keyStorage.deleteAllForUser(s, b.session, e);
4492
+ e && (e = D.hashSessionId(e)), await this.keyStorage.deleteAllForUser(s, b.session, e);
4474
4493
  }
4475
4494
  }
4476
4495
  class Lt {
@@ -4495,9 +4514,9 @@ class Lt {
4495
4514
  t.userStorage && (this.userStorage = t.userStorage), this.keyStorage = s, this.authenticators = e;
4496
4515
  for (let r in this.authenticators)
4497
4516
  this.authenticators[r].factorName = r;
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)) {
4517
+ 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)) {
4499
4518
  let r = this.keyStorage;
4500
- t.emailTokenStorage && (this.emailTokenStorage = t.emailTokenStorage), this.tokenEmailer = new D(this.userStorage, r, t);
4519
+ t.emailTokenStorage && (this.emailTokenStorage = t.emailTokenStorage), this.tokenEmailer = new R(this.userStorage, r, t);
4501
4520
  }
4502
4521
  }
4503
4522
  /**
@@ -4561,9 +4580,10 @@ class Lt {
4561
4580
  try {
4562
4581
  let T = await this.userStorage.getUserByUsername(s, { skipActiveCheck: !0, skipEmailVerifiedCheck: !0 });
4563
4582
  n = T.secrets, i = T.user, v = T.user;
4564
- } catch {
4565
- for (let k in this.authenticators)
4566
- this.authenticators[k].requireUserEntry() || (v = { username: e.username, state: "active" }, c = k);
4583
+ } catch (T) {
4584
+ if (o.asCrossauthError(T).code == l.Connection) throw T;
4585
+ for (let A in this.authenticators)
4586
+ this.authenticators[A].requireUserEntry() || (v = { username: e.username, state: "active" }, c = A);
4567
4587
  }
4568
4588
  if (v.username == "") throw new o(l.UserNotExist);
4569
4589
  await this.authenticators[(i == null ? void 0 : i.factor1) ?? c].authenticateUser(v, n, e);
@@ -4626,7 +4646,7 @@ class Lt {
4626
4646
  */
4627
4647
  async logout(s) {
4628
4648
  const e = await this.session.getSessionKey(s);
4629
- return await this.keyStorage.deleteKey(R.hashSessionId(e.value));
4649
+ return await this.keyStorage.deleteKey(D.hashSessionId(e.value));
4630
4650
  }
4631
4651
  /**
4632
4652
  * Logs a user out from all sessions.
@@ -4774,7 +4794,7 @@ class Lt {
4774
4794
  * @param value new value to store
4775
4795
  */
4776
4796
  async updateSessionData(s, e, t) {
4777
- const r = R.hashSessionId(s);
4797
+ const r = D.hashSessionId(s);
4778
4798
  u.logger.debug(f({ msg: `Updating session data value ${e}`, hashedSessionCookie: _.hash(s) })), await this.keyStorage.updateData(r, e, t);
4779
4799
  }
4780
4800
  /**
@@ -4786,7 +4806,7 @@ class Lt {
4786
4806
  * @param dataArray names and values.
4787
4807
  */
4788
4808
  async updateManySessionData(s, e) {
4789
- const t = R.hashSessionId(s);
4809
+ const t = D.hashSessionId(s);
4790
4810
  u.logger.debug(f({ msg: "Updating session data", hashedSessionCookie: _.hash(s) })), await this.keyStorage.updateManyData(t, e);
4791
4811
  }
4792
4812
  /**
@@ -4798,7 +4818,7 @@ class Lt {
4798
4818
  * @param name of the field.
4799
4819
  */
4800
4820
  async deleteSessionData(s, e) {
4801
- const t = R.hashSessionId(s);
4821
+ const t = D.hashSessionId(s);
4802
4822
  u.logger.debug(f({ msg: `Updating session data value ${e}`, hashedSessionCookie: _.hash(s) })), await this.keyStorage.deleteData(t, e);
4803
4823
  }
4804
4824
  /**
@@ -4807,7 +4827,7 @@ class Lt {
4807
4827
  * @param sessionId the session Id to delete
4808
4828
  */
4809
4829
  async deleteSession(s) {
4810
- return await this.keyStorage.deleteKey(R.hashSessionId(s));
4830
+ return await this.keyStorage.deleteKey(D.hashSessionId(s));
4811
4831
  }
4812
4832
  /**
4813
4833
  * Creates a new user, sending an email verification message if necessary.
@@ -4838,7 +4858,7 @@ class Lt {
4838
4858
  */
4839
4859
  async deleteUserByUsername(s) {
4840
4860
  if (!this.userStorage) throw new o(l.Configuration, "Cannot call deleteUser if no user storage provided");
4841
- this.userStorage.deleteUserByUsername(s);
4861
+ await this.userStorage.deleteUserByUsername(s);
4842
4862
  }
4843
4863
  /** Creates a user with 2FA enabled.
4844
4864
  *
@@ -4862,7 +4882,7 @@ class Lt {
4862
4882
  if (!this.authenticators[s.factor2]) throw new o(l.Configuration, "Two factor authentication not enabled for user");
4863
4883
  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
4884
  return s.state = "awaitingtwofactorsetup", await this.keyStorage.updateData(
4865
- R.hashSessionId(t),
4885
+ D.hashSessionId(t),
4866
4886
  "2fa",
4867
4887
  c
4868
4888
  ), { userid: (await this.userStorage.createUser(s, d)).id, userData: n };
@@ -4882,13 +4902,13 @@ class Lt {
4882
4902
  if (!this.authenticators[e]) throw new o(l.Configuration, "Two factor authentication not enabled for user");
4883
4903
  const i = await this.authenticators[e].prepareConfiguration(s), a = i == null ? {} : i.userData, n = i == null ? {} : i.sessionData;
4884
4904
  return n && (n.userData = a), await this.keyStorage.updateData(
4885
- R.hashSessionId(t),
4905
+ D.hashSessionId(t),
4886
4906
  "2fa",
4887
4907
  n
4888
4908
  ), a;
4889
4909
  }
4890
4910
  return await this.userStorage.updateUser({ id: s.id, factor2: e ?? "" }), await this.keyStorage.updateData(
4891
- R.hashSessionId(t),
4911
+ D.hashSessionId(t),
4892
4912
  "2fa",
4893
4913
  void 0
4894
4914
  ), {};
@@ -4908,7 +4928,7 @@ class Lt {
4908
4928
  */
4909
4929
  async repeatTwoFactorSignup(s) {
4910
4930
  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 = 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;
4931
+ 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;
4912
4932
  y && await this.keyStorage.updateData(i, "2fa", y);
4913
4933
  const { user: C } = await this.userStorage.getUserByUsername(t, { skipActiveCheck: !0, skipEmailVerifiedCheck: !0 });
4914
4934
  return { userid: C.id, userData: d, secrets: w };
@@ -4948,7 +4968,7 @@ class Lt {
4948
4968
  state: !y && this.enableEmailVerification ? "awaitingemailverification" : "active",
4949
4969
  factor2: a.factor2
4950
4970
  };
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 };
4971
+ 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 };
4952
4972
  }
4953
4973
  /**
4954
4974
  * Initiates the two factor login process.
@@ -4979,7 +4999,7 @@ class Lt {
4979
4999
  async initiateTwoFactorPageVisit(s, e, t, r, i) {
4980
5000
  const n = await this.authenticators[s.factor2].createOneTimeSecrets(s);
4981
5001
  let c, d, w;
4982
- const y = R.hashSessionId(e);
5002
+ const y = D.hashSessionId(e);
4983
5003
  u.logger.debug("initiateTwoFactorPageVisit " + s.username + " " + e + " " + y);
4984
5004
  let C = { username: s.username, factor2: s.factor2, secrets: n, body: t, url: r };
4985
5005
  return i && (C["content-type"] = i), await this.keyStorage.updateData(y, "pre2fa", C), {
@@ -5008,7 +5028,7 @@ class Lt {
5008
5028
  const n = {}, c = a.secretNames();
5009
5029
  for (let d in i)
5010
5030
  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(R.hashSessionId(t.value), "pre2fa", void 0);
5031
+ await a.authenticateUser(void 0, { ...n, ...r.pre2fa.secrets }, s), await this.keyStorage.updateData(D.hashSessionId(t.value), "pre2fa", void 0);
5012
5032
  }
5013
5033
  /**
5014
5034
  * Cancels the 2FA that was previously initiated but not completed..
@@ -5021,10 +5041,10 @@ class Lt {
5021
5041
  */
5022
5042
  async cancelTwoFactorPageVisit(s) {
5023
5043
  let { key: e } = await this.session.getUserForSessionId(s);
5024
- if (!e) throw new o(l.InvalidKey, "Session key not found");
5044
+ if (!e) throw new o(l.InvalidSession, "Session key not found");
5025
5045
  let t = z.decodeData(e.data);
5026
5046
  if (!("pre2fa" in t)) throw new o(l.Unauthorized, "Two factor authentication not initiated");
5027
- return await this.keyStorage.updateData(R.hashSessionId(e.value), "pre2fa", void 0), t.pre2fa;
5047
+ return await this.keyStorage.updateData(D.hashSessionId(e.value), "pre2fa", void 0), t.pre2fa;
5028
5048
  }
5029
5049
  /**
5030
5050
  * Performs the second factor authentication as the second step of the login
@@ -5052,15 +5072,15 @@ class Lt {
5052
5072
  if (!y) throw new o(l.Configuration, "Second factor " + c + " not enabled");
5053
5073
  await y.authenticateUser(d, { ...w, ...a }, s);
5054
5074
  const C = await this.session.createSessionKey(d.id, t);
5055
- await this.keyStorage.deleteKey(R.hashSessionId(i.value));
5075
+ await this.keyStorage.deleteKey(D.hashSessionId(i.value));
5056
5076
  const v = this.session.makeCookie(C, r), p = this.csrfTokens.createCsrfToken(), T = this.csrfTokens.makeCsrfCookie(p), k = this.csrfTokens.makeCsrfFormOrHeaderToken(p);
5057
5077
  try {
5058
5078
  this.emailTokenStorage.deleteAllForUser(
5059
5079
  d.id,
5060
5080
  b.passwordResetToken
5061
5081
  );
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 }));
5082
+ } catch (A) {
5083
+ u.logger.warn(f({ msg: "Couldn't delete password reset tokens while logging in", user: n })), u.logger.debug(f({ err: A }));
5064
5084
  }
5065
5085
  return {
5066
5086
  sessionCookie: v,
@@ -5126,7 +5146,7 @@ class Lt {
5126
5146
  d
5127
5147
  );
5128
5148
  try {
5129
- this.emailTokenStorage.deleteAllForUser(
5149
+ await this.emailTokenStorage.deleteAllForUser(
5130
5150
  a.id,
5131
5151
  b.passwordResetToken
5132
5152
  );
@@ -5150,17 +5170,17 @@ class Lt {
5150
5170
  if (!("username" in s) || s.username == null)
5151
5171
  throw new o(l.UserNotExist, "Please specify a userername");
5152
5172
  let { email: a, username: n, password: c, ...d } = e;
5153
- d.userid = s.userid;
5173
+ d.userid = s.userid, d.id = s.id;
5154
5174
  let w = !1;
5155
5175
  if (a)
5156
- i = a, D.validateEmail(i), w = !0;
5176
+ i = a, R.validateEmail(i), w = !0;
5157
5177
  else if (n) {
5158
5178
  i = n;
5159
5179
  try {
5160
- D.validateEmail(s.username), w = !0;
5180
+ R.validateEmail(s.username), w = !0;
5161
5181
  } catch {
5162
5182
  }
5163
- w && D.validateEmail(i);
5183
+ w && R.validateEmail(i);
5164
5184
  }
5165
5185
  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
5186
  emailVerificationTokenSent: !t && this.enableEmailVerification && w,
@@ -5975,7 +5995,7 @@ class Ht {
5975
5995
  };
5976
5996
  const k = await this.getClientById(e);
5977
5997
  if (!k.client) return k;
5978
- const P = k.client, H = await this.authenticateClient(T, P, i);
5998
+ const A = k.client, H = await this.authenticateClient(T, A, i);
5979
5999
  if (H.error) return H;
5980
6000
  if (T == U.Password && !this.validFlows.includes(T) && !this.validFlows.includes(U.PasswordMfa))
5981
6001
  return {
@@ -5987,7 +6007,7 @@ class Ht {
5987
6007
  error: "access_denied",
5988
6008
  error_description: "Unsupported flow type " + T
5989
6009
  };
5990
- if (P && !P.valid_flow.includes(T))
6010
+ if (A && !A.valid_flow.includes(T))
5991
6011
  return {
5992
6012
  error: "unauthorized_client",
5993
6013
  error_description: "Client does not support " + T
@@ -5996,14 +6016,14 @@ class Ht {
5996
6016
  this.issueRefreshToken && T != U.RefreshToken && (j = !0), this.issueRefreshToken && T == U.RefreshToken && this.rollingRefreshToken && (j = !0);
5997
6017
  let O;
5998
6018
  if (s == "authorization_code")
5999
- return this.requireClientSecretOrChallenge && P && P.client_secret && !i && !a ? {
6019
+ return this.requireClientSecretOrChallenge && A && A.client_secret && !i && !a ? {
6000
6020
  error: "access_denied",
6001
6021
  error_description: "Must provide either a client secret or use PKCE"
6002
- } : P && P.client_secret && !i ? {
6022
+ } : A && A.client_secret && !i ? {
6003
6023
  error: "access_denied",
6004
6024
  error_description: "No client secret or code verifier provided for authorization coode flow"
6005
6025
  } : r ? await this.makeAccessToken({
6006
- client: P,
6026
+ client: A,
6007
6027
  code: r,
6008
6028
  client_secret: i,
6009
6029
  codeVerifier: a,
@@ -6019,26 +6039,26 @@ class Ht {
6019
6039
  error: "invalid_request",
6020
6040
  error_description: "If executing the refresh token flow, must provide a refresh token"
6021
6041
  };
6022
- let A = await this.upstreamClient.refreshTokenFlow(n);
6023
- if (!A.access_token)
6042
+ let I = await this.upstreamClient.refreshTokenFlow(n);
6043
+ if (!I.access_token)
6024
6044
  return {
6025
6045
  error: "access_denied",
6026
6046
  error_description: "Didn't receive an access token"
6027
6047
  };
6028
- let I = A.access_token;
6029
- if (this.upstreamClientOptions.accessTokenIsJwt && (I = await this.upstreamClient.validateAccessToken(A.access_token, !1), !I))
6048
+ let P = I.access_token;
6049
+ if (this.upstreamClientOptions.accessTokenIsJwt && (P = await this.upstreamClient.validateAccessToken(I.access_token, !1), !P))
6030
6050
  return {
6031
6051
  error: "access_denied",
6032
6052
  error_description: "Couldn't decode access token"
6033
6053
  };
6034
- const x = await this.upstreamClientOptions.tokenMergeFn(I, A.id_payload, this.userStorage);
6054
+ const x = await this.upstreamClientOptions.tokenMergeFn(P, I.id_payload, this.userStorage);
6035
6055
  if (x.authorized) {
6036
6056
  const B = await this.createTokensFromPayload(
6037
6057
  e,
6038
6058
  x.access_payload,
6039
6059
  x.id_payload
6040
6060
  );
6041
- return A.access_token = B.access_token, A.id_token = B.id_token, A.id_payload = B.id_payload, A;
6061
+ return I.access_token = B.access_token, I.id_token = B.id_token, I.id_payload = B.id_payload, I;
6042
6062
  } else
6043
6063
  return u.logger.warn(f({ msg: x.error_description })), {
6044
6064
  error: x.error,
@@ -6054,11 +6074,11 @@ class Ht {
6054
6074
  let K;
6055
6075
  if (N.username)
6056
6076
  try {
6057
- const { user: A } = await ((F = this.userStorage) == null ? void 0 : F.getUserByUsername(N.username));
6058
- K = A;
6059
- } catch (A) {
6077
+ const { user: I } = await ((F = this.userStorage) == null ? void 0 : F.getUserByUsername(N.username));
6078
+ K = I;
6079
+ } catch (I) {
6060
6080
  return u.logger.error(f({
6061
- err: A,
6081
+ err: I,
6062
6082
  msg: "Couldn't get user for refresh token. Doesn't exist?",
6063
6083
  username: N.username
6064
6084
  })), {
@@ -6067,14 +6087,14 @@ class Ht {
6067
6087
  };
6068
6088
  }
6069
6089
  try {
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 }));
6090
+ const I = b.refreshToken + _.hash(n);
6091
+ await this.keyStorage.deleteKey(I);
6092
+ } catch (I) {
6093
+ const P = o.asCrossauthError(I);
6094
+ u.logger.debug(f({ err: I })), u.logger.warn(f({ msg: "Cannot delete refresh token", cerr: P }));
6075
6095
  }
6076
6096
  return await this.makeAccessToken({
6077
- client: P,
6097
+ client: A,
6078
6098
  client_secret: i,
6079
6099
  codeVerifier: a,
6080
6100
  issueRefreshToken: j,
@@ -6085,13 +6105,13 @@ class Ht {
6085
6105
  const {
6086
6106
  scopes: N,
6087
6107
  error: K,
6088
- error_description: A
6108
+ error_description: I
6089
6109
  } = await this.validateAndPersistScope(e, t, void 0);
6090
6110
  return K ? {
6091
6111
  error: K,
6092
- error_description: A
6112
+ error_description: I
6093
6113
  } : await this.makeAccessToken({
6094
- client: P,
6114
+ client: A,
6095
6115
  client_secret: i,
6096
6116
  codeVerifier: a,
6097
6117
  scopes: N,
@@ -6109,19 +6129,19 @@ class Ht {
6109
6129
  error: "server_error",
6110
6130
  error_description: "Password authentication not configured"
6111
6131
  };
6112
- const { user: I, secrets: x } = await this.userStorage.getUserByUsername(c), B = this.authenticators[I.factor1];
6132
+ const { user: P, secrets: x } = await this.userStorage.getUserByUsername(c), B = this.authenticators[P.factor1];
6113
6133
  if (!B || !B.secretNames().includes("password"))
6114
6134
  return {
6115
6135
  error: "access_denied",
6116
6136
  error_description: "Password flow used but factor 1 authenticator does not accept passwords"
6117
6137
  };
6118
6138
  await B.authenticateUser(
6119
- I,
6139
+ P,
6120
6140
  x,
6121
6141
  { password: d }
6122
- ), O = I;
6123
- } catch (I) {
6124
- return u.logger.debug(f({ err: I })), {
6142
+ ), O = P;
6143
+ } catch (P) {
6144
+ return u.logger.debug(f({ err: P })), {
6125
6145
  error: "access_denied",
6126
6146
  error_description: "Username and/or password do not match"
6127
6147
  };
@@ -6129,16 +6149,16 @@ class Ht {
6129
6149
  const {
6130
6150
  scopes: N,
6131
6151
  error: K,
6132
- error_description: A
6152
+ error_description: I
6133
6153
  } = await this.validateAndPersistScope(e, t, O);
6134
6154
  return K ? {
6135
6155
  error: K,
6136
- error_description: A
6156
+ error_description: I
6137
6157
  } : O.factor2 ? this.allowedFactor2.length > 0 && (O.state == E.factor2ResetNeeded || !this.allowedFactor2.includes(O.factor2 ? O.factor2 : "none")) ? {
6138
6158
  error: "access_denied",
6139
6159
  error_description: "2FA method not allowed or needs to be reconfigured"
6140
6160
  } : await this.createMfaRequest(O) : await this.makeAccessToken({
6141
- client: P,
6161
+ client: A,
6142
6162
  client_secret: i,
6143
6163
  codeVerifier: a,
6144
6164
  scopes: N,
@@ -6149,12 +6169,12 @@ class Ht {
6149
6169
  const {
6150
6170
  scopes: N,
6151
6171
  error: K,
6152
- error_description: A
6172
+ error_description: I
6153
6173
  } = await this.validateAndPersistScope(e, t, void 0);
6154
6174
  if (K)
6155
6175
  return {
6156
6176
  error: K,
6157
- error_description: A
6177
+ error_description: I
6158
6178
  };
6159
6179
  if (!v)
6160
6180
  return {
@@ -6166,22 +6186,22 @@ class Ht {
6166
6186
  error: "access_denied",
6167
6187
  error_description: "MFA token not provided"
6168
6188
  };
6169
- const I = await this.validateMfaToken(w), x = b.mfaToken + _.hash(w);
6170
- if (!I.user || !I.key)
6189
+ const P = await this.validateMfaToken(w), x = b.mfaToken + _.hash(w);
6190
+ if (!P.user || !P.key)
6171
6191
  return {
6172
6192
  error: "access_denied",
6173
6193
  error_description: "Invalid MFA token"
6174
6194
  };
6175
- const B = this.authenticators[I.user.factor2];
6195
+ const B = this.authenticators[P.user.factor2];
6176
6196
  if (!B || !this.userStorage)
6177
6197
  return {
6178
6198
  error: "access_denied",
6179
6199
  error_description: "MFA type is not supported for OAuth"
6180
6200
  };
6181
6201
  try {
6182
- const { secrets: V } = await this.userStorage.getUserById(I.user.id);
6202
+ const { secrets: V } = await this.userStorage.getUserById(P.user.id);
6183
6203
  await B.authenticateUser(
6184
- I.user,
6204
+ P.user,
6185
6205
  V,
6186
6206
  { otp: v }
6187
6207
  );
@@ -6197,27 +6217,27 @@ class Ht {
6197
6217
  u.logger.debug(f({ err: V })), u.logger.warn(f({
6198
6218
  cerr: V,
6199
6219
  msg: "Couldn't delete mfa token",
6200
- hashedMfaToken: I.key.value
6220
+ hashedMfaToken: P.key.value
6201
6221
  }));
6202
6222
  }
6203
6223
  return await this.makeAccessToken({
6204
- client: P,
6224
+ client: A,
6205
6225
  client_secret: i,
6206
6226
  codeVerifier: a,
6207
6227
  scopes: N,
6208
6228
  issueRefreshToken: j,
6209
- user: I.user
6229
+ user: P.user
6210
6230
  });
6211
6231
  } else if (s == "http://auth0.com/oauth/grant-type/mfa-oob") {
6212
6232
  const {
6213
6233
  scopes: N,
6214
6234
  error: K,
6215
- error_description: A
6235
+ error_description: I
6216
6236
  } = await this.validateAndPersistScope(e, t, void 0);
6217
6237
  if (K)
6218
6238
  return {
6219
6239
  error: K,
6220
- error_description: A
6240
+ error_description: I
6221
6241
  };
6222
6242
  if (!y || !C)
6223
6243
  return {
@@ -6229,20 +6249,20 @@ class Ht {
6229
6249
  error: "access_denied",
6230
6250
  error_description: "MFA token not provided"
6231
6251
  };
6232
- const I = await this.validateMfaToken(w);
6233
- if (!I.user || !I.key)
6252
+ const P = await this.validateMfaToken(w);
6253
+ if (!P.user || !P.key)
6234
6254
  return {
6235
6255
  error: "access_denied",
6236
6256
  error_description: "Invalid MFA token"
6237
6257
  };
6238
- const x = this.authenticators[I.user.factor2];
6258
+ const x = this.authenticators[P.user.factor2];
6239
6259
  if (!x || !this.userStorage)
6240
6260
  return {
6241
6261
  error: "access_denied",
6242
6262
  error_description: "MFA type is not supported for OAuth"
6243
6263
  };
6244
6264
  try {
6245
- const { secrets: B } = await this.userStorage.getUserById(I.user.id), V = z.decodeData(I.key.data).omfa;
6265
+ const { secrets: B } = await this.userStorage.getUserById(P.user.id), V = z.decodeData(P.key.data).omfa;
6246
6266
  if (!V || !V.otp || !V.oobCode)
6247
6267
  return {
6248
6268
  error: "server_error",
@@ -6254,8 +6274,8 @@ class Ht {
6254
6274
  error_description: "Invalid OOB code"
6255
6275
  };
6256
6276
  await x.authenticateUser(
6257
- I.user,
6258
- { ...B, otp: V.otp, expiry: ($ = I.key.expires) == null ? void 0 : $.getTime() },
6277
+ P.user,
6278
+ { ...B, otp: V.otp, expiry: ($ = P.key.expires) == null ? void 0 : $.getTime() },
6259
6279
  { otp: C }
6260
6280
  );
6261
6281
  } catch (B) {
@@ -6265,21 +6285,21 @@ class Ht {
6265
6285
  };
6266
6286
  }
6267
6287
  try {
6268
- await this.keyStorage.deleteKey(I.key.value);
6288
+ await this.keyStorage.deleteKey(P.key.value);
6269
6289
  } catch (B) {
6270
6290
  u.logger.debug(f({ err: B })), u.logger.warn(f({
6271
6291
  cerr: B,
6272
6292
  msg: "Couldn't delete mfa token",
6273
- hashedMfaToken: I.key.value
6293
+ hashedMfaToken: P.key.value
6274
6294
  }));
6275
6295
  }
6276
6296
  return await this.makeAccessToken({
6277
- client: P,
6297
+ client: A,
6278
6298
  client_secret: i,
6279
6299
  codeVerifier: a,
6280
6300
  scopes: N,
6281
6301
  issueRefreshToken: j,
6282
- user: I.user
6302
+ user: P.user
6283
6303
  });
6284
6304
  } else if (s == "urn:ietf:params:oauth:grant-type:device_code") {
6285
6305
  if (!p)
@@ -6291,15 +6311,15 @@ class Ht {
6291
6311
  try {
6292
6312
  N = await this.keyStorage.getKey(b.deviceCode + p);
6293
6313
  } 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 })), {
6314
+ const I = o.asCrossauthError(K);
6315
+ return u.logger.debug(f({ err: I })), u.logger.error(f({ msg: "Couldn't get device code", cerr: I })), {
6296
6316
  error: "accerss_denied",
6297
6317
  error_description: "Invalid device code"
6298
6318
  };
6299
6319
  }
6300
6320
  try {
6301
- const K = JSON.parse(N.data ?? "{}"), A = (/* @__PURE__ */ new Date()).getTime();
6302
- if (N.expires && A > N.expires.getTime())
6321
+ const K = JSON.parse(N.data ?? "{}"), I = (/* @__PURE__ */ new Date()).getTime();
6322
+ if (N.expires && I > N.expires.getTime())
6303
6323
  return await this.deleteDeviceCode(p), {
6304
6324
  error: "expired_token",
6305
6325
  error_description: "Code has expired"
@@ -6310,19 +6330,19 @@ class Ht {
6310
6330
  error_description: "Waiting for user code to be entered"
6311
6331
  };
6312
6332
  {
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;
6333
+ let P = K.scope ? K.scope.split(" ") : void 0, x = K.userid ? await ((M = this.userStorage) == null ? void 0 : M.getUserById(K.userid)) : void 0;
6314
6334
  return await this.deleteDeviceCode(p), await this.makeAccessToken({
6315
- client: P,
6335
+ client: A,
6316
6336
  client_secret: i,
6317
6337
  codeVerifier: a,
6318
- scopes: I,
6338
+ scopes: P,
6319
6339
  issueRefreshToken: j,
6320
6340
  user: x == null ? void 0 : x.user
6321
6341
  });
6322
6342
  }
6323
6343
  } 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), {
6344
+ const I = o.asCrossauthError(K);
6345
+ return u.logger.debug(f({ err: I })), u.logger.error(f({ msg: "Couldn't get device code", cerr: I })), await this.deleteDeviceCode(p), {
6326
6346
  error: "accerss_denied",
6327
6347
  error_description: "Invalid device code"
6328
6348
  };
@@ -7038,7 +7058,7 @@ class Ht {
7038
7058
  );
7039
7059
  });
7040
7060
  }
7041
- let P;
7061
+ let A;
7042
7062
  if (a) {
7043
7063
  const O = {
7044
7064
  username: d.username,
@@ -7053,22 +7073,22 @@ class Ht {
7053
7073
  sub: d.username,
7054
7074
  type: "refresh"
7055
7075
  };
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) => {
7076
+ 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), A = await new Promise((N, K) => {
7057
7077
  ee.sign(
7058
7078
  M,
7059
7079
  this.secretOrPrivateKey,
7060
7080
  { algorithm: this.jwtAlgorithmChecked, keyid: "1" },
7061
- (A, I) => {
7062
- I ? N(I) : K(A || new o(
7081
+ (I, P) => {
7082
+ P ? N(P) : K(I || new o(
7063
7083
  l.Unauthorized,
7064
7084
  "Couldn't create jwt"
7065
7085
  ));
7066
7086
  }
7067
7087
  );
7068
- }), P && await ((j = this.keyStorage) == null ? void 0 : j.saveKey(
7088
+ }), A && await ((j = this.keyStorage) == null ? void 0 : j.saveKey(
7069
7089
  void 0,
7070
7090
  // to avoid user storage dependency
7071
- b.refreshToken + _.hash(P),
7091
+ b.refreshToken + _.hash(A),
7072
7092
  w,
7073
7093
  F,
7074
7094
  JSON.stringify(O)
@@ -7077,7 +7097,7 @@ class Ht {
7077
7097
  return {
7078
7098
  access_token: T,
7079
7099
  id_token: k,
7080
- refresh_token: P,
7100
+ refresh_token: A,
7081
7101
  expires_in: this.accessTokenExpiry == null ? void 0 : this.accessTokenExpiry,
7082
7102
  token_type: "Bearer",
7083
7103
  scope: i ? i.join(" ") : void 0
@@ -7499,7 +7519,7 @@ export {
7499
7519
  ie as Authenticator,
7500
7520
  _ as Crypto,
7501
7521
  rt as DoubleSubmitCsrfToken,
7502
- Rt as DummyFactor2Authenticator,
7522
+ Dt as DummyFactor2Authenticator,
7503
7523
  Z as EmailAuthenticator,
7504
7524
  It as InMemoryKeyStorage,
7505
7525
  Kt as InMemoryOAuthAuthorizationStorage,
@@ -7519,17 +7539,17 @@ export {
7519
7539
  g as ParamType,
7520
7540
  be as PasswordAuthenticator,
7521
7541
  Ft as PostgresKeyStorage,
7522
- Dt as PostgresOAuthAuthorizationStorage,
7542
+ Rt as PostgresOAuthAuthorizationStorage,
7523
7543
  Nt as PostgresOAuthClientStorage,
7524
7544
  Ot as PostgresUserStorage,
7525
7545
  Et as PrismaKeyStorage,
7526
7546
  Ut as PrismaOAuthAuthorizationStorage,
7527
7547
  bt as PrismaOAuthClientStorage,
7528
7548
  G as PrismaUserStorage,
7529
- R as SessionCookie,
7549
+ D as SessionCookie,
7530
7550
  Lt as SessionManager,
7531
7551
  Q as SmsAuthenticator,
7532
- D as TokenEmailer,
7552
+ R as TokenEmailer,
7533
7553
  Bt as TotpAuthenticator,
7534
7554
  Ue as TwilioAuthenticator,
7535
7555
  L as UserStorage,