create-mohit-next 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/README.md +96 -65
  2. package/index.js +195 -195
  3. package/lib/features.js +358 -0
  4. package/lib/scaffold.js +471 -0
  5. package/package.json +10 -6
  6. package/templates/common/_editorconfig +12 -0
  7. package/templates/common/_gitattributes +5 -0
  8. package/templates/common/_github/dependabot.yml +14 -0
  9. package/templates/common/_github/workflows/ci.yml +66 -0
  10. package/templates/common/_husky/commit-msg +1 -0
  11. package/templates/common/_husky/pre-commit +1 -0
  12. package/templates/common/_nvmrc +1 -0
  13. package/{template → templates/common}/_prettierignore +4 -0
  14. package/templates/common/commitlint.config.mjs +10 -0
  15. package/templates/next/README.md +328 -0
  16. package/{template → templates/next}/_env.example +10 -1
  17. package/{template → templates/next}/_gitignore +8 -0
  18. package/templates/next/e2e/rbac.spec.ts +69 -0
  19. package/templates/next/e2e/server.mjs +35 -0
  20. package/{template → templates/next}/eslint.config.mjs +12 -0
  21. package/{template → templates/next}/next.config.ts +2 -0
  22. package/{template → templates/next}/package.json +18 -3
  23. package/templates/next/playwright.config.ts +30 -0
  24. package/templates/next/scripts/seed.ts +111 -0
  25. package/templates/next/src/app/(app)/admin/audit/page.tsx +99 -0
  26. package/templates/next/src/app/(app)/admin/page.tsx +92 -0
  27. package/{template → templates/next}/src/app/(app)/dashboard/page.tsx +22 -29
  28. package/{template → templates/next}/src/app/(app)/error.tsx +7 -7
  29. package/{template → templates/next}/src/app/(app)/layout.tsx +25 -2
  30. package/templates/next/src/app/(app)/reports/page.tsx +128 -0
  31. package/templates/next/src/app/(app)/settings/page.tsx +66 -0
  32. package/templates/next/src/app/(auth)/forgot-password/page.tsx +17 -0
  33. package/templates/next/src/app/(auth)/layout.tsx +18 -0
  34. package/{template → templates/next}/src/app/(auth)/register/page.tsx +2 -4
  35. package/templates/next/src/app/(auth)/reset-password/page.tsx +18 -0
  36. package/templates/next/src/app/api/account/password/route.ts +45 -0
  37. package/templates/next/src/app/api/account/route.ts +25 -0
  38. package/templates/next/src/app/api/account/sessions/route.ts +12 -0
  39. package/templates/next/src/app/api/admin/audit/route.ts +13 -0
  40. package/{template → templates/next}/src/app/api/admin/users/[id]/route.ts +25 -4
  41. package/templates/next/src/app/api/auth/forgot-password/route.ts +47 -0
  42. package/{template → templates/next}/src/app/api/auth/login/route.ts +19 -2
  43. package/{template → templates/next}/src/app/api/auth/me/route.ts +4 -2
  44. package/{template → templates/next}/src/app/api/auth/register/route.ts +38 -4
  45. package/templates/next/src/app/api/auth/resend-verification/route.ts +25 -0
  46. package/templates/next/src/app/api/auth/reset-password/route.ts +43 -0
  47. package/templates/next/src/app/api/auth/verify-email/route.ts +29 -0
  48. package/{template → templates/next}/src/app/forbidden/page.tsx +11 -13
  49. package/{template → templates/next}/src/app/layout.tsx +9 -6
  50. package/templates/next/src/app/not-found.tsx +20 -0
  51. package/templates/next/src/app/opengraph-image.tsx +49 -0
  52. package/templates/next/src/app/page.tsx +165 -0
  53. package/templates/next/src/app/robots.ts +15 -0
  54. package/templates/next/src/app/sitemap.ts +13 -0
  55. package/templates/next/src/app/verify-email/page.tsx +23 -0
  56. package/templates/next/src/components/admin/user-actions.tsx +124 -0
  57. package/templates/next/src/components/admin/users-data-table.tsx +221 -0
  58. package/templates/next/src/components/admin/users-table.tsx +67 -0
  59. package/{template → templates/next}/src/components/auth/auth-card.tsx +8 -8
  60. package/templates/next/src/components/auth/forgot-password-form.tsx +76 -0
  61. package/templates/next/src/components/auth/form-field.tsx +40 -0
  62. package/{template → templates/next}/src/components/auth/login-form.tsx +14 -9
  63. package/templates/next/src/components/auth/password-input.tsx +43 -0
  64. package/{template → templates/next}/src/components/auth/register-form.tsx +22 -19
  65. package/templates/next/src/components/auth/reset-password-form.tsx +80 -0
  66. package/{template → templates/next}/src/components/auth/session-refresher.tsx +1 -1
  67. package/templates/next/src/components/auth/verify-email-banner.tsx +43 -0
  68. package/templates/next/src/components/auth/verify-email-status.tsx +44 -0
  69. package/templates/next/src/components/layout/nav-links.tsx +37 -0
  70. package/templates/next/src/components/layout/navbar.tsx +27 -0
  71. package/templates/next/src/components/layout/page-header.tsx +21 -0
  72. package/templates/next/src/components/layout/sidebar.tsx +83 -0
  73. package/templates/next/src/components/layout/skeletons.tsx +57 -0
  74. package/templates/next/src/components/layout/user-menu.tsx +118 -0
  75. package/{template → templates/next}/src/components/logo.tsx +3 -6
  76. package/{template → templates/next}/src/components/reports/animated-bar.tsx +1 -5
  77. package/templates/next/src/components/reports/role-chart.tsx +61 -0
  78. package/templates/next/src/components/reports/signups-chart.tsx +64 -0
  79. package/templates/next/src/components/role-badge.tsx +11 -0
  80. package/templates/next/src/components/settings/password-form.tsx +80 -0
  81. package/templates/next/src/components/settings/profile-form.tsx +63 -0
  82. package/templates/next/src/components/settings/sessions-card.tsx +70 -0
  83. package/templates/next/src/components/theme-toggle.tsx +61 -0
  84. package/templates/next/src/config/rbac.test.ts +89 -0
  85. package/{template → templates/next}/src/config/rbac.ts +35 -5
  86. package/{template → templates/next}/src/lib/api.ts +40 -4
  87. package/templates/next/src/lib/audit.ts +66 -0
  88. package/{template → templates/next}/src/lib/auth.ts +10 -2
  89. package/{template → templates/next}/src/lib/dal.ts +8 -5
  90. package/templates/next/src/lib/email-templates.ts +55 -0
  91. package/templates/next/src/lib/email.ts +53 -0
  92. package/templates/next/src/lib/env.ts +90 -0
  93. package/templates/next/src/lib/password-strength.test.ts +20 -0
  94. package/templates/next/src/lib/password-strength.ts +24 -0
  95. package/templates/next/src/lib/rate-limit.test.ts +47 -0
  96. package/templates/next/src/lib/rate-limit.ts +70 -0
  97. package/templates/next/src/lib/redirect.test.ts +23 -0
  98. package/{template → templates/next}/src/lib/session.ts +5 -1
  99. package/templates/next/src/lib/theme.ts +32 -0
  100. package/templates/next/src/lib/tokens.ts +63 -0
  101. package/{template → templates/next}/src/lib/users.ts +49 -12
  102. package/templates/next/src/lib/validations/account.ts +20 -0
  103. package/templates/next/src/lib/validations/auth.test.ts +39 -0
  104. package/{template → templates/next}/src/lib/validations/auth.ts +24 -2
  105. package/templates/next/src/models/audit-log.ts +33 -0
  106. package/templates/next/src/models/auth-token.ts +26 -0
  107. package/{template → templates/next}/src/models/user.ts +5 -0
  108. package/{template → templates/next}/src/proxy.ts +1 -1
  109. package/templates/next/src/styles/app.css +1092 -0
  110. package/{template → templates/next}/src/types/user.ts +3 -0
  111. package/templates/next/vitest.config.mts +13 -0
  112. package/templates/styles/css.css +580 -0
  113. package/templates/styles/tailwind.css +140 -0
  114. package/templates/ui/css/components/alert-dialog.tsx +172 -0
  115. package/templates/ui/css/components/avatar.tsx +17 -0
  116. package/templates/ui/css/components/badge.tsx +18 -0
  117. package/templates/ui/css/components/button.tsx +41 -0
  118. package/templates/ui/css/components/card.tsx +33 -0
  119. package/templates/ui/css/components/dropdown-menu.tsx +230 -0
  120. package/templates/ui/css/components/input.tsx +7 -0
  121. package/templates/ui/css/components/label.tsx +7 -0
  122. package/templates/ui/css/components/native-select.tsx +23 -0
  123. package/templates/ui/css/components/skeleton.tsx +7 -0
  124. package/templates/ui/css/components/slot.tsx +30 -0
  125. package/templates/ui/css/components/table.tsx +31 -0
  126. package/templates/ui/css/utils.ts +16 -0
  127. package/templates/ui/shadcn/components/alert-dialog.tsx +199 -0
  128. package/templates/ui/shadcn/components/avatar.tsx +111 -0
  129. package/templates/ui/shadcn/components/dropdown-menu.tsx +268 -0
  130. package/templates/ui/shadcn/components/table.tsx +115 -0
  131. package/templates/ui/tailwind/components/alert-dialog.tsx +177 -0
  132. package/templates/ui/tailwind/components/avatar.tsx +36 -0
  133. package/templates/ui/tailwind/components/badge.tsx +29 -0
  134. package/templates/ui/tailwind/components/button.tsx +65 -0
  135. package/templates/ui/tailwind/components/card.tsx +70 -0
  136. package/templates/ui/tailwind/components/dropdown-menu.tsx +236 -0
  137. package/templates/ui/tailwind/components/input.tsx +17 -0
  138. package/templates/ui/tailwind/components/label.tsx +16 -0
  139. package/templates/ui/tailwind/components/native-select.tsx +32 -0
  140. package/templates/ui/tailwind/components/skeleton.tsx +13 -0
  141. package/templates/ui/tailwind/components/slot.tsx +34 -0
  142. package/templates/ui/tailwind/components/table.tsx +56 -0
  143. package/templates/ui/tailwind/utils.ts +1 -0
  144. package/templates/vite/Dockerfile +29 -0
  145. package/templates/vite/README.md +142 -0
  146. package/templates/vite/_dockerignore +14 -0
  147. package/templates/vite/_env.example +8 -0
  148. package/templates/vite/_gitignore +37 -0
  149. package/templates/vite/e2e/app.spec.ts +41 -0
  150. package/templates/vite/index.html +32 -0
  151. package/templates/vite/nginx.conf +26 -0
  152. package/templates/vite/package.json +61 -0
  153. package/templates/vite/playwright.config.ts +27 -0
  154. package/templates/vite/public/favicon.svg +1 -0
  155. package/templates/vite/src/App.test.tsx +28 -0
  156. package/templates/vite/src/App.tsx +26 -0
  157. package/templates/vite/src/components/home.tsx +121 -0
  158. package/templates/vite/src/components/layout/root-layout.tsx +18 -0
  159. package/templates/vite/src/components/layout/site-footer.tsx +10 -0
  160. package/templates/vite/src/components/layout/site-header.tsx +49 -0
  161. package/templates/vite/src/components/theme-toggle.tsx +90 -0
  162. package/templates/vite/src/env.ts +36 -0
  163. package/templates/vite/src/lib/theme.ts +26 -0
  164. package/templates/vite/src/main.tsx +13 -0
  165. package/templates/vite/src/pages/about.tsx +52 -0
  166. package/templates/vite/src/pages/not-found.tsx +33 -0
  167. package/templates/vite/src/router.ts +24 -0
  168. package/templates/vite/src/styles/app.css +281 -0
  169. package/templates/vite/src/test/setup.ts +21 -0
  170. package/templates/vite/tsconfig.app.json +31 -0
  171. package/templates/vite/tsconfig.json +7 -0
  172. package/templates/vite/tsconfig.node.json +23 -0
  173. package/templates/vite/vite.config.ts +30 -0
  174. package/template/README.md +0 -262
  175. package/template/_prettierrc +0 -9
  176. package/template/components.json +0 -25
  177. package/template/src/app/(app)/admin/page.tsx +0 -53
  178. package/template/src/app/(app)/reports/page.tsx +0 -109
  179. package/template/src/app/(auth)/layout.tsx +0 -22
  180. package/template/src/app/not-found.tsx +0 -18
  181. package/template/src/app/page.tsx +0 -187
  182. package/template/src/components/admin/users-table.tsx +0 -162
  183. package/template/src/components/auth/form-field.tsx +0 -32
  184. package/template/src/components/layout/logout-button.tsx +0 -34
  185. package/template/src/components/layout/navbar.tsx +0 -67
  186. package/template/src/components/layout/page-header.tsx +0 -21
  187. package/template/src/components/layout/skeletons.tsx +0 -35
  188. package/template/src/components/role-badge.tsx +0 -17
  189. package/template/src/components/theme-toggle.tsx +0 -25
  190. package/template/src/lib/env.ts +0 -36
  191. package/template/src/lib/theme.ts +0 -8
  192. /package/{template → templates/next}/AGENTS.md +0 -0
  193. /package/{template → templates/next}/Dockerfile +0 -0
  194. /package/{template → templates/next}/_dockerignore +0 -0
  195. /package/{template → templates/next}/docker-compose.yml +0 -0
  196. /package/{template → templates/next}/public/robots.txt +0 -0
  197. /package/{template → templates/next}/src/app/(app)/loading.tsx +0 -0
  198. /package/{template → templates/next}/src/app/(auth)/login/page.tsx +0 -0
  199. /package/{template → templates/next}/src/app/api/admin/users/route.ts +0 -0
  200. /package/{template → templates/next}/src/app/api/auth/logout/route.ts +0 -0
  201. /package/{template → templates/next}/src/app/api/health/route.ts +0 -0
  202. /package/{template → templates/next}/src/app/favicon.ico +0 -0
  203. /package/{template → templates/next}/src/components/auth/can.tsx +0 -0
  204. /package/{template → templates/next}/src/components/motion/fade-in.tsx +0 -0
  205. /package/{template → templates/next}/src/components/providers/user-provider.tsx +0 -0
  206. /package/{template → templates/next}/src/config/site.ts +0 -0
  207. /package/{template → templates/next}/src/lib/db.ts +0 -0
  208. /package/{template → templates/next}/src/lib/http.ts +0 -0
  209. /package/{template → templates/next}/src/lib/redirect.ts +0 -0
  210. /package/{template → templates/next}/src/lib/validations/user.ts +0 -0
  211. /package/{template → templates/next}/tsconfig.json +0 -0
  212. /package/{template/src/app/globals.css → templates/styles/shadcn.css} +0 -0
  213. /package/{template/src/components/ui → templates/ui/shadcn/components}/badge.tsx +0 -0
  214. /package/{template/src/components/ui → templates/ui/shadcn/components}/button.tsx +0 -0
  215. /package/{template/src/components/ui → templates/ui/shadcn/components}/card.tsx +0 -0
  216. /package/{template/src/components/ui → templates/ui/shadcn/components}/input.tsx +0 -0
  217. /package/{template/src/components/ui → templates/ui/shadcn/components}/label.tsx +0 -0
  218. /package/{template/src/components/ui → templates/ui/shadcn/components}/native-select.tsx +0 -0
  219. /package/{template/src/components/ui → templates/ui/shadcn/components}/skeleton.tsx +0 -0
  220. /package/{template/src/lib → templates/ui/shadcn}/utils.ts +0 -0
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Fixed-window rate limiting, kept in memory.
3
+ *
4
+ * Good for a single server instance (and for development). When you run
5
+ * several instances (serverless, multiple containers), swap the Map for a
6
+ * shared store such as Redis / Upstash so all instances see the same counts.
7
+ */
8
+
9
+ type Bucket = { count: number; resetAt: number };
10
+
11
+ const globalForRateLimit = globalThis as typeof globalThis & {
12
+ __rateLimitBuckets?: Map<string, Bucket>;
13
+ };
14
+ const buckets: Map<string, Bucket> = (globalForRateLimit.__rateLimitBuckets ??= new Map());
15
+
16
+ export type RateLimitOptions = {
17
+ /** Max requests allowed per window. */
18
+ limit: number;
19
+ /** Window length in milliseconds. */
20
+ windowMs: number;
21
+ };
22
+
23
+ export type RateLimitResult = {
24
+ success: boolean;
25
+ remaining: number;
26
+ /** Milliseconds until the window resets. */
27
+ retryAfterMs: number;
28
+ };
29
+
30
+ function sweep(now: number) {
31
+ // Cheap housekeeping so the map can't grow forever.
32
+ if (buckets.size < 10_000) return;
33
+ for (const [key, bucket] of buckets) if (bucket.resetAt <= now) buckets.delete(key);
34
+ }
35
+
36
+ export function rateLimit(key: string, { limit, windowMs }: RateLimitOptions): RateLimitResult {
37
+ const now = Date.now();
38
+ sweep(now);
39
+ let bucket = buckets.get(key);
40
+ if (!bucket || bucket.resetAt <= now) {
41
+ bucket = { count: 0, resetAt: now + windowMs };
42
+ buckets.set(key, bucket);
43
+ }
44
+ bucket.count += 1;
45
+ return {
46
+ success: bucket.count <= limit,
47
+ remaining: Math.max(0, limit - bucket.count),
48
+ retryAfterMs: Math.max(0, bucket.resetAt - now),
49
+ };
50
+ }
51
+
52
+ /** Best-effort client IP (behind a proxy, make sure it sets X-Forwarded-For). */
53
+ export function getClientIp(req: Request): string {
54
+ const forwarded = req.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
55
+ return forwarded || req.headers.get("x-real-ip") || "unknown";
56
+ }
57
+
58
+ /** Clears all counters (useful in tests). */
59
+ export function resetRateLimits() {
60
+ buckets.clear();
61
+ }
62
+
63
+ /** Per-endpoint limits. Tune these for your app. */
64
+ export const RATE_LIMITS = {
65
+ login: { limit: 10, windowMs: 15 * 60_000 },
66
+ loginPerEmail: { limit: 20, windowMs: 60 * 60_000 },
67
+ register: { limit: 10, windowMs: 60 * 60_000 },
68
+ passwordReset: { limit: 5, windowMs: 15 * 60_000 },
69
+ sensitive: { limit: 5, windowMs: 15 * 60_000 },
70
+ } satisfies Record<string, RateLimitOptions>;
@@ -0,0 +1,23 @@
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import { safeRedirectPath } from "./redirect";
4
+
5
+ describe("safeRedirectPath", () => {
6
+ it("keeps same-origin paths", () => {
7
+ expect(safeRedirectPath("/reports")).toBe("/reports");
8
+ expect(safeRedirectPath("/admin?tab=1#top")).toBe("/admin?tab=1#top");
9
+ });
10
+
11
+ it("blocks open redirects", () => {
12
+ expect(safeRedirectPath("https://evil.com")).toBe("/dashboard");
13
+ expect(safeRedirectPath("//evil.com")).toBe("/dashboard");
14
+ expect(safeRedirectPath("/\\evil.com")).toBe("/dashboard");
15
+ });
16
+
17
+ it("falls back for empty values and guest-only pages", () => {
18
+ expect(safeRedirectPath(null)).toBe("/dashboard");
19
+ expect(safeRedirectPath("")).toBe("/dashboard");
20
+ expect(safeRedirectPath("/login")).toBe("/dashboard");
21
+ expect(safeRedirectPath(undefined, "/home")).toBe("/home");
22
+ });
23
+ });
@@ -20,6 +20,8 @@ const payloadSchema = z.object({
20
20
  sub: z.string().min(1),
21
21
  role: z.enum(ROLES),
22
22
  name: z.string(),
23
+ // Token version: bumping it in the DB signs out every existing session.
24
+ ver: z.number().int().nonnegative().default(0),
23
25
  });
24
26
 
25
27
  export type SessionPayload = {
@@ -27,6 +29,8 @@ export type SessionPayload = {
27
29
  sub: string;
28
30
  role: Role;
29
31
  name: string;
32
+ /** Must match the user's tokenVersion in the database (checked by the DAL). */
33
+ ver: number;
30
34
  };
31
35
 
32
36
  function getKey() {
@@ -34,7 +38,7 @@ function getKey() {
34
38
  }
35
39
 
36
40
  export async function signSession(payload: SessionPayload): Promise<string> {
37
- return new SignJWT({ role: payload.role, name: payload.name })
41
+ return new SignJWT({ role: payload.role, name: payload.name, ver: payload.ver })
38
42
  .setProtectedHeader({ alg: ALGORITHM })
39
43
  .setSubject(payload.sub)
40
44
  .setIssuedAt()
@@ -0,0 +1,32 @@
1
+ export const THEME_STORAGE_KEY = "theme";
2
+ export const THEMES = ["light", "dark", "system"] as const;
3
+ export type Theme = (typeof THEMES)[number];
4
+
5
+ /**
6
+ * Runs in <head> before first paint so the page never flashes the wrong theme.
7
+ * "system" (or nothing saved) follows the OS setting, including live changes.
8
+ * See node_modules/next/dist/docs/01-app/02-guides/preventing-flash-before-hydration.md
9
+ */
10
+ export const themeScript = `(function(){try{var k="${THEME_STORAGE_KEY}",m=window.matchMedia("(prefers-color-scheme: dark)");function a(){var t=localStorage.getItem(k);document.documentElement.classList.toggle("dark",t==="dark"||((!t||t==="system")&&m.matches))}a();m.addEventListener("change",a);window.addEventListener("storage",function(e){if(e.key===k)a()})}catch(e){}})()`;
11
+
12
+ export function readTheme(): Theme {
13
+ try {
14
+ const value = localStorage.getItem(THEME_STORAGE_KEY);
15
+ return value === "light" || value === "dark" ? value : "system";
16
+ } catch {
17
+ return "system";
18
+ }
19
+ }
20
+
21
+ /** Saves the preference and applies it immediately. */
22
+ export function applyTheme(theme: Theme) {
23
+ try {
24
+ localStorage.setItem(THEME_STORAGE_KEY, theme);
25
+ } catch {
26
+ // Storage unavailable (private mode): the choice just won't persist.
27
+ }
28
+ const dark =
29
+ theme === "dark" ||
30
+ (theme === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches);
31
+ document.documentElement.classList.toggle("dark", dark);
32
+ }
@@ -0,0 +1,63 @@
1
+ import "server-only";
2
+
3
+ import crypto from "node:crypto";
4
+
5
+ import { connectDB } from "@/lib/db";
6
+ import { sendEmail } from "@/lib/email";
7
+ import { passwordResetEmail, verificationEmail } from "@/lib/email-templates";
8
+ import { appUrl } from "@/lib/env";
9
+ import { AuthToken, type AuthTokenType } from "@/models/auth-token";
10
+
11
+ export const TOKEN_TTL: Record<AuthTokenType, number> = {
12
+ "password-reset": 60 * 60 * 1000, // 1 hour
13
+ "email-verification": 24 * 60 * 60 * 1000, // 24 hours
14
+ };
15
+
16
+ function hashToken(token: string): string {
17
+ return crypto.createHash("sha256").update(token).digest("hex");
18
+ }
19
+
20
+ /**
21
+ * Creates a one-time token and returns the raw value (send it to the user).
22
+ * Any previous token of the same type for that user stops working.
23
+ */
24
+ export async function createToken(userId: string, type: AuthTokenType): Promise<string> {
25
+ await connectDB();
26
+ const token = crypto.randomBytes(32).toString("base64url");
27
+ await AuthToken.deleteMany({ userId, type });
28
+ await AuthToken.create({
29
+ userId,
30
+ type,
31
+ tokenHash: hashToken(token),
32
+ expiresAt: new Date(Date.now() + TOKEN_TTL[type]),
33
+ });
34
+ return token;
35
+ }
36
+
37
+ /** Verifies and deletes a token in one step. Returns the user id, or null if invalid/expired. */
38
+ export async function consumeToken(token: string, type: AuthTokenType): Promise<string | null> {
39
+ if (!token || token.length > 200) return null;
40
+ await connectDB();
41
+ const doc = await AuthToken.findOneAndDelete({
42
+ tokenHash: hashToken(token),
43
+ type,
44
+ expiresAt: { $gt: new Date() },
45
+ }).lean();
46
+ return doc ? String(doc.userId) : null;
47
+ }
48
+
49
+ type Recipient = { id: string; name: string; email: string };
50
+
51
+ /** Creates a verification token and emails the link (GET /api/auth/verify-email?token=...). */
52
+ export async function sendVerificationEmail(user: Recipient): Promise<void> {
53
+ const token = await createToken(user.id, "email-verification");
54
+ const url = `${appUrl()}/api/auth/verify-email?token=${encodeURIComponent(token)}`;
55
+ await sendEmail(verificationEmail(user.email, user.name, url));
56
+ }
57
+
58
+ /** Creates a password-reset token and emails the link to /reset-password. */
59
+ export async function sendPasswordResetEmail(user: Recipient): Promise<void> {
60
+ const token = await createToken(user.id, "password-reset");
61
+ const url = `${appUrl()}/reset-password?token=${encodeURIComponent(token)}`;
62
+ await sendEmail(passwordResetEmail(user.email, user.name, url));
63
+ }
@@ -14,6 +14,9 @@ import type { PublicUser } from "@/types/user";
14
14
 
15
15
  type UserLike = Pick<UserDocument, "_id" | "name" | "email" | "role"> & {
16
16
  createdAt?: Date | string;
17
+ // @feature email
18
+ emailVerifiedAt?: Date | null;
19
+ // @end email
17
20
  };
18
21
 
19
22
  export function toPublicUser(user: UserLike): PublicUser {
@@ -23,6 +26,9 @@ export function toPublicUser(user: UserLike): PublicUser {
23
26
  email: user.email,
24
27
  role: user.role as Role,
25
28
  createdAt: new Date(user.createdAt ?? Date.now()).toISOString(),
29
+ // @feature email
30
+ emailVerified: Boolean(user.emailVerifiedAt),
31
+ // @end email
26
32
  };
27
33
  }
28
34
 
@@ -37,6 +43,27 @@ export async function findUserById(id: string): Promise<PublicUser | null> {
37
43
  return user ? toPublicUser(user) : null;
38
44
  }
39
45
 
46
+ /** The user plus their current token version (for validating sessions). */
47
+ export async function findSessionUser(
48
+ id: string,
49
+ ): Promise<{ user: PublicUser; tokenVersion: number } | null> {
50
+ if (!isValidId(id)) return null;
51
+ await connectDB();
52
+ const doc = await User.findById(id).lean();
53
+ return doc ? { user: toPublicUser(doc), tokenVersion: doc.tokenVersion ?? 0 } : null;
54
+ }
55
+
56
+ /** Invalidates every session of the user. Returns the new token version. */
57
+ export async function bumpTokenVersion(id: string): Promise<number> {
58
+ await connectDB();
59
+ const doc = await User.findByIdAndUpdate(
60
+ id,
61
+ { $inc: { tokenVersion: 1 } },
62
+ { returnDocument: "after" },
63
+ ).lean();
64
+ return doc?.tokenVersion ?? 0;
65
+ }
66
+
40
67
  export async function listUsers({ page = 1, limit = 50 } = {}): Promise<{
41
68
  users: PublicUser[];
42
69
  total: number;
@@ -53,22 +80,28 @@ export async function listUsers({ page = 1, limit = 50 } = {}): Promise<{
53
80
  return { users: docs.map(toPublicUser), total };
54
81
  }
55
82
 
56
- export async function updateUserRole(id: string, role: Role): Promise<PublicUser | null> {
83
+ /** Changes a user's role. Returns the updated user and their previous role, or null if not found. */
84
+ export async function updateUserRole(
85
+ id: string,
86
+ role: Role,
87
+ ): Promise<{ user: PublicUser; previousRole: Role } | null> {
57
88
  if (!isValidId(id)) return null;
58
89
  await connectDB();
59
- const user = await User.findByIdAndUpdate(
90
+ const before = await User.findByIdAndUpdate(
60
91
  id,
61
92
  { role },
62
- { returnDocument: "after", runValidators: true },
93
+ { returnDocument: "before", runValidators: true },
63
94
  ).lean();
64
- return user ? toPublicUser(user) : null;
95
+ if (!before) return null;
96
+ return { user: { ...toPublicUser(before), role }, previousRole: before.role as Role };
65
97
  }
66
98
 
67
- export async function deleteUser(id: string): Promise<boolean> {
68
- if (!isValidId(id)) return false;
99
+ /** Deletes a user. Returns the deleted user, or null if not found. */
100
+ export async function deleteUser(id: string): Promise<PublicUser | null> {
101
+ if (!isValidId(id)) return null;
69
102
  await connectDB();
70
- const result = await User.deleteOne({ _id: id });
71
- return result.deletedCount === 1;
103
+ const deleted = await User.findByIdAndDelete(id).lean();
104
+ return deleted ? toPublicUser(deleted) : null;
72
105
  }
73
106
 
74
107
  export function isDuplicateKeyError(error: unknown): boolean {
@@ -111,10 +144,14 @@ export async function releaseFirstAdmin(): Promise<void> {
111
144
  .deleteOne({ _id: FIRST_ADMIN_KEY });
112
145
  }
113
146
 
147
+ /** Number of days shown in the sign-ups report. */
148
+ export const SIGNUP_DAYS = 14;
149
+
114
150
  export type UserStats = {
115
151
  total: number;
116
152
  byRole: Record<Role, number>;
117
- newLast7Days: number;
153
+ /** Sign-ups in the last SIGNUP_DAYS days. */
154
+ newInPeriod: number;
118
155
  signupsByDay: { date: string; count: number }[];
119
156
  };
120
157
 
@@ -122,7 +159,7 @@ export async function getUserStats(): Promise<UserStats> {
122
159
  await connectDB();
123
160
  const since = new Date();
124
161
  since.setUTCHours(0, 0, 0, 0);
125
- since.setUTCDate(since.getUTCDate() - 6);
162
+ since.setUTCDate(since.getUTCDate() - (SIGNUP_DAYS - 1));
126
163
 
127
164
  const [roleCounts, daily] = await Promise.all([
128
165
  User.aggregate<{ _id: Role; count: number }>([
@@ -143,7 +180,7 @@ export async function getUserStats(): Promise<UserStats> {
143
180
  for (const { _id, count } of roleCounts) if (_id in byRole) byRole[_id] = count;
144
181
 
145
182
  const dailyMap = new Map(daily.map((d) => [d._id, d.count]));
146
- const signupsByDay = Array.from({ length: 7 }, (_, i) => {
183
+ const signupsByDay = Array.from({ length: SIGNUP_DAYS }, (_, i) => {
147
184
  const day = new Date(since);
148
185
  day.setUTCDate(since.getUTCDate() + i);
149
186
  const key = day.toISOString().slice(0, 10);
@@ -153,7 +190,7 @@ export async function getUserStats(): Promise<UserStats> {
153
190
  return {
154
191
  total: Object.values(byRole).reduce((a, b) => a + b, 0),
155
192
  byRole,
156
- newLast7Days: signupsByDay.reduce((a, d) => a + d.count, 0),
193
+ newInPeriod: signupsByDay.reduce((a, d) => a + d.count, 0),
157
194
  signupsByDay,
158
195
  };
159
196
  }
@@ -0,0 +1,20 @@
1
+ import { z } from "zod";
2
+
3
+ import { passwordSchema, registerSchema } from "@/lib/validations/auth";
4
+
5
+ export const updateProfileSchema = registerSchema.pick({ name: true });
6
+ export type UpdateProfileInput = z.infer<typeof updateProfileSchema>;
7
+
8
+ export const changePasswordSchema = z.object({
9
+ currentPassword: z.string().min(1, "Enter your current password"),
10
+ newPassword: passwordSchema,
11
+ });
12
+ export type ChangePasswordInput = z.infer<typeof changePasswordSchema>;
13
+
14
+ /** Client-only extension with a confirmation field. */
15
+ export const changePasswordFormSchema = changePasswordSchema
16
+ .extend({ confirmPassword: z.string().min(1, "Please confirm your new password") })
17
+ .refine((data) => data.newPassword === data.confirmPassword, {
18
+ message: "Passwords do not match",
19
+ path: ["confirmPassword"],
20
+ });
@@ -0,0 +1,39 @@
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import { loginSchema, registerFormSchema, registerSchema } from "./auth";
4
+
5
+ describe("auth schemas", () => {
6
+ it("normalizes emails", () => {
7
+ const result = loginSchema.parse({ email: " Ada@Example.COM ", password: "x" });
8
+ expect(result.email).toBe("ada@example.com");
9
+ });
10
+
11
+ it("rejects short passwords and names", () => {
12
+ const result = registerSchema.safeParse({ name: "A", email: "a@b.co", password: "short" });
13
+ expect(result.success).toBe(false);
14
+ if (!result.success) {
15
+ const fields = result.error.issues.map((i) => i.path[0]);
16
+ expect(fields).toContain("name");
17
+ expect(fields).toContain("password");
18
+ }
19
+ });
20
+
21
+ it("rejects passwords longer than bcrypt can use (72 bytes)", () => {
22
+ const result = registerSchema.safeParse({
23
+ name: "Ada",
24
+ email: "ada@example.com",
25
+ password: "a".repeat(73),
26
+ });
27
+ expect(result.success).toBe(false);
28
+ });
29
+
30
+ it("requires matching confirmation on the register form", () => {
31
+ const result = registerFormSchema.safeParse({
32
+ name: "Ada",
33
+ email: "ada@example.com",
34
+ password: "correct-horse",
35
+ confirmPassword: "correct-horsf",
36
+ });
37
+ expect(result.success).toBe(false);
38
+ });
39
+ });
@@ -12,7 +12,7 @@ const email = z
12
12
  .pipe(z.email("Enter a valid email address").max(254, "Email is too long"));
13
13
 
14
14
  // bcrypt only uses the first 72 bytes of a password.
15
- const password = z
15
+ export const passwordSchema = z
16
16
  .string()
17
17
  .min(8, "Password must be at least 8 characters")
18
18
  .refine((value) => new TextEncoder().encode(value).length <= 72, "Password is too long");
@@ -30,7 +30,7 @@ export const registerSchema = z.object({
30
30
  .min(2, "Name must be at least 2 characters")
31
31
  .max(80, "Name must be at most 80 characters"),
32
32
  email,
33
- password,
33
+ password: passwordSchema,
34
34
  });
35
35
  export type RegisterInput = z.infer<typeof registerSchema>;
36
36
 
@@ -42,3 +42,25 @@ export const registerFormSchema = registerSchema
42
42
  path: ["confirmPassword"],
43
43
  });
44
44
  export type RegisterFormInput = z.infer<typeof registerFormSchema>;
45
+ // @feature email
46
+
47
+ export const forgotPasswordSchema = z.object({ email });
48
+ export type ForgotPasswordInput = z.infer<typeof forgotPasswordSchema>;
49
+
50
+ export const resetPasswordSchema = z.object({
51
+ token: z.string().min(1, "Missing reset token"),
52
+ password: passwordSchema,
53
+ });
54
+ export type ResetPasswordInput = z.infer<typeof resetPasswordSchema>;
55
+
56
+ /** Client-only extension with a confirmation field. */
57
+ export const resetPasswordFormSchema = z
58
+ .object({
59
+ password: passwordSchema,
60
+ confirmPassword: z.string().min(1, "Please confirm your password"),
61
+ })
62
+ .refine((data) => data.password === data.confirmPassword, {
63
+ message: "Passwords do not match",
64
+ path: ["confirmPassword"],
65
+ });
66
+ // @end email
@@ -0,0 +1,33 @@
1
+ import "server-only";
2
+
3
+ import mongoose, { Schema, type InferSchemaType, type Model } from "mongoose";
4
+
5
+ export const AUDIT_ACTIONS = ["user.role_changed", "user.deleted"] as const;
6
+ export type AuditAction = (typeof AUDIT_ACTIONS)[number];
7
+
8
+ const personSchema = new Schema(
9
+ { id: { type: String, required: true }, name: String, email: String },
10
+ { _id: false },
11
+ );
12
+
13
+ /** An append-only record of who did what to whom. */
14
+ const auditLogSchema = new Schema(
15
+ {
16
+ action: { type: String, enum: AUDIT_ACTIONS, required: true, index: true },
17
+ actor: { type: personSchema, required: true },
18
+ target: { type: personSchema, required: true },
19
+ details: { type: Schema.Types.Mixed, default: {} },
20
+ ip: { type: String, default: null },
21
+ },
22
+ { timestamps: { createdAt: true, updatedAt: false } },
23
+ );
24
+ auditLogSchema.index({ createdAt: -1 });
25
+
26
+ export type AuditLogDocument = InferSchemaType<typeof auditLogSchema> & {
27
+ _id: mongoose.Types.ObjectId;
28
+ createdAt: Date;
29
+ };
30
+
31
+ export const AuditLog: Model<AuditLogDocument> =
32
+ (mongoose.models.AuditLog as Model<AuditLogDocument> | undefined) ??
33
+ mongoose.model<AuditLogDocument>("AuditLog", auditLogSchema);
@@ -0,0 +1,26 @@
1
+ import "server-only";
2
+
3
+ import mongoose, { Schema, type InferSchemaType, type Model } from "mongoose";
4
+
5
+ export const AUTH_TOKEN_TYPES = ["password-reset", "email-verification"] as const;
6
+ export type AuthTokenType = (typeof AUTH_TOKEN_TYPES)[number];
7
+
8
+ /** One-time tokens for password resets and email verification. Only a hash is stored. */
9
+ const authTokenSchema = new Schema(
10
+ {
11
+ userId: { type: Schema.Types.ObjectId, ref: "User", required: true, index: true },
12
+ type: { type: String, enum: AUTH_TOKEN_TYPES, required: true },
13
+ tokenHash: { type: String, required: true, unique: true },
14
+ // MongoDB deletes the document automatically once this date passes.
15
+ expiresAt: { type: Date, required: true, expires: 0 },
16
+ },
17
+ { timestamps: { createdAt: true, updatedAt: false } },
18
+ );
19
+
20
+ export type AuthTokenDocument = InferSchemaType<typeof authTokenSchema> & {
21
+ _id: mongoose.Types.ObjectId;
22
+ };
23
+
24
+ export const AuthToken: Model<AuthTokenDocument> =
25
+ (mongoose.models.AuthToken as Model<AuthTokenDocument> | undefined) ??
26
+ mongoose.model<AuthTokenDocument>("AuthToken", authTokenSchema);
@@ -18,6 +18,11 @@ const userSchema = new Schema(
18
18
  // bcrypt hash. Excluded from queries unless explicitly selected with "+password".
19
19
  password: { type: String, required: true, select: false },
20
20
  role: { type: String, enum: ROLES, default: DEFAULT_ROLE, required: true, index: true },
21
+ // Incremented to invalidate every existing session (password change, "sign out everywhere").
22
+ tokenVersion: { type: Number, default: 0, required: true },
23
+ // @feature email
24
+ emailVerifiedAt: { type: Date, default: null },
25
+ // @end email
21
26
  },
22
27
  { timestamps: true },
23
28
  );
@@ -42,7 +42,7 @@ export async function proxy(request: NextRequest) {
42
42
  return response;
43
43
  }
44
44
 
45
- if (!hasPermission(session.role, rule.permission)) {
45
+ if (rule.permission && !hasPermission(session.role, rule.permission)) {
46
46
  const forbiddenUrl = new URL(FORBIDDEN_PATH, request.url);
47
47
  forbiddenUrl.searchParams.set("from", pathname);
48
48
  return NextResponse.redirect(forbiddenUrl);