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,328 @@
1
+ # {{PROJECT_TITLE}}
2
+
3
+ A full-stack **Next.js 16** app with MongoDB, JWT authentication and role-based access control
4
+ (RBAC), scaffolded with `create-mohit-next`.
5
+
6
+ ## What's inside
7
+
8
+ <!-- @feature ts -->
9
+ - **Next.js 16** (App Router, Turbopack, Cache Components) + **React 19** + **TypeScript**
10
+ <!-- @end ts -->
11
+ <!-- @feature !ts -->
12
+ - **Next.js 16** (App Router, Turbopack, Cache Components) + **React 19** (JavaScript)
13
+ <!-- @end !ts -->
14
+ <!-- @feature shadcn -->
15
+ - **Tailwind CSS v4 + shadcn/ui** components in `src/components/ui`
16
+ <!-- @end shadcn -->
17
+ <!-- @feature tailwind -->
18
+ <!-- @feature !shadcn -->
19
+ - **Tailwind CSS v4** with hand-written components in `src/components/ui` (no component library)
20
+ <!-- @end !shadcn -->
21
+ <!-- @end tailwind -->
22
+ <!-- @feature css -->
23
+ - **Plain CSS** (no Tailwind): theme tokens + component styles in `src/app/globals.css`
24
+ <!-- @end css -->
25
+ - Light / dark / system themes, `motion` animations, `sonner` toasts, `lucide-react` icons
26
+ - **MongoDB + Mongoose** with a cached connection
27
+ - **Auth**: bcrypt (cost 12) + JWT (`jose`, HS256) in an httpOnly cookie, timing-safe login
28
+ - **RBAC**: `user` < `manager` < `admin`, enforced in three layers (see below)
29
+ <!-- @feature env -->
30
+ - **zod**-validated environment variables, plus request/form schemas shared by client and server
31
+ <!-- @end env -->
32
+ <!-- @feature !env -->
33
+ - **zod** request/form schemas shared by client and server
34
+ <!-- @end !env -->
35
+ <!-- @feature sidebar -->
36
+ - Sidebar dashboard layout (a drawer on mobile)
37
+ <!-- @end sidebar -->
38
+ <!-- @feature data-table -->
39
+ - Admin users table with search, role filter, sorting and pagination
40
+ <!-- @end data-table -->
41
+ <!-- @feature charts -->
42
+ - Charts on the reports page (Recharts)
43
+ <!-- @end charts -->
44
+ <!-- @feature profile -->
45
+ - Settings page: change name and password, sign out of other devices
46
+ <!-- @end profile -->
47
+ <!-- @feature email -->
48
+ - Forgot password + email verification (Resend, or printed to the console in development)
49
+ <!-- @end email -->
50
+ <!-- @feature rate-limit -->
51
+ - Rate limiting on the auth endpoints
52
+ <!-- @end rate-limit -->
53
+ <!-- @feature audit-log -->
54
+ - Audit log of admin actions (`/admin/audit`)
55
+ <!-- @end audit-log -->
56
+ <!-- @feature seo -->
57
+ - SEO: `sitemap.xml`, `robots.txt`, Open Graph image
58
+ <!-- @end seo -->
59
+ <!-- @feature eslint -->
60
+ - ESLint (`eslint-config-next`)
61
+ <!-- @end eslint -->
62
+ <!-- @feature prettier -->
63
+ - Prettier
64
+ <!-- @end prettier -->
65
+ <!-- @feature git-hooks -->
66
+ - Git hooks: Husky + lint-staged (on commit) + commitlint (Conventional Commits)
67
+ <!-- @end git-hooks -->
68
+ <!-- @feature vitest -->
69
+ - Unit tests with Vitest
70
+ <!-- @end vitest -->
71
+ <!-- @feature playwright -->
72
+ - End-to-end tests with Playwright (with a throwaway in-memory MongoDB)
73
+ <!-- @end playwright -->
74
+ <!-- @feature docker -->
75
+ - Docker: multi-stage `Dockerfile` (standalone output) + `docker-compose.yml` with MongoDB
76
+ <!-- @end docker -->
77
+ <!-- @feature ci -->
78
+ - GitHub Actions CI + Dependabot
79
+ <!-- @end ci -->
80
+
81
+ ## Getting started
82
+
83
+ **Requirements:** Node.js 22.12+ and a MongoDB database.
84
+
85
+ ```bash
86
+ npm install # if you skipped it during scaffolding
87
+ ```
88
+
89
+ 1. **Environment.** `.env.local` was generated for you with a random `JWT_SECRET`. To recreate it,
90
+ copy `.env.example` to `.env.local` and fill it in.
91
+
92
+ | Variable | Description |
93
+ | ------------- | -------------------------------------------------------------- |
94
+ | `MONGODB_URI` | e.g. `mongodb://localhost:27017/my-app` or a MongoDB Atlas URI |
95
+ | `JWT_SECRET` | At least 32 random characters, used to sign session tokens |
96
+ | `APP_URL` | Public URL of the app (links in emails, sitemap) |
97
+ <!-- @feature email -->
98
+ | `RESEND_API_KEY` | Optional. Without it, emails are printed to the server console |
99
+ | `EMAIL_FROM` | Sender address for emails (must be verified in Resend) |
100
+ <!-- @end email -->
101
+
102
+ 2. **Database.** Use any MongoDB 6+ instance (a local install or MongoDB Atlas) and point
103
+ `MONGODB_URI` at it.
104
+ <!-- @feature docker -->
105
+ Or run `npm run docker:db` to start MongoDB 8 in Docker on `localhost:27017`.
106
+ <!-- @end docker -->
107
+
108
+ 3. **Run it.**
109
+
110
+ ```bash
111
+ npm run dev
112
+ ```
113
+
114
+ Open http://localhost:3000 and register. **The first account becomes `admin`**; every account
115
+ after that starts as `user`. Promote people from **/admin**.
116
+ <!-- @feature seed -->
117
+
118
+ Want data right away? `npm run seed` creates `admin@example.com`, `manager@example.com` and
119
+ `user@example.com` (password `Password123!`) plus sample users for the reports page.
120
+ `npm run seed -- --reset` wipes the users first.
121
+ <!-- @end seed -->
122
+
123
+ ### Scripts
124
+
125
+ | Script | What it does |
126
+ | ------ | ------------ |
127
+ | `npm run dev` | Dev server with Turbopack |
128
+ | `npm run build` | Production build (`.next/standalone`) |
129
+ | `npm run start` | Serve the production build |
130
+ <!-- @feature eslint -->
131
+ | `npm run lint` | ESLint |
132
+ <!-- @end eslint -->
133
+ <!-- @feature ts -->
134
+ | `npm run typecheck` | Generate route types, then `tsc --noEmit` |
135
+ <!-- @end ts -->
136
+ <!-- @feature prettier -->
137
+ | `npm run format` | Format everything with Prettier |
138
+ | `npm run format:check` | Check formatting (CI) |
139
+ <!-- @end prettier -->
140
+ <!-- @feature vitest -->
141
+ | `npm test` | Unit tests (Vitest) |
142
+ <!-- @end vitest -->
143
+ <!-- @feature playwright -->
144
+ | `npm run test:e2e` | End-to-end tests (first time: `npx playwright install chromium`) |
145
+ <!-- @end playwright -->
146
+ <!-- @feature seed -->
147
+ | `npm run seed` | Create demo users |
148
+ <!-- @end seed -->
149
+ <!-- @feature docker -->
150
+ | `npm run docker:db` | Start only MongoDB in Docker |
151
+ | `npm run docker:up` | Build and start the app + MongoDB |
152
+ | `npm run docker:down` | Stop the containers (the data volume is kept) |
153
+ <!-- @end docker -->
154
+
155
+ ## How RBAC works
156
+
157
+ Everything starts in `src/config/rbac`:
158
+
159
+ ```ts
160
+ ROLES = ["user", "manager", "admin"] // lowest -> highest
161
+ ROLE_PERMISSIONS = {
162
+ user: ["dashboard:view"],
163
+ manager: ["dashboard:view", "reports:view", "users:read"],
164
+ admin: [...everything, "users:update-role", "users:delete"],
165
+ }
166
+ ROUTE_RULES = [{ prefix: "/reports", permission: "reports:view" }, ...] // longest prefix wins
167
+ ```
168
+
169
+ Each request is checked in **three layers**:
170
+
171
+ | Layer | Where | Checks | Why |
172
+ | ----- | ----- | ------ | --- |
173
+ | 1 | `src/proxy` | The JWT's role | Fast redirects: signed out -> `/login?next=...`, no permission -> `/forbidden`, signed in -> away from `/login` |
174
+ | 2 | `src/lib/dal` | The user **in MongoDB** | Source of truth: role changes, deleted accounts and revoked sessions apply on the next request |
175
+ | 3 | `withAuth()` in `src/lib/api` | The user **in MongoDB** | Route handlers answer `401` / `403` JSON |
176
+
177
+ On the client, `useUser()` and `<Can permission="...">` hide UI the user can't use. That's only
178
+ cosmetic: the server always re-checks.
179
+
180
+ **Stale tokens.** The JWT stores the role so the proxy can stay database-free. After an admin
181
+ changes someone's role, layers 2 and 3 use the new role immediately; the app shell notices the token
182
+ is out of date and calls `GET /api/auth/me`, which re-issues the cookie. The `/forbidden` page does
183
+ the same, so a freshly promoted user can just press "Try again".
184
+
185
+ **Revoking sessions.** Every user has a `tokenVersion`; tokens carry it and the DAL rejects tokens
186
+ whose version is out of date. Bump it to sign a user out everywhere (password changes and resets do
187
+ this automatically).
188
+
189
+ ### Add a role
190
+
191
+ 1. Add it to `ROLES` (keep the order, lowest -> highest) in `src/config/rbac`.
192
+ 2. Give it permissions in `ROLE_PERMISSIONS` and a label in `ROLE_LABELS`.
193
+
194
+ The Mongoose enum, the zod schemas and the admin role selector all read from `ROLES`, so nothing
195
+ else needs to change.
196
+
197
+ ### Add a permission
198
+
199
+ Add it to `PERMISSIONS`, label it in `PERMISSION_LABELS`, and grant it in `ROLE_PERMISSIONS`.
200
+
201
+ ### Protect a page
202
+
203
+ 1. Add a route rule (layer 1) and, optionally, a nav item:
204
+
205
+ ```ts
206
+ ROUTE_RULES = [..., { prefix: "/billing", permission: "billing:manage" }];
207
+ NAV_ITEMS = [..., { href: "/billing", label: "Billing", permission: "billing:manage" }];
208
+ ```
209
+
210
+ Omit `permission` to only require a signed-in user.
211
+
212
+ 2. Create `src/app/(app)/billing/page` and check on the server (layer 2):
213
+
214
+ ```tsx
215
+ import { requirePermission } from "@/lib/dal";
216
+
217
+ export default async function BillingPage() {
218
+ const user = await requirePermission("billing:manage"); // redirects to /forbidden otherwise
219
+ return <h1>Billing for {user.name}</h1>;
220
+ }
221
+ ```
222
+
223
+ Pages inside `(app)` already render inside a `<Suspense>` boundary, which Cache Components
224
+ requires for anything that reads cookies or the database.
225
+
226
+ 3. Hide or show UI with `<Can permission="billing:manage" fallback={...}>`.
227
+
228
+ ### Protect an API route
229
+
230
+ ```ts
231
+ // src/app/api/invoices/[id]/route
232
+ import { NextResponse } from "next/server";
233
+ import { ApiError, parseBody, withAuth } from "@/lib/api";
234
+
235
+ export const PATCH = withAuth(
236
+ async (req, ctx, user) => {
237
+ const { id } = await ctx.params; // params are a Promise in Next.js 16
238
+ const body = await parseBody(req, invoiceSchema); // 400 bad JSON / 422 validation
239
+ if (!invoice) throw ApiError.notFound("Invoice not found");
240
+ return NextResponse.json({ invoice });
241
+ },
242
+ { permission: "billing:manage" }, // 401 if signed out, 403 without permission
243
+ );
244
+ ```
245
+
246
+ Errors always use one JSON shape: `{ "error": { "code": "FORBIDDEN", "message": "...", "details"?: ... } }`.
247
+
248
+ ## API
249
+
250
+ | Method | Route | Access | Notes |
251
+ | ------ | ----- | ------ | ----- |
252
+ | POST | `/api/auth/register` | public | `{ name, email, password }`; the first user becomes admin |
253
+ | POST | `/api/auth/login` | public | `{ email, password }`; generic error on failure |
254
+ | POST | `/api/auth/logout` | public | Clears the session cookie |
255
+ | GET | `/api/auth/me` | signed in | Current user + permissions; refreshes stale tokens |
256
+ <!-- @feature email -->
257
+ | POST | `/api/auth/forgot-password` | public | `{ email }`; same answer whether or not the account exists |
258
+ | POST | `/api/auth/reset-password` | public | `{ token, password }`; signs out every session |
259
+ | GET | `/api/auth/verify-email?token=` | public | The link in the verification email |
260
+ | POST | `/api/auth/resend-verification` | signed in | Sends a new verification email |
261
+ <!-- @end email -->
262
+ <!-- @feature profile -->
263
+ | PATCH | `/api/account` | signed in | `{ name }` |
264
+ | POST | `/api/account/password` | signed in | `{ currentPassword, newPassword }` |
265
+ | DELETE | `/api/account/sessions` | signed in | Signs out every other device |
266
+ <!-- @end profile -->
267
+ | GET | `/api/admin/users` | `users:read` | `?page=1&limit=50` |
268
+ | PATCH | `/api/admin/users/:id` | `users:update-role` | `{ role }`; you can't change your own role |
269
+ | DELETE | `/api/admin/users/:id` | `users:delete` | You can't delete yourself |
270
+ <!-- @feature audit-log -->
271
+ | GET | `/api/admin/audit` | `audit:read` | Most recent admin actions |
272
+ <!-- @end audit-log -->
273
+ | GET | `/api/health` | public | `200` when the database is reachable, else `503` |
274
+
275
+ ## Styling
276
+
277
+ `src/components/ui` holds the UI primitives (Button, Card, Input, DropdownMenu, AlertDialog, ...).
278
+ Pages and layouts use them plus the plain-CSS classes in `src/styles/app.css`, which are built on the
279
+ theme tokens (`--background`, `--primary`, `--border`, ...) defined in `src/app/globals.css`.
280
+ Change the tokens to re-theme the whole app.
281
+ <!-- @feature shadcn -->
282
+
283
+ shadcn/ui is configured (`components.json`), so you can add more components:
284
+
285
+ ```bash
286
+ npx shadcn@latest add dialog tabs tooltip
287
+ ```
288
+ <!-- @end shadcn -->
289
+ <!-- @feature docker -->
290
+
291
+ ## Docker
292
+
293
+ ```bash
294
+ npm run docker:up # builds the image and starts app + MongoDB on http://localhost:3000
295
+ npm run docker:down
296
+ ```
297
+
298
+ - The `Dockerfile` is multi-stage: deps -> build -> a slim runtime containing only
299
+ `.next/standalone`, running as a non-root user with a `HEALTHCHECK` on `/api/health`.
300
+ - `docker-compose.yml` reads secrets from `.env.local` and points `MONGODB_URI` at the `mongo`
301
+ service. Data persists in the `mongo-data` volume.
302
+ - With `NODE_ENV=production` the session cookie is `Secure`, so serve the app over HTTPS
303
+ (browsers allow it on `http://localhost`).
304
+ <!-- @end docker -->
305
+
306
+ ## Security notes
307
+
308
+ - Passwords are hashed with bcrypt (cost 12). Login always runs one bcrypt comparison and returns
309
+ the same error, so responses don't reveal which emails exist.
310
+ - Session cookie: `httpOnly`, `SameSite=Lax`, `Secure` in production, expires after 7 days.
311
+ - `?next=` redirects only accept same-origin relative paths.
312
+ - Security headers are set in `next.config`. Add a Content-Security-Policy once you know which
313
+ origins you need.
314
+ - The "first user becomes admin" claim is atomic (a unique `_id` in the `app_meta` collection), so
315
+ concurrent sign-ups on an empty database can't create two admins.
316
+ <!-- @feature rate-limit -->
317
+ - Rate limits live in `src/lib/rate-limit` and are kept in memory (per server instance). For several
318
+ instances, back them with Redis/Upstash.
319
+ <!-- @end rate-limit -->
320
+ <!-- @feature !rate-limit -->
321
+ - Consider adding rate limiting to `/api/auth/*` before going live.
322
+ <!-- @end !rate-limit -->
323
+
324
+ ## Learn more
325
+
326
+ This project uses Next.js 16, which differs from older versions (for example, `middleware` is now
327
+ `proxy`, and `params` are Promises). Its docs ship with the package in `node_modules/next/dist/docs/`;
328
+ see `AGENTS.md`.
@@ -2,10 +2,19 @@
2
2
  # Never commit real secrets.
3
3
 
4
4
  # MongoDB connection string.
5
- # Local / `npm run docker:db`: mongodb://localhost:27017/my-app
5
+ # Local / Docker: mongodb://localhost:27017/my-app
6
6
  # Atlas: mongodb+srv://<user>:<password>@<cluster>.mongodb.net/my-app
7
7
  MONGODB_URI=mongodb://localhost:27017/my-app
8
8
 
9
9
  # Secret used to sign session JWTs (HS256). At least 32 characters.
10
10
  # Generate one with: node -e "console.log(require('crypto').randomBytes(48).toString('base64url'))"
11
11
  JWT_SECRET=change-me-to-a-long-random-string-of-at-least-32-chars
12
+
13
+ # Public URL of the app (used for links in emails and the sitemap).
14
+ APP_URL=http://localhost:3000
15
+ # @feature email
16
+
17
+ # Email (https://resend.com). Leave RESEND_API_KEY empty to print emails to the console instead.
18
+ RESEND_API_KEY=
19
+ EMAIL_FROM=onboarding@resend.dev
20
+ # @end email
@@ -40,3 +40,11 @@ yarn-error.log*
40
40
  # typescript
41
41
  *.tsbuildinfo
42
42
  next-env.d.ts
43
+ # @feature playwright
44
+
45
+ # playwright
46
+ /test-results/
47
+ /playwright-report/
48
+ /blob-report/
49
+ /playwright/.cache/
50
+ # @end playwright
@@ -0,0 +1,69 @@
1
+ import { expect, test, type Page } from "@playwright/test";
2
+
3
+ /**
4
+ * The RBAC flow end to end, through the real UI:
5
+ * first user = admin -> second user = user -> admin promotes them to manager
6
+ * -> the manager can open /reports but the API still refuses role changes.
7
+ */
8
+ // The steps build on each other (and the first user must be admin), so no retries.
9
+ test.describe.configure({ mode: "serial", retries: 0 });
10
+
11
+ const admin = { name: "Alice Admin", email: "alice@example.com", password: "Correct-Horse-42" };
12
+ const member = { name: "Bob Builder", email: "bob@example.com", password: "Correct-Horse-42" };
13
+
14
+ async function register(page: Page, user: typeof admin) {
15
+ await page.goto("/register");
16
+ await page.getByLabel("Name").fill(user.name);
17
+ await page.getByLabel("Email").fill(user.email);
18
+ await page.getByLabel("Password", { exact: true }).fill(user.password);
19
+ await page.getByLabel("Confirm password").fill(user.password);
20
+ await page.getByRole("button", { name: "Create account" }).click();
21
+ await expect(page).toHaveURL(/\/dashboard$/);
22
+ }
23
+
24
+ test("signed-out visitors are sent to /login", async ({ page }) => {
25
+ await page.goto("/dashboard");
26
+ await expect(page).toHaveURL(/\/login\?next=%2Fdashboard/);
27
+ });
28
+
29
+ test("roles, permissions and route protection", async ({ browser }) => {
30
+ // 1. The first account becomes admin.
31
+ const adminPage = await (await browser.newContext()).newPage();
32
+ await register(adminPage, admin);
33
+ await expect(adminPage.getByRole("heading", { name: "Hi, Alice" })).toBeVisible();
34
+ await expect(adminPage.getByText("Your role", { exact: true })).toBeVisible();
35
+ await expect(adminPage.getByRole("link", { name: "Admin", exact: true }).first()).toBeVisible();
36
+
37
+ // 2. The second account is a regular user and can't open /reports.
38
+ const memberPage = await (await browser.newContext()).newPage();
39
+ await register(memberPage, member);
40
+ await expect(memberPage.getByRole("link", { name: "Reports" })).toHaveCount(0);
41
+ await memberPage.goto("/reports");
42
+ await expect(memberPage).toHaveURL(/\/forbidden/);
43
+
44
+ // 3. The admin promotes them to manager.
45
+ await adminPage.goto("/admin");
46
+ await adminPage.getByLabel(`Role for ${member.name}`).selectOption("manager");
47
+ await expect(adminPage.getByText(`${member.name} is now manager`)).toBeVisible();
48
+
49
+ // 4. Their old token still says "user": the 403 page refreshes it and offers a retry.
50
+ await memberPage.goto("/reports");
51
+ await expect(memberPage).toHaveURL(/\/forbidden/);
52
+ await memberPage.getByRole("button", { name: "Try again" }).click();
53
+ await expect(memberPage.getByRole("heading", { name: "Reports" })).toBeVisible();
54
+
55
+ // 5. Managers can read users, but the API refuses role changes.
56
+ const users = await memberPage.request.get("/api/admin/users");
57
+ expect(users.status()).toBe(200);
58
+ const { users: list } = (await users.json()) as { users: { id: string; email: string }[] };
59
+ const aliceId = list.find((u) => u.email === admin.email)?.id;
60
+ const patch = await memberPage.request.patch(`/api/admin/users/${aliceId}`, {
61
+ data: { role: "user" },
62
+ });
63
+ expect(patch.status()).toBe(403);
64
+
65
+ // 6. Signing out returns to /login.
66
+ await memberPage.getByRole("button", { name: "Account menu" }).click();
67
+ await memberPage.getByRole("menuitem", { name: "Sign out" }).click();
68
+ await expect(memberPage).toHaveURL(/\/login$/);
69
+ });
@@ -0,0 +1,35 @@
1
+ // Starts a throwaway in-memory MongoDB, then the Next.js app pointed at it.
2
+ // Used by playwright.config as its webServer. Set E2E_PROD=1 to run `next start`
3
+ // against an existing production build (CI does this after `npm run build`).
4
+ import { spawn } from "node:child_process";
5
+ import { createRequire } from "node:module";
6
+
7
+ import { MongoMemoryServer } from "mongodb-memory-server";
8
+
9
+ const port = process.env.E2E_PORT ?? "3100";
10
+ const mongo = await MongoMemoryServer.create();
11
+ const nextBin = createRequire(import.meta.url).resolve("next/dist/bin/next");
12
+
13
+ const app = spawn(
14
+ process.execPath,
15
+ [nextBin, process.env.E2E_PROD === "1" ? "start" : "dev", "--port", port],
16
+ {
17
+ stdio: "inherit",
18
+ env: {
19
+ ...process.env,
20
+ MONGODB_URI: mongo.getUri("e2e"),
21
+ JWT_SECRET: "e2e-only-secret-that-is-long-enough-for-hs256",
22
+ APP_URL: `http://localhost:${port}`,
23
+ },
24
+ },
25
+ );
26
+
27
+ async function shutdown(code = 0) {
28
+ app.kill();
29
+ await mongo.stop();
30
+ process.exit(code);
31
+ }
32
+
33
+ process.on("SIGINT", () => shutdown());
34
+ process.on("SIGTERM", () => shutdown());
35
+ app.on("exit", (code) => shutdown(code ?? 0));
@@ -1,13 +1,21 @@
1
1
  import { defineConfig, globalIgnores } from "eslint/config";
2
2
  import nextVitals from "eslint-config-next/core-web-vitals";
3
+ // @feature ts
3
4
  import nextTs from "eslint-config-next/typescript";
5
+ // @end ts
6
+ // @feature prettier
4
7
  import prettier from "eslint-config-prettier/flat";
8
+ // @end prettier
5
9
 
6
10
  const eslintConfig = defineConfig([
7
11
  ...nextVitals,
12
+ // @feature ts
8
13
  ...nextTs,
14
+ // @end ts
15
+ // @feature prettier
9
16
  // Turn off stylistic rules that conflict with Prettier (keep this last).
10
17
  prettier,
18
+ // @end prettier
11
19
  // Override default ignores of eslint-config-next.
12
20
  globalIgnores([
13
21
  // Default ignores of eslint-config-next:
@@ -15,6 +23,10 @@ const eslintConfig = defineConfig([
15
23
  "out/**",
16
24
  "build/**",
17
25
  "next-env.d.ts",
26
+ // @feature playwright
27
+ "playwright-report/**",
28
+ "test-results/**",
29
+ // @end playwright
18
30
  ]),
19
31
  ]);
20
32
 
@@ -29,6 +29,7 @@ const nextConfig: NextConfig = {
29
29
  partialPrefetching: true,
30
30
  // Mongoose relies on Node.js internals; load it natively instead of bundling.
31
31
  serverExternalPackages: ["mongoose"],
32
+ // @feature tailwind
32
33
  turbopack: {
33
34
  rules: {
34
35
  "*.css": {
@@ -37,6 +38,7 @@ const nextConfig: NextConfig = {
37
38
  },
38
39
  },
39
40
  },
41
+ // @end tailwind
40
42
  async headers() {
41
43
  return [{ source: "/:path*", headers: securityHeaders }];
42
44
  },
@@ -7,9 +7,15 @@
7
7
  "build": "next build",
8
8
  "start": "next start",
9
9
  "lint": "eslint",
10
+ "lint:fix": "eslint --fix",
10
11
  "typecheck": "next typegen && tsc --noEmit",
11
12
  "format": "prettier --write .",
12
13
  "format:check": "prettier --check .",
14
+ "test": "vitest run",
15
+ "test:watch": "vitest",
16
+ "test:e2e": "playwright test",
17
+ "seed": "tsx scripts/seed.ts",
18
+ "prepare": "husky",
13
19
  "docker:db": "docker compose up -d mongo",
14
20
  "docker:up": "docker compose up -d --build",
15
21
  "docker:down": "docker compose down"
@@ -28,26 +34,35 @@
28
34
  "react": "19.3.0",
29
35
  "react-dom": "19.3.0",
30
36
  "react-hook-form": "^7.92.0",
37
+ "recharts": "^3.8.0",
31
38
  "server-only": "^0.0.1",
32
39
  "sonner": "^2.0.8",
33
40
  "tw-animate-css": "^1.4.0",
34
41
  "zod": "^4.6.7"
35
42
  },
36
43
  "devDependencies": {
44
+ "@commitlint/cli": "^21.2.4",
45
+ "@commitlint/config-conventional": "^21.2.4",
46
+ "@playwright/test": "^1.65.1",
37
47
  "@tailwindcss/turbopack": "4.3.3",
38
- "@types/node": "^20",
48
+ "@types/node": "^22",
39
49
  "@types/react": "^19",
40
50
  "@types/react-dom": "^19",
41
51
  "eslint": "^9",
42
52
  "eslint-config-next": "16.4.6",
43
53
  "eslint-config-prettier": "^10.1.8",
54
+ "husky": "^9.1.7",
55
+ "lint-staged": "^17.6.1",
56
+ "mongodb-memory-server": "^11.3.0",
44
57
  "prettier": "^3.10.1",
45
58
  "prettier-plugin-tailwindcss": "^0.8.1",
46
59
  "shadcn": "^4.23.0",
47
60
  "tailwindcss": "4.3.3",
48
- "typescript": "^5"
61
+ "tsx": "^4.23.15",
62
+ "typescript": "^5",
63
+ "vitest": "^5.1.0"
49
64
  },
50
65
  "engines": {
51
- "node": ">=20.19.0"
66
+ "node": ">=22.12.0"
52
67
  }
53
68
  }
@@ -0,0 +1,30 @@
1
+ import { defineConfig, devices } from "@playwright/test";
2
+
3
+ const PORT = 3100;
4
+
5
+ /**
6
+ * End-to-end tests. `npm run test:e2e` starts the app on port 3100 with a
7
+ * throwaway in-memory MongoDB (see e2e/server.mjs), so no database setup is
8
+ * needed. First run: `npx playwright install chromium`.
9
+ */
10
+ export default defineConfig({
11
+ testDir: "./e2e",
12
+ fullyParallel: false,
13
+ workers: 1,
14
+ retries: process.env.CI ? 1 : 0,
15
+ reporter: process.env.CI ? "github" : "list",
16
+ timeout: 60_000,
17
+ expect: { timeout: 15_000 },
18
+ use: {
19
+ baseURL: `http://localhost:${PORT}`,
20
+ trace: "on-first-retry",
21
+ },
22
+ projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
23
+ webServer: {
24
+ command: "node e2e/server.mjs",
25
+ url: `http://localhost:${PORT}/api/health`,
26
+ reuseExistingServer: !process.env.CI,
27
+ timeout: 180_000,
28
+ env: { E2E_PORT: String(PORT) },
29
+ },
30
+ });