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.
- package/CHANGELOG.md +35 -0
- package/LICENSE +21 -0
- package/README.md +125 -2
- package/bin/cli.js +8 -0
- package/package.json +76 -4
- package/src/constants.js +29 -0
- package/src/generator.js +142 -0
- package/src/index.js +99 -0
- package/src/prompts.js +59 -0
- package/src/utils/fs.js +36 -0
- package/src/utils/logger.js +8 -0
- package/src/utils/packageJson.js +16 -0
- package/src/utils/validateProjectName.js +19 -0
- package/templates/base/Dockerfile +22 -0
- package/templates/base/README.md +108 -0
- package/templates/base/_dockerignore +16 -0
- package/templates/base/_env.example +25 -0
- package/templates/base/_gitignore +5 -0
- package/templates/base/_husky/pre-commit +1 -0
- package/templates/base/_prettierignore +5 -0
- package/templates/base/_prettierrc +1 -0
- package/templates/base/package.json +62 -0
- package/templates/base/scripts/docker-entrypoint.sh +9 -0
- 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 +23 -0
- package/templates/databases/mongodb/_github/workflows/ci.yml +29 -0
- package/templates/databases/mongodb/docker-compose.yml +30 -0
- package/templates/databases/mongodb/env.part +2 -0
- package/templates/databases/mongodb/package.part.json +4 -0
- package/templates/databases/mongodb/src/database/connection.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 +31 -0
- package/templates/databases/postgres/_github/workflows/ci.yml +46 -0
- package/templates/databases/postgres/docker-compose.yml +34 -0
- package/templates/databases/postgres/env.part +2 -0
- package/templates/databases/postgres/package.part.json +15 -0
- package/templates/databases/postgres/prisma/migrations/20261030073256_init/migration.sql +39 -0
- package/templates/databases/postgres/prisma/migrations/migration_lock.toml +3 -0
- package/templates/databases/postgres/prisma/schema.prisma +39 -0
- package/templates/databases/postgres/prisma.config.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/js/eslint.config.js +23 -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/base/scripts/generate-postman.js +70 -0
- package/templates-js/base/scripts/seed-admin.js +61 -0
- package/templates-js/base/src/app.js +46 -0
- package/templates-js/base/src/config/env.js +15 -0
- package/templates-js/base/src/config/env.schema.js +85 -0
- package/templates-js/base/src/config/logger.js +20 -0
- package/templates-js/base/src/constants/examples.js +3 -0
- package/templates-js/base/src/constants/roles.js +2 -0
- package/templates-js/base/src/constants/user.rules.js +16 -0
- package/templates-js/base/src/docs/openapi.js +26 -0
- package/templates-js/base/src/docs/openapi.registry.js +81 -0
- package/templates-js/base/src/docs/paths/auth.paths.js +87 -0
- package/templates-js/base/src/docs/paths/user.paths.js +87 -0
- package/templates-js/base/src/middlewares/authenticate.js +19 -0
- package/templates-js/base/src/middlewares/authorize.js +11 -0
- package/templates-js/base/src/middlewares/errorHandler.js +35 -0
- package/templates-js/base/src/middlewares/notFound.js +5 -0
- package/templates-js/base/src/middlewares/rateLimiter.js +20 -0
- package/templates-js/base/src/middlewares/validate.js +31 -0
- package/templates-js/base/src/modules/auth/auth.controller.js +40 -0
- package/templates-js/base/src/modules/auth/auth.cookie.js +21 -0
- package/templates-js/base/src/modules/auth/auth.routes.js +12 -0
- package/templates-js/base/src/modules/auth/auth.service.js +79 -0
- package/templates-js/base/src/modules/auth/auth.validation.js +41 -0
- package/templates-js/base/src/modules/user/user.controller.js +21 -0
- package/templates-js/base/src/modules/user/user.routes.js +22 -0
- package/templates-js/base/src/modules/user/user.service.js +19 -0
- package/templates-js/base/src/modules/user/user.validation.js +24 -0
- package/templates-js/base/src/routes/docs.routes.js +16 -0
- package/templates-js/base/src/routes/health.routes.js +17 -0
- package/templates-js/base/src/routes/index.js +13 -0
- package/templates-js/base/src/server.js +50 -0
- package/templates-js/base/src/utils/ApiError.js +32 -0
- package/templates-js/base/src/utils/apiResponse.js +8 -0
- package/templates-js/base/src/utils/password.js +14 -0
- package/templates-js/base/src/utils/token.js +46 -0
- package/templates-js/base/src/utils/zod.js +5 -0
- package/templates-js/base/tests/app.test.js +67 -0
- package/templates-js/base/tests/auth.test.js +185 -0
- package/templates-js/base/tests/authenticate.test.js +61 -0
- package/templates-js/base/tests/docs.test.js +115 -0
- package/templates-js/base/tests/env.test.js +94 -0
- package/templates-js/base/tests/health.test.js +21 -0
- package/templates-js/base/tests/helpers/auth.helper.js +41 -0
- package/templates-js/base/tests/password.test.js +18 -0
- package/templates-js/base/tests/postman.test.js +31 -0
- package/templates-js/base/tests/rateLimiter.test.js +27 -0
- package/templates-js/base/tests/seedAdmin.test.js +42 -0
- package/templates-js/base/tests/token.test.js +69 -0
- package/templates-js/base/tests/trustProxy.test.js +24 -0
- package/templates-js/base/tests/user.repository.test.js +210 -0
- package/templates-js/base/tests/user.test.js +144 -0
- package/templates-js/base/tests/validate.test.js +35 -0
- package/templates-js/base/tests/validation.test.js +61 -0
- package/templates-js/base/vitest.config.js +16 -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/mongodb/src/database/connection.js +39 -0
- package/templates-js/databases/mongodb/src/database/env.schema.js +3 -0
- package/templates-js/databases/mongodb/src/database/id.schema.js +3 -0
- package/templates-js/databases/mongodb/src/database/models/refreshToken.model.js +15 -0
- package/templates-js/databases/mongodb/src/database/models/user.model.js +41 -0
- package/templates-js/databases/mongodb/src/modules/user/user.repository.js +68 -0
- package/templates-js/databases/mongodb/tests/globalSetup.js +13 -0
- package/templates-js/databases/mongodb/tests/setup.js +17 -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-js/databases/postgres/prisma.config.js +14 -0
- package/templates-js/databases/postgres/src/database/connection.js +61 -0
- package/templates-js/databases/postgres/src/database/env.schema.js +3 -0
- package/templates-js/databases/postgres/src/database/id.schema.js +3 -0
- package/templates-js/databases/postgres/src/database/prisma.js +9 -0
- package/templates-js/databases/postgres/src/modules/user/user.repository.js +88 -0
- package/templates-js/databases/postgres/tests/connection.test.js +17 -0
- package/templates-js/databases/postgres/tests/globalSetup.js +60 -0
- package/templates-js/databases/postgres/tests/prismaSchema.test.js +27 -0
- package/templates-js/databases/postgres/tests/setup.js +15 -0
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { execSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { parseEnv } from 'node:util';
|
|
4
|
+
import pg from 'pg';
|
|
5
|
+
|
|
6
|
+
type Errno = NodeJS.ErrnoException | null | undefined;
|
|
7
|
+
|
|
8
|
+
const DEFAULT_URL = 'postgresql://postgres:postgres@localhost:5432/app';
|
|
9
|
+
const ENV_FILE = new URL('../.env', import.meta.url);
|
|
10
|
+
const NOT_RUNNING_MESSAGE = `Cannot reach Postgres. Start it first: docker compose up -d --wait db
|
|
11
|
+
(or set DATABASE_URL to a running server).`;
|
|
12
|
+
|
|
13
|
+
// A real environment variable wins, then DATABASE_URL from .env. Only that one
|
|
14
|
+
// variable is read, so the rest of .env cannot change the test setup.
|
|
15
|
+
function databaseUrl() {
|
|
16
|
+
if (process.env.DATABASE_URL) return process.env.DATABASE_URL;
|
|
17
|
+
if (existsSync(ENV_FILE)) {
|
|
18
|
+
const fromFile = parseEnv(readFileSync(ENV_FILE, 'utf8')).DATABASE_URL;
|
|
19
|
+
if (fromFile) return fromFile;
|
|
20
|
+
}
|
|
21
|
+
return DEFAULT_URL;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function exitNotRunning() {
|
|
25
|
+
console.error(NOT_RUNNING_MESSAGE);
|
|
26
|
+
process.exit(1);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Creates `<db>_test` on the same server if needed, points DATABASE_URL at it, and applies migrations.
|
|
30
|
+
export async function setup() {
|
|
31
|
+
const url = new URL(databaseUrl());
|
|
32
|
+
const testDatabase = `${url.pathname.slice(1).replace(/_test$/, '')}_test`;
|
|
33
|
+
|
|
34
|
+
const admin = new URL(url);
|
|
35
|
+
admin.pathname = '/postgres';
|
|
36
|
+
const client = new pg.Client({ connectionString: admin.toString() });
|
|
37
|
+
try {
|
|
38
|
+
await client.connect();
|
|
39
|
+
const { rowCount } = await client.query('SELECT 1 FROM pg_database WHERE datname = $1', [
|
|
40
|
+
testDatabase,
|
|
41
|
+
]);
|
|
42
|
+
if (rowCount === 0) await client.query(`CREATE DATABASE "${testDatabase}"`);
|
|
43
|
+
} catch (err) {
|
|
44
|
+
if (
|
|
45
|
+
(err as Errno)?.code === 'ECONNREFUSED' ||
|
|
46
|
+
(err as Errno)?.code === 'ENOTFOUND' ||
|
|
47
|
+
(err as Errno)?.code === 'ETIMEDOUT'
|
|
48
|
+
) {
|
|
49
|
+
exitNotRunning();
|
|
50
|
+
}
|
|
51
|
+
if (err instanceof AggregateError) exitNotRunning();
|
|
52
|
+
throw err;
|
|
53
|
+
} finally {
|
|
54
|
+
await client.end().catch(() => {});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
url.pathname = `/${testDatabase}`;
|
|
58
|
+
process.env.DATABASE_URL = url.toString();
|
|
59
|
+
execSync('npx prisma migrate deploy', {
|
|
60
|
+
stdio: 'pipe',
|
|
61
|
+
env: process.env,
|
|
62
|
+
cwd: new URL('..', import.meta.url),
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function teardown() {}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { describe, expect, it } from 'vitest';
|
|
3
|
+
import { ROLE_VALUES } from '../src/constants/roles.ts';
|
|
4
|
+
import { USER_RULES } from '../src/constants/user.rules.ts';
|
|
5
|
+
|
|
6
|
+
// Prisma's schema cannot import JS, so this guards against the limits drifting apart.
|
|
7
|
+
const schema = readFileSync(new URL('../prisma/schema.prisma', import.meta.url), 'utf8');
|
|
8
|
+
|
|
9
|
+
describe('prisma schema', () => {
|
|
10
|
+
it('uses the name length from user.rules.ts', () => {
|
|
11
|
+
expect(schema).toMatch(
|
|
12
|
+
new RegExp(String.raw`\bname\s+String\s+@db\.VarChar\(${USER_RULES.NAME.MAX}\)`),
|
|
13
|
+
);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it('uses the email length from user.rules.ts and makes it unique', () => {
|
|
17
|
+
expect(schema).toMatch(
|
|
18
|
+
new RegExp(String.raw`\bemail\s+String\s+@unique\s+@db\.VarChar\(${USER_RULES.EMAIL.MAX}\)`),
|
|
19
|
+
);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it('has a Role enum equal to ROLE_VALUES', () => {
|
|
23
|
+
const body = schema.match(/enum\s+Role\s*\{([^}]*)\}/)?.[1] ?? '';
|
|
24
|
+
const values = body.split(/\s+/).filter(Boolean);
|
|
25
|
+
expect(values).toEqual([...ROLE_VALUES]);
|
|
26
|
+
});
|
|
27
|
+
});
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { afterAll, afterEach, beforeAll } from 'vitest';
|
|
2
|
+
import { connectDatabase, disconnectDatabase } from '../src/database/connection.ts';
|
|
3
|
+
import { prisma } from '../src/database/prisma.ts';
|
|
4
|
+
|
|
5
|
+
beforeAll(async () => {
|
|
6
|
+
await connectDatabase();
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
afterEach(async () => {
|
|
10
|
+
await prisma.$executeRawUnsafe('TRUNCATE users, refresh_tokens CASCADE');
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
afterAll(async () => {
|
|
14
|
+
await disconnectDatabase();
|
|
15
|
+
});
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import js from '@eslint/js';
|
|
2
|
+
import globals from 'globals';
|
|
3
|
+
import prettier from 'eslint-config-prettier';
|
|
4
|
+
|
|
5
|
+
export default [
|
|
6
|
+
{
|
|
7
|
+
ignores: ['node_modules', 'coverage', 'prisma/migrations', 'src/generated'],
|
|
8
|
+
},
|
|
9
|
+
js.configs.recommended,
|
|
10
|
+
{
|
|
11
|
+
languageOptions: {
|
|
12
|
+
ecmaVersion: 'latest',
|
|
13
|
+
sourceType: 'module',
|
|
14
|
+
globals: globals.node,
|
|
15
|
+
},
|
|
16
|
+
rules: {
|
|
17
|
+
'no-unused-vars': ['error', { argsIgnorePattern: '^_', ignoreRestSiblings: true }],
|
|
18
|
+
'prefer-const': 'error',
|
|
19
|
+
eqeqeq: 'error',
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
prettier,
|
|
23
|
+
];
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import js from '@eslint/js';
|
|
2
|
+
import globals from 'globals';
|
|
3
|
+
import prettier from 'eslint-config-prettier';
|
|
4
|
+
import tseslint from 'typescript-eslint';
|
|
5
|
+
|
|
6
|
+
export default [
|
|
7
|
+
{
|
|
8
|
+
ignores: ['node_modules', 'coverage', 'prisma/migrations', 'src/generated'],
|
|
9
|
+
},
|
|
10
|
+
js.configs.recommended,
|
|
11
|
+
...tseslint.configs.recommended,
|
|
12
|
+
{
|
|
13
|
+
languageOptions: {
|
|
14
|
+
ecmaVersion: 'latest',
|
|
15
|
+
sourceType: 'module',
|
|
16
|
+
globals: globals.node,
|
|
17
|
+
},
|
|
18
|
+
rules: {
|
|
19
|
+
'no-unused-vars': 'off',
|
|
20
|
+
'@typescript-eslint/no-unused-vars': [
|
|
21
|
+
'error',
|
|
22
|
+
{ argsIgnorePattern: '^_', ignoreRestSiblings: true },
|
|
23
|
+
],
|
|
24
|
+
'@typescript-eslint/no-explicit-any': 'error',
|
|
25
|
+
'prefer-const': 'error',
|
|
26
|
+
eqeqeq: 'error',
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
prettier,
|
|
30
|
+
];
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"scripts": {
|
|
3
|
+
"lint": "tsc --noEmit && eslint .",
|
|
4
|
+
"typecheck": "tsc --noEmit"
|
|
5
|
+
},
|
|
6
|
+
"lint-staged": {
|
|
7
|
+
"*.{js,ts}": ["eslint --fix", "prettier --write"],
|
|
8
|
+
"*.{json,md,yml}": ["prettier --write"]
|
|
9
|
+
},
|
|
10
|
+
"devDependencies": {
|
|
11
|
+
"@types/cookie-parser": "^1.4.10",
|
|
12
|
+
"@types/cors": "^2.8.19",
|
|
13
|
+
"@types/express": "^5.0.6",
|
|
14
|
+
"@types/jsonwebtoken": "^9.0.10",
|
|
15
|
+
"@types/node": "^22.20.5",
|
|
16
|
+
"@types/supertest": "^7.2.1",
|
|
17
|
+
"@types/swagger-ui-express": "^4.1.8",
|
|
18
|
+
"typescript": "~6.0.3",
|
|
19
|
+
"typescript-eslint": "^8.73.0"
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "esnext",
|
|
4
|
+
"module": "nodenext",
|
|
5
|
+
"moduleResolution": "nodenext",
|
|
6
|
+
"strict": true,
|
|
7
|
+
"noEmit": true,
|
|
8
|
+
"allowImportingTsExtensions": true,
|
|
9
|
+
"verbatimModuleSyntax": true,
|
|
10
|
+
"erasableSyntaxOnly": true,
|
|
11
|
+
"skipLibCheck": true,
|
|
12
|
+
"types": ["node"]
|
|
13
|
+
},
|
|
14
|
+
"include": ["src", "scripts", "tests", "*.ts"]
|
|
15
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Stage 1: install all dependencies (dev ones are needed for the build step).
|
|
2
|
+
FROM node:24-alpine AS deps
|
|
3
|
+
WORKDIR /app
|
|
4
|
+
COPY package.json package-lock.json ./
|
|
5
|
+
RUN npm ci --ignore-scripts
|
|
6
|
+
|
|
7
|
+
# Stage 2: copy the source, generate the Prisma client (Postgres only), drop dev dependencies.
|
|
8
|
+
FROM deps AS build
|
|
9
|
+
COPY . .
|
|
10
|
+
RUN if [ -f prisma/schema.prisma ]; then npx prisma generate; fi
|
|
11
|
+
RUN npm prune --omit=dev
|
|
12
|
+
|
|
13
|
+
# Stage 3: small runtime image that runs as the non-root "node" user.
|
|
14
|
+
FROM node:24-alpine AS runner
|
|
15
|
+
ENV NODE_ENV=production
|
|
16
|
+
WORKDIR /app
|
|
17
|
+
COPY --from=build --chown=node:node /app ./
|
|
18
|
+
USER node
|
|
19
|
+
EXPOSE 3000
|
|
20
|
+
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
|
21
|
+
CMD wget -qO- http://localhost:3000/health || exit 1
|
|
22
|
+
CMD ["sh", "scripts/docker-entrypoint.sh"]
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# {{projectName}}
|
|
2
|
+
|
|
3
|
+
Express authentication API generated by authkit-api.
|
|
4
|
+
|
|
5
|
+
## What you get
|
|
6
|
+
|
|
7
|
+
- Register, login, refresh and logout with JWT access tokens and rotating refresh tokens (httpOnly cookie)
|
|
8
|
+
- Roles (`user`, `admin`), a `/users/me` endpoint and admin-only user management
|
|
9
|
+
- Validation (Zod), rate limiting, Helmet, CORS, structured logs (pino)
|
|
10
|
+
- Swagger UI, a Postman export, tests (Vitest), ESLint and Prettier
|
|
11
|
+
- A Dockerfile, a compose file and a GitHub Actions workflow
|
|
12
|
+
|
|
13
|
+
{{databaseSection}}
|
|
14
|
+
|
|
15
|
+
## Environment variables
|
|
16
|
+
|
|
17
|
+
Copy `.env.example` to `.env`. The database variable is listed in the Database section above.
|
|
18
|
+
|
|
19
|
+
| Variable | Meaning |
|
|
20
|
+
| ------------------------------------------------- | --------------------------------------------------------------- |
|
|
21
|
+
| `NODE_ENV` | `development`, `test` or `production` |
|
|
22
|
+
| `PORT` | Port the API listens on (default `3000`) |
|
|
23
|
+
| `LOG_LEVEL` | pino log level (default `info`) |
|
|
24
|
+
| `CORS_ORIGIN` | Allowed browser origin |
|
|
25
|
+
| `TRUST_PROXY` | Express `trust proxy`. Set `1` behind one reverse proxy or PaaS |
|
|
26
|
+
| `JWT_ACCESS_SECRET`, `JWT_REFRESH_SECRET` | Two different values of 32+ characters: `openssl rand -hex 32` |
|
|
27
|
+
| `JWT_ACCESS_EXPIRES_IN`, `JWT_REFRESH_EXPIRES_IN` | Token lifetimes, for example `15m` and `7d` |
|
|
28
|
+
| `AUTH_RATE_LIMIT_MAX` | Login/register requests allowed per window |
|
|
29
|
+
| `ADMIN_NAME`, `ADMIN_EMAIL`, `ADMIN_PASSWORD` | Used by `npm run seed:admin` |
|
|
30
|
+
| `API_DOCS_ENABLED` | `true` or `false`. Swagger is off in production by default |
|
|
31
|
+
|
|
32
|
+
## Scripts
|
|
33
|
+
|
|
34
|
+
| Script | Does |
|
|
35
|
+
| ----------------------------------- | ------------------------------------------------------ |
|
|
36
|
+
| `npm run dev` | Start with auto-reload, reading `.env` |
|
|
37
|
+
| `npm start` | Start for production (env from the environment) |
|
|
38
|
+
| `npm test` | Run the tests once (`test:watch`, `test:coverage` too) |
|
|
39
|
+
| `npm run lint` | ESLint (`lint:fix` repairs) |
|
|
40
|
+
| `npm run format` / `format:check` | Prettier write / check |
|
|
41
|
+
| `npm run seed:admin` | Create the first admin |
|
|
42
|
+
| `npm run docs:postman` | Write `postman/collection.json` |
|
|
43
|
+
| `npm run docker:up` / `docker:down` | Start / stop the app and database in Docker |
|
|
44
|
+
|
|
45
|
+
## API
|
|
46
|
+
|
|
47
|
+
All routes are under `/api/v1`. Successful responses look like `{ "success": true, "message": "...", "data": { ... } }`.
|
|
48
|
+
|
|
49
|
+
| Method | Path | Who | Does |
|
|
50
|
+
| ------ | ---------------- | ------ | ------------------------------------------------- |
|
|
51
|
+
| POST | `/auth/register` | all | Create a user |
|
|
52
|
+
| POST | `/auth/login` | all | Get an access token and refresh cookie |
|
|
53
|
+
| POST | `/auth/refresh` | cookie | Rotate the refresh token, new access token |
|
|
54
|
+
| POST | `/auth/logout` | cookie | Revoke the refresh token |
|
|
55
|
+
| GET | `/users/me` | user | Current user |
|
|
56
|
+
| GET | `/users` | admin | List users (`?page=1&limit=20`) |
|
|
57
|
+
| GET | `/users/:id` | admin | One user |
|
|
58
|
+
| DELETE | `/users/:id` | admin | Delete a user |
|
|
59
|
+
| GET | `/health` | all | Liveness and database check (not under `/api/v1`) |
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
curl -X POST http://localhost:3000/api/v1/auth/register \
|
|
63
|
+
-H 'Content-Type: application/json' \
|
|
64
|
+
-d '{"name":"Ada","email":"ada@example.com","password":"Passw0rd123"}'
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## API docs
|
|
68
|
+
|
|
69
|
+
Open <http://localhost:3000/api-docs> (raw JSON at `/api-docs.json`). Click Authorize and paste the access token from login.
|
|
70
|
+
|
|
71
|
+
To use Postman: run `npm run docs:postman`, then in Postman choose Import and pick `postman/collection.json`. The collection saves the access token after you log in.
|
|
72
|
+
|
|
73
|
+
## First admin
|
|
74
|
+
|
|
75
|
+
Set `ADMIN_NAME`, `ADMIN_EMAIL` and `ADMIN_PASSWORD` in `.env`, then run `npm run seed:admin`. The example password from `.env.example` is refused. If that email already exists the user is promoted to admin; an existing password is never changed.
|
|
76
|
+
|
|
77
|
+
## Add a field to the user
|
|
78
|
+
|
|
79
|
+
Example: a `phone` number. Touch these files:
|
|
80
|
+
|
|
81
|
+
1. `src/constants/user.rules.js`: add the limits (for example `PHONE: { MAX: 20 }`).
|
|
82
|
+
2. `src/modules/auth/auth.validation.js`: add the field to `registerSchema`.
|
|
83
|
+
3. `src/modules/auth/auth.service.js` and the repository `create`: pass the field through.
|
|
84
|
+
4. The database files: see "Adding a user field" in the Database section above.
|
|
85
|
+
5. `src/docs/openapi.registry.js`: add the field to `PublicUser` so the docs stay correct.
|
|
86
|
+
6. Add a test in `tests/user.test.js`.
|
|
87
|
+
|
|
88
|
+
## Docker
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
cp .env.example .env
|
|
92
|
+
# Docker runs in production mode, which refuses the example secrets.
|
|
93
|
+
# In .env, replace the existing JWT_ACCESS_SECRET= and JWT_REFRESH_SECRET= values
|
|
94
|
+
# with two different outputs of:
|
|
95
|
+
openssl rand -base64 48
|
|
96
|
+
npm run docker:up # build and start the app and the database
|
|
97
|
+
npm run docker:down # stop them
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
The app is then on <http://localhost:3000>. The container runs as the non-root `node` user, starts in production mode (so `/api-docs` is off) and has a health check on `/health`. If port 3000 is taken, run `PORT=3001 npm run docker:up`: this changes only the host port, the app listens on 3000 inside the container. For the database port, see the Database section above.
|
|
101
|
+
|
|
102
|
+
The GitHub Actions workflow in `.github/workflows/ci.yml` lints, checks formatting, tests and builds the image on every push. It needs `package-lock.json` committed. It does not push the image anywhere; to publish one, add a `docker/login-action` step and set `push: true` in `docker/build-push-action`.
|
|
103
|
+
|
|
104
|
+
## Notes
|
|
105
|
+
|
|
106
|
+
- Logout revokes the refresh token, but an access token already issued stays valid until it expires (`JWT_ACCESS_EXPIRES_IN`, 15 minutes by default). That is the trade-off of stateless access tokens. Keep them short.
|
|
107
|
+
- Serialize refresh calls in your frontend; parallel refreshes with the same cookie are treated as token reuse and log the user out.
|
|
108
|
+
- Node.js 22.18 or newer is required.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# {{projectName}} environment. Copy to .env and adjust.
|
|
2
|
+
NODE_ENV=development
|
|
3
|
+
PORT=3000
|
|
4
|
+
LOG_LEVEL=info
|
|
5
|
+
CORS_ORIGIN=http://localhost:5173
|
|
6
|
+
# Behind one reverse proxy or a PaaS (Render, Fly, Heroku...) set 1, so rate limits see the client IP.
|
|
7
|
+
# Also accepts true/false, a hop count, or names/CIDRs such as loopback,10.0.0.0/8. Unset: off.
|
|
8
|
+
# TRUST_PROXY=1
|
|
9
|
+
|
|
10
|
+
# JWT secrets must be at least 32 characters. Generate with: openssl rand -hex 32
|
|
11
|
+
JWT_ACCESS_SECRET=change-me-access-secret-at-least-32-chars
|
|
12
|
+
JWT_REFRESH_SECRET=change-me-refresh-secret-at-least-32-chars
|
|
13
|
+
JWT_ACCESS_EXPIRES_IN=15m
|
|
14
|
+
JWT_REFRESH_EXPIRES_IN=7d
|
|
15
|
+
|
|
16
|
+
# Rate limit for auth endpoints (requests per window)
|
|
17
|
+
AUTH_RATE_LIMIT_MAX=10
|
|
18
|
+
|
|
19
|
+
# Optional admin seed
|
|
20
|
+
ADMIN_NAME=Admin
|
|
21
|
+
ADMIN_EMAIL=admin@example.com
|
|
22
|
+
ADMIN_PASSWORD=ChangeMe123!
|
|
23
|
+
|
|
24
|
+
# Swagger UI at /api-docs; disabled in production by default
|
|
25
|
+
# API_DOCS_ENABLED=true
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
npx lint-staged
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{ "singleQuote": true, "semi": true, "trailingComma": "all", "printWidth": 100 }
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "authkit-api-template",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"engines": {
|
|
7
|
+
"node": ">=22.18"
|
|
8
|
+
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"dev": "node --watch --env-file=.env src/server.js",
|
|
11
|
+
"start": "node src/server.js",
|
|
12
|
+
"seed:admin": "node --env-file=.env scripts/seed-admin.js",
|
|
13
|
+
"test": "vitest run",
|
|
14
|
+
"test:watch": "vitest",
|
|
15
|
+
"test:coverage": "vitest run --coverage",
|
|
16
|
+
"lint": "eslint .",
|
|
17
|
+
"lint:fix": "eslint . --fix",
|
|
18
|
+
"format": "prettier --write .",
|
|
19
|
+
"format:check": "prettier --check .",
|
|
20
|
+
"prepare": "husky || true",
|
|
21
|
+
"docs:postman": "node --env-file-if-exists=.env scripts/generate-postman.js",
|
|
22
|
+
"docker:up": "docker compose up -d --build",
|
|
23
|
+
"docker:down": "docker compose down"
|
|
24
|
+
},
|
|
25
|
+
"lint-staged": {
|
|
26
|
+
"*.js": [
|
|
27
|
+
"eslint --fix",
|
|
28
|
+
"prettier --write"
|
|
29
|
+
],
|
|
30
|
+
"*.{json,md,yml}": [
|
|
31
|
+
"prettier --write"
|
|
32
|
+
]
|
|
33
|
+
},
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"@asteasolutions/zod-to-openapi": "^9.1.0",
|
|
36
|
+
"argon2": "^0.45.1",
|
|
37
|
+
"cookie-parser": "^1.4.7",
|
|
38
|
+
"cors": "^2.8.6",
|
|
39
|
+
"express": "^5.3.0",
|
|
40
|
+
"express-rate-limit": "^8.7.2",
|
|
41
|
+
"helmet": "^8.3.0",
|
|
42
|
+
"jsonwebtoken": "^9.0.3",
|
|
43
|
+
"pino": "^10.4.0",
|
|
44
|
+
"pino-http": "^11.0.0",
|
|
45
|
+
"swagger-ui-express": "^5.0.1",
|
|
46
|
+
"zod": "^4.6.7"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@eslint/js": "^10.0.1",
|
|
50
|
+
"@vitest/coverage-v8": "^5.0.5",
|
|
51
|
+
"eslint": "^10.13.0",
|
|
52
|
+
"eslint-config-prettier": "^10.1.8",
|
|
53
|
+
"globals": "^17.13.0",
|
|
54
|
+
"husky": "^9.1.7",
|
|
55
|
+
"lint-staged": "^17.6.0",
|
|
56
|
+
"openapi-to-postmanv2": "^6.4.2",
|
|
57
|
+
"pino-pretty": "^13.2.0",
|
|
58
|
+
"prettier": "^3.9.10",
|
|
59
|
+
"supertest": "^7.3.1",
|
|
60
|
+
"vitest": "^5.0.5"
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import Converter from 'openapi-to-postmanv2';
|
|
4
|
+
import { buildOpenApiDocument } from '../src/docs/openapi.js';
|
|
5
|
+
|
|
6
|
+
const BASE_URL = 'http://localhost:3000/api/v1';
|
|
7
|
+
const TOKEN_SCRIPT = [
|
|
8
|
+
'const json = pm.response.json();',
|
|
9
|
+
"if (json?.data?.accessToken) pm.collectionVariables.set('accessToken', json.data.accessToken);",
|
|
10
|
+
];
|
|
11
|
+
const PUBLIC_PATHS = new Set(['register', 'login', 'refresh', 'logout']);
|
|
12
|
+
const TOKEN_PATHS = new Set(['login', 'refresh']);
|
|
13
|
+
|
|
14
|
+
function convert(document) {
|
|
15
|
+
return new Promise((resolve, reject) => {
|
|
16
|
+
Converter.convert({ type: 'json', data: document }, {}, (err, result) => {
|
|
17
|
+
if (err) return reject(err);
|
|
18
|
+
if (!result.result) return reject(new Error(result.reason));
|
|
19
|
+
resolve(result.output[0].data);
|
|
20
|
+
});
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function* walk(items) {
|
|
25
|
+
for (const item of items ?? []) {
|
|
26
|
+
if (item.request) yield item;
|
|
27
|
+
yield* walk(item.item);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function lastSegment(item) {
|
|
32
|
+
const path = item.request.url?.path ?? [];
|
|
33
|
+
return path[path.length - 1];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function buildPostmanCollection() {
|
|
37
|
+
const collection = await convert(buildOpenApiDocument());
|
|
38
|
+
|
|
39
|
+
collection.variable = [
|
|
40
|
+
...(collection.variable ?? []).filter((v) => v.key !== 'baseUrl'),
|
|
41
|
+
{ key: 'baseUrl', value: BASE_URL, type: 'string' },
|
|
42
|
+
{ key: 'accessToken', value: '', type: 'string' },
|
|
43
|
+
];
|
|
44
|
+
collection.auth = {
|
|
45
|
+
type: 'bearer',
|
|
46
|
+
bearer: [{ key: 'token', value: '{{accessToken}}', type: 'string' }],
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
for (const item of walk(collection.item)) {
|
|
50
|
+
const name = lastSegment(item);
|
|
51
|
+
// Secured requests inherit the collection bearer auth. Public ones send no token.
|
|
52
|
+
if (PUBLIC_PATHS.has(name)) item.request.auth = { type: 'noauth' };
|
|
53
|
+
else delete item.request.auth;
|
|
54
|
+
if (TOKEN_PATHS.has(name)) {
|
|
55
|
+
item.event = [
|
|
56
|
+
...(item.event ?? []),
|
|
57
|
+
{ listen: 'test', script: { type: 'text/javascript', exec: TOKEN_SCRIPT } },
|
|
58
|
+
];
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return collection;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
65
|
+
const outDir = new URL('../postman/', import.meta.url);
|
|
66
|
+
const collection = await buildPostmanCollection();
|
|
67
|
+
mkdirSync(outDir, { recursive: true });
|
|
68
|
+
writeFileSync(new URL('collection.json', outDir), `${JSON.stringify(collection, null, 2)}\n`);
|
|
69
|
+
console.log('Wrote postman/collection.json (import it into Postman).');
|
|
70
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { pathToFileURL } from 'node:url';
|
|
2
|
+
import { env } from '../src/config/env.js';
|
|
3
|
+
import { logger } from '../src/config/logger.js';
|
|
4
|
+
import { EXAMPLE_ADMIN_PASSWORD } from '../src/constants/examples.js';
|
|
5
|
+
import { ROLES } from '../src/constants/roles.js';
|
|
6
|
+
import { connectDatabase, disconnectDatabase } from '../src/database/connection.js';
|
|
7
|
+
import { registerSchema } from '../src/modules/auth/auth.validation.js';
|
|
8
|
+
import * as userRepository from '../src/modules/user/user.repository.js';
|
|
9
|
+
import { hashPassword } from '../src/utils/password.js';
|
|
10
|
+
|
|
11
|
+
// Creates the admin, or promotes the existing user with that email. The password
|
|
12
|
+
// of an existing user is never changed.
|
|
13
|
+
export async function seedAdmin({ name, email, password }) {
|
|
14
|
+
// Everyone can read .env.example, so an admin with that password is an open door.
|
|
15
|
+
if (password === EXAMPLE_ADMIN_PASSWORD) {
|
|
16
|
+
throw new Error('ADMIN_PASSWORD still has the example value; set a real password in .env');
|
|
17
|
+
}
|
|
18
|
+
const existing = await userRepository.findByEmail(email);
|
|
19
|
+
if (!existing) {
|
|
20
|
+
const user = await userRepository.create({
|
|
21
|
+
name,
|
|
22
|
+
email,
|
|
23
|
+
password: await hashPassword(password),
|
|
24
|
+
role: ROLES.ADMIN,
|
|
25
|
+
});
|
|
26
|
+
return { action: 'created', user };
|
|
27
|
+
}
|
|
28
|
+
if (existing.role === ROLES.ADMIN) return { action: 'unchanged', user: existing };
|
|
29
|
+
const user = await userRepository.updateRole(existing.id, ROLES.ADMIN);
|
|
30
|
+
return { action: 'promoted', user };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function main() {
|
|
34
|
+
const parsed = registerSchema.shape.body.safeParse({
|
|
35
|
+
name: env.ADMIN_NAME,
|
|
36
|
+
email: env.ADMIN_EMAIL,
|
|
37
|
+
password: env.ADMIN_PASSWORD,
|
|
38
|
+
});
|
|
39
|
+
if (!parsed.success) {
|
|
40
|
+
for (const issue of parsed.error.issues) {
|
|
41
|
+
logger.error(`${issue.path.join('.')}: ${issue.message}`);
|
|
42
|
+
}
|
|
43
|
+
process.exit(1);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
await connectDatabase();
|
|
47
|
+
try {
|
|
48
|
+
const { action, user } = await seedAdmin(parsed.data);
|
|
49
|
+
logger.info(`Admin ${action}: ${user.email}`);
|
|
50
|
+
} finally {
|
|
51
|
+
await disconnectDatabase();
|
|
52
|
+
}
|
|
53
|
+
process.exit(0);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
57
|
+
main().catch((err) => {
|
|
58
|
+
logger.error({ err }, `Seeding admin failed: ${err.message}`);
|
|
59
|
+
process.exit(1);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import cookieParser from 'cookie-parser';
|
|
3
|
+
import cors from 'cors';
|
|
4
|
+
import express from 'express';
|
|
5
|
+
import helmet from 'helmet';
|
|
6
|
+
import { pinoHttp } from 'pino-http';
|
|
7
|
+
import { env } from './config/env.js';
|
|
8
|
+
import { logger } from './config/logger.js';
|
|
9
|
+
import { errorHandler } from './middlewares/errorHandler.js';
|
|
10
|
+
import { notFound } from './middlewares/notFound.js';
|
|
11
|
+
import { docsRouter } from './routes/docs.routes.js';
|
|
12
|
+
import { healthRouter } from './routes/health.routes.js';
|
|
13
|
+
import { apiRouter } from './routes/index.js';
|
|
14
|
+
|
|
15
|
+
export function createApp() {
|
|
16
|
+
const app = express();
|
|
17
|
+
// Behind a reverse proxy or PaaS, req.ip (and so the rate limiter) needs this.
|
|
18
|
+
if (env.TRUST_PROXY !== undefined) app.set('trust proxy', env.TRUST_PROXY);
|
|
19
|
+
|
|
20
|
+
// Before the global helmet: Swagger UI needs a relaxed CSP, the API keeps the strict one.
|
|
21
|
+
if (env.API_DOCS_ENABLED) app.use(docsRouter);
|
|
22
|
+
|
|
23
|
+
app.use(helmet());
|
|
24
|
+
app.use(cors({ origin: env.CORS_ORIGIN, credentials: true }));
|
|
25
|
+
// Before the body parser, so parse errors are logged with a request id.
|
|
26
|
+
app.use(
|
|
27
|
+
pinoHttp({
|
|
28
|
+
logger,
|
|
29
|
+
genReqId: (req, res) => {
|
|
30
|
+
const id = randomUUID();
|
|
31
|
+
res.setHeader('x-request-id', id);
|
|
32
|
+
return id;
|
|
33
|
+
},
|
|
34
|
+
}),
|
|
35
|
+
);
|
|
36
|
+
app.use(express.json({ limit: '10kb' }));
|
|
37
|
+
app.use(cookieParser());
|
|
38
|
+
|
|
39
|
+
app.use('/health', healthRouter);
|
|
40
|
+
app.use('/api/v1', apiRouter);
|
|
41
|
+
|
|
42
|
+
app.use(notFound);
|
|
43
|
+
app.use(errorHandler);
|
|
44
|
+
|
|
45
|
+
return app;
|
|
46
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { envSchema } from './env.schema.js';
|
|
2
|
+
|
|
3
|
+
function loadEnv() {
|
|
4
|
+
const result = envSchema.safeParse(process.env);
|
|
5
|
+
if (!result.success) {
|
|
6
|
+
console.error('Invalid environment variables:');
|
|
7
|
+
for (const issue of result.error.issues) {
|
|
8
|
+
console.error(` ${issue.path.join('.')}: ${issue.message}`);
|
|
9
|
+
}
|
|
10
|
+
process.exit(1);
|
|
11
|
+
}
|
|
12
|
+
return Object.freeze(result.data);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const env = loadEnv();
|