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