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

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