@xk2800/nextjs-template 0.7.2-beta.7 → 0.7.2-beta.8

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 (126) hide show
  1. package/README.md +1 -0
  2. package/components/auth/forms/signup-form.tsx +3 -0
  3. package/components/dashboard/admin/activity-logs/admin-activity-logs-table.tsx +1 -1
  4. package/components/dashboard/admin/users/impersonation-tab.tsx +1 -1
  5. package/components/dashboard/layout/app-sidebar.tsx +7 -2
  6. package/components/dashboard/layout/mobile-nav.tsx +95 -0
  7. package/components/dashboard/layout/top-nav.tsx +14 -33
  8. package/components/dashboard/settings/activity-logs-card.tsx +1 -1
  9. package/dist/activity/logger.d.mts +2 -1
  10. package/dist/activity/logger.d.ts +2 -1
  11. package/dist/activity/logger.js +64 -13
  12. package/dist/activity/logger.js.map +1 -1
  13. package/dist/activity/logger.mjs +4 -4
  14. package/dist/activity/queries.d.mts +25 -18
  15. package/dist/activity/queries.d.ts +25 -18
  16. package/dist/activity/queries.js +73 -20
  17. package/dist/activity/queries.js.map +1 -1
  18. package/dist/activity/queries.mjs +15 -13
  19. package/dist/activity/queries.mjs.map +1 -1
  20. package/dist/admin/queries.d.mts +2 -1
  21. package/dist/admin/queries.d.ts +2 -1
  22. package/dist/admin/queries.js +44 -13
  23. package/dist/admin/queries.js.map +1 -1
  24. package/dist/admin/queries.mjs +7 -7
  25. package/dist/admin/queries.mjs.map +1 -1
  26. package/dist/api/feedback.js +247 -224
  27. package/dist/api/feedback.js.map +1 -1
  28. package/dist/api/feedback.mjs +14 -12
  29. package/dist/api/feedback.mjs.map +1 -1
  30. package/dist/api/marketing.js +262 -239
  31. package/dist/api/marketing.js.map +1 -1
  32. package/dist/api/marketing.mjs +14 -23
  33. package/dist/api/marketing.mjs.map +1 -1
  34. package/dist/auth/helpers.d.mts +54 -12
  35. package/dist/auth/helpers.d.ts +54 -12
  36. package/dist/auth/helpers.js +276 -242
  37. package/dist/auth/helpers.js.map +1 -1
  38. package/dist/auth/helpers.mjs +9 -9
  39. package/dist/auth/index.d.mts +68 -47
  40. package/dist/auth/index.d.ts +68 -47
  41. package/dist/auth/index.js +242 -221
  42. package/dist/auth/index.js.map +1 -1
  43. package/dist/auth/index.mjs +8 -8
  44. package/dist/auth-client/index.d.mts +1215 -2527
  45. package/dist/auth-client/index.d.ts +1215 -2527
  46. package/dist/auth-client/index.js +37 -3
  47. package/dist/auth-client/index.js.map +1 -1
  48. package/dist/auth-client/index.mjs +19 -3
  49. package/dist/auth-client/index.mjs.map +1 -1
  50. package/dist/{chunk-M6Y2XNJC.mjs → chunk-3BH6BVBQ.mjs} +16 -6
  51. package/dist/chunk-3BH6BVBQ.mjs.map +1 -0
  52. package/dist/chunk-D56ENLSX.mjs +6 -0
  53. package/dist/chunk-D56ENLSX.mjs.map +1 -0
  54. package/dist/{chunk-HUEDEAY3.mjs → chunk-DCPVEZS7.mjs} +14 -4
  55. package/dist/chunk-DCPVEZS7.mjs.map +1 -0
  56. package/dist/{chunk-J5XRJ2GW.mjs → chunk-DWLMCMXF.mjs} +4 -4
  57. package/dist/{chunk-J5XRJ2GW.mjs.map → chunk-DWLMCMXF.mjs.map} +1 -1
  58. package/dist/{chunk-AOSJUQQG.mjs → chunk-EXMUANQ3.mjs} +4 -4
  59. package/dist/{chunk-AOSJUQQG.mjs.map → chunk-EXMUANQ3.mjs.map} +1 -1
  60. package/dist/{chunk-NOFQCVHC.mjs → chunk-IH6CMZIN.mjs} +195 -215
  61. package/dist/chunk-IH6CMZIN.mjs.map +1 -0
  62. package/dist/chunk-LADVCLEQ.mjs +43 -0
  63. package/dist/chunk-LADVCLEQ.mjs.map +1 -0
  64. package/dist/{chunk-TMANA7KL.mjs → chunk-NJBRKKLK.mjs} +9 -6
  65. package/dist/chunk-NJBRKKLK.mjs.map +1 -0
  66. package/dist/{chunk-JRDMU6I2.mjs → chunk-QDUPSU5O.mjs} +3 -3
  67. package/dist/chunk-QDUPSU5O.mjs.map +1 -0
  68. package/dist/{chunk-2BKXG4MG.mjs → chunk-S23GC776.mjs} +38 -27
  69. package/dist/chunk-S23GC776.mjs.map +1 -0
  70. package/dist/{chunk-CRDC62BU.mjs → chunk-TIR7KHXL.mjs} +3 -3
  71. package/dist/{chunk-CRDC62BU.mjs.map → chunk-TIR7KHXL.mjs.map} +1 -1
  72. package/dist/{chunk-JSB36AY6.mjs → chunk-ZOQHHFYA.mjs} +7 -4
  73. package/dist/chunk-ZOQHHFYA.mjs.map +1 -0
  74. package/dist/config/env.d.mts +3 -0
  75. package/dist/config/env.d.ts +3 -0
  76. package/dist/config/env.js +12 -2
  77. package/dist/config/env.js.map +1 -1
  78. package/dist/config/env.mjs +1 -1
  79. package/dist/db/index.d.mts +3 -7
  80. package/dist/db/index.d.ts +3 -7
  81. package/dist/db/index.js +60 -11
  82. package/dist/db/index.js.map +1 -1
  83. package/dist/db/index.mjs +3 -3
  84. package/dist/db/schema.d.mts +1 -1
  85. package/dist/db/schema.d.ts +1 -1
  86. package/dist/db/schema.js +13 -3
  87. package/dist/db/schema.js.map +1 -1
  88. package/dist/db/schema.mjs +1 -1
  89. package/dist/errors.d.mts +2 -1
  90. package/dist/errors.d.ts +2 -1
  91. package/dist/errors.js +60 -11
  92. package/dist/errors.js.map +1 -1
  93. package/dist/errors.mjs +4 -4
  94. package/dist/marketing/index.d.mts +4 -3
  95. package/dist/marketing/index.d.ts +4 -3
  96. package/dist/marketing/index.js +12 -2
  97. package/dist/marketing/index.js.map +1 -1
  98. package/dist/marketing/index.mjs +3 -3
  99. package/dist/{schema-DzC5zdOq.d.mts → schema-BujGgvAy.d.mts} +35 -2
  100. package/dist/{schema-DzC5zdOq.d.ts → schema-BujGgvAy.d.ts} +35 -2
  101. package/dist/sessions/queries.js +60 -11
  102. package/dist/sessions/queries.js.map +1 -1
  103. package/dist/sessions/queries.mjs +3 -3
  104. package/dist/settings/queries.d.mts +3 -2
  105. package/dist/settings/queries.d.ts +3 -2
  106. package/dist/settings/queries.js +46 -12
  107. package/dist/settings/queries.js.map +1 -1
  108. package/dist/settings/queries.mjs +4 -4
  109. package/dist/users/queries.d.mts +24 -19
  110. package/dist/users/queries.d.ts +24 -19
  111. package/dist/users/queries.js +48 -13
  112. package/dist/users/queries.js.map +1 -1
  113. package/dist/users/queries.mjs +8 -6
  114. package/dist/users/queries.mjs.map +1 -1
  115. package/lib/auth/client.ts +22 -2
  116. package/lib/utils/request-info.ts +7 -3
  117. package/package.json +62 -58
  118. package/dist/chunk-2BKXG4MG.mjs.map +0 -1
  119. package/dist/chunk-HUEDEAY3.mjs.map +0 -1
  120. package/dist/chunk-JRDMU6I2.mjs.map +0 -1
  121. package/dist/chunk-JSB36AY6.mjs.map +0 -1
  122. package/dist/chunk-M6Y2XNJC.mjs.map +0 -1
  123. package/dist/chunk-NOFQCVHC.mjs.map +0 -1
  124. package/dist/chunk-RLZ7F7ZY.mjs +0 -30
  125. package/dist/chunk-RLZ7F7ZY.mjs.map +0 -1
  126. package/dist/chunk-TMANA7KL.mjs.map +0 -1
@@ -44,8 +44,13 @@ var __spreadValues = (a, b) => {
44
44
  return a;
45
45
  };
46
46
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
47
- var __esm = (fn, res) => function __init() {
48
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
47
+ var __esm = (fn, res, err) => function __init() {
48
+ if (err) throw err[0];
49
+ try {
50
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
51
+ } catch (e) {
52
+ throw err = [e], e;
53
+ }
49
54
  };
50
55
  var __export = (target, all) => {
51
56
  for (var name in all)
@@ -287,7 +292,10 @@ var sessions = pgCore.pgTable("session", {
287
292
  // Set by better-auth's admin plugin while this session is an admin
288
293
  // impersonating another user; holds the impersonating admin's user id.
289
294
  impersonatedBy: pgCore.text("impersonatedBy")
290
- });
295
+ }, (table) => [
296
+ // Read by userId on every login (session count), ban/delete and the admin sessions view.
297
+ pgCore.index("session_user_idx").on(table.userId)
298
+ ]);
291
299
  var accounts = pgCore.pgTable("account", {
292
300
  id: pgCore.text("id").notNull().primaryKey().$defaultFn(() => cuid2.createId()),
293
301
  accountId: pgCore.text("accountId").notNull(),
@@ -336,7 +344,10 @@ var verifications = pgCore.pgTable("verification", {
336
344
  });
337
345
  var activityLogs = pgCore.pgTable("activity_log", {
338
346
  id: pgCore.text("id").notNull().primaryKey().$defaultFn(() => cuid2.createId()),
339
- userId: pgCore.text("userId").notNull().references(() => users.id, { onDelete: "cascade" }),
347
+ // SET NULL, not cascade: deleting an admin must not erase the audit trail of
348
+ // what they did. actorEmail keeps who it was once the user row is gone.
349
+ userId: pgCore.text("userId").references(() => users.id, { onDelete: "set null" }),
350
+ actorEmail: pgCore.text("actorEmail"),
340
351
  action: ActivityActionEnum("action").notNull(),
341
352
  description: pgCore.text("description").notNull(),
342
353
  ipAddress: pgCore.text("ipAddress"),
@@ -352,7 +363,11 @@ var activityLogs = pgCore.pgTable("activity_log", {
352
363
  country: pgCore.text("country"),
353
364
  city: pgCore.text("city"),
354
365
  createdAt: pgCore.timestamp("createdAt").notNull().defaultNow()
355
- });
366
+ }, (table) => [
367
+ // Per-user history, and the admin log's newest-first ordering.
368
+ pgCore.index("activity_log_user_created_idx").on(table.userId, table.createdAt),
369
+ pgCore.index("activity_log_created_idx").on(table.createdAt)
370
+ ]);
356
371
  var deviceFingerprints = pgCore.pgTable("device_fingerprint", {
357
372
  id: pgCore.text("id").notNull().primaryKey().$defaultFn(() => cuid2.createId()),
358
373
  userId: pgCore.text("userId").notNull().references(() => users.id, { onDelete: "cascade" }),
@@ -467,7 +482,9 @@ var envSchema = zod.z.object({
467
482
  RESEND_MARKETING_SEGMENT_ID: zod.z.string().default(""),
468
483
  // Sender for every transactional email. Must be on a domain verified in
469
484
  // your Resend account.
470
- EMAIL_FROM: zod.z.string().default("Acme <onboarding@xavierkhew.xyz>"),
485
+ // Resend's shared sandbox sender: works without a verified domain but only
486
+ // delivers to your own Resend account email. Set your verified domain for real use.
487
+ EMAIL_FROM: zod.z.string().default("Acme <onboarding@resend.dev>"),
471
488
  // Display name for this deployment — shown as the authenticator-app label
472
489
  // (2FA issuer) and the passkey relying-party name. Consuming projects set
473
490
  // this in their own .env; defaults to the template name.
@@ -477,6 +494,9 @@ var envSchema = zod.z.object({
477
494
  // a comma-separated list and sends through Resend (needs RESEND_API_KEY).
478
495
  FEEDBACK_DISCORD_WEBHOOK_URL: zod.z.string().default(""),
479
496
  FEEDBACK_EMAIL: zod.z.string().default(""),
497
+ // Seconds between feedback messages per user (default 30, 0 = off). Read
498
+ // straight from process.env in lib/feedback/route.ts; listed here for docs.
499
+ FEEDBACK_COOLDOWN_SECONDS: zod.z.string().default("30"),
480
500
  // Web Push (example, see lib/push.ts). Generate keys with
481
501
  // `bunx web-push generate-vapid-keys`. Blank = the notifications card is hidden.
482
502
  // The public key is also read in the browser as NEXT_PUBLIC_VAPID_PUBLIC_KEY.
@@ -493,7 +513,12 @@ var envSchema = zod.z.object({
493
513
  DB_DRIVER: zod.z.enum(["pg", "neon"]).default("pg"),
494
514
  // Only relevant when DB_DRIVER=pg — whether the target Postgres server has SSL
495
515
  // enabled. Self-hosted Postgres (e.g. via Docker/Dokploy) typically does not.
496
- DATABASE_SSL: zod.z.string().default("false").transform((val) => val === "true")
516
+ DATABASE_SSL: zod.z.string().default("false").transform((val) => val === "true"),
517
+ // With DATABASE_SSL=true the server certificate is verified. Set the CA (PEM,
518
+ // "\n" for newlines) for a self-signed or private CA; DATABASE_SSL_INSECURE=true
519
+ // skips verification (encrypts only). Both are read in config/pg-ssl.ts.
520
+ DATABASE_SSL_CA: zod.z.string().default(""),
521
+ DATABASE_SSL_INSECURE: zod.z.string().default("false")
497
522
  });
498
523
 
499
524
  // config/env.ts
@@ -507,24 +532,47 @@ if (!results.success) {
507
532
  }
508
533
  var config = results.data;
509
534
 
535
+ // config/pg-ssl.ts
536
+ function pgSslOptions() {
537
+ var _a;
538
+ if (process.env.DATABASE_SSL_INSECURE === "true") return { rejectUnauthorized: false };
539
+ const ca = (_a = process.env.DATABASE_SSL_CA) == null ? void 0 : _a.replace(/\\n/g, "\n");
540
+ return __spreadValues({ rejectUnauthorized: true }, ca ? { ca } : {});
541
+ }
542
+
510
543
  // server/db/index.ts
511
544
  var db;
512
545
  if (config.DB_DRIVER === "pg") {
513
546
  const pool = new pg.Pool({
514
547
  connectionString: config.DATABASE_URL,
515
- ssl: config.DATABASE_SSL ? { rejectUnauthorized: false } : void 0
548
+ ssl: config.DATABASE_SSL ? pgSslOptions() : void 0,
549
+ // pg waits forever by default; a hung DB would otherwise freeze every request (proxy reads settings).
550
+ connectionTimeoutMillis: 5e3,
551
+ query_timeout: 15e3
552
+ // roomy enough for the 10k-row exports
516
553
  });
517
554
  db = nodePostgres.drizzle(pool, {
518
555
  schema: schema_exports,
519
- logger: true
556
+ logger: process.env.NODE_ENV === "development"
520
557
  });
521
558
  console.log("\u{1F7E1} Using PostgreSQL (pg) driver");
522
- } else if (config.DB_DRIVER === "neon") {
523
- const sql4 = serverless.neon(config.DATABASE_URL);
524
- db = neonHttp.drizzle(sql4, { schema: schema_exports, logger: true });
525
- console.log("\u{1F7E2} Using Neon (HTTP) driver");
526
559
  } else {
527
- console.log("Database connection not established, unknown DB_DRIVER:", config.DB_DRIVER);
560
+ serverless.neonConfig.fetchFunction = (url, init) => fetch(url, __spreadProps(__spreadValues({}, init), { signal: AbortSignal.timeout(15e3) }));
561
+ const sql6 = serverless.neon(config.DATABASE_URL);
562
+ db = neonHttp.drizzle(sql6, { schema: schema_exports, logger: process.env.NODE_ENV === "development" });
563
+ console.log("\u{1F7E2} Using Neon (HTTP) driver");
564
+ }
565
+
566
+ // node_modules/@better-auth/utils/dist/bytes.mjs
567
+ function toBufferSource(data) {
568
+ if (typeof data === "string") return new TextEncoder().encode(data);
569
+ if (!ArrayBuffer.isView(data)) return data;
570
+ if (data.buffer instanceof ArrayBuffer) return data;
571
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength).slice();
572
+ }
573
+ function toUint8Array(data) {
574
+ if (typeof data === "string") return new TextEncoder().encode(data);
575
+ return new Uint8Array(data);
528
576
  }
529
577
 
530
578
  // node_modules/@better-auth/utils/dist/base32.mjs
@@ -533,9 +581,7 @@ function getAlphabet(hex2) {
533
581
  }
534
582
  function createDecodeMap(alphabet) {
535
583
  const decodeMap = /* @__PURE__ */ new Map();
536
- for (let i = 0; i < alphabet.length; i++) {
537
- decodeMap.set(alphabet[i], i);
538
- }
584
+ for (let i = 0; i < alphabet.length; i++) decodeMap.set(alphabet[i], i);
539
585
  return decodeMap;
540
586
  }
541
587
  function base32Encode(data, alphabet, padding) {
@@ -550,9 +596,7 @@ function base32Encode(data, alphabet, padding) {
550
596
  result += alphabet[buffer >> shift & 31];
551
597
  }
552
598
  }
553
- if (shift > 0) {
554
- result += alphabet[buffer << 5 - shift & 31];
555
- }
599
+ if (shift > 0) result += alphabet[buffer << 5 - shift & 31];
556
600
  if (padding) {
557
601
  const padCount = (8 - result.length % 8) % 8;
558
602
  result += "=".repeat(padCount);
@@ -565,12 +609,9 @@ function base32Decode(data, alphabet) {
565
609
  let buffer = 0;
566
610
  let bitsCollected = 0;
567
611
  for (const char of data) {
568
- if (char === "=")
569
- break;
612
+ if (char === "=") break;
570
613
  const value = decodeMap.get(char);
571
- if (value === void 0) {
572
- throw new Error(`Invalid Base32 character: ${char}`);
573
- }
614
+ if (value === void 0) throw new Error(`Invalid Base32 character: ${char}`);
574
615
  buffer = buffer << 5 | value;
575
616
  bitsCollected += 5;
576
617
  while (bitsCollected >= 8) {
@@ -582,68 +623,34 @@ function base32Decode(data, alphabet) {
582
623
  }
583
624
  var base32 = {
584
625
  /**
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
- */
626
+ * Encodes data into a Base32 string.
627
+ * @param data - The data to encode (ArrayBuffer, number-based TypedArray, or string).
628
+ * @param options - Encoding options.
629
+ * @returns The Base32 encoded string.
630
+ */
590
631
  encode(data, options = {}) {
591
632
  var _a;
592
633
  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);
634
+ return base32Encode(toUint8Array(data), alphabet, (_a = options.padding) != null ? _a : true);
595
635
  },
596
636
  /**
597
- * Decodes a Base32 string into a Uint8Array.
598
- * @param data - The Base32 encoded string or ArrayBuffer/TypedArray.
599
- * @returns The decoded Uint8Array.
600
- */
637
+ * Decodes a Base32 string into a Uint8Array.
638
+ * @param data - The Base32 encoded string or ArrayBuffer/TypedArray.
639
+ * @returns The decoded Uint8Array.
640
+ */
601
641
  decode(data) {
602
- if (typeof data !== "string") {
603
- data = new TextDecoder().decode(data);
604
- }
642
+ if (typeof data !== "string") data = new TextDecoder().decode(data);
605
643
  const alphabet = getAlphabet();
606
644
  return base32Decode(data, alphabet);
607
645
  }
608
646
  };
609
647
 
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
- };
648
+ // node_modules/@better-auth/utils/dist/index.mjs
649
+ function getWebcryptoSubtle() {
650
+ const cr = typeof globalThis !== "undefined" && globalThis.crypto;
651
+ if (cr && typeof cr.subtle === "object" && cr.subtle != null) return cr.subtle;
652
+ throw new Error("crypto.subtle must be defined");
653
+ }
647
654
 
648
655
  // node_modules/@better-auth/utils/dist/base64.mjs
649
656
  function getAlphabet2(urlSafe) {
@@ -661,9 +668,7 @@ function base64Encode(data, alphabet, padding) {
661
668
  result += alphabet[buffer >> shift & 63];
662
669
  }
663
670
  }
664
- if (shift > 0) {
665
- result += alphabet[buffer << 6 - shift & 63];
666
- }
671
+ if (shift > 0) result += alphabet[buffer << 6 - shift & 63];
667
672
  if (padding) {
668
673
  const padCount = (4 - result.length % 4) % 4;
669
674
  result += "=".repeat(padCount);
@@ -672,19 +677,14 @@ function base64Encode(data, alphabet, padding) {
672
677
  }
673
678
  function base64Decode(data, alphabet) {
674
679
  const decodeMap = /* @__PURE__ */ new Map();
675
- for (let i = 0; i < alphabet.length; i++) {
676
- decodeMap.set(alphabet[i], i);
677
- }
680
+ for (let i = 0; i < alphabet.length; i++) decodeMap.set(alphabet[i], i);
678
681
  const result = [];
679
682
  let buffer = 0;
680
683
  let bitsCollected = 0;
681
684
  for (const char of data) {
682
- if (char === "=")
683
- break;
685
+ if (char === "=") break;
684
686
  const value = decodeMap.get(char);
685
- if (value === void 0) {
686
- throw new Error(`Invalid Base64 character: ${char}`);
687
- }
687
+ if (value === void 0) throw new Error(`Invalid Base64 character: ${char}`);
688
688
  buffer = buffer << 6 | value;
689
689
  bitsCollected += 6;
690
690
  if (bitsCollected >= 8) {
@@ -698,15 +698,11 @@ var base64 = {
698
698
  encode(data, options = {}) {
699
699
  var _a;
700
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);
701
+ return base64Encode(toUint8Array(data), alphabet, (_a = options.padding) != null ? _a : true);
703
702
  },
704
703
  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);
704
+ if (typeof data !== "string") data = new TextDecoder().decode(data);
705
+ const alphabet = getAlphabet2(data.includes("-") || data.includes("_"));
710
706
  return base64Decode(data, alphabet);
711
707
  }
712
708
  };
@@ -714,152 +710,142 @@ var base64Url = {
714
710
  encode(data, options = {}) {
715
711
  var _a;
716
712
  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);
713
+ return base64Encode(toUint8Array(data), alphabet, (_a = options.padding) != null ? _a : true);
719
714
  },
720
715
  decode(data) {
721
- const urlSafe = data.includes("-") || data.includes("_");
722
- const alphabet = getAlphabet2(urlSafe);
723
- return base64Decode(data, alphabet);
716
+ return base64Decode(data, getAlphabet2(data.includes("-") || data.includes("_")));
724
717
  }
725
718
  };
726
719
 
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");
720
+ // node_modules/@noble/hashes/utils.js
721
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
722
+ // @ts-ignore
723
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
724
+ ))();
725
+ function asciiToBase16(ch) {
726
+ return ch >= 48 && ch <= 57 ? ch - 48 : ch >= 65 && ch <= 70 ? ch - (65 - 10) : ch >= 97 && ch <= 102 ? ch - (97 - 10) : void 0;
727
+ }
728
+ function hexToBytes(hex2) {
729
+ if (typeof hex2 !== "string")
730
+ throw new TypeError("hex string expected, got " + typeof hex2);
731
+ if (hasHexBuiltin) {
732
+ try {
733
+ return Uint8Array.fromHex(hex2);
734
+ } catch (error) {
735
+ if (error instanceof SyntaxError)
736
+ throw new RangeError(error.message);
737
+ throw error;
738
+ }
739
+ }
740
+ const hl = hex2.length;
741
+ const al = hl / 2;
742
+ if (hl % 2)
743
+ throw new RangeError("hex string expected, got unpadded hex of length " + hl);
744
+ const array = new Uint8Array(al);
745
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
746
+ const n1 = asciiToBase16(hex2.charCodeAt(hi));
747
+ const n2 = asciiToBase16(hex2.charCodeAt(hi + 1));
748
+ if (n1 === void 0 || n2 === void 0) {
749
+ const char = hex2[hi] + hex2[hi + 1];
750
+ throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
751
+ }
752
+ array[ai] = n1 * 16 + n2;
753
+ }
754
+ return array;
733
755
  }
734
756
 
757
+ // node_modules/@better-auth/utils/dist/hex.mjs
758
+ var toBytes = (data) => hexToBytes(data);
759
+ var hex = {
760
+ encode: (data) => {
761
+ const buffer = toUint8Array(data);
762
+ if (buffer.byteLength === 0) return "";
763
+ let result = "";
764
+ for (const byte of buffer) result += byte.toString(16).padStart(2, "0");
765
+ return result;
766
+ },
767
+ decode: (data) => {
768
+ if (!data) return "";
769
+ if (typeof data === "string") return new TextDecoder().decode(toBytes(data));
770
+ return new TextDecoder().decode(data);
771
+ },
772
+ toBytes
773
+ };
774
+
735
775
  // node_modules/@better-auth/utils/dist/hmac.mjs
736
776
  var createHMAC = (algorithm = "SHA-256", encoding = "none") => {
737
- const hmac = {
777
+ const hmac2 = {
738
778
  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
- );
779
+ return getWebcryptoSubtle().importKey("raw", toBufferSource(key), {
780
+ name: "HMAC",
781
+ hash: { name: algorithm }
782
+ }, false, [keyUsage]);
746
783
  },
747
784
  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
- }
785
+ if (typeof hmacKey === "string") hmacKey = await hmac2.importKey(hmacKey, "sign");
786
+ const signature = await getWebcryptoSubtle().sign("HMAC", hmacKey, toBufferSource(data));
787
+ if (encoding === "hex") return hex.encode(signature);
788
+ if (encoding === "base64") return base64.encode(signature);
789
+ if (encoding === "base64url" || encoding === "base64urlnopad") return base64Url.encode(signature, { padding: encoding !== "base64urlnopad" });
764
790
  return signature;
765
791
  },
766
792
  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
- );
793
+ if (typeof hmacKey === "string") hmacKey = await hmac2.importKey(hmacKey, "verify");
794
+ if (encoding === "hex") signature = typeof signature === "string" ? hex.toBytes(signature) : signature;
795
+ if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") signature = await base64.decode(signature);
796
+ return getWebcryptoSubtle().verify("HMAC", hmacKey, toBufferSource(signature), toBufferSource(data));
782
797
  }
783
798
  };
784
- return hmac;
799
+ return hmac2;
785
800
  };
786
801
 
787
802
  // node_modules/@better-auth/utils/dist/otp.mjs
788
803
  var defaultPeriod = 30;
789
804
  var defaultDigits = 6;
805
+ var hmac = createHMAC("SHA-1");
790
806
  function constantTimeEqualOTP(input, expected) {
791
807
  let difference = input.length ^ expected.length;
792
- for (let i = 0; i < expected.length; i++) {
793
- difference |= input.charCodeAt(i) ^ expected.charCodeAt(i);
794
- }
808
+ for (let i = 0; i < expected.length; i++) difference |= input.charCodeAt(i) ^ expected.charCodeAt(i);
795
809
  return difference === 0;
796
810
  }
797
- async function generateHOTP(secret, {
798
- counter,
799
- digits,
800
- hash = "SHA-1"
801
- }) {
811
+ async function generateHOTP(key, { counter, digits }) {
802
812
  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);
813
+ if (_digits < 1 || _digits > 8) throw new TypeError("Digits must be between 1 and 8");
814
+ const buffer = /* @__PURE__ */ new ArrayBuffer(8);
807
815
  new DataView(buffer).setBigUint64(0, BigInt(counter), false);
808
816
  const bytes = new Uint8Array(buffer);
809
- const hmacResult = new Uint8Array(await createHMAC(hash).sign(secret, bytes));
817
+ const signature = await hmac.sign(key, bytes);
818
+ const hmacResult = new Uint8Array(signature);
810
819
  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");
820
+ return (((hmacResult[offset] & 127) << 24 | (hmacResult[offset + 1] & 255) << 16 | (hmacResult[offset + 2] & 255) << 8 | hmacResult[offset + 3] & 255) % 10 ** _digits).toString().padStart(_digits, "0");
814
821
  }
815
- async function generateTOTP(secret, options) {
822
+ async function generateTOTP(key, options) {
816
823
  var _a, _b;
817
824
  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 });
825
+ const milliseconds = ((_b = options == null ? void 0 : options.period) != null ? _b : defaultPeriod) * 1e3;
826
+ return await generateHOTP(key, {
827
+ counter: Math.floor(Date.now() / milliseconds),
828
+ digits
829
+ });
822
830
  }
823
- async function verifyTOTP(otp, {
824
- window = 1,
825
- digits = defaultDigits,
826
- secret,
827
- period = defaultPeriod
828
- }) {
831
+ async function verifyTOTP(otp, { window = 1, digits = defaultDigits, key, period = defaultPeriod }) {
829
832
  const milliseconds = period * 1e3;
830
833
  const counter = Math.floor(Date.now() / milliseconds);
831
834
  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
- }
835
+ for (let i = -window; i <= window; i++) matched = constantTimeEqualOTP(otp, await generateHOTP(key, {
836
+ counter: counter + i,
837
+ digits
838
+ })) || matched;
839
839
  return matched;
840
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}`;
841
+ function generateQRCode({ issuer, account, secret, digits = defaultDigits, period = defaultPeriod }) {
842
+ const baseURI = `otpauth://totp/${encodeURIComponent(issuer)}:${encodeURIComponent(account)}`;
851
843
  const params = new URLSearchParams({
852
- secret: base32.encode(secret, {
853
- padding: false
854
- }),
844
+ secret: base32.encode(secret, { padding: false }),
855
845
  issuer
856
846
  });
857
- if (digits !== void 0) {
858
- params.set("digits", digits.toString());
859
- }
860
- if (period !== void 0) {
861
- params.set("period", period.toString());
862
- }
847
+ if (digits !== void 0) params.set("digits", digits.toString());
848
+ if (period !== void 0) params.set("period", period.toString());
863
849
  return `${baseURI}?${params.toString()}`;
864
850
  }
865
851
  var createOTP = (secret, opts) => {
@@ -867,10 +853,34 @@ var createOTP = (secret, opts) => {
867
853
  const digits = (_a = void 0 ) != null ? _a : defaultDigits;
868
854
  const period = (_b = void 0 ) != null ? _b : defaultPeriod;
869
855
  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 })
856
+ hotp: async (counter) => {
857
+ return generateHOTP(await hmac.importKey(secret, "sign"), {
858
+ counter,
859
+ digits
860
+ });
861
+ },
862
+ totp: async () => {
863
+ return generateTOTP(await hmac.importKey(secret, "sign"), {
864
+ digits,
865
+ period
866
+ });
867
+ },
868
+ verify: async (otp, options) => {
869
+ return verifyTOTP(otp, __spreadValues({
870
+ key: await hmac.importKey(secret, "sign"),
871
+ digits,
872
+ period
873
+ }, options));
874
+ },
875
+ url: (issuer, account) => {
876
+ return generateQRCode({
877
+ issuer,
878
+ account,
879
+ secret,
880
+ digits,
881
+ period
882
+ });
883
+ }
874
884
  };
875
885
  };
876
886
 
@@ -947,6 +957,8 @@ async function logActivity({
947
957
  try {
948
958
  await db.insert(activityLogs).values({
949
959
  userId,
960
+ // Snapshot the email at write time; survives deletion of the user row.
961
+ actorEmail: drizzleOrm.sql`(select "email" from "user" where "id" = ${userId})`,
950
962
  action,
951
963
  description,
952
964
  ipAddress: ipAddress || null,
@@ -967,7 +979,7 @@ var countryNames = new Intl.DisplayNames(["en"], { type: "region" });
967
979
  function getClientIp(headers) {
968
980
  var _a;
969
981
  const forwardedFor = headers == null ? void 0 : headers.get("x-forwarded-for");
970
- if (forwardedFor) return forwardedFor.split(",")[0].trim();
982
+ if (forwardedFor) return forwardedFor.split(",").at(-1).trim();
971
983
  return (_a = headers == null ? void 0 : headers.get("x-real-ip")) != null ? _a : null;
972
984
  }
973
985
  function parseUserAgent(userAgent) {
@@ -1010,6 +1022,16 @@ function formatLocation({ country, city }) {
1010
1022
  var LOGIN_REFERRER_COOKIE = "login_referrer";
1011
1023
  var DEVICE_FINGERPRINT_HEADER = "x-device-fingerprint";
1012
1024
 
1025
+ // lib/auth/base-url.ts
1026
+ function getBaseUrl() {
1027
+ const url = process.env.BETTER_AUTH_URL || process.env.NEXTAUTH_URL || process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000";
1028
+ return url.replace(/\/+$/, "");
1029
+ }
1030
+ function otherActiveAdminExists(excludeIds) {
1031
+ const ids = drizzleOrm.sql.join(excludeIds.map((id) => drizzleOrm.sql`${id}`), drizzleOrm.sql`, `);
1032
+ return drizzleOrm.sql`(select count(*) from (select ${users.id} as id from ${users} where ${users.role} = 'admin' and ${users.banned} = false for update) a where a.id not in (${ids})) > 0`;
1033
+ }
1034
+
1013
1035
  // lib/auth/throttle-limits.ts
1014
1036
  var WINDOW_MS = 15 * 60 * 1e3;
1015
1037
  var MAX = 10;
@@ -1045,8 +1067,10 @@ async function recordDeviceAttempt(fingerprint, meta) {
1045
1067
  await db.insert(authThrottle).values(__spreadValues({ fingerprint, count: 1, windowStart: now }, seen)).onConflictDoUpdate({
1046
1068
  target: authThrottle.fingerprint,
1047
1069
  set: __spreadValues({
1048
- count: drizzleOrm.sql`case when ${authThrottle.windowStart} < ${cutoff} then 1 else ${authThrottle.count} + 1 end`,
1049
- windowStart: drizzleOrm.sql`case when ${authThrottle.windowStart} < ${cutoff} then ${now} else ${authThrottle.windowStart} end`
1070
+ // ISO strings, not Dates: pg sends a raw Date as server-local time, which a
1071
+ // tz-less `timestamp` column (stored as UTC) misreads on any non-UTC host.
1072
+ count: drizzleOrm.sql`case when ${authThrottle.windowStart} < ${cutoff.toISOString()} then 1 else ${authThrottle.count} + 1 end`,
1073
+ windowStart: drizzleOrm.sql`case when ${authThrottle.windowStart} < ${cutoff.toISOString()} then ${now.toISOString()} else ${authThrottle.windowStart} end`
1050
1074
  }, seen)
1051
1075
  });
1052
1076
  } catch (error) {
@@ -1065,15 +1089,9 @@ async function pruneStaleRows(now = /* @__PURE__ */ new Date()) {
1065
1089
  console.error("auth-throttle prune failed", error);
1066
1090
  }
1067
1091
  }
1068
- async function clearDeviceThrottle(fingerprint) {
1069
- try {
1070
- await db.delete(authThrottle).where(drizzleOrm.eq(authThrottle.fingerprint, fingerprint));
1071
- } catch (error) {
1072
- console.error("auth-throttle clear failed", error);
1073
- }
1074
- }
1075
1092
  var SETTINGS_ROW_ID = "default";
1076
1093
  var CACHE_TTL_MS = 1e4;
1094
+ var FAILURE_CACHE_TTL_MS = 5e3;
1077
1095
  var cached = null;
1078
1096
  function fallbackSettings() {
1079
1097
  return {
@@ -1116,7 +1134,9 @@ async function getSystemSettings() {
1116
1134
  return value;
1117
1135
  } catch (error) {
1118
1136
  console.error("Failed to load system settings, failing open:", error);
1119
- return fallbackSettings();
1137
+ const value = fallbackSettings();
1138
+ cached = { value, expiresAt: now + FAILURE_CACHE_TTL_MS };
1139
+ return value;
1120
1140
  }
1121
1141
  }
1122
1142
  async function getEffectiveAuthFlags() {
@@ -1185,7 +1205,7 @@ async function notifyPasskeyChange(ctx, action, log) {
1185
1205
  location: formatLocation(lookupGeoLocation(ip)),
1186
1206
  ipAddress: ip || "Unknown",
1187
1207
  when: (/* @__PURE__ */ new Date()).toUTCString(),
1188
- manageUrl: `${process.env.BETTER_AUTH_URL || process.env.NEXTAUTH_URL || process.env.NEXT_PUBLIC_APP_URL || ""}/dashboard/settings`
1208
+ manageUrl: `${getBaseUrl()}/dashboard/settings`
1189
1209
  })
1190
1210
  });
1191
1211
  } catch (error) {
@@ -1260,7 +1280,7 @@ function createAuth(overrides = {}) {
1260
1280
  "No auth provider is enabled \u2014 every social provider is off and emailAndPassword.enabled is false. Enable AUTH_ENABLE_GOOGLE / AUTH_ENABLE_EMAIL_PASSWORD, or pass your own provider via createAuth({ socialProviders: {...} })."
1261
1281
  );
1262
1282
  }
1263
- const baseURL = process.env.NEXTAUTH_URL || process.env.BETTER_AUTH_URL || "http://localhost:3000";
1283
+ const baseURL = getBaseUrl();
1264
1284
  const log = (_a = overrides.logActivity) != null ? _a : logActivity;
1265
1285
  const [twoFactorPlugin, twoFactorExtras] = twoFactorPlugins(baseURL, {
1266
1286
  issuer: config.APP_NAME,
@@ -1394,7 +1414,7 @@ function createAuth(overrides = {}) {
1394
1414
  // available together.
1395
1415
  hooks: {
1396
1416
  before: api.createAuthMiddleware(async (ctx) => {
1397
- var _a2, _b2, _c2, _d2;
1417
+ var _a2, _b2, _c2, _d2, _e2;
1398
1418
  if (ctx.path === "/sign-in/email" || ctx.path === "/sign-up/email") {
1399
1419
  const fingerprint = (_a2 = ctx.headers) == null ? void 0 : _a2.get(DEVICE_FINGERPRINT_HEADER);
1400
1420
  const ip = getClientIp(ctx.headers);
@@ -1428,6 +1448,9 @@ function createAuth(overrides = {}) {
1428
1448
  }
1429
1449
  return;
1430
1450
  }
1451
+ if (ctx.request && ((_c2 = ctx.path) == null ? void 0 : _c2.startsWith("/admin/")) && ctx.path !== "/admin/impersonate-user" && ctx.path !== "/admin/stop-impersonating") {
1452
+ throw new api.APIError("FORBIDDEN", { message: "Use the dashboard to manage users." });
1453
+ }
1431
1454
  if (ctx.path === "/admin/impersonate-user" && overrides.impersonation === false) {
1432
1455
  throw new api.APIError("FORBIDDEN", { message: "Impersonation is turned off." });
1433
1456
  }
@@ -1438,8 +1461,8 @@ function createAuth(overrides = {}) {
1438
1461
  throw new api.APIError("FORBIDDEN", { message: "Stop impersonating before deleting an account." });
1439
1462
  }
1440
1463
  if (current2.user.role === "admin") {
1441
- const [{ count }] = await db.select({ count: drizzleOrm.sql`count(*)` }).from(users).where(drizzleOrm.eq(users.role, "admin"));
1442
- if (Number(count) <= 1) {
1464
+ const [other] = await db.select({ n: drizzleOrm.sql`1` }).from(users).where(otherActiveAdminExists([current2.user.id])).limit(1);
1465
+ if (!other) {
1443
1466
  throw new api.APIError("FORBIDDEN", { message: "You're the only admin. Promote another user to admin first." });
1444
1467
  }
1445
1468
  }
@@ -1452,7 +1475,7 @@ function createAuth(overrides = {}) {
1452
1475
  await log({
1453
1476
  userId: current.session.impersonatedBy,
1454
1477
  action: "impersonation_stopped",
1455
- description: `Admin stopped impersonating ${(_d2 = (_c2 = target[0]) == null ? void 0 : _c2.email) != null ? _d2 : current.session.userId}`,
1478
+ description: `Admin stopped impersonating ${(_e2 = (_d2 = target[0]) == null ? void 0 : _d2.email) != null ? _e2 : current.session.userId}`,
1456
1479
  metadata: { impersonatedUserId: current.session.userId }
1457
1480
  });
1458
1481
  }
@@ -1488,8 +1511,6 @@ function createAuth(overrides = {}) {
1488
1511
  if (failed) {
1489
1512
  await Promise.all(keys.map((key) => recordDeviceAttempt(key, __spreadProps(__spreadValues({}, meta), { kind: "signin" }))));
1490
1513
  await logFailedLogin(ctx, log);
1491
- } else {
1492
- await Promise.all(keys.map((key) => clearDeviceThrottle(key)));
1493
1514
  }
1494
1515
  })
1495
1516
  },