@xk2800/nextjs-template 0.5.3

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