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