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
package/CHANGELOG.md ADDED
@@ -0,0 +1,35 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.1.0] - 2026-11-20
9
+
10
+ ### Added
11
+
12
+ - `create-authkit-api` alias package (in `packages/create-authkit-api`) so `npm create authkit-api my-app` works.
13
+ - TypeScript option: `--lang ts` (or pick it at the prompt) generates the same API in strict TypeScript, run directly by Node with no build step. JavaScript stays the default and its output is unchanged.
14
+
15
+ ### Changed
16
+
17
+ - Releases are published automatically from GitHub Actions when a version tag is pushed.
18
+
19
+ ## [1.0.0] - 2026-10-30
20
+
21
+ First public release.
22
+
23
+ ### Added
24
+
25
+ - `npx authkit-api <project-name>` CLI with `--db mongodb|postgres`, `--yes` and `--version`, interactive prompts for anything omitted.
26
+ - Generated Express API with register, login, refresh and logout endpoints.
27
+ - JWT access tokens and rotating refresh tokens in an httpOnly cookie, with reuse detection.
28
+ - Passwords hashed with argon2.
29
+ - Roles (`user`, `admin`), `/users/me`, admin-only user listing, lookup and deletion, and a `seed:admin` script.
30
+ - Request validation with Zod, rate limiting, Helmet, CORS and structured logging with Pino.
31
+ - Production refuses the example JWT secrets; `TRUST_PROXY` support for apps behind a proxy.
32
+ - Swagger UI at `/api-docs` and a Postman collection export.
33
+ - MongoDB (Mongoose) or PostgreSQL (Prisma) as the database.
34
+ - Tests with Vitest, ESLint, Prettier and Husky pre-commit hooks in every generated project.
35
+ - Dockerfile, docker-compose file and a GitHub Actions CI workflow.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nitish Kumar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,126 @@
1
- # Temporary Holding Version
1
+ # authkit-api
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Generate a ready-to-run Express authentication API in one command. Pick MongoDB or PostgreSQL, answer a couple of questions, and you get a clean, tested project with register, login, refresh tokens, roles and admin user management already working.
4
+
5
+ ## Quick start
6
+
7
+ ```bash
8
+ npx authkit-api my-app
9
+ cd my-app
10
+ ```
11
+
12
+ Or, equivalently:
13
+
14
+ ```bash
15
+ npm create authkit-api my-app
16
+ ```
17
+
18
+ Want TypeScript? Add `--lang ts` (with `npm create`, put it after `--`):
19
+
20
+ ```bash
21
+ npx authkit-api my-app --lang ts
22
+ ```
23
+
24
+ Then follow the `README.md` inside the generated project. It has the exact steps to set up the database, start the server and try the API.
25
+
26
+ ## Flags
27
+
28
+ ```bash
29
+ npx authkit-api <project-name> [--db mongodb|postgres] [--lang js|ts] [--yes]
30
+ ```
31
+
32
+ | Flag | Does |
33
+ | ----------------- | ----------------------------------- |
34
+ | `--db mongodb` | Use MongoDB with Mongoose |
35
+ | `--db postgres` | Use PostgreSQL with Prisma |
36
+ | `--lang js` | Plain JavaScript (default) |
37
+ | `--lang ts` | Strict TypeScript, no build step |
38
+ | `--yes`, `-y` | Skip the questions and use defaults |
39
+ | `--version`, `-v` | Print the version |
40
+ | `--help`, `-h` | Show usage |
41
+
42
+ Anything you leave out is asked interactively.
43
+
44
+ ## What you get
45
+
46
+ - Auth endpoints: register, login, refresh and logout
47
+ - Roles (`user`, `admin`), a `/users/me` endpoint and admin-only user management
48
+ - Request validation with Zod
49
+ - Passwords hashed with argon2
50
+ - JWT access tokens plus a rotating refresh token in an httpOnly cookie, with reuse detection
51
+ - Rate limiting, Helmet and CORS
52
+ - Structured logs with Pino
53
+ - Swagger UI and a Postman collection export
54
+ - Tests with Vitest
55
+ - ESLint, Prettier and Husky pre-commit hooks
56
+ - A Dockerfile and a compose file
57
+ - A GitHub Actions CI workflow
58
+ - MongoDB (Mongoose) or PostgreSQL (Prisma)
59
+
60
+ ## Requirements
61
+
62
+ - Node.js 22.18 or newer
63
+ - Docker, for the PostgreSQL option and for the generated compose file
64
+
65
+ ## Generated project layout
66
+
67
+ ```text
68
+ my-app/
69
+ ├── src/
70
+ │ ├── config/ environment schema and logger
71
+ │ ├── constants/ shared limits and constants
72
+ │ ├── database/ connection and models (Mongoose or Prisma)
73
+ │ ├── docs/ OpenAPI document
74
+ │ ├── middlewares/ auth, validation, errors, rate limits
75
+ │ ├── modules/
76
+ │ │ ├── auth/ routes, controller, service, validation
77
+ │ │ └── user/ routes, controller, service, repository
78
+ │ ├── routes/ versioned router, health, API docs
79
+ │ ├── utils/ tokens, passwords, errors, responses
80
+ │ ├── app.js
81
+ │ └── server.js
82
+ ├── tests/
83
+ ├── scripts/ seed admin, Postman export, Docker entrypoint
84
+ ├── Dockerfile
85
+ ├── docker-compose.yml
86
+ ├── .github/workflows/ci.yml
87
+ ├── .env.example
88
+ └── README.md
89
+ ```
90
+
91
+ ## API endpoints
92
+
93
+ All routes are under `/api/v1`, except `/health`.
94
+
95
+ | Method | Path | Who | Does |
96
+ | ------ | ---------------- | ------ | ------------------------------------------ |
97
+ | POST | `/auth/register` | all | Create a user |
98
+ | POST | `/auth/login` | all | Get an access token and a refresh cookie |
99
+ | POST | `/auth/refresh` | cookie | Rotate the refresh token, new access token |
100
+ | POST | `/auth/logout` | cookie | Revoke the refresh token |
101
+ | GET | `/users/me` | user | Current user |
102
+ | GET | `/users` | admin | List users (`?page=1&limit=20`) |
103
+ | GET | `/users/:id` | admin | One user |
104
+ | DELETE | `/users/:id` | admin | Delete a user |
105
+ | GET | `/health` | all | Liveness and database check |
106
+
107
+ ## Security notes
108
+
109
+ - In production the generated app refuses to start with the example JWT secrets from `.env.example`. Set two different, random secrets, for example with `openssl rand -base64 48`.
110
+ - If the app runs behind a reverse proxy or a PaaS, set `TRUST_PROXY` (for example `1`). Without it, rate limiting sees the proxy's address instead of the client's.
111
+ - Passwords, password hashes and refresh tokens are never returned or logged.
112
+
113
+ ## License
114
+
115
+ MIT
116
+
117
+ ## Releasing
118
+
119
+ For maintainers. Releases are published to npm automatically from GitHub Actions.
120
+
121
+ 1. Update `CHANGELOG.md`: move the `## [Unreleased]` entries under a new version heading.
122
+ 2. Run `npm version patch`, `npm version minor` or `npm version major`. This bumps `package.json`, commits and creates the `vX.Y.Z` git tag.
123
+ 3. Run `git push --follow-tags`.
124
+ 4. GitHub Actions runs the full CI and then publishes to npm. Watch it under Actions → Publish.
125
+
126
+ The one-time trusted-publisher setup on npmjs.com is described at the top of `.github/workflows/publish.yml`.
package/bin/cli.js ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { run } from '../src/index.js';
3
+ import { logger } from '../src/utils/logger.js';
4
+
5
+ run().catch((err) => {
6
+ logger.error(err.message);
7
+ process.exit(1);
8
+ });
package/package.json CHANGED
@@ -1,6 +1,78 @@
1
1
  {
2
2
  "name": "authkit-api",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "Generate an Express authentication API (JWT, roles, MongoDB or PostgreSQL) with one command",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Nitish Kumar",
8
+ "engines": {
9
+ "node": ">=22.18"
10
+ },
11
+ "bin": {
12
+ "authkit-api": "bin/cli.js"
13
+ },
14
+ "files": [
15
+ "bin",
16
+ "src",
17
+ "templates",
18
+ "templates-js",
19
+ "CHANGELOG.md"
20
+ ],
21
+ "scripts": {
22
+ "lint": "eslint .",
23
+ "lint:fix": "eslint . --fix",
24
+ "format": "prettier --write .",
25
+ "format:check": "prettier --check .",
26
+ "build:templates": "node scripts/build-templates.js",
27
+ "pretest": "npm run build:templates",
28
+ "test": "vitest run",
29
+ "test:watch": "vitest",
30
+ "sandbox:mongo": "npm run build:templates && rm -rf .sandbox/mongo-app && node bin/cli.js .sandbox/mongo-app --db mongodb",
31
+ "sandbox:pg": "npm run build:templates && rm -rf .sandbox/pg-app && node bin/cli.js .sandbox/pg-app --db postgres",
32
+ "prepare": "husky",
33
+ "prepack": "npm run build:templates",
34
+ "e2e:mongo": "bash scripts/e2e.sh mongodb",
35
+ "e2e:pg": "bash scripts/e2e.sh postgres",
36
+ "e2e:mongo:ts": "bash scripts/e2e.sh mongodb ts",
37
+ "e2e:pg:ts": "bash scripts/e2e.sh postgres ts",
38
+ "compare:v1": "bash scripts/compare-v1.sh"
39
+ },
40
+ "lint-staged": {
41
+ "*.js": [
42
+ "eslint --fix --config eslint.config.js --no-warn-ignored",
43
+ "prettier --write"
44
+ ],
45
+ "*.{json,md,yml}": [
46
+ "prettier --write"
47
+ ]
48
+ },
49
+ "devDependencies": {
50
+ "@eslint/js": "^10.0.1",
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
+ "prettier": "^3.9.10",
57
+ "vitest": "^5.0.5"
58
+ },
59
+ "dependencies": {
60
+ "@clack/prompts": "^1.8.1",
61
+ "picocolors": "^1.1.1",
62
+ "validate-npm-package-name": "^8.0.0"
63
+ },
64
+ "keywords": [
65
+ "express",
66
+ "auth",
67
+ "authentication",
68
+ "jwt",
69
+ "boilerplate",
70
+ "generator",
71
+ "scaffold",
72
+ "mongodb",
73
+ "mongoose",
74
+ "postgres",
75
+ "prisma",
76
+ "cli"
77
+ ]
78
+ }
@@ -0,0 +1,29 @@
1
+ import { fileURLToPath } from 'node:url';
2
+
3
+ export const DATABASES = { MONGODB: 'mongodb', POSTGRES: 'postgres' };
4
+ export const DEFAULT_DATABASE = DATABASES.MONGODB;
5
+ export const LANGUAGES = { JS: 'js', TS: 'ts' };
6
+ export const DEFAULT_LANGUAGE = LANGUAGES.JS;
7
+
8
+ export const TEMPLATES_DIR = fileURLToPath(new URL('../templates', import.meta.url));
9
+ // Built from TEMPLATES_DIR by `npm run build:templates` (types stripped). JS projects are copied from here,
10
+ // TS projects from TEMPLATES_DIR. Both then get TEMPLATES_DIR/languages/<lang> on top.
11
+ export const JS_TEMPLATES_DIR = fileURLToPath(new URL('../templates-js', import.meta.url));
12
+ export const PACKAGE_PART_FILE = 'package.part.json';
13
+ // Per-database env vars, appended to the base _env.example.
14
+ export const ENV_PART_FILE = 'env.part';
15
+ // Per-database README section, substituted for {{databaseSection}} in the base README.
16
+ export const README_PART_FILE = 'README.part.md';
17
+ export const ENV_EXAMPLE_FILE = '_env.example';
18
+ // Replaced before dotfile renaming, so names still carry the "_" prefix.
19
+ export const PLACEHOLDER_FILES = ['README.md', 'docker-compose.yml', '_env.example'];
20
+ // Template dotfiles are stored as "_name" (npm drops dotfiles when publishing). Only these are renamed.
21
+ export const SPECIAL_FILE_NAMES = new Set([
22
+ '_gitignore',
23
+ '_env.example',
24
+ '_dockerignore',
25
+ '_prettierrc',
26
+ '_prettierignore',
27
+ '_github',
28
+ '_husky',
29
+ ]);
@@ -0,0 +1,142 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import {
4
+ DEFAULT_LANGUAGE,
5
+ ENV_EXAMPLE_FILE,
6
+ ENV_PART_FILE,
7
+ JS_TEMPLATES_DIR,
8
+ LANGUAGES,
9
+ PACKAGE_PART_FILE,
10
+ PLACEHOLDER_FILES,
11
+ README_PART_FILE,
12
+ TEMPLATES_DIR,
13
+ } from './constants.js';
14
+ import { copyDir, isDirEmpty, renameSpecialFiles } from './utils/fs.js';
15
+ import { mergePackageJson } from './utils/packageJson.js';
16
+
17
+ const pathExists = (p) =>
18
+ fs.access(p).then(
19
+ () => true,
20
+ () => false,
21
+ );
22
+ const readJson = async (file) => JSON.parse(await fs.readFile(file, 'utf8'));
23
+ // A layer without a package.part.json adds nothing to package.json.
24
+ const readPart = async (dir) => {
25
+ try {
26
+ return await readJson(path.join(dir, PACKAGE_PART_FILE));
27
+ } catch (error) {
28
+ if (error.code === 'ENOENT') return {};
29
+ throw error;
30
+ }
31
+ };
32
+
33
+ // Database names allow fewer characters than npm names: "my.app" and "my-app" become "my_app".
34
+ export const toDatabaseName = (projectName) =>
35
+ projectName.toLowerCase().replace(/[^a-z0-9_]/g, '_');
36
+
37
+ async function replacePlaceholders(targetDir, projectName) {
38
+ const databaseName = toDatabaseName(projectName);
39
+ for (const file of PLACEHOLDER_FILES) {
40
+ const filePath = path.join(targetDir, file);
41
+ let content;
42
+ try {
43
+ content = await fs.readFile(filePath, 'utf8');
44
+ } catch (error) {
45
+ if (error.code === 'ENOENT') continue;
46
+ throw error;
47
+ }
48
+ await fs.writeFile(
49
+ filePath,
50
+ content
51
+ .replaceAll('{{projectName}}', projectName)
52
+ .replaceAll('{{databaseName}}', databaseName),
53
+ );
54
+ }
55
+ }
56
+
57
+ async function appendEnvPart(dbDir, targetDir) {
58
+ let part;
59
+ try {
60
+ part = await fs.readFile(path.join(dbDir, ENV_PART_FILE), 'utf8');
61
+ } catch (error) {
62
+ if (error.code === 'ENOENT') return;
63
+ throw error;
64
+ }
65
+ const envPath = path.join(targetDir, ENV_EXAMPLE_FILE);
66
+ const base = await fs.readFile(envPath, 'utf8');
67
+ await fs.writeFile(envPath, `${base.trimEnd()}\n\n${part}`);
68
+ }
69
+
70
+ async function insertReadmePart(dbDir, targetDir) {
71
+ let part;
72
+ try {
73
+ part = await fs.readFile(path.join(dbDir, README_PART_FILE), 'utf8');
74
+ } catch (error) {
75
+ if (error.code === 'ENOENT') return;
76
+ throw error;
77
+ }
78
+ const readmePath = path.join(targetDir, 'README.md');
79
+ const readme = await fs.readFile(readmePath, 'utf8');
80
+ await fs.writeFile(
81
+ readmePath,
82
+ readme.replace('{{databaseSection}}', () => part.trim()),
83
+ );
84
+ }
85
+
86
+ // `displayName` is the path as the user typed it, used in error messages.
87
+ export async function generateProject({
88
+ projectName,
89
+ db,
90
+ lang = DEFAULT_LANGUAGE,
91
+ targetDir,
92
+ displayName = projectName,
93
+ }) {
94
+ if (!(await isDirEmpty(targetDir))) {
95
+ throw new Error(`Directory "${displayName}" already exists and is not empty.`);
96
+ }
97
+
98
+ if (lang !== LANGUAGES.TS && !(await pathExists(JS_TEMPLATES_DIR))) {
99
+ throw new Error('JS templates are missing. Run "npm run build:templates" first.');
100
+ }
101
+
102
+ const existed = await pathExists(targetDir);
103
+ try {
104
+ await writeProject({ projectName, db, lang, targetDir });
105
+ } catch (error) {
106
+ // Leave no half-written project behind. A target that already existed was empty, so only empty it.
107
+ if (existed) {
108
+ for (const entry of await fs.readdir(targetDir)) {
109
+ await fs.rm(path.join(targetDir, entry), { recursive: true, force: true });
110
+ }
111
+ } else {
112
+ await fs.rm(targetDir, { recursive: true, force: true });
113
+ }
114
+ throw error;
115
+ }
116
+ }
117
+
118
+ // Layers: base, then databases/<db>, then languages/<lang>. JS reads base and databases from the
119
+ // built JS templates, TS from the TS source. languages/ always comes from the source.
120
+ async function writeProject({ projectName, db, lang, targetDir }) {
121
+ const sourceRoot = lang === LANGUAGES.TS ? TEMPLATES_DIR : JS_TEMPLATES_DIR;
122
+ const baseDir = path.join(sourceRoot, 'base');
123
+ const dbDir = path.join(sourceRoot, 'databases', db);
124
+ const langDir = path.join(TEMPLATES_DIR, 'languages', lang);
125
+
126
+ await copyDir(baseDir, targetDir, { skip: [] });
127
+ await copyDir(dbDir, targetDir, { skip: [PACKAGE_PART_FILE, ENV_PART_FILE, README_PART_FILE] });
128
+ await copyDir(langDir, targetDir, { skip: [PACKAGE_PART_FILE] });
129
+
130
+ const basePackage = await readJson(path.join(baseDir, 'package.json'));
131
+ const merged = mergePackageJson(
132
+ mergePackageJson(basePackage, await readPart(dbDir), { name: projectName }),
133
+ await readPart(langDir),
134
+ { name: projectName },
135
+ );
136
+ await fs.writeFile(path.join(targetDir, 'package.json'), `${JSON.stringify(merged, null, 2)}\n`);
137
+
138
+ await appendEnvPart(dbDir, targetDir);
139
+ await insertReadmePart(dbDir, targetDir);
140
+ await replacePlaceholders(targetDir, projectName);
141
+ await renameSpecialFiles(targetDir);
142
+ }
package/src/index.js ADDED
@@ -0,0 +1,99 @@
1
+ import { createRequire } from 'node:module';
2
+ import { parseArgs } from 'node:util';
3
+ import path from 'node:path';
4
+ import { DATABASES, LANGUAGES } from './constants.js';
5
+ import { generateProject } from './generator.js';
6
+ import { askOptions } from './prompts.js';
7
+ import { logger } from './utils/logger.js';
8
+ import { assertValidProjectName } from './utils/validateProjectName.js';
9
+
10
+ // Quote a path for the "cd" hint only when the shell would need it.
11
+ const shellQuote = (value) => (/^[\w./@+-]+$/.test(value) ? value : JSON.stringify(value));
12
+
13
+ const USAGE = 'npx authkit-api <project-name> [--db mongodb|postgres] [--lang js|ts] [--yes]';
14
+
15
+ export function parseCliArgs(argv) {
16
+ const { values, positionals } = parseArgs({
17
+ args: argv,
18
+ allowPositionals: true,
19
+ options: {
20
+ db: { type: 'string' },
21
+ lang: { type: 'string' },
22
+ yes: { type: 'boolean', short: 'y', default: false },
23
+ help: { type: 'boolean', short: 'h', default: false },
24
+ version: { type: 'boolean', short: 'v', default: false },
25
+ },
26
+ });
27
+
28
+ if (positionals.length > 1) {
29
+ throw new Error(`Too many arguments. Usage: ${USAGE}`);
30
+ }
31
+
32
+ const databases = Object.values(DATABASES);
33
+ if (values.db !== undefined && !databases.includes(values.db)) {
34
+ throw new Error(`Invalid --db value "${values.db}". Choose one of: ${databases.join(', ')}`);
35
+ }
36
+
37
+ const languages = Object.values(LANGUAGES);
38
+ if (values.lang !== undefined && !languages.includes(values.lang)) {
39
+ throw new Error(
40
+ `Invalid --lang value "${values.lang}". Choose one of: ${languages.join(', ')}`,
41
+ );
42
+ }
43
+
44
+ return {
45
+ projectName: positionals[0],
46
+ db: values.db,
47
+ lang: values.lang,
48
+ yes: values.yes,
49
+ help: values.help,
50
+ version: values.version,
51
+ };
52
+ }
53
+
54
+ export async function run(argv = process.argv.slice(2)) {
55
+ const args = parseCliArgs(argv);
56
+
57
+ if (args.help) {
58
+ logger.info(`Usage: ${USAGE}`);
59
+ return;
60
+ }
61
+ if (args.version) {
62
+ const { version } = createRequire(import.meta.url)('../package.json');
63
+ process.stdout.write(`${version}\n`);
64
+ return;
65
+ }
66
+
67
+ if (args.yes && !args.projectName) {
68
+ throw new Error('Project name is required when using --yes.');
69
+ }
70
+ if (args.projectName !== undefined) assertValidProjectName(args.projectName);
71
+
72
+ const options = await askOptions(args);
73
+ if (!options) return; // user cancelled: exit 0
74
+
75
+ assertValidProjectName(options.projectName);
76
+
77
+ const targetDir = path.resolve(process.cwd(), options.projectName);
78
+ const name = path.basename(options.projectName);
79
+ await generateProject({
80
+ projectName: name,
81
+ db: options.db,
82
+ lang: options.lang,
83
+ targetDir,
84
+ displayName: options.projectName,
85
+ });
86
+
87
+ logger.success(`Created ${name}`);
88
+ const steps = [
89
+ `cd ${shellQuote(options.projectName)}`,
90
+ 'cp .env.example .env',
91
+ 'npm install',
92
+ // --wait returns once the database health check passes, so the next step can connect.
93
+ 'docker compose up -d --wait db',
94
+ ...(options.db === DATABASES.POSTGRES ? ['npm run db:deploy'] : []),
95
+ 'npm run dev',
96
+ ];
97
+ logger.info('Next steps:');
98
+ for (const step of steps) logger.info(` ${step}`);
99
+ }
package/src/prompts.js ADDED
@@ -0,0 +1,59 @@
1
+ import * as clack from '@clack/prompts';
2
+ import { DATABASES, DEFAULT_DATABASE, DEFAULT_LANGUAGE, LANGUAGES } from './constants.js';
3
+ import { validateProjectName } from './utils/validateProjectName.js';
4
+
5
+ export async function askOptions({ projectName, db, lang, yes }) {
6
+ if (yes) {
7
+ return { projectName, db: db ?? DEFAULT_DATABASE, lang: lang ?? DEFAULT_LANGUAGE };
8
+ }
9
+
10
+ let name = projectName;
11
+ if (!name) {
12
+ name = await clack.text({
13
+ message: 'Project name?',
14
+ placeholder: 'my-app',
15
+ validate: (value) => {
16
+ const { valid, problems } = validateProjectName(value ?? '');
17
+ return valid ? undefined : problems.join(', ');
18
+ },
19
+ });
20
+ if (clack.isCancel(name)) {
21
+ clack.cancel('Cancelled.');
22
+ return null;
23
+ }
24
+ }
25
+
26
+ let database = db;
27
+ if (!database) {
28
+ database = await clack.select({
29
+ message: 'Which database?',
30
+ options: [
31
+ { value: DATABASES.MONGODB, label: 'MongoDB (Mongoose)' },
32
+ { value: DATABASES.POSTGRES, label: 'PostgreSQL (Prisma)' },
33
+ ],
34
+ initialValue: DEFAULT_DATABASE,
35
+ });
36
+ if (clack.isCancel(database)) {
37
+ clack.cancel('Cancelled.');
38
+ return null;
39
+ }
40
+ }
41
+
42
+ let language = lang;
43
+ if (!language) {
44
+ language = await clack.select({
45
+ message: 'Which language?',
46
+ options: [
47
+ { value: LANGUAGES.JS, label: 'JavaScript' },
48
+ { value: LANGUAGES.TS, label: 'TypeScript' },
49
+ ],
50
+ initialValue: DEFAULT_LANGUAGE,
51
+ });
52
+ if (clack.isCancel(language)) {
53
+ clack.cancel('Cancelled.');
54
+ return null;
55
+ }
56
+ }
57
+
58
+ return { projectName: name, db: database, lang: language };
59
+ }
@@ -0,0 +1,36 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { SPECIAL_FILE_NAMES } from '../constants.js';
4
+
5
+ export async function isDirEmpty(dir) {
6
+ try {
7
+ return (await fs.readdir(dir)).length === 0;
8
+ } catch (error) {
9
+ if (error.code === 'ENOENT') return true;
10
+ // The target exists but is a file, so it is certainly not an empty directory.
11
+ if (error.code === 'ENOTDIR') return false;
12
+ throw error;
13
+ }
14
+ }
15
+
16
+ export async function copyDir(src, dest, { skip = [] } = {}) {
17
+ await fs.cp(src, dest, {
18
+ recursive: true,
19
+ force: true,
20
+ filter: (source) => !skip.includes(path.basename(source)),
21
+ });
22
+ }
23
+
24
+ // npm drops dotfiles when publishing, so templates store them as "_name".
25
+ // Other "_" names (such as a test helper) are left alone.
26
+ export async function renameSpecialFiles(dir) {
27
+ for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
28
+ let current = path.join(dir, entry.name);
29
+ if (SPECIAL_FILE_NAMES.has(entry.name)) {
30
+ const renamed = path.join(dir, `.${entry.name.slice(1)}`);
31
+ await fs.rename(current, renamed);
32
+ current = renamed;
33
+ }
34
+ if (entry.isDirectory()) await renameSpecialFiles(current);
35
+ }
36
+ }
@@ -0,0 +1,8 @@
1
+ import pc from 'picocolors';
2
+
3
+ export const logger = {
4
+ info: (msg) => console.log(pc.cyan(msg)),
5
+ success: (msg) => console.log(pc.green(msg)),
6
+ warn: (msg) => console.error(pc.yellow(msg)),
7
+ error: (msg) => console.error(pc.red(msg)),
8
+ };
@@ -0,0 +1,16 @@
1
+ const MERGED_KEYS = ['scripts', 'dependencies', 'devDependencies'];
2
+
3
+ function sortKeys(obj) {
4
+ return Object.fromEntries(Object.entries(obj).sort(([a], [b]) => a.localeCompare(b)));
5
+ }
6
+
7
+ export function mergePackageJson(base, part, { name }) {
8
+ const merged = { ...base, ...part, name };
9
+ for (const key of MERGED_KEYS) {
10
+ if (base[key] || part[key]) {
11
+ const combined = { ...base[key], ...part[key] };
12
+ merged[key] = key === 'scripts' ? combined : sortKeys(combined);
13
+ }
14
+ }
15
+ return merged;
16
+ }