@xk2800/nextjs-template 0.8.0-beta.3 → 0.8.0-beta.5

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.
@@ -0,0 +1,1137 @@
1
+ 'use strict';
2
+
3
+ var components = require('@react-email/components');
4
+ var jsxRuntime = require('react/jsx-runtime');
5
+ require('server-only');
6
+ var server = require('next/server');
7
+ var headers = require('next/headers');
8
+ var zod = require('zod');
9
+ var betterAuth = require('better-auth');
10
+ var drizzle = require('better-auth/adapters/drizzle');
11
+ var cuid2 = require('@paralleldrive/cuid2');
12
+ var drizzleOrm = require('drizzle-orm');
13
+ var serverless = require('@neondatabase/serverless');
14
+ var neonHttp = require('drizzle-orm/neon-http');
15
+ var nodePostgres = require('drizzle-orm/node-postgres');
16
+ var pg = require('pg');
17
+ var pgCore = require('drizzle-orm/pg-core');
18
+ var plugins = require('better-auth/plugins');
19
+ var passkey = require('@better-auth/passkey');
20
+ var api = require('better-auth/api');
21
+ var uaParserJs = require('ua-parser-js');
22
+ var geoip = require('geoip-lite');
23
+
24
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
25
+
26
+ var geoip__default = /*#__PURE__*/_interopDefault(geoip);
27
+
28
+ var __defProp = Object.defineProperty;
29
+ var __defProps = Object.defineProperties;
30
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
31
+ var __getOwnPropNames = Object.getOwnPropertyNames;
32
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
33
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
34
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
35
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
36
+ var __spreadValues = (a, b) => {
37
+ for (var prop in b || (b = {}))
38
+ if (__hasOwnProp.call(b, prop))
39
+ __defNormalProp(a, prop, b[prop]);
40
+ if (__getOwnPropSymbols)
41
+ for (var prop of __getOwnPropSymbols(b)) {
42
+ if (__propIsEnum.call(b, prop))
43
+ __defNormalProp(a, prop, b[prop]);
44
+ }
45
+ return a;
46
+ };
47
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
48
+ var __esm = (fn, res) => function __init() {
49
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
50
+ };
51
+ var __export = (target, all) => {
52
+ for (var name in all)
53
+ __defProp(target, name, { get: all[name], enumerable: true });
54
+ };
55
+
56
+ // components/email/email-template-passkey-change.tsx
57
+ var email_template_passkey_change_exports = {};
58
+ __export(email_template_passkey_change_exports, {
59
+ EmailTemplatePasskeyChange: () => EmailTemplatePasskeyChange
60
+ });
61
+ function EmailTemplatePasskeyChange({
62
+ firstName,
63
+ action,
64
+ device,
65
+ location,
66
+ ipAddress,
67
+ when,
68
+ manageUrl
69
+ }) {
70
+ const verb = action === "added" ? "added to" : "removed from";
71
+ return /* @__PURE__ */ jsxRuntime.jsxs(components.Html, { children: [
72
+ /* @__PURE__ */ jsxRuntime.jsx(components.Head, {}),
73
+ /* @__PURE__ */ jsxRuntime.jsx(components.Tailwind, { children: /* @__PURE__ */ jsxRuntime.jsx(components.Body, { className: "bg-white font-sans", children: /* @__PURE__ */ jsxRuntime.jsx(components.Container, { className: "mx-auto max-w-[560px] px-0 pt-5 pb-12", children: /* @__PURE__ */ jsxRuntime.jsxs(components.Section, { className: "rounded-xl bg-[#f8f9fa] p-10", children: [
74
+ /* @__PURE__ */ jsxRuntime.jsxs(components.Heading, { className: "mb-3 text-center text-2xl font-bold text-[#1a1a1a]", children: [
75
+ "A passkey was ",
76
+ action
77
+ ] }),
78
+ /* @__PURE__ */ jsxRuntime.jsxs(components.Text, { className: "mb-6 text-base leading-6 text-[#666666]", children: [
79
+ "Hi ",
80
+ firstName,
81
+ ", a passkey was just ",
82
+ verb,
83
+ " your account."
84
+ ] }),
85
+ /* @__PURE__ */ jsxRuntime.jsxs(components.Section, { className: "mb-6 rounded-lg bg-white p-5", children: [
86
+ /* @__PURE__ */ jsxRuntime.jsxs(components.Text, { className: "m-0 mb-2 text-sm leading-5 text-[#1a1a1a]", children: [
87
+ /* @__PURE__ */ jsxRuntime.jsx("strong", { children: "Device:" }),
88
+ " ",
89
+ device
90
+ ] }),
91
+ /* @__PURE__ */ jsxRuntime.jsxs(components.Text, { className: "m-0 mb-2 text-sm leading-5 text-[#1a1a1a]", children: [
92
+ /* @__PURE__ */ jsxRuntime.jsx("strong", { children: "Approx. location:" }),
93
+ " ",
94
+ location
95
+ ] }),
96
+ /* @__PURE__ */ jsxRuntime.jsxs(components.Text, { className: "m-0 mb-2 text-sm leading-5 text-[#1a1a1a]", children: [
97
+ /* @__PURE__ */ jsxRuntime.jsx("strong", { children: "IP address:" }),
98
+ " ",
99
+ ipAddress
100
+ ] }),
101
+ /* @__PURE__ */ jsxRuntime.jsxs(components.Text, { className: "m-0 text-sm leading-5 text-[#1a1a1a]", children: [
102
+ /* @__PURE__ */ jsxRuntime.jsx("strong", { children: "When:" }),
103
+ " ",
104
+ when
105
+ ] })
106
+ ] }),
107
+ manageUrl && /* @__PURE__ */ jsxRuntime.jsx(components.Section, { className: "mb-6 text-center", children: /* @__PURE__ */ jsxRuntime.jsx(
108
+ components.Button,
109
+ {
110
+ href: manageUrl,
111
+ className: "rounded-lg bg-[#1a1a1a] px-6 py-3 text-sm font-bold text-white no-underline",
112
+ children: "Review your passkeys"
113
+ }
114
+ ) }),
115
+ /* @__PURE__ */ jsxRuntime.jsx(components.Text, { className: "text-sm leading-[22px] text-[#666666]", children: "If this was you, no action is needed. If you don't recognize it, change your password now and review your passkeys and active sessions." })
116
+ ] }) }) }) })
117
+ ] });
118
+ }
119
+ var init_email_template_passkey_change = __esm({
120
+ "components/email/email-template-passkey-change.tsx"() {
121
+ }
122
+ });
123
+
124
+ // components/email/email-template-reset-password.tsx
125
+ var email_template_reset_password_exports = {};
126
+ __export(email_template_reset_password_exports, {
127
+ EmailTemplateResetPassword: () => EmailTemplateResetPassword
128
+ });
129
+ function EmailTemplateResetPassword({ firstName, url }) {
130
+ return /* @__PURE__ */ jsxRuntime.jsxs(components.Html, { children: [
131
+ /* @__PURE__ */ jsxRuntime.jsx(components.Head, {}),
132
+ /* @__PURE__ */ jsxRuntime.jsx(components.Body, { style: { backgroundColor: "#ffffff", fontFamily: "Arial, sans-serif" }, children: /* @__PURE__ */ jsxRuntime.jsx(components.Container, { style: { margin: "0 auto", padding: "20px 0 48px", maxWidth: "560px" }, children: /* @__PURE__ */ jsxRuntime.jsxs(components.Section, { style: { backgroundColor: "#f8f9fa", borderRadius: "12px", padding: "40px", textAlign: "center" }, children: [
133
+ /* @__PURE__ */ jsxRuntime.jsx(components.Heading, { style: { fontSize: "28px", fontWeight: "bold", marginBottom: "12px", color: "#1a1a1a" }, children: "Reset your password" }),
134
+ /* @__PURE__ */ jsxRuntime.jsxs(components.Text, { style: { fontSize: "16px", color: "#666666", marginBottom: "32px", lineHeight: "24px" }, children: [
135
+ "Hi ",
136
+ firstName,
137
+ ", we got a request to reset your password. This link expires in an hour \u2014 if you didn't ask for this, you can safely ignore this email."
138
+ ] }),
139
+ /* @__PURE__ */ jsxRuntime.jsx(components.Section, { style: { marginBottom: "32px" }, children: /* @__PURE__ */ jsxRuntime.jsx(
140
+ components.Button,
141
+ {
142
+ href: url,
143
+ style: {
144
+ backgroundColor: "#000000",
145
+ color: "#ffffff",
146
+ padding: "12px 32px",
147
+ borderRadius: "6px",
148
+ textDecoration: "none",
149
+ fontSize: "16px",
150
+ fontWeight: "bold"
151
+ },
152
+ children: "Reset password"
153
+ }
154
+ ) }),
155
+ /* @__PURE__ */ jsxRuntime.jsxs(components.Text, { style: { fontSize: "13px", color: "#999999", lineHeight: "20px", wordBreak: "break-all" }, children: [
156
+ "Or paste this link into your browser:",
157
+ /* @__PURE__ */ jsxRuntime.jsx("br", {}),
158
+ /* @__PURE__ */ jsxRuntime.jsx("a", { href: url, style: { color: "#000000", textDecoration: "underline" }, children: url })
159
+ ] })
160
+ ] }) }) })
161
+ ] });
162
+ }
163
+ var init_email_template_reset_password = __esm({
164
+ "components/email/email-template-reset-password.tsx"() {
165
+ }
166
+ });
167
+
168
+ // components/email/email-template-verify-email.tsx
169
+ var email_template_verify_email_exports = {};
170
+ __export(email_template_verify_email_exports, {
171
+ EmailTemplateVerifyEmail: () => EmailTemplateVerifyEmail
172
+ });
173
+ function EmailTemplateVerifyEmail({ firstName, url }) {
174
+ return /* @__PURE__ */ jsxRuntime.jsxs(components.Html, { children: [
175
+ /* @__PURE__ */ jsxRuntime.jsx(components.Head, {}),
176
+ /* @__PURE__ */ jsxRuntime.jsx(components.Tailwind, { children: /* @__PURE__ */ jsxRuntime.jsx(components.Body, { className: "bg-white font-sans", children: /* @__PURE__ */ jsxRuntime.jsx(components.Container, { className: "mx-auto max-w-[560px] px-0 pt-5 pb-12", children: /* @__PURE__ */ jsxRuntime.jsxs(components.Section, { className: "rounded-xl bg-[#f8f9fa] p-10 text-center", children: [
177
+ /* @__PURE__ */ jsxRuntime.jsx(components.Heading, { className: "mb-3 text-[28px] font-bold text-[#1a1a1a]", children: "Confirm your email" }),
178
+ /* @__PURE__ */ jsxRuntime.jsxs(components.Text, { className: "mb-8 text-base leading-6 text-[#666666]", children: [
179
+ "Hi ",
180
+ firstName,
181
+ ", click the button below to verify this email address. If you didn't create an account, you can safely ignore this email."
182
+ ] }),
183
+ /* @__PURE__ */ jsxRuntime.jsx(components.Section, { className: "mb-8", children: /* @__PURE__ */ jsxRuntime.jsx(
184
+ components.Button,
185
+ {
186
+ href: url,
187
+ className: "rounded-md bg-black px-8 py-3 text-base font-bold text-white no-underline",
188
+ children: "Verify email"
189
+ }
190
+ ) }),
191
+ /* @__PURE__ */ jsxRuntime.jsxs(components.Text, { className: "text-[13px] leading-5 break-all text-[#999999]", children: [
192
+ "Or paste this link into your browser:",
193
+ /* @__PURE__ */ jsxRuntime.jsx("br", {}),
194
+ /* @__PURE__ */ jsxRuntime.jsx(components.Link, { href: url, className: "text-black underline", children: url })
195
+ ] })
196
+ ] }) }) }) })
197
+ ] });
198
+ }
199
+ var init_email_template_verify_email = __esm({
200
+ "components/email/email-template-verify-email.tsx"() {
201
+ }
202
+ });
203
+
204
+ // server/db/schema.ts
205
+ var schema_exports = {};
206
+ __export(schema_exports, {
207
+ ActivityActionEnum: () => ActivityActionEnum,
208
+ RoleEnum: () => RoleEnum,
209
+ accounts: () => accounts,
210
+ activityLogs: () => activityLogs,
211
+ authThrottle: () => authThrottle,
212
+ deviceFingerprints: () => deviceFingerprints,
213
+ passkeys: () => passkeys,
214
+ sessions: () => sessions,
215
+ systemSettings: () => systemSettings,
216
+ twoFactors: () => twoFactors,
217
+ users: () => users,
218
+ verifications: () => verifications
219
+ });
220
+
221
+ // lib/maintenance.ts
222
+ var DEFAULT_MAINTENANCE_EXEMPT_PATHS = [
223
+ "/",
224
+ "/features",
225
+ "/changelog",
226
+ "/changelog-template",
227
+ "/privacy",
228
+ "/terms"
229
+ ];
230
+
231
+ // server/db/schema.ts
232
+ var RoleEnum = pgCore.pgEnum("roles", ["user", "admin", "tester"]);
233
+ var ActivityActionEnum = pgCore.pgEnum("activity_actions", [
234
+ "login",
235
+ "logout",
236
+ "login_failed",
237
+ "password_changed",
238
+ "email_changed",
239
+ "profile_updated",
240
+ "session_revoked",
241
+ "user_deleted",
242
+ "user_banned",
243
+ "user_unbanned",
244
+ "role_changed",
245
+ "impersonation_started",
246
+ "impersonation_stopped",
247
+ "settings_changed",
248
+ "passkey_added",
249
+ "passkey_removed"
250
+ ]);
251
+ var users = pgCore.pgTable("user", {
252
+ id: pgCore.text("id").notNull().primaryKey().$defaultFn(() => cuid2.createId()),
253
+ name: pgCore.text("name").notNull(),
254
+ email: pgCore.text("email").notNull().unique(),
255
+ password: pgCore.text("password"),
256
+ emailVerified: pgCore.boolean("emailVerified").notNull().default(false),
257
+ image: pgCore.text("image"),
258
+ role: RoleEnum("roles").default("user").notNull(),
259
+ banned: pgCore.boolean("banned").default(false).notNull(),
260
+ bannedAt: pgCore.timestamp("bannedAt"),
261
+ bannedReason: pgCore.text("bannedReason"),
262
+ // Required by better-auth's admin plugin schema (auto-expiring bans). We
263
+ // never set this ourselves, so it stays null and bans behave as permanent,
264
+ // same as before the plugin was added.
265
+ banExpires: pgCore.timestamp("banExpires"),
266
+ lastLoginAt: pgCore.timestamp("lastLoginAt"),
267
+ lastActiveAt: pgCore.timestamp("lastActiveAt"),
268
+ // Set by better-auth's twoFactor plugin — true once the user has
269
+ // completed TOTP setup (see twoFactor pgTable below for the secret /
270
+ // backup codes themselves).
271
+ twoFactorEnabled: pgCore.boolean("twoFactorEnabled").notNull().default(false),
272
+ createdAt: pgCore.timestamp("createdAt").notNull().defaultNow(),
273
+ updatedAt: pgCore.timestamp("updatedAt").notNull().defaultNow()
274
+ });
275
+ var sessions = pgCore.pgTable("session", {
276
+ id: pgCore.text("id").notNull().primaryKey().$defaultFn(() => cuid2.createId()),
277
+ expiresAt: pgCore.timestamp("expiresAt").notNull(),
278
+ token: pgCore.text("token").notNull().unique(),
279
+ createdAt: pgCore.timestamp("createdAt").notNull().defaultNow(),
280
+ updatedAt: pgCore.timestamp("updatedAt").notNull().defaultNow(),
281
+ ipAddress: pgCore.text("ipAddress"),
282
+ userAgent: pgCore.text("userAgent"),
283
+ userId: pgCore.text("userId").notNull().references(() => users.id, { onDelete: "cascade" }),
284
+ // Set by better-auth's admin plugin while this session is an admin
285
+ // impersonating another user; holds the impersonating admin's user id.
286
+ impersonatedBy: pgCore.text("impersonatedBy")
287
+ });
288
+ var accounts = pgCore.pgTable("account", {
289
+ id: pgCore.text("id").notNull().primaryKey().$defaultFn(() => cuid2.createId()),
290
+ accountId: pgCore.text("accountId").notNull(),
291
+ providerId: pgCore.text("providerId").notNull(),
292
+ userId: pgCore.text("userId").notNull().references(() => users.id, { onDelete: "cascade" }),
293
+ accessToken: pgCore.text("accessToken"),
294
+ refreshToken: pgCore.text("refreshToken"),
295
+ idToken: pgCore.text("idToken"),
296
+ accessTokenExpiresAt: pgCore.timestamp("accessTokenExpiresAt"),
297
+ refreshTokenExpiresAt: pgCore.timestamp("refreshTokenExpiresAt"),
298
+ scope: pgCore.text("scope"),
299
+ password: pgCore.text("password"),
300
+ createdAt: pgCore.timestamp("createdAt").notNull().defaultNow(),
301
+ updatedAt: pgCore.timestamp("updatedAt").notNull().defaultNow()
302
+ });
303
+ var twoFactors = pgCore.pgTable("twoFactor", {
304
+ id: pgCore.text("id").notNull().primaryKey().$defaultFn(() => cuid2.createId()),
305
+ secret: pgCore.text("secret").notNull(),
306
+ backupCodes: pgCore.text("backupCodes").notNull(),
307
+ userId: pgCore.text("userId").notNull().references(() => users.id, { onDelete: "cascade" }),
308
+ // Added in better-auth 1.7 (TOTP lockout). Defaults match the plugin's.
309
+ verified: pgCore.boolean("verified").default(true),
310
+ failedVerificationCount: pgCore.integer("failedVerificationCount").default(0),
311
+ lockedUntil: pgCore.timestamp("lockedUntil")
312
+ });
313
+ var passkeys = pgCore.pgTable("passkey", {
314
+ id: pgCore.text("id").notNull().primaryKey().$defaultFn(() => cuid2.createId()),
315
+ name: pgCore.text("name"),
316
+ publicKey: pgCore.text("publicKey").notNull(),
317
+ userId: pgCore.text("userId").notNull().references(() => users.id, { onDelete: "cascade" }),
318
+ credentialID: pgCore.text("credentialID").notNull().unique(),
319
+ counter: pgCore.integer("counter").notNull(),
320
+ deviceType: pgCore.text("deviceType").notNull(),
321
+ backedUp: pgCore.boolean("backedUp").notNull(),
322
+ transports: pgCore.text("transports"),
323
+ createdAt: pgCore.timestamp("createdAt"),
324
+ aaguid: pgCore.text("aaguid")
325
+ });
326
+ var verifications = pgCore.pgTable("verification", {
327
+ id: pgCore.text("id").notNull().primaryKey().$defaultFn(() => cuid2.createId()),
328
+ identifier: pgCore.text("identifier").notNull(),
329
+ value: pgCore.text("value").notNull(),
330
+ expiresAt: pgCore.timestamp("expiresAt").notNull(),
331
+ createdAt: pgCore.timestamp("createdAt").notNull().defaultNow(),
332
+ updatedAt: pgCore.timestamp("updatedAt").notNull().defaultNow()
333
+ });
334
+ var activityLogs = pgCore.pgTable("activity_log", {
335
+ id: pgCore.text("id").notNull().primaryKey().$defaultFn(() => cuid2.createId()),
336
+ userId: pgCore.text("userId").notNull().references(() => users.id, { onDelete: "cascade" }),
337
+ action: ActivityActionEnum("action").notNull(),
338
+ description: pgCore.text("description").notNull(),
339
+ ipAddress: pgCore.text("ipAddress"),
340
+ userAgent: pgCore.text("userAgent"),
341
+ metadata: pgCore.text("metadata"),
342
+ // Populated on 'login' events only (registration + sign-in) — parsed from
343
+ // userAgent/ipAddress at write time so the record stays stable even if
344
+ // the parsing library or geoip database changes later.
345
+ referrerUrl: pgCore.text("referrerUrl"),
346
+ os: pgCore.text("os"),
347
+ browser: pgCore.text("browser"),
348
+ deviceType: pgCore.text("deviceType"),
349
+ country: pgCore.text("country"),
350
+ city: pgCore.text("city"),
351
+ createdAt: pgCore.timestamp("createdAt").notNull().defaultNow()
352
+ });
353
+ var deviceFingerprints = pgCore.pgTable("device_fingerprint", {
354
+ id: pgCore.text("id").notNull().primaryKey().$defaultFn(() => cuid2.createId()),
355
+ userId: pgCore.text("userId").notNull().references(() => users.id, { onDelete: "cascade" }),
356
+ visitorId: pgCore.text("visitorId").notNull(),
357
+ // Context captured at first-seen time — for the admin panel's "New devices"
358
+ // card and the alert email. Not part of the new-vs-known decision (that's
359
+ // visitorId only), just so an admin can eyeball whether a sign-in looks like
360
+ // a hijack. Nullable: an old row predates these columns, or geoip missed.
361
+ ipAddress: pgCore.text("ipAddress"),
362
+ userAgent: pgCore.text("userAgent"),
363
+ country: pgCore.text("country"),
364
+ city: pgCore.text("city"),
365
+ createdAt: pgCore.timestamp("createdAt").notNull().defaultNow()
366
+ }, (table) => [
367
+ pgCore.unique("device_fingerprint_user_visitor").on(table.userId, table.visitorId)
368
+ ]);
369
+ var authThrottle = pgCore.pgTable("auth_throttle", {
370
+ fingerprint: pgCore.text("fingerprint").notNull().primaryKey(),
371
+ count: pgCore.integer("count").notNull().default(0),
372
+ windowStart: pgCore.timestamp("windowStart").notNull().defaultNow(),
373
+ // Blockable data points, overwritten on every attempt (last-write-wins) so
374
+ // the admin panel can show who to block — by IP or by fingerprint — with no
375
+ // join and no per-attempt history table. windowStart anchors the counter's
376
+ // window; lastAttemptAt is just "most recently seen".
377
+ lastAttemptAt: pgCore.timestamp("lastAttemptAt").notNull().defaultNow(),
378
+ ipAddress: pgCore.text("ipAddress"),
379
+ userAgent: pgCore.text("userAgent"),
380
+ lastEmail: pgCore.text("lastEmail"),
381
+ lastKind: pgCore.text("lastKind")
382
+ // 'signin' | 'signup'
383
+ });
384
+ var systemSettings = pgCore.pgTable("system_settings", {
385
+ id: pgCore.text("id").primaryKey().default("default"),
386
+ maintenanceMode: pgCore.boolean("maintenanceMode").notNull().default(false),
387
+ maintenanceMessage: pgCore.text("maintenanceMessage"),
388
+ // Path prefixes that stay reachable while maintenance mode is on (see
389
+ // lib/maintenance.ts — a few auth paths are always open on top of these).
390
+ maintenanceExemptPaths: pgCore.text("maintenanceExemptPaths").array().notNull().default(DEFAULT_MAINTENANCE_EXEMPT_PATHS),
391
+ authEnableGoogle: pgCore.boolean("authEnableGoogle").notNull().default(true),
392
+ authEnableEmailPassword: pgCore.boolean("authEnableEmailPassword").notNull().default(true),
393
+ authEnableOneTap: pgCore.boolean("authEnableOneTap").notNull().default(false),
394
+ enableSessionRevocation: pgCore.boolean("enableSessionRevocation").notNull().default(true),
395
+ updatedAt: pgCore.timestamp("updatedAt").notNull().defaultNow(),
396
+ // Who last changed a setting. This row doesn't "belong" to that admin the
397
+ // way sessions/activityLogs belong to their user, so deleting that admin's
398
+ // account should null this out rather than cascade-delete the singleton row.
399
+ updatedBy: pgCore.text("updatedBy").references(() => users.id, { onDelete: "set null" })
400
+ }, (table) => [
401
+ pgCore.check("system_settings_singleton", drizzleOrm.sql`${table.id} = 'default'`)
402
+ ]);
403
+ var envSchema = zod.z.object({
404
+ NODE_ENV: zod.z.enum(["development", "production", "test"]).default("development"),
405
+ PORT: zod.z.string().default("3000").transform(Number),
406
+ DATABASE_URL: zod.z.string().default(""),
407
+ RESEND_API_KEY: zod.z.string().default(""),
408
+ // Sender for every transactional email. Must be on a domain verified in
409
+ // your Resend account.
410
+ EMAIL_FROM: zod.z.string().default("Acme <onboarding@xavierkhew.xyz>"),
411
+ // Display name for this deployment — shown as the authenticator-app label
412
+ // (2FA issuer) and the passkey relying-party name. Consuming projects set
413
+ // this in their own .env; defaults to the template name.
414
+ APP_NAME: zod.z.string().default("Next.js Template"),
415
+ // Where the dashboard feedback form delivers (app/api/feedback). Set either
416
+ // or both; with neither, the Feedback button is hidden. FEEDBACK_EMAIL takes
417
+ // a comma-separated list and sends through Resend (needs RESEND_API_KEY).
418
+ FEEDBACK_DISCORD_WEBHOOK_URL: zod.z.string().default(""),
419
+ FEEDBACK_EMAIL: zod.z.string().default(""),
420
+ // Seed-only: the live value lives in the system_settings DB row (see
421
+ // lib/settings-queries.ts) once it's been seeded on first read, and is
422
+ // changed from the admin System Settings page, not by editing this var.
423
+ ENABLE_SESSION_REVOCATION: zod.z.string().default("true").transform((val) => val === "true"),
424
+ AUTH_ENABLE_GOOGLE: zod.z.string().default("true").transform((val) => val === "true"),
425
+ AUTH_ENABLE_EMAIL_PASSWORD: zod.z.string().default("true").transform((val) => val === "true"),
426
+ AUTH_ENABLE_ONE_TAP: zod.z.string().default("false").transform((val) => val === "true"),
427
+ DB_DRIVER: zod.z.enum(["pg", "neon"]).default("pg"),
428
+ // Only relevant when DB_DRIVER=pg — whether the target Postgres server has SSL
429
+ // enabled. Self-hosted Postgres (e.g. via Docker/Dokploy) typically does not.
430
+ DATABASE_SSL: zod.z.string().default("false").transform((val) => val === "true")
431
+ });
432
+
433
+ // config/env.ts
434
+ var results = envSchema.safeParse(process.env);
435
+ if (results.success && results.data.NODE_ENV === "development") {
436
+ console.log("Environment variables loaded:", Object.keys(results.data));
437
+ }
438
+ if (!results.success) {
439
+ console.error("Invalid environment variables:", results.error.format());
440
+ throw new Error("Invalid environment variables");
441
+ }
442
+ var config = results.data;
443
+
444
+ // server/db/index.ts
445
+ var db;
446
+ if (config.DB_DRIVER === "pg") {
447
+ const pool = new pg.Pool({
448
+ connectionString: config.DATABASE_URL,
449
+ ssl: config.DATABASE_SSL ? { rejectUnauthorized: false } : void 0
450
+ });
451
+ db = nodePostgres.drizzle(pool, {
452
+ schema: schema_exports,
453
+ logger: true
454
+ });
455
+ console.log("\u{1F7E1} Using PostgreSQL (pg) driver");
456
+ } else if (config.DB_DRIVER === "neon") {
457
+ const sql4 = serverless.neon(config.DATABASE_URL);
458
+ db = neonHttp.drizzle(sql4, { schema: schema_exports, logger: true });
459
+ console.log("\u{1F7E2} Using Neon (HTTP) driver");
460
+ } else {
461
+ console.log("Database connection not established, unknown DB_DRIVER:", config.DB_DRIVER);
462
+ }
463
+ async function logActivity({
464
+ userId,
465
+ action,
466
+ description,
467
+ ipAddress,
468
+ userAgent,
469
+ metadata,
470
+ referrerUrl,
471
+ os,
472
+ browser,
473
+ deviceType,
474
+ country,
475
+ city
476
+ }) {
477
+ try {
478
+ await db.insert(activityLogs).values({
479
+ userId,
480
+ action,
481
+ description,
482
+ ipAddress: ipAddress || null,
483
+ userAgent: userAgent || null,
484
+ metadata: metadata ? JSON.stringify(metadata) : null,
485
+ referrerUrl: referrerUrl || null,
486
+ os: os || null,
487
+ browser: browser || null,
488
+ deviceType: deviceType || null,
489
+ country: country || null,
490
+ city: city || null
491
+ });
492
+ } catch (error) {
493
+ console.error("Failed to log activity:", error);
494
+ }
495
+ }
496
+ var countryNames = new Intl.DisplayNames(["en"], { type: "region" });
497
+ function getClientIp(headers2) {
498
+ var _a;
499
+ const forwardedFor = headers2 == null ? void 0 : headers2.get("x-forwarded-for");
500
+ if (forwardedFor) return forwardedFor.split(",")[0].trim();
501
+ return (_a = headers2 == null ? void 0 : headers2.get("x-real-ip")) != null ? _a : null;
502
+ }
503
+ function parseUserAgent(userAgent) {
504
+ var _a;
505
+ if (!userAgent) {
506
+ return { os: null, browser: null, deviceType: "desktop" };
507
+ }
508
+ const { os, browser, device } = new uaParserJs.UAParser(userAgent).getResult();
509
+ return {
510
+ os: os.name ? [os.name, os.version].filter(Boolean).join(" ") : null,
511
+ browser: (_a = browser.name) != null ? _a : null,
512
+ deviceType: device.type === "mobile" || device.type === "tablet" ? device.type : "desktop"
513
+ };
514
+ }
515
+ function lookupGeoLocation(ipAddress) {
516
+ var _a;
517
+ if (!ipAddress) return { country: null, city: null };
518
+ const geo = geoip__default.default.lookup(ipAddress);
519
+ if (!geo) return { country: null, city: null };
520
+ let country = geo.country || null;
521
+ if (country) {
522
+ try {
523
+ country = (_a = countryNames.of(country)) != null ? _a : country;
524
+ } catch (e) {
525
+ }
526
+ }
527
+ return { country, city: geo.city || null };
528
+ }
529
+ function formatDeviceInfo({ os, browser, deviceType }) {
530
+ const label = [browser, os].filter(Boolean).join(" on ");
531
+ const typeLabel = deviceType === "mobile" ? "Mobile" : deviceType === "tablet" ? "Tablet" : "Desktop";
532
+ return label ? `${label} \xB7 ${typeLabel}` : `Unknown device \xB7 ${typeLabel}`;
533
+ }
534
+ function formatLocation({ country, city }) {
535
+ if (!country && !city) return "Unknown";
536
+ return [city, country].filter(Boolean).join(", ");
537
+ }
538
+
539
+ // lib/cookie-names.ts
540
+ var LOGIN_REFERRER_COOKIE = "login_referrer";
541
+ var DEVICE_FINGERPRINT_HEADER = "x-device-fingerprint";
542
+
543
+ // lib/auth-throttle-limits.ts
544
+ var WINDOW_MS = 15 * 60 * 1e3;
545
+ var MAX = 10;
546
+ var MAX_IP = MAX * 3;
547
+ function isOverLimit(row, now, max = MAX) {
548
+ if (!row) return false;
549
+ if (now - row.windowStart.getTime() >= WINDOW_MS) return false;
550
+ return row.count >= max;
551
+ }
552
+
553
+ // lib/auth-throttle.ts
554
+ async function isDeviceThrottled(fingerprint, max) {
555
+ try {
556
+ const [row] = await db.select({ count: authThrottle.count, windowStart: authThrottle.windowStart }).from(authThrottle).where(drizzleOrm.eq(authThrottle.fingerprint, fingerprint)).limit(1);
557
+ return isOverLimit(row, Date.now(), max);
558
+ } catch (error) {
559
+ console.error("auth-throttle read failed, allowing request", error);
560
+ return false;
561
+ }
562
+ }
563
+ async function recordDeviceAttempt(fingerprint, meta) {
564
+ const now = /* @__PURE__ */ new Date();
565
+ const cutoff = new Date(now.getTime() - WINDOW_MS);
566
+ const seen = {
567
+ lastAttemptAt: now,
568
+ ipAddress: meta.ipAddress,
569
+ userAgent: meta.userAgent,
570
+ lastEmail: meta.email,
571
+ lastKind: meta.kind
572
+ };
573
+ try {
574
+ await db.insert(authThrottle).values(__spreadValues({ fingerprint, count: 1, windowStart: now }, seen)).onConflictDoUpdate({
575
+ target: authThrottle.fingerprint,
576
+ set: __spreadValues({
577
+ count: drizzleOrm.sql`case when ${authThrottle.windowStart} < ${cutoff} then 1 else ${authThrottle.count} + 1 end`,
578
+ windowStart: drizzleOrm.sql`case when ${authThrottle.windowStart} < ${cutoff} then ${now} else ${authThrottle.windowStart} end`
579
+ }, seen)
580
+ });
581
+ } catch (error) {
582
+ console.error("auth-throttle write failed", error);
583
+ }
584
+ }
585
+ async function clearDeviceThrottle(fingerprint) {
586
+ try {
587
+ await db.delete(authThrottle).where(drizzleOrm.eq(authThrottle.fingerprint, fingerprint));
588
+ } catch (error) {
589
+ console.error("auth-throttle clear failed", error);
590
+ }
591
+ }
592
+ var SETTINGS_ROW_ID = "default";
593
+ var CACHE_TTL_MS = 1e4;
594
+ var cached = null;
595
+ function fallbackSettings() {
596
+ return {
597
+ id: SETTINGS_ROW_ID,
598
+ maintenanceMode: false,
599
+ maintenanceMessage: null,
600
+ maintenanceExemptPaths: DEFAULT_MAINTENANCE_EXEMPT_PATHS,
601
+ authEnableGoogle: config.AUTH_ENABLE_GOOGLE,
602
+ authEnableEmailPassword: config.AUTH_ENABLE_EMAIL_PASSWORD,
603
+ authEnableOneTap: config.AUTH_ENABLE_ONE_TAP,
604
+ enableSessionRevocation: config.ENABLE_SESSION_REVOCATION,
605
+ updatedAt: /* @__PURE__ */ new Date(0),
606
+ updatedBy: null
607
+ };
608
+ }
609
+ async function loadOrSeed() {
610
+ var _a;
611
+ const existing = await db.select().from(systemSettings).where(drizzleOrm.eq(systemSettings.id, SETTINGS_ROW_ID)).limit(1);
612
+ if (existing[0]) return existing[0];
613
+ const seeded = await db.insert(systemSettings).values({
614
+ id: SETTINGS_ROW_ID,
615
+ maintenanceMode: false,
616
+ authEnableGoogle: config.AUTH_ENABLE_GOOGLE,
617
+ authEnableEmailPassword: config.AUTH_ENABLE_EMAIL_PASSWORD,
618
+ authEnableOneTap: config.AUTH_ENABLE_ONE_TAP,
619
+ enableSessionRevocation: config.ENABLE_SESSION_REVOCATION
620
+ }).onConflictDoNothing().returning();
621
+ if (seeded[0]) return seeded[0];
622
+ const retry = await db.select().from(systemSettings).where(drizzleOrm.eq(systemSettings.id, SETTINGS_ROW_ID)).limit(1);
623
+ return (_a = retry[0]) != null ? _a : fallbackSettings();
624
+ }
625
+ async function getSystemSettings() {
626
+ const now = Date.now();
627
+ if (cached && cached.expiresAt > now) return cached.value;
628
+ try {
629
+ const value = await loadOrSeed();
630
+ cached = { value, expiresAt: now + CACHE_TTL_MS };
631
+ return value;
632
+ } catch (error) {
633
+ console.error("Failed to load system settings, failing open:", error);
634
+ return fallbackSettings();
635
+ }
636
+ }
637
+ async function getEffectiveAuthFlags() {
638
+ const settings = await getSystemSettings();
639
+ return {
640
+ google: config.AUTH_ENABLE_GOOGLE && settings.authEnableGoogle,
641
+ emailPassword: config.AUTH_ENABLE_EMAIL_PASSWORD && settings.authEnableEmailPassword,
642
+ oneTap: config.AUTH_ENABLE_ONE_TAP && settings.authEnableOneTap
643
+ };
644
+ }
645
+ var EMAIL_FROM = config.EMAIL_FROM;
646
+ var resend;
647
+ async function getResend() {
648
+ if (!resend) {
649
+ const { Resend } = await import('resend');
650
+ resend = new Resend(config.RESEND_API_KEY);
651
+ }
652
+ return resend;
653
+ }
654
+
655
+ // server/auth.ts
656
+ async function logFailedLogin(ctx) {
657
+ var _a, _b, _c;
658
+ try {
659
+ const raw = (_a = ctx.body) == null ? void 0 : _a.email;
660
+ const email = typeof raw === "string" ? raw.toLowerCase() : null;
661
+ if (!email) return;
662
+ const [user] = await db.select({ id: users.id }).from(users).where(drizzleOrm.eq(users.email, email)).limit(1);
663
+ if (!user) return;
664
+ await logActivity({
665
+ userId: user.id,
666
+ action: "login_failed",
667
+ description: "Failed login attempt",
668
+ ipAddress: getClientIp(ctx.headers),
669
+ userAgent: (_c = (_b = ctx.headers) == null ? void 0 : _b.get("user-agent")) != null ? _c : null
670
+ });
671
+ } catch (error) {
672
+ console.error("Failed to log login_failed activity", error);
673
+ }
674
+ }
675
+ async function notifyPasskeyChange(ctx, action) {
676
+ var _a, _b, _c, _d;
677
+ try {
678
+ const session = await api.getSessionFromCtx(ctx);
679
+ const user = session == null ? void 0 : session.user;
680
+ if (!user) return;
681
+ const ip = getClientIp(ctx.headers);
682
+ await logActivity({
683
+ userId: user.id,
684
+ action: action === "added" ? "passkey_added" : "passkey_removed",
685
+ description: `Passkey ${action}`,
686
+ ipAddress: ip,
687
+ userAgent: (_b = (_a = ctx.headers) == null ? void 0 : _a.get("user-agent")) != null ? _b : null
688
+ });
689
+ if (!config.RESEND_API_KEY) return;
690
+ const { EmailTemplatePasskeyChange: EmailTemplatePasskeyChange2 } = await Promise.resolve().then(() => (init_email_template_passkey_change(), email_template_passkey_change_exports));
691
+ await (await getResend()).emails.send({
692
+ from: EMAIL_FROM,
693
+ to: [user.email],
694
+ subject: action === "added" ? "A passkey was added to your account" : "A passkey was removed from your account",
695
+ react: EmailTemplatePasskeyChange2({
696
+ firstName: user.name || "there",
697
+ action,
698
+ device: formatDeviceInfo(parseUserAgent((_d = (_c = ctx.headers) == null ? void 0 : _c.get("user-agent")) != null ? _d : null)),
699
+ location: formatLocation(lookupGeoLocation(ip)),
700
+ ipAddress: ip || "Unknown",
701
+ when: (/* @__PURE__ */ new Date()).toUTCString(),
702
+ manageUrl: `${process.env.BETTER_AUTH_URL || process.env.NEXTAUTH_URL || process.env.NEXT_PUBLIC_APP_URL || ""}/dashboard/settings`
703
+ })
704
+ });
705
+ } catch (error) {
706
+ console.error("Failed to send passkey-change notification", error);
707
+ }
708
+ }
709
+ function createAuth(overrides = {}) {
710
+ const socialProviders = __spreadValues(__spreadValues({}, config.AUTH_ENABLE_GOOGLE ? {
711
+ google: {
712
+ clientId: process.env.AUTH_GOOGLE_ID || process.env.GOOGLE_CLIENT_ID || "",
713
+ clientSecret: process.env.AUTH_GOOGLE_SECRET || process.env.GOOGLE_CLIENT_SECRET || ""
714
+ }
715
+ } : {}), overrides.socialProviders);
716
+ const emailAndPasswordEnabled = config.AUTH_ENABLE_EMAIL_PASSWORD;
717
+ const hasEnabledSocialProvider = Object.values(socialProviders).some(Boolean);
718
+ if (!hasEnabledSocialProvider && !emailAndPasswordEnabled) {
719
+ throw new Error(
720
+ "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: {...} })."
721
+ );
722
+ }
723
+ const baseURL = process.env.NEXTAUTH_URL || process.env.BETTER_AUTH_URL || "http://localhost:3000";
724
+ return betterAuth.betterAuth({
725
+ database: drizzle.drizzleAdapter(db, {
726
+ provider: "pg",
727
+ schema: {
728
+ user: users,
729
+ account: accounts,
730
+ session: sessions,
731
+ verification: verifications,
732
+ twoFactor: twoFactors,
733
+ passkey: passkeys
734
+ }
735
+ }),
736
+ // Session configuration (30 days expiration matching previous NextAuth setup)
737
+ session: {
738
+ expiresIn: 60 * 60 * 24 * 30,
739
+ // 30 days
740
+ updateAge: 60 * 60 * 24,
741
+ // Update session every 24 hours
742
+ cookieCache: {
743
+ enabled: true,
744
+ // Enable hybrid session caching for performance
745
+ maxAge: 5 * 60
746
+ // 5 minutes
747
+ }
748
+ },
749
+ // Email & Password Authentication (replaces Credentials provider)
750
+ // Toggle per-project via AUTH_ENABLE_EMAIL_PASSWORD in that project's own .env.*
751
+ emailAndPassword: {
752
+ enabled: emailAndPasswordEnabled,
753
+ requireEmailVerification: false,
754
+ // `url` is fully composed by better-auth (baseURL + verification token +
755
+ // callbackURL) — see app/(auth)/forgot-password and reset-password for
756
+ // the pages this points at.
757
+ async sendResetPassword({ user, url }) {
758
+ const { EmailTemplateResetPassword: EmailTemplateResetPassword2 } = await Promise.resolve().then(() => (init_email_template_reset_password(), email_template_reset_password_exports));
759
+ await (await getResend()).emails.send({
760
+ from: EMAIL_FROM,
761
+ to: [user.email],
762
+ subject: "Reset your password",
763
+ react: EmailTemplateResetPassword2({ firstName: user.name || "there", url })
764
+ });
765
+ }
766
+ },
767
+ // Email verification. `requireEmailVerification` above stays false, so this
768
+ // is opt-in: users trigger it from the dashboard via
769
+ // authClient.sendVerificationEmail(). better-auth composes `url`
770
+ // (baseURL + token + callbackURL) and serves the /api/auth/verify-email
771
+ // callback that flips users.emailVerified on click.
772
+ emailVerification: {
773
+ autoSignInAfterVerification: true,
774
+ async sendVerificationEmail({ user, url }) {
775
+ const { EmailTemplateVerifyEmail: EmailTemplateVerifyEmail2 } = await Promise.resolve().then(() => (init_email_template_verify_email(), email_template_verify_email_exports));
776
+ await (await getResend()).emails.send({
777
+ from: EMAIL_FROM,
778
+ to: [user.email],
779
+ subject: "Confirm your email",
780
+ react: EmailTemplateVerifyEmail2({ firstName: user.name || "there", url })
781
+ });
782
+ }
783
+ },
784
+ // Social Providers — google is included by default; toggle per-project via
785
+ // AUTH_ENABLE_GOOGLE. overrides.socialProviders can still add more (or replace it).
786
+ socialProviders,
787
+ // User schema configuration
788
+ user: {
789
+ additionalFields: {
790
+ role: {
791
+ type: "string",
792
+ required: false,
793
+ defaultValue: "user",
794
+ input: false
795
+ // Prevent users from setting their own role
796
+ }
797
+ },
798
+ // Self-service "Delete account" (dashboard Settings → Danger zone).
799
+ // Credential users confirm with their password; OAuth-only users have
800
+ // no password, so better-auth instead requires a session younger than
801
+ // `freshAge` (default 1 day). Every user-owned table cascades on delete.
802
+ // Impersonation and last-admin guards live in hooks.before below.
803
+ deleteUser: { enabled: true }
804
+ },
805
+ // Advanced options
806
+ advanced: {
807
+ database: {
808
+ generateId: () => cuid2.createId()
809
+ }
810
+ },
811
+ // Every new session row corresponds to a sign-in (credential or OAuth) —
812
+ // use that as the "last logged in" signal rather than session updates,
813
+ // which also fire on cookie-cache refresh / expiry extension.
814
+ databaseHooks: {
815
+ session: {
816
+ create: {
817
+ async after(session, context) {
818
+ var _a, _b, _c, _d;
819
+ const impersonatedBy = session.impersonatedBy;
820
+ if (impersonatedBy) {
821
+ const target = await db.select({ email: users.email }).from(users).where(drizzleOrm.eq(users.id, session.userId)).limit(1);
822
+ await logActivity({
823
+ userId: impersonatedBy,
824
+ action: "impersonation_started",
825
+ description: `Admin started impersonating ${(_b = (_a = target[0]) == null ? void 0 : _a.email) != null ? _b : session.userId}`,
826
+ metadata: { impersonatedUserId: session.userId }
827
+ });
828
+ return;
829
+ }
830
+ try {
831
+ await db.update(users).set({ lastLoginAt: /* @__PURE__ */ new Date() }).where(drizzleOrm.eq(users.id, session.userId));
832
+ } catch (error) {
833
+ console.error("Failed to update lastLoginAt", error);
834
+ }
835
+ try {
836
+ const headers2 = context == null ? void 0 : context.headers;
837
+ const ipAddress = getClientIp(headers2);
838
+ const userAgent = (_c = headers2 == null ? void 0 : headers2.get("user-agent")) != null ? _c : null;
839
+ const referrerUrl = ((_d = context == null ? void 0 : context.getCookie) == null ? void 0 : _d.call(context, LOGIN_REFERRER_COOKIE)) || (headers2 == null ? void 0 : headers2.get("referer")) || null;
840
+ const device = parseUserAgent(userAgent);
841
+ const geo = lookupGeoLocation(ipAddress);
842
+ const [{ count }] = await db.select({ count: drizzleOrm.sql`count(*)` }).from(sessions).where(drizzleOrm.eq(sessions.userId, session.userId));
843
+ const isFirstSession = Number(count) <= 1;
844
+ await logActivity({
845
+ userId: session.userId,
846
+ action: "login",
847
+ description: isFirstSession ? "New account registered and signed in" : "User logged in",
848
+ ipAddress,
849
+ userAgent,
850
+ referrerUrl,
851
+ os: device.os,
852
+ browser: device.browser,
853
+ deviceType: device.deviceType,
854
+ country: geo.country,
855
+ city: geo.city
856
+ });
857
+ } catch (error) {
858
+ console.error("Failed to log login activity", error);
859
+ }
860
+ }
861
+ }
862
+ }
863
+ },
864
+ // better-auth's admin plugin ends impersonation by deleting the
865
+ // impersonation session and restoring the admin's original session
866
+ // straight from a signed cookie — it never runs session.create, so
867
+ // there's no databaseHooks entry point to log the stop event from.
868
+ // Reading the session here (before the endpoint deletes it) is the only
869
+ // point where both the admin id and the impersonated user id are still
870
+ // available together.
871
+ hooks: {
872
+ before: api.createAuthMiddleware(async (ctx) => {
873
+ var _a, _b, _c, _d;
874
+ if (ctx.path === "/sign-in/email" || ctx.path === "/sign-up/email") {
875
+ const fingerprint = (_a = ctx.headers) == null ? void 0 : _a.get(DEVICE_FINGERPRINT_HEADER);
876
+ const ip = getClientIp(ctx.headers);
877
+ const throttled = fingerprint && await isDeviceThrottled(fingerprint) || ip && await isDeviceThrottled(`ip:${ip}`, MAX_IP);
878
+ if (throttled) {
879
+ throw new api.APIError("TOO_MANY_REQUESTS", {
880
+ message: "Too many attempts from this device. Try again in a few minutes."
881
+ });
882
+ }
883
+ }
884
+ if (ctx.path === "/sign-in/social") {
885
+ if (((_b = ctx.body) == null ? void 0 : _b.provider) === "google") {
886
+ const flags = await getEffectiveAuthFlags();
887
+ if (!flags.google) {
888
+ throw new api.APIError("FORBIDDEN", { message: "Google sign-in is currently disabled." });
889
+ }
890
+ }
891
+ return;
892
+ }
893
+ if (ctx.path === "/sign-in/email") {
894
+ const flags = await getEffectiveAuthFlags();
895
+ if (!flags.emailPassword) {
896
+ throw new api.APIError("FORBIDDEN", { message: "Email/password sign-in is currently disabled." });
897
+ }
898
+ return;
899
+ }
900
+ if (ctx.path === "/one-tap/callback") {
901
+ const flags = await getEffectiveAuthFlags();
902
+ if (!flags.google || !flags.oneTap) {
903
+ throw new api.APIError("FORBIDDEN", { message: "Google One Tap is currently disabled." });
904
+ }
905
+ return;
906
+ }
907
+ if (ctx.path === "/delete-user") {
908
+ const current2 = await api.getSessionFromCtx(ctx, { disableCookieCache: true });
909
+ if (!current2) return;
910
+ if (current2.session.impersonatedBy) {
911
+ throw new api.APIError("FORBIDDEN", { message: "Stop impersonating before deleting an account." });
912
+ }
913
+ if (current2.user.role === "admin") {
914
+ const [{ count }] = await db.select({ count: drizzleOrm.sql`count(*)` }).from(users).where(drizzleOrm.eq(users.role, "admin"));
915
+ if (Number(count) <= 1) {
916
+ throw new api.APIError("FORBIDDEN", { message: "You're the only admin. Promote another user to admin first." });
917
+ }
918
+ }
919
+ return;
920
+ }
921
+ if (ctx.path !== "/admin/stop-impersonating") return;
922
+ const current = await api.getSessionFromCtx(ctx, { disableCookieCache: true });
923
+ if (current == null ? void 0 : current.session.impersonatedBy) {
924
+ const target = await db.select({ email: users.email }).from(users).where(drizzleOrm.eq(users.id, current.session.userId)).limit(1);
925
+ await logActivity({
926
+ userId: current.session.impersonatedBy,
927
+ action: "impersonation_stopped",
928
+ description: `Admin stopped impersonating ${(_d = (_c = target[0]) == null ? void 0 : _c.email) != null ? _d : current.session.userId}`,
929
+ metadata: { impersonatedUserId: current.session.userId }
930
+ });
931
+ }
932
+ }),
933
+ after: api.createAuthMiddleware(async (ctx) => {
934
+ var _a, _b, _c, _d;
935
+ if (ctx.path === "/passkey/verify-registration" || ctx.path === "/passkey/delete-passkey") {
936
+ if (ctx.context.returned instanceof api.APIError) return;
937
+ await notifyPasskeyChange(
938
+ ctx,
939
+ ctx.path === "/passkey/verify-registration" ? "added" : "removed"
940
+ );
941
+ return;
942
+ }
943
+ if (ctx.path !== "/sign-in/email" && ctx.path !== "/sign-up/email") return;
944
+ const fingerprint = (_a = ctx.headers) == null ? void 0 : _a.get(DEVICE_FINGERPRINT_HEADER);
945
+ const ip = getClientIp(ctx.headers);
946
+ const ipKey = ip ? `ip:${ip}` : null;
947
+ if (!fingerprint && !ipKey) return;
948
+ const failed = ctx.context.returned instanceof api.APIError;
949
+ const rawEmail = (_b = ctx.body) == null ? void 0 : _b.email;
950
+ const meta = {
951
+ ipAddress: ip,
952
+ userAgent: (_d = (_c = ctx.headers) == null ? void 0 : _c.get("user-agent")) != null ? _d : null,
953
+ email: typeof rawEmail === "string" ? rawEmail.toLowerCase() : null
954
+ };
955
+ const keys = [fingerprint, ipKey].filter((k) => !!k);
956
+ if (ctx.path === "/sign-up/email") {
957
+ await Promise.all(keys.map((key) => recordDeviceAttempt(key, __spreadProps(__spreadValues({}, meta), { kind: "signup" }))));
958
+ return;
959
+ }
960
+ if (failed) {
961
+ await Promise.all(keys.map((key) => recordDeviceAttempt(key, __spreadProps(__spreadValues({}, meta), { kind: "signin" }))));
962
+ await logFailedLogin(ctx);
963
+ } else {
964
+ await Promise.all(keys.map((key) => clearDeviceThrottle(key)));
965
+ }
966
+ })
967
+ },
968
+ // Base URL for callbacks
969
+ baseURL,
970
+ // Secret for signing cookies and tokens
971
+ secret: process.env.AUTH_SECRET,
972
+ // The OAuth `state` is a one-time verification row: the callback consumes
973
+ // and deletes it. When the same callback URL gets hit twice (browser
974
+ // prefetch / bfcache / double nav — common on a repeat Google sign-in
975
+ // where Google auto-redirects with no consent screen), the first hit
976
+ // logs the user in and the second finds no `state` row and throws
977
+ // `please_restart_the_process`. Default sends that to better-auth's bare
978
+ // error page; point it at /login instead, which already bounces an
979
+ // authenticated user straight to their callbackUrl — so the losing race
980
+ // just lands them logged in. See better-auth#5658 / #6544.
981
+ onAPIError: {
982
+ errorURL: "/login"
983
+ },
984
+ plugins: [
985
+ // Registered for impersonation (auth.api.impersonateUser / stopImpersonating)
986
+ // only — role/ban/delete stay on our own custom routes above. adminRoles
987
+ // matches our existing role column so the plugin's own permission checks
988
+ // line up with hasRole(role, 'admin'). banReason is remapped onto our
989
+ // existing bannedReason column instead of adding a duplicate field.
990
+ plugins.admin({
991
+ adminRoles: ["admin"],
992
+ schema: {
993
+ user: {
994
+ fields: {
995
+ banReason: "bannedReason"
996
+ }
997
+ }
998
+ }
999
+ }),
1000
+ // TOTP second factor + encrypted backup codes. `issuer` is the label
1001
+ // shown in the user's authenticator app.
1002
+ plugins.twoFactor({ issuer: config.APP_NAME }),
1003
+ // WebAuthn passkeys (Touch ID / Windows Hello / security keys) as a
1004
+ // passwordless sign-in method. rpID must be the bare host and origin
1005
+ // the full URL — both derived from baseURL above.
1006
+ passkey.passkey({
1007
+ rpID: new URL(baseURL).hostname,
1008
+ rpName: config.APP_NAME,
1009
+ origin: baseURL
1010
+ }),
1011
+ // checks to see if oneTap is enabled and if google provider is available, then add the oneTap plugin.
1012
+ // Keep this spread last: a leading spread turns `plugins` from a tuple into a plain
1013
+ // array and better-auth 1.7 then drops plugin fields (e.g. session.impersonatedBy).
1014
+ ...config.AUTH_ENABLE_ONE_TAP && Boolean(socialProviders.google) ? [plugins.oneTap()] : []
1015
+ ]
1016
+ });
1017
+ }
1018
+ var _auth;
1019
+ function getDefaultAuth() {
1020
+ if (!_auth) _auth = createAuth();
1021
+ return _auth;
1022
+ }
1023
+ var auth = new Proxy({}, {
1024
+ get(_target, prop) {
1025
+ const instance = getDefaultAuth();
1026
+ const value = Reflect.get(instance, prop);
1027
+ return typeof value === "function" ? value.bind(instance) : value;
1028
+ },
1029
+ // "prop" in auth (e.g. better-auth's toNextJsHandler does `"handler" in auth`)
1030
+ // must also see the real instance — without this it checks the empty
1031
+ // placeholder target and always reports false.
1032
+ has(_target, prop) {
1033
+ return Reflect.has(getDefaultAuth(), prop);
1034
+ },
1035
+ ownKeys(_target) {
1036
+ return Reflect.ownKeys(getDefaultAuth());
1037
+ },
1038
+ getOwnPropertyDescriptor(_target, prop) {
1039
+ return Reflect.getOwnPropertyDescriptor(getDefaultAuth(), prop);
1040
+ }
1041
+ });
1042
+
1043
+ // lib/feedback-route.ts
1044
+ var feedbackSchema = zod.z.object({
1045
+ type: zod.z.enum(["bug", "feedback"]),
1046
+ // Keep in sync with FEEDBACK_MAX_LENGTH in components/dashboard/feedbackDialog.tsx.
1047
+ message: zod.z.string().trim().min(1).max(2e3),
1048
+ page: zod.z.string().max(300).optional()
1049
+ });
1050
+ var COOLDOWN_MS = 3e4;
1051
+ var lastSentAt = /* @__PURE__ */ new Map();
1052
+ async function POST(request) {
1053
+ var _a;
1054
+ const discordUrl = config.FEEDBACK_DISCORD_WEBHOOK_URL;
1055
+ const emailTo = config.FEEDBACK_EMAIL;
1056
+ if (!discordUrl && !emailTo) {
1057
+ return server.NextResponse.json({ error: "Feedback is not configured" }, { status: 503 });
1058
+ }
1059
+ const session = await auth.api.getSession({ headers: await headers.headers() });
1060
+ if (!(session == null ? void 0 : session.user)) {
1061
+ return server.NextResponse.json({ error: "Unauthorized" }, { status: 401 });
1062
+ }
1063
+ const parsed = feedbackSchema.safeParse(await request.json().catch(() => null));
1064
+ if (!parsed.success) {
1065
+ return server.NextResponse.json({ error: "Message must be 1-2000 characters" }, { status: 400 });
1066
+ }
1067
+ const now = Date.now();
1068
+ if (now - ((_a = lastSentAt.get(session.user.id)) != null ? _a : 0) < COOLDOWN_MS) {
1069
+ return server.NextResponse.json(
1070
+ { error: "Please wait a moment before sending more feedback" },
1071
+ { status: 429 }
1072
+ );
1073
+ }
1074
+ lastSentAt.set(session.user.id, now);
1075
+ const { type, message, page } = parsed.data;
1076
+ const { user } = session;
1077
+ const title = type === "bug" ? "\u{1F41E} Bug report" : "\u{1F4AC} Feedback";
1078
+ const userAgent = request.headers.get("user-agent") || "unknown";
1079
+ const sends = [];
1080
+ if (discordUrl) {
1081
+ sends.push(
1082
+ fetch(discordUrl, {
1083
+ method: "POST",
1084
+ headers: { "Content-Type": "application/json" },
1085
+ body: JSON.stringify({
1086
+ username: config.APP_NAME,
1087
+ // User text must never ping @everyone/@here/roles in the channel.
1088
+ allowed_mentions: { parse: [] },
1089
+ embeds: [{
1090
+ title,
1091
+ description: message,
1092
+ color: type === "bug" ? 15680580 : 3900150,
1093
+ fields: [
1094
+ { name: "User", value: `${user.name} (${user.email})`.slice(0, 1024) },
1095
+ { name: "Page", value: page || "unknown", inline: true },
1096
+ { name: "User agent", value: userAgent.slice(0, 1024) }
1097
+ ],
1098
+ timestamp: new Date(now).toISOString()
1099
+ }]
1100
+ })
1101
+ }).then((res) => {
1102
+ if (!res.ok) throw new Error(`Discord webhook responded ${res.status}`);
1103
+ })
1104
+ );
1105
+ }
1106
+ if (emailTo) {
1107
+ sends.push(
1108
+ getResend().then((resend2) => resend2.emails.send({
1109
+ from: EMAIL_FROM,
1110
+ to: emailTo.split(",").map((s) => s.trim()),
1111
+ replyTo: user.email,
1112
+ subject: `[${config.APP_NAME}] ${title} from ${user.name}`,
1113
+ text: `${message}
1114
+
1115
+ ---
1116
+ User: ${user.name} <${user.email}>
1117
+ Page: ${page || "unknown"}
1118
+ User agent: ${userAgent}`
1119
+ })).then(({ error }) => {
1120
+ if (error) throw new Error(error.message);
1121
+ })
1122
+ );
1123
+ }
1124
+ const results2 = await Promise.allSettled(sends);
1125
+ results2.forEach((r) => {
1126
+ if (r.status === "rejected") console.error("Feedback delivery failed:", r.reason);
1127
+ });
1128
+ if (!results2.some((r) => r.status === "fulfilled")) {
1129
+ lastSentAt.delete(user.id);
1130
+ return server.NextResponse.json({ error: "Failed to send feedback" }, { status: 502 });
1131
+ }
1132
+ return server.NextResponse.json({ success: true });
1133
+ }
1134
+
1135
+ exports.POST = POST;
1136
+ //# sourceMappingURL=feedback.js.map
1137
+ //# sourceMappingURL=feedback.js.map