authkit-api 1.0.0 → 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.
- package/CHANGELOG.md +10 -1
- package/README.md +21 -5
- package/package.json +12 -5
- package/src/constants.js +5 -0
- package/src/generator.js +37 -7
- package/src/index.js +12 -2
- package/src/prompts.js +20 -4
- package/templates/base/README.md +5 -5
- package/templates/base/package.json +4 -4
- package/templates/base/scripts/docker-entrypoint.sh +1 -1
- package/templates/base/scripts/generate-postman.ts +102 -0
- package/templates/base/scripts/seed-admin.ts +62 -0
- package/templates/base/src/app.ts +46 -0
- package/templates/base/src/config/env.schema.ts +85 -0
- package/templates/base/src/config/env.ts +15 -0
- package/templates/base/src/config/logger.ts +20 -0
- package/templates/base/src/constants/examples.ts +3 -0
- package/templates/base/src/constants/roles.ts +4 -0
- package/templates/base/src/constants/user.rules.ts +16 -0
- package/templates/base/src/docs/openapi.registry.ts +90 -0
- package/templates/base/src/docs/openapi.ts +36 -0
- package/templates/base/src/docs/paths/auth.paths.ts +88 -0
- package/templates/base/src/docs/paths/user.paths.ts +88 -0
- package/templates/base/src/middlewares/authenticate.ts +20 -0
- package/templates/base/src/middlewares/authorize.ts +13 -0
- package/templates/base/src/middlewares/errorHandler.ts +52 -0
- package/templates/base/src/middlewares/notFound.ts +6 -0
- package/templates/base/src/middlewares/rateLimiter.ts +20 -0
- package/templates/base/src/middlewares/validate.ts +39 -0
- package/templates/base/src/modules/auth/auth.controller.ts +45 -0
- package/templates/base/src/modules/auth/auth.cookie.ts +22 -0
- package/templates/base/src/modules/auth/auth.routes.ts +12 -0
- package/templates/base/src/modules/auth/auth.service.ts +81 -0
- package/templates/base/src/modules/auth/auth.validation.ts +44 -0
- package/templates/base/src/modules/user/user.controller.ts +24 -0
- package/templates/base/src/modules/user/user.routes.ts +22 -0
- package/templates/base/src/modules/user/user.service.ts +57 -0
- package/templates/base/src/modules/user/user.validation.ts +27 -0
- package/templates/base/src/routes/docs.routes.ts +16 -0
- package/templates/base/src/routes/health.routes.ts +17 -0
- package/templates/base/src/routes/index.ts +13 -0
- package/templates/base/src/server.ts +51 -0
- package/templates/base/src/types/express.d.ts +14 -0
- package/templates/base/src/utils/ApiError.ts +35 -0
- package/templates/base/src/utils/apiResponse.ts +24 -0
- package/templates/base/src/utils/password.ts +14 -0
- package/templates/base/src/utils/token.ts +60 -0
- package/templates/base/src/utils/zod.ts +5 -0
- package/templates/base/tests/app.test.ts +67 -0
- package/templates/base/tests/auth.test.ts +194 -0
- package/templates/base/tests/authenticate.test.ts +61 -0
- package/templates/base/tests/docs.test.ts +127 -0
- package/templates/base/tests/env.test.ts +96 -0
- package/templates/base/tests/health.test.ts +21 -0
- package/templates/base/tests/helpers/auth.helper.ts +49 -0
- package/templates/base/tests/password.test.ts +18 -0
- package/templates/base/tests/postman.test.ts +32 -0
- package/templates/base/tests/rateLimiter.test.ts +27 -0
- package/templates/base/tests/seedAdmin.test.ts +42 -0
- package/templates/base/tests/token.test.ts +69 -0
- package/templates/base/tests/trustProxy.test.ts +24 -0
- package/templates/base/tests/user.repository.test.ts +211 -0
- package/templates/base/tests/user.test.ts +145 -0
- package/templates/base/tests/validate.test.ts +42 -0
- package/templates/base/tests/validation.test.ts +62 -0
- package/templates/base/vitest.config.ts +16 -0
- package/templates/databases/mongodb/README.part.md +1 -1
- package/templates/databases/mongodb/src/database/connection.ts +46 -0
- package/templates/databases/mongodb/src/database/env.schema.ts +3 -0
- package/templates/databases/mongodb/src/database/id.schema.ts +3 -0
- package/templates/databases/mongodb/src/database/models/refreshToken.model.ts +24 -0
- package/templates/databases/mongodb/src/database/models/user.model.ts +52 -0
- package/templates/databases/mongodb/src/modules/user/user.repository.ts +91 -0
- package/templates/databases/mongodb/tests/globalSetup.ts +13 -0
- package/templates/databases/mongodb/tests/setup.ts +17 -0
- package/templates/databases/postgres/README.part.md +1 -1
- package/templates/databases/postgres/prisma.config.ts +14 -0
- package/templates/databases/postgres/src/database/connection.ts +72 -0
- package/templates/databases/postgres/src/database/env.schema.ts +3 -0
- package/templates/databases/postgres/src/database/id.schema.ts +3 -0
- package/templates/databases/postgres/src/database/prisma.ts +9 -0
- package/templates/databases/postgres/src/modules/user/user.repository.ts +111 -0
- package/templates/databases/postgres/tests/connection.test.ts +19 -0
- package/templates/databases/postgres/tests/globalSetup.ts +66 -0
- package/templates/databases/postgres/tests/prismaSchema.test.ts +27 -0
- package/templates/databases/postgres/tests/setup.ts +15 -0
- package/templates/languages/ts/eslint.config.js +30 -0
- package/templates/languages/ts/package.part.json +21 -0
- package/templates/languages/ts/tsconfig.json +15 -0
- package/templates-js/base/Dockerfile +22 -0
- package/templates-js/base/README.md +108 -0
- package/templates-js/base/_dockerignore +16 -0
- package/templates-js/base/_env.example +25 -0
- package/templates-js/base/_gitignore +5 -0
- package/templates-js/base/_husky/pre-commit +1 -0
- package/templates-js/base/_prettierignore +5 -0
- package/templates-js/base/_prettierrc +1 -0
- package/templates-js/base/package.json +62 -0
- package/templates-js/base/scripts/docker-entrypoint.sh +9 -0
- package/templates-js/databases/mongodb/README.part.md +23 -0
- package/templates-js/databases/mongodb/_github/workflows/ci.yml +29 -0
- package/templates-js/databases/mongodb/docker-compose.yml +30 -0
- package/templates-js/databases/mongodb/env.part +2 -0
- package/templates-js/databases/mongodb/package.part.json +4 -0
- package/templates-js/databases/postgres/README.part.md +31 -0
- package/templates-js/databases/postgres/_github/workflows/ci.yml +46 -0
- package/templates-js/databases/postgres/docker-compose.yml +34 -0
- package/templates-js/databases/postgres/env.part +2 -0
- package/templates-js/databases/postgres/package.part.json +15 -0
- package/templates-js/databases/postgres/prisma/migrations/20261030073256_init/migration.sql +39 -0
- package/templates-js/databases/postgres/prisma/migrations/migration_lock.toml +3 -0
- package/templates-js/databases/postgres/prisma/schema.prisma +39 -0
- /package/templates/{base → languages/js}/eslint.config.js +0 -0
- /package/{templates → templates-js}/base/scripts/generate-postman.js +0 -0
- /package/{templates → templates-js}/base/scripts/seed-admin.js +0 -0
- /package/{templates → templates-js}/base/src/app.js +0 -0
- /package/{templates → templates-js}/base/src/config/env.js +0 -0
- /package/{templates → templates-js}/base/src/config/env.schema.js +0 -0
- /package/{templates → templates-js}/base/src/config/logger.js +0 -0
- /package/{templates → templates-js}/base/src/constants/examples.js +0 -0
- /package/{templates → templates-js}/base/src/constants/roles.js +0 -0
- /package/{templates → templates-js}/base/src/constants/user.rules.js +0 -0
- /package/{templates → templates-js}/base/src/docs/openapi.js +0 -0
- /package/{templates → templates-js}/base/src/docs/openapi.registry.js +0 -0
- /package/{templates → templates-js}/base/src/docs/paths/auth.paths.js +0 -0
- /package/{templates → templates-js}/base/src/docs/paths/user.paths.js +0 -0
- /package/{templates → templates-js}/base/src/middlewares/authenticate.js +0 -0
- /package/{templates → templates-js}/base/src/middlewares/authorize.js +0 -0
- /package/{templates → templates-js}/base/src/middlewares/errorHandler.js +0 -0
- /package/{templates → templates-js}/base/src/middlewares/notFound.js +0 -0
- /package/{templates → templates-js}/base/src/middlewares/rateLimiter.js +0 -0
- /package/{templates → templates-js}/base/src/middlewares/validate.js +0 -0
- /package/{templates → templates-js}/base/src/modules/auth/auth.controller.js +0 -0
- /package/{templates → templates-js}/base/src/modules/auth/auth.cookie.js +0 -0
- /package/{templates → templates-js}/base/src/modules/auth/auth.routes.js +0 -0
- /package/{templates → templates-js}/base/src/modules/auth/auth.service.js +0 -0
- /package/{templates → templates-js}/base/src/modules/auth/auth.validation.js +0 -0
- /package/{templates → templates-js}/base/src/modules/user/user.controller.js +0 -0
- /package/{templates → templates-js}/base/src/modules/user/user.routes.js +0 -0
- /package/{templates → templates-js}/base/src/modules/user/user.service.js +0 -0
- /package/{templates → templates-js}/base/src/modules/user/user.validation.js +0 -0
- /package/{templates → templates-js}/base/src/routes/docs.routes.js +0 -0
- /package/{templates → templates-js}/base/src/routes/health.routes.js +0 -0
- /package/{templates → templates-js}/base/src/routes/index.js +0 -0
- /package/{templates → templates-js}/base/src/server.js +0 -0
- /package/{templates → templates-js}/base/src/utils/ApiError.js +0 -0
- /package/{templates → templates-js}/base/src/utils/apiResponse.js +0 -0
- /package/{templates → templates-js}/base/src/utils/password.js +0 -0
- /package/{templates → templates-js}/base/src/utils/token.js +0 -0
- /package/{templates → templates-js}/base/src/utils/zod.js +0 -0
- /package/{templates → templates-js}/base/tests/app.test.js +0 -0
- /package/{templates → templates-js}/base/tests/auth.test.js +0 -0
- /package/{templates → templates-js}/base/tests/authenticate.test.js +0 -0
- /package/{templates → templates-js}/base/tests/docs.test.js +0 -0
- /package/{templates → templates-js}/base/tests/env.test.js +0 -0
- /package/{templates → templates-js}/base/tests/health.test.js +0 -0
- /package/{templates → templates-js}/base/tests/helpers/auth.helper.js +0 -0
- /package/{templates → templates-js}/base/tests/password.test.js +0 -0
- /package/{templates → templates-js}/base/tests/postman.test.js +0 -0
- /package/{templates → templates-js}/base/tests/rateLimiter.test.js +0 -0
- /package/{templates → templates-js}/base/tests/seedAdmin.test.js +0 -0
- /package/{templates → templates-js}/base/tests/token.test.js +0 -0
- /package/{templates → templates-js}/base/tests/trustProxy.test.js +0 -0
- /package/{templates → templates-js}/base/tests/user.repository.test.js +0 -0
- /package/{templates → templates-js}/base/tests/user.test.js +0 -0
- /package/{templates → templates-js}/base/tests/validate.test.js +0 -0
- /package/{templates → templates-js}/base/tests/validation.test.js +0 -0
- /package/{templates → templates-js}/base/vitest.config.js +0 -0
- /package/{templates → templates-js}/databases/mongodb/src/database/connection.js +0 -0
- /package/{templates → templates-js}/databases/mongodb/src/database/env.schema.js +0 -0
- /package/{templates → templates-js}/databases/mongodb/src/database/id.schema.js +0 -0
- /package/{templates → templates-js}/databases/mongodb/src/database/models/refreshToken.model.js +0 -0
- /package/{templates → templates-js}/databases/mongodb/src/database/models/user.model.js +0 -0
- /package/{templates → templates-js}/databases/mongodb/src/modules/user/user.repository.js +0 -0
- /package/{templates → templates-js}/databases/mongodb/tests/globalSetup.js +0 -0
- /package/{templates → templates-js}/databases/mongodb/tests/setup.js +0 -0
- /package/{templates → templates-js}/databases/postgres/prisma.config.js +0 -0
- /package/{templates → templates-js}/databases/postgres/src/database/connection.js +0 -0
- /package/{templates → templates-js}/databases/postgres/src/database/env.schema.js +0 -0
- /package/{templates → templates-js}/databases/postgres/src/database/id.schema.js +0 -0
- /package/{templates → templates-js}/databases/postgres/src/database/prisma.js +0 -0
- /package/{templates → templates-js}/databases/postgres/src/modules/user/user.repository.js +0 -0
- /package/{templates → templates-js}/databases/postgres/tests/connection.test.js +0 -0
- /package/{templates → templates-js}/databases/postgres/tests/globalSetup.js +0 -0
- /package/{templates → templates-js}/databases/postgres/tests/prismaSchema.test.js +0 -0
- /package/{templates → templates-js}/databases/postgres/tests/setup.js +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -5,7 +5,16 @@ All notable changes to this project are documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
-
## [
|
|
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.
|
|
9
18
|
|
|
10
19
|
## [1.0.0] - 2026-10-30
|
|
11
20
|
|
package/README.md
CHANGED
|
@@ -9,18 +9,32 @@ npx authkit-api my-app
|
|
|
9
9
|
cd my-app
|
|
10
10
|
```
|
|
11
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
|
+
|
|
12
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.
|
|
13
25
|
|
|
14
26
|
## Flags
|
|
15
27
|
|
|
16
28
|
```bash
|
|
17
|
-
npx authkit-api <project-name> [--db mongodb|postgres] [--yes]
|
|
29
|
+
npx authkit-api <project-name> [--db mongodb|postgres] [--lang js|ts] [--yes]
|
|
18
30
|
```
|
|
19
31
|
|
|
20
32
|
| Flag | Does |
|
|
21
33
|
| ----------------- | ----------------------------------- |
|
|
22
34
|
| `--db mongodb` | Use MongoDB with Mongoose |
|
|
23
35
|
| `--db postgres` | Use PostgreSQL with Prisma |
|
|
36
|
+
| `--lang js` | Plain JavaScript (default) |
|
|
37
|
+
| `--lang ts` | Strict TypeScript, no build step |
|
|
24
38
|
| `--yes`, `-y` | Skip the questions and use defaults |
|
|
25
39
|
| `--version`, `-v` | Print the version |
|
|
26
40
|
| `--help`, `-h` | Show usage |
|
|
@@ -102,9 +116,11 @@ MIT
|
|
|
102
116
|
|
|
103
117
|
## Releasing
|
|
104
118
|
|
|
105
|
-
For maintainers.
|
|
119
|
+
For maintainers. Releases are published to npm automatically from GitHub Actions.
|
|
106
120
|
|
|
107
|
-
1.
|
|
121
|
+
1. Update `CHANGELOG.md`: move the `## [Unreleased]` entries under a new version heading.
|
|
108
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.
|
|
109
|
-
3. Run `
|
|
110
|
-
4.
|
|
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "authkit-api",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Generate an Express authentication API (JWT, roles, MongoDB or PostgreSQL) with one command",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
"bin",
|
|
16
16
|
"src",
|
|
17
17
|
"templates",
|
|
18
|
+
"templates-js",
|
|
18
19
|
"CHANGELOG.md"
|
|
19
20
|
],
|
|
20
21
|
"scripts": {
|
|
@@ -22,17 +23,23 @@
|
|
|
22
23
|
"lint:fix": "eslint . --fix",
|
|
23
24
|
"format": "prettier --write .",
|
|
24
25
|
"format:check": "prettier --check .",
|
|
26
|
+
"build:templates": "node scripts/build-templates.js",
|
|
27
|
+
"pretest": "npm run build:templates",
|
|
25
28
|
"test": "vitest run",
|
|
26
29
|
"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",
|
|
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",
|
|
29
32
|
"prepare": "husky",
|
|
33
|
+
"prepack": "npm run build:templates",
|
|
30
34
|
"e2e:mongo": "bash scripts/e2e.sh mongodb",
|
|
31
|
-
"e2e:pg": "bash scripts/e2e.sh postgres"
|
|
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"
|
|
32
39
|
},
|
|
33
40
|
"lint-staged": {
|
|
34
41
|
"*.js": [
|
|
35
|
-
"eslint --fix",
|
|
42
|
+
"eslint --fix --config eslint.config.js --no-warn-ignored",
|
|
36
43
|
"prettier --write"
|
|
37
44
|
],
|
|
38
45
|
"*.{json,md,yml}": [
|
package/src/constants.js
CHANGED
|
@@ -2,8 +2,13 @@ import { fileURLToPath } from 'node:url';
|
|
|
2
2
|
|
|
3
3
|
export const DATABASES = { MONGODB: 'mongodb', POSTGRES: 'postgres' };
|
|
4
4
|
export const DEFAULT_DATABASE = DATABASES.MONGODB;
|
|
5
|
+
export const LANGUAGES = { JS: 'js', TS: 'ts' };
|
|
6
|
+
export const DEFAULT_LANGUAGE = LANGUAGES.JS;
|
|
5
7
|
|
|
6
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));
|
|
7
12
|
export const PACKAGE_PART_FILE = 'package.part.json';
|
|
8
13
|
// Per-database env vars, appended to the base _env.example.
|
|
9
14
|
export const ENV_PART_FILE = 'env.part';
|
package/src/generator.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import fs from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import {
|
|
4
|
+
DEFAULT_LANGUAGE,
|
|
4
5
|
ENV_EXAMPLE_FILE,
|
|
5
6
|
ENV_PART_FILE,
|
|
7
|
+
JS_TEMPLATES_DIR,
|
|
8
|
+
LANGUAGES,
|
|
6
9
|
PACKAGE_PART_FILE,
|
|
7
10
|
PLACEHOLDER_FILES,
|
|
8
11
|
README_PART_FILE,
|
|
@@ -17,6 +20,15 @@ const pathExists = (p) =>
|
|
|
17
20
|
() => false,
|
|
18
21
|
);
|
|
19
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
|
+
};
|
|
20
32
|
|
|
21
33
|
// Database names allow fewer characters than npm names: "my.app" and "my-app" become "my_app".
|
|
22
34
|
export const toDatabaseName = (projectName) =>
|
|
@@ -72,14 +84,24 @@ async function insertReadmePart(dbDir, targetDir) {
|
|
|
72
84
|
}
|
|
73
85
|
|
|
74
86
|
// `displayName` is the path as the user typed it, used in error messages.
|
|
75
|
-
export async function generateProject({
|
|
87
|
+
export async function generateProject({
|
|
88
|
+
projectName,
|
|
89
|
+
db,
|
|
90
|
+
lang = DEFAULT_LANGUAGE,
|
|
91
|
+
targetDir,
|
|
92
|
+
displayName = projectName,
|
|
93
|
+
}) {
|
|
76
94
|
if (!(await isDirEmpty(targetDir))) {
|
|
77
95
|
throw new Error(`Directory "${displayName}" already exists and is not empty.`);
|
|
78
96
|
}
|
|
79
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
|
+
|
|
80
102
|
const existed = await pathExists(targetDir);
|
|
81
103
|
try {
|
|
82
|
-
await writeProject({ projectName, db, targetDir });
|
|
104
|
+
await writeProject({ projectName, db, lang, targetDir });
|
|
83
105
|
} catch (error) {
|
|
84
106
|
// Leave no half-written project behind. A target that already existed was empty, so only empty it.
|
|
85
107
|
if (existed) {
|
|
@@ -93,16 +115,24 @@ export async function generateProject({ projectName, db, targetDir, displayName
|
|
|
93
115
|
}
|
|
94
116
|
}
|
|
95
117
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
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);
|
|
99
125
|
|
|
100
126
|
await copyDir(baseDir, targetDir, { skip: [] });
|
|
101
127
|
await copyDir(dbDir, targetDir, { skip: [PACKAGE_PART_FILE, ENV_PART_FILE, README_PART_FILE] });
|
|
128
|
+
await copyDir(langDir, targetDir, { skip: [PACKAGE_PART_FILE] });
|
|
102
129
|
|
|
103
130
|
const basePackage = await readJson(path.join(baseDir, 'package.json'));
|
|
104
|
-
const
|
|
105
|
-
|
|
131
|
+
const merged = mergePackageJson(
|
|
132
|
+
mergePackageJson(basePackage, await readPart(dbDir), { name: projectName }),
|
|
133
|
+
await readPart(langDir),
|
|
134
|
+
{ name: projectName },
|
|
135
|
+
);
|
|
106
136
|
await fs.writeFile(path.join(targetDir, 'package.json'), `${JSON.stringify(merged, null, 2)}\n`);
|
|
107
137
|
|
|
108
138
|
await appendEnvPart(dbDir, targetDir);
|
package/src/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
2
|
import { parseArgs } from 'node:util';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
-
import { DATABASES } from './constants.js';
|
|
4
|
+
import { DATABASES, LANGUAGES } from './constants.js';
|
|
5
5
|
import { generateProject } from './generator.js';
|
|
6
6
|
import { askOptions } from './prompts.js';
|
|
7
7
|
import { logger } from './utils/logger.js';
|
|
@@ -10,7 +10,7 @@ import { assertValidProjectName } from './utils/validateProjectName.js';
|
|
|
10
10
|
// Quote a path for the "cd" hint only when the shell would need it.
|
|
11
11
|
const shellQuote = (value) => (/^[\w./@+-]+$/.test(value) ? value : JSON.stringify(value));
|
|
12
12
|
|
|
13
|
-
const USAGE = 'npx authkit-api <project-name> [--db mongodb|postgres] [--yes]';
|
|
13
|
+
const USAGE = 'npx authkit-api <project-name> [--db mongodb|postgres] [--lang js|ts] [--yes]';
|
|
14
14
|
|
|
15
15
|
export function parseCliArgs(argv) {
|
|
16
16
|
const { values, positionals } = parseArgs({
|
|
@@ -18,6 +18,7 @@ export function parseCliArgs(argv) {
|
|
|
18
18
|
allowPositionals: true,
|
|
19
19
|
options: {
|
|
20
20
|
db: { type: 'string' },
|
|
21
|
+
lang: { type: 'string' },
|
|
21
22
|
yes: { type: 'boolean', short: 'y', default: false },
|
|
22
23
|
help: { type: 'boolean', short: 'h', default: false },
|
|
23
24
|
version: { type: 'boolean', short: 'v', default: false },
|
|
@@ -33,9 +34,17 @@ export function parseCliArgs(argv) {
|
|
|
33
34
|
throw new Error(`Invalid --db value "${values.db}". Choose one of: ${databases.join(', ')}`);
|
|
34
35
|
}
|
|
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
|
+
|
|
36
44
|
return {
|
|
37
45
|
projectName: positionals[0],
|
|
38
46
|
db: values.db,
|
|
47
|
+
lang: values.lang,
|
|
39
48
|
yes: values.yes,
|
|
40
49
|
help: values.help,
|
|
41
50
|
version: values.version,
|
|
@@ -70,6 +79,7 @@ export async function run(argv = process.argv.slice(2)) {
|
|
|
70
79
|
await generateProject({
|
|
71
80
|
projectName: name,
|
|
72
81
|
db: options.db,
|
|
82
|
+
lang: options.lang,
|
|
73
83
|
targetDir,
|
|
74
84
|
displayName: options.projectName,
|
|
75
85
|
});
|
package/src/prompts.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import * as clack from '@clack/prompts';
|
|
2
|
-
import { DATABASES, DEFAULT_DATABASE } from './constants.js';
|
|
2
|
+
import { DATABASES, DEFAULT_DATABASE, DEFAULT_LANGUAGE, LANGUAGES } from './constants.js';
|
|
3
3
|
import { validateProjectName } from './utils/validateProjectName.js';
|
|
4
4
|
|
|
5
|
-
export async function askOptions({ projectName, db, yes }) {
|
|
5
|
+
export async function askOptions({ projectName, db, lang, yes }) {
|
|
6
6
|
if (yes) {
|
|
7
|
-
return { projectName, db: db ?? DEFAULT_DATABASE };
|
|
7
|
+
return { projectName, db: db ?? DEFAULT_DATABASE, lang: lang ?? DEFAULT_LANGUAGE };
|
|
8
8
|
}
|
|
9
9
|
|
|
10
10
|
let name = projectName;
|
|
@@ -39,5 +39,21 @@ export async function askOptions({ projectName, db, yes }) {
|
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
-
|
|
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 };
|
|
43
59
|
}
|
package/templates/base/README.md
CHANGED
|
@@ -78,12 +78,12 @@ Set `ADMIN_NAME`, `ADMIN_EMAIL` and `ADMIN_PASSWORD` in `.env`, then run `npm ru
|
|
|
78
78
|
|
|
79
79
|
Example: a `phone` number. Touch these files:
|
|
80
80
|
|
|
81
|
-
1. `src/constants/user.rules.
|
|
82
|
-
2. `src/modules/auth/auth.validation.
|
|
83
|
-
3. `src/modules/auth/auth.service.
|
|
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
84
|
4. The database files: see "Adding a user field" in the Database section above.
|
|
85
|
-
5. `src/docs/openapi.registry.
|
|
86
|
-
6. Add a test in `tests/user.test.
|
|
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
87
|
|
|
88
88
|
## Docker
|
|
89
89
|
|
|
@@ -7,9 +7,9 @@
|
|
|
7
7
|
"node": ">=22.18"
|
|
8
8
|
},
|
|
9
9
|
"scripts": {
|
|
10
|
-
"dev": "node --watch --env-file=.env src/server.
|
|
11
|
-
"start": "node src/server.
|
|
12
|
-
"seed:admin": "node --env-file=.env scripts/seed-admin.
|
|
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
13
|
"test": "vitest run",
|
|
14
14
|
"test:watch": "vitest",
|
|
15
15
|
"test:coverage": "vitest run --coverage",
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"format": "prettier --write .",
|
|
19
19
|
"format:check": "prettier --check .",
|
|
20
20
|
"prepare": "husky || true",
|
|
21
|
-
"docs:postman": "node --env-file-if-exists=.env scripts/generate-postman.
|
|
21
|
+
"docs:postman": "node --env-file-if-exists=.env scripts/generate-postman.ts",
|
|
22
22
|
"docker:up": "docker compose up -d --build",
|
|
23
23
|
"docker:down": "docker compose down"
|
|
24
24
|
},
|
|
@@ -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();
|