authkit-api 0.0.0-stage → 1.1.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 (210) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/LICENSE +21 -0
  3. package/README.md +125 -2
  4. package/bin/cli.js +8 -0
  5. package/package.json +76 -4
  6. package/src/constants.js +29 -0
  7. package/src/generator.js +142 -0
  8. package/src/index.js +99 -0
  9. package/src/prompts.js +59 -0
  10. package/src/utils/fs.js +36 -0
  11. package/src/utils/logger.js +8 -0
  12. package/src/utils/packageJson.js +16 -0
  13. package/src/utils/validateProjectName.js +19 -0
  14. package/templates/base/Dockerfile +22 -0
  15. package/templates/base/README.md +108 -0
  16. package/templates/base/_dockerignore +16 -0
  17. package/templates/base/_env.example +25 -0
  18. package/templates/base/_gitignore +5 -0
  19. package/templates/base/_husky/pre-commit +1 -0
  20. package/templates/base/_prettierignore +5 -0
  21. package/templates/base/_prettierrc +1 -0
  22. package/templates/base/package.json +62 -0
  23. package/templates/base/scripts/docker-entrypoint.sh +9 -0
  24. package/templates/base/scripts/generate-postman.ts +102 -0
  25. package/templates/base/scripts/seed-admin.ts +62 -0
  26. package/templates/base/src/app.ts +46 -0
  27. package/templates/base/src/config/env.schema.ts +85 -0
  28. package/templates/base/src/config/env.ts +15 -0
  29. package/templates/base/src/config/logger.ts +20 -0
  30. package/templates/base/src/constants/examples.ts +3 -0
  31. package/templates/base/src/constants/roles.ts +4 -0
  32. package/templates/base/src/constants/user.rules.ts +16 -0
  33. package/templates/base/src/docs/openapi.registry.ts +90 -0
  34. package/templates/base/src/docs/openapi.ts +36 -0
  35. package/templates/base/src/docs/paths/auth.paths.ts +88 -0
  36. package/templates/base/src/docs/paths/user.paths.ts +88 -0
  37. package/templates/base/src/middlewares/authenticate.ts +20 -0
  38. package/templates/base/src/middlewares/authorize.ts +13 -0
  39. package/templates/base/src/middlewares/errorHandler.ts +52 -0
  40. package/templates/base/src/middlewares/notFound.ts +6 -0
  41. package/templates/base/src/middlewares/rateLimiter.ts +20 -0
  42. package/templates/base/src/middlewares/validate.ts +39 -0
  43. package/templates/base/src/modules/auth/auth.controller.ts +45 -0
  44. package/templates/base/src/modules/auth/auth.cookie.ts +22 -0
  45. package/templates/base/src/modules/auth/auth.routes.ts +12 -0
  46. package/templates/base/src/modules/auth/auth.service.ts +81 -0
  47. package/templates/base/src/modules/auth/auth.validation.ts +44 -0
  48. package/templates/base/src/modules/user/user.controller.ts +24 -0
  49. package/templates/base/src/modules/user/user.routes.ts +22 -0
  50. package/templates/base/src/modules/user/user.service.ts +57 -0
  51. package/templates/base/src/modules/user/user.validation.ts +27 -0
  52. package/templates/base/src/routes/docs.routes.ts +16 -0
  53. package/templates/base/src/routes/health.routes.ts +17 -0
  54. package/templates/base/src/routes/index.ts +13 -0
  55. package/templates/base/src/server.ts +51 -0
  56. package/templates/base/src/types/express.d.ts +14 -0
  57. package/templates/base/src/utils/ApiError.ts +35 -0
  58. package/templates/base/src/utils/apiResponse.ts +24 -0
  59. package/templates/base/src/utils/password.ts +14 -0
  60. package/templates/base/src/utils/token.ts +60 -0
  61. package/templates/base/src/utils/zod.ts +5 -0
  62. package/templates/base/tests/app.test.ts +67 -0
  63. package/templates/base/tests/auth.test.ts +194 -0
  64. package/templates/base/tests/authenticate.test.ts +61 -0
  65. package/templates/base/tests/docs.test.ts +127 -0
  66. package/templates/base/tests/env.test.ts +96 -0
  67. package/templates/base/tests/health.test.ts +21 -0
  68. package/templates/base/tests/helpers/auth.helper.ts +49 -0
  69. package/templates/base/tests/password.test.ts +18 -0
  70. package/templates/base/tests/postman.test.ts +32 -0
  71. package/templates/base/tests/rateLimiter.test.ts +27 -0
  72. package/templates/base/tests/seedAdmin.test.ts +42 -0
  73. package/templates/base/tests/token.test.ts +69 -0
  74. package/templates/base/tests/trustProxy.test.ts +24 -0
  75. package/templates/base/tests/user.repository.test.ts +211 -0
  76. package/templates/base/tests/user.test.ts +145 -0
  77. package/templates/base/tests/validate.test.ts +42 -0
  78. package/templates/base/tests/validation.test.ts +62 -0
  79. package/templates/base/vitest.config.ts +16 -0
  80. package/templates/databases/mongodb/README.part.md +23 -0
  81. package/templates/databases/mongodb/_github/workflows/ci.yml +29 -0
  82. package/templates/databases/mongodb/docker-compose.yml +30 -0
  83. package/templates/databases/mongodb/env.part +2 -0
  84. package/templates/databases/mongodb/package.part.json +4 -0
  85. package/templates/databases/mongodb/src/database/connection.ts +46 -0
  86. package/templates/databases/mongodb/src/database/env.schema.ts +3 -0
  87. package/templates/databases/mongodb/src/database/id.schema.ts +3 -0
  88. package/templates/databases/mongodb/src/database/models/refreshToken.model.ts +24 -0
  89. package/templates/databases/mongodb/src/database/models/user.model.ts +52 -0
  90. package/templates/databases/mongodb/src/modules/user/user.repository.ts +91 -0
  91. package/templates/databases/mongodb/tests/globalSetup.ts +13 -0
  92. package/templates/databases/mongodb/tests/setup.ts +17 -0
  93. package/templates/databases/postgres/README.part.md +31 -0
  94. package/templates/databases/postgres/_github/workflows/ci.yml +46 -0
  95. package/templates/databases/postgres/docker-compose.yml +34 -0
  96. package/templates/databases/postgres/env.part +2 -0
  97. package/templates/databases/postgres/package.part.json +15 -0
  98. package/templates/databases/postgres/prisma/migrations/20261030073256_init/migration.sql +39 -0
  99. package/templates/databases/postgres/prisma/migrations/migration_lock.toml +3 -0
  100. package/templates/databases/postgres/prisma/schema.prisma +39 -0
  101. package/templates/databases/postgres/prisma.config.ts +14 -0
  102. package/templates/databases/postgres/src/database/connection.ts +72 -0
  103. package/templates/databases/postgres/src/database/env.schema.ts +3 -0
  104. package/templates/databases/postgres/src/database/id.schema.ts +3 -0
  105. package/templates/databases/postgres/src/database/prisma.ts +9 -0
  106. package/templates/databases/postgres/src/modules/user/user.repository.ts +111 -0
  107. package/templates/databases/postgres/tests/connection.test.ts +19 -0
  108. package/templates/databases/postgres/tests/globalSetup.ts +66 -0
  109. package/templates/databases/postgres/tests/prismaSchema.test.ts +27 -0
  110. package/templates/databases/postgres/tests/setup.ts +15 -0
  111. package/templates/languages/js/eslint.config.js +23 -0
  112. package/templates/languages/ts/eslint.config.js +30 -0
  113. package/templates/languages/ts/package.part.json +21 -0
  114. package/templates/languages/ts/tsconfig.json +15 -0
  115. package/templates-js/base/Dockerfile +22 -0
  116. package/templates-js/base/README.md +108 -0
  117. package/templates-js/base/_dockerignore +16 -0
  118. package/templates-js/base/_env.example +25 -0
  119. package/templates-js/base/_gitignore +5 -0
  120. package/templates-js/base/_husky/pre-commit +1 -0
  121. package/templates-js/base/_prettierignore +5 -0
  122. package/templates-js/base/_prettierrc +1 -0
  123. package/templates-js/base/package.json +62 -0
  124. package/templates-js/base/scripts/docker-entrypoint.sh +9 -0
  125. package/templates-js/base/scripts/generate-postman.js +70 -0
  126. package/templates-js/base/scripts/seed-admin.js +61 -0
  127. package/templates-js/base/src/app.js +46 -0
  128. package/templates-js/base/src/config/env.js +15 -0
  129. package/templates-js/base/src/config/env.schema.js +85 -0
  130. package/templates-js/base/src/config/logger.js +20 -0
  131. package/templates-js/base/src/constants/examples.js +3 -0
  132. package/templates-js/base/src/constants/roles.js +2 -0
  133. package/templates-js/base/src/constants/user.rules.js +16 -0
  134. package/templates-js/base/src/docs/openapi.js +26 -0
  135. package/templates-js/base/src/docs/openapi.registry.js +81 -0
  136. package/templates-js/base/src/docs/paths/auth.paths.js +87 -0
  137. package/templates-js/base/src/docs/paths/user.paths.js +87 -0
  138. package/templates-js/base/src/middlewares/authenticate.js +19 -0
  139. package/templates-js/base/src/middlewares/authorize.js +11 -0
  140. package/templates-js/base/src/middlewares/errorHandler.js +35 -0
  141. package/templates-js/base/src/middlewares/notFound.js +5 -0
  142. package/templates-js/base/src/middlewares/rateLimiter.js +20 -0
  143. package/templates-js/base/src/middlewares/validate.js +31 -0
  144. package/templates-js/base/src/modules/auth/auth.controller.js +40 -0
  145. package/templates-js/base/src/modules/auth/auth.cookie.js +21 -0
  146. package/templates-js/base/src/modules/auth/auth.routes.js +12 -0
  147. package/templates-js/base/src/modules/auth/auth.service.js +79 -0
  148. package/templates-js/base/src/modules/auth/auth.validation.js +41 -0
  149. package/templates-js/base/src/modules/user/user.controller.js +21 -0
  150. package/templates-js/base/src/modules/user/user.routes.js +22 -0
  151. package/templates-js/base/src/modules/user/user.service.js +19 -0
  152. package/templates-js/base/src/modules/user/user.validation.js +24 -0
  153. package/templates-js/base/src/routes/docs.routes.js +16 -0
  154. package/templates-js/base/src/routes/health.routes.js +17 -0
  155. package/templates-js/base/src/routes/index.js +13 -0
  156. package/templates-js/base/src/server.js +50 -0
  157. package/templates-js/base/src/utils/ApiError.js +32 -0
  158. package/templates-js/base/src/utils/apiResponse.js +8 -0
  159. package/templates-js/base/src/utils/password.js +14 -0
  160. package/templates-js/base/src/utils/token.js +46 -0
  161. package/templates-js/base/src/utils/zod.js +5 -0
  162. package/templates-js/base/tests/app.test.js +67 -0
  163. package/templates-js/base/tests/auth.test.js +185 -0
  164. package/templates-js/base/tests/authenticate.test.js +61 -0
  165. package/templates-js/base/tests/docs.test.js +115 -0
  166. package/templates-js/base/tests/env.test.js +94 -0
  167. package/templates-js/base/tests/health.test.js +21 -0
  168. package/templates-js/base/tests/helpers/auth.helper.js +41 -0
  169. package/templates-js/base/tests/password.test.js +18 -0
  170. package/templates-js/base/tests/postman.test.js +31 -0
  171. package/templates-js/base/tests/rateLimiter.test.js +27 -0
  172. package/templates-js/base/tests/seedAdmin.test.js +42 -0
  173. package/templates-js/base/tests/token.test.js +69 -0
  174. package/templates-js/base/tests/trustProxy.test.js +24 -0
  175. package/templates-js/base/tests/user.repository.test.js +210 -0
  176. package/templates-js/base/tests/user.test.js +144 -0
  177. package/templates-js/base/tests/validate.test.js +35 -0
  178. package/templates-js/base/tests/validation.test.js +61 -0
  179. package/templates-js/base/vitest.config.js +16 -0
  180. package/templates-js/databases/mongodb/README.part.md +23 -0
  181. package/templates-js/databases/mongodb/_github/workflows/ci.yml +29 -0
  182. package/templates-js/databases/mongodb/docker-compose.yml +30 -0
  183. package/templates-js/databases/mongodb/env.part +2 -0
  184. package/templates-js/databases/mongodb/package.part.json +4 -0
  185. package/templates-js/databases/mongodb/src/database/connection.js +39 -0
  186. package/templates-js/databases/mongodb/src/database/env.schema.js +3 -0
  187. package/templates-js/databases/mongodb/src/database/id.schema.js +3 -0
  188. package/templates-js/databases/mongodb/src/database/models/refreshToken.model.js +15 -0
  189. package/templates-js/databases/mongodb/src/database/models/user.model.js +41 -0
  190. package/templates-js/databases/mongodb/src/modules/user/user.repository.js +68 -0
  191. package/templates-js/databases/mongodb/tests/globalSetup.js +13 -0
  192. package/templates-js/databases/mongodb/tests/setup.js +17 -0
  193. package/templates-js/databases/postgres/README.part.md +31 -0
  194. package/templates-js/databases/postgres/_github/workflows/ci.yml +46 -0
  195. package/templates-js/databases/postgres/docker-compose.yml +34 -0
  196. package/templates-js/databases/postgres/env.part +2 -0
  197. package/templates-js/databases/postgres/package.part.json +15 -0
  198. package/templates-js/databases/postgres/prisma/migrations/20261030073256_init/migration.sql +39 -0
  199. package/templates-js/databases/postgres/prisma/migrations/migration_lock.toml +3 -0
  200. package/templates-js/databases/postgres/prisma/schema.prisma +39 -0
  201. package/templates-js/databases/postgres/prisma.config.js +14 -0
  202. package/templates-js/databases/postgres/src/database/connection.js +61 -0
  203. package/templates-js/databases/postgres/src/database/env.schema.js +3 -0
  204. package/templates-js/databases/postgres/src/database/id.schema.js +3 -0
  205. package/templates-js/databases/postgres/src/database/prisma.js +9 -0
  206. package/templates-js/databases/postgres/src/modules/user/user.repository.js +88 -0
  207. package/templates-js/databases/postgres/tests/connection.test.js +17 -0
  208. package/templates-js/databases/postgres/tests/globalSetup.js +60 -0
  209. package/templates-js/databases/postgres/tests/prismaSchema.test.js +27 -0
  210. package/templates-js/databases/postgres/tests/setup.js +15 -0
@@ -0,0 +1,19 @@
1
+ import path from 'node:path';
2
+ import validate from 'validate-npm-package-name';
3
+
4
+ export function validateProjectName(name) {
5
+ const result = validate(name);
6
+ const problems = [...(result.errors ?? []), ...(result.warnings ?? [])];
7
+ const valid = result.validForNewPackages && name !== '.';
8
+ if (name === '.')
9
+ problems.push('name cannot be "." (generating into the current folder is not supported)');
10
+ return { valid, problems };
11
+ }
12
+
13
+ // Validates the last path segment, so targets like `.sandbox/mongo-app` are allowed.
14
+ export function assertValidProjectName(projectName) {
15
+ const { valid, problems } = validateProjectName(path.basename(projectName ?? ''));
16
+ if (!valid) {
17
+ throw new Error(`Invalid project name "${projectName ?? ''}": ${problems.join(', ')}`);
18
+ }
19
+ }
@@ -0,0 +1,22 @@
1
+ # Stage 1: install all dependencies (dev ones are needed for the build step).
2
+ FROM node:24-alpine AS deps
3
+ WORKDIR /app
4
+ COPY package.json package-lock.json ./
5
+ RUN npm ci --ignore-scripts
6
+
7
+ # Stage 2: copy the source, generate the Prisma client (Postgres only), drop dev dependencies.
8
+ FROM deps AS build
9
+ COPY . .
10
+ RUN if [ -f prisma/schema.prisma ]; then npx prisma generate; fi
11
+ RUN npm prune --omit=dev
12
+
13
+ # Stage 3: small runtime image that runs as the non-root "node" user.
14
+ FROM node:24-alpine AS runner
15
+ ENV NODE_ENV=production
16
+ WORKDIR /app
17
+ COPY --from=build --chown=node:node /app ./
18
+ USER node
19
+ EXPOSE 3000
20
+ HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
21
+ CMD wget -qO- http://localhost:3000/health || exit 1
22
+ CMD ["sh", "scripts/docker-entrypoint.sh"]
@@ -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.ts`: add the limits (for example `PHONE: { MAX: 20 }`).
82
+ 2. `src/modules/auth/auth.validation.ts`: add the field to `registerSchema`.
83
+ 3. `src/modules/auth/auth.service.ts` 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.ts`: add the field to `PublicUser` so the docs stay correct.
86
+ 6. Add a test in `tests/user.test.ts`.
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,16 @@
1
+ node_modules
2
+ .git
3
+ .github
4
+ .husky
5
+ .sandbox
6
+ tests
7
+ coverage
8
+ postman
9
+ src/generated
10
+ .env
11
+ .env.*
12
+ !.env.example
13
+ *.log
14
+ Dockerfile
15
+ docker-compose.yml
16
+ README.md
@@ -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,5 @@
1
+ node_modules/
2
+ .env
3
+ coverage/
4
+ src/generated/
5
+ postman/
@@ -0,0 +1 @@
1
+ npx lint-staged
@@ -0,0 +1,5 @@
1
+ node_modules
2
+ coverage
3
+ package-lock.json
4
+ prisma/migrations
5
+ src/generated
@@ -0,0 +1 @@
1
+ { "singleQuote": true, "semi": true, "trailingComma": "all", "printWidth": 100 }
@@ -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.ts",
11
+ "start": "node src/server.ts",
12
+ "seed:admin": "node --env-file=.env scripts/seed-admin.ts",
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.ts",
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,9 @@
1
+ #!/bin/sh
2
+ # Container start: apply database migrations (Postgres only), then run the server.
3
+ set -e
4
+
5
+ if [ -f prisma/schema.prisma ]; then
6
+ npx prisma migrate deploy
7
+ fi
8
+
9
+ exec node src/server.ts
@@ -0,0 +1,102 @@
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.ts';
5
+
6
+ export interface PostmanCollection {
7
+ // The parts of a Postman collection this script reads or changes.
8
+ item: PostmanItem[];
9
+ variable?: PostmanVariable[];
10
+ auth?: PostmanAuth;
11
+ }
12
+
13
+ export interface PostmanVariable {
14
+ key: string;
15
+ value: string;
16
+ type: string;
17
+ }
18
+
19
+ export interface PostmanEvent {
20
+ listen: string;
21
+ script: { type: string; exec: string[] };
22
+ }
23
+
24
+ export interface PostmanAuth {
25
+ type: string;
26
+ bearer?: PostmanVariable[];
27
+ }
28
+
29
+ export interface PostmanItem {
30
+ name: string;
31
+ request?: { url?: { path?: string[] }; auth?: PostmanAuth };
32
+ item?: PostmanItem[];
33
+ event?: PostmanEvent[];
34
+ }
35
+
36
+ type PostmanRequestItem = PostmanItem & { request: NonNullable<PostmanItem['request']> };
37
+
38
+ const BASE_URL = 'http://localhost:3000/api/v1';
39
+ const TOKEN_SCRIPT = [
40
+ 'const json = pm.response.json();',
41
+ "if (json?.data?.accessToken) pm.collectionVariables.set('accessToken', json.data.accessToken);",
42
+ ];
43
+ const PUBLIC_PATHS = new Set(['register', 'login', 'refresh', 'logout']);
44
+ const TOKEN_PATHS = new Set(['login', 'refresh']);
45
+
46
+ function convert(document: object) {
47
+ return new Promise<PostmanCollection>((resolve, reject) => {
48
+ Converter.convert({ type: 'json', data: document }, {}, (err, result) => {
49
+ if (err) return reject(err);
50
+ if (!result!.result) return reject(new Error(result!.reason));
51
+ resolve(result!.output![0].data as PostmanCollection);
52
+ });
53
+ });
54
+ }
55
+
56
+ function* walk(items: PostmanItem[] | undefined): Generator<PostmanRequestItem> {
57
+ for (const item of items ?? []) {
58
+ if (item.request) yield item as PostmanRequestItem;
59
+ yield* walk(item.item);
60
+ }
61
+ }
62
+
63
+ function lastSegment(item: PostmanRequestItem) {
64
+ const path = item.request.url?.path ?? [];
65
+ return path[path.length - 1];
66
+ }
67
+
68
+ export async function buildPostmanCollection() {
69
+ const collection = await convert(buildOpenApiDocument());
70
+
71
+ collection.variable = [
72
+ ...(collection.variable ?? []).filter((v) => v.key !== 'baseUrl'),
73
+ { key: 'baseUrl', value: BASE_URL, type: 'string' },
74
+ { key: 'accessToken', value: '', type: 'string' },
75
+ ];
76
+ collection.auth = {
77
+ type: 'bearer',
78
+ bearer: [{ key: 'token', value: '{{accessToken}}', type: 'string' }],
79
+ };
80
+
81
+ for (const item of walk(collection.item)) {
82
+ const name = lastSegment(item);
83
+ // Secured requests inherit the collection bearer auth. Public ones send no token.
84
+ if (PUBLIC_PATHS.has(name)) item.request.auth = { type: 'noauth' };
85
+ else delete item.request.auth;
86
+ if (TOKEN_PATHS.has(name)) {
87
+ item.event = [
88
+ ...(item.event ?? []),
89
+ { listen: 'test', script: { type: 'text/javascript', exec: TOKEN_SCRIPT } },
90
+ ];
91
+ }
92
+ }
93
+ return collection;
94
+ }
95
+
96
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
97
+ const outDir = new URL('../postman/', import.meta.url);
98
+ const collection = await buildPostmanCollection();
99
+ mkdirSync(outDir, { recursive: true });
100
+ writeFileSync(new URL('collection.json', outDir), `${JSON.stringify(collection, null, 2)}\n`);
101
+ console.log('Wrote postman/collection.json (import it into Postman).');
102
+ }
@@ -0,0 +1,62 @@
1
+ import { pathToFileURL } from 'node:url';
2
+ import { env } from '../src/config/env.ts';
3
+ import { logger } from '../src/config/logger.ts';
4
+ import { EXAMPLE_ADMIN_PASSWORD } from '../src/constants/examples.ts';
5
+ import { ROLES } from '../src/constants/roles.ts';
6
+ import { connectDatabase, disconnectDatabase } from '../src/database/connection.ts';
7
+ import { registerSchema } from '../src/modules/auth/auth.validation.ts';
8
+ import * as userRepository from '../src/modules/user/user.repository.ts';
9
+ import { hashPassword } from '../src/utils/password.ts';
10
+ import type { RegisterInput } from '../src/modules/auth/auth.validation.ts';
11
+
12
+ // Creates the admin, or promotes the existing user with that email. The password
13
+ // of an existing user is never changed.
14
+ export async function seedAdmin({ name, email, password }: RegisterInput['body']) {
15
+ // Everyone can read .env.example, so an admin with that password is an open door.
16
+ if (password === EXAMPLE_ADMIN_PASSWORD) {
17
+ throw new Error('ADMIN_PASSWORD still has the example value; set a real password in .env');
18
+ }
19
+ const existing = await userRepository.findByEmail(email);
20
+ if (!existing) {
21
+ const user = await userRepository.create({
22
+ name,
23
+ email,
24
+ password: await hashPassword(password),
25
+ role: ROLES.ADMIN,
26
+ });
27
+ return { action: 'created', user };
28
+ }
29
+ if (existing.role === ROLES.ADMIN) return { action: 'unchanged', user: existing };
30
+ const user = (await userRepository.updateRole(existing.id, ROLES.ADMIN))!;
31
+ return { action: 'promoted', user };
32
+ }
33
+
34
+ async function main() {
35
+ const parsed = registerSchema.shape.body.safeParse({
36
+ name: env.ADMIN_NAME,
37
+ email: env.ADMIN_EMAIL,
38
+ password: env.ADMIN_PASSWORD,
39
+ });
40
+ if (!parsed.success) {
41
+ for (const issue of parsed.error.issues) {
42
+ logger.error(`${issue.path.join('.')}: ${issue.message}`);
43
+ }
44
+ process.exit(1);
45
+ }
46
+
47
+ await connectDatabase();
48
+ try {
49
+ const { action, user } = await seedAdmin(parsed.data);
50
+ logger.info(`Admin ${action}: ${user.email}`);
51
+ } finally {
52
+ await disconnectDatabase();
53
+ }
54
+ process.exit(0);
55
+ }
56
+
57
+ if (import.meta.url === pathToFileURL(process.argv[1]).href) {
58
+ main().catch((err) => {
59
+ logger.error({ err }, `Seeding admin failed: ${err.message}`);
60
+ process.exit(1);
61
+ });
62
+ }
@@ -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.ts';
8
+ import { logger } from './config/logger.ts';
9
+ import { errorHandler } from './middlewares/errorHandler.ts';
10
+ import { notFound } from './middlewares/notFound.ts';
11
+ import { docsRouter } from './routes/docs.routes.ts';
12
+ import { healthRouter } from './routes/health.routes.ts';
13
+ import { apiRouter } from './routes/index.ts';
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,85 @@
1
+ import { z } from 'zod';
2
+ import { EXAMPLE_SECRET_PREFIX } from '../constants/examples.ts';
3
+ import { databaseEnvSchema } from '../database/env.schema.ts';
4
+
5
+ const LOG_LEVELS = ['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent'] as const;
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: string) =>
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: z.output<typeof baseEnvSchema>, ctx: z.RefinementCtx) {
56
+ if (value.NODE_ENV === 'production') {
57
+ for (const key of ['JWT_ACCESS_SECRET', 'JWT_REFRESH_SECRET'] as const) {
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,15 @@
1
+ import { envSchema } from './env.schema.ts';
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,20 @@
1
+ import pino from 'pino';
2
+ import { env } from './env.ts';
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,3 @@
1
+ // Values shipped in .env.example. They are fine for local development, never for real use.
2
+ export const EXAMPLE_SECRET_PREFIX = 'change-me';
3
+ export const EXAMPLE_ADMIN_PASSWORD = 'ChangeMe123!';
@@ -0,0 +1,4 @@
1
+ export const ROLES = Object.freeze({ USER: 'user', ADMIN: 'admin' });
2
+ export const ROLE_VALUES = Object.values(ROLES);
3
+
4
+ export type Role = (typeof ROLES)[keyof typeof ROLES];
@@ -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
+ });