authkit-api 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/CHANGELOG.md +26 -0
- package/LICENSE +21 -0
- package/README.md +109 -2
- package/bin/cli.js +8 -0
- package/package.json +69 -4
- package/src/constants.js +24 -0
- package/src/generator.js +112 -0
- package/src/index.js +89 -0
- package/src/prompts.js +43 -0
- package/src/utils/fs.js +36 -0
- package/src/utils/logger.js +8 -0
- package/src/utils/packageJson.js +16 -0
- package/src/utils/validateProjectName.js +19 -0
- package/templates/base/Dockerfile +22 -0
- package/templates/base/README.md +108 -0
- package/templates/base/_dockerignore +16 -0
- package/templates/base/_env.example +25 -0
- package/templates/base/_gitignore +5 -0
- package/templates/base/_husky/pre-commit +1 -0
- package/templates/base/_prettierignore +5 -0
- package/templates/base/_prettierrc +1 -0
- package/templates/base/eslint.config.js +23 -0
- package/templates/base/package.json +62 -0
- package/templates/base/scripts/docker-entrypoint.sh +9 -0
- package/templates/base/scripts/generate-postman.js +70 -0
- package/templates/base/scripts/seed-admin.js +61 -0
- package/templates/base/src/app.js +46 -0
- package/templates/base/src/config/env.js +15 -0
- package/templates/base/src/config/env.schema.js +85 -0
- package/templates/base/src/config/logger.js +20 -0
- package/templates/base/src/constants/examples.js +3 -0
- package/templates/base/src/constants/roles.js +2 -0
- package/templates/base/src/constants/user.rules.js +16 -0
- package/templates/base/src/docs/openapi.js +26 -0
- package/templates/base/src/docs/openapi.registry.js +81 -0
- package/templates/base/src/docs/paths/auth.paths.js +87 -0
- package/templates/base/src/docs/paths/user.paths.js +87 -0
- package/templates/base/src/middlewares/authenticate.js +19 -0
- package/templates/base/src/middlewares/authorize.js +11 -0
- package/templates/base/src/middlewares/errorHandler.js +35 -0
- package/templates/base/src/middlewares/notFound.js +5 -0
- package/templates/base/src/middlewares/rateLimiter.js +20 -0
- package/templates/base/src/middlewares/validate.js +31 -0
- package/templates/base/src/modules/auth/auth.controller.js +40 -0
- package/templates/base/src/modules/auth/auth.cookie.js +21 -0
- package/templates/base/src/modules/auth/auth.routes.js +12 -0
- package/templates/base/src/modules/auth/auth.service.js +79 -0
- package/templates/base/src/modules/auth/auth.validation.js +41 -0
- package/templates/base/src/modules/user/user.controller.js +21 -0
- package/templates/base/src/modules/user/user.routes.js +22 -0
- package/templates/base/src/modules/user/user.service.js +19 -0
- package/templates/base/src/modules/user/user.validation.js +24 -0
- package/templates/base/src/routes/docs.routes.js +16 -0
- package/templates/base/src/routes/health.routes.js +17 -0
- package/templates/base/src/routes/index.js +13 -0
- package/templates/base/src/server.js +50 -0
- package/templates/base/src/utils/ApiError.js +32 -0
- package/templates/base/src/utils/apiResponse.js +8 -0
- package/templates/base/src/utils/password.js +14 -0
- package/templates/base/src/utils/token.js +46 -0
- package/templates/base/src/utils/zod.js +5 -0
- package/templates/base/tests/app.test.js +67 -0
- package/templates/base/tests/auth.test.js +185 -0
- package/templates/base/tests/authenticate.test.js +61 -0
- package/templates/base/tests/docs.test.js +115 -0
- package/templates/base/tests/env.test.js +94 -0
- package/templates/base/tests/health.test.js +21 -0
- package/templates/base/tests/helpers/auth.helper.js +41 -0
- package/templates/base/tests/password.test.js +18 -0
- package/templates/base/tests/postman.test.js +31 -0
- package/templates/base/tests/rateLimiter.test.js +27 -0
- package/templates/base/tests/seedAdmin.test.js +42 -0
- package/templates/base/tests/token.test.js +69 -0
- package/templates/base/tests/trustProxy.test.js +24 -0
- package/templates/base/tests/user.repository.test.js +210 -0
- package/templates/base/tests/user.test.js +144 -0
- package/templates/base/tests/validate.test.js +35 -0
- package/templates/base/tests/validation.test.js +61 -0
- package/templates/base/vitest.config.js +16 -0
- package/templates/databases/mongodb/README.part.md +23 -0
- package/templates/databases/mongodb/_github/workflows/ci.yml +29 -0
- package/templates/databases/mongodb/docker-compose.yml +30 -0
- package/templates/databases/mongodb/env.part +2 -0
- package/templates/databases/mongodb/package.part.json +4 -0
- package/templates/databases/mongodb/src/database/connection.js +39 -0
- package/templates/databases/mongodb/src/database/env.schema.js +3 -0
- package/templates/databases/mongodb/src/database/id.schema.js +3 -0
- package/templates/databases/mongodb/src/database/models/refreshToken.model.js +15 -0
- package/templates/databases/mongodb/src/database/models/user.model.js +41 -0
- package/templates/databases/mongodb/src/modules/user/user.repository.js +68 -0
- package/templates/databases/mongodb/tests/globalSetup.js +13 -0
- package/templates/databases/mongodb/tests/setup.js +17 -0
- package/templates/databases/postgres/README.part.md +31 -0
- package/templates/databases/postgres/_github/workflows/ci.yml +46 -0
- package/templates/databases/postgres/docker-compose.yml +34 -0
- package/templates/databases/postgres/env.part +2 -0
- package/templates/databases/postgres/package.part.json +15 -0
- package/templates/databases/postgres/prisma/migrations/20261030073256_init/migration.sql +39 -0
- package/templates/databases/postgres/prisma/migrations/migration_lock.toml +3 -0
- package/templates/databases/postgres/prisma/schema.prisma +39 -0
- package/templates/databases/postgres/prisma.config.js +14 -0
- package/templates/databases/postgres/src/database/connection.js +61 -0
- package/templates/databases/postgres/src/database/env.schema.js +3 -0
- package/templates/databases/postgres/src/database/id.schema.js +3 -0
- package/templates/databases/postgres/src/database/prisma.js +9 -0
- package/templates/databases/postgres/src/modules/user/user.repository.js +88 -0
- package/templates/databases/postgres/tests/connection.test.js +17 -0
- package/templates/databases/postgres/tests/globalSetup.js +60 -0
- package/templates/databases/postgres/tests/prismaSchema.test.js +27 -0
- package/templates/databases/postgres/tests/setup.js +15 -0
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# {{projectName}}
|
|
2
|
+
|
|
3
|
+
Express authentication API generated by authkit-api.
|
|
4
|
+
|
|
5
|
+
## What you get
|
|
6
|
+
|
|
7
|
+
- Register, login, refresh and logout with JWT access tokens and rotating refresh tokens (httpOnly cookie)
|
|
8
|
+
- Roles (`user`, `admin`), a `/users/me` endpoint and admin-only user management
|
|
9
|
+
- Validation (Zod), rate limiting, Helmet, CORS, structured logs (pino)
|
|
10
|
+
- Swagger UI, a Postman export, tests (Vitest), ESLint and Prettier
|
|
11
|
+
- A Dockerfile, a compose file and a GitHub Actions workflow
|
|
12
|
+
|
|
13
|
+
{{databaseSection}}
|
|
14
|
+
|
|
15
|
+
## Environment variables
|
|
16
|
+
|
|
17
|
+
Copy `.env.example` to `.env`. The database variable is listed in the Database section above.
|
|
18
|
+
|
|
19
|
+
| Variable | Meaning |
|
|
20
|
+
| ------------------------------------------------- | --------------------------------------------------------------- |
|
|
21
|
+
| `NODE_ENV` | `development`, `test` or `production` |
|
|
22
|
+
| `PORT` | Port the API listens on (default `3000`) |
|
|
23
|
+
| `LOG_LEVEL` | pino log level (default `info`) |
|
|
24
|
+
| `CORS_ORIGIN` | Allowed browser origin |
|
|
25
|
+
| `TRUST_PROXY` | Express `trust proxy`. Set `1` behind one reverse proxy or PaaS |
|
|
26
|
+
| `JWT_ACCESS_SECRET`, `JWT_REFRESH_SECRET` | Two different values of 32+ characters: `openssl rand -hex 32` |
|
|
27
|
+
| `JWT_ACCESS_EXPIRES_IN`, `JWT_REFRESH_EXPIRES_IN` | Token lifetimes, for example `15m` and `7d` |
|
|
28
|
+
| `AUTH_RATE_LIMIT_MAX` | Login/register requests allowed per window |
|
|
29
|
+
| `ADMIN_NAME`, `ADMIN_EMAIL`, `ADMIN_PASSWORD` | Used by `npm run seed:admin` |
|
|
30
|
+
| `API_DOCS_ENABLED` | `true` or `false`. Swagger is off in production by default |
|
|
31
|
+
|
|
32
|
+
## Scripts
|
|
33
|
+
|
|
34
|
+
| Script | Does |
|
|
35
|
+
| ----------------------------------- | ------------------------------------------------------ |
|
|
36
|
+
| `npm run dev` | Start with auto-reload, reading `.env` |
|
|
37
|
+
| `npm start` | Start for production (env from the environment) |
|
|
38
|
+
| `npm test` | Run the tests once (`test:watch`, `test:coverage` too) |
|
|
39
|
+
| `npm run lint` | ESLint (`lint:fix` repairs) |
|
|
40
|
+
| `npm run format` / `format:check` | Prettier write / check |
|
|
41
|
+
| `npm run seed:admin` | Create the first admin |
|
|
42
|
+
| `npm run docs:postman` | Write `postman/collection.json` |
|
|
43
|
+
| `npm run docker:up` / `docker:down` | Start / stop the app and database in Docker |
|
|
44
|
+
|
|
45
|
+
## API
|
|
46
|
+
|
|
47
|
+
All routes are under `/api/v1`. Successful responses look like `{ "success": true, "message": "...", "data": { ... } }`.
|
|
48
|
+
|
|
49
|
+
| Method | Path | Who | Does |
|
|
50
|
+
| ------ | ---------------- | ------ | ------------------------------------------------- |
|
|
51
|
+
| POST | `/auth/register` | all | Create a user |
|
|
52
|
+
| POST | `/auth/login` | all | Get an access token and refresh cookie |
|
|
53
|
+
| POST | `/auth/refresh` | cookie | Rotate the refresh token, new access token |
|
|
54
|
+
| POST | `/auth/logout` | cookie | Revoke the refresh token |
|
|
55
|
+
| GET | `/users/me` | user | Current user |
|
|
56
|
+
| GET | `/users` | admin | List users (`?page=1&limit=20`) |
|
|
57
|
+
| GET | `/users/:id` | admin | One user |
|
|
58
|
+
| DELETE | `/users/:id` | admin | Delete a user |
|
|
59
|
+
| GET | `/health` | all | Liveness and database check (not under `/api/v1`) |
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
curl -X POST http://localhost:3000/api/v1/auth/register \
|
|
63
|
+
-H 'Content-Type: application/json' \
|
|
64
|
+
-d '{"name":"Ada","email":"ada@example.com","password":"Passw0rd123"}'
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## API docs
|
|
68
|
+
|
|
69
|
+
Open <http://localhost:3000/api-docs> (raw JSON at `/api-docs.json`). Click Authorize and paste the access token from login.
|
|
70
|
+
|
|
71
|
+
To use Postman: run `npm run docs:postman`, then in Postman choose Import and pick `postman/collection.json`. The collection saves the access token after you log in.
|
|
72
|
+
|
|
73
|
+
## First admin
|
|
74
|
+
|
|
75
|
+
Set `ADMIN_NAME`, `ADMIN_EMAIL` and `ADMIN_PASSWORD` in `.env`, then run `npm run seed:admin`. The example password from `.env.example` is refused. If that email already exists the user is promoted to admin; an existing password is never changed.
|
|
76
|
+
|
|
77
|
+
## Add a field to the user
|
|
78
|
+
|
|
79
|
+
Example: a `phone` number. Touch these files:
|
|
80
|
+
|
|
81
|
+
1. `src/constants/user.rules.js`: add the limits (for example `PHONE: { MAX: 20 }`).
|
|
82
|
+
2. `src/modules/auth/auth.validation.js`: add the field to `registerSchema`.
|
|
83
|
+
3. `src/modules/auth/auth.service.js` and the repository `create`: pass the field through.
|
|
84
|
+
4. The database files: see "Adding a user field" in the Database section above.
|
|
85
|
+
5. `src/docs/openapi.registry.js`: add the field to `PublicUser` so the docs stay correct.
|
|
86
|
+
6. Add a test in `tests/user.test.js`.
|
|
87
|
+
|
|
88
|
+
## Docker
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
cp .env.example .env
|
|
92
|
+
# Docker runs in production mode, which refuses the example secrets.
|
|
93
|
+
# In .env, replace the existing JWT_ACCESS_SECRET= and JWT_REFRESH_SECRET= values
|
|
94
|
+
# with two different outputs of:
|
|
95
|
+
openssl rand -base64 48
|
|
96
|
+
npm run docker:up # build and start the app and the database
|
|
97
|
+
npm run docker:down # stop them
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
The app is then on <http://localhost:3000>. The container runs as the non-root `node` user, starts in production mode (so `/api-docs` is off) and has a health check on `/health`. If port 3000 is taken, run `PORT=3001 npm run docker:up`: this changes only the host port, the app listens on 3000 inside the container. For the database port, see the Database section above.
|
|
101
|
+
|
|
102
|
+
The GitHub Actions workflow in `.github/workflows/ci.yml` lints, checks formatting, tests and builds the image on every push. It needs `package-lock.json` committed. It does not push the image anywhere; to publish one, add a `docker/login-action` step and set `push: true` in `docker/build-push-action`.
|
|
103
|
+
|
|
104
|
+
## Notes
|
|
105
|
+
|
|
106
|
+
- Logout revokes the refresh token, but an access token already issued stays valid until it expires (`JWT_ACCESS_EXPIRES_IN`, 15 minutes by default). That is the trade-off of stateless access tokens. Keep them short.
|
|
107
|
+
- Serialize refresh calls in your frontend; parallel refreshes with the same cookie are treated as token reuse and log the user out.
|
|
108
|
+
- Node.js 22.18 or newer is required.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# {{projectName}} environment. Copy to .env and adjust.
|
|
2
|
+
NODE_ENV=development
|
|
3
|
+
PORT=3000
|
|
4
|
+
LOG_LEVEL=info
|
|
5
|
+
CORS_ORIGIN=http://localhost:5173
|
|
6
|
+
# Behind one reverse proxy or a PaaS (Render, Fly, Heroku...) set 1, so rate limits see the client IP.
|
|
7
|
+
# Also accepts true/false, a hop count, or names/CIDRs such as loopback,10.0.0.0/8. Unset: off.
|
|
8
|
+
# TRUST_PROXY=1
|
|
9
|
+
|
|
10
|
+
# JWT secrets must be at least 32 characters. Generate with: openssl rand -hex 32
|
|
11
|
+
JWT_ACCESS_SECRET=change-me-access-secret-at-least-32-chars
|
|
12
|
+
JWT_REFRESH_SECRET=change-me-refresh-secret-at-least-32-chars
|
|
13
|
+
JWT_ACCESS_EXPIRES_IN=15m
|
|
14
|
+
JWT_REFRESH_EXPIRES_IN=7d
|
|
15
|
+
|
|
16
|
+
# Rate limit for auth endpoints (requests per window)
|
|
17
|
+
AUTH_RATE_LIMIT_MAX=10
|
|
18
|
+
|
|
19
|
+
# Optional admin seed
|
|
20
|
+
ADMIN_NAME=Admin
|
|
21
|
+
ADMIN_EMAIL=admin@example.com
|
|
22
|
+
ADMIN_PASSWORD=ChangeMe123!
|
|
23
|
+
|
|
24
|
+
# Swagger UI at /api-docs; disabled in production by default
|
|
25
|
+
# API_DOCS_ENABLED=true
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
npx lint-staged
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{ "singleQuote": true, "semi": true, "trailingComma": "all", "printWidth": 100 }
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import js from '@eslint/js';
|
|
2
|
+
import globals from 'globals';
|
|
3
|
+
import prettier from 'eslint-config-prettier';
|
|
4
|
+
|
|
5
|
+
export default [
|
|
6
|
+
{
|
|
7
|
+
ignores: ['node_modules', 'coverage', 'prisma/migrations', 'src/generated'],
|
|
8
|
+
},
|
|
9
|
+
js.configs.recommended,
|
|
10
|
+
{
|
|
11
|
+
languageOptions: {
|
|
12
|
+
ecmaVersion: 'latest',
|
|
13
|
+
sourceType: 'module',
|
|
14
|
+
globals: globals.node,
|
|
15
|
+
},
|
|
16
|
+
rules: {
|
|
17
|
+
'no-unused-vars': ['error', { argsIgnorePattern: '^_', ignoreRestSiblings: true }],
|
|
18
|
+
'prefer-const': 'error',
|
|
19
|
+
eqeqeq: 'error',
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
prettier,
|
|
23
|
+
];
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "authkit-api-template",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"engines": {
|
|
7
|
+
"node": ">=22.18"
|
|
8
|
+
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"dev": "node --watch --env-file=.env src/server.js",
|
|
11
|
+
"start": "node src/server.js",
|
|
12
|
+
"seed:admin": "node --env-file=.env scripts/seed-admin.js",
|
|
13
|
+
"test": "vitest run",
|
|
14
|
+
"test:watch": "vitest",
|
|
15
|
+
"test:coverage": "vitest run --coverage",
|
|
16
|
+
"lint": "eslint .",
|
|
17
|
+
"lint:fix": "eslint . --fix",
|
|
18
|
+
"format": "prettier --write .",
|
|
19
|
+
"format:check": "prettier --check .",
|
|
20
|
+
"prepare": "husky || true",
|
|
21
|
+
"docs:postman": "node --env-file-if-exists=.env scripts/generate-postman.js",
|
|
22
|
+
"docker:up": "docker compose up -d --build",
|
|
23
|
+
"docker:down": "docker compose down"
|
|
24
|
+
},
|
|
25
|
+
"lint-staged": {
|
|
26
|
+
"*.js": [
|
|
27
|
+
"eslint --fix",
|
|
28
|
+
"prettier --write"
|
|
29
|
+
],
|
|
30
|
+
"*.{json,md,yml}": [
|
|
31
|
+
"prettier --write"
|
|
32
|
+
]
|
|
33
|
+
},
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"@asteasolutions/zod-to-openapi": "^9.1.0",
|
|
36
|
+
"argon2": "^0.45.1",
|
|
37
|
+
"cookie-parser": "^1.4.7",
|
|
38
|
+
"cors": "^2.8.6",
|
|
39
|
+
"express": "^5.3.0",
|
|
40
|
+
"express-rate-limit": "^8.7.2",
|
|
41
|
+
"helmet": "^8.3.0",
|
|
42
|
+
"jsonwebtoken": "^9.0.3",
|
|
43
|
+
"pino": "^10.4.0",
|
|
44
|
+
"pino-http": "^11.0.0",
|
|
45
|
+
"swagger-ui-express": "^5.0.1",
|
|
46
|
+
"zod": "^4.6.7"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@eslint/js": "^10.0.1",
|
|
50
|
+
"@vitest/coverage-v8": "^5.0.5",
|
|
51
|
+
"eslint": "^10.13.0",
|
|
52
|
+
"eslint-config-prettier": "^10.1.8",
|
|
53
|
+
"globals": "^17.13.0",
|
|
54
|
+
"husky": "^9.1.7",
|
|
55
|
+
"lint-staged": "^17.6.0",
|
|
56
|
+
"openapi-to-postmanv2": "^6.4.2",
|
|
57
|
+
"pino-pretty": "^13.2.0",
|
|
58
|
+
"prettier": "^3.9.10",
|
|
59
|
+
"supertest": "^7.3.1",
|
|
60
|
+
"vitest": "^5.0.5"
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import Converter from 'openapi-to-postmanv2';
|
|
4
|
+
import { buildOpenApiDocument } from '../src/docs/openapi.js';
|
|
5
|
+
|
|
6
|
+
const BASE_URL = 'http://localhost:3000/api/v1';
|
|
7
|
+
const TOKEN_SCRIPT = [
|
|
8
|
+
'const json = pm.response.json();',
|
|
9
|
+
"if (json?.data?.accessToken) pm.collectionVariables.set('accessToken', json.data.accessToken);",
|
|
10
|
+
];
|
|
11
|
+
const PUBLIC_PATHS = new Set(['register', 'login', 'refresh', 'logout']);
|
|
12
|
+
const TOKEN_PATHS = new Set(['login', 'refresh']);
|
|
13
|
+
|
|
14
|
+
function convert(document) {
|
|
15
|
+
return new Promise((resolve, reject) => {
|
|
16
|
+
Converter.convert({ type: 'json', data: document }, {}, (err, result) => {
|
|
17
|
+
if (err) return reject(err);
|
|
18
|
+
if (!result.result) return reject(new Error(result.reason));
|
|
19
|
+
resolve(result.output[0].data);
|
|
20
|
+
});
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function* walk(items) {
|
|
25
|
+
for (const item of items ?? []) {
|
|
26
|
+
if (item.request) yield item;
|
|
27
|
+
yield* walk(item.item);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function lastSegment(item) {
|
|
32
|
+
const path = item.request.url?.path ?? [];
|
|
33
|
+
return path[path.length - 1];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function buildPostmanCollection() {
|
|
37
|
+
const collection = await convert(buildOpenApiDocument());
|
|
38
|
+
|
|
39
|
+
collection.variable = [
|
|
40
|
+
...(collection.variable ?? []).filter((v) => v.key !== 'baseUrl'),
|
|
41
|
+
{ key: 'baseUrl', value: BASE_URL, type: 'string' },
|
|
42
|
+
{ key: 'accessToken', value: '', type: 'string' },
|
|
43
|
+
];
|
|
44
|
+
collection.auth = {
|
|
45
|
+
type: 'bearer',
|
|
46
|
+
bearer: [{ key: 'token', value: '{{accessToken}}', type: 'string' }],
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
for (const item of walk(collection.item)) {
|
|
50
|
+
const name = lastSegment(item);
|
|
51
|
+
// Secured requests inherit the collection bearer auth. Public ones send no token.
|
|
52
|
+
if (PUBLIC_PATHS.has(name)) item.request.auth = { type: 'noauth' };
|
|
53
|
+
else delete item.request.auth;
|
|
54
|
+
if (TOKEN_PATHS.has(name)) {
|
|
55
|
+
item.event = [
|
|
56
|
+
...(item.event ?? []),
|
|
57
|
+
{ listen: 'test', script: { type: 'text/javascript', exec: TOKEN_SCRIPT } },
|
|
58
|
+
];
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return collection;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
65
|
+
const outDir = new URL('../postman/', import.meta.url);
|
|
66
|
+
const collection = await buildPostmanCollection();
|
|
67
|
+
mkdirSync(outDir, { recursive: true });
|
|
68
|
+
writeFileSync(new URL('collection.json', outDir), `${JSON.stringify(collection, null, 2)}\n`);
|
|
69
|
+
console.log('Wrote postman/collection.json (import it into Postman).');
|
|
70
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { pathToFileURL } from 'node:url';
|
|
2
|
+
import { env } from '../src/config/env.js';
|
|
3
|
+
import { logger } from '../src/config/logger.js';
|
|
4
|
+
import { EXAMPLE_ADMIN_PASSWORD } from '../src/constants/examples.js';
|
|
5
|
+
import { ROLES } from '../src/constants/roles.js';
|
|
6
|
+
import { connectDatabase, disconnectDatabase } from '../src/database/connection.js';
|
|
7
|
+
import { registerSchema } from '../src/modules/auth/auth.validation.js';
|
|
8
|
+
import * as userRepository from '../src/modules/user/user.repository.js';
|
|
9
|
+
import { hashPassword } from '../src/utils/password.js';
|
|
10
|
+
|
|
11
|
+
// Creates the admin, or promotes the existing user with that email. The password
|
|
12
|
+
// of an existing user is never changed.
|
|
13
|
+
export async function seedAdmin({ name, email, password }) {
|
|
14
|
+
// Everyone can read .env.example, so an admin with that password is an open door.
|
|
15
|
+
if (password === EXAMPLE_ADMIN_PASSWORD) {
|
|
16
|
+
throw new Error('ADMIN_PASSWORD still has the example value; set a real password in .env');
|
|
17
|
+
}
|
|
18
|
+
const existing = await userRepository.findByEmail(email);
|
|
19
|
+
if (!existing) {
|
|
20
|
+
const user = await userRepository.create({
|
|
21
|
+
name,
|
|
22
|
+
email,
|
|
23
|
+
password: await hashPassword(password),
|
|
24
|
+
role: ROLES.ADMIN,
|
|
25
|
+
});
|
|
26
|
+
return { action: 'created', user };
|
|
27
|
+
}
|
|
28
|
+
if (existing.role === ROLES.ADMIN) return { action: 'unchanged', user: existing };
|
|
29
|
+
const user = await userRepository.updateRole(existing.id, ROLES.ADMIN);
|
|
30
|
+
return { action: 'promoted', user };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function main() {
|
|
34
|
+
const parsed = registerSchema.shape.body.safeParse({
|
|
35
|
+
name: env.ADMIN_NAME,
|
|
36
|
+
email: env.ADMIN_EMAIL,
|
|
37
|
+
password: env.ADMIN_PASSWORD,
|
|
38
|
+
});
|
|
39
|
+
if (!parsed.success) {
|
|
40
|
+
for (const issue of parsed.error.issues) {
|
|
41
|
+
logger.error(`${issue.path.join('.')}: ${issue.message}`);
|
|
42
|
+
}
|
|
43
|
+
process.exit(1);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
await connectDatabase();
|
|
47
|
+
try {
|
|
48
|
+
const { action, user } = await seedAdmin(parsed.data);
|
|
49
|
+
logger.info(`Admin ${action}: ${user.email}`);
|
|
50
|
+
} finally {
|
|
51
|
+
await disconnectDatabase();
|
|
52
|
+
}
|
|
53
|
+
process.exit(0);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
57
|
+
main().catch((err) => {
|
|
58
|
+
logger.error({ err }, `Seeding admin failed: ${err.message}`);
|
|
59
|
+
process.exit(1);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import cookieParser from 'cookie-parser';
|
|
3
|
+
import cors from 'cors';
|
|
4
|
+
import express from 'express';
|
|
5
|
+
import helmet from 'helmet';
|
|
6
|
+
import { pinoHttp } from 'pino-http';
|
|
7
|
+
import { env } from './config/env.js';
|
|
8
|
+
import { logger } from './config/logger.js';
|
|
9
|
+
import { errorHandler } from './middlewares/errorHandler.js';
|
|
10
|
+
import { notFound } from './middlewares/notFound.js';
|
|
11
|
+
import { docsRouter } from './routes/docs.routes.js';
|
|
12
|
+
import { healthRouter } from './routes/health.routes.js';
|
|
13
|
+
import { apiRouter } from './routes/index.js';
|
|
14
|
+
|
|
15
|
+
export function createApp() {
|
|
16
|
+
const app = express();
|
|
17
|
+
// Behind a reverse proxy or PaaS, req.ip (and so the rate limiter) needs this.
|
|
18
|
+
if (env.TRUST_PROXY !== undefined) app.set('trust proxy', env.TRUST_PROXY);
|
|
19
|
+
|
|
20
|
+
// Before the global helmet: Swagger UI needs a relaxed CSP, the API keeps the strict one.
|
|
21
|
+
if (env.API_DOCS_ENABLED) app.use(docsRouter);
|
|
22
|
+
|
|
23
|
+
app.use(helmet());
|
|
24
|
+
app.use(cors({ origin: env.CORS_ORIGIN, credentials: true }));
|
|
25
|
+
// Before the body parser, so parse errors are logged with a request id.
|
|
26
|
+
app.use(
|
|
27
|
+
pinoHttp({
|
|
28
|
+
logger,
|
|
29
|
+
genReqId: (req, res) => {
|
|
30
|
+
const id = randomUUID();
|
|
31
|
+
res.setHeader('x-request-id', id);
|
|
32
|
+
return id;
|
|
33
|
+
},
|
|
34
|
+
}),
|
|
35
|
+
);
|
|
36
|
+
app.use(express.json({ limit: '10kb' }));
|
|
37
|
+
app.use(cookieParser());
|
|
38
|
+
|
|
39
|
+
app.use('/health', healthRouter);
|
|
40
|
+
app.use('/api/v1', apiRouter);
|
|
41
|
+
|
|
42
|
+
app.use(notFound);
|
|
43
|
+
app.use(errorHandler);
|
|
44
|
+
|
|
45
|
+
return app;
|
|
46
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { envSchema } from './env.schema.js';
|
|
2
|
+
|
|
3
|
+
function loadEnv() {
|
|
4
|
+
const result = envSchema.safeParse(process.env);
|
|
5
|
+
if (!result.success) {
|
|
6
|
+
console.error('Invalid environment variables:');
|
|
7
|
+
for (const issue of result.error.issues) {
|
|
8
|
+
console.error(` ${issue.path.join('.')}: ${issue.message}`);
|
|
9
|
+
}
|
|
10
|
+
process.exit(1);
|
|
11
|
+
}
|
|
12
|
+
return Object.freeze(result.data);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const env = loadEnv();
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { EXAMPLE_SECRET_PREFIX } from '../constants/examples.js';
|
|
3
|
+
import { databaseEnvSchema } from '../database/env.schema.js';
|
|
4
|
+
|
|
5
|
+
const LOG_LEVELS = ['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent'];
|
|
6
|
+
// jsonwebtoken (ms) time spans such as 900, 15m or 7d.
|
|
7
|
+
const TIME_SPAN = /^\d+(ms|s|m|h|d|w|y)?$/;
|
|
8
|
+
const timeSpan = (fallback) =>
|
|
9
|
+
z
|
|
10
|
+
.string()
|
|
11
|
+
.regex(TIME_SPAN, 'must be a number with an optional unit (ms, s, m, h, d, w, y), e.g. 15m')
|
|
12
|
+
.default(fallback);
|
|
13
|
+
|
|
14
|
+
// Express "trust proxy": true/false, a hop count, or names/CIDRs such as "loopback" or "10.0.0.0/8".
|
|
15
|
+
// An empty `TRUST_PROXY=` counts as unset.
|
|
16
|
+
const trustProxy = z.preprocess(
|
|
17
|
+
(value) => (typeof value === 'string' && value.trim() === '' ? undefined : value),
|
|
18
|
+
z
|
|
19
|
+
.string()
|
|
20
|
+
.trim()
|
|
21
|
+
.transform((value) => {
|
|
22
|
+
if (value === 'true') return true;
|
|
23
|
+
if (value === 'false') return false;
|
|
24
|
+
if (/^\d+$/.test(value)) return Number(value);
|
|
25
|
+
return value;
|
|
26
|
+
})
|
|
27
|
+
.optional(),
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
const baseEnvSchema = z.object({
|
|
31
|
+
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
|
|
32
|
+
PORT: z.coerce.number().int().positive().default(3000),
|
|
33
|
+
LOG_LEVEL: z.enum(LOG_LEVELS).default('info'),
|
|
34
|
+
CORS_ORIGIN: z
|
|
35
|
+
.string()
|
|
36
|
+
.default('http://localhost:5173')
|
|
37
|
+
.transform((value) =>
|
|
38
|
+
value
|
|
39
|
+
.split(',')
|
|
40
|
+
.map((origin) => origin.trim())
|
|
41
|
+
.filter(Boolean),
|
|
42
|
+
),
|
|
43
|
+
TRUST_PROXY: trustProxy,
|
|
44
|
+
JWT_ACCESS_SECRET: z.string().min(32),
|
|
45
|
+
JWT_REFRESH_SECRET: z.string().min(32),
|
|
46
|
+
JWT_ACCESS_EXPIRES_IN: timeSpan('15m'),
|
|
47
|
+
JWT_REFRESH_EXPIRES_IN: timeSpan('7d'),
|
|
48
|
+
AUTH_RATE_LIMIT_MAX: z.coerce.number().int().positive().default(10),
|
|
49
|
+
API_DOCS_ENABLED: z.enum(['true', 'false']).optional(),
|
|
50
|
+
ADMIN_NAME: z.string().optional(),
|
|
51
|
+
ADMIN_EMAIL: z.string().optional(),
|
|
52
|
+
ADMIN_PASSWORD: z.string().optional(),
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
function checkSecrets(value, ctx) {
|
|
56
|
+
if (value.NODE_ENV === 'production') {
|
|
57
|
+
for (const key of ['JWT_ACCESS_SECRET', 'JWT_REFRESH_SECRET']) {
|
|
58
|
+
if (value[key].trim().toLowerCase().startsWith(EXAMPLE_SECRET_PREFIX)) {
|
|
59
|
+
ctx.addIssue({
|
|
60
|
+
code: 'custom',
|
|
61
|
+
path: [key],
|
|
62
|
+
message: `${key} still has the example value; set a real secret (e.g. \`openssl rand -base64 48\`)`,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (value.JWT_ACCESS_SECRET === value.JWT_REFRESH_SECRET) {
|
|
68
|
+
ctx.addIssue({
|
|
69
|
+
code: 'custom',
|
|
70
|
+
path: ['JWT_REFRESH_SECRET'],
|
|
71
|
+
message: 'JWT_REFRESH_SECRET must differ from JWT_ACCESS_SECRET',
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export const envSchema = baseEnvSchema
|
|
77
|
+
.extend(databaseEnvSchema.shape)
|
|
78
|
+
.superRefine(checkSecrets)
|
|
79
|
+
.transform((value) => ({
|
|
80
|
+
...value,
|
|
81
|
+
// Docs are on by default, except in production.
|
|
82
|
+
API_DOCS_ENABLED: value.API_DOCS_ENABLED
|
|
83
|
+
? value.API_DOCS_ENABLED === 'true'
|
|
84
|
+
: value.NODE_ENV !== 'production',
|
|
85
|
+
}));
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import pino from 'pino';
|
|
2
|
+
import { env } from './env.js';
|
|
3
|
+
|
|
4
|
+
export const logger = pino({
|
|
5
|
+
level: env.NODE_ENV === 'test' ? 'silent' : env.LOG_LEVEL,
|
|
6
|
+
redact: {
|
|
7
|
+
paths: [
|
|
8
|
+
'req.headers.authorization',
|
|
9
|
+
'req.headers.cookie',
|
|
10
|
+
'res.headers["set-cookie"]',
|
|
11
|
+
'*.password',
|
|
12
|
+
'*.token',
|
|
13
|
+
'*.refreshToken',
|
|
14
|
+
],
|
|
15
|
+
censor: '[REDACTED]',
|
|
16
|
+
},
|
|
17
|
+
...(env.NODE_ENV === 'development' && {
|
|
18
|
+
transport: { target: 'pino-pretty', options: { colorize: true } },
|
|
19
|
+
}),
|
|
20
|
+
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Every field limit lives here. Zod schemas and the database models import it.
|
|
2
|
+
export const USER_RULES = Object.freeze({
|
|
3
|
+
NAME: Object.freeze({ MIN: 2, MAX: 50 }),
|
|
4
|
+
EMAIL: Object.freeze({ MAX: 254 }),
|
|
5
|
+
PASSWORD: Object.freeze({
|
|
6
|
+
MIN: 8,
|
|
7
|
+
MAX: 128,
|
|
8
|
+
PATTERN: /(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/,
|
|
9
|
+
}),
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
export const PAGINATION = Object.freeze({
|
|
13
|
+
DEFAULT_PAGE: 1,
|
|
14
|
+
DEFAULT_LIMIT: 20,
|
|
15
|
+
MAX_LIMIT: 100,
|
|
16
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { OpenApiGeneratorV31 } from '@asteasolutions/zod-to-openapi';
|
|
3
|
+
import { registerAuthPaths } from './paths/auth.paths.js';
|
|
4
|
+
import { registerUserPaths } from './paths/user.paths.js';
|
|
5
|
+
import { registry } from './openapi.registry.js';
|
|
6
|
+
|
|
7
|
+
let cached;
|
|
8
|
+
|
|
9
|
+
export function buildOpenApiDocument() {
|
|
10
|
+
if (cached) return cached;
|
|
11
|
+
|
|
12
|
+
const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
|
|
13
|
+
registerAuthPaths(registry);
|
|
14
|
+
registerUserPaths(registry);
|
|
15
|
+
|
|
16
|
+
cached = new OpenApiGeneratorV31(registry.definitions).generateDocument({
|
|
17
|
+
openapi: '3.1.0',
|
|
18
|
+
info: {
|
|
19
|
+
title: pkg.name,
|
|
20
|
+
version: pkg.version,
|
|
21
|
+
...(pkg.description && { description: pkg.description }),
|
|
22
|
+
},
|
|
23
|
+
servers: [{ url: '/api/v1' }],
|
|
24
|
+
});
|
|
25
|
+
return cached;
|
|
26
|
+
}
|