@xk2800/nextjs-template 0.7.1-beta.9 → 0.7.2-beta.1

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