@xk2800/nextjs-template 0.7.1-beta.8 → 0.7.2-beta.0

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.
Files changed (125) hide show
  1. package/components/auth/oneTap.tsx +15 -5
  2. package/components/dashboard/admin/adminActivityLogsTable.tsx +4 -0
  3. package/components/dashboard/admin/adminUsersTable.tsx +154 -34
  4. package/components/dashboard/admin/impersonationLogCard.tsx +2 -2
  5. package/components/dashboard/appSidebar.tsx +2 -2
  6. package/components/dashboard/deleteAccountCard.tsx +31 -4
  7. package/components/dashboard/navStyleToggle.tsx +29 -0
  8. package/components/dashboard/topNav.tsx +95 -0
  9. package/components/email/email-template-banned.tsx +53 -0
  10. package/components/ui/alert-dialog.tsx +2 -2
  11. package/components/ui/avatar.tsx +1 -1
  12. package/components/ui/badge.tsx +5 -3
  13. package/components/ui/calendar.tsx +220 -0
  14. package/components/ui/card.tsx +1 -1
  15. package/components/ui/category-selector.tsx +215 -0
  16. package/components/ui/chart.tsx +374 -0
  17. package/components/ui/column-picker.tsx +140 -0
  18. package/components/ui/command.tsx +184 -0
  19. package/components/ui/data-table.tsx +44 -6
  20. package/components/ui/date-picker-with-presets.tsx +122 -0
  21. package/components/ui/dialog.tsx +2 -2
  22. package/components/ui/disclaimer.tsx +4 -0
  23. package/components/ui/dropdown-menu.tsx +3 -3
  24. package/components/ui/field.tsx +248 -0
  25. package/components/ui/info-tooltip.tsx +53 -0
  26. package/components/ui/input.tsx +10 -1
  27. package/components/ui/label.tsx +1 -1
  28. package/components/ui/month-selector.tsx +194 -0
  29. package/components/ui/navigation-menu.tsx +168 -0
  30. package/components/ui/pagination.tsx +127 -0
  31. package/components/ui/popover.tsx +89 -0
  32. package/components/ui/select.tsx +1 -1
  33. package/components/ui/source-selector.tsx +164 -0
  34. package/components/ui/switch.tsx +3 -3
  35. package/dist/activity/logger.d.mts +3 -1
  36. package/dist/activity/logger.d.ts +3 -1
  37. package/dist/activity/logger.js +20 -0
  38. package/dist/activity/logger.js.map +1 -1
  39. package/dist/activity/logger.mjs +4 -4
  40. package/dist/activity/queries.d.mts +1 -1
  41. package/dist/activity/queries.d.ts +1 -1
  42. package/dist/activity/queries.js +20 -0
  43. package/dist/activity/queries.js.map +1 -1
  44. package/dist/activity/queries.mjs +3 -3
  45. package/dist/admin/queries.js +20 -0
  46. package/dist/admin/queries.js.map +1 -1
  47. package/dist/admin/queries.mjs +3 -3
  48. package/dist/api/feedback.js +527 -70
  49. package/dist/api/feedback.js.map +1 -1
  50. package/dist/api/feedback.mjs +8 -8
  51. package/dist/api/marketing.js +527 -70
  52. package/dist/api/marketing.js.map +1 -1
  53. package/dist/api/marketing.mjs +10 -10
  54. package/dist/auth/helpers.js +525 -68
  55. package/dist/auth/helpers.js.map +1 -1
  56. package/dist/auth/helpers.mjs +8 -8
  57. package/dist/auth/index.d.mts +149 -10
  58. package/dist/auth/index.d.ts +149 -10
  59. package/dist/auth/index.js +525 -68
  60. package/dist/auth/index.js.map +1 -1
  61. package/dist/auth/index.mjs +7 -7
  62. package/dist/{chunk-ZJMFE5B2.mjs → chunk-4C7JHGT5.mjs} +4 -4
  63. package/dist/{chunk-ZJMFE5B2.mjs.map → chunk-4C7JHGT5.mjs.map} +1 -1
  64. package/dist/{chunk-7F2POZM6.mjs → chunk-4F6KE47S.mjs} +4 -4
  65. package/dist/chunk-4F6KE47S.mjs.map +1 -0
  66. package/dist/{chunk-P2G23JMY.mjs → chunk-A6JXMHOQ.mjs} +5 -5
  67. package/dist/{chunk-P2G23JMY.mjs.map → chunk-A6JXMHOQ.mjs.map} +1 -1
  68. package/dist/{chunk-TKWNEKK6.mjs → chunk-HUEDEAY3.mjs} +8 -2
  69. package/dist/chunk-HUEDEAY3.mjs.map +1 -0
  70. package/dist/{chunk-6Z3WUSDJ.mjs → chunk-JUSU6UZA.mjs} +5 -5
  71. package/dist/{chunk-6Z3WUSDJ.mjs.map → chunk-JUSU6UZA.mjs.map} +1 -1
  72. package/dist/{chunk-TR5XFBTD.mjs → chunk-KA2KMGPY.mjs} +17 -3
  73. package/dist/chunk-KA2KMGPY.mjs.map +1 -0
  74. package/dist/{chunk-OVKVD2HH.mjs → chunk-L242CZ64.mjs} +3 -3
  75. package/dist/{chunk-OVKVD2HH.mjs.map → chunk-L242CZ64.mjs.map} +1 -1
  76. package/dist/{chunk-C6RGN6QA.mjs → chunk-NQELV53D.mjs} +4 -4
  77. package/dist/{chunk-C6RGN6QA.mjs.map → chunk-NQELV53D.mjs.map} +1 -1
  78. package/dist/chunk-VHNGYAIG.mjs +899 -0
  79. package/dist/chunk-VHNGYAIG.mjs.map +1 -0
  80. package/dist/{chunk-6MDQRT6U.mjs → chunk-YH53UPUW.mjs} +4 -4
  81. package/dist/{chunk-6MDQRT6U.mjs.map → chunk-YH53UPUW.mjs.map} +1 -1
  82. package/dist/config/env.d.mts +2 -0
  83. package/dist/config/env.d.ts +2 -0
  84. package/dist/config/env.js +6 -0
  85. package/dist/config/env.js.map +1 -1
  86. package/dist/config/env.mjs +1 -1
  87. package/dist/db/index.d.mts +1 -1
  88. package/dist/db/index.d.ts +1 -1
  89. package/dist/db/index.js +20 -0
  90. package/dist/db/index.js.map +1 -1
  91. package/dist/db/index.mjs +3 -3
  92. package/dist/db/schema.d.mts +1 -1
  93. package/dist/db/schema.d.ts +1 -1
  94. package/dist/db/schema.js +14 -0
  95. package/dist/db/schema.js.map +1 -1
  96. package/dist/db/schema.mjs +1 -1
  97. package/dist/errors.js +20 -0
  98. package/dist/errors.js.map +1 -1
  99. package/dist/errors.mjs +4 -4
  100. package/dist/marketing/index.js +6 -0
  101. package/dist/marketing/index.js.map +1 -1
  102. package/dist/marketing/index.mjs +3 -3
  103. package/dist/{schema-CN_Y6EXv.d.mts → schema-DzC5zdOq.d.mts} +146 -2
  104. package/dist/{schema-CN_Y6EXv.d.ts → schema-DzC5zdOq.d.ts} +146 -2
  105. package/dist/sessions/queries.js +20 -0
  106. package/dist/sessions/queries.js.map +1 -1
  107. package/dist/sessions/queries.mjs +3 -3
  108. package/dist/settings/queries.d.mts +1 -1
  109. package/dist/settings/queries.d.ts +1 -1
  110. package/dist/settings/queries.js +20 -0
  111. package/dist/settings/queries.js.map +1 -1
  112. package/dist/settings/queries.mjs +4 -4
  113. package/dist/users/queries.d.mts +3 -0
  114. package/dist/users/queries.d.ts +3 -0
  115. package/dist/users/queries.js +20 -0
  116. package/dist/users/queries.js.map +1 -1
  117. package/dist/users/queries.mjs +3 -3
  118. package/lib/recalculate-columns.ts +8 -2
  119. package/package.json +28 -18
  120. package/styles/theme.css +23 -3
  121. package/dist/chunk-7F2POZM6.mjs.map +0 -1
  122. package/dist/chunk-7QVIOQ47.mjs +0 -462
  123. package/dist/chunk-7QVIOQ47.mjs.map +0 -1
  124. package/dist/chunk-TKWNEKK6.mjs.map +0 -1
  125. package/dist/chunk-TR5XFBTD.mjs.map +0 -1
@@ -15,8 +15,9 @@ var pg = require('pg');
15
15
  var pgCore = require('drizzle-orm/pg-core');
16
16
  var zod = require('zod');
17
17
  var plugins = require('better-auth/plugins');
18
- var passkey = require('@better-auth/passkey');
19
18
  var api = require('better-auth/api');
19
+ var crypto = require('better-auth/crypto');
20
+ var passkey = require('@better-auth/passkey');
20
21
  var uaParserJs = require('ua-parser-js');
21
22
  var geoip = require('geoip-lite');
22
23
  var headers = require('next/headers');
@@ -214,6 +215,7 @@ __export(schema_exports, {
214
215
  deviceFingerprints: () => deviceFingerprints,
215
216
  errorRefs: () => errorRefs,
216
217
  passkeys: () => passkeys,
218
+ pushSubscriptions: () => pushSubscriptions,
217
219
  sessions: () => sessions,
218
220
  systemSettings: () => systemSettings,
219
221
  twoFactors: () => twoFactors,
@@ -262,6 +264,8 @@ var users = pgCore.pgTable("user", {
262
264
  banned: pgCore.boolean("banned").default(false).notNull(),
263
265
  bannedAt: pgCore.timestamp("bannedAt"),
264
266
  bannedReason: pgCore.text("bannedReason"),
267
+ bannedBy: pgCore.text("bannedBy"),
268
+ // email of the admin who issued the ban
265
269
  // Required by better-auth's admin plugin schema (auto-expiring bans). We
266
270
  // never set this ourselves, so it stays null and bans behave as permanent,
267
271
  // same as before the plugin was added.
@@ -443,6 +447,17 @@ var errorRefs = pgCore.pgTable("error_refs", {
443
447
  }, (table) => [
444
448
  pgCore.index("error_refs_created_at_idx").on(table.createdAt)
445
449
  ]);
450
+ var pushSubscriptions = pgCore.pgTable("push_subscription", {
451
+ id: pgCore.text("id").primaryKey().$defaultFn(() => cuid2.createId()),
452
+ userId: pgCore.text("userId").notNull().references(() => users.id, { onDelete: "cascade" }),
453
+ endpoint: pgCore.text("endpoint").notNull().unique(),
454
+ p256dh: pgCore.text("p256dh").notNull(),
455
+ auth: pgCore.text("auth").notNull(),
456
+ userAgent: pgCore.text("userAgent"),
457
+ createdAt: pgCore.timestamp("createdAt").notNull().defaultNow()
458
+ }, (table) => [
459
+ pgCore.index("push_subscription_user_idx").on(table.userId)
460
+ ]);
446
461
  var envSchema = zod.z.object({
447
462
  NODE_ENV: zod.z.enum(["development", "production", "test"]).default("development"),
448
463
  PORT: zod.z.string().default("3000").transform(Number),
@@ -466,6 +481,12 @@ var envSchema = zod.z.object({
466
481
  // a comma-separated list and sends through Resend (needs RESEND_API_KEY).
467
482
  FEEDBACK_DISCORD_WEBHOOK_URL: zod.z.string().default(""),
468
483
  FEEDBACK_EMAIL: zod.z.string().default(""),
484
+ // Web Push (example, see lib/push.ts). Generate keys with
485
+ // `bunx web-push generate-vapid-keys`. Blank = the notifications card is hidden.
486
+ // The public key is also read in the browser as NEXT_PUBLIC_VAPID_PUBLIC_KEY.
487
+ VAPID_PRIVATE_KEY: zod.z.string().default(""),
488
+ // mailto: or https: URL push services can contact you at.
489
+ VAPID_SUBJECT: zod.z.string().default(""),
469
490
  // Seed-only: the live value lives in the system_settings DB row (see
470
491
  // lib/settings-queries.ts) once it's been seeded on first read, and is
471
492
  // changed from the admin System Settings page, not by editing this var.
@@ -509,6 +530,410 @@ if (config.DB_DRIVER === "pg") {
509
530
  } else {
510
531
  console.log("Database connection not established, unknown DB_DRIVER:", config.DB_DRIVER);
511
532
  }
533
+
534
+ // node_modules/@better-auth/utils/dist/base32.mjs
535
+ function getAlphabet(hex2) {
536
+ return "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
537
+ }
538
+ function createDecodeMap(alphabet) {
539
+ const decodeMap = /* @__PURE__ */ new Map();
540
+ for (let i = 0; i < alphabet.length; i++) {
541
+ decodeMap.set(alphabet[i], i);
542
+ }
543
+ return decodeMap;
544
+ }
545
+ function base32Encode(data, alphabet, padding) {
546
+ let result = "";
547
+ let buffer = 0;
548
+ let shift = 0;
549
+ for (const byte of data) {
550
+ buffer = buffer << 8 | byte;
551
+ shift += 8;
552
+ while (shift >= 5) {
553
+ shift -= 5;
554
+ result += alphabet[buffer >> shift & 31];
555
+ }
556
+ }
557
+ if (shift > 0) {
558
+ result += alphabet[buffer << 5 - shift & 31];
559
+ }
560
+ if (padding) {
561
+ const padCount = (8 - result.length % 8) % 8;
562
+ result += "=".repeat(padCount);
563
+ }
564
+ return result;
565
+ }
566
+ function base32Decode(data, alphabet) {
567
+ const decodeMap = createDecodeMap(alphabet);
568
+ const result = [];
569
+ let buffer = 0;
570
+ let bitsCollected = 0;
571
+ for (const char of data) {
572
+ if (char === "=")
573
+ break;
574
+ const value = decodeMap.get(char);
575
+ if (value === void 0) {
576
+ throw new Error(`Invalid Base32 character: ${char}`);
577
+ }
578
+ buffer = buffer << 5 | value;
579
+ bitsCollected += 5;
580
+ while (bitsCollected >= 8) {
581
+ bitsCollected -= 8;
582
+ result.push(buffer >> bitsCollected & 255);
583
+ }
584
+ }
585
+ return Uint8Array.from(result);
586
+ }
587
+ var base32 = {
588
+ /**
589
+ * Encodes data into a Base32 string.
590
+ * @param data - The data to encode (ArrayBuffer, TypedArray, or string).
591
+ * @param options - Encoding options.
592
+ * @returns The Base32 encoded string.
593
+ */
594
+ encode(data, options = {}) {
595
+ var _a;
596
+ const alphabet = getAlphabet();
597
+ const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
598
+ return base32Encode(buffer, alphabet, (_a = options.padding) != null ? _a : true);
599
+ },
600
+ /**
601
+ * Decodes a Base32 string into a Uint8Array.
602
+ * @param data - The Base32 encoded string or ArrayBuffer/TypedArray.
603
+ * @returns The decoded Uint8Array.
604
+ */
605
+ decode(data) {
606
+ if (typeof data !== "string") {
607
+ data = new TextDecoder().decode(data);
608
+ }
609
+ const alphabet = getAlphabet();
610
+ return base32Decode(data, alphabet);
611
+ }
612
+ };
613
+
614
+ // node_modules/@better-auth/utils/dist/hex.mjs
615
+ var hexadecimal = "0123456789abcdef";
616
+ var hex = {
617
+ encode: (data) => {
618
+ if (typeof data === "string") {
619
+ data = new TextEncoder().encode(data);
620
+ }
621
+ if (data.byteLength === 0) {
622
+ return "";
623
+ }
624
+ const buffer = new Uint8Array(data);
625
+ let result = "";
626
+ for (const byte of buffer) {
627
+ result += byte.toString(16).padStart(2, "0");
628
+ }
629
+ return result;
630
+ },
631
+ decode: (data) => {
632
+ if (!data) {
633
+ return "";
634
+ }
635
+ if (typeof data === "string") {
636
+ if (data.length % 2 !== 0) {
637
+ throw new Error("Invalid hexadecimal string");
638
+ }
639
+ if (!new RegExp(`^[${hexadecimal}]+$`).test(data)) {
640
+ throw new Error("Invalid hexadecimal string");
641
+ }
642
+ const result = new Uint8Array(data.length / 2);
643
+ for (let i = 0; i < data.length; i += 2) {
644
+ result[i / 2] = parseInt(data.slice(i, i + 2), 16);
645
+ }
646
+ return new TextDecoder().decode(result);
647
+ }
648
+ return new TextDecoder().decode(data);
649
+ }
650
+ };
651
+
652
+ // node_modules/@better-auth/utils/dist/base64.mjs
653
+ function getAlphabet2(urlSafe) {
654
+ return urlSafe ? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
655
+ }
656
+ function base64Encode(data, alphabet, padding) {
657
+ let result = "";
658
+ let buffer = 0;
659
+ let shift = 0;
660
+ for (const byte of data) {
661
+ buffer = buffer << 8 | byte;
662
+ shift += 8;
663
+ while (shift >= 6) {
664
+ shift -= 6;
665
+ result += alphabet[buffer >> shift & 63];
666
+ }
667
+ }
668
+ if (shift > 0) {
669
+ result += alphabet[buffer << 6 - shift & 63];
670
+ }
671
+ if (padding) {
672
+ const padCount = (4 - result.length % 4) % 4;
673
+ result += "=".repeat(padCount);
674
+ }
675
+ return result;
676
+ }
677
+ function base64Decode(data, alphabet) {
678
+ const decodeMap = /* @__PURE__ */ new Map();
679
+ for (let i = 0; i < alphabet.length; i++) {
680
+ decodeMap.set(alphabet[i], i);
681
+ }
682
+ const result = [];
683
+ let buffer = 0;
684
+ let bitsCollected = 0;
685
+ for (const char of data) {
686
+ if (char === "=")
687
+ break;
688
+ const value = decodeMap.get(char);
689
+ if (value === void 0) {
690
+ throw new Error(`Invalid Base64 character: ${char}`);
691
+ }
692
+ buffer = buffer << 6 | value;
693
+ bitsCollected += 6;
694
+ if (bitsCollected >= 8) {
695
+ bitsCollected -= 8;
696
+ result.push(buffer >> bitsCollected & 255);
697
+ }
698
+ }
699
+ return Uint8Array.from(result);
700
+ }
701
+ var base64 = {
702
+ encode(data, options = {}) {
703
+ var _a;
704
+ const alphabet = getAlphabet2(false);
705
+ const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
706
+ return base64Encode(buffer, alphabet, (_a = options.padding) != null ? _a : true);
707
+ },
708
+ decode(data) {
709
+ if (typeof data !== "string") {
710
+ data = new TextDecoder().decode(data);
711
+ }
712
+ const urlSafe = data.includes("-") || data.includes("_");
713
+ const alphabet = getAlphabet2(urlSafe);
714
+ return base64Decode(data, alphabet);
715
+ }
716
+ };
717
+ var base64Url = {
718
+ encode(data, options = {}) {
719
+ var _a;
720
+ const alphabet = getAlphabet2(true);
721
+ const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
722
+ return base64Encode(buffer, alphabet, (_a = options.padding) != null ? _a : true);
723
+ },
724
+ decode(data) {
725
+ const urlSafe = data.includes("-") || data.includes("_");
726
+ const alphabet = getAlphabet2(urlSafe);
727
+ return base64Decode(data, alphabet);
728
+ }
729
+ };
730
+
731
+ // node_modules/@better-auth/utils/dist/index.mjs
732
+ function getWebcryptoSubtle() {
733
+ const cr = typeof globalThis !== "undefined" && globalThis.crypto;
734
+ if (cr && typeof cr.subtle === "object" && cr.subtle != null)
735
+ return cr.subtle;
736
+ throw new Error("crypto.subtle must be defined");
737
+ }
738
+
739
+ // node_modules/@better-auth/utils/dist/hmac.mjs
740
+ var createHMAC = (algorithm = "SHA-256", encoding = "none") => {
741
+ const hmac = {
742
+ importKey: async (key, keyUsage) => {
743
+ return getWebcryptoSubtle().importKey(
744
+ "raw",
745
+ typeof key === "string" ? new TextEncoder().encode(key) : key,
746
+ { name: "HMAC", hash: { name: algorithm } },
747
+ false,
748
+ [keyUsage]
749
+ );
750
+ },
751
+ sign: async (hmacKey, data) => {
752
+ if (typeof hmacKey === "string") {
753
+ hmacKey = await hmac.importKey(hmacKey, "sign");
754
+ }
755
+ const signature = await getWebcryptoSubtle().sign(
756
+ "HMAC",
757
+ hmacKey,
758
+ typeof data === "string" ? new TextEncoder().encode(data) : data
759
+ );
760
+ if (encoding === "hex") {
761
+ return hex.encode(signature);
762
+ }
763
+ if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") {
764
+ return base64Url.encode(signature, {
765
+ padding: encoding !== "base64urlnopad"
766
+ });
767
+ }
768
+ return signature;
769
+ },
770
+ verify: async (hmacKey, data, signature) => {
771
+ if (typeof hmacKey === "string") {
772
+ hmacKey = await hmac.importKey(hmacKey, "verify");
773
+ }
774
+ if (encoding === "hex") {
775
+ signature = hex.decode(signature);
776
+ }
777
+ if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") {
778
+ signature = await base64.decode(signature);
779
+ }
780
+ return getWebcryptoSubtle().verify(
781
+ "HMAC",
782
+ hmacKey,
783
+ typeof signature === "string" ? new TextEncoder().encode(signature) : signature,
784
+ typeof data === "string" ? new TextEncoder().encode(data) : data
785
+ );
786
+ }
787
+ };
788
+ return hmac;
789
+ };
790
+
791
+ // node_modules/@better-auth/utils/dist/otp.mjs
792
+ var defaultPeriod = 30;
793
+ var defaultDigits = 6;
794
+ function constantTimeEqualOTP(input, expected) {
795
+ let difference = input.length ^ expected.length;
796
+ for (let i = 0; i < expected.length; i++) {
797
+ difference |= input.charCodeAt(i) ^ expected.charCodeAt(i);
798
+ }
799
+ return difference === 0;
800
+ }
801
+ async function generateHOTP(secret, {
802
+ counter,
803
+ digits,
804
+ hash = "SHA-1"
805
+ }) {
806
+ const _digits = digits != null ? digits : defaultDigits;
807
+ if (_digits < 1 || _digits > 8) {
808
+ throw new TypeError("Digits must be between 1 and 8");
809
+ }
810
+ const buffer = new ArrayBuffer(8);
811
+ new DataView(buffer).setBigUint64(0, BigInt(counter), false);
812
+ const bytes = new Uint8Array(buffer);
813
+ const hmacResult = new Uint8Array(await createHMAC(hash).sign(secret, bytes));
814
+ const offset = hmacResult[hmacResult.length - 1] & 15;
815
+ const truncated = (hmacResult[offset] & 127) << 24 | (hmacResult[offset + 1] & 255) << 16 | (hmacResult[offset + 2] & 255) << 8 | hmacResult[offset + 3] & 255;
816
+ const otp = truncated % 10 ** _digits;
817
+ return otp.toString().padStart(_digits, "0");
818
+ }
819
+ async function generateTOTP(secret, options) {
820
+ var _a, _b;
821
+ const digits = (_a = options == null ? void 0 : options.digits) != null ? _a : defaultDigits;
822
+ const period = (_b = options == null ? void 0 : options.period) != null ? _b : defaultPeriod;
823
+ const milliseconds = period * 1e3;
824
+ const counter = Math.floor(Date.now() / milliseconds);
825
+ return await generateHOTP(secret, { counter, digits, hash: options == null ? void 0 : options.hash });
826
+ }
827
+ async function verifyTOTP(otp, {
828
+ window = 1,
829
+ digits = defaultDigits,
830
+ secret,
831
+ period = defaultPeriod
832
+ }) {
833
+ const milliseconds = period * 1e3;
834
+ const counter = Math.floor(Date.now() / milliseconds);
835
+ let matched = false;
836
+ for (let i = -window; i <= window; i++) {
837
+ const generatedOTP = await generateHOTP(secret, {
838
+ counter: counter + i,
839
+ digits
840
+ });
841
+ matched = constantTimeEqualOTP(otp, generatedOTP) || matched;
842
+ }
843
+ return matched;
844
+ }
845
+ function generateQRCode({
846
+ issuer,
847
+ account,
848
+ secret,
849
+ digits = defaultDigits,
850
+ period = defaultPeriod
851
+ }) {
852
+ const encodedIssuer = encodeURIComponent(issuer);
853
+ const encodedAccountName = encodeURIComponent(account);
854
+ const baseURI = `otpauth://totp/${encodedIssuer}:${encodedAccountName}`;
855
+ const params = new URLSearchParams({
856
+ secret: base32.encode(secret, {
857
+ padding: false
858
+ }),
859
+ issuer
860
+ });
861
+ if (digits !== void 0) {
862
+ params.set("digits", digits.toString());
863
+ }
864
+ if (period !== void 0) {
865
+ params.set("period", period.toString());
866
+ }
867
+ return `${baseURI}?${params.toString()}`;
868
+ }
869
+ var createOTP = (secret, opts) => {
870
+ var _a, _b;
871
+ const digits = (_a = void 0 ) != null ? _a : defaultDigits;
872
+ const period = (_b = void 0 ) != null ? _b : defaultPeriod;
873
+ return {
874
+ hotp: (counter) => generateHOTP(secret, { counter, digits }),
875
+ totp: () => generateTOTP(secret, { digits, period }),
876
+ verify: (otp, options) => verifyTOTP(otp, __spreadValues({ secret, digits, period }, options)),
877
+ url: (issuer, account) => generateQRCode({ issuer, account, secret, digits, period })
878
+ };
879
+ };
880
+
881
+ // lib/two-factor.ts
882
+ var CHALLENGED_PATHS = ["/callback/:id", "/one-tap/callback"];
883
+ var CODE_REQUIRED_PATHS = ["/two-factor/disable", "/two-factor/generate-backup-codes"];
884
+ function twoFactorPlugins(baseURL, { issuer, passwordless = false, challengeAfterOAuth = false }) {
885
+ const plugin = plugins.twoFactor({ issuer, allowPasswordless: passwordless });
886
+ if (challengeAfterOAuth) {
887
+ const [challenge] = plugin.hooks.after;
888
+ plugin.hooks.after = [__spreadProps(__spreadValues({}, challenge), {
889
+ matcher: (ctx) => {
890
+ var _a;
891
+ return challenge.matcher(ctx) || CHALLENGED_PATHS.includes((_a = ctx.path) != null ? _a : "");
892
+ }
893
+ })];
894
+ }
895
+ const extras = {
896
+ id: "two-factor-extras",
897
+ hooks: {
898
+ // allowPasswordless lets disable / regenerate-backup-codes run on a session alone,
899
+ // so anyone at an unlocked, signed-in browser could switch 2FA off. Require a
900
+ // current authenticator code instead of the password the user doesn't have.
901
+ before: passwordless ? [{
902
+ matcher: (ctx) => {
903
+ var _a;
904
+ return CODE_REQUIRED_PATHS.includes((_a = ctx.path) != null ? _a : "");
905
+ },
906
+ handler: api.createAuthMiddleware(async (ctx) => {
907
+ var _a;
908
+ const session = await api.getSessionFromCtx(ctx);
909
+ if (!session) return;
910
+ const code = (_a = ctx.body) == null ? void 0 : _a.code;
911
+ const row = await ctx.context.adapter.findOne({
912
+ model: "twoFactor",
913
+ where: [{ field: "userId", value: session.user.id }]
914
+ });
915
+ const valid = typeof code === "string" && !!row && await createOTP(await crypto.symmetricDecrypt({ key: ctx.context.secretConfig, data: row.secret })).verify(code);
916
+ if (!valid) throw new api.APIError("UNAUTHORIZED", { message: "Enter the current code from your authenticator app" });
917
+ })
918
+ }] : [],
919
+ // The challenge answers with JSON ({ twoFactorRedirect: true }), which One Tap's
920
+ // caller handles. The Google callback is a browser redirect, so turn it into a
921
+ // redirect to /login/2fa, keeping where the user was headed (same-origin only).
922
+ after: challengeAfterOAuth ? [{
923
+ matcher: (ctx) => ctx.path === "/callback/:id",
924
+ handler: api.createAuthMiddleware(async (ctx) => {
925
+ var _a, _b;
926
+ const returned = ctx.context.returned;
927
+ if (!(returned == null ? void 0 : returned.twoFactorRedirect)) return;
928
+ const target = new URL((_b = (_a = ctx.context.responseHeaders) == null ? void 0 : _a.get("location")) != null ? _b : "/dashboard", baseURL);
929
+ const callbackUrl = target.origin === new URL(baseURL).origin ? target.pathname + target.search : "/dashboard";
930
+ throw ctx.redirect(`/login/2fa?callbackUrl=${encodeURIComponent(callbackUrl)}`);
931
+ })
932
+ }] : []
933
+ }
934
+ };
935
+ return [plugin, extras];
936
+ }
512
937
  async function logActivity({
513
938
  userId,
514
939
  action,
@@ -718,7 +1143,7 @@ async function getResend() {
718
1143
  config.RESEND_BROADCAST_API_KEY || config.RESEND_API_KEY;
719
1144
 
720
1145
  // server/auth.ts
721
- async function logFailedLogin(ctx) {
1146
+ async function logFailedLogin(ctx, log) {
722
1147
  var _a, _b, _c;
723
1148
  try {
724
1149
  const raw = (_a = ctx.body) == null ? void 0 : _a.email;
@@ -726,7 +1151,7 @@ async function logFailedLogin(ctx) {
726
1151
  if (!email) return;
727
1152
  const [user] = await db.select({ id: users.id }).from(users).where(drizzleOrm.eq(users.email, email)).limit(1);
728
1153
  if (!user) return;
729
- await logActivity({
1154
+ await log({
730
1155
  userId: user.id,
731
1156
  action: "login_failed",
732
1157
  description: "Failed login attempt",
@@ -737,14 +1162,14 @@ async function logFailedLogin(ctx) {
737
1162
  console.error("Failed to log login_failed activity", error);
738
1163
  }
739
1164
  }
740
- async function notifyPasskeyChange(ctx, action) {
1165
+ async function notifyPasskeyChange(ctx, action, log) {
741
1166
  var _a, _b, _c, _d;
742
1167
  try {
743
1168
  const session = await api.getSessionFromCtx(ctx);
744
1169
  const user = session == null ? void 0 : session.user;
745
1170
  if (!user) return;
746
1171
  const ip = getClientIp(ctx.headers);
747
- await logActivity({
1172
+ await log({
748
1173
  userId: user.id,
749
1174
  action: action === "added" ? "passkey_added" : "passkey_removed",
750
1175
  description: `Passkey ${action}`,
@@ -771,7 +1196,52 @@ async function notifyPasskeyChange(ctx, action) {
771
1196
  console.error("Failed to send passkey-change notification", error);
772
1197
  }
773
1198
  }
1199
+ async function packageSessionCreated(log, ...[session, context]) {
1200
+ var _a, _b, _c, _d;
1201
+ const impersonatedBy = session.impersonatedBy;
1202
+ if (impersonatedBy) {
1203
+ const target = await db.select({ email: users.email }).from(users).where(drizzleOrm.eq(users.id, session.userId)).limit(1);
1204
+ await log({
1205
+ userId: impersonatedBy,
1206
+ action: "impersonation_started",
1207
+ description: `Admin started impersonating ${(_b = (_a = target[0]) == null ? void 0 : _a.email) != null ? _b : session.userId}`,
1208
+ metadata: { impersonatedUserId: session.userId }
1209
+ });
1210
+ return;
1211
+ }
1212
+ try {
1213
+ await db.update(users).set({ lastLoginAt: /* @__PURE__ */ new Date() }).where(drizzleOrm.eq(users.id, session.userId));
1214
+ } catch (error) {
1215
+ console.error("Failed to update lastLoginAt", error);
1216
+ }
1217
+ try {
1218
+ const headers2 = context == null ? void 0 : context.headers;
1219
+ const ipAddress = getClientIp(headers2);
1220
+ const userAgent = (_c = headers2 == null ? void 0 : headers2.get("user-agent")) != null ? _c : null;
1221
+ const referrerUrl = ((_d = context == null ? void 0 : context.getCookie) == null ? void 0 : _d.call(context, LOGIN_REFERRER_COOKIE)) || (headers2 == null ? void 0 : headers2.get("referer")) || null;
1222
+ const device = parseUserAgent(userAgent);
1223
+ const geo = lookupGeoLocation(ipAddress);
1224
+ const [{ count }] = await db.select({ count: drizzleOrm.sql`count(*)` }).from(sessions).where(drizzleOrm.eq(sessions.userId, session.userId));
1225
+ const isFirstSession = Number(count) <= 1;
1226
+ await log({
1227
+ userId: session.userId,
1228
+ action: "login",
1229
+ description: isFirstSession ? "New account registered and signed in" : "User logged in",
1230
+ ipAddress,
1231
+ userAgent,
1232
+ referrerUrl,
1233
+ os: device.os,
1234
+ browser: device.browser,
1235
+ deviceType: device.deviceType,
1236
+ country: geo.country,
1237
+ city: geo.city
1238
+ });
1239
+ } catch (error) {
1240
+ console.error("Failed to log login activity", error);
1241
+ }
1242
+ }
774
1243
  function createAuth(overrides = {}) {
1244
+ var _a, _b, _c, _d, _e, _f, _g;
775
1245
  const socialProviders = __spreadValues(__spreadValues({}, config.AUTH_ENABLE_GOOGLE ? {
776
1246
  google: {
777
1247
  clientId: process.env.AUTH_GOOGLE_ID || process.env.GOOGLE_CLIENT_ID || "",
@@ -786,6 +1256,19 @@ function createAuth(overrides = {}) {
786
1256
  );
787
1257
  }
788
1258
  const baseURL = process.env.NEXTAUTH_URL || process.env.BETTER_AUTH_URL || "http://localhost:3000";
1259
+ const log = (_a = overrides.logActivity) != null ? _a : logActivity;
1260
+ const [twoFactorPlugin, twoFactorExtras] = twoFactorPlugins(baseURL, {
1261
+ issuer: config.APP_NAME,
1262
+ passwordless: (_b = overrides.twoFactor) == null ? void 0 : _b.passwordless,
1263
+ challengeAfterOAuth: (_c = overrides.twoFactor) == null ? void 0 : _c.challengeAfterOAuth
1264
+ });
1265
+ const appHooks = {
1266
+ id: "app-hooks",
1267
+ hooks: {
1268
+ before: ((_d = overrides.hooks) == null ? void 0 : _d.before) ? [{ matcher: () => true, handler: overrides.hooks.before }] : [],
1269
+ after: ((_e = overrides.hooks) == null ? void 0 : _e.after) ? [{ matcher: () => true, handler: overrides.hooks.after }] : []
1270
+ }
1271
+ };
789
1272
  return betterAuth.betterAuth({
790
1273
  database: drizzle.drizzleAdapter(db, {
791
1274
  provider: "pg",
@@ -865,63 +1348,30 @@ function createAuth(overrides = {}) {
865
1348
  // no password, so better-auth instead requires a session younger than
866
1349
  // `freshAge` (default 1 day). Every user-owned table cascades on delete.
867
1350
  // Impersonation and last-admin guards live in hooks.before below.
868
- deleteUser: { enabled: true }
1351
+ deleteUser: { enabled: (_f = overrides.deleteUser) != null ? _f : true }
869
1352
  },
870
1353
  // Advanced options
871
- advanced: {
1354
+ advanced: __spreadProps(__spreadValues({}, overrides.advanced), {
872
1355
  database: {
873
1356
  generateId: () => cuid2.createId()
874
1357
  }
875
- },
876
- // Every new session row corresponds to a sign-in (credential or OAuth) —
877
- // use that as the "last logged in" signal rather than session updates,
878
- // which also fire on cookie-cache refresh / expiry extension.
1358
+ }),
1359
+ rateLimit: overrides.rateLimit,
879
1360
  databaseHooks: {
1361
+ user: {
1362
+ create: {
1363
+ async after(user, context) {
1364
+ var _a2, _b2, _c2, _d2;
1365
+ 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));
1366
+ }
1367
+ }
1368
+ },
880
1369
  session: {
881
1370
  create: {
882
1371
  async after(session, context) {
883
- var _a, _b, _c, _d;
884
- const impersonatedBy = session.impersonatedBy;
885
- if (impersonatedBy) {
886
- const target = await db.select({ email: users.email }).from(users).where(drizzleOrm.eq(users.id, session.userId)).limit(1);
887
- await logActivity({
888
- userId: impersonatedBy,
889
- action: "impersonation_started",
890
- description: `Admin started impersonating ${(_b = (_a = target[0]) == null ? void 0 : _a.email) != null ? _b : session.userId}`,
891
- metadata: { impersonatedUserId: session.userId }
892
- });
893
- return;
894
- }
895
- try {
896
- await db.update(users).set({ lastLoginAt: /* @__PURE__ */ new Date() }).where(drizzleOrm.eq(users.id, session.userId));
897
- } catch (error) {
898
- console.error("Failed to update lastLoginAt", error);
899
- }
900
- try {
901
- const headers2 = context == null ? void 0 : context.headers;
902
- const ipAddress = getClientIp(headers2);
903
- const userAgent = (_c = headers2 == null ? void 0 : headers2.get("user-agent")) != null ? _c : null;
904
- const referrerUrl = ((_d = context == null ? void 0 : context.getCookie) == null ? void 0 : _d.call(context, LOGIN_REFERRER_COOKIE)) || (headers2 == null ? void 0 : headers2.get("referer")) || null;
905
- const device = parseUserAgent(userAgent);
906
- const geo = lookupGeoLocation(ipAddress);
907
- const [{ count }] = await db.select({ count: drizzleOrm.sql`count(*)` }).from(sessions).where(drizzleOrm.eq(sessions.userId, session.userId));
908
- const isFirstSession = Number(count) <= 1;
909
- await logActivity({
910
- userId: session.userId,
911
- action: "login",
912
- description: isFirstSession ? "New account registered and signed in" : "User logged in",
913
- ipAddress,
914
- userAgent,
915
- referrerUrl,
916
- os: device.os,
917
- browser: device.browser,
918
- deviceType: device.deviceType,
919
- country: geo.country,
920
- city: geo.city
921
- });
922
- } catch (error) {
923
- console.error("Failed to log login activity", error);
924
- }
1372
+ var _a2, _b2, _c2, _d2;
1373
+ await packageSessionCreated(log, session, context);
1374
+ 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));
925
1375
  }
926
1376
  }
927
1377
  }
@@ -935,9 +1385,9 @@ function createAuth(overrides = {}) {
935
1385
  // available together.
936
1386
  hooks: {
937
1387
  before: api.createAuthMiddleware(async (ctx) => {
938
- var _a, _b, _c, _d;
1388
+ var _a2, _b2, _c2, _d2;
939
1389
  if (ctx.path === "/sign-in/email" || ctx.path === "/sign-up/email") {
940
- const fingerprint = (_a = ctx.headers) == null ? void 0 : _a.get(DEVICE_FINGERPRINT_HEADER);
1390
+ const fingerprint = (_a2 = ctx.headers) == null ? void 0 : _a2.get(DEVICE_FINGERPRINT_HEADER);
941
1391
  const ip = getClientIp(ctx.headers);
942
1392
  const throttled = fingerprint && await isDeviceThrottled(fingerprint) || ip && await isDeviceThrottled(`ip:${ip}`, MAX_IP);
943
1393
  if (throttled) {
@@ -947,7 +1397,7 @@ function createAuth(overrides = {}) {
947
1397
  }
948
1398
  }
949
1399
  if (ctx.path === "/sign-in/social") {
950
- if (((_b = ctx.body) == null ? void 0 : _b.provider) === "google") {
1400
+ if (((_b2 = ctx.body) == null ? void 0 : _b2.provider) === "google") {
951
1401
  const flags = await getEffectiveAuthFlags();
952
1402
  if (!flags.google) {
953
1403
  throw new api.APIError("FORBIDDEN", { message: "Google sign-in is currently disabled." });
@@ -969,6 +1419,9 @@ function createAuth(overrides = {}) {
969
1419
  }
970
1420
  return;
971
1421
  }
1422
+ if (ctx.path === "/admin/impersonate-user" && overrides.impersonation === false) {
1423
+ throw new api.APIError("FORBIDDEN", { message: "Impersonation is turned off." });
1424
+ }
972
1425
  if (ctx.path === "/delete-user") {
973
1426
  const current2 = await api.getSessionFromCtx(ctx, { disableCookieCache: true });
974
1427
  if (!current2) return;
@@ -987,34 +1440,35 @@ function createAuth(overrides = {}) {
987
1440
  const current = await api.getSessionFromCtx(ctx, { disableCookieCache: true });
988
1441
  if (current == null ? void 0 : current.session.impersonatedBy) {
989
1442
  const target = await db.select({ email: users.email }).from(users).where(drizzleOrm.eq(users.id, current.session.userId)).limit(1);
990
- await logActivity({
1443
+ await log({
991
1444
  userId: current.session.impersonatedBy,
992
1445
  action: "impersonation_stopped",
993
- description: `Admin stopped impersonating ${(_d = (_c = target[0]) == null ? void 0 : _c.email) != null ? _d : current.session.userId}`,
1446
+ description: `Admin stopped impersonating ${(_d2 = (_c2 = target[0]) == null ? void 0 : _c2.email) != null ? _d2 : current.session.userId}`,
994
1447
  metadata: { impersonatedUserId: current.session.userId }
995
1448
  });
996
1449
  }
997
1450
  }),
998
1451
  after: api.createAuthMiddleware(async (ctx) => {
999
- var _a, _b, _c, _d;
1452
+ var _a2, _b2, _c2, _d2;
1000
1453
  if (ctx.path === "/passkey/verify-registration" || ctx.path === "/passkey/delete-passkey") {
1001
1454
  if (ctx.context.returned instanceof api.APIError) return;
1002
1455
  await notifyPasskeyChange(
1003
1456
  ctx,
1004
- ctx.path === "/passkey/verify-registration" ? "added" : "removed"
1457
+ ctx.path === "/passkey/verify-registration" ? "added" : "removed",
1458
+ log
1005
1459
  );
1006
1460
  return;
1007
1461
  }
1008
1462
  if (ctx.path !== "/sign-in/email" && ctx.path !== "/sign-up/email") return;
1009
- const fingerprint = (_a = ctx.headers) == null ? void 0 : _a.get(DEVICE_FINGERPRINT_HEADER);
1463
+ const fingerprint = (_a2 = ctx.headers) == null ? void 0 : _a2.get(DEVICE_FINGERPRINT_HEADER);
1010
1464
  const ip = getClientIp(ctx.headers);
1011
1465
  const ipKey = ip ? `ip:${ip}` : null;
1012
1466
  if (!fingerprint && !ipKey) return;
1013
1467
  const failed = ctx.context.returned instanceof api.APIError;
1014
- const rawEmail = (_b = ctx.body) == null ? void 0 : _b.email;
1468
+ const rawEmail = (_b2 = ctx.body) == null ? void 0 : _b2.email;
1015
1469
  const meta = {
1016
1470
  ipAddress: ip,
1017
- userAgent: (_d = (_c = ctx.headers) == null ? void 0 : _c.get("user-agent")) != null ? _d : null,
1471
+ userAgent: (_d2 = (_c2 = ctx.headers) == null ? void 0 : _c2.get("user-agent")) != null ? _d2 : null,
1018
1472
  email: typeof rawEmail === "string" ? rawEmail.toLowerCase() : null
1019
1473
  };
1020
1474
  const keys = [fingerprint, ipKey].filter((k) => !!k);
@@ -1024,7 +1478,7 @@ function createAuth(overrides = {}) {
1024
1478
  }
1025
1479
  if (failed) {
1026
1480
  await Promise.all(keys.map((key) => recordDeviceAttempt(key, __spreadProps(__spreadValues({}, meta), { kind: "signin" }))));
1027
- await logFailedLogin(ctx);
1481
+ await logFailedLogin(ctx, log);
1028
1482
  } else {
1029
1483
  await Promise.all(keys.map((key) => clearDeviceThrottle(key)));
1030
1484
  }
@@ -1062,9 +1516,10 @@ function createAuth(overrides = {}) {
1062
1516
  }
1063
1517
  }
1064
1518
  }),
1065
- // TOTP second factor + encrypted backup codes. `issuer` is the label
1066
- // shown in the user's authenticator app.
1067
- plugins.twoFactor({ issuer: config.APP_NAME }),
1519
+ // TOTP second factor + encrypted backup codes (see lib/two-factor.ts).
1520
+ // Listed individually, not spread: see the note on the spread below.
1521
+ twoFactorPlugin,
1522
+ twoFactorExtras,
1068
1523
  // WebAuthn passkeys (Touch ID / Windows Hello / security keys) as a
1069
1524
  // passwordless sign-in method. rpID must be the bare host and origin
1070
1525
  // the full URL — both derived from baseURL above.
@@ -1076,7 +1531,9 @@ function createAuth(overrides = {}) {
1076
1531
  // checks to see if oneTap is enabled and if google provider is available, then add the oneTap plugin.
1077
1532
  // Keep this spread last: a leading spread turns `plugins` from a tuple into a plain
1078
1533
  // array and better-auth 1.7 then drops plugin fields (e.g. session.impersonatedBy).
1079
- ...config.AUTH_ENABLE_ONE_TAP && Boolean(socialProviders.google) ? [plugins.oneTap()] : []
1534
+ ...config.AUTH_ENABLE_ONE_TAP && Boolean(socialProviders.google) ? [plugins.oneTap()] : [],
1535
+ appHooks,
1536
+ ...(_g = overrides.plugins) != null ? _g : []
1080
1537
  ]
1081
1538
  });
1082
1539
  }