create-ishwor-menn 0.0.0-stage → 1.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.
- package/README.md +216 -2
- package/apps/backend/.dockerignore +10 -0
- package/apps/backend/.env.example +73 -0
- package/apps/backend/Dockerfile +56 -0
- package/apps/backend/package.json +55 -0
- package/apps/backend/src/app.ts +72 -0
- package/apps/backend/src/config/database.ts +24 -0
- package/apps/backend/src/config/env.ts +62 -0
- package/apps/backend/src/config/logger.ts +24 -0
- package/apps/backend/src/errors/api-error.ts +85 -0
- package/apps/backend/src/errors/app-error.ts +6 -0
- package/apps/backend/src/features/admin/admin.controller.ts +180 -0
- package/apps/backend/src/features/admin/admin.route.ts +49 -0
- package/apps/backend/src/features/auth/auth.route.ts +183 -0
- package/apps/backend/src/features/auth/credentials/account-exists.template.ts +132 -0
- package/apps/backend/src/features/auth/credentials/auth.controller.ts +257 -0
- package/apps/backend/src/features/auth/credentials/auth.service.ts +409 -0
- package/apps/backend/src/features/auth/email/Notes.md +105 -0
- package/apps/backend/src/features/auth/email/email.service.ts +7 -0
- package/apps/backend/src/features/auth/email/email.types.ts +10 -0
- package/apps/backend/src/features/auth/email/nodemailer.provider.ts +62 -0
- package/apps/backend/src/features/auth/email/resend.provider.ts +38 -0
- package/apps/backend/src/features/auth/models/session.model.ts +63 -0
- package/apps/backend/src/features/auth/models/user.model.ts +134 -0
- package/apps/backend/src/features/auth/oauth/oauth-account.model.ts +53 -0
- package/apps/backend/src/features/auth/oauth/oauth.controller.ts +179 -0
- package/apps/backend/src/features/auth/oauth/oauth.service.ts +332 -0
- package/apps/backend/src/features/auth/password-reset/password-reset.repository.ts +64 -0
- package/apps/backend/src/features/auth/password-reset/password-reset.template.ts +26 -0
- package/apps/backend/src/features/auth/verification/email-verification.repository.ts +76 -0
- package/apps/backend/src/features/auth/verification/email-verification.service.ts +64 -0
- package/apps/backend/src/features/auth/verification/email-verification.template.ts +167 -0
- package/apps/backend/src/middleware/auth.middleware.ts +85 -0
- package/apps/backend/src/middleware/error.middleware.ts +114 -0
- package/apps/backend/src/middleware/permission.middleware.ts +157 -0
- package/apps/backend/src/middleware/validation.middleware.ts +54 -0
- package/apps/backend/src/scripts/promote-user.ts +120 -0
- package/apps/backend/src/server.ts +68 -0
- package/apps/backend/src/utils/api-response.utils.ts +38 -0
- package/apps/backend/src/utils/token.utils.ts +37 -0
- package/apps/backend/tsconfig.json +15 -0
- package/apps/frontend/.dockerignore +11 -0
- package/apps/frontend/.turbo/turbo-build.log +39 -0
- package/apps/frontend/.turbo/turbo-lint.log +1 -0
- package/apps/frontend/.turbo/turbo-typecheck.log +1 -0
- package/apps/frontend/AGENTS.md +9 -0
- package/apps/frontend/Dockerfile +53 -0
- package/apps/frontend/README.md +36 -0
- package/apps/frontend/eslint.config.mjs +18 -0
- package/apps/frontend/next.config.ts +35 -0
- package/apps/frontend/package.json +41 -0
- package/apps/frontend/public/file.svg +1 -0
- package/apps/frontend/public/globe.svg +1 -0
- package/apps/frontend/public/next.svg +1 -0
- package/apps/frontend/public/vercel.svg +1 -0
- package/apps/frontend/public/window.svg +1 -0
- package/apps/frontend/src/app/(auth)/_components/auth-footer-link.tsx +44 -0
- package/apps/frontend/src/app/(auth)/_components/auth-status-card.tsx +50 -0
- package/apps/frontend/src/app/(auth)/_components/unverified-email-banner.tsx +35 -0
- package/apps/frontend/src/app/(auth)/forgot-password/page.tsx +111 -0
- package/apps/frontend/src/app/(auth)/layout.tsx +51 -0
- package/apps/frontend/src/app/(auth)/login/page.tsx +183 -0
- package/apps/frontend/src/app/(auth)/register/page.tsx +172 -0
- package/apps/frontend/src/app/(auth)/reset-password/page.tsx +143 -0
- package/apps/frontend/src/app/(auth)/verify-email/page.tsx +162 -0
- package/apps/frontend/src/app/auth/oauth-success/page.tsx +143 -0
- package/apps/frontend/src/app/dashboard/_components/dashboard-header.tsx +64 -0
- package/apps/frontend/src/app/dashboard/_components/dashboard-nav.tsx +87 -0
- package/apps/frontend/src/app/dashboard/_components/profile-banner.tsx +82 -0
- package/apps/frontend/src/app/dashboard/admin/page.tsx +373 -0
- package/apps/frontend/src/app/dashboard/layout.tsx +92 -0
- package/apps/frontend/src/app/dashboard/page.tsx +127 -0
- package/apps/frontend/src/app/dashboard/security/_components/oauth-provider-card.tsx +132 -0
- package/apps/frontend/src/app/dashboard/security/page.tsx +132 -0
- package/apps/frontend/src/app/dashboard/sessions/_components/session-card.tsx +77 -0
- package/apps/frontend/src/app/dashboard/sessions/_components/sessions-skeleton.tsx +21 -0
- package/apps/frontend/src/app/dashboard/sessions/page.tsx +146 -0
- package/apps/frontend/src/app/favicon.ico +0 -0
- package/apps/frontend/src/app/globals.css +26 -0
- package/apps/frontend/src/app/layout.tsx +39 -0
- package/apps/frontend/src/app/page.tsx +166 -0
- package/apps/frontend/src/components/auth/can.tsx +109 -0
- package/apps/frontend/src/components/auth/oauth-buttons.tsx +83 -0
- package/apps/frontend/src/components/auth/password-strength.tsx +115 -0
- package/apps/frontend/src/components/dashboard/system-status-pill.tsx +98 -0
- package/apps/frontend/src/components/ui/alert.tsx +54 -0
- package/apps/frontend/src/components/ui/button.tsx +62 -0
- package/apps/frontend/src/components/ui/card.tsx +79 -0
- package/apps/frontend/src/components/ui/input.tsx +78 -0
- package/apps/frontend/src/context/auth-context.tsx +253 -0
- package/apps/frontend/src/hooks/queries/use-admin.ts +46 -0
- package/apps/frontend/src/hooks/queries/use-health.ts +30 -0
- package/apps/frontend/src/hooks/queries/use-oauth.ts +46 -0
- package/apps/frontend/src/hooks/queries/use-sessions.ts +60 -0
- package/apps/frontend/src/hooks/use-auth.ts +2 -0
- package/apps/frontend/src/hooks/use-permission.ts +36 -0
- package/apps/frontend/src/lib/api/admin/admin.api.ts +79 -0
- package/apps/frontend/src/lib/api/auth/auth.api.ts +97 -0
- package/apps/frontend/src/lib/api/auth/oauth.api.ts +30 -0
- package/apps/frontend/src/lib/api/auth/sessions.api.ts +21 -0
- package/apps/frontend/src/lib/api/client.ts +93 -0
- package/apps/frontend/src/lib/api/health.api.ts +16 -0
- package/apps/frontend/src/lib/utils.ts +60 -0
- package/apps/frontend/src/middleware.ts +52 -0
- package/apps/frontend/src/providers/query-provider.tsx +55 -0
- package/apps/frontend/tsconfig.json +34 -0
- package/bin/cli.js +206 -0
- package/docker-compose.yml +92 -0
- package/package.json +37 -4
- package/packages/types/.turbo/turbo-build.log +1 -0
- package/packages/types/.turbo/turbo-typecheck.log +1 -0
- package/packages/types/dist/api.types.d.ts +34 -0
- package/packages/types/dist/api.types.d.ts.map +1 -0
- package/packages/types/dist/api.types.js +2 -0
- package/packages/types/dist/api.types.js.map +1 -0
- package/packages/types/dist/auth.types.d.ts +93 -0
- package/packages/types/dist/auth.types.d.ts.map +1 -0
- package/packages/types/dist/auth.types.js +62 -0
- package/packages/types/dist/auth.types.js.map +1 -0
- package/packages/types/dist/index.d.ts +7 -0
- package/packages/types/dist/index.d.ts.map +1 -0
- package/packages/types/dist/index.js +7 -0
- package/packages/types/dist/index.js.map +1 -0
- package/packages/types/node_modules/.bin/tsc +43 -0
- package/packages/types/node_modules/.bin/tsserver +43 -0
- package/packages/types/package.json +23 -0
- package/packages/types/src/api.types.ts +36 -0
- package/packages/types/src/auth.types.ts +137 -0
- package/packages/types/src/index.ts +7 -0
- package/packages/types/tsconfig.json +15 -0
- package/packages/validations/.turbo/turbo-build.log +1 -0
- package/packages/validations/.turbo/turbo-typecheck.log +1 -0
- package/packages/validations/dist/auth.validation.d.ts +88 -0
- package/packages/validations/dist/auth.validation.d.ts.map +1 -0
- package/packages/validations/dist/auth.validation.js +94 -0
- package/packages/validations/dist/auth.validation.js.map +1 -0
- package/packages/validations/dist/common.validation.d.ts +19 -0
- package/packages/validations/dist/common.validation.d.ts.map +1 -0
- package/packages/validations/dist/common.validation.js +35 -0
- package/packages/validations/dist/common.validation.js.map +1 -0
- package/packages/validations/dist/index.d.ts +7 -0
- package/packages/validations/dist/index.d.ts.map +1 -0
- package/packages/validations/dist/index.js +7 -0
- package/packages/validations/dist/index.js.map +1 -0
- package/packages/validations/node_modules/.bin/tsc +43 -0
- package/packages/validations/node_modules/.bin/tsserver +43 -0
- package/packages/validations/package.json +26 -0
- package/packages/validations/src/auth.validation.ts +127 -0
- package/packages/validations/src/common.validation.ts +40 -0
- package/packages/validations/src/index.ts +7 -0
- package/packages/validations/tsconfig.json +15 -0
- package/pnpm-workspace.yaml +7 -0
- package/turbo.json +24 -0
package/README.md
CHANGED
|
@@ -1,3 +1,217 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Express-Mongo-Next Starter (MERN + Next.js App Router)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A production-grade, developer-first authentication and session management starter template. Built with **Express 5**, **MongoDB (Mongoose)**, and **Next.js 16 (App Router)**, engineered around zero-compromise security principles and developer ergonomics.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Architecture Overview
|
|
8
|
+
|
|
9
|
+
```mermaid
|
|
10
|
+
sequenceDiagram
|
|
11
|
+
autonumber
|
|
12
|
+
actor User
|
|
13
|
+
participant NextJS as Next.js 16 (Frontend)
|
|
14
|
+
participant Edge as Edge Middleware
|
|
15
|
+
participant Express as Express 5 (Backend)
|
|
16
|
+
participant Mongo as MongoDB
|
|
17
|
+
|
|
18
|
+
Note over User,NextJS: 1. Authentication (Credentials or OAuth)
|
|
19
|
+
User->>NextJS: Submit Credentials or Sign in with Google/GitHub
|
|
20
|
+
NextJS->>Express: POST /api/auth/login (or OAuth callback)
|
|
21
|
+
Express->>Mongo: Validate user & record active session
|
|
22
|
+
Express-->>NextJS: 200 OK + In-Memory Access Token + HTTP-Only Refresh Cookie
|
|
23
|
+
|
|
24
|
+
Note over NextJS,Edge: 2. Route Protection
|
|
25
|
+
User->>NextJS: Navigate to /dashboard
|
|
26
|
+
Edge->>Edge: Verify `hasSession` cookie
|
|
27
|
+
alt Session Valid
|
|
28
|
+
NextJS-->>User: Render Dashboard Shell
|
|
29
|
+
else Unauthenticated
|
|
30
|
+
Edge-->>User: Redirect to /login?from=/dashboard
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
Note over NextJS,Express: 3. Silent Token Rotation & Invalidation
|
|
34
|
+
NextJS->>Express: API request with Bearer Access Token
|
|
35
|
+
alt Access Token Expired (401)
|
|
36
|
+
NextJS->>Express: POST /api/auth/refresh-token (Sends HTTP-only Cookie)
|
|
37
|
+
Express->>Mongo: Rotate Refresh Token Family
|
|
38
|
+
Express-->>NextJS: New Access Token + Rotated Refresh Cookie
|
|
39
|
+
NextJS->>Express: Replay original request
|
|
40
|
+
end
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## Key Features
|
|
46
|
+
|
|
47
|
+
* **Zero-Compromise Token Architecture**:
|
|
48
|
+
* **Short-lived Access Tokens (15m)** kept strictly in client memory to mitigate XSS vector attacks.
|
|
49
|
+
* **Long-lived Refresh Tokens (7d)** stored in `HttpOnly`, `SameSite=Lax`, `Secure` cookies with automatic rotation and reuse detection.
|
|
50
|
+
* **Complete Credential Lifecycle**:
|
|
51
|
+
* Registration with real-time password strength meter and 72-byte Bcrypt truncate-safety guards.
|
|
52
|
+
* Email verification workflow with automatic token processing and resend capability (Nodemailer & Resend API support).
|
|
53
|
+
* Anti-enumeration secure password recovery (`/forgot-password` and `/reset-password`).
|
|
54
|
+
* **OAuth 2.0 Integration**:
|
|
55
|
+
* One-click authentication with Google and GitHub.
|
|
56
|
+
* Dedicated callback handler (`/auth/oauth-success`) that hydrates memory tokens and scrubs query params cleanly.
|
|
57
|
+
* Account linking and unlinking with safety warnings against user account lockouts.
|
|
58
|
+
* **Active Session Manager**:
|
|
59
|
+
* Detailed session auditing (`GET /api/auth/sessions`) with device type detection (Laptop, Smartphone, Tablet), browser, OS, and client IP.
|
|
60
|
+
* Individual session termination (`DELETE /api/auth/sessions/:id`).
|
|
61
|
+
* Global "Sign out from all devices" (`POST /api/auth/logout-all`).
|
|
62
|
+
* **Technical Dark-Mode UI**:
|
|
63
|
+
* Responsive and accessible UI built with Tailwind CSS v4, Lucide icons, and component primitives.
|
|
64
|
+
* Mobile-first navigation and layout adaptations across mobile, tablet, and desktop viewports.
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## Quick Start (2-Step Setup)
|
|
69
|
+
|
|
70
|
+
### 1. Install Dependencies
|
|
71
|
+
```bash
|
|
72
|
+
# From the repository root:
|
|
73
|
+
pnpm install
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### 2. Configure Environment Files
|
|
77
|
+
Copy the example environment files for both apps:
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
# Backend configuration
|
|
81
|
+
cp apps/backend/.env.example apps/backend/.env
|
|
82
|
+
|
|
83
|
+
# Frontend configuration
|
|
84
|
+
cp apps/frontend/.env.example apps/frontend/.env.local
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
> [!NOTE]
|
|
88
|
+
> Ensure local MongoDB is running (`mongodb://localhost:27017/auth_db`) or supply your MongoDB Atlas connection string in `apps/backend/.env`.
|
|
89
|
+
|
|
90
|
+
### 3. Run Development Servers
|
|
91
|
+
```bash
|
|
92
|
+
pnpm dev
|
|
93
|
+
```
|
|
94
|
+
* **Frontend**: [http://localhost:3000](http://localhost:3000)
|
|
95
|
+
* **Backend API**: [http://localhost:5000](http://localhost:5000)
|
|
96
|
+
|
|
97
|
+
---
|
|
98
|
+
|
|
99
|
+
## Monorepo Architecture & Directory Structure
|
|
100
|
+
|
|
101
|
+
```text
|
|
102
|
+
.
|
|
103
|
+
├── apps/
|
|
104
|
+
│ ├── backend/ # Express 5 REST API (Port 5000)
|
|
105
|
+
│ └── frontend/ # Next.js 16 App Router (Port 3000)
|
|
106
|
+
├── packages/
|
|
107
|
+
│ ├── types/ # Shared domain entities & API response interfaces
|
|
108
|
+
│ └── validations/ # Universal Zod schemas & byte-boundary validations
|
|
109
|
+
├── turbo.json # Turborepo task pipelines & build caching
|
|
110
|
+
├── pnpm-workspace.yaml # Monorepo workspace membership
|
|
111
|
+
├── docker-compose.yml # Production multi-stage Docker deployment
|
|
112
|
+
└── package.json # Root monorepo scripts & orchestration
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
---
|
|
116
|
+
|
|
117
|
+
## Monorepo Workspace Scripts
|
|
118
|
+
|
|
119
|
+
All workspace commands run directly from the root with Turborepo caching:
|
|
120
|
+
|
|
121
|
+
| Command | Description |
|
|
122
|
+
| :--- | :--- |
|
|
123
|
+
| `pnpm dev` | Starts backend (`tsx watch`) and frontend (`next dev`) concurrently. |
|
|
124
|
+
| `pnpm dev:backend` | Starts only the Express API backend. |
|
|
125
|
+
| `pnpm dev:frontend` | Starts only the Next.js frontend. |
|
|
126
|
+
| `pnpm build` | Builds shared packages (`@starter/types`, `@starter/validations`), backend (`tsc`), and Next.js frontend with Turborepo caching. |
|
|
127
|
+
| `pnpm lint` | Runs ESLint checks across workspace packages. |
|
|
128
|
+
| `pnpm typecheck` | Runs TypeScript static verification (`tsc --noEmit`) across all apps and shared packages. |
|
|
129
|
+
| `pnpm clean` | Cleans dist and cache artifacts across all apps and packages. |
|
|
130
|
+
| `pnpm docker:build` | Builds and starts all 3 containers (`backend`, `frontend`, `mongodb`) in background. |
|
|
131
|
+
| `pnpm docker:logs` | Streams live container logs. |
|
|
132
|
+
| `pnpm docker:down` | Stops all containers (preserves MongoDB data in volume). |
|
|
133
|
+
|
|
134
|
+
---
|
|
135
|
+
|
|
136
|
+
## Running with Docker (Production Containers)
|
|
137
|
+
|
|
138
|
+
You can spin up the full stack (Next.js, Express, and MongoDB) using Docker without installing Node or MongoDB on your host:
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
# 1. Build and start containers
|
|
142
|
+
pnpm docker:build
|
|
143
|
+
|
|
144
|
+
# 2. View logs
|
|
145
|
+
pnpm docker:logs
|
|
146
|
+
|
|
147
|
+
# 3. Stop containers
|
|
148
|
+
pnpm docker:down
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
---
|
|
152
|
+
|
|
153
|
+
## Implementation Details & Design Rationale
|
|
154
|
+
|
|
155
|
+
### 1. In-Memory JWT vs LocalStorage
|
|
156
|
+
Storing access tokens in `localStorage` or `sessionStorage` leaves applications vulnerable to Cross-Site Scripting (XSS). In this architecture, the `accessToken` is stored in a private JavaScript closure inside `frontend/src/lib/api/client.ts`. When the page refreshes, the app silently calls `GET /api/auth/me` or `/api/auth/refresh-token` to re-hydrate the user session without flashing the UI.
|
|
157
|
+
|
|
158
|
+
### 2. Cookie Path Scope (`path: "/"`)
|
|
159
|
+
Refresh token cookies must be available across both `/api/auth/refresh-token` and OAuth redirection endpoints like `/api/auth/oauth/google/callback`. Setting `path: "/"` in `refreshCookieOptions` ensures the cookie is transmitted consistently without request-path scoping restrictions.
|
|
160
|
+
|
|
161
|
+
### 3. Edge Middleware Route Protection
|
|
162
|
+
Next.js Edge Middleware intercepts unauthorized requests to `/dashboard/*` without needing synchronous round-trip API calls to Express on every navigation. A lightweight `hasSession=true` cookie is toggled by `AuthContext` upon login/logout. If absent, the middleware instantly issues a 307 redirect to `/login?from=...`.
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
166
|
+
## Concise Debugging Guide & Tools
|
|
167
|
+
|
|
168
|
+
### 1. Inspecting Authentication State in Chrome DevTools
|
|
169
|
+
* **Application > Cookies > `http://localhost:5000`**:
|
|
170
|
+
* Verify `refreshToken` is present, flagged with `HttpOnly`, `SameSite=Lax`, and `Path=/`.
|
|
171
|
+
* **Application > Cookies > `http://localhost:3000`**:
|
|
172
|
+
* Verify `hasSession=true` exists when signed in.
|
|
173
|
+
* **Network Tab**:
|
|
174
|
+
* Filter by `Fetch/XHR`. Look for `401 Unauthorized` followed immediately by `POST /api/auth/refresh-token` (status `200`) and the retried original request.
|
|
175
|
+
|
|
176
|
+
### 2. Testing Endpoints Directly via cURL
|
|
177
|
+
Test session refresh or login directly from your terminal:
|
|
178
|
+
|
|
179
|
+
```bash
|
|
180
|
+
# 1. Login with credentials
|
|
181
|
+
curl -i -X POST http://localhost:5000/api/auth/login \
|
|
182
|
+
-H "Content-Type: application/json" \
|
|
183
|
+
-d '{"email":"user@example.com","password":"Password123!"}' \
|
|
184
|
+
-c cookies.txt
|
|
185
|
+
|
|
186
|
+
# 2. Access protected endpoint using in-memory Bearer token
|
|
187
|
+
curl -i -X GET http://localhost:5000/api/auth/me \
|
|
188
|
+
-H "Authorization: Bearer <ACCESS_TOKEN>"
|
|
189
|
+
|
|
190
|
+
# 3. Rotate refresh token using cookie
|
|
191
|
+
curl -i -X POST http://localhost:5000/api/auth/refresh-token \
|
|
192
|
+
-b cookies.txt \
|
|
193
|
+
-c cookies.txt
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
### 3. Inspecting Active Sessions in MongoDB
|
|
197
|
+
Connect via `mongosh` to inspect database session persistence:
|
|
198
|
+
|
|
199
|
+
```javascript
|
|
200
|
+
use auth_db
|
|
201
|
+
|
|
202
|
+
// View active sessions for a user
|
|
203
|
+
db.sessions.find({ userId: ObjectId("<USER_ID>") }).pretty()
|
|
204
|
+
|
|
205
|
+
// View refresh token rotation family
|
|
206
|
+
db.refreshtokens.find({ userId: ObjectId("<USER_ID>") }).pretty()
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
### 4. Common Developer Pitfalls
|
|
210
|
+
* **Google/GitHub Redirect URI Mismatch**: Make sure the callback configured in your OAuth provider dashboard matches `http://localhost:5000/api/auth/oauth/<provider>/callback` exactly.
|
|
211
|
+
* **Bcrypt 72-Byte Truncation**: Bcrypt natively ignores characters beyond 72 bytes. The registration form and backend schema explicitly reject inputs over 72 characters to maintain deterministic password strength.
|
|
212
|
+
* **React 19 Cascading Renders**: Avoid `setState` calls synchronously inside `useEffect` bodies. Derive state during render or use asynchronous promise completions with cleanup flags.
|
|
213
|
+
|
|
214
|
+
---
|
|
215
|
+
|
|
216
|
+
## License
|
|
217
|
+
MIT
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# ==============================================================================
|
|
2
|
+
# SERVER CONFIGURATION
|
|
3
|
+
# ==============================================================================
|
|
4
|
+
NODE_ENV=development
|
|
5
|
+
PORT=5000
|
|
6
|
+
|
|
7
|
+
# ==============================================================================
|
|
8
|
+
# DATABASE (MongoDB)
|
|
9
|
+
# ==============================================================================
|
|
10
|
+
# Local: mongodb://localhost:27017/auth_db
|
|
11
|
+
# Atlas: mongodb+srv://<username>:<password>@cluster0.example.mongodb.net/auth_db?retryWrites=true&w=majority
|
|
12
|
+
MONGO_URI=mongodb://localhost:27017/auth_db
|
|
13
|
+
|
|
14
|
+
# ==============================================================================
|
|
15
|
+
# CLIENT / FRONTEND CONFIGURATION
|
|
16
|
+
# ==============================================================================
|
|
17
|
+
# Must be HTTPS in production
|
|
18
|
+
FRONTEND_URL=http://localhost:3000
|
|
19
|
+
|
|
20
|
+
# ==============================================================================
|
|
21
|
+
# AUTHENTICATION & TOKENS (JWT)
|
|
22
|
+
# ==============================================================================
|
|
23
|
+
# Generate secure 64-character random strings in your terminal with:
|
|
24
|
+
# node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
|
|
25
|
+
# or: openssl rand -hex 32
|
|
26
|
+
ACCESS_TOKEN_SECRET=your_jwt_access_token_secret_here_min_32_chars
|
|
27
|
+
REFRESH_TOKEN_SECRET=your_jwt_refresh_token_secret_here_min_32_chars
|
|
28
|
+
|
|
29
|
+
# ==============================================================================
|
|
30
|
+
# EMAIL SERVICE CONFIGURATION
|
|
31
|
+
# ==============================================================================
|
|
32
|
+
# Supported providers: "nodemailer" | "resend"
|
|
33
|
+
EMAIL_PROVIDER=nodemailer
|
|
34
|
+
EMAIL_FROM=MyApp <noreply@example.com>
|
|
35
|
+
|
|
36
|
+
# ------------------------------------------------------------------------------
|
|
37
|
+
# Provider Option 1: Nodemailer (SMTP)
|
|
38
|
+
# Required if EMAIL_PROVIDER=nodemailer
|
|
39
|
+
# ------------------------------------------------------------------------------
|
|
40
|
+
# Examples:
|
|
41
|
+
# Gmail: smtp.gmail.com (Port: 587 or 465)
|
|
42
|
+
# Ethereal (Test): smtp.ethereal.email (Port: 587)
|
|
43
|
+
SMTP_HOST=smtp.ethereal.email
|
|
44
|
+
SMTP_PORT=587
|
|
45
|
+
SMTP_USER=your_smtp_username
|
|
46
|
+
SMTP_PASS=your_smtp_password
|
|
47
|
+
|
|
48
|
+
# ------------------------------------------------------------------------------
|
|
49
|
+
# Provider Option 2: Resend API
|
|
50
|
+
# Required if EMAIL_PROVIDER=resend
|
|
51
|
+
# ------------------------------------------------------------------------------
|
|
52
|
+
RESEND_API_KEY=re_your_resend_api_key_here
|
|
53
|
+
|
|
54
|
+
# ==============================================================================
|
|
55
|
+
# OAUTH / OIDC CONFIGURATION (Google & GitHub)
|
|
56
|
+
# ==============================================================================
|
|
57
|
+
# Google Cloud Console: https://console.cloud.google.com/apis/credentials
|
|
58
|
+
GOOGLE_CLIENT_ID=your_google_client_id_here
|
|
59
|
+
GOOGLE_CLIENT_SECRET=your_google_client_secret_here
|
|
60
|
+
GOOGLE_CALLBACK_URL=http://localhost:5000/api/auth/oauth/google/callback
|
|
61
|
+
|
|
62
|
+
# GitHub Developer Settings: https://github.com/settings/developers
|
|
63
|
+
GITHUB_CLIENT_ID=your_github_client_id_here
|
|
64
|
+
GITHUB_CLIENT_SECRET=your_github_client_secret_here
|
|
65
|
+
GITHUB_CALLBACK_URL=http://localhost:5000/api/auth/oauth/github/callback
|
|
66
|
+
|
|
67
|
+
# ==============================================================================
|
|
68
|
+
# INITIAL ADMIN BOOTSTRAP (Optional)
|
|
69
|
+
# ==============================================================================
|
|
70
|
+
# If specified, any user registering or signing in (credentials or OAuth) with
|
|
71
|
+
# this email is automatically granted the "admin" role.
|
|
72
|
+
INITIAL_ADMIN_EMAIL=admin@example.com
|
|
73
|
+
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# ==============================================================================
|
|
2
|
+
# STAGE 1: TypeScript Build & Native Compilation (Monorepo Context)
|
|
3
|
+
# ==============================================================================
|
|
4
|
+
FROM node:22-alpine AS builder
|
|
5
|
+
|
|
6
|
+
WORKDIR /app
|
|
7
|
+
|
|
8
|
+
# Install native build tools (python3, make, g++) required by bcrypt C++ addon
|
|
9
|
+
RUN apk add --no-cache python3 make g++
|
|
10
|
+
|
|
11
|
+
# Enable pnpm via Corepack
|
|
12
|
+
RUN corepack enable && corepack prepare pnpm@11.15.0 --activate
|
|
13
|
+
|
|
14
|
+
# Copy workspace configuration and manifests
|
|
15
|
+
COPY pnpm-workspace.yaml pnpm-lock.yaml package.json turbo.json* ./
|
|
16
|
+
COPY packages/ packages/
|
|
17
|
+
COPY apps/backend/ apps/backend/
|
|
18
|
+
|
|
19
|
+
# Install dependencies across workspace (with native build approval for bcrypt/esbuild)
|
|
20
|
+
RUN pnpm install --frozen-lockfile
|
|
21
|
+
|
|
22
|
+
# Compile shared packages, then compile backend
|
|
23
|
+
RUN pnpm --filter @starter/validations build
|
|
24
|
+
RUN pnpm --filter @starter/types build
|
|
25
|
+
RUN pnpm --filter backend build
|
|
26
|
+
|
|
27
|
+
# Deploy isolated production bundle with compiled native binaries
|
|
28
|
+
RUN pnpm --filter backend --prod --legacy deploy /app/deploy
|
|
29
|
+
|
|
30
|
+
# ==============================================================================
|
|
31
|
+
# STAGE 2: Minimal Production Runner (No Build Tools, Non-Root)
|
|
32
|
+
# ==============================================================================
|
|
33
|
+
FROM node:22-alpine AS runner
|
|
34
|
+
|
|
35
|
+
WORKDIR /app
|
|
36
|
+
ENV NODE_ENV=production
|
|
37
|
+
|
|
38
|
+
# Install curl for container health check probe
|
|
39
|
+
RUN apk add --no-cache curl
|
|
40
|
+
|
|
41
|
+
# Copy deployed standalone bundle and compiled dist from builder
|
|
42
|
+
COPY --from=builder /app/deploy ./
|
|
43
|
+
COPY --from=builder /app/apps/backend/dist ./dist
|
|
44
|
+
|
|
45
|
+
# Security: Run as non-privileged default 'node' user
|
|
46
|
+
USER node
|
|
47
|
+
|
|
48
|
+
# Expose backend API port
|
|
49
|
+
EXPOSE 5000
|
|
50
|
+
|
|
51
|
+
# Health check probe against the backend /health endpoint
|
|
52
|
+
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
|
53
|
+
CMD curl -f http://localhost:5000/health || exit 1
|
|
54
|
+
|
|
55
|
+
# Start the Express production server
|
|
56
|
+
CMD ["node", "dist/server.js"]
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "backend",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"dev": "tsx watch src/server.ts",
|
|
8
|
+
"clean": "rm -rf dist",
|
|
9
|
+
"build": "rm -rf dist && tsc",
|
|
10
|
+
"typecheck": "tsc --noEmit",
|
|
11
|
+
"prestart": "pnpm run build",
|
|
12
|
+
"start": "node dist/server.js",
|
|
13
|
+
"admin:promote": "tsx src/scripts/promote-user.ts",
|
|
14
|
+
"test": "node --test"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [],
|
|
17
|
+
"author": "",
|
|
18
|
+
"license": "ISC",
|
|
19
|
+
"devEngines": {
|
|
20
|
+
"packageManager": {
|
|
21
|
+
"name": "pnpm",
|
|
22
|
+
"version": "^11.15.0",
|
|
23
|
+
"onFail": "download"
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"type": "module",
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"@starter/types": "workspace:*",
|
|
29
|
+
"@starter/validations": "workspace:*",
|
|
30
|
+
"bcrypt": "^6.0.0",
|
|
31
|
+
"cookie-parser": "^1.4.7",
|
|
32
|
+
"cors": "^2.8.6",
|
|
33
|
+
"dotenv": "^18.0.9",
|
|
34
|
+
"express": "^5.3.0",
|
|
35
|
+
"express-rate-limit": "^8.7.1",
|
|
36
|
+
"helmet": "^8.3.0",
|
|
37
|
+
"jsonwebtoken": "^9.0.3",
|
|
38
|
+
"mongoose": "^9.11.4",
|
|
39
|
+
"nodemailer": "^10.2.1",
|
|
40
|
+
"pino": "^10.4.0",
|
|
41
|
+
"resend": "^6.34.1",
|
|
42
|
+
"zod": "^4.6.7"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@types/bcrypt": "^6.0.0",
|
|
46
|
+
"@types/cookie-parser": "^1.4.10",
|
|
47
|
+
"@types/cors": "^2.8.19",
|
|
48
|
+
"@types/express": "^5.0.6",
|
|
49
|
+
"@types/jsonwebtoken": "^9.0.10",
|
|
50
|
+
"@types/node": "^26.6.5",
|
|
51
|
+
"@types/nodemailer": "^8.0.2",
|
|
52
|
+
"tsx": "^4.23.15",
|
|
53
|
+
"typescript": "^7.0.2"
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import express from "express";
|
|
2
|
+
import helmet from "helmet";
|
|
3
|
+
import cors from "cors";
|
|
4
|
+
|
|
5
|
+
import authRoutes from "./features/auth/auth.route.js";
|
|
6
|
+
import adminRoutes from "./features/admin/admin.route.js";
|
|
7
|
+
import { env } from "./config/env.js";
|
|
8
|
+
import {
|
|
9
|
+
errorHandler,
|
|
10
|
+
notFoundHandler,
|
|
11
|
+
} from "./middleware/error.middleware.js";
|
|
12
|
+
import cookieParser from "cookie-parser";
|
|
13
|
+
import type { Request, Response, NextFunction } from "express";
|
|
14
|
+
import mongoose from "mongoose";
|
|
15
|
+
|
|
16
|
+
const app = express();
|
|
17
|
+
|
|
18
|
+
app.use(cookieParser());
|
|
19
|
+
|
|
20
|
+
// In production behind a reverse proxy or load balancer (Nginx, AWS ALB, Cloudflare, Render, Fly.io), Express sees every incoming request as originating from the proxy's IP address (e.g. 127.0.0.1).
|
|
21
|
+
if (env.NODE_ENV === "production") {
|
|
22
|
+
app.set("trust proxy", 1);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Hide Express identification header.
|
|
26
|
+
app.disable("x-powered-by");
|
|
27
|
+
|
|
28
|
+
// Security headers.
|
|
29
|
+
app.use(helmet());
|
|
30
|
+
|
|
31
|
+
// Cross-origin configuration.
|
|
32
|
+
app.use(
|
|
33
|
+
cors({
|
|
34
|
+
origin: env.FRONTEND_URL,
|
|
35
|
+
credentials: true, // MANDATORY for cookies to work with your frontend!
|
|
36
|
+
methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
|
|
37
|
+
allowedHeaders: ["Content-Type", "Authorization"],
|
|
38
|
+
}),
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
// Parse JSON request bodies.
|
|
42
|
+
app.use(express.json({ limit: "10kb" }));
|
|
43
|
+
|
|
44
|
+
// HEALTH CHECK (Placed before API routes and before notFoundHandler)
|
|
45
|
+
app.get("/health", (_req: Request, res: Response) => {
|
|
46
|
+
const isDbConnected = mongoose.connection.readyState === 1;
|
|
47
|
+
|
|
48
|
+
const healthData = {
|
|
49
|
+
status: isDbConnected ? "ok" : "degraded",
|
|
50
|
+
database: isDbConnected ? "connected" : "disconnected",
|
|
51
|
+
uptimeSeconds: Math.floor(process.uptime()),
|
|
52
|
+
timestamp: new Date().toISOString(),
|
|
53
|
+
};
|
|
54
|
+
// Return 503 if DB is disconnected so orchestrators/load-balancers detect failures
|
|
55
|
+
const statusCode = isDbConnected ? 200 : 503;
|
|
56
|
+
|
|
57
|
+
res.status(statusCode).json(healthData);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
// Authentication routes.
|
|
61
|
+
app.use("/api/auth", authRoutes);
|
|
62
|
+
|
|
63
|
+
// Administrative & Authorization-protected routes.
|
|
64
|
+
app.use("/api/admin", adminRoutes);
|
|
65
|
+
|
|
66
|
+
// Handle unknown routes.
|
|
67
|
+
app.use(notFoundHandler);
|
|
68
|
+
|
|
69
|
+
// Centralized error handler.
|
|
70
|
+
app.use(errorHandler);
|
|
71
|
+
|
|
72
|
+
export default app;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import mongoose from "mongoose";
|
|
2
|
+
import { env } from "./env.js";
|
|
3
|
+
import { logger } from "./logger.js";
|
|
4
|
+
|
|
5
|
+
let connectionPromise: Promise<typeof mongoose> | null = null;
|
|
6
|
+
|
|
7
|
+
export async function connectDatabase(): Promise<void> {
|
|
8
|
+
// If readyState === 1, MongoDB is already connected.
|
|
9
|
+
if (mongoose.connection.readyState === 1) {
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// Imagine two requests trigger database initialization at nearly the same time. Without storing the promise, both could initiate separate connection attempts.
|
|
14
|
+
if (!connectionPromise) {
|
|
15
|
+
connectionPromise = mongoose.connect(env.MONGO_URI).catch((error) => {
|
|
16
|
+
connectionPromise = null;
|
|
17
|
+
throw error;
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
await connectionPromise;
|
|
22
|
+
|
|
23
|
+
logger.info("MongoDB connected successfully");
|
|
24
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import "dotenv/config";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
const envSchema = z.object({
|
|
5
|
+
NODE_ENV: z
|
|
6
|
+
.enum(["development", "test", "production"])
|
|
7
|
+
.default("development"),
|
|
8
|
+
|
|
9
|
+
PORT: z.coerce.number().int().positive().default(5000),
|
|
10
|
+
|
|
11
|
+
MONGO_URI: z.string().min(1),
|
|
12
|
+
FRONTEND_URL: z.url(),
|
|
13
|
+
|
|
14
|
+
EMAIL_PROVIDER: z.enum(["nodemailer", "resend"]).default("nodemailer"),
|
|
15
|
+
|
|
16
|
+
EMAIL_FROM: z.string().min(1),
|
|
17
|
+
|
|
18
|
+
SMTP_HOST: z.string().optional(),
|
|
19
|
+
SMTP_PORT: z.coerce.number().int().positive().default(587),
|
|
20
|
+
SMTP_USER: z.string().optional(),
|
|
21
|
+
SMTP_PASS: z.string().optional(),
|
|
22
|
+
|
|
23
|
+
RESEND_API_KEY: z.string().optional(),
|
|
24
|
+
ACCESS_TOKEN_SECRET: z.string().min(1),
|
|
25
|
+
REFRESH_TOKEN_SECRET: z.string().min(1),
|
|
26
|
+
|
|
27
|
+
GOOGLE_CLIENT_ID: z.string().optional(),
|
|
28
|
+
GOOGLE_CLIENT_SECRET: z.string().optional(),
|
|
29
|
+
GOOGLE_CALLBACK_URL: z.string().optional(),
|
|
30
|
+
|
|
31
|
+
GITHUB_CLIENT_ID: z.string().optional(),
|
|
32
|
+
GITHUB_CLIENT_SECRET: z.string().optional(),
|
|
33
|
+
GITHUB_CALLBACK_URL: z.string().optional(),
|
|
34
|
+
|
|
35
|
+
INITIAL_ADMIN_EMAIL: z.string().email().optional(),
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
export const env = envSchema.parse(process.env);
|
|
39
|
+
|
|
40
|
+
if (
|
|
41
|
+
env.EMAIL_PROVIDER === "nodemailer" &&
|
|
42
|
+
(!env.SMTP_HOST || !env.SMTP_USER || !env.SMTP_PASS)
|
|
43
|
+
) {
|
|
44
|
+
throw new Error("SMTP configuration is incomplete");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (env.EMAIL_PROVIDER === "resend" && !env.RESEND_API_KEY) {
|
|
48
|
+
throw new Error("RESEND_API_KEY is required");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const frontendUrlObj = new URL(env.FRONTEND_URL);
|
|
52
|
+
const isLocalhost =
|
|
53
|
+
frontendUrlObj.hostname === "localhost" ||
|
|
54
|
+
frontendUrlObj.hostname === "127.0.0.1";
|
|
55
|
+
|
|
56
|
+
if (
|
|
57
|
+
env.NODE_ENV === "production" &&
|
|
58
|
+
!isLocalhost &&
|
|
59
|
+
frontendUrlObj.protocol !== "https:"
|
|
60
|
+
) {
|
|
61
|
+
throw new Error("FRONTEND_URL must use HTTPS in production");
|
|
62
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Application Logger (Pino)
|
|
3
|
+
*
|
|
4
|
+
* Usage in Services & Controllers:
|
|
5
|
+
* Pass structured metadata objects as the first argument, message string as the second.
|
|
6
|
+
* Note: Never log sensitive data (e.g. passwords, secrets, refresh tokens).
|
|
7
|
+
*
|
|
8
|
+
* Scenarios & Examples:
|
|
9
|
+
* - info: Milestones & audit events
|
|
10
|
+
* `logger.info({ userId: user.id }, "User registered successfully");`
|
|
11
|
+
* - warn: Degraded states, suspicious events, or recoverable issues
|
|
12
|
+
* `logger.warn({ ip: req.ip, email }, "Repeated failed login attempt");`
|
|
13
|
+
* - error: Caught exceptions & background task failures
|
|
14
|
+
* `logger.error({ err, userId }, "Failed to deliver verification email");`
|
|
15
|
+
* - debug: Development-only troubleshooting (automatically silenced in production)
|
|
16
|
+
* `logger.debug({ state, provider }, "OAuth handshake payload received");`
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import pino from "pino";
|
|
20
|
+
import { env } from "./env.js";
|
|
21
|
+
|
|
22
|
+
export const logger = pino({
|
|
23
|
+
level: env.NODE_ENV === "production" ? "info" : "debug",
|
|
24
|
+
});
|