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

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