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,89 @@
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import {
4
+ getNavItems,
5
+ getRouteRule,
6
+ hasPermission,
7
+ isGuestOnlyRoute,
8
+ isRole,
9
+ isRoleAtLeast,
10
+ PERMISSIONS,
11
+ ROLE_PERMISSIONS,
12
+ ROLES,
13
+ } from "./rbac";
14
+
15
+ describe("hasPermission", () => {
16
+ it("gives users only the dashboard", () => {
17
+ expect(hasPermission("user", "dashboard:view")).toBe(true);
18
+ expect(hasPermission("user", "reports:view")).toBe(false);
19
+ expect(hasPermission("user", "users:read")).toBe(false);
20
+ });
21
+
22
+ it("lets managers read but not change users", () => {
23
+ expect(hasPermission("manager", "reports:view")).toBe(true);
24
+ expect(hasPermission("manager", "users:read")).toBe(true);
25
+ expect(hasPermission("manager", "users:update-role")).toBe(false);
26
+ expect(hasPermission("manager", "users:delete")).toBe(false);
27
+ });
28
+
29
+ it("gives admins every permission", () => {
30
+ for (const permission of PERMISSIONS) expect(hasPermission("admin", permission)).toBe(true);
31
+ });
32
+
33
+ it("denies a missing role", () => {
34
+ expect(hasPermission(null, "dashboard:view")).toBe(false);
35
+ expect(hasPermission(undefined, "dashboard:view")).toBe(false);
36
+ });
37
+
38
+ it("never lets a lower role have a permission a higher role lacks", () => {
39
+ for (let i = 1; i < ROLES.length; i++) {
40
+ for (const permission of ROLE_PERMISSIONS[ROLES[i - 1]]) {
41
+ expect(hasPermission(ROLES[i], permission)).toBe(true);
42
+ }
43
+ }
44
+ });
45
+ });
46
+
47
+ describe("roles", () => {
48
+ it("validates role names", () => {
49
+ expect(isRole("admin")).toBe(true);
50
+ expect(isRole("superuser")).toBe(false);
51
+ expect(isRole(42)).toBe(false);
52
+ });
53
+
54
+ it("orders roles from user to admin", () => {
55
+ expect(isRoleAtLeast("admin", "manager")).toBe(true);
56
+ expect(isRoleAtLeast("user", "manager")).toBe(false);
57
+ });
58
+ });
59
+
60
+ describe("getRouteRule", () => {
61
+ it("matches on segment boundaries", () => {
62
+ expect(getRouteRule("/admin")?.permission).toBe("users:read");
63
+ expect(getRouteRule("/admin/anything")?.permission).toBe("users:read");
64
+ expect(getRouteRule("/administrator")).toBeNull();
65
+ });
66
+
67
+ it("returns null for public pages", () => {
68
+ expect(getRouteRule("/")).toBeNull();
69
+ expect(getRouteRule("/login")).toBeNull();
70
+ });
71
+ // @feature audit-log
72
+
73
+ it("prefers the longest matching prefix", () => {
74
+ expect(getRouteRule("/admin/audit")?.permission).toBe("audit:read");
75
+ });
76
+ // @end audit-log
77
+ });
78
+
79
+ describe("navigation", () => {
80
+ it("only lists pages the role may open", () => {
81
+ expect(getNavItems("user").map((i) => i.href)).toEqual(["/dashboard"]);
82
+ expect(getNavItems("admin").map((i) => i.href)).toEqual(["/dashboard", "/reports", "/admin"]);
83
+ });
84
+
85
+ it("knows the guest-only pages", () => {
86
+ expect(isGuestOnlyRoute("/login")).toBe(true);
87
+ expect(isGuestOnlyRoute("/dashboard")).toBe(false);
88
+ });
89
+ });
@@ -24,13 +24,25 @@ export const PERMISSIONS = [
24
24
  "users:read",
25
25
  "users:update-role",
26
26
  "users:delete",
27
+ // @feature audit-log
28
+ "audit:read",
29
+ // @end audit-log
27
30
  ] as const;
28
31
  export type Permission = (typeof PERMISSIONS)[number];
29
32
 
30
33
  export const ROLE_PERMISSIONS: Record<Role, readonly Permission[]> = {
31
34
  user: ["dashboard:view"],
32
35
  manager: ["dashboard:view", "reports:view", "users:read"],
33
- admin: ["dashboard:view", "reports:view", "users:read", "users:update-role", "users:delete"],
36
+ admin: [
37
+ "dashboard:view",
38
+ "reports:view",
39
+ "users:read",
40
+ "users:update-role",
41
+ "users:delete",
42
+ // @feature audit-log
43
+ "audit:read",
44
+ // @end audit-log
45
+ ],
34
46
  };
35
47
 
36
48
  export const ROLE_LABELS: Record<Role, string> = {
@@ -45,6 +57,9 @@ export const PERMISSION_LABELS: Record<Permission, string> = {
45
57
  "users:read": "View all users",
46
58
  "users:update-role": "Change user roles",
47
59
  "users:delete": "Delete users",
60
+ // @feature audit-log
61
+ "audit:read": "View the audit log",
62
+ // @end audit-log
48
63
  };
49
64
 
50
65
  export function isRole(value: unknown): value is Role {
@@ -76,22 +91,37 @@ export function isRoleAtLeast(role: Role, minimum: Role): boolean {
76
91
  export type RouteRule = {
77
92
  /** Path prefix, matched on segment boundaries ("/admin" matches "/admin/x" but not "/administrator"). */
78
93
  prefix: string;
79
- permission: Permission;
94
+ /** Required permission. Omit it to only require a signed-in user. */
95
+ permission?: Permission;
80
96
  };
81
97
 
82
98
  /**
83
- * Pages that require a permission. The longest matching prefix wins, so you can
84
- * tighten sub-routes, e.g. { prefix: "/admin/billing", permission: "users:delete" }.
99
+ * Pages that require a signed-in user (and optionally a permission). The
100
+ * longest matching prefix wins, so sub-routes can be tightened, e.g.
101
+ * { prefix: "/admin/billing", permission: "users:delete" }.
85
102
  * API routes are protected separately with withAuth() (see src/lib/api.ts).
86
103
  */
87
104
  export const ROUTE_RULES: readonly RouteRule[] = [
88
105
  { prefix: "/dashboard", permission: "dashboard:view" },
89
106
  { prefix: "/reports", permission: "reports:view" },
90
107
  { prefix: "/admin", permission: "users:read" },
108
+ // @feature audit-log
109
+ { prefix: "/admin/audit", permission: "audit:read" },
110
+ // @end audit-log
111
+ // @feature profile
112
+ { prefix: "/settings" },
113
+ // @end profile
91
114
  ];
92
115
 
93
116
  /** Pages only for signed-out visitors; signed-in users are sent to AFTER_LOGIN_PATH. */
94
- export const GUEST_ONLY_ROUTES: readonly string[] = ["/login", "/register"];
117
+ export const GUEST_ONLY_ROUTES: readonly string[] = [
118
+ "/login",
119
+ "/register",
120
+ // @feature email
121
+ "/forgot-password",
122
+ "/reset-password",
123
+ // @end email
124
+ ];
95
125
 
96
126
  export const LOGIN_PATH = "/login";
97
127
  export const AFTER_LOGIN_PATH = "/dashboard";
@@ -6,6 +6,9 @@ import { z } from "zod";
6
6
 
7
7
  import { hasPermission, type Permission } from "@/config/rbac";
8
8
  import { getCurrentUser } from "@/lib/dal";
9
+ // @feature rate-limit
10
+ import { rateLimit, type RateLimitOptions } from "@/lib/rate-limit";
11
+ // @end rate-limit
9
12
  import type { PublicUser } from "@/types/user";
10
13
 
11
14
  /**
@@ -23,13 +26,22 @@ export class ApiError extends Error {
23
26
  readonly status: number;
24
27
  readonly code: string;
25
28
  readonly details?: unknown;
29
+ /** Extra response headers, e.g. Retry-After for 429 responses. */
30
+ readonly headers?: Record<string, string>;
26
31
 
27
- constructor(status: number, message: string, code = "BAD_REQUEST", details?: unknown) {
32
+ constructor(
33
+ status: number,
34
+ message: string,
35
+ code = "BAD_REQUEST",
36
+ details?: unknown,
37
+ headers?: Record<string, string>,
38
+ ) {
28
39
  super(message);
29
40
  this.name = "ApiError";
30
41
  this.status = status;
31
42
  this.code = code;
32
43
  this.details = details;
44
+ this.headers = headers;
33
45
  }
34
46
 
35
47
  static badRequest(message = "Bad request", code = "BAD_REQUEST", details?: unknown) {
@@ -47,18 +59,42 @@ export class ApiError extends Error {
47
59
  static conflict(message: string) {
48
60
  return new ApiError(409, message, "CONFLICT");
49
61
  }
62
+ static tooManyRequests(retryAfterMs: number) {
63
+ const seconds = Math.max(1, Math.ceil(retryAfterMs / 1000));
64
+ return new ApiError(
65
+ 429,
66
+ "Too many requests. Please try again later.",
67
+ "RATE_LIMITED",
68
+ { retryAfter: seconds },
69
+ { "Retry-After": String(seconds) },
70
+ );
71
+ }
50
72
  }
73
+ // @feature rate-limit
51
74
 
52
- export function errorResponse(status: number, code: string, message: string, details?: unknown) {
75
+ /** Throws a 429 ApiError when `key` has exceeded its limit. */
76
+ export function enforceRateLimit(key: string, options: RateLimitOptions) {
77
+ const result = rateLimit(key, options);
78
+ if (!result.success) throw ApiError.tooManyRequests(result.retryAfterMs);
79
+ }
80
+ // @end rate-limit
81
+
82
+ export function errorResponse(
83
+ status: number,
84
+ code: string,
85
+ message: string,
86
+ details?: unknown,
87
+ headers?: Record<string, string>,
88
+ ) {
53
89
  const body: ApiErrorBody = {
54
90
  error: { code, message, ...(details !== undefined && { details }) },
55
91
  };
56
- return NextResponse.json(body, { status });
92
+ return NextResponse.json(body, { status, headers });
57
93
  }
58
94
 
59
95
  export function handleApiError(error: unknown): NextResponse<ApiErrorBody> {
60
96
  if (error instanceof ApiError) {
61
- return errorResponse(error.status, error.code, error.message, error.details);
97
+ return errorResponse(error.status, error.code, error.message, error.details, error.headers);
62
98
  }
63
99
  if (error instanceof z.ZodError) {
64
100
  return errorResponse(
@@ -0,0 +1,66 @@
1
+ import "server-only";
2
+
3
+ import { connectDB } from "@/lib/db";
4
+ import { AuditLog, type AuditAction } from "@/models/audit-log";
5
+ import type { PublicUser } from "@/types/user";
6
+
7
+ type Person = Pick<PublicUser, "id" | "name" | "email">;
8
+
9
+ export type AuditEntry = {
10
+ id: string;
11
+ action: AuditAction;
12
+ actor: Person;
13
+ target: Person;
14
+ details: Record<string, unknown>;
15
+ ip: string | null;
16
+ createdAt: string;
17
+ };
18
+
19
+ const person = ({ id, name, email }: Person): Person => ({ id, name, email });
20
+
21
+ function clientIp(req?: Request): string | null {
22
+ if (!req) return null;
23
+ return req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || req.headers.get("x-real-ip");
24
+ }
25
+
26
+ /**
27
+ * Records an admin action. Never throws: a failed audit write is logged but
28
+ * doesn't break the action that triggered it.
29
+ */
30
+ export async function recordAudit(
31
+ action: AuditAction,
32
+ { actor, target, details = {}, req }: {
33
+ actor: Person;
34
+ target: Person;
35
+ details?: Record<string, unknown>;
36
+ req?: Request;
37
+ },
38
+ ): Promise<void> {
39
+ try {
40
+ await connectDB();
41
+ await AuditLog.create({
42
+ action,
43
+ actor: person(actor),
44
+ target: person(target),
45
+ details,
46
+ ip: clientIp(req),
47
+ });
48
+ } catch (error) {
49
+ console.error("[audit] Failed to record", action, error);
50
+ }
51
+ }
52
+
53
+ /** Most recent entries first. Callers must check the audit:read permission. */
54
+ export async function listAuditEntries(limit = 100): Promise<AuditEntry[]> {
55
+ await connectDB();
56
+ const docs = await AuditLog.find().sort({ createdAt: -1 }).limit(limit).lean();
57
+ return docs.map((doc) => ({
58
+ id: String(doc._id),
59
+ action: doc.action as AuditAction,
60
+ actor: { id: doc.actor.id, name: doc.actor.name ?? "", email: doc.actor.email ?? "" },
61
+ target: { id: doc.target.id, name: doc.target.name ?? "", email: doc.target.email ?? "" },
62
+ details: (doc.details ?? {}) as Record<string, unknown>,
63
+ ip: doc.ip ?? null,
64
+ createdAt: new Date(doc.createdAt).toISOString(),
65
+ }));
66
+ }
@@ -31,9 +31,17 @@ export function verifyPassword(
31
31
  return bcrypt.compare(password, hash ?? DUMMY_HASH).then((ok) => ok && Boolean(hash));
32
32
  }
33
33
 
34
+ /** The fields a session token is built from. */
35
+ export type SessionUser = { id: string; role: SessionPayload["role"]; name: string; tokenVersion: number };
36
+
34
37
  /** Signs a session JWT and stores it in the httpOnly cookie (Route Handlers / Server Actions only). */
35
- export async function setSessionCookie(payload: SessionPayload): Promise<void> {
36
- const token = await signSession(payload);
38
+ export async function setSessionCookie(user: SessionUser): Promise<void> {
39
+ const token = await signSession({
40
+ sub: user.id,
41
+ role: user.role,
42
+ name: user.name,
43
+ ver: user.tokenVersion,
44
+ });
37
45
  (await cookies()).set(SESSION_COOKIE, token, sessionCookieOptions());
38
46
  }
39
47
 
@@ -6,22 +6,22 @@ import { cache } from "react";
6
6
 
7
7
  import { FORBIDDEN_PATH, hasPermission, LOGIN_PATH, type Permission } from "@/config/rbac";
8
8
  import { SESSION_COOKIE, verifySession } from "@/lib/session";
9
- import { findUserById } from "@/lib/users";
9
+ import { findSessionUser } from "@/lib/users";
10
10
  import type { PublicUser } from "@/types/user";
11
11
 
12
12
  /**
13
13
  * Data Access Layer: layer 2 of the RBAC model.
14
14
  *
15
15
  * The proxy only checks the JWT (fast but possibly stale). These helpers
16
- * re-read the user from MongoDB, the source of truth, so role changes and
17
- * deleted accounts take effect on the very next request.
16
+ * re-read the user from MongoDB, the source of truth, so role changes,
17
+ * deleted accounts and revoked sessions take effect on the very next request.
18
18
  *
19
19
  * Call them from Server Components, Route Handlers and Server Actions. Any
20
20
  * component that calls them must render inside a <Suspense> boundary
21
21
  * (they read cookies, which is request-time data under Cache Components).
22
22
  */
23
23
 
24
- /** Visited when a token is valid but its user no longer exists: clears the cookie, then goes to /login. */
24
+ /** Visited when a token is valid but its user is gone or the session was revoked. */
25
25
  const STALE_SESSION_PATH = "/api/auth/logout";
26
26
 
27
27
  /** Decoded JWT from the session cookie (not re-validated against the DB). Deduped per request. */
@@ -34,7 +34,10 @@ export const getSession = cache(async () => {
34
34
  export const getCurrentUser = cache(async (): Promise<PublicUser | null> => {
35
35
  const session = await getSession();
36
36
  if (!session) return null;
37
- return findUserById(session.sub);
37
+ const found = await findSessionUser(session.sub);
38
+ // A token issued before the user's tokenVersion was bumped has been revoked.
39
+ if (!found || found.tokenVersion !== session.ver) return null;
40
+ return found.user;
38
41
  });
39
42
 
40
43
  /** Returns the current user or redirects to the login page. */
@@ -0,0 +1,55 @@
1
+ import "server-only";
2
+
3
+ import { siteConfig } from "@/config/site";
4
+ import type { Email } from "@/lib/email";
5
+
6
+ function escapeHtml(value: string): string {
7
+ return value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
8
+ }
9
+
10
+ function layout(title: string, body: string, action: { label: string; url: string }) {
11
+ return `<!doctype html>
12
+ <html>
13
+ <body style="margin:0;padding:24px;background:#f5f5f5;font-family:system-ui,-apple-system,sans-serif;color:#171717">
14
+ <div style="max-width:480px;margin:0 auto;background:#fff;border-radius:12px;padding:32px">
15
+ <h1 style="margin:0 0 16px;font-size:20px">${escapeHtml(title)}</h1>
16
+ ${body}
17
+ <p style="margin:24px 0">
18
+ <a href="${escapeHtml(action.url)}" style="display:inline-block;background:#171717;color:#fff;text-decoration:none;padding:10px 16px;border-radius:8px;font-weight:600">${escapeHtml(action.label)}</a>
19
+ </p>
20
+ <p style="margin:0;font-size:12px;color:#737373">If the button doesn't work, paste this link into your browser:<br>${escapeHtml(action.url)}</p>
21
+ </div>
22
+ <p style="text-align:center;font-size:12px;color:#a3a3a3">${escapeHtml(siteConfig.name)}</p>
23
+ </body>
24
+ </html>`;
25
+ }
26
+
27
+ export function passwordResetEmail(to: string, name: string, url: string): Email {
28
+ const greeting = `Hi ${name},`;
29
+ const line = "We received a request to reset your password. This link expires in 1 hour.";
30
+ const ignore = "If you didn't ask for this, you can ignore this email.";
31
+ return {
32
+ to,
33
+ subject: `Reset your ${siteConfig.name} password`,
34
+ text: `${greeting}\n\n${line}\n\n${url}\n\n${ignore}`,
35
+ html: layout(
36
+ "Reset your password",
37
+ `<p>${escapeHtml(greeting)}</p><p>${line}</p><p style="color:#737373">${ignore}</p>`,
38
+ { label: "Reset password", url },
39
+ ),
40
+ };
41
+ }
42
+
43
+ export function verificationEmail(to: string, name: string, url: string): Email {
44
+ const greeting = `Hi ${name},`;
45
+ const line = `Please confirm your email address for ${siteConfig.name}. This link expires in 24 hours.`;
46
+ return {
47
+ to,
48
+ subject: `Verify your email for ${siteConfig.name}`,
49
+ text: `${greeting}\n\n${line}\n\n${url}`,
50
+ html: layout("Verify your email", `<p>${escapeHtml(greeting)}</p><p>${escapeHtml(line)}</p>`, {
51
+ label: "Verify email",
52
+ url,
53
+ }),
54
+ };
55
+ }
@@ -0,0 +1,53 @@
1
+ import "server-only";
2
+
3
+ import { env } from "@/lib/env";
4
+
5
+ export type Email = {
6
+ to: string;
7
+ subject: string;
8
+ text: string;
9
+ html: string;
10
+ };
11
+
12
+ /**
13
+ * Sends an email with Resend (https://resend.com) using its REST API.
14
+ * Without RESEND_API_KEY the email is printed to the server console instead,
15
+ * so password resets and verification work out of the box in development.
16
+ */
17
+ export async function sendEmail(email: Email): Promise<void> {
18
+ const { RESEND_API_KEY, EMAIL_FROM } = env();
19
+
20
+ if (!RESEND_API_KEY) {
21
+ console.info(
22
+ [
23
+ "",
24
+ "┌─ Email (set RESEND_API_KEY to send for real) ─────────────",
25
+ `│ To: ${email.to}`,
26
+ `│ Subject: ${email.subject}`,
27
+ "│",
28
+ ...email.text.split("\n").map((line) => `│ ${line}`),
29
+ "└───────────────────────────────────────────────────────────",
30
+ "",
31
+ ].join("\n"),
32
+ );
33
+ return;
34
+ }
35
+
36
+ const res = await fetch("https://api.resend.com/emails", {
37
+ method: "POST",
38
+ headers: {
39
+ Authorization: `Bearer ${RESEND_API_KEY}`,
40
+ "Content-Type": "application/json",
41
+ },
42
+ body: JSON.stringify({
43
+ from: EMAIL_FROM,
44
+ to: email.to,
45
+ subject: email.subject,
46
+ text: email.text,
47
+ html: email.html,
48
+ }),
49
+ });
50
+ if (!res.ok) {
51
+ throw new Error(`Resend responded ${res.status}: ${await res.text()}`);
52
+ }
53
+ }
@@ -0,0 +1,90 @@
1
+ // @feature env
2
+ import { z } from "zod";
3
+
4
+ /**
5
+ * Server environment variables, validated with zod.
6
+ *
7
+ * Validation is lazy (on first use, not at import time) so `next build` and
8
+ * the Docker build work without any secrets present. Never import this from
9
+ * a Client Component: these values must stay on the server.
10
+ */
11
+ const envSchema = z.object({
12
+ NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
13
+ MONGODB_URI: z
14
+ .string({ error: "MONGODB_URI is required" })
15
+ .regex(/^mongodb(\+srv)?:\/\//, "MONGODB_URI must start with mongodb:// or mongodb+srv://"),
16
+ JWT_SECRET: z
17
+ .string({ error: "JWT_SECRET is required" })
18
+ .min(32, "JWT_SECRET must be at least 32 characters long"),
19
+ /** Public URL of the app, used for absolute links (emails, sitemap). */
20
+ APP_URL: z.url().default("http://localhost:3000"),
21
+ // @feature email
22
+ /** Optional: without it, emails are printed to the server console. */
23
+ RESEND_API_KEY: z.string().optional(),
24
+ EMAIL_FROM: z.string().default("onboarding@resend.dev"),
25
+ // @end email
26
+ });
27
+
28
+ export type Env = z.infer<typeof envSchema>;
29
+
30
+ let cached: Env | undefined;
31
+
32
+ export function env(): Env {
33
+ if (cached) return cached;
34
+ const parsed = envSchema.safeParse(process.env);
35
+ if (!parsed.success) {
36
+ throw new Error(
37
+ `Invalid environment variables (check .env.local):\n${z.prettifyError(parsed.error)}`,
38
+ );
39
+ }
40
+ cached = parsed.data;
41
+ return cached;
42
+ }
43
+ // @end env
44
+ // @feature !env
45
+ /**
46
+ * Server environment variables.
47
+ *
48
+ * Read lazily (on first use) so `next build` works without any secrets.
49
+ * Never import this from a Client Component.
50
+ */
51
+ export type Env = {
52
+ NODE_ENV: string;
53
+ MONGODB_URI: string;
54
+ JWT_SECRET: string;
55
+ APP_URL: string;
56
+ // @feature email
57
+ RESEND_API_KEY?: string;
58
+ EMAIL_FROM: string;
59
+ // @end email
60
+ };
61
+
62
+ function required(name: string): string {
63
+ const value = process.env[name];
64
+ if (!value) throw new Error(`Missing environment variable ${name} (check .env.local)`);
65
+ return value;
66
+ }
67
+
68
+ let cached: Env | undefined;
69
+
70
+ export function env(): Env {
71
+ cached ??= {
72
+ NODE_ENV: process.env.NODE_ENV ?? "development",
73
+ MONGODB_URI: required("MONGODB_URI"),
74
+ JWT_SECRET: required("JWT_SECRET"),
75
+ APP_URL: process.env.APP_URL ?? "http://localhost:3000",
76
+ // @feature email
77
+ RESEND_API_KEY: process.env.RESEND_API_KEY,
78
+ EMAIL_FROM: process.env.EMAIL_FROM ?? "onboarding@resend.dev",
79
+ // @end email
80
+ };
81
+ return cached;
82
+ }
83
+ // @end !env
84
+
85
+ export const isProduction = () => process.env.NODE_ENV === "production";
86
+
87
+ /** Absolute app URL without a trailing slash. Safe to call at build time. */
88
+ export function appUrl(): string {
89
+ return (process.env.APP_URL ?? "http://localhost:3000").replace(/\/$/, "");
90
+ }
@@ -0,0 +1,20 @@
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import { getPasswordStrength } from "./password-strength";
4
+
5
+ describe("getPasswordStrength", () => {
6
+ it("is empty for an empty password", () => {
7
+ expect(getPasswordStrength("")).toEqual({ score: 0, label: "" });
8
+ });
9
+
10
+ it("rates short passwords as weak", () => {
11
+ expect(getPasswordStrength("Ab1!").score).toBe(1);
12
+ });
13
+
14
+ it("rewards length and variety", () => {
15
+ expect(getPasswordStrength("password").score).toBeLessThan(
16
+ getPasswordStrength("Correct-Horse-42").score,
17
+ );
18
+ expect(getPasswordStrength("Correct-Horse-Battery-42").label).toBe("Strong");
19
+ });
20
+ });
@@ -0,0 +1,24 @@
1
+ export type PasswordStrength = {
2
+ /** 0 (empty) to 4 (strong). */
3
+ score: 0 | 1 | 2 | 3 | 4;
4
+ label: "" | "Weak" | "Fair" | "Good" | "Strong";
5
+ };
6
+
7
+ const LABELS = ["", "Weak", "Fair", "Good", "Strong"] as const;
8
+
9
+ /**
10
+ * A quick, dependency-free estimate for UI feedback only. The real rule
11
+ * (minimum length) is enforced by the zod schema on the server.
12
+ */
13
+ export function getPasswordStrength(password: string): PasswordStrength {
14
+ if (!password) return { score: 0, label: "" };
15
+ let points = 0;
16
+ if (password.length >= 8) points++;
17
+ if (password.length >= 12) points++;
18
+ if (/[a-z]/.test(password) && /[A-Z]/.test(password)) points++;
19
+ if (/\d/.test(password)) points++;
20
+ if (/[^A-Za-z0-9]/.test(password)) points++;
21
+ if (password.length < 8) points = Math.min(points, 1);
22
+ const score = Math.max(1, Math.min(4, points)) as PasswordStrength["score"];
23
+ return { score, label: LABELS[score] };
24
+ }
@@ -0,0 +1,47 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+
3
+ import { getClientIp, rateLimit, resetRateLimits } from "./rate-limit";
4
+
5
+ afterEach(() => {
6
+ resetRateLimits();
7
+ vi.useRealTimers();
8
+ });
9
+
10
+ describe("rateLimit", () => {
11
+ it("allows requests up to the limit, then blocks", () => {
12
+ const options = { limit: 3, windowMs: 60_000 };
13
+ expect(rateLimit("k", options).success).toBe(true);
14
+ expect(rateLimit("k", options).success).toBe(true);
15
+ expect(rateLimit("k", options).remaining).toBe(0);
16
+ const blocked = rateLimit("k", options);
17
+ expect(blocked.success).toBe(false);
18
+ expect(blocked.retryAfterMs).toBeGreaterThan(0);
19
+ });
20
+
21
+ it("tracks keys separately", () => {
22
+ const options = { limit: 1, windowMs: 60_000 };
23
+ expect(rateLimit("a", options).success).toBe(true);
24
+ expect(rateLimit("b", options).success).toBe(true);
25
+ expect(rateLimit("a", options).success).toBe(false);
26
+ });
27
+
28
+ it("resets after the window", () => {
29
+ vi.useFakeTimers();
30
+ const options = { limit: 1, windowMs: 1_000 };
31
+ expect(rateLimit("k", options).success).toBe(true);
32
+ expect(rateLimit("k", options).success).toBe(false);
33
+ vi.advanceTimersByTime(1_001);
34
+ expect(rateLimit("k", options).success).toBe(true);
35
+ });
36
+ });
37
+
38
+ describe("getClientIp", () => {
39
+ it("uses the first X-Forwarded-For address", () => {
40
+ const req = new Request("http://x", { headers: { "x-forwarded-for": "1.2.3.4, 10.0.0.1" } });
41
+ expect(getClientIp(req)).toBe("1.2.3.4");
42
+ });
43
+
44
+ it("falls back to 'unknown'", () => {
45
+ expect(getClientIp(new Request("http://x"))).toBe("unknown");
46
+ });
47
+ });