@xk2800/nextjs-template 0.7.1-beta.13 → 0.7.1-beta.15

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