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.
Files changed (110) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/LICENSE +21 -0
  3. package/README.md +109 -2
  4. package/bin/cli.js +8 -0
  5. package/package.json +69 -4
  6. package/src/constants.js +24 -0
  7. package/src/generator.js +112 -0
  8. package/src/index.js +89 -0
  9. package/src/prompts.js +43 -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/eslint.config.js +23 -0
  23. package/templates/base/package.json +62 -0
  24. package/templates/base/scripts/docker-entrypoint.sh +9 -0
  25. package/templates/base/scripts/generate-postman.js +70 -0
  26. package/templates/base/scripts/seed-admin.js +61 -0
  27. package/templates/base/src/app.js +46 -0
  28. package/templates/base/src/config/env.js +15 -0
  29. package/templates/base/src/config/env.schema.js +85 -0
  30. package/templates/base/src/config/logger.js +20 -0
  31. package/templates/base/src/constants/examples.js +3 -0
  32. package/templates/base/src/constants/roles.js +2 -0
  33. package/templates/base/src/constants/user.rules.js +16 -0
  34. package/templates/base/src/docs/openapi.js +26 -0
  35. package/templates/base/src/docs/openapi.registry.js +81 -0
  36. package/templates/base/src/docs/paths/auth.paths.js +87 -0
  37. package/templates/base/src/docs/paths/user.paths.js +87 -0
  38. package/templates/base/src/middlewares/authenticate.js +19 -0
  39. package/templates/base/src/middlewares/authorize.js +11 -0
  40. package/templates/base/src/middlewares/errorHandler.js +35 -0
  41. package/templates/base/src/middlewares/notFound.js +5 -0
  42. package/templates/base/src/middlewares/rateLimiter.js +20 -0
  43. package/templates/base/src/middlewares/validate.js +31 -0
  44. package/templates/base/src/modules/auth/auth.controller.js +40 -0
  45. package/templates/base/src/modules/auth/auth.cookie.js +21 -0
  46. package/templates/base/src/modules/auth/auth.routes.js +12 -0
  47. package/templates/base/src/modules/auth/auth.service.js +79 -0
  48. package/templates/base/src/modules/auth/auth.validation.js +41 -0
  49. package/templates/base/src/modules/user/user.controller.js +21 -0
  50. package/templates/base/src/modules/user/user.routes.js +22 -0
  51. package/templates/base/src/modules/user/user.service.js +19 -0
  52. package/templates/base/src/modules/user/user.validation.js +24 -0
  53. package/templates/base/src/routes/docs.routes.js +16 -0
  54. package/templates/base/src/routes/health.routes.js +17 -0
  55. package/templates/base/src/routes/index.js +13 -0
  56. package/templates/base/src/server.js +50 -0
  57. package/templates/base/src/utils/ApiError.js +32 -0
  58. package/templates/base/src/utils/apiResponse.js +8 -0
  59. package/templates/base/src/utils/password.js +14 -0
  60. package/templates/base/src/utils/token.js +46 -0
  61. package/templates/base/src/utils/zod.js +5 -0
  62. package/templates/base/tests/app.test.js +67 -0
  63. package/templates/base/tests/auth.test.js +185 -0
  64. package/templates/base/tests/authenticate.test.js +61 -0
  65. package/templates/base/tests/docs.test.js +115 -0
  66. package/templates/base/tests/env.test.js +94 -0
  67. package/templates/base/tests/health.test.js +21 -0
  68. package/templates/base/tests/helpers/auth.helper.js +41 -0
  69. package/templates/base/tests/password.test.js +18 -0
  70. package/templates/base/tests/postman.test.js +31 -0
  71. package/templates/base/tests/rateLimiter.test.js +27 -0
  72. package/templates/base/tests/seedAdmin.test.js +42 -0
  73. package/templates/base/tests/token.test.js +69 -0
  74. package/templates/base/tests/trustProxy.test.js +24 -0
  75. package/templates/base/tests/user.repository.test.js +210 -0
  76. package/templates/base/tests/user.test.js +144 -0
  77. package/templates/base/tests/validate.test.js +35 -0
  78. package/templates/base/tests/validation.test.js +61 -0
  79. package/templates/base/vitest.config.js +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.js +39 -0
  86. package/templates/databases/mongodb/src/database/env.schema.js +3 -0
  87. package/templates/databases/mongodb/src/database/id.schema.js +3 -0
  88. package/templates/databases/mongodb/src/database/models/refreshToken.model.js +15 -0
  89. package/templates/databases/mongodb/src/database/models/user.model.js +41 -0
  90. package/templates/databases/mongodb/src/modules/user/user.repository.js +68 -0
  91. package/templates/databases/mongodb/tests/globalSetup.js +13 -0
  92. package/templates/databases/mongodb/tests/setup.js +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.js +14 -0
  102. package/templates/databases/postgres/src/database/connection.js +61 -0
  103. package/templates/databases/postgres/src/database/env.schema.js +3 -0
  104. package/templates/databases/postgres/src/database/id.schema.js +3 -0
  105. package/templates/databases/postgres/src/database/prisma.js +9 -0
  106. package/templates/databases/postgres/src/modules/user/user.repository.js +88 -0
  107. package/templates/databases/postgres/tests/connection.test.js +17 -0
  108. package/templates/databases/postgres/tests/globalSetup.js +60 -0
  109. package/templates/databases/postgres/tests/prismaSchema.test.js +27 -0
  110. package/templates/databases/postgres/tests/setup.js +15 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,26 @@
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
+ ## [Unreleased]
9
+
10
+ ## [1.0.0] - 2026-10-30
11
+
12
+ First public release.
13
+
14
+ ### Added
15
+
16
+ - `npx authkit-api <project-name>` CLI with `--db mongodb|postgres`, `--yes` and `--version`, interactive prompts for anything omitted.
17
+ - Generated Express API with register, login, refresh and logout endpoints.
18
+ - JWT access tokens and rotating refresh tokens in an httpOnly cookie, with reuse detection.
19
+ - Passwords hashed with argon2.
20
+ - Roles (`user`, `admin`), `/users/me`, admin-only user listing, lookup and deletion, and a `seed:admin` script.
21
+ - Request validation with Zod, rate limiting, Helmet, CORS and structured logging with Pino.
22
+ - Production refuses the example JWT secrets; `TRUST_PROXY` support for apps behind a proxy.
23
+ - Swagger UI at `/api-docs` and a Postman collection export.
24
+ - MongoDB (Mongoose) or PostgreSQL (Prisma) as the database.
25
+ - Tests with Vitest, ESLint, Prettier and Husky pre-commit hooks in every generated project.
26
+ - 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,110 @@
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
+ 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.
13
+
14
+ ## Flags
15
+
16
+ ```bash
17
+ npx authkit-api <project-name> [--db mongodb|postgres] [--yes]
18
+ ```
19
+
20
+ | Flag | Does |
21
+ | ----------------- | ----------------------------------- |
22
+ | `--db mongodb` | Use MongoDB with Mongoose |
23
+ | `--db postgres` | Use PostgreSQL with Prisma |
24
+ | `--yes`, `-y` | Skip the questions and use defaults |
25
+ | `--version`, `-v` | Print the version |
26
+ | `--help`, `-h` | Show usage |
27
+
28
+ Anything you leave out is asked interactively.
29
+
30
+ ## What you get
31
+
32
+ - Auth endpoints: register, login, refresh and logout
33
+ - Roles (`user`, `admin`), a `/users/me` endpoint and admin-only user management
34
+ - Request validation with Zod
35
+ - Passwords hashed with argon2
36
+ - JWT access tokens plus a rotating refresh token in an httpOnly cookie, with reuse detection
37
+ - Rate limiting, Helmet and CORS
38
+ - Structured logs with Pino
39
+ - Swagger UI and a Postman collection export
40
+ - Tests with Vitest
41
+ - ESLint, Prettier and Husky pre-commit hooks
42
+ - A Dockerfile and a compose file
43
+ - A GitHub Actions CI workflow
44
+ - MongoDB (Mongoose) or PostgreSQL (Prisma)
45
+
46
+ ## Requirements
47
+
48
+ - Node.js 22.18 or newer
49
+ - Docker, for the PostgreSQL option and for the generated compose file
50
+
51
+ ## Generated project layout
52
+
53
+ ```text
54
+ my-app/
55
+ ├── src/
56
+ │ ├── config/ environment schema and logger
57
+ │ ├── constants/ shared limits and constants
58
+ │ ├── database/ connection and models (Mongoose or Prisma)
59
+ │ ├── docs/ OpenAPI document
60
+ │ ├── middlewares/ auth, validation, errors, rate limits
61
+ │ ├── modules/
62
+ │ │ ├── auth/ routes, controller, service, validation
63
+ │ │ └── user/ routes, controller, service, repository
64
+ │ ├── routes/ versioned router, health, API docs
65
+ │ ├── utils/ tokens, passwords, errors, responses
66
+ │ ├── app.js
67
+ │ └── server.js
68
+ ├── tests/
69
+ ├── scripts/ seed admin, Postman export, Docker entrypoint
70
+ ├── Dockerfile
71
+ ├── docker-compose.yml
72
+ ├── .github/workflows/ci.yml
73
+ ├── .env.example
74
+ └── README.md
75
+ ```
76
+
77
+ ## API endpoints
78
+
79
+ All routes are under `/api/v1`, except `/health`.
80
+
81
+ | Method | Path | Who | Does |
82
+ | ------ | ---------------- | ------ | ------------------------------------------ |
83
+ | POST | `/auth/register` | all | Create a user |
84
+ | POST | `/auth/login` | all | Get an access token and a refresh cookie |
85
+ | POST | `/auth/refresh` | cookie | Rotate the refresh token, new access token |
86
+ | POST | `/auth/logout` | cookie | Revoke the refresh token |
87
+ | GET | `/users/me` | user | Current user |
88
+ | GET | `/users` | admin | List users (`?page=1&limit=20`) |
89
+ | GET | `/users/:id` | admin | One user |
90
+ | DELETE | `/users/:id` | admin | Delete a user |
91
+ | GET | `/health` | all | Liveness and database check |
92
+
93
+ ## Security notes
94
+
95
+ - 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`.
96
+ - 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.
97
+ - Passwords, password hashes and refresh tokens are never returned or logged.
98
+
99
+ ## License
100
+
101
+ MIT
102
+
103
+ ## Releasing
104
+
105
+ For maintainers. (Automating this is planned.)
106
+
107
+ 1. Add the changes to `CHANGELOG.md` under `## [Unreleased]`, then move them under a new version heading.
108
+ 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.
109
+ 3. Run `npm publish --access public`.
110
+ 4. Push the commit and the tag.
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,71 @@
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.0.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
+ "CHANGELOG.md"
19
+ ],
20
+ "scripts": {
21
+ "lint": "eslint .",
22
+ "lint:fix": "eslint . --fix",
23
+ "format": "prettier --write .",
24
+ "format:check": "prettier --check .",
25
+ "test": "vitest run",
26
+ "test:watch": "vitest",
27
+ "sandbox:mongo": "rm -rf .sandbox/mongo-app && node bin/cli.js .sandbox/mongo-app --db mongodb",
28
+ "sandbox:pg": "rm -rf .sandbox/pg-app && node bin/cli.js .sandbox/pg-app --db postgres",
29
+ "prepare": "husky",
30
+ "e2e:mongo": "bash scripts/e2e.sh mongodb",
31
+ "e2e:pg": "bash scripts/e2e.sh postgres"
32
+ },
33
+ "lint-staged": {
34
+ "*.js": [
35
+ "eslint --fix",
36
+ "prettier --write"
37
+ ],
38
+ "*.{json,md,yml}": [
39
+ "prettier --write"
40
+ ]
41
+ },
42
+ "devDependencies": {
43
+ "@eslint/js": "^10.0.1",
44
+ "eslint": "^10.13.0",
45
+ "eslint-config-prettier": "^10.1.8",
46
+ "globals": "^17.13.0",
47
+ "husky": "^9.1.7",
48
+ "lint-staged": "^17.6.0",
49
+ "prettier": "^3.9.10",
50
+ "vitest": "^5.0.5"
51
+ },
52
+ "dependencies": {
53
+ "@clack/prompts": "^1.8.1",
54
+ "picocolors": "^1.1.1",
55
+ "validate-npm-package-name": "^8.0.0"
56
+ },
57
+ "keywords": [
58
+ "express",
59
+ "auth",
60
+ "authentication",
61
+ "jwt",
62
+ "boilerplate",
63
+ "generator",
64
+ "scaffold",
65
+ "mongodb",
66
+ "mongoose",
67
+ "postgres",
68
+ "prisma",
69
+ "cli"
70
+ ]
71
+ }
@@ -0,0 +1,24 @@
1
+ import { fileURLToPath } from 'node:url';
2
+
3
+ export const DATABASES = { MONGODB: 'mongodb', POSTGRES: 'postgres' };
4
+ export const DEFAULT_DATABASE = DATABASES.MONGODB;
5
+
6
+ export const TEMPLATES_DIR = fileURLToPath(new URL('../templates', import.meta.url));
7
+ export const PACKAGE_PART_FILE = 'package.part.json';
8
+ // Per-database env vars, appended to the base _env.example.
9
+ export const ENV_PART_FILE = 'env.part';
10
+ // Per-database README section, substituted for {{databaseSection}} in the base README.
11
+ export const README_PART_FILE = 'README.part.md';
12
+ export const ENV_EXAMPLE_FILE = '_env.example';
13
+ // Replaced before dotfile renaming, so names still carry the "_" prefix.
14
+ export const PLACEHOLDER_FILES = ['README.md', 'docker-compose.yml', '_env.example'];
15
+ // Template dotfiles are stored as "_name" (npm drops dotfiles when publishing). Only these are renamed.
16
+ export const SPECIAL_FILE_NAMES = new Set([
17
+ '_gitignore',
18
+ '_env.example',
19
+ '_dockerignore',
20
+ '_prettierrc',
21
+ '_prettierignore',
22
+ '_github',
23
+ '_husky',
24
+ ]);
@@ -0,0 +1,112 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import {
4
+ ENV_EXAMPLE_FILE,
5
+ ENV_PART_FILE,
6
+ PACKAGE_PART_FILE,
7
+ PLACEHOLDER_FILES,
8
+ README_PART_FILE,
9
+ TEMPLATES_DIR,
10
+ } from './constants.js';
11
+ import { copyDir, isDirEmpty, renameSpecialFiles } from './utils/fs.js';
12
+ import { mergePackageJson } from './utils/packageJson.js';
13
+
14
+ const pathExists = (p) =>
15
+ fs.access(p).then(
16
+ () => true,
17
+ () => false,
18
+ );
19
+ const readJson = async (file) => JSON.parse(await fs.readFile(file, 'utf8'));
20
+
21
+ // Database names allow fewer characters than npm names: "my.app" and "my-app" become "my_app".
22
+ export const toDatabaseName = (projectName) =>
23
+ projectName.toLowerCase().replace(/[^a-z0-9_]/g, '_');
24
+
25
+ async function replacePlaceholders(targetDir, projectName) {
26
+ const databaseName = toDatabaseName(projectName);
27
+ for (const file of PLACEHOLDER_FILES) {
28
+ const filePath = path.join(targetDir, file);
29
+ let content;
30
+ try {
31
+ content = await fs.readFile(filePath, 'utf8');
32
+ } catch (error) {
33
+ if (error.code === 'ENOENT') continue;
34
+ throw error;
35
+ }
36
+ await fs.writeFile(
37
+ filePath,
38
+ content
39
+ .replaceAll('{{projectName}}', projectName)
40
+ .replaceAll('{{databaseName}}', databaseName),
41
+ );
42
+ }
43
+ }
44
+
45
+ async function appendEnvPart(dbDir, targetDir) {
46
+ let part;
47
+ try {
48
+ part = await fs.readFile(path.join(dbDir, ENV_PART_FILE), 'utf8');
49
+ } catch (error) {
50
+ if (error.code === 'ENOENT') return;
51
+ throw error;
52
+ }
53
+ const envPath = path.join(targetDir, ENV_EXAMPLE_FILE);
54
+ const base = await fs.readFile(envPath, 'utf8');
55
+ await fs.writeFile(envPath, `${base.trimEnd()}\n\n${part}`);
56
+ }
57
+
58
+ async function insertReadmePart(dbDir, targetDir) {
59
+ let part;
60
+ try {
61
+ part = await fs.readFile(path.join(dbDir, README_PART_FILE), 'utf8');
62
+ } catch (error) {
63
+ if (error.code === 'ENOENT') return;
64
+ throw error;
65
+ }
66
+ const readmePath = path.join(targetDir, 'README.md');
67
+ const readme = await fs.readFile(readmePath, 'utf8');
68
+ await fs.writeFile(
69
+ readmePath,
70
+ readme.replace('{{databaseSection}}', () => part.trim()),
71
+ );
72
+ }
73
+
74
+ // `displayName` is the path as the user typed it, used in error messages.
75
+ export async function generateProject({ projectName, db, targetDir, displayName = projectName }) {
76
+ if (!(await isDirEmpty(targetDir))) {
77
+ throw new Error(`Directory "${displayName}" already exists and is not empty.`);
78
+ }
79
+
80
+ const existed = await pathExists(targetDir);
81
+ try {
82
+ await writeProject({ projectName, db, targetDir });
83
+ } catch (error) {
84
+ // Leave no half-written project behind. A target that already existed was empty, so only empty it.
85
+ if (existed) {
86
+ for (const entry of await fs.readdir(targetDir)) {
87
+ await fs.rm(path.join(targetDir, entry), { recursive: true, force: true });
88
+ }
89
+ } else {
90
+ await fs.rm(targetDir, { recursive: true, force: true });
91
+ }
92
+ throw error;
93
+ }
94
+ }
95
+
96
+ async function writeProject({ projectName, db, targetDir }) {
97
+ const baseDir = path.join(TEMPLATES_DIR, 'base');
98
+ const dbDir = path.join(TEMPLATES_DIR, 'databases', db);
99
+
100
+ await copyDir(baseDir, targetDir, { skip: [] });
101
+ await copyDir(dbDir, targetDir, { skip: [PACKAGE_PART_FILE, ENV_PART_FILE, README_PART_FILE] });
102
+
103
+ const basePackage = await readJson(path.join(baseDir, 'package.json'));
104
+ const part = await readJson(path.join(dbDir, PACKAGE_PART_FILE));
105
+ const merged = mergePackageJson(basePackage, part, { name: projectName });
106
+ await fs.writeFile(path.join(targetDir, 'package.json'), `${JSON.stringify(merged, null, 2)}\n`);
107
+
108
+ await appendEnvPart(dbDir, targetDir);
109
+ await insertReadmePart(dbDir, targetDir);
110
+ await replacePlaceholders(targetDir, projectName);
111
+ await renameSpecialFiles(targetDir);
112
+ }
package/src/index.js ADDED
@@ -0,0 +1,89 @@
1
+ import { createRequire } from 'node:module';
2
+ import { parseArgs } from 'node:util';
3
+ import path from 'node:path';
4
+ import { DATABASES } 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] [--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
+ yes: { type: 'boolean', short: 'y', default: false },
22
+ help: { type: 'boolean', short: 'h', default: false },
23
+ version: { type: 'boolean', short: 'v', default: false },
24
+ },
25
+ });
26
+
27
+ if (positionals.length > 1) {
28
+ throw new Error(`Too many arguments. Usage: ${USAGE}`);
29
+ }
30
+
31
+ const databases = Object.values(DATABASES);
32
+ if (values.db !== undefined && !databases.includes(values.db)) {
33
+ throw new Error(`Invalid --db value "${values.db}". Choose one of: ${databases.join(', ')}`);
34
+ }
35
+
36
+ return {
37
+ projectName: positionals[0],
38
+ db: values.db,
39
+ yes: values.yes,
40
+ help: values.help,
41
+ version: values.version,
42
+ };
43
+ }
44
+
45
+ export async function run(argv = process.argv.slice(2)) {
46
+ const args = parseCliArgs(argv);
47
+
48
+ if (args.help) {
49
+ logger.info(`Usage: ${USAGE}`);
50
+ return;
51
+ }
52
+ if (args.version) {
53
+ const { version } = createRequire(import.meta.url)('../package.json');
54
+ process.stdout.write(`${version}\n`);
55
+ return;
56
+ }
57
+
58
+ if (args.yes && !args.projectName) {
59
+ throw new Error('Project name is required when using --yes.');
60
+ }
61
+ if (args.projectName !== undefined) assertValidProjectName(args.projectName);
62
+
63
+ const options = await askOptions(args);
64
+ if (!options) return; // user cancelled: exit 0
65
+
66
+ assertValidProjectName(options.projectName);
67
+
68
+ const targetDir = path.resolve(process.cwd(), options.projectName);
69
+ const name = path.basename(options.projectName);
70
+ await generateProject({
71
+ projectName: name,
72
+ db: options.db,
73
+ targetDir,
74
+ displayName: options.projectName,
75
+ });
76
+
77
+ logger.success(`Created ${name}`);
78
+ const steps = [
79
+ `cd ${shellQuote(options.projectName)}`,
80
+ 'cp .env.example .env',
81
+ 'npm install',
82
+ // --wait returns once the database health check passes, so the next step can connect.
83
+ 'docker compose up -d --wait db',
84
+ ...(options.db === DATABASES.POSTGRES ? ['npm run db:deploy'] : []),
85
+ 'npm run dev',
86
+ ];
87
+ logger.info('Next steps:');
88
+ for (const step of steps) logger.info(` ${step}`);
89
+ }
package/src/prompts.js ADDED
@@ -0,0 +1,43 @@
1
+ import * as clack from '@clack/prompts';
2
+ import { DATABASES, DEFAULT_DATABASE } from './constants.js';
3
+ import { validateProjectName } from './utils/validateProjectName.js';
4
+
5
+ export async function askOptions({ projectName, db, yes }) {
6
+ if (yes) {
7
+ return { projectName, db: db ?? DEFAULT_DATABASE };
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
+ return { projectName: name, db: database };
43
+ }
@@ -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
+ }
@@ -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"]