@xk2800/nextjs-template 0.7.1-beta.14 → 0.7.1-beta.16

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.
@@ -14,8 +14,9 @@ var pg = require('pg');
14
14
  var pgCore = require('drizzle-orm/pg-core');
15
15
  var zod = require('zod');
16
16
  var plugins = require('better-auth/plugins');
17
- var passkey = require('@better-auth/passkey');
18
17
  var api = require('better-auth/api');
18
+ var crypto = require('better-auth/crypto');
19
+ var passkey = require('@better-auth/passkey');
19
20
  var uaParserJs = require('ua-parser-js');
20
21
  var geoip = require('geoip-lite');
21
22
 
@@ -506,6 +507,410 @@ if (config.DB_DRIVER === "pg") {
506
507
  } else {
507
508
  console.log("Database connection not established, unknown DB_DRIVER:", config.DB_DRIVER);
508
509
  }
510
+
511
+ // node_modules/@better-auth/utils/dist/base32.mjs
512
+ function getAlphabet(hex2) {
513
+ return "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
514
+ }
515
+ function createDecodeMap(alphabet) {
516
+ const decodeMap = /* @__PURE__ */ new Map();
517
+ for (let i = 0; i < alphabet.length; i++) {
518
+ decodeMap.set(alphabet[i], i);
519
+ }
520
+ return decodeMap;
521
+ }
522
+ function base32Encode(data, alphabet, padding) {
523
+ let result = "";
524
+ let buffer = 0;
525
+ let shift = 0;
526
+ for (const byte of data) {
527
+ buffer = buffer << 8 | byte;
528
+ shift += 8;
529
+ while (shift >= 5) {
530
+ shift -= 5;
531
+ result += alphabet[buffer >> shift & 31];
532
+ }
533
+ }
534
+ if (shift > 0) {
535
+ result += alphabet[buffer << 5 - shift & 31];
536
+ }
537
+ if (padding) {
538
+ const padCount = (8 - result.length % 8) % 8;
539
+ result += "=".repeat(padCount);
540
+ }
541
+ return result;
542
+ }
543
+ function base32Decode(data, alphabet) {
544
+ const decodeMap = createDecodeMap(alphabet);
545
+ const result = [];
546
+ let buffer = 0;
547
+ let bitsCollected = 0;
548
+ for (const char of data) {
549
+ if (char === "=")
550
+ break;
551
+ const value = decodeMap.get(char);
552
+ if (value === void 0) {
553
+ throw new Error(`Invalid Base32 character: ${char}`);
554
+ }
555
+ buffer = buffer << 5 | value;
556
+ bitsCollected += 5;
557
+ while (bitsCollected >= 8) {
558
+ bitsCollected -= 8;
559
+ result.push(buffer >> bitsCollected & 255);
560
+ }
561
+ }
562
+ return Uint8Array.from(result);
563
+ }
564
+ var base32 = {
565
+ /**
566
+ * Encodes data into a Base32 string.
567
+ * @param data - The data to encode (ArrayBuffer, TypedArray, or string).
568
+ * @param options - Encoding options.
569
+ * @returns The Base32 encoded string.
570
+ */
571
+ encode(data, options = {}) {
572
+ var _a;
573
+ const alphabet = getAlphabet();
574
+ const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
575
+ return base32Encode(buffer, alphabet, (_a = options.padding) != null ? _a : true);
576
+ },
577
+ /**
578
+ * Decodes a Base32 string into a Uint8Array.
579
+ * @param data - The Base32 encoded string or ArrayBuffer/TypedArray.
580
+ * @returns The decoded Uint8Array.
581
+ */
582
+ decode(data) {
583
+ if (typeof data !== "string") {
584
+ data = new TextDecoder().decode(data);
585
+ }
586
+ const alphabet = getAlphabet();
587
+ return base32Decode(data, alphabet);
588
+ }
589
+ };
590
+
591
+ // node_modules/@better-auth/utils/dist/hex.mjs
592
+ var hexadecimal = "0123456789abcdef";
593
+ var hex = {
594
+ encode: (data) => {
595
+ if (typeof data === "string") {
596
+ data = new TextEncoder().encode(data);
597
+ }
598
+ if (data.byteLength === 0) {
599
+ return "";
600
+ }
601
+ const buffer = new Uint8Array(data);
602
+ let result = "";
603
+ for (const byte of buffer) {
604
+ result += byte.toString(16).padStart(2, "0");
605
+ }
606
+ return result;
607
+ },
608
+ decode: (data) => {
609
+ if (!data) {
610
+ return "";
611
+ }
612
+ if (typeof data === "string") {
613
+ if (data.length % 2 !== 0) {
614
+ throw new Error("Invalid hexadecimal string");
615
+ }
616
+ if (!new RegExp(`^[${hexadecimal}]+$`).test(data)) {
617
+ throw new Error("Invalid hexadecimal string");
618
+ }
619
+ const result = new Uint8Array(data.length / 2);
620
+ for (let i = 0; i < data.length; i += 2) {
621
+ result[i / 2] = parseInt(data.slice(i, i + 2), 16);
622
+ }
623
+ return new TextDecoder().decode(result);
624
+ }
625
+ return new TextDecoder().decode(data);
626
+ }
627
+ };
628
+
629
+ // node_modules/@better-auth/utils/dist/base64.mjs
630
+ function getAlphabet2(urlSafe) {
631
+ return urlSafe ? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
632
+ }
633
+ function base64Encode(data, alphabet, padding) {
634
+ let result = "";
635
+ let buffer = 0;
636
+ let shift = 0;
637
+ for (const byte of data) {
638
+ buffer = buffer << 8 | byte;
639
+ shift += 8;
640
+ while (shift >= 6) {
641
+ shift -= 6;
642
+ result += alphabet[buffer >> shift & 63];
643
+ }
644
+ }
645
+ if (shift > 0) {
646
+ result += alphabet[buffer << 6 - shift & 63];
647
+ }
648
+ if (padding) {
649
+ const padCount = (4 - result.length % 4) % 4;
650
+ result += "=".repeat(padCount);
651
+ }
652
+ return result;
653
+ }
654
+ function base64Decode(data, alphabet) {
655
+ const decodeMap = /* @__PURE__ */ new Map();
656
+ for (let i = 0; i < alphabet.length; i++) {
657
+ decodeMap.set(alphabet[i], i);
658
+ }
659
+ const result = [];
660
+ let buffer = 0;
661
+ let bitsCollected = 0;
662
+ for (const char of data) {
663
+ if (char === "=")
664
+ break;
665
+ const value = decodeMap.get(char);
666
+ if (value === void 0) {
667
+ throw new Error(`Invalid Base64 character: ${char}`);
668
+ }
669
+ buffer = buffer << 6 | value;
670
+ bitsCollected += 6;
671
+ if (bitsCollected >= 8) {
672
+ bitsCollected -= 8;
673
+ result.push(buffer >> bitsCollected & 255);
674
+ }
675
+ }
676
+ return Uint8Array.from(result);
677
+ }
678
+ var base64 = {
679
+ encode(data, options = {}) {
680
+ var _a;
681
+ const alphabet = getAlphabet2(false);
682
+ const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
683
+ return base64Encode(buffer, alphabet, (_a = options.padding) != null ? _a : true);
684
+ },
685
+ decode(data) {
686
+ if (typeof data !== "string") {
687
+ data = new TextDecoder().decode(data);
688
+ }
689
+ const urlSafe = data.includes("-") || data.includes("_");
690
+ const alphabet = getAlphabet2(urlSafe);
691
+ return base64Decode(data, alphabet);
692
+ }
693
+ };
694
+ var base64Url = {
695
+ encode(data, options = {}) {
696
+ var _a;
697
+ const alphabet = getAlphabet2(true);
698
+ const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
699
+ return base64Encode(buffer, alphabet, (_a = options.padding) != null ? _a : true);
700
+ },
701
+ decode(data) {
702
+ const urlSafe = data.includes("-") || data.includes("_");
703
+ const alphabet = getAlphabet2(urlSafe);
704
+ return base64Decode(data, alphabet);
705
+ }
706
+ };
707
+
708
+ // node_modules/@better-auth/utils/dist/index.mjs
709
+ function getWebcryptoSubtle() {
710
+ const cr = typeof globalThis !== "undefined" && globalThis.crypto;
711
+ if (cr && typeof cr.subtle === "object" && cr.subtle != null)
712
+ return cr.subtle;
713
+ throw new Error("crypto.subtle must be defined");
714
+ }
715
+
716
+ // node_modules/@better-auth/utils/dist/hmac.mjs
717
+ var createHMAC = (algorithm = "SHA-256", encoding = "none") => {
718
+ const hmac = {
719
+ importKey: async (key, keyUsage) => {
720
+ return getWebcryptoSubtle().importKey(
721
+ "raw",
722
+ typeof key === "string" ? new TextEncoder().encode(key) : key,
723
+ { name: "HMAC", hash: { name: algorithm } },
724
+ false,
725
+ [keyUsage]
726
+ );
727
+ },
728
+ sign: async (hmacKey, data) => {
729
+ if (typeof hmacKey === "string") {
730
+ hmacKey = await hmac.importKey(hmacKey, "sign");
731
+ }
732
+ const signature = await getWebcryptoSubtle().sign(
733
+ "HMAC",
734
+ hmacKey,
735
+ typeof data === "string" ? new TextEncoder().encode(data) : data
736
+ );
737
+ if (encoding === "hex") {
738
+ return hex.encode(signature);
739
+ }
740
+ if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") {
741
+ return base64Url.encode(signature, {
742
+ padding: encoding !== "base64urlnopad"
743
+ });
744
+ }
745
+ return signature;
746
+ },
747
+ verify: async (hmacKey, data, signature) => {
748
+ if (typeof hmacKey === "string") {
749
+ hmacKey = await hmac.importKey(hmacKey, "verify");
750
+ }
751
+ if (encoding === "hex") {
752
+ signature = hex.decode(signature);
753
+ }
754
+ if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") {
755
+ signature = await base64.decode(signature);
756
+ }
757
+ return getWebcryptoSubtle().verify(
758
+ "HMAC",
759
+ hmacKey,
760
+ typeof signature === "string" ? new TextEncoder().encode(signature) : signature,
761
+ typeof data === "string" ? new TextEncoder().encode(data) : data
762
+ );
763
+ }
764
+ };
765
+ return hmac;
766
+ };
767
+
768
+ // node_modules/@better-auth/utils/dist/otp.mjs
769
+ var defaultPeriod = 30;
770
+ var defaultDigits = 6;
771
+ function constantTimeEqualOTP(input, expected) {
772
+ let difference = input.length ^ expected.length;
773
+ for (let i = 0; i < expected.length; i++) {
774
+ difference |= input.charCodeAt(i) ^ expected.charCodeAt(i);
775
+ }
776
+ return difference === 0;
777
+ }
778
+ async function generateHOTP(secret, {
779
+ counter,
780
+ digits,
781
+ hash = "SHA-1"
782
+ }) {
783
+ const _digits = digits != null ? digits : defaultDigits;
784
+ if (_digits < 1 || _digits > 8) {
785
+ throw new TypeError("Digits must be between 1 and 8");
786
+ }
787
+ const buffer = new ArrayBuffer(8);
788
+ new DataView(buffer).setBigUint64(0, BigInt(counter), false);
789
+ const bytes = new Uint8Array(buffer);
790
+ const hmacResult = new Uint8Array(await createHMAC(hash).sign(secret, bytes));
791
+ const offset = hmacResult[hmacResult.length - 1] & 15;
792
+ const truncated = (hmacResult[offset] & 127) << 24 | (hmacResult[offset + 1] & 255) << 16 | (hmacResult[offset + 2] & 255) << 8 | hmacResult[offset + 3] & 255;
793
+ const otp = truncated % 10 ** _digits;
794
+ return otp.toString().padStart(_digits, "0");
795
+ }
796
+ async function generateTOTP(secret, options) {
797
+ var _a, _b;
798
+ const digits = (_a = options == null ? void 0 : options.digits) != null ? _a : defaultDigits;
799
+ const period = (_b = options == null ? void 0 : options.period) != null ? _b : defaultPeriod;
800
+ const milliseconds = period * 1e3;
801
+ const counter = Math.floor(Date.now() / milliseconds);
802
+ return await generateHOTP(secret, { counter, digits, hash: options == null ? void 0 : options.hash });
803
+ }
804
+ async function verifyTOTP(otp, {
805
+ window = 1,
806
+ digits = defaultDigits,
807
+ secret,
808
+ period = defaultPeriod
809
+ }) {
810
+ const milliseconds = period * 1e3;
811
+ const counter = Math.floor(Date.now() / milliseconds);
812
+ let matched = false;
813
+ for (let i = -window; i <= window; i++) {
814
+ const generatedOTP = await generateHOTP(secret, {
815
+ counter: counter + i,
816
+ digits
817
+ });
818
+ matched = constantTimeEqualOTP(otp, generatedOTP) || matched;
819
+ }
820
+ return matched;
821
+ }
822
+ function generateQRCode({
823
+ issuer,
824
+ account,
825
+ secret,
826
+ digits = defaultDigits,
827
+ period = defaultPeriod
828
+ }) {
829
+ const encodedIssuer = encodeURIComponent(issuer);
830
+ const encodedAccountName = encodeURIComponent(account);
831
+ const baseURI = `otpauth://totp/${encodedIssuer}:${encodedAccountName}`;
832
+ const params = new URLSearchParams({
833
+ secret: base32.encode(secret, {
834
+ padding: false
835
+ }),
836
+ issuer
837
+ });
838
+ if (digits !== void 0) {
839
+ params.set("digits", digits.toString());
840
+ }
841
+ if (period !== void 0) {
842
+ params.set("period", period.toString());
843
+ }
844
+ return `${baseURI}?${params.toString()}`;
845
+ }
846
+ var createOTP = (secret, opts) => {
847
+ var _a, _b;
848
+ const digits = (_a = void 0 ) != null ? _a : defaultDigits;
849
+ const period = (_b = void 0 ) != null ? _b : defaultPeriod;
850
+ return {
851
+ hotp: (counter) => generateHOTP(secret, { counter, digits }),
852
+ totp: () => generateTOTP(secret, { digits, period }),
853
+ verify: (otp, options) => verifyTOTP(otp, __spreadValues({ secret, digits, period }, options)),
854
+ url: (issuer, account) => generateQRCode({ issuer, account, secret, digits, period })
855
+ };
856
+ };
857
+
858
+ // lib/two-factor.ts
859
+ var CHALLENGED_PATHS = ["/callback/:id", "/one-tap/callback"];
860
+ var CODE_REQUIRED_PATHS = ["/two-factor/disable", "/two-factor/generate-backup-codes"];
861
+ function twoFactorPlugins(baseURL, { issuer, passwordless = false, challengeAfterOAuth = false }) {
862
+ const plugin = plugins.twoFactor({ issuer, allowPasswordless: passwordless });
863
+ if (challengeAfterOAuth) {
864
+ const [challenge] = plugin.hooks.after;
865
+ plugin.hooks.after = [__spreadProps(__spreadValues({}, challenge), {
866
+ matcher: (ctx) => {
867
+ var _a;
868
+ return challenge.matcher(ctx) || CHALLENGED_PATHS.includes((_a = ctx.path) != null ? _a : "");
869
+ }
870
+ })];
871
+ }
872
+ const extras = {
873
+ id: "two-factor-extras",
874
+ hooks: {
875
+ // allowPasswordless lets disable / regenerate-backup-codes run on a session alone,
876
+ // so anyone at an unlocked, signed-in browser could switch 2FA off. Require a
877
+ // current authenticator code instead of the password the user doesn't have.
878
+ before: passwordless ? [{
879
+ matcher: (ctx) => {
880
+ var _a;
881
+ return CODE_REQUIRED_PATHS.includes((_a = ctx.path) != null ? _a : "");
882
+ },
883
+ handler: api.createAuthMiddleware(async (ctx) => {
884
+ var _a;
885
+ const session = await api.getSessionFromCtx(ctx);
886
+ if (!session) return;
887
+ const code = (_a = ctx.body) == null ? void 0 : _a.code;
888
+ const row = await ctx.context.adapter.findOne({
889
+ model: "twoFactor",
890
+ where: [{ field: "userId", value: session.user.id }]
891
+ });
892
+ const valid = typeof code === "string" && !!row && await createOTP(await crypto.symmetricDecrypt({ key: ctx.context.secretConfig, data: row.secret })).verify(code);
893
+ if (!valid) throw new api.APIError("UNAUTHORIZED", { message: "Enter the current code from your authenticator app" });
894
+ })
895
+ }] : [],
896
+ // The challenge answers with JSON ({ twoFactorRedirect: true }), which One Tap's
897
+ // caller handles. The Google callback is a browser redirect, so turn it into a
898
+ // redirect to /login/2fa, keeping where the user was headed (same-origin only).
899
+ after: challengeAfterOAuth ? [{
900
+ matcher: (ctx) => ctx.path === "/callback/:id",
901
+ handler: api.createAuthMiddleware(async (ctx) => {
902
+ var _a, _b;
903
+ const returned = ctx.context.returned;
904
+ if (!(returned == null ? void 0 : returned.twoFactorRedirect)) return;
905
+ const target = new URL((_b = (_a = ctx.context.responseHeaders) == null ? void 0 : _a.get("location")) != null ? _b : "/dashboard", baseURL);
906
+ const callbackUrl = target.origin === new URL(baseURL).origin ? target.pathname + target.search : "/dashboard";
907
+ throw ctx.redirect(`/login/2fa?callbackUrl=${encodeURIComponent(callbackUrl)}`);
908
+ })
909
+ }] : []
910
+ }
911
+ };
912
+ return [plugin, extras];
913
+ }
509
914
  async function logActivity({
510
915
  userId,
511
916
  action,
@@ -768,7 +1173,52 @@ async function notifyPasskeyChange(ctx, action) {
768
1173
  console.error("Failed to send passkey-change notification", error);
769
1174
  }
770
1175
  }
1176
+ async function packageSessionCreated(...[session, context]) {
1177
+ var _a, _b, _c, _d;
1178
+ const impersonatedBy = session.impersonatedBy;
1179
+ if (impersonatedBy) {
1180
+ const target = await db.select({ email: users.email }).from(users).where(drizzleOrm.eq(users.id, session.userId)).limit(1);
1181
+ await logActivity({
1182
+ userId: impersonatedBy,
1183
+ action: "impersonation_started",
1184
+ description: `Admin started impersonating ${(_b = (_a = target[0]) == null ? void 0 : _a.email) != null ? _b : session.userId}`,
1185
+ metadata: { impersonatedUserId: session.userId }
1186
+ });
1187
+ return;
1188
+ }
1189
+ try {
1190
+ await db.update(users).set({ lastLoginAt: /* @__PURE__ */ new Date() }).where(drizzleOrm.eq(users.id, session.userId));
1191
+ } catch (error) {
1192
+ console.error("Failed to update lastLoginAt", error);
1193
+ }
1194
+ try {
1195
+ const headers = context == null ? void 0 : context.headers;
1196
+ const ipAddress = getClientIp(headers);
1197
+ const userAgent = (_c = headers == null ? void 0 : headers.get("user-agent")) != null ? _c : null;
1198
+ const referrerUrl = ((_d = context == null ? void 0 : context.getCookie) == null ? void 0 : _d.call(context, LOGIN_REFERRER_COOKIE)) || (headers == null ? void 0 : headers.get("referer")) || null;
1199
+ const device = parseUserAgent(userAgent);
1200
+ const geo = lookupGeoLocation(ipAddress);
1201
+ const [{ count }] = await db.select({ count: drizzleOrm.sql`count(*)` }).from(sessions).where(drizzleOrm.eq(sessions.userId, session.userId));
1202
+ const isFirstSession = Number(count) <= 1;
1203
+ await logActivity({
1204
+ userId: session.userId,
1205
+ action: "login",
1206
+ description: isFirstSession ? "New account registered and signed in" : "User logged in",
1207
+ ipAddress,
1208
+ userAgent,
1209
+ referrerUrl,
1210
+ os: device.os,
1211
+ browser: device.browser,
1212
+ deviceType: device.deviceType,
1213
+ country: geo.country,
1214
+ city: geo.city
1215
+ });
1216
+ } catch (error) {
1217
+ console.error("Failed to log login activity", error);
1218
+ }
1219
+ }
771
1220
  function createAuth(overrides = {}) {
1221
+ var _a, _b, _c, _d, _e, _f;
772
1222
  const socialProviders = __spreadValues(__spreadValues({}, config.AUTH_ENABLE_GOOGLE ? {
773
1223
  google: {
774
1224
  clientId: process.env.AUTH_GOOGLE_ID || process.env.GOOGLE_CLIENT_ID || "",
@@ -783,6 +1233,18 @@ function createAuth(overrides = {}) {
783
1233
  );
784
1234
  }
785
1235
  const baseURL = process.env.NEXTAUTH_URL || process.env.BETTER_AUTH_URL || "http://localhost:3000";
1236
+ const [twoFactorPlugin, twoFactorExtras] = twoFactorPlugins(baseURL, {
1237
+ issuer: config.APP_NAME,
1238
+ passwordless: (_a = overrides.twoFactor) == null ? void 0 : _a.passwordless,
1239
+ challengeAfterOAuth: (_b = overrides.twoFactor) == null ? void 0 : _b.challengeAfterOAuth
1240
+ });
1241
+ const appHooks = {
1242
+ id: "app-hooks",
1243
+ hooks: {
1244
+ before: ((_c = overrides.hooks) == null ? void 0 : _c.before) ? [{ matcher: () => true, handler: overrides.hooks.before }] : [],
1245
+ after: ((_d = overrides.hooks) == null ? void 0 : _d.after) ? [{ matcher: () => true, handler: overrides.hooks.after }] : []
1246
+ }
1247
+ };
786
1248
  return betterAuth.betterAuth({
787
1249
  database: drizzle.drizzleAdapter(db, {
788
1250
  provider: "pg",
@@ -862,63 +1324,30 @@ function createAuth(overrides = {}) {
862
1324
  // no password, so better-auth instead requires a session younger than
863
1325
  // `freshAge` (default 1 day). Every user-owned table cascades on delete.
864
1326
  // Impersonation and last-admin guards live in hooks.before below.
865
- deleteUser: { enabled: true }
1327
+ deleteUser: { enabled: (_e = overrides.deleteUser) != null ? _e : true }
866
1328
  },
867
1329
  // Advanced options
868
- advanced: {
1330
+ advanced: __spreadProps(__spreadValues({}, overrides.advanced), {
869
1331
  database: {
870
1332
  generateId: () => cuid2.createId()
871
1333
  }
872
- },
873
- // Every new session row corresponds to a sign-in (credential or OAuth) —
874
- // use that as the "last logged in" signal rather than session updates,
875
- // which also fire on cookie-cache refresh / expiry extension.
1334
+ }),
1335
+ rateLimit: overrides.rateLimit,
876
1336
  databaseHooks: {
1337
+ user: {
1338
+ create: {
1339
+ async after(user, context) {
1340
+ var _a2, _b2, _c2, _d2;
1341
+ await ((_d2 = (_c2 = (_b2 = (_a2 = overrides.databaseHooks) == null ? void 0 : _a2.user) == null ? void 0 : _b2.create) == null ? void 0 : _c2.after) == null ? void 0 : _d2.call(_c2, user, context));
1342
+ }
1343
+ }
1344
+ },
877
1345
  session: {
878
1346
  create: {
879
1347
  async after(session, context) {
880
- var _a, _b, _c, _d;
881
- const impersonatedBy = session.impersonatedBy;
882
- if (impersonatedBy) {
883
- const target = await db.select({ email: users.email }).from(users).where(drizzleOrm.eq(users.id, session.userId)).limit(1);
884
- await logActivity({
885
- userId: impersonatedBy,
886
- action: "impersonation_started",
887
- description: `Admin started impersonating ${(_b = (_a = target[0]) == null ? void 0 : _a.email) != null ? _b : session.userId}`,
888
- metadata: { impersonatedUserId: session.userId }
889
- });
890
- return;
891
- }
892
- try {
893
- await db.update(users).set({ lastLoginAt: /* @__PURE__ */ new Date() }).where(drizzleOrm.eq(users.id, session.userId));
894
- } catch (error) {
895
- console.error("Failed to update lastLoginAt", error);
896
- }
897
- try {
898
- const headers = context == null ? void 0 : context.headers;
899
- const ipAddress = getClientIp(headers);
900
- const userAgent = (_c = headers == null ? void 0 : headers.get("user-agent")) != null ? _c : null;
901
- const referrerUrl = ((_d = context == null ? void 0 : context.getCookie) == null ? void 0 : _d.call(context, LOGIN_REFERRER_COOKIE)) || (headers == null ? void 0 : headers.get("referer")) || null;
902
- const device = parseUserAgent(userAgent);
903
- const geo = lookupGeoLocation(ipAddress);
904
- const [{ count }] = await db.select({ count: drizzleOrm.sql`count(*)` }).from(sessions).where(drizzleOrm.eq(sessions.userId, session.userId));
905
- const isFirstSession = Number(count) <= 1;
906
- await logActivity({
907
- userId: session.userId,
908
- action: "login",
909
- description: isFirstSession ? "New account registered and signed in" : "User logged in",
910
- ipAddress,
911
- userAgent,
912
- referrerUrl,
913
- os: device.os,
914
- browser: device.browser,
915
- deviceType: device.deviceType,
916
- country: geo.country,
917
- city: geo.city
918
- });
919
- } catch (error) {
920
- console.error("Failed to log login activity", error);
921
- }
1348
+ var _a2, _b2, _c2, _d2;
1349
+ await packageSessionCreated(session, context);
1350
+ await ((_d2 = (_c2 = (_b2 = (_a2 = overrides.databaseHooks) == null ? void 0 : _a2.session) == null ? void 0 : _b2.create) == null ? void 0 : _c2.after) == null ? void 0 : _d2.call(_c2, session, context));
922
1351
  }
923
1352
  }
924
1353
  }
@@ -932,9 +1361,9 @@ function createAuth(overrides = {}) {
932
1361
  // available together.
933
1362
  hooks: {
934
1363
  before: api.createAuthMiddleware(async (ctx) => {
935
- var _a, _b, _c, _d;
1364
+ var _a2, _b2, _c2, _d2;
936
1365
  if (ctx.path === "/sign-in/email" || ctx.path === "/sign-up/email") {
937
- const fingerprint = (_a = ctx.headers) == null ? void 0 : _a.get(DEVICE_FINGERPRINT_HEADER);
1366
+ const fingerprint = (_a2 = ctx.headers) == null ? void 0 : _a2.get(DEVICE_FINGERPRINT_HEADER);
938
1367
  const ip = getClientIp(ctx.headers);
939
1368
  const throttled = fingerprint && await isDeviceThrottled(fingerprint) || ip && await isDeviceThrottled(`ip:${ip}`, MAX_IP);
940
1369
  if (throttled) {
@@ -944,7 +1373,7 @@ function createAuth(overrides = {}) {
944
1373
  }
945
1374
  }
946
1375
  if (ctx.path === "/sign-in/social") {
947
- if (((_b = ctx.body) == null ? void 0 : _b.provider) === "google") {
1376
+ if (((_b2 = ctx.body) == null ? void 0 : _b2.provider) === "google") {
948
1377
  const flags = await getEffectiveAuthFlags();
949
1378
  if (!flags.google) {
950
1379
  throw new api.APIError("FORBIDDEN", { message: "Google sign-in is currently disabled." });
@@ -966,6 +1395,9 @@ function createAuth(overrides = {}) {
966
1395
  }
967
1396
  return;
968
1397
  }
1398
+ if (ctx.path === "/admin/impersonate-user" && overrides.impersonation === false) {
1399
+ throw new api.APIError("FORBIDDEN", { message: "Impersonation is turned off." });
1400
+ }
969
1401
  if (ctx.path === "/delete-user") {
970
1402
  const current2 = await api.getSessionFromCtx(ctx, { disableCookieCache: true });
971
1403
  if (!current2) return;
@@ -987,13 +1419,13 @@ function createAuth(overrides = {}) {
987
1419
  await logActivity({
988
1420
  userId: current.session.impersonatedBy,
989
1421
  action: "impersonation_stopped",
990
- description: `Admin stopped impersonating ${(_d = (_c = target[0]) == null ? void 0 : _c.email) != null ? _d : current.session.userId}`,
1422
+ description: `Admin stopped impersonating ${(_d2 = (_c2 = target[0]) == null ? void 0 : _c2.email) != null ? _d2 : current.session.userId}`,
991
1423
  metadata: { impersonatedUserId: current.session.userId }
992
1424
  });
993
1425
  }
994
1426
  }),
995
1427
  after: api.createAuthMiddleware(async (ctx) => {
996
- var _a, _b, _c, _d;
1428
+ var _a2, _b2, _c2, _d2;
997
1429
  if (ctx.path === "/passkey/verify-registration" || ctx.path === "/passkey/delete-passkey") {
998
1430
  if (ctx.context.returned instanceof api.APIError) return;
999
1431
  await notifyPasskeyChange(
@@ -1003,15 +1435,15 @@ function createAuth(overrides = {}) {
1003
1435
  return;
1004
1436
  }
1005
1437
  if (ctx.path !== "/sign-in/email" && ctx.path !== "/sign-up/email") return;
1006
- const fingerprint = (_a = ctx.headers) == null ? void 0 : _a.get(DEVICE_FINGERPRINT_HEADER);
1438
+ const fingerprint = (_a2 = ctx.headers) == null ? void 0 : _a2.get(DEVICE_FINGERPRINT_HEADER);
1007
1439
  const ip = getClientIp(ctx.headers);
1008
1440
  const ipKey = ip ? `ip:${ip}` : null;
1009
1441
  if (!fingerprint && !ipKey) return;
1010
1442
  const failed = ctx.context.returned instanceof api.APIError;
1011
- const rawEmail = (_b = ctx.body) == null ? void 0 : _b.email;
1443
+ const rawEmail = (_b2 = ctx.body) == null ? void 0 : _b2.email;
1012
1444
  const meta = {
1013
1445
  ipAddress: ip,
1014
- userAgent: (_d = (_c = ctx.headers) == null ? void 0 : _c.get("user-agent")) != null ? _d : null,
1446
+ userAgent: (_d2 = (_c2 = ctx.headers) == null ? void 0 : _c2.get("user-agent")) != null ? _d2 : null,
1015
1447
  email: typeof rawEmail === "string" ? rawEmail.toLowerCase() : null
1016
1448
  };
1017
1449
  const keys = [fingerprint, ipKey].filter((k) => !!k);
@@ -1059,9 +1491,10 @@ function createAuth(overrides = {}) {
1059
1491
  }
1060
1492
  }
1061
1493
  }),
1062
- // TOTP second factor + encrypted backup codes. `issuer` is the label
1063
- // shown in the user's authenticator app.
1064
- plugins.twoFactor({ issuer: config.APP_NAME }),
1494
+ // TOTP second factor + encrypted backup codes (see lib/two-factor.ts).
1495
+ // Listed individually, not spread: see the note on the spread below.
1496
+ twoFactorPlugin,
1497
+ twoFactorExtras,
1065
1498
  // WebAuthn passkeys (Touch ID / Windows Hello / security keys) as a
1066
1499
  // passwordless sign-in method. rpID must be the bare host and origin
1067
1500
  // the full URL — both derived from baseURL above.
@@ -1073,7 +1506,9 @@ function createAuth(overrides = {}) {
1073
1506
  // checks to see if oneTap is enabled and if google provider is available, then add the oneTap plugin.
1074
1507
  // Keep this spread last: a leading spread turns `plugins` from a tuple into a plain
1075
1508
  // array and better-auth 1.7 then drops plugin fields (e.g. session.impersonatedBy).
1076
- ...config.AUTH_ENABLE_ONE_TAP && Boolean(socialProviders.google) ? [plugins.oneTap()] : []
1509
+ ...config.AUTH_ENABLE_ONE_TAP && Boolean(socialProviders.google) ? [plugins.oneTap()] : [],
1510
+ appHooks,
1511
+ ...(_f = overrides.plugins) != null ? _f : []
1077
1512
  ]
1078
1513
  });
1079
1514
  }