@xk2800/nextjs-template 0.7.1-beta.13 → 0.7.1-beta.15
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.
- package/components/auth/oneTap.tsx +9 -1
- package/components/ui/alert-dialog.tsx +1 -1
- package/components/ui/avatar.tsx +1 -1
- package/components/ui/badge.tsx +2 -2
- package/components/ui/dialog.tsx +1 -1
- package/components/ui/dropdown-menu.tsx +1 -1
- package/components/ui/label.tsx +1 -1
- package/dist/api/feedback.js +498 -63
- package/dist/api/feedback.js.map +1 -1
- package/dist/api/feedback.mjs +1 -1
- package/dist/api/marketing.js +498 -63
- package/dist/api/marketing.js.map +1 -1
- package/dist/api/marketing.mjs +2 -2
- package/dist/auth/helpers.d.mts +3 -3
- package/dist/auth/helpers.d.ts +3 -3
- package/dist/auth/helpers.js +496 -61
- package/dist/auth/helpers.js.map +1 -1
- package/dist/auth/helpers.mjs +2 -2
- package/dist/auth/index.d.mts +142 -10
- package/dist/auth/index.d.ts +142 -10
- package/dist/auth/index.js +496 -61
- package/dist/auth/index.js.map +1 -1
- package/dist/auth/index.mjs +1 -1
- package/dist/auth-client/index.d.mts +16 -16
- package/dist/auth-client/index.d.ts +16 -16
- package/dist/{chunk-6Z3WUSDJ.mjs → chunk-A2K3FVDH.mjs} +3 -3
- package/dist/{chunk-6Z3WUSDJ.mjs.map → chunk-A2K3FVDH.mjs.map} +1 -1
- package/dist/chunk-WJMWCE2I.mjs +897 -0
- package/dist/chunk-WJMWCE2I.mjs.map +1 -0
- package/package.json +2 -16
- package/dist/chunk-7QVIOQ47.mjs +0 -462
- package/dist/chunk-7QVIOQ47.mjs.map +0 -1
|
@@ -0,0 +1,897 @@
|
|
|
1
|
+
import { logActivity } from './chunk-7F2POZM6.mjs';
|
|
2
|
+
import { getClientIp, formatLocation, lookupGeoLocation, formatDeviceInfo, parseUserAgent, WINDOW_MS, isOverLimit, MAX_IP, RETENTION_MS } from './chunk-6OAHCEDJ.mjs';
|
|
3
|
+
import { getEffectiveAuthFlags } from './chunk-P2G23JMY.mjs';
|
|
4
|
+
import { getResend, EMAIL_FROM } from './chunk-OVKVD2HH.mjs';
|
|
5
|
+
import { db } from './chunk-ZJMFE5B2.mjs';
|
|
6
|
+
import { users, passkeys, twoFactors, verifications, sessions, accounts, authThrottle } from './chunk-TR5XFBTD.mjs';
|
|
7
|
+
import { config } from './chunk-TKWNEKK6.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) {
|
|
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 logActivity({
|
|
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) {
|
|
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 logActivity({
|
|
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(...[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 logActivity({
|
|
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 logActivity({
|
|
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;
|
|
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 [twoFactorPlugin, twoFactorExtras] = twoFactorPlugins(baseURL, {
|
|
592
|
+
issuer: config.APP_NAME,
|
|
593
|
+
passwordless: (_a = overrides.twoFactor) == null ? void 0 : _a.passwordless,
|
|
594
|
+
challengeAfterOAuth: (_b = overrides.twoFactor) == null ? void 0 : _b.challengeAfterOAuth
|
|
595
|
+
});
|
|
596
|
+
const appHooks = {
|
|
597
|
+
id: "app-hooks",
|
|
598
|
+
hooks: {
|
|
599
|
+
before: ((_c = overrides.hooks) == null ? void 0 : _c.before) ? [{ matcher: () => true, handler: overrides.hooks.before }] : [],
|
|
600
|
+
after: ((_d = overrides.hooks) == null ? void 0 : _d.after) ? [{ matcher: () => true, handler: overrides.hooks.after }] : []
|
|
601
|
+
}
|
|
602
|
+
};
|
|
603
|
+
return betterAuth({
|
|
604
|
+
database: drizzleAdapter(db, {
|
|
605
|
+
provider: "pg",
|
|
606
|
+
schema: {
|
|
607
|
+
user: users,
|
|
608
|
+
account: accounts,
|
|
609
|
+
session: sessions,
|
|
610
|
+
verification: verifications,
|
|
611
|
+
twoFactor: twoFactors,
|
|
612
|
+
passkey: passkeys
|
|
613
|
+
}
|
|
614
|
+
}),
|
|
615
|
+
// Session configuration (30 days expiration matching previous NextAuth setup)
|
|
616
|
+
session: {
|
|
617
|
+
expiresIn: 60 * 60 * 24 * 30,
|
|
618
|
+
// 30 days
|
|
619
|
+
updateAge: 60 * 60 * 24,
|
|
620
|
+
// Update session every 24 hours
|
|
621
|
+
cookieCache: {
|
|
622
|
+
enabled: true,
|
|
623
|
+
// Enable hybrid session caching for performance
|
|
624
|
+
maxAge: 5 * 60
|
|
625
|
+
// 5 minutes
|
|
626
|
+
}
|
|
627
|
+
},
|
|
628
|
+
// Email & Password Authentication (replaces Credentials provider)
|
|
629
|
+
// Toggle per-project via AUTH_ENABLE_EMAIL_PASSWORD in that project's own .env.*
|
|
630
|
+
emailAndPassword: {
|
|
631
|
+
enabled: emailAndPasswordEnabled,
|
|
632
|
+
requireEmailVerification: false,
|
|
633
|
+
// `url` is fully composed by better-auth (baseURL + verification token +
|
|
634
|
+
// callbackURL) — see app/(auth)/forgot-password and reset-password for
|
|
635
|
+
// the pages this points at.
|
|
636
|
+
async sendResetPassword({ user, url }) {
|
|
637
|
+
const { EmailTemplateResetPassword } = await import('./email-template-reset-password-QTCQNXOD.mjs');
|
|
638
|
+
await (await getResend()).emails.send({
|
|
639
|
+
from: EMAIL_FROM,
|
|
640
|
+
to: [user.email],
|
|
641
|
+
subject: "Reset your password",
|
|
642
|
+
react: EmailTemplateResetPassword({ firstName: user.name || "there", url })
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
},
|
|
646
|
+
// Email verification. `requireEmailVerification` above stays false, so this
|
|
647
|
+
// is opt-in: users trigger it from the dashboard via
|
|
648
|
+
// authClient.sendVerificationEmail(). better-auth composes `url`
|
|
649
|
+
// (baseURL + token + callbackURL) and serves the /api/auth/verify-email
|
|
650
|
+
// callback that flips users.emailVerified on click.
|
|
651
|
+
emailVerification: {
|
|
652
|
+
autoSignInAfterVerification: true,
|
|
653
|
+
async sendVerificationEmail({ user, url }) {
|
|
654
|
+
const { EmailTemplateVerifyEmail } = await import('./email-template-verify-email-WZDCCAKK.mjs');
|
|
655
|
+
await (await getResend()).emails.send({
|
|
656
|
+
from: EMAIL_FROM,
|
|
657
|
+
to: [user.email],
|
|
658
|
+
subject: "Confirm your email",
|
|
659
|
+
react: EmailTemplateVerifyEmail({ firstName: user.name || "there", url })
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
},
|
|
663
|
+
// Social Providers — google is included by default; toggle per-project via
|
|
664
|
+
// AUTH_ENABLE_GOOGLE. overrides.socialProviders can still add more (or replace it).
|
|
665
|
+
socialProviders,
|
|
666
|
+
// User schema configuration
|
|
667
|
+
user: {
|
|
668
|
+
additionalFields: {
|
|
669
|
+
role: {
|
|
670
|
+
type: "string",
|
|
671
|
+
required: false,
|
|
672
|
+
defaultValue: "user",
|
|
673
|
+
input: false
|
|
674
|
+
// Prevent users from setting their own role
|
|
675
|
+
}
|
|
676
|
+
},
|
|
677
|
+
// Self-service "Delete account" (dashboard Settings → Danger zone).
|
|
678
|
+
// Credential users confirm with their password; OAuth-only users have
|
|
679
|
+
// no password, so better-auth instead requires a session younger than
|
|
680
|
+
// `freshAge` (default 1 day). Every user-owned table cascades on delete.
|
|
681
|
+
// Impersonation and last-admin guards live in hooks.before below.
|
|
682
|
+
deleteUser: { enabled: (_e = overrides.deleteUser) != null ? _e : true }
|
|
683
|
+
},
|
|
684
|
+
// Advanced options
|
|
685
|
+
advanced: __spreadProps(__spreadValues({}, overrides.advanced), {
|
|
686
|
+
database: {
|
|
687
|
+
generateId: () => createId()
|
|
688
|
+
}
|
|
689
|
+
}),
|
|
690
|
+
rateLimit: overrides.rateLimit,
|
|
691
|
+
databaseHooks: {
|
|
692
|
+
user: {
|
|
693
|
+
create: {
|
|
694
|
+
async after(user, context) {
|
|
695
|
+
var _a2, _b2, _c2, _d2;
|
|
696
|
+
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));
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
},
|
|
700
|
+
session: {
|
|
701
|
+
create: {
|
|
702
|
+
async after(session, context) {
|
|
703
|
+
var _a2, _b2, _c2, _d2;
|
|
704
|
+
await packageSessionCreated(session, context);
|
|
705
|
+
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));
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
},
|
|
710
|
+
// better-auth's admin plugin ends impersonation by deleting the
|
|
711
|
+
// impersonation session and restoring the admin's original session
|
|
712
|
+
// straight from a signed cookie — it never runs session.create, so
|
|
713
|
+
// there's no databaseHooks entry point to log the stop event from.
|
|
714
|
+
// Reading the session here (before the endpoint deletes it) is the only
|
|
715
|
+
// point where both the admin id and the impersonated user id are still
|
|
716
|
+
// available together.
|
|
717
|
+
hooks: {
|
|
718
|
+
before: createAuthMiddleware(async (ctx) => {
|
|
719
|
+
var _a2, _b2, _c2, _d2;
|
|
720
|
+
if (ctx.path === "/sign-in/email" || ctx.path === "/sign-up/email") {
|
|
721
|
+
const fingerprint = (_a2 = ctx.headers) == null ? void 0 : _a2.get(DEVICE_FINGERPRINT_HEADER);
|
|
722
|
+
const ip = getClientIp(ctx.headers);
|
|
723
|
+
const throttled = fingerprint && await isDeviceThrottled(fingerprint) || ip && await isDeviceThrottled(`ip:${ip}`, MAX_IP);
|
|
724
|
+
if (throttled) {
|
|
725
|
+
throw new APIError("TOO_MANY_REQUESTS", {
|
|
726
|
+
message: "Too many attempts from this device. Try again in a few minutes."
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
if (ctx.path === "/sign-in/social") {
|
|
731
|
+
if (((_b2 = ctx.body) == null ? void 0 : _b2.provider) === "google") {
|
|
732
|
+
const flags = await getEffectiveAuthFlags();
|
|
733
|
+
if (!flags.google) {
|
|
734
|
+
throw new APIError("FORBIDDEN", { message: "Google sign-in is currently disabled." });
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
if (ctx.path === "/sign-in/email") {
|
|
740
|
+
const flags = await getEffectiveAuthFlags();
|
|
741
|
+
if (!flags.emailPassword) {
|
|
742
|
+
throw new APIError("FORBIDDEN", { message: "Email/password sign-in is currently disabled." });
|
|
743
|
+
}
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
if (ctx.path === "/one-tap/callback") {
|
|
747
|
+
const flags = await getEffectiveAuthFlags();
|
|
748
|
+
if (!flags.google || !flags.oneTap) {
|
|
749
|
+
throw new APIError("FORBIDDEN", { message: "Google One Tap is currently disabled." });
|
|
750
|
+
}
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
if (ctx.path === "/admin/impersonate-user" && overrides.impersonation === false) {
|
|
754
|
+
throw new APIError("FORBIDDEN", { message: "Impersonation is turned off." });
|
|
755
|
+
}
|
|
756
|
+
if (ctx.path === "/delete-user") {
|
|
757
|
+
const current2 = await getSessionFromCtx(ctx, { disableCookieCache: true });
|
|
758
|
+
if (!current2) return;
|
|
759
|
+
if (current2.session.impersonatedBy) {
|
|
760
|
+
throw new APIError("FORBIDDEN", { message: "Stop impersonating before deleting an account." });
|
|
761
|
+
}
|
|
762
|
+
if (current2.user.role === "admin") {
|
|
763
|
+
const [{ count }] = await db.select({ count: sql`count(*)` }).from(users).where(eq(users.role, "admin"));
|
|
764
|
+
if (Number(count) <= 1) {
|
|
765
|
+
throw new APIError("FORBIDDEN", { message: "You're the only admin. Promote another user to admin first." });
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
if (ctx.path !== "/admin/stop-impersonating") return;
|
|
771
|
+
const current = await getSessionFromCtx(ctx, { disableCookieCache: true });
|
|
772
|
+
if (current == null ? void 0 : current.session.impersonatedBy) {
|
|
773
|
+
const target = await db.select({ email: users.email }).from(users).where(eq(users.id, current.session.userId)).limit(1);
|
|
774
|
+
await logActivity({
|
|
775
|
+
userId: current.session.impersonatedBy,
|
|
776
|
+
action: "impersonation_stopped",
|
|
777
|
+
description: `Admin stopped impersonating ${(_d2 = (_c2 = target[0]) == null ? void 0 : _c2.email) != null ? _d2 : current.session.userId}`,
|
|
778
|
+
metadata: { impersonatedUserId: current.session.userId }
|
|
779
|
+
});
|
|
780
|
+
}
|
|
781
|
+
}),
|
|
782
|
+
after: createAuthMiddleware(async (ctx) => {
|
|
783
|
+
var _a2, _b2, _c2, _d2;
|
|
784
|
+
if (ctx.path === "/passkey/verify-registration" || ctx.path === "/passkey/delete-passkey") {
|
|
785
|
+
if (ctx.context.returned instanceof APIError) return;
|
|
786
|
+
await notifyPasskeyChange(
|
|
787
|
+
ctx,
|
|
788
|
+
ctx.path === "/passkey/verify-registration" ? "added" : "removed"
|
|
789
|
+
);
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
if (ctx.path !== "/sign-in/email" && ctx.path !== "/sign-up/email") return;
|
|
793
|
+
const fingerprint = (_a2 = ctx.headers) == null ? void 0 : _a2.get(DEVICE_FINGERPRINT_HEADER);
|
|
794
|
+
const ip = getClientIp(ctx.headers);
|
|
795
|
+
const ipKey = ip ? `ip:${ip}` : null;
|
|
796
|
+
if (!fingerprint && !ipKey) return;
|
|
797
|
+
const failed = ctx.context.returned instanceof APIError;
|
|
798
|
+
const rawEmail = (_b2 = ctx.body) == null ? void 0 : _b2.email;
|
|
799
|
+
const meta = {
|
|
800
|
+
ipAddress: ip,
|
|
801
|
+
userAgent: (_d2 = (_c2 = ctx.headers) == null ? void 0 : _c2.get("user-agent")) != null ? _d2 : null,
|
|
802
|
+
email: typeof rawEmail === "string" ? rawEmail.toLowerCase() : null
|
|
803
|
+
};
|
|
804
|
+
const keys = [fingerprint, ipKey].filter((k) => !!k);
|
|
805
|
+
if (ctx.path === "/sign-up/email") {
|
|
806
|
+
await Promise.all(keys.map((key) => recordDeviceAttempt(key, __spreadProps(__spreadValues({}, meta), { kind: "signup" }))));
|
|
807
|
+
return;
|
|
808
|
+
}
|
|
809
|
+
if (failed) {
|
|
810
|
+
await Promise.all(keys.map((key) => recordDeviceAttempt(key, __spreadProps(__spreadValues({}, meta), { kind: "signin" }))));
|
|
811
|
+
await logFailedLogin(ctx);
|
|
812
|
+
} else {
|
|
813
|
+
await Promise.all(keys.map((key) => clearDeviceThrottle(key)));
|
|
814
|
+
}
|
|
815
|
+
})
|
|
816
|
+
},
|
|
817
|
+
// Base URL for callbacks
|
|
818
|
+
baseURL,
|
|
819
|
+
// Secret for signing cookies and tokens
|
|
820
|
+
secret: process.env.AUTH_SECRET,
|
|
821
|
+
// The OAuth `state` is a one-time verification row: the callback consumes
|
|
822
|
+
// and deletes it. When the same callback URL gets hit twice (browser
|
|
823
|
+
// prefetch / bfcache / double nav — common on a repeat Google sign-in
|
|
824
|
+
// where Google auto-redirects with no consent screen), the first hit
|
|
825
|
+
// logs the user in and the second finds no `state` row and throws
|
|
826
|
+
// `please_restart_the_process`. Default sends that to better-auth's bare
|
|
827
|
+
// error page; point it at /login instead, which already bounces an
|
|
828
|
+
// authenticated user straight to their callbackUrl — so the losing race
|
|
829
|
+
// just lands them logged in. See better-auth#5658 / #6544.
|
|
830
|
+
onAPIError: {
|
|
831
|
+
errorURL: "/login"
|
|
832
|
+
},
|
|
833
|
+
plugins: [
|
|
834
|
+
// Registered for impersonation (auth.api.impersonateUser / stopImpersonating)
|
|
835
|
+
// only — role/ban/delete stay on our own custom routes above. adminRoles
|
|
836
|
+
// matches our existing role column so the plugin's own permission checks
|
|
837
|
+
// line up with hasRole(role, 'admin'). banReason is remapped onto our
|
|
838
|
+
// existing bannedReason column instead of adding a duplicate field.
|
|
839
|
+
admin({
|
|
840
|
+
adminRoles: ["admin"],
|
|
841
|
+
schema: {
|
|
842
|
+
user: {
|
|
843
|
+
fields: {
|
|
844
|
+
banReason: "bannedReason"
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
}),
|
|
849
|
+
// TOTP second factor + encrypted backup codes (see lib/two-factor.ts).
|
|
850
|
+
// Listed individually, not spread: see the note on the spread below.
|
|
851
|
+
twoFactorPlugin,
|
|
852
|
+
twoFactorExtras,
|
|
853
|
+
// WebAuthn passkeys (Touch ID / Windows Hello / security keys) as a
|
|
854
|
+
// passwordless sign-in method. rpID must be the bare host and origin
|
|
855
|
+
// the full URL — both derived from baseURL above.
|
|
856
|
+
passkey({
|
|
857
|
+
rpID: new URL(baseURL).hostname,
|
|
858
|
+
rpName: config.APP_NAME,
|
|
859
|
+
origin: baseURL
|
|
860
|
+
}),
|
|
861
|
+
// checks to see if oneTap is enabled and if google provider is available, then add the oneTap plugin.
|
|
862
|
+
// Keep this spread last: a leading spread turns `plugins` from a tuple into a plain
|
|
863
|
+
// array and better-auth 1.7 then drops plugin fields (e.g. session.impersonatedBy).
|
|
864
|
+
...config.AUTH_ENABLE_ONE_TAP && Boolean(socialProviders.google) ? [oneTap()] : [],
|
|
865
|
+
appHooks,
|
|
866
|
+
...(_f = overrides.plugins) != null ? _f : []
|
|
867
|
+
]
|
|
868
|
+
});
|
|
869
|
+
}
|
|
870
|
+
var _auth;
|
|
871
|
+
function getDefaultAuth() {
|
|
872
|
+
if (!_auth) _auth = createAuth();
|
|
873
|
+
return _auth;
|
|
874
|
+
}
|
|
875
|
+
var auth = new Proxy({}, {
|
|
876
|
+
get(_target, prop) {
|
|
877
|
+
const instance = getDefaultAuth();
|
|
878
|
+
const value = Reflect.get(instance, prop);
|
|
879
|
+
return typeof value === "function" ? value.bind(instance) : value;
|
|
880
|
+
},
|
|
881
|
+
// "prop" in auth (e.g. better-auth's toNextJsHandler does `"handler" in auth`)
|
|
882
|
+
// must also see the real instance — without this it checks the empty
|
|
883
|
+
// placeholder target and always reports false.
|
|
884
|
+
has(_target, prop) {
|
|
885
|
+
return Reflect.has(getDefaultAuth(), prop);
|
|
886
|
+
},
|
|
887
|
+
ownKeys(_target) {
|
|
888
|
+
return Reflect.ownKeys(getDefaultAuth());
|
|
889
|
+
},
|
|
890
|
+
getOwnPropertyDescriptor(_target, prop) {
|
|
891
|
+
return Reflect.getOwnPropertyDescriptor(getDefaultAuth(), prop);
|
|
892
|
+
}
|
|
893
|
+
});
|
|
894
|
+
|
|
895
|
+
export { auth, createAuth };
|
|
896
|
+
//# sourceMappingURL=chunk-WJMWCE2I.mjs.map
|
|
897
|
+
//# sourceMappingURL=chunk-WJMWCE2I.mjs.map
|