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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/components/auth/oneTap.tsx +15 -5
  2. package/components/dashboard/admin/adminActivityLogsTable.tsx +4 -0
  3. package/components/dashboard/admin/adminUsersTable.tsx +154 -34
  4. package/components/dashboard/admin/impersonationLogCard.tsx +2 -2
  5. package/components/dashboard/appSidebar.tsx +2 -2
  6. package/components/dashboard/deleteAccountCard.tsx +31 -4
  7. package/components/dashboard/navStyleToggle.tsx +29 -0
  8. package/components/dashboard/topNav.tsx +95 -0
  9. package/components/email/email-template-banned.tsx +53 -0
  10. package/components/ui/alert-dialog.tsx +1 -1
  11. package/components/ui/avatar.tsx +1 -1
  12. package/components/ui/badge.tsx +4 -2
  13. package/components/ui/calendar.tsx +220 -0
  14. package/components/ui/category-selector.tsx +215 -0
  15. package/components/ui/chart.tsx +374 -0
  16. package/components/ui/column-picker.tsx +140 -0
  17. package/components/ui/command.tsx +184 -0
  18. package/components/ui/data-table.tsx +44 -6
  19. package/components/ui/date-picker-with-presets.tsx +122 -0
  20. package/components/ui/dialog.tsx +1 -1
  21. package/components/ui/disclaimer.tsx +4 -0
  22. package/components/ui/dropdown-menu.tsx +1 -1
  23. package/components/ui/field.tsx +248 -0
  24. package/components/ui/info-tooltip.tsx +53 -0
  25. package/components/ui/input.tsx +10 -1
  26. package/components/ui/label.tsx +1 -1
  27. package/components/ui/month-selector.tsx +194 -0
  28. package/components/ui/navigation-menu.tsx +168 -0
  29. package/components/ui/pagination.tsx +127 -0
  30. package/components/ui/popover.tsx +89 -0
  31. package/components/ui/source-selector.tsx +164 -0
  32. package/components/ui/switch.tsx +3 -3
  33. package/dist/activity/logger.d.mts +3 -1
  34. package/dist/activity/logger.d.ts +3 -1
  35. package/dist/activity/logger.js +20 -0
  36. package/dist/activity/logger.js.map +1 -1
  37. package/dist/activity/logger.mjs +4 -4
  38. package/dist/activity/queries.d.mts +1 -1
  39. package/dist/activity/queries.d.ts +1 -1
  40. package/dist/activity/queries.js +20 -0
  41. package/dist/activity/queries.js.map +1 -1
  42. package/dist/activity/queries.mjs +3 -3
  43. package/dist/admin/queries.js +20 -0
  44. package/dist/admin/queries.js.map +1 -1
  45. package/dist/admin/queries.mjs +3 -3
  46. package/dist/api/feedback.js +527 -70
  47. package/dist/api/feedback.js.map +1 -1
  48. package/dist/api/feedback.mjs +8 -8
  49. package/dist/api/marketing.js +527 -70
  50. package/dist/api/marketing.js.map +1 -1
  51. package/dist/api/marketing.mjs +10 -10
  52. package/dist/auth/helpers.d.mts +3 -3
  53. package/dist/auth/helpers.d.ts +3 -3
  54. package/dist/auth/helpers.js +525 -68
  55. package/dist/auth/helpers.js.map +1 -1
  56. package/dist/auth/helpers.mjs +8 -8
  57. package/dist/auth/index.d.mts +149 -10
  58. package/dist/auth/index.d.ts +149 -10
  59. package/dist/auth/index.js +525 -68
  60. package/dist/auth/index.js.map +1 -1
  61. package/dist/auth/index.mjs +7 -7
  62. package/dist/auth-client/index.d.mts +16 -16
  63. package/dist/auth-client/index.d.ts +16 -16
  64. package/dist/{chunk-ZJMFE5B2.mjs → chunk-4C7JHGT5.mjs} +4 -4
  65. package/dist/{chunk-ZJMFE5B2.mjs.map → chunk-4C7JHGT5.mjs.map} +1 -1
  66. package/dist/{chunk-7F2POZM6.mjs → chunk-4F6KE47S.mjs} +4 -4
  67. package/dist/chunk-4F6KE47S.mjs.map +1 -0
  68. package/dist/{chunk-P2G23JMY.mjs → chunk-A6JXMHOQ.mjs} +5 -5
  69. package/dist/{chunk-P2G23JMY.mjs.map → chunk-A6JXMHOQ.mjs.map} +1 -1
  70. package/dist/{chunk-TKWNEKK6.mjs → chunk-HUEDEAY3.mjs} +8 -2
  71. package/dist/chunk-HUEDEAY3.mjs.map +1 -0
  72. package/dist/{chunk-6Z3WUSDJ.mjs → chunk-JUSU6UZA.mjs} +5 -5
  73. package/dist/{chunk-6Z3WUSDJ.mjs.map → chunk-JUSU6UZA.mjs.map} +1 -1
  74. package/dist/{chunk-TR5XFBTD.mjs → chunk-KA2KMGPY.mjs} +17 -3
  75. package/dist/chunk-KA2KMGPY.mjs.map +1 -0
  76. package/dist/{chunk-OVKVD2HH.mjs → chunk-L242CZ64.mjs} +3 -3
  77. package/dist/{chunk-OVKVD2HH.mjs.map → chunk-L242CZ64.mjs.map} +1 -1
  78. package/dist/{chunk-C6RGN6QA.mjs → chunk-NQELV53D.mjs} +4 -4
  79. package/dist/{chunk-C6RGN6QA.mjs.map → chunk-NQELV53D.mjs.map} +1 -1
  80. package/dist/chunk-VHNGYAIG.mjs +899 -0
  81. package/dist/chunk-VHNGYAIG.mjs.map +1 -0
  82. package/dist/{chunk-6MDQRT6U.mjs → chunk-YH53UPUW.mjs} +4 -4
  83. package/dist/{chunk-6MDQRT6U.mjs.map → chunk-YH53UPUW.mjs.map} +1 -1
  84. package/dist/config/env.d.mts +2 -0
  85. package/dist/config/env.d.ts +2 -0
  86. package/dist/config/env.js +6 -0
  87. package/dist/config/env.js.map +1 -1
  88. package/dist/config/env.mjs +1 -1
  89. package/dist/db/index.d.mts +1 -1
  90. package/dist/db/index.d.ts +1 -1
  91. package/dist/db/index.js +20 -0
  92. package/dist/db/index.js.map +1 -1
  93. package/dist/db/index.mjs +3 -3
  94. package/dist/db/schema.d.mts +1 -1
  95. package/dist/db/schema.d.ts +1 -1
  96. package/dist/db/schema.js +14 -0
  97. package/dist/db/schema.js.map +1 -1
  98. package/dist/db/schema.mjs +1 -1
  99. package/dist/errors.js +20 -0
  100. package/dist/errors.js.map +1 -1
  101. package/dist/errors.mjs +4 -4
  102. package/dist/marketing/index.js +6 -0
  103. package/dist/marketing/index.js.map +1 -1
  104. package/dist/marketing/index.mjs +3 -3
  105. package/dist/{schema-CN_Y6EXv.d.mts → schema-DzC5zdOq.d.mts} +146 -2
  106. package/dist/{schema-CN_Y6EXv.d.ts → schema-DzC5zdOq.d.ts} +146 -2
  107. package/dist/sessions/queries.js +20 -0
  108. package/dist/sessions/queries.js.map +1 -1
  109. package/dist/sessions/queries.mjs +3 -3
  110. package/dist/settings/queries.d.mts +1 -1
  111. package/dist/settings/queries.d.ts +1 -1
  112. package/dist/settings/queries.js +20 -0
  113. package/dist/settings/queries.js.map +1 -1
  114. package/dist/settings/queries.mjs +4 -4
  115. package/dist/users/queries.d.mts +3 -0
  116. package/dist/users/queries.d.ts +3 -0
  117. package/dist/users/queries.js +20 -0
  118. package/dist/users/queries.js.map +1 -1
  119. package/dist/users/queries.mjs +3 -3
  120. package/lib/recalculate-columns.ts +8 -2
  121. package/package.json +28 -18
  122. package/styles/theme.css +6 -0
  123. package/dist/chunk-7F2POZM6.mjs.map +0 -1
  124. package/dist/chunk-7QVIOQ47.mjs +0 -462
  125. package/dist/chunk-7QVIOQ47.mjs.map +0 -1
  126. package/dist/chunk-TKWNEKK6.mjs.map +0 -1
  127. package/dist/chunk-TR5XFBTD.mjs.map +0 -1
@@ -0,0 +1,899 @@
1
+ import { logActivity } from './chunk-4F6KE47S.mjs';
2
+ import { getClientIp, formatLocation, lookupGeoLocation, formatDeviceInfo, parseUserAgent, WINDOW_MS, isOverLimit, MAX_IP, RETENTION_MS } from './chunk-6OAHCEDJ.mjs';
3
+ import { getEffectiveAuthFlags } from './chunk-A6JXMHOQ.mjs';
4
+ import { getResend, EMAIL_FROM } from './chunk-L242CZ64.mjs';
5
+ import { db } from './chunk-4C7JHGT5.mjs';
6
+ import { users, passkeys, twoFactors, verifications, sessions, accounts, authThrottle } from './chunk-KA2KMGPY.mjs';
7
+ import { config } from './chunk-HUEDEAY3.mjs';
8
+ import { __spreadValues, __spreadProps } from './chunk-3465SI5N.mjs';
9
+ import 'server-only';
10
+ import { betterAuth } from 'better-auth';
11
+ import { drizzleAdapter } from 'better-auth/adapters/drizzle';
12
+ import { createId } from '@paralleldrive/cuid2';
13
+ import { sql, eq, lt } from 'drizzle-orm';
14
+ import { admin, oneTap, twoFactor } from 'better-auth/plugins';
15
+ import { createAuthMiddleware, APIError, getSessionFromCtx } from 'better-auth/api';
16
+ import { symmetricDecrypt } from 'better-auth/crypto';
17
+ import { passkey } from '@better-auth/passkey';
18
+
19
+ // node_modules/@better-auth/utils/dist/base32.mjs
20
+ function getAlphabet(hex2) {
21
+ return "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
22
+ }
23
+ function createDecodeMap(alphabet) {
24
+ const decodeMap = /* @__PURE__ */ new Map();
25
+ for (let i = 0; i < alphabet.length; i++) {
26
+ decodeMap.set(alphabet[i], i);
27
+ }
28
+ return decodeMap;
29
+ }
30
+ function base32Encode(data, alphabet, padding) {
31
+ let result = "";
32
+ let buffer = 0;
33
+ let shift = 0;
34
+ for (const byte of data) {
35
+ buffer = buffer << 8 | byte;
36
+ shift += 8;
37
+ while (shift >= 5) {
38
+ shift -= 5;
39
+ result += alphabet[buffer >> shift & 31];
40
+ }
41
+ }
42
+ if (shift > 0) {
43
+ result += alphabet[buffer << 5 - shift & 31];
44
+ }
45
+ if (padding) {
46
+ const padCount = (8 - result.length % 8) % 8;
47
+ result += "=".repeat(padCount);
48
+ }
49
+ return result;
50
+ }
51
+ function base32Decode(data, alphabet) {
52
+ const decodeMap = createDecodeMap(alphabet);
53
+ const result = [];
54
+ let buffer = 0;
55
+ let bitsCollected = 0;
56
+ for (const char of data) {
57
+ if (char === "=")
58
+ break;
59
+ const value = decodeMap.get(char);
60
+ if (value === void 0) {
61
+ throw new Error(`Invalid Base32 character: ${char}`);
62
+ }
63
+ buffer = buffer << 5 | value;
64
+ bitsCollected += 5;
65
+ while (bitsCollected >= 8) {
66
+ bitsCollected -= 8;
67
+ result.push(buffer >> bitsCollected & 255);
68
+ }
69
+ }
70
+ return Uint8Array.from(result);
71
+ }
72
+ var base32 = {
73
+ /**
74
+ * Encodes data into a Base32 string.
75
+ * @param data - The data to encode (ArrayBuffer, TypedArray, or string).
76
+ * @param options - Encoding options.
77
+ * @returns The Base32 encoded string.
78
+ */
79
+ encode(data, options = {}) {
80
+ var _a;
81
+ const alphabet = getAlphabet();
82
+ const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
83
+ return base32Encode(buffer, alphabet, (_a = options.padding) != null ? _a : true);
84
+ },
85
+ /**
86
+ * Decodes a Base32 string into a Uint8Array.
87
+ * @param data - The Base32 encoded string or ArrayBuffer/TypedArray.
88
+ * @returns The decoded Uint8Array.
89
+ */
90
+ decode(data) {
91
+ if (typeof data !== "string") {
92
+ data = new TextDecoder().decode(data);
93
+ }
94
+ const alphabet = getAlphabet();
95
+ return base32Decode(data, alphabet);
96
+ }
97
+ };
98
+
99
+ // node_modules/@better-auth/utils/dist/hex.mjs
100
+ var hexadecimal = "0123456789abcdef";
101
+ var hex = {
102
+ encode: (data) => {
103
+ if (typeof data === "string") {
104
+ data = new TextEncoder().encode(data);
105
+ }
106
+ if (data.byteLength === 0) {
107
+ return "";
108
+ }
109
+ const buffer = new Uint8Array(data);
110
+ let result = "";
111
+ for (const byte of buffer) {
112
+ result += byte.toString(16).padStart(2, "0");
113
+ }
114
+ return result;
115
+ },
116
+ decode: (data) => {
117
+ if (!data) {
118
+ return "";
119
+ }
120
+ if (typeof data === "string") {
121
+ if (data.length % 2 !== 0) {
122
+ throw new Error("Invalid hexadecimal string");
123
+ }
124
+ if (!new RegExp(`^[${hexadecimal}]+$`).test(data)) {
125
+ throw new Error("Invalid hexadecimal string");
126
+ }
127
+ const result = new Uint8Array(data.length / 2);
128
+ for (let i = 0; i < data.length; i += 2) {
129
+ result[i / 2] = parseInt(data.slice(i, i + 2), 16);
130
+ }
131
+ return new TextDecoder().decode(result);
132
+ }
133
+ return new TextDecoder().decode(data);
134
+ }
135
+ };
136
+
137
+ // node_modules/@better-auth/utils/dist/base64.mjs
138
+ function getAlphabet2(urlSafe) {
139
+ return urlSafe ? "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
140
+ }
141
+ function base64Encode(data, alphabet, padding) {
142
+ let result = "";
143
+ let buffer = 0;
144
+ let shift = 0;
145
+ for (const byte of data) {
146
+ buffer = buffer << 8 | byte;
147
+ shift += 8;
148
+ while (shift >= 6) {
149
+ shift -= 6;
150
+ result += alphabet[buffer >> shift & 63];
151
+ }
152
+ }
153
+ if (shift > 0) {
154
+ result += alphabet[buffer << 6 - shift & 63];
155
+ }
156
+ if (padding) {
157
+ const padCount = (4 - result.length % 4) % 4;
158
+ result += "=".repeat(padCount);
159
+ }
160
+ return result;
161
+ }
162
+ function base64Decode(data, alphabet) {
163
+ const decodeMap = /* @__PURE__ */ new Map();
164
+ for (let i = 0; i < alphabet.length; i++) {
165
+ decodeMap.set(alphabet[i], i);
166
+ }
167
+ const result = [];
168
+ let buffer = 0;
169
+ let bitsCollected = 0;
170
+ for (const char of data) {
171
+ if (char === "=")
172
+ break;
173
+ const value = decodeMap.get(char);
174
+ if (value === void 0) {
175
+ throw new Error(`Invalid Base64 character: ${char}`);
176
+ }
177
+ buffer = buffer << 6 | value;
178
+ bitsCollected += 6;
179
+ if (bitsCollected >= 8) {
180
+ bitsCollected -= 8;
181
+ result.push(buffer >> bitsCollected & 255);
182
+ }
183
+ }
184
+ return Uint8Array.from(result);
185
+ }
186
+ var base64 = {
187
+ encode(data, options = {}) {
188
+ var _a;
189
+ const alphabet = getAlphabet2(false);
190
+ const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
191
+ return base64Encode(buffer, alphabet, (_a = options.padding) != null ? _a : true);
192
+ },
193
+ decode(data) {
194
+ if (typeof data !== "string") {
195
+ data = new TextDecoder().decode(data);
196
+ }
197
+ const urlSafe = data.includes("-") || data.includes("_");
198
+ const alphabet = getAlphabet2(urlSafe);
199
+ return base64Decode(data, alphabet);
200
+ }
201
+ };
202
+ var base64Url = {
203
+ encode(data, options = {}) {
204
+ var _a;
205
+ const alphabet = getAlphabet2(true);
206
+ const buffer = typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
207
+ return base64Encode(buffer, alphabet, (_a = options.padding) != null ? _a : true);
208
+ },
209
+ decode(data) {
210
+ const urlSafe = data.includes("-") || data.includes("_");
211
+ const alphabet = getAlphabet2(urlSafe);
212
+ return base64Decode(data, alphabet);
213
+ }
214
+ };
215
+
216
+ // node_modules/@better-auth/utils/dist/index.mjs
217
+ function getWebcryptoSubtle() {
218
+ const cr = typeof globalThis !== "undefined" && globalThis.crypto;
219
+ if (cr && typeof cr.subtle === "object" && cr.subtle != null)
220
+ return cr.subtle;
221
+ throw new Error("crypto.subtle must be defined");
222
+ }
223
+
224
+ // node_modules/@better-auth/utils/dist/hmac.mjs
225
+ var createHMAC = (algorithm = "SHA-256", encoding = "none") => {
226
+ const hmac = {
227
+ importKey: async (key, keyUsage) => {
228
+ return getWebcryptoSubtle().importKey(
229
+ "raw",
230
+ typeof key === "string" ? new TextEncoder().encode(key) : key,
231
+ { name: "HMAC", hash: { name: algorithm } },
232
+ false,
233
+ [keyUsage]
234
+ );
235
+ },
236
+ sign: async (hmacKey, data) => {
237
+ if (typeof hmacKey === "string") {
238
+ hmacKey = await hmac.importKey(hmacKey, "sign");
239
+ }
240
+ const signature = await getWebcryptoSubtle().sign(
241
+ "HMAC",
242
+ hmacKey,
243
+ typeof data === "string" ? new TextEncoder().encode(data) : data
244
+ );
245
+ if (encoding === "hex") {
246
+ return hex.encode(signature);
247
+ }
248
+ if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") {
249
+ return base64Url.encode(signature, {
250
+ padding: encoding !== "base64urlnopad"
251
+ });
252
+ }
253
+ return signature;
254
+ },
255
+ verify: async (hmacKey, data, signature) => {
256
+ if (typeof hmacKey === "string") {
257
+ hmacKey = await hmac.importKey(hmacKey, "verify");
258
+ }
259
+ if (encoding === "hex") {
260
+ signature = hex.decode(signature);
261
+ }
262
+ if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") {
263
+ signature = await base64.decode(signature);
264
+ }
265
+ return getWebcryptoSubtle().verify(
266
+ "HMAC",
267
+ hmacKey,
268
+ typeof signature === "string" ? new TextEncoder().encode(signature) : signature,
269
+ typeof data === "string" ? new TextEncoder().encode(data) : data
270
+ );
271
+ }
272
+ };
273
+ return hmac;
274
+ };
275
+
276
+ // node_modules/@better-auth/utils/dist/otp.mjs
277
+ var defaultPeriod = 30;
278
+ var defaultDigits = 6;
279
+ function constantTimeEqualOTP(input, expected) {
280
+ let difference = input.length ^ expected.length;
281
+ for (let i = 0; i < expected.length; i++) {
282
+ difference |= input.charCodeAt(i) ^ expected.charCodeAt(i);
283
+ }
284
+ return difference === 0;
285
+ }
286
+ async function generateHOTP(secret, {
287
+ counter,
288
+ digits,
289
+ hash = "SHA-1"
290
+ }) {
291
+ const _digits = digits != null ? digits : defaultDigits;
292
+ if (_digits < 1 || _digits > 8) {
293
+ throw new TypeError("Digits must be between 1 and 8");
294
+ }
295
+ const buffer = new ArrayBuffer(8);
296
+ new DataView(buffer).setBigUint64(0, BigInt(counter), false);
297
+ const bytes = new Uint8Array(buffer);
298
+ const hmacResult = new Uint8Array(await createHMAC(hash).sign(secret, bytes));
299
+ const offset = hmacResult[hmacResult.length - 1] & 15;
300
+ const truncated = (hmacResult[offset] & 127) << 24 | (hmacResult[offset + 1] & 255) << 16 | (hmacResult[offset + 2] & 255) << 8 | hmacResult[offset + 3] & 255;
301
+ const otp = truncated % 10 ** _digits;
302
+ return otp.toString().padStart(_digits, "0");
303
+ }
304
+ async function generateTOTP(secret, options) {
305
+ var _a, _b;
306
+ const digits = (_a = options == null ? void 0 : options.digits) != null ? _a : defaultDigits;
307
+ const period = (_b = options == null ? void 0 : options.period) != null ? _b : defaultPeriod;
308
+ const milliseconds = period * 1e3;
309
+ const counter = Math.floor(Date.now() / milliseconds);
310
+ return await generateHOTP(secret, { counter, digits, hash: options == null ? void 0 : options.hash });
311
+ }
312
+ async function verifyTOTP(otp, {
313
+ window = 1,
314
+ digits = defaultDigits,
315
+ secret,
316
+ period = defaultPeriod
317
+ }) {
318
+ const milliseconds = period * 1e3;
319
+ const counter = Math.floor(Date.now() / milliseconds);
320
+ let matched = false;
321
+ for (let i = -window; i <= window; i++) {
322
+ const generatedOTP = await generateHOTP(secret, {
323
+ counter: counter + i,
324
+ digits
325
+ });
326
+ matched = constantTimeEqualOTP(otp, generatedOTP) || matched;
327
+ }
328
+ return matched;
329
+ }
330
+ function generateQRCode({
331
+ issuer,
332
+ account,
333
+ secret,
334
+ digits = defaultDigits,
335
+ period = defaultPeriod
336
+ }) {
337
+ const encodedIssuer = encodeURIComponent(issuer);
338
+ const encodedAccountName = encodeURIComponent(account);
339
+ const baseURI = `otpauth://totp/${encodedIssuer}:${encodedAccountName}`;
340
+ const params = new URLSearchParams({
341
+ secret: base32.encode(secret, {
342
+ padding: false
343
+ }),
344
+ issuer
345
+ });
346
+ if (digits !== void 0) {
347
+ params.set("digits", digits.toString());
348
+ }
349
+ if (period !== void 0) {
350
+ params.set("period", period.toString());
351
+ }
352
+ return `${baseURI}?${params.toString()}`;
353
+ }
354
+ var createOTP = (secret, opts) => {
355
+ var _a, _b;
356
+ const digits = (_a = void 0 ) != null ? _a : defaultDigits;
357
+ const period = (_b = void 0 ) != null ? _b : defaultPeriod;
358
+ return {
359
+ hotp: (counter) => generateHOTP(secret, { counter, digits }),
360
+ totp: () => generateTOTP(secret, { digits, period }),
361
+ verify: (otp, options) => verifyTOTP(otp, __spreadValues({ secret, digits, period }, options)),
362
+ url: (issuer, account) => generateQRCode({ issuer, account, secret, digits, period })
363
+ };
364
+ };
365
+
366
+ // lib/two-factor.ts
367
+ var CHALLENGED_PATHS = ["/callback/:id", "/one-tap/callback"];
368
+ var CODE_REQUIRED_PATHS = ["/two-factor/disable", "/two-factor/generate-backup-codes"];
369
+ function twoFactorPlugins(baseURL, { issuer, passwordless = false, challengeAfterOAuth = false }) {
370
+ const plugin = twoFactor({ issuer, allowPasswordless: passwordless });
371
+ if (challengeAfterOAuth) {
372
+ const [challenge] = plugin.hooks.after;
373
+ plugin.hooks.after = [__spreadProps(__spreadValues({}, challenge), {
374
+ matcher: (ctx) => {
375
+ var _a;
376
+ return challenge.matcher(ctx) || CHALLENGED_PATHS.includes((_a = ctx.path) != null ? _a : "");
377
+ }
378
+ })];
379
+ }
380
+ const extras = {
381
+ id: "two-factor-extras",
382
+ hooks: {
383
+ // allowPasswordless lets disable / regenerate-backup-codes run on a session alone,
384
+ // so anyone at an unlocked, signed-in browser could switch 2FA off. Require a
385
+ // current authenticator code instead of the password the user doesn't have.
386
+ before: passwordless ? [{
387
+ matcher: (ctx) => {
388
+ var _a;
389
+ return CODE_REQUIRED_PATHS.includes((_a = ctx.path) != null ? _a : "");
390
+ },
391
+ handler: createAuthMiddleware(async (ctx) => {
392
+ var _a;
393
+ const session = await getSessionFromCtx(ctx);
394
+ if (!session) return;
395
+ const code = (_a = ctx.body) == null ? void 0 : _a.code;
396
+ const row = await ctx.context.adapter.findOne({
397
+ model: "twoFactor",
398
+ where: [{ field: "userId", value: session.user.id }]
399
+ });
400
+ const valid = typeof code === "string" && !!row && await createOTP(await symmetricDecrypt({ key: ctx.context.secretConfig, data: row.secret })).verify(code);
401
+ if (!valid) throw new APIError("UNAUTHORIZED", { message: "Enter the current code from your authenticator app" });
402
+ })
403
+ }] : [],
404
+ // The challenge answers with JSON ({ twoFactorRedirect: true }), which One Tap's
405
+ // caller handles. The Google callback is a browser redirect, so turn it into a
406
+ // redirect to /login/2fa, keeping where the user was headed (same-origin only).
407
+ after: challengeAfterOAuth ? [{
408
+ matcher: (ctx) => ctx.path === "/callback/:id",
409
+ handler: createAuthMiddleware(async (ctx) => {
410
+ var _a, _b;
411
+ const returned = ctx.context.returned;
412
+ if (!(returned == null ? void 0 : returned.twoFactorRedirect)) return;
413
+ const target = new URL((_b = (_a = ctx.context.responseHeaders) == null ? void 0 : _a.get("location")) != null ? _b : "/dashboard", baseURL);
414
+ const callbackUrl = target.origin === new URL(baseURL).origin ? target.pathname + target.search : "/dashboard";
415
+ throw ctx.redirect(`/login/2fa?callbackUrl=${encodeURIComponent(callbackUrl)}`);
416
+ })
417
+ }] : []
418
+ }
419
+ };
420
+ return [plugin, extras];
421
+ }
422
+
423
+ // lib/cookie-names.ts
424
+ var LOGIN_REFERRER_COOKIE = "login_referrer";
425
+ var DEVICE_FINGERPRINT_HEADER = "x-device-fingerprint";
426
+ async function isDeviceThrottled(fingerprint, max) {
427
+ try {
428
+ const [row] = await db.select({ count: authThrottle.count, windowStart: authThrottle.windowStart }).from(authThrottle).where(eq(authThrottle.fingerprint, fingerprint)).limit(1);
429
+ return isOverLimit(row, Date.now(), max);
430
+ } catch (error) {
431
+ console.error("auth-throttle read failed, allowing request", error);
432
+ return false;
433
+ }
434
+ }
435
+ async function recordDeviceAttempt(fingerprint, meta) {
436
+ const now = /* @__PURE__ */ new Date();
437
+ const cutoff = new Date(now.getTime() - WINDOW_MS);
438
+ const seen = {
439
+ lastAttemptAt: now,
440
+ ipAddress: meta.ipAddress,
441
+ userAgent: meta.userAgent,
442
+ lastEmail: meta.email,
443
+ lastKind: meta.kind
444
+ };
445
+ try {
446
+ await db.insert(authThrottle).values(__spreadValues({ fingerprint, count: 1, windowStart: now }, seen)).onConflictDoUpdate({
447
+ target: authThrottle.fingerprint,
448
+ set: __spreadValues({
449
+ count: sql`case when ${authThrottle.windowStart} < ${cutoff} then 1 else ${authThrottle.count} + 1 end`,
450
+ windowStart: sql`case when ${authThrottle.windowStart} < ${cutoff} then ${now} else ${authThrottle.windowStart} end`
451
+ }, seen)
452
+ });
453
+ } catch (error) {
454
+ console.error("auth-throttle write failed", error);
455
+ }
456
+ await pruneStaleRows(now);
457
+ }
458
+ var PRUNE_EVERY_MS = 60 * 60 * 1e3;
459
+ var lastPrune = 0;
460
+ async function pruneStaleRows(now = /* @__PURE__ */ new Date()) {
461
+ if (now.getTime() - lastPrune < PRUNE_EVERY_MS) return;
462
+ lastPrune = now.getTime();
463
+ try {
464
+ await db.delete(authThrottle).where(lt(authThrottle.lastAttemptAt, new Date(now.getTime() - RETENTION_MS)));
465
+ } catch (error) {
466
+ console.error("auth-throttle prune failed", error);
467
+ }
468
+ }
469
+ async function clearDeviceThrottle(fingerprint) {
470
+ try {
471
+ await db.delete(authThrottle).where(eq(authThrottle.fingerprint, fingerprint));
472
+ } catch (error) {
473
+ console.error("auth-throttle clear failed", error);
474
+ }
475
+ }
476
+
477
+ // server/auth.ts
478
+ async function logFailedLogin(ctx, log) {
479
+ var _a, _b, _c;
480
+ try {
481
+ const raw = (_a = ctx.body) == null ? void 0 : _a.email;
482
+ const email = typeof raw === "string" ? raw.toLowerCase() : null;
483
+ if (!email) return;
484
+ const [user] = await db.select({ id: users.id }).from(users).where(eq(users.email, email)).limit(1);
485
+ if (!user) return;
486
+ await log({
487
+ userId: user.id,
488
+ action: "login_failed",
489
+ description: "Failed login attempt",
490
+ ipAddress: getClientIp(ctx.headers),
491
+ userAgent: (_c = (_b = ctx.headers) == null ? void 0 : _b.get("user-agent")) != null ? _c : null
492
+ });
493
+ } catch (error) {
494
+ console.error("Failed to log login_failed activity", error);
495
+ }
496
+ }
497
+ async function notifyPasskeyChange(ctx, action, log) {
498
+ var _a, _b, _c, _d;
499
+ try {
500
+ const session = await getSessionFromCtx(ctx);
501
+ const user = session == null ? void 0 : session.user;
502
+ if (!user) return;
503
+ const ip = getClientIp(ctx.headers);
504
+ await log({
505
+ userId: user.id,
506
+ action: action === "added" ? "passkey_added" : "passkey_removed",
507
+ description: `Passkey ${action}`,
508
+ ipAddress: ip,
509
+ userAgent: (_b = (_a = ctx.headers) == null ? void 0 : _a.get("user-agent")) != null ? _b : null
510
+ });
511
+ if (!config.RESEND_API_KEY) return;
512
+ const { EmailTemplatePasskeyChange } = await import('./email-template-passkey-change-F5Q2SXHD.mjs');
513
+ await (await getResend()).emails.send({
514
+ from: EMAIL_FROM,
515
+ to: [user.email],
516
+ subject: action === "added" ? "A passkey was added to your account" : "A passkey was removed from your account",
517
+ react: EmailTemplatePasskeyChange({
518
+ firstName: user.name || "there",
519
+ action,
520
+ device: formatDeviceInfo(parseUserAgent((_d = (_c = ctx.headers) == null ? void 0 : _c.get("user-agent")) != null ? _d : null)),
521
+ location: formatLocation(lookupGeoLocation(ip)),
522
+ ipAddress: ip || "Unknown",
523
+ when: (/* @__PURE__ */ new Date()).toUTCString(),
524
+ manageUrl: `${process.env.BETTER_AUTH_URL || process.env.NEXTAUTH_URL || process.env.NEXT_PUBLIC_APP_URL || ""}/dashboard/settings`
525
+ })
526
+ });
527
+ } catch (error) {
528
+ console.error("Failed to send passkey-change notification", error);
529
+ }
530
+ }
531
+ async function packageSessionCreated(log, ...[session, context]) {
532
+ var _a, _b, _c, _d;
533
+ const impersonatedBy = session.impersonatedBy;
534
+ if (impersonatedBy) {
535
+ const target = await db.select({ email: users.email }).from(users).where(eq(users.id, session.userId)).limit(1);
536
+ await log({
537
+ userId: impersonatedBy,
538
+ action: "impersonation_started",
539
+ description: `Admin started impersonating ${(_b = (_a = target[0]) == null ? void 0 : _a.email) != null ? _b : session.userId}`,
540
+ metadata: { impersonatedUserId: session.userId }
541
+ });
542
+ return;
543
+ }
544
+ try {
545
+ await db.update(users).set({ lastLoginAt: /* @__PURE__ */ new Date() }).where(eq(users.id, session.userId));
546
+ } catch (error) {
547
+ console.error("Failed to update lastLoginAt", error);
548
+ }
549
+ try {
550
+ const headers = context == null ? void 0 : context.headers;
551
+ const ipAddress = getClientIp(headers);
552
+ const userAgent = (_c = headers == null ? void 0 : headers.get("user-agent")) != null ? _c : null;
553
+ const referrerUrl = ((_d = context == null ? void 0 : context.getCookie) == null ? void 0 : _d.call(context, LOGIN_REFERRER_COOKIE)) || (headers == null ? void 0 : headers.get("referer")) || null;
554
+ const device = parseUserAgent(userAgent);
555
+ const geo = lookupGeoLocation(ipAddress);
556
+ const [{ count }] = await db.select({ count: sql`count(*)` }).from(sessions).where(eq(sessions.userId, session.userId));
557
+ const isFirstSession = Number(count) <= 1;
558
+ await log({
559
+ userId: session.userId,
560
+ action: "login",
561
+ description: isFirstSession ? "New account registered and signed in" : "User logged in",
562
+ ipAddress,
563
+ userAgent,
564
+ referrerUrl,
565
+ os: device.os,
566
+ browser: device.browser,
567
+ deviceType: device.deviceType,
568
+ country: geo.country,
569
+ city: geo.city
570
+ });
571
+ } catch (error) {
572
+ console.error("Failed to log login activity", error);
573
+ }
574
+ }
575
+ function createAuth(overrides = {}) {
576
+ var _a, _b, _c, _d, _e, _f, _g;
577
+ const socialProviders = __spreadValues(__spreadValues({}, config.AUTH_ENABLE_GOOGLE ? {
578
+ google: {
579
+ clientId: process.env.AUTH_GOOGLE_ID || process.env.GOOGLE_CLIENT_ID || "",
580
+ clientSecret: process.env.AUTH_GOOGLE_SECRET || process.env.GOOGLE_CLIENT_SECRET || ""
581
+ }
582
+ } : {}), overrides.socialProviders);
583
+ const emailAndPasswordEnabled = config.AUTH_ENABLE_EMAIL_PASSWORD;
584
+ const hasEnabledSocialProvider = Object.values(socialProviders).some(Boolean);
585
+ if (!hasEnabledSocialProvider && !emailAndPasswordEnabled) {
586
+ throw new Error(
587
+ "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: {...} })."
588
+ );
589
+ }
590
+ const baseURL = process.env.NEXTAUTH_URL || process.env.BETTER_AUTH_URL || "http://localhost:3000";
591
+ const log = (_a = overrides.logActivity) != null ? _a : logActivity;
592
+ const [twoFactorPlugin, twoFactorExtras] = twoFactorPlugins(baseURL, {
593
+ issuer: config.APP_NAME,
594
+ passwordless: (_b = overrides.twoFactor) == null ? void 0 : _b.passwordless,
595
+ challengeAfterOAuth: (_c = overrides.twoFactor) == null ? void 0 : _c.challengeAfterOAuth
596
+ });
597
+ const appHooks = {
598
+ id: "app-hooks",
599
+ hooks: {
600
+ before: ((_d = overrides.hooks) == null ? void 0 : _d.before) ? [{ matcher: () => true, handler: overrides.hooks.before }] : [],
601
+ after: ((_e = overrides.hooks) == null ? void 0 : _e.after) ? [{ matcher: () => true, handler: overrides.hooks.after }] : []
602
+ }
603
+ };
604
+ return betterAuth({
605
+ database: drizzleAdapter(db, {
606
+ provider: "pg",
607
+ schema: {
608
+ user: users,
609
+ account: accounts,
610
+ session: sessions,
611
+ verification: verifications,
612
+ twoFactor: twoFactors,
613
+ passkey: passkeys
614
+ }
615
+ }),
616
+ // Session configuration (30 days expiration matching previous NextAuth setup)
617
+ session: {
618
+ expiresIn: 60 * 60 * 24 * 30,
619
+ // 30 days
620
+ updateAge: 60 * 60 * 24,
621
+ // Update session every 24 hours
622
+ cookieCache: {
623
+ enabled: true,
624
+ // Enable hybrid session caching for performance
625
+ maxAge: 5 * 60
626
+ // 5 minutes
627
+ }
628
+ },
629
+ // Email & Password Authentication (replaces Credentials provider)
630
+ // Toggle per-project via AUTH_ENABLE_EMAIL_PASSWORD in that project's own .env.*
631
+ emailAndPassword: {
632
+ enabled: emailAndPasswordEnabled,
633
+ requireEmailVerification: false,
634
+ // `url` is fully composed by better-auth (baseURL + verification token +
635
+ // callbackURL) — see app/(auth)/forgot-password and reset-password for
636
+ // the pages this points at.
637
+ async sendResetPassword({ user, url }) {
638
+ const { EmailTemplateResetPassword } = await import('./email-template-reset-password-QTCQNXOD.mjs');
639
+ await (await getResend()).emails.send({
640
+ from: EMAIL_FROM,
641
+ to: [user.email],
642
+ subject: "Reset your password",
643
+ react: EmailTemplateResetPassword({ firstName: user.name || "there", url })
644
+ });
645
+ }
646
+ },
647
+ // Email verification. `requireEmailVerification` above stays false, so this
648
+ // is opt-in: users trigger it from the dashboard via
649
+ // authClient.sendVerificationEmail(). better-auth composes `url`
650
+ // (baseURL + token + callbackURL) and serves the /api/auth/verify-email
651
+ // callback that flips users.emailVerified on click.
652
+ emailVerification: {
653
+ autoSignInAfterVerification: true,
654
+ async sendVerificationEmail({ user, url }) {
655
+ const { EmailTemplateVerifyEmail } = await import('./email-template-verify-email-WZDCCAKK.mjs');
656
+ await (await getResend()).emails.send({
657
+ from: EMAIL_FROM,
658
+ to: [user.email],
659
+ subject: "Confirm your email",
660
+ react: EmailTemplateVerifyEmail({ firstName: user.name || "there", url })
661
+ });
662
+ }
663
+ },
664
+ // Social Providers — google is included by default; toggle per-project via
665
+ // AUTH_ENABLE_GOOGLE. overrides.socialProviders can still add more (or replace it).
666
+ socialProviders,
667
+ // User schema configuration
668
+ user: {
669
+ additionalFields: {
670
+ role: {
671
+ type: "string",
672
+ required: false,
673
+ defaultValue: "user",
674
+ input: false
675
+ // Prevent users from setting their own role
676
+ }
677
+ },
678
+ // Self-service "Delete account" (dashboard Settings → Danger zone).
679
+ // Credential users confirm with their password; OAuth-only users have
680
+ // no password, so better-auth instead requires a session younger than
681
+ // `freshAge` (default 1 day). Every user-owned table cascades on delete.
682
+ // Impersonation and last-admin guards live in hooks.before below.
683
+ deleteUser: { enabled: (_f = overrides.deleteUser) != null ? _f : true }
684
+ },
685
+ // Advanced options
686
+ advanced: __spreadProps(__spreadValues({}, overrides.advanced), {
687
+ database: {
688
+ generateId: () => createId()
689
+ }
690
+ }),
691
+ rateLimit: overrides.rateLimit,
692
+ databaseHooks: {
693
+ user: {
694
+ create: {
695
+ async after(user, context) {
696
+ var _a2, _b2, _c2, _d2;
697
+ 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));
698
+ }
699
+ }
700
+ },
701
+ session: {
702
+ create: {
703
+ async after(session, context) {
704
+ var _a2, _b2, _c2, _d2;
705
+ await packageSessionCreated(log, session, context);
706
+ 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));
707
+ }
708
+ }
709
+ }
710
+ },
711
+ // better-auth's admin plugin ends impersonation by deleting the
712
+ // impersonation session and restoring the admin's original session
713
+ // straight from a signed cookie — it never runs session.create, so
714
+ // there's no databaseHooks entry point to log the stop event from.
715
+ // Reading the session here (before the endpoint deletes it) is the only
716
+ // point where both the admin id and the impersonated user id are still
717
+ // available together.
718
+ hooks: {
719
+ before: createAuthMiddleware(async (ctx) => {
720
+ var _a2, _b2, _c2, _d2;
721
+ if (ctx.path === "/sign-in/email" || ctx.path === "/sign-up/email") {
722
+ const fingerprint = (_a2 = ctx.headers) == null ? void 0 : _a2.get(DEVICE_FINGERPRINT_HEADER);
723
+ const ip = getClientIp(ctx.headers);
724
+ const throttled = fingerprint && await isDeviceThrottled(fingerprint) || ip && await isDeviceThrottled(`ip:${ip}`, MAX_IP);
725
+ if (throttled) {
726
+ throw new APIError("TOO_MANY_REQUESTS", {
727
+ message: "Too many attempts from this device. Try again in a few minutes."
728
+ });
729
+ }
730
+ }
731
+ if (ctx.path === "/sign-in/social") {
732
+ if (((_b2 = ctx.body) == null ? void 0 : _b2.provider) === "google") {
733
+ const flags = await getEffectiveAuthFlags();
734
+ if (!flags.google) {
735
+ throw new APIError("FORBIDDEN", { message: "Google sign-in is currently disabled." });
736
+ }
737
+ }
738
+ return;
739
+ }
740
+ if (ctx.path === "/sign-in/email") {
741
+ const flags = await getEffectiveAuthFlags();
742
+ if (!flags.emailPassword) {
743
+ throw new APIError("FORBIDDEN", { message: "Email/password sign-in is currently disabled." });
744
+ }
745
+ return;
746
+ }
747
+ if (ctx.path === "/one-tap/callback") {
748
+ const flags = await getEffectiveAuthFlags();
749
+ if (!flags.google || !flags.oneTap) {
750
+ throw new APIError("FORBIDDEN", { message: "Google One Tap is currently disabled." });
751
+ }
752
+ return;
753
+ }
754
+ if (ctx.path === "/admin/impersonate-user" && overrides.impersonation === false) {
755
+ throw new APIError("FORBIDDEN", { message: "Impersonation is turned off." });
756
+ }
757
+ if (ctx.path === "/delete-user") {
758
+ const current2 = await getSessionFromCtx(ctx, { disableCookieCache: true });
759
+ if (!current2) return;
760
+ if (current2.session.impersonatedBy) {
761
+ throw new APIError("FORBIDDEN", { message: "Stop impersonating before deleting an account." });
762
+ }
763
+ if (current2.user.role === "admin") {
764
+ const [{ count }] = await db.select({ count: sql`count(*)` }).from(users).where(eq(users.role, "admin"));
765
+ if (Number(count) <= 1) {
766
+ throw new APIError("FORBIDDEN", { message: "You're the only admin. Promote another user to admin first." });
767
+ }
768
+ }
769
+ return;
770
+ }
771
+ if (ctx.path !== "/admin/stop-impersonating") return;
772
+ const current = await getSessionFromCtx(ctx, { disableCookieCache: true });
773
+ if (current == null ? void 0 : current.session.impersonatedBy) {
774
+ const target = await db.select({ email: users.email }).from(users).where(eq(users.id, current.session.userId)).limit(1);
775
+ await log({
776
+ userId: current.session.impersonatedBy,
777
+ action: "impersonation_stopped",
778
+ description: `Admin stopped impersonating ${(_d2 = (_c2 = target[0]) == null ? void 0 : _c2.email) != null ? _d2 : current.session.userId}`,
779
+ metadata: { impersonatedUserId: current.session.userId }
780
+ });
781
+ }
782
+ }),
783
+ after: createAuthMiddleware(async (ctx) => {
784
+ var _a2, _b2, _c2, _d2;
785
+ if (ctx.path === "/passkey/verify-registration" || ctx.path === "/passkey/delete-passkey") {
786
+ if (ctx.context.returned instanceof APIError) return;
787
+ await notifyPasskeyChange(
788
+ ctx,
789
+ ctx.path === "/passkey/verify-registration" ? "added" : "removed",
790
+ log
791
+ );
792
+ return;
793
+ }
794
+ if (ctx.path !== "/sign-in/email" && ctx.path !== "/sign-up/email") return;
795
+ const fingerprint = (_a2 = ctx.headers) == null ? void 0 : _a2.get(DEVICE_FINGERPRINT_HEADER);
796
+ const ip = getClientIp(ctx.headers);
797
+ const ipKey = ip ? `ip:${ip}` : null;
798
+ if (!fingerprint && !ipKey) return;
799
+ const failed = ctx.context.returned instanceof APIError;
800
+ const rawEmail = (_b2 = ctx.body) == null ? void 0 : _b2.email;
801
+ const meta = {
802
+ ipAddress: ip,
803
+ userAgent: (_d2 = (_c2 = ctx.headers) == null ? void 0 : _c2.get("user-agent")) != null ? _d2 : null,
804
+ email: typeof rawEmail === "string" ? rawEmail.toLowerCase() : null
805
+ };
806
+ const keys = [fingerprint, ipKey].filter((k) => !!k);
807
+ if (ctx.path === "/sign-up/email") {
808
+ await Promise.all(keys.map((key) => recordDeviceAttempt(key, __spreadProps(__spreadValues({}, meta), { kind: "signup" }))));
809
+ return;
810
+ }
811
+ if (failed) {
812
+ await Promise.all(keys.map((key) => recordDeviceAttempt(key, __spreadProps(__spreadValues({}, meta), { kind: "signin" }))));
813
+ await logFailedLogin(ctx, log);
814
+ } else {
815
+ await Promise.all(keys.map((key) => clearDeviceThrottle(key)));
816
+ }
817
+ })
818
+ },
819
+ // Base URL for callbacks
820
+ baseURL,
821
+ // Secret for signing cookies and tokens
822
+ secret: process.env.AUTH_SECRET,
823
+ // The OAuth `state` is a one-time verification row: the callback consumes
824
+ // and deletes it. When the same callback URL gets hit twice (browser
825
+ // prefetch / bfcache / double nav — common on a repeat Google sign-in
826
+ // where Google auto-redirects with no consent screen), the first hit
827
+ // logs the user in and the second finds no `state` row and throws
828
+ // `please_restart_the_process`. Default sends that to better-auth's bare
829
+ // error page; point it at /login instead, which already bounces an
830
+ // authenticated user straight to their callbackUrl — so the losing race
831
+ // just lands them logged in. See better-auth#5658 / #6544.
832
+ onAPIError: {
833
+ errorURL: "/login"
834
+ },
835
+ plugins: [
836
+ // Registered for impersonation (auth.api.impersonateUser / stopImpersonating)
837
+ // only — role/ban/delete stay on our own custom routes above. adminRoles
838
+ // matches our existing role column so the plugin's own permission checks
839
+ // line up with hasRole(role, 'admin'). banReason is remapped onto our
840
+ // existing bannedReason column instead of adding a duplicate field.
841
+ admin({
842
+ adminRoles: ["admin"],
843
+ schema: {
844
+ user: {
845
+ fields: {
846
+ banReason: "bannedReason"
847
+ }
848
+ }
849
+ }
850
+ }),
851
+ // TOTP second factor + encrypted backup codes (see lib/two-factor.ts).
852
+ // Listed individually, not spread: see the note on the spread below.
853
+ twoFactorPlugin,
854
+ twoFactorExtras,
855
+ // WebAuthn passkeys (Touch ID / Windows Hello / security keys) as a
856
+ // passwordless sign-in method. rpID must be the bare host and origin
857
+ // the full URL — both derived from baseURL above.
858
+ passkey({
859
+ rpID: new URL(baseURL).hostname,
860
+ rpName: config.APP_NAME,
861
+ origin: baseURL
862
+ }),
863
+ // checks to see if oneTap is enabled and if google provider is available, then add the oneTap plugin.
864
+ // Keep this spread last: a leading spread turns `plugins` from a tuple into a plain
865
+ // array and better-auth 1.7 then drops plugin fields (e.g. session.impersonatedBy).
866
+ ...config.AUTH_ENABLE_ONE_TAP && Boolean(socialProviders.google) ? [oneTap()] : [],
867
+ appHooks,
868
+ ...(_g = overrides.plugins) != null ? _g : []
869
+ ]
870
+ });
871
+ }
872
+ var _auth;
873
+ function getDefaultAuth() {
874
+ if (!_auth) _auth = createAuth();
875
+ return _auth;
876
+ }
877
+ var auth = new Proxy({}, {
878
+ get(_target, prop) {
879
+ const instance = getDefaultAuth();
880
+ const value = Reflect.get(instance, prop);
881
+ return typeof value === "function" ? value.bind(instance) : value;
882
+ },
883
+ // "prop" in auth (e.g. better-auth's toNextJsHandler does `"handler" in auth`)
884
+ // must also see the real instance — without this it checks the empty
885
+ // placeholder target and always reports false.
886
+ has(_target, prop) {
887
+ return Reflect.has(getDefaultAuth(), prop);
888
+ },
889
+ ownKeys(_target) {
890
+ return Reflect.ownKeys(getDefaultAuth());
891
+ },
892
+ getOwnPropertyDescriptor(_target, prop) {
893
+ return Reflect.getOwnPropertyDescriptor(getDefaultAuth(), prop);
894
+ }
895
+ });
896
+
897
+ export { auth, createAuth };
898
+ //# sourceMappingURL=chunk-VHNGYAIG.mjs.map
899
+ //# sourceMappingURL=chunk-VHNGYAIG.mjs.map