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.
- package/CHANGELOG.md +26 -0
- package/LICENSE +21 -0
- package/README.md +109 -2
- package/bin/cli.js +8 -0
- package/package.json +69 -4
- package/src/constants.js +24 -0
- package/src/generator.js +112 -0
- package/src/index.js +89 -0
- package/src/prompts.js +43 -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/eslint.config.js +23 -0
- package/templates/base/package.json +62 -0
- package/templates/base/scripts/docker-entrypoint.sh +9 -0
- package/templates/base/scripts/generate-postman.js +70 -0
- package/templates/base/scripts/seed-admin.js +61 -0
- package/templates/base/src/app.js +46 -0
- package/templates/base/src/config/env.js +15 -0
- package/templates/base/src/config/env.schema.js +85 -0
- package/templates/base/src/config/logger.js +20 -0
- package/templates/base/src/constants/examples.js +3 -0
- package/templates/base/src/constants/roles.js +2 -0
- package/templates/base/src/constants/user.rules.js +16 -0
- package/templates/base/src/docs/openapi.js +26 -0
- package/templates/base/src/docs/openapi.registry.js +81 -0
- package/templates/base/src/docs/paths/auth.paths.js +87 -0
- package/templates/base/src/docs/paths/user.paths.js +87 -0
- package/templates/base/src/middlewares/authenticate.js +19 -0
- package/templates/base/src/middlewares/authorize.js +11 -0
- package/templates/base/src/middlewares/errorHandler.js +35 -0
- package/templates/base/src/middlewares/notFound.js +5 -0
- package/templates/base/src/middlewares/rateLimiter.js +20 -0
- package/templates/base/src/middlewares/validate.js +31 -0
- package/templates/base/src/modules/auth/auth.controller.js +40 -0
- package/templates/base/src/modules/auth/auth.cookie.js +21 -0
- package/templates/base/src/modules/auth/auth.routes.js +12 -0
- package/templates/base/src/modules/auth/auth.service.js +79 -0
- package/templates/base/src/modules/auth/auth.validation.js +41 -0
- package/templates/base/src/modules/user/user.controller.js +21 -0
- package/templates/base/src/modules/user/user.routes.js +22 -0
- package/templates/base/src/modules/user/user.service.js +19 -0
- package/templates/base/src/modules/user/user.validation.js +24 -0
- package/templates/base/src/routes/docs.routes.js +16 -0
- package/templates/base/src/routes/health.routes.js +17 -0
- package/templates/base/src/routes/index.js +13 -0
- package/templates/base/src/server.js +50 -0
- package/templates/base/src/utils/ApiError.js +32 -0
- package/templates/base/src/utils/apiResponse.js +8 -0
- package/templates/base/src/utils/password.js +14 -0
- package/templates/base/src/utils/token.js +46 -0
- package/templates/base/src/utils/zod.js +5 -0
- package/templates/base/tests/app.test.js +67 -0
- package/templates/base/tests/auth.test.js +185 -0
- package/templates/base/tests/authenticate.test.js +61 -0
- package/templates/base/tests/docs.test.js +115 -0
- package/templates/base/tests/env.test.js +94 -0
- package/templates/base/tests/health.test.js +21 -0
- package/templates/base/tests/helpers/auth.helper.js +41 -0
- package/templates/base/tests/password.test.js +18 -0
- package/templates/base/tests/postman.test.js +31 -0
- package/templates/base/tests/rateLimiter.test.js +27 -0
- package/templates/base/tests/seedAdmin.test.js +42 -0
- package/templates/base/tests/token.test.js +69 -0
- package/templates/base/tests/trustProxy.test.js +24 -0
- package/templates/base/tests/user.repository.test.js +210 -0
- package/templates/base/tests/user.test.js +144 -0
- package/templates/base/tests/validate.test.js +35 -0
- package/templates/base/tests/validation.test.js +61 -0
- package/templates/base/vitest.config.js +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.js +39 -0
- package/templates/databases/mongodb/src/database/env.schema.js +3 -0
- package/templates/databases/mongodb/src/database/id.schema.js +3 -0
- package/templates/databases/mongodb/src/database/models/refreshToken.model.js +15 -0
- package/templates/databases/mongodb/src/database/models/user.model.js +41 -0
- package/templates/databases/mongodb/src/modules/user/user.repository.js +68 -0
- package/templates/databases/mongodb/tests/globalSetup.js +13 -0
- package/templates/databases/mongodb/tests/setup.js +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.js +14 -0
- package/templates/databases/postgres/src/database/connection.js +61 -0
- package/templates/databases/postgres/src/database/env.schema.js +3 -0
- package/templates/databases/postgres/src/database/id.schema.js +3 -0
- package/templates/databases/postgres/src/database/prisma.js +9 -0
- package/templates/databases/postgres/src/modules/user/user.repository.js +88 -0
- package/templates/databases/postgres/tests/connection.test.js +17 -0
- package/templates/databases/postgres/tests/globalSetup.js +60 -0
- package/templates/databases/postgres/tests/prismaSchema.test.js +27 -0
- package/templates/databases/postgres/tests/setup.js +15 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Router } from 'express';
|
|
2
|
+
import helmet from 'helmet';
|
|
3
|
+
import swaggerUi from 'swagger-ui-express';
|
|
4
|
+
import { buildOpenApiDocument } from '../docs/openapi.js';
|
|
5
|
+
|
|
6
|
+
export const docsRouter = Router();
|
|
7
|
+
|
|
8
|
+
// Swagger UI uses inline scripts and styles, so the strict CSP is off for the docs only.
|
|
9
|
+
docsRouter.use(['/api-docs', '/api-docs.json'], helmet({ contentSecurityPolicy: false }));
|
|
10
|
+
|
|
11
|
+
docsRouter.get('/api-docs.json', (req, res) => res.json(buildOpenApiDocument()));
|
|
12
|
+
docsRouter.use(
|
|
13
|
+
'/api-docs',
|
|
14
|
+
swaggerUi.serve,
|
|
15
|
+
swaggerUi.setup(buildOpenApiDocument(), { swaggerOptions: { persistAuthorization: true } }),
|
|
16
|
+
);
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Router } from 'express';
|
|
2
|
+
import { isDatabaseConnected } from '../database/connection.js';
|
|
3
|
+
import { sendSuccess } from '../utils/apiResponse.js';
|
|
4
|
+
|
|
5
|
+
export const healthRouter = Router();
|
|
6
|
+
|
|
7
|
+
healthRouter.get('/', async (_req, res) => {
|
|
8
|
+
if (await isDatabaseConnected()) {
|
|
9
|
+
return sendSuccess(res, { message: 'OK', data: { status: 'ok', database: 'up' } });
|
|
10
|
+
}
|
|
11
|
+
// Built here rather than in errorHandler: a degraded health check still reports its data.
|
|
12
|
+
return res.status(503).json({
|
|
13
|
+
success: false,
|
|
14
|
+
message: 'Service unavailable',
|
|
15
|
+
data: { status: 'degraded', database: 'down' },
|
|
16
|
+
});
|
|
17
|
+
});
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Router } from 'express';
|
|
2
|
+
import { authRouter } from '../modules/auth/auth.routes.js';
|
|
3
|
+
import { userRouter } from '../modules/user/user.routes.js';
|
|
4
|
+
|
|
5
|
+
export const apiRouter = Router();
|
|
6
|
+
|
|
7
|
+
// One list drives both the mounting and the docs coverage test.
|
|
8
|
+
export const API_MOUNTS = [
|
|
9
|
+
{ path: '/auth', router: authRouter },
|
|
10
|
+
{ path: '/users', router: userRouter },
|
|
11
|
+
];
|
|
12
|
+
|
|
13
|
+
for (const { path, router } of API_MOUNTS) apiRouter.use(path, router);
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { env } from './config/env.js';
|
|
2
|
+
import { logger } from './config/logger.js';
|
|
3
|
+
import { connectDatabase, disconnectDatabase } from './database/connection.js';
|
|
4
|
+
import { createApp } from './app.js';
|
|
5
|
+
|
|
6
|
+
const FORCE_EXIT_MS = 10_000;
|
|
7
|
+
|
|
8
|
+
let server;
|
|
9
|
+
try {
|
|
10
|
+
await connectDatabase();
|
|
11
|
+
server = createApp().listen(env.PORT, (err) => {
|
|
12
|
+
// Express 5 also calls this on a listen error, which the handler below reports.
|
|
13
|
+
if (!err) logger.info(`Server listening on port ${env.PORT} (${env.NODE_ENV})`);
|
|
14
|
+
});
|
|
15
|
+
// For example the port is already in use.
|
|
16
|
+
server.on('error', (err) => {
|
|
17
|
+
logger.fatal({ err }, 'Server error');
|
|
18
|
+
process.exit(1);
|
|
19
|
+
});
|
|
20
|
+
} catch (err) {
|
|
21
|
+
logger.fatal({ err }, 'Failed to start');
|
|
22
|
+
process.exit(1);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
let shuttingDown = false;
|
|
26
|
+
|
|
27
|
+
function shutdown(signal) {
|
|
28
|
+
if (shuttingDown) return;
|
|
29
|
+
shuttingDown = true;
|
|
30
|
+
logger.info(`${signal} received, shutting down`);
|
|
31
|
+
|
|
32
|
+
// Do not wait forever for open connections.
|
|
33
|
+
setTimeout(() => {
|
|
34
|
+
logger.error('Shutdown timed out, forcing exit');
|
|
35
|
+
process.exit(1);
|
|
36
|
+
}, FORCE_EXIT_MS).unref();
|
|
37
|
+
|
|
38
|
+
server.close(async () => {
|
|
39
|
+
await disconnectDatabase();
|
|
40
|
+
process.exit(0);
|
|
41
|
+
});
|
|
42
|
+
server.closeIdleConnections?.();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
process.on('SIGINT', () => shutdown('SIGINT'));
|
|
46
|
+
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
47
|
+
process.on('unhandledRejection', (reason) => {
|
|
48
|
+
logger.error({ err: reason }, 'Unhandled rejection');
|
|
49
|
+
process.exit(1);
|
|
50
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export class ApiError extends Error {
|
|
2
|
+
constructor(statusCode, message, errors) {
|
|
3
|
+
super(message);
|
|
4
|
+
this.name = 'ApiError';
|
|
5
|
+
this.statusCode = statusCode;
|
|
6
|
+
if (errors !== undefined) this.errors = errors;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
static badRequest(message, errors) {
|
|
10
|
+
return new ApiError(400, message, errors);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
static unauthorized(message = 'Unauthorized') {
|
|
14
|
+
return new ApiError(401, message);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
static forbidden(message = 'Forbidden') {
|
|
18
|
+
return new ApiError(403, message);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
static notFound(message = 'Resource not found') {
|
|
22
|
+
return new ApiError(404, message);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
static conflict(message) {
|
|
26
|
+
return new ApiError(409, message);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
static tooManyRequests(message) {
|
|
30
|
+
return new ApiError(429, message);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import argon2 from 'argon2';
|
|
2
|
+
|
|
3
|
+
export function hashPassword(plain) {
|
|
4
|
+
return argon2.hash(plain, { type: argon2.argon2id });
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export async function verifyPassword(hash, plain) {
|
|
8
|
+
try {
|
|
9
|
+
return await argon2.verify(hash, plain);
|
|
10
|
+
} catch {
|
|
11
|
+
// A malformed hash is just "no match", never an error.
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import jwt from 'jsonwebtoken';
|
|
3
|
+
import { env } from '../config/env.js';
|
|
4
|
+
import { ApiError } from './ApiError.js';
|
|
5
|
+
|
|
6
|
+
const TOKEN_TYPES = Object.freeze({ ACCESS: 'access', REFRESH: 'refresh' });
|
|
7
|
+
|
|
8
|
+
export function signAccessToken({ userId, role }) {
|
|
9
|
+
return jwt.sign({ sub: userId, role, type: TOKEN_TYPES.ACCESS }, env.JWT_ACCESS_SECRET, {
|
|
10
|
+
expiresIn: env.JWT_ACCESS_EXPIRES_IN,
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function signRefreshToken({ userId }) {
|
|
15
|
+
const token = jwt.sign(
|
|
16
|
+
{ sub: userId, type: TOKEN_TYPES.REFRESH, jti: randomUUID() },
|
|
17
|
+
env.JWT_REFRESH_SECRET,
|
|
18
|
+
{ expiresIn: env.JWT_REFRESH_EXPIRES_IN },
|
|
19
|
+
);
|
|
20
|
+
const { exp } = jwt.decode(token);
|
|
21
|
+
return { token, expiresAt: new Date(exp * 1000) };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function verify(token, secret, type) {
|
|
25
|
+
try {
|
|
26
|
+
const payload = jwt.verify(token, secret, { algorithms: ['HS256'] });
|
|
27
|
+
if (payload.type !== type) throw new Error('wrong token type');
|
|
28
|
+
return payload;
|
|
29
|
+
} catch {
|
|
30
|
+
throw ApiError.unauthorized('Invalid or expired token');
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function verifyAccessToken(token) {
|
|
35
|
+
const payload = verify(token, env.JWT_ACCESS_SECRET, TOKEN_TYPES.ACCESS);
|
|
36
|
+
return { userId: payload.sub, role: payload.role };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function verifyRefreshToken(token) {
|
|
40
|
+
const payload = verify(token, env.JWT_REFRESH_SECRET, TOKEN_TYPES.REFRESH);
|
|
41
|
+
return { userId: payload.sub };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function hashToken(token) {
|
|
45
|
+
return createHash('sha256').update(token).digest('hex');
|
|
46
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import request from 'supertest';
|
|
2
|
+
import { describe, expect, it } from 'vitest';
|
|
3
|
+
import { createApp } from '../src/app.js';
|
|
4
|
+
import { isDatabaseConnected } from '../src/database/connection.js';
|
|
5
|
+
|
|
6
|
+
const app = createApp();
|
|
7
|
+
|
|
8
|
+
describe('base app', () => {
|
|
9
|
+
it('GET /health returns ok', async () => {
|
|
10
|
+
const res = await request(app).get('/health');
|
|
11
|
+
expect(res.status).toBe(200);
|
|
12
|
+
expect(res.body.success).toBe(true);
|
|
13
|
+
expect(res.body.data.status).toBe('ok');
|
|
14
|
+
expect(res.body.data.database).toBe('up');
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
it('checks the database live', async () => {
|
|
18
|
+
const check = isDatabaseConnected();
|
|
19
|
+
expect(check).toBeInstanceOf(Promise);
|
|
20
|
+
expect(await check).toBe(true);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('returns a JSON 404 for unknown routes', async () => {
|
|
24
|
+
const res = await request(app).get('/api/v1/nope');
|
|
25
|
+
expect(res.status).toBe(404);
|
|
26
|
+
expect(res.body).toEqual({ success: false, message: 'Route not found' });
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('returns 400 for malformed JSON', async () => {
|
|
30
|
+
const res = await request(app)
|
|
31
|
+
.post('/api/v1/anything')
|
|
32
|
+
.set('Content-Type', 'application/json')
|
|
33
|
+
.send('{bad');
|
|
34
|
+
expect(res.status).toBe(400);
|
|
35
|
+
expect(res.headers['content-type']).toMatch(/json/);
|
|
36
|
+
expect(res.body).toEqual({ success: false, message: 'Invalid JSON body' });
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('returns 415 JSON for an unsupported charset', async () => {
|
|
40
|
+
const res = await request(app)
|
|
41
|
+
.post('/api/v1/anything')
|
|
42
|
+
.set('Content-Type', 'application/json; charset=iso-8859-1')
|
|
43
|
+
.send('{}');
|
|
44
|
+
expect(res.status).toBe(415);
|
|
45
|
+
expect(res.headers['content-type']).toMatch(/json/);
|
|
46
|
+
expect(res.body.success).toBe(false);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('returns 413 for bodies over 10kb', async () => {
|
|
50
|
+
const res = await request(app)
|
|
51
|
+
.post('/api/v1/anything')
|
|
52
|
+
.send({ blob: 'x'.repeat(11 * 1024) });
|
|
53
|
+
expect(res.status).toBe(413);
|
|
54
|
+
expect(res.headers['content-type']).toMatch(/json/);
|
|
55
|
+
expect(res.body).toEqual({ success: false, message: 'Request body too large' });
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('does not trust proxy headers unless TRUST_PROXY is set', () => {
|
|
59
|
+
expect(app.get('trust proxy')).toBe(false);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('sets x-request-id and hides x-powered-by', async () => {
|
|
63
|
+
const res = await request(app).get('/health');
|
|
64
|
+
expect(res.headers['x-request-id']).toBeTruthy();
|
|
65
|
+
expect(res.headers['x-powered-by']).toBeUndefined();
|
|
66
|
+
});
|
|
67
|
+
});
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import request from 'supertest';
|
|
2
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
3
|
+
import { createApp } from '../src/app.js';
|
|
4
|
+
import { signAccessToken } from '../src/utils/token.js';
|
|
5
|
+
import { createUser, getRefreshCookie, loginAs } from './helpers/auth.helper.js';
|
|
6
|
+
|
|
7
|
+
const app = createApp();
|
|
8
|
+
const validBody = { name: 'Foo Bar', email: 'foo@x.com', password: 'Passw0rd!' };
|
|
9
|
+
|
|
10
|
+
const register = (body = validBody) => request(app).post('/api/v1/auth/register').send(body);
|
|
11
|
+
const login = (body) => request(app).post('/api/v1/auth/login').send(body);
|
|
12
|
+
const refresh = (cookie) => {
|
|
13
|
+
const req = request(app).post('/api/v1/auth/refresh');
|
|
14
|
+
return cookie ? req.set('Cookie', cookie) : req;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
describe('POST /auth/register', () => {
|
|
18
|
+
it('creates a user without exposing the password', async () => {
|
|
19
|
+
const res = await register();
|
|
20
|
+
expect(res.status).toBe(201);
|
|
21
|
+
expect(res.body.message).toBe('User registered successfully');
|
|
22
|
+
expect(res.body.data.user).not.toHaveProperty('password');
|
|
23
|
+
expect(res.body.data.user.role).toBe('user');
|
|
24
|
+
expect(res.body.data.user.email).toBe('foo@x.com');
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it('rejects a role field', async () => {
|
|
28
|
+
const res = await register({ ...validBody, role: 'admin' });
|
|
29
|
+
expect(res.status).toBe(400);
|
|
30
|
+
expect(res.body.errors.some((e) => e.field === 'role')).toBe(true);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('treats emails case- and whitespace-insensitively', async () => {
|
|
34
|
+
expect((await register({ ...validBody, email: ' Foo@X.com ' })).status).toBe(201);
|
|
35
|
+
expect((await register({ ...validBody, email: 'foo@x.com' })).status).toBe(409);
|
|
36
|
+
const res = await login({ email: 'FOO@x.com', password: validBody.password });
|
|
37
|
+
expect(res.status).toBe(200);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it('rejects a weak password', async () => {
|
|
41
|
+
const res = await register({ ...validBody, password: 'weak' });
|
|
42
|
+
expect(res.status).toBe(400);
|
|
43
|
+
expect(res.body.errors[0].field).toBe('password');
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
describe('POST /auth/login', () => {
|
|
48
|
+
it('gives the same 401 for a wrong password and an unknown email', async () => {
|
|
49
|
+
const { user } = await createUser();
|
|
50
|
+
const wrong = await login({ email: user.email, password: 'Wrong1234' });
|
|
51
|
+
const unknown = await login({ email: 'nobody@test.com', password: 'Wrong1234' });
|
|
52
|
+
expect(wrong.status).toBe(401);
|
|
53
|
+
expect(unknown.status).toBe(401);
|
|
54
|
+
expect(wrong.body.message).toBe('Invalid email or password');
|
|
55
|
+
expect(unknown.body).toEqual(wrong.body);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('returns an access token and sets a hardened refresh cookie', async () => {
|
|
59
|
+
const { user, password } = await createUser();
|
|
60
|
+
const res = await login({ email: user.email, password });
|
|
61
|
+
expect(res.status).toBe(200);
|
|
62
|
+
expect(res.body.message).toBe('Logged in successfully');
|
|
63
|
+
expect(res.body.data.accessToken).toEqual(expect.any(String));
|
|
64
|
+
expect(res.body.data.user).not.toHaveProperty('password');
|
|
65
|
+
|
|
66
|
+
const cookie = res.headers['set-cookie'].find((c) => c.startsWith('refreshToken='));
|
|
67
|
+
expect(cookie).toContain('HttpOnly');
|
|
68
|
+
expect(cookie).toContain('SameSite=Strict');
|
|
69
|
+
expect(cookie).toContain('Path=/api/v1/auth');
|
|
70
|
+
|
|
71
|
+
const tokenValue = getRefreshCookie(res).split('=')[1];
|
|
72
|
+
expect(JSON.stringify(res.body)).not.toContain(tokenValue);
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
describe('POST /auth/refresh', () => {
|
|
77
|
+
it('rotates the refresh token', async () => {
|
|
78
|
+
const { user, password } = await createUser();
|
|
79
|
+
const { refreshCookie } = await loginAs(app, { email: user.email, password });
|
|
80
|
+
const res = await refresh(refreshCookie);
|
|
81
|
+
expect(res.status).toBe(200);
|
|
82
|
+
expect(res.body.message).toBe('Token refreshed');
|
|
83
|
+
expect(res.body.data.accessToken).toEqual(expect.any(String));
|
|
84
|
+
const newCookie = getRefreshCookie(res);
|
|
85
|
+
expect(newCookie).not.toBeNull();
|
|
86
|
+
expect(newCookie).not.toBe(refreshCookie);
|
|
87
|
+
expect(JSON.stringify(res.body)).not.toContain(newCookie.split('=')[1]);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it('revokes every token when a rotated token is reused', async () => {
|
|
91
|
+
const { user, password } = await createUser();
|
|
92
|
+
const { refreshCookie: oldCookie } = await loginAs(app, { email: user.email, password });
|
|
93
|
+
const rotated = await refresh(oldCookie);
|
|
94
|
+
const newCookie = getRefreshCookie(rotated);
|
|
95
|
+
|
|
96
|
+
expect((await refresh(oldCookie)).status).toBe(401);
|
|
97
|
+
expect((await refresh(newCookie)).status).toBe(401);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it('lets exactly one of two concurrent refreshes win', async () => {
|
|
101
|
+
const { user, password } = await createUser();
|
|
102
|
+
const { refreshCookie } = await loginAs(app, { email: user.email, password });
|
|
103
|
+
const results = await Promise.all([refresh(refreshCookie), refresh(refreshCookie)]);
|
|
104
|
+
const statuses = results.map((res) => res.status).sort();
|
|
105
|
+
// Whether the winner's new cookie survives depends on timing, so only the race itself is checked.
|
|
106
|
+
expect(statuses).toEqual([200, 401]);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it('rejects a tampered cookie', async () => {
|
|
110
|
+
const { user, password } = await createUser();
|
|
111
|
+
const { refreshCookie } = await loginAs(app, { email: user.email, password });
|
|
112
|
+
const [name, value] = refreshCookie.split('=');
|
|
113
|
+
const [header, payload, signature] = value.split('.');
|
|
114
|
+
const forged = JSON.parse(Buffer.from(payload, 'base64url').toString());
|
|
115
|
+
forged.sub = 'someone-else';
|
|
116
|
+
const tampered = `${header}.${Buffer.from(JSON.stringify(forged)).toString('base64url')}.${signature}`;
|
|
117
|
+
expect((await refresh(`${name}=${tampered}`)).status).toBe(401);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it('rejects an expired cookie', async () => {
|
|
121
|
+
const { user, password } = await createUser();
|
|
122
|
+
const { refreshCookie } = await loginAs(app, { email: user.email, password });
|
|
123
|
+
vi.useFakeTimers({ toFake: ['Date'] });
|
|
124
|
+
try {
|
|
125
|
+
vi.setSystemTime(Date.now() + 8 * 24 * 60 * 60 * 1000);
|
|
126
|
+
expect((await refresh(refreshCookie)).status).toBe(401);
|
|
127
|
+
} finally {
|
|
128
|
+
vi.useRealTimers();
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it('rejects a missing cookie', async () => {
|
|
133
|
+
expect((await refresh()).status).toBe(401);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it('rejects an access token used as the refresh cookie', async () => {
|
|
137
|
+
const { user } = await createUser();
|
|
138
|
+
const accessToken = signAccessToken({ userId: user.id, role: user.role });
|
|
139
|
+
expect((await refresh(`refreshToken=${accessToken}`)).status).toBe(401);
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
describe('POST /auth/logout', () => {
|
|
144
|
+
it('revokes the token and clears the cookie', async () => {
|
|
145
|
+
const { user, password } = await createUser();
|
|
146
|
+
const { refreshCookie } = await loginAs(app, { email: user.email, password });
|
|
147
|
+
const res = await request(app).post('/api/v1/auth/logout').set('Cookie', refreshCookie);
|
|
148
|
+
expect(res.status).toBe(200);
|
|
149
|
+
expect(res.body.message).toBe('Logged out successfully');
|
|
150
|
+
const cleared = res.headers['set-cookie'].find((c) => c.startsWith('refreshToken='));
|
|
151
|
+
expect(cleared).toMatch(/refreshToken=;/);
|
|
152
|
+
expect(cleared).toContain('Path=/api/v1/auth');
|
|
153
|
+
expect((await refresh(refreshCookie)).status).toBe(401);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('succeeds without a cookie', async () => {
|
|
157
|
+
const res = await request(app).post('/api/v1/auth/logout');
|
|
158
|
+
expect(res.status).toBe(200);
|
|
159
|
+
expect(res.body.message).toBe('Logged out successfully');
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it('succeeds with a malformed cookie and still clears it', async () => {
|
|
163
|
+
const res = await request(app)
|
|
164
|
+
.post('/api/v1/auth/logout')
|
|
165
|
+
.set('Cookie', 'refreshToken=not-a-jwt');
|
|
166
|
+
expect(res.status).toBe(200);
|
|
167
|
+
const cleared = res.headers['set-cookie'].find((c) => c.startsWith('refreshToken='));
|
|
168
|
+
expect(cleared).toMatch(/refreshToken=;/);
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
describe('Bearer authentication', () => {
|
|
173
|
+
it('rejects a tampered access token', async () => {
|
|
174
|
+
const { user } = await createUser();
|
|
175
|
+
const token = signAccessToken({ userId: user.id, role: user.role });
|
|
176
|
+
const [header, payload, signature] = token.split('.');
|
|
177
|
+
const forged = JSON.parse(Buffer.from(payload, 'base64url').toString());
|
|
178
|
+
forged.role = 'admin';
|
|
179
|
+
const tampered = `${header}.${Buffer.from(JSON.stringify(forged)).toString('base64url')}.${signature}`;
|
|
180
|
+
const res = await request(app)
|
|
181
|
+
.get('/api/v1/users/me')
|
|
182
|
+
.set('Authorization', `Bearer ${tampered}`);
|
|
183
|
+
expect(res.status).toBe(401);
|
|
184
|
+
});
|
|
185
|
+
});
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import cookieParser from 'cookie-parser';
|
|
2
|
+
import express from 'express';
|
|
3
|
+
import { pinoHttp } from 'pino-http';
|
|
4
|
+
import request from 'supertest';
|
|
5
|
+
import { describe, expect, it } from 'vitest';
|
|
6
|
+
import { logger } from '../src/config/logger.js';
|
|
7
|
+
import { authenticate } from '../src/middlewares/authenticate.js';
|
|
8
|
+
import { errorHandler } from '../src/middlewares/errorHandler.js';
|
|
9
|
+
import * as userRepository from '../src/modules/user/user.repository.js';
|
|
10
|
+
import { sendSuccess } from '../src/utils/apiResponse.js';
|
|
11
|
+
import { signAccessToken, signRefreshToken } from '../src/utils/token.js';
|
|
12
|
+
import { createUser } from './helpers/auth.helper.js';
|
|
13
|
+
|
|
14
|
+
const app = express();
|
|
15
|
+
app.use(pinoHttp({ logger }));
|
|
16
|
+
app.use(cookieParser());
|
|
17
|
+
app.get('/protected', authenticate, (req, res) => sendSuccess(res, { data: { user: req.user } }));
|
|
18
|
+
app.use(errorHandler);
|
|
19
|
+
|
|
20
|
+
const get = (authorization) => {
|
|
21
|
+
const req = request(app).get('/protected');
|
|
22
|
+
return authorization ? req.set('Authorization', authorization) : req;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
describe('authenticate', () => {
|
|
26
|
+
it('rejects a missing header', async () => {
|
|
27
|
+
const res = await get();
|
|
28
|
+
expect(res.status).toBe(401);
|
|
29
|
+
expect(res.body.message).toBe('Authentication required');
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('rejects a non-Bearer scheme', async () => {
|
|
33
|
+
const res = await get('Basic xyz');
|
|
34
|
+
expect(res.status).toBe(401);
|
|
35
|
+
expect(res.body.message).toBe('Authentication required');
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('rejects a refresh token used as Bearer', async () => {
|
|
39
|
+
const { user } = await createUser();
|
|
40
|
+
const { token } = signRefreshToken({ userId: user.id });
|
|
41
|
+
expect((await get(`Bearer ${token}`)).status).toBe(401);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('rejects a token for a deleted user', async () => {
|
|
45
|
+
const { user } = await createUser();
|
|
46
|
+
const token = signAccessToken({ userId: user.id, role: user.role });
|
|
47
|
+
await userRepository.deleteById(user.id);
|
|
48
|
+
expect((await get(`Bearer ${token}`)).status).toBe(401);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('accepts a valid token and takes the role from the database', async () => {
|
|
52
|
+
const { user } = await createUser();
|
|
53
|
+
const token = signAccessToken({ userId: user.id, role: user.role });
|
|
54
|
+
await userRepository.updateRole(user.id, 'admin');
|
|
55
|
+
const res = await get(`Bearer ${token}`);
|
|
56
|
+
expect(res.status).toBe(200);
|
|
57
|
+
expect(res.body.data.user.id).toBe(user.id);
|
|
58
|
+
expect(res.body.data.user.role).toBe('admin');
|
|
59
|
+
expect(res.body.data.user).not.toHaveProperty('password');
|
|
60
|
+
});
|
|
61
|
+
});
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import request from 'supertest';
|
|
2
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
3
|
+
import { createApp } from '../src/app.js';
|
|
4
|
+
import { USER_RULES } from '../src/constants/user.rules.js';
|
|
5
|
+
import { buildOpenApiDocument } from '../src/docs/openapi.js';
|
|
6
|
+
import { API_MOUNTS } from '../src/routes/index.js';
|
|
7
|
+
import pkg from '../package.json' with { type: 'json' };
|
|
8
|
+
|
|
9
|
+
const app = createApp();
|
|
10
|
+
const doc = buildOpenApiDocument();
|
|
11
|
+
|
|
12
|
+
// Collect `{ method, path }` for every route layer of every mounted router.
|
|
13
|
+
function collectRoutes() {
|
|
14
|
+
const routes = [];
|
|
15
|
+
for (const { path: mount, router } of API_MOUNTS) {
|
|
16
|
+
for (const layer of router.stack) {
|
|
17
|
+
if (!layer.route) continue;
|
|
18
|
+
const sub = layer.route.path === '/' ? '' : layer.route.path.replace(/:(\w+)/g, '{$1}');
|
|
19
|
+
for (const method of Object.keys(layer.route.methods)) {
|
|
20
|
+
routes.push({ method, path: `${mount}${sub}` });
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return routes;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
describe('openapi document', () => {
|
|
28
|
+
it('GET /api-docs.json returns an OpenAPI 3.1 document', async () => {
|
|
29
|
+
const res = await request(app).get('/api-docs.json');
|
|
30
|
+
expect(res.status).toBe(200);
|
|
31
|
+
expect(res.body.openapi).toMatch(/^3\.1/);
|
|
32
|
+
expect(res.body.info.title).toBe(pkg.name);
|
|
33
|
+
expect(res.body.info.version).toBe(pkg.version);
|
|
34
|
+
expect('description' in res.body.info).toBe(Boolean(pkg.description));
|
|
35
|
+
expect(res.body.servers).toEqual([{ url: '/api/v1' }]);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('documents every route mounted under /api/v1', () => {
|
|
39
|
+
const routes = collectRoutes();
|
|
40
|
+
const documented = Object.values(doc.paths).flatMap((item) => Object.keys(item));
|
|
41
|
+
expect(routes.length).toBe(documented.length);
|
|
42
|
+
for (const { method, path } of routes) {
|
|
43
|
+
expect(doc.paths[path]?.[method], `${method.toUpperCase()} ${path}`).toBeDefined();
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('builds request bodies from the shared rules', () => {
|
|
48
|
+
const schema = doc.paths['/auth/register'].post.requestBody.content['application/json'].schema;
|
|
49
|
+
const { password, email } = schema.properties;
|
|
50
|
+
expect(password.minLength).toBe(USER_RULES.PASSWORD.MIN);
|
|
51
|
+
expect(password.maxLength).toBe(USER_RULES.PASSWORD.MAX);
|
|
52
|
+
expect(email.maxLength).toBe(USER_RULES.EMAIL.MAX);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('declares bearer auth on user routes only', () => {
|
|
56
|
+
const bearer = [{ bearerAuth: [] }];
|
|
57
|
+
expect(doc.paths['/users'].get.security).toEqual(bearer);
|
|
58
|
+
expect(doc.paths['/users/me'].get.security).toEqual(bearer);
|
|
59
|
+
expect(doc.paths['/users/{id}'].get.security).toEqual(bearer);
|
|
60
|
+
expect(doc.paths['/users/{id}'].delete.security).toEqual(bearer);
|
|
61
|
+
expect(doc.paths['/auth/register'].post.security).toBeUndefined();
|
|
62
|
+
expect(doc.paths['/auth/login'].post.security).toBeUndefined();
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('never exposes a password outside the register and login request bodies', () => {
|
|
66
|
+
const allowed = new Set(['/auth/register', '/auth/login']);
|
|
67
|
+
const bodies = [...allowed].map(
|
|
68
|
+
(p) => doc.paths[p].post.requestBody.content['application/json'].schema,
|
|
69
|
+
);
|
|
70
|
+
expect(bodies.every((b) => 'password' in b.properties)).toBe(true);
|
|
71
|
+
|
|
72
|
+
const withoutBodies = structuredClone(doc);
|
|
73
|
+
for (const p of allowed) delete withoutBodies.paths[p].post.requestBody;
|
|
74
|
+
const json = JSON.stringify(withoutBodies);
|
|
75
|
+
expect(json).not.toMatch(/"password"/i);
|
|
76
|
+
expect(json).not.toMatch(/refreshToken"\s*:\s*\{\s*"type"/);
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
describe('swagger ui', () => {
|
|
81
|
+
it('GET /api-docs serves the UI', async () => {
|
|
82
|
+
const res = await request(app).get('/api-docs/');
|
|
83
|
+
expect(res.status).toBe(200);
|
|
84
|
+
expect(res.text).toContain('swagger-ui');
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it('keeps the strict CSP on the API', async () => {
|
|
88
|
+
const res = await request(app).get('/health');
|
|
89
|
+
expect(res.headers['content-security-policy']).toBeDefined();
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
describe('API_DOCS_ENABLED=false', () => {
|
|
94
|
+
afterEach(() => {
|
|
95
|
+
vi.unstubAllEnvs();
|
|
96
|
+
vi.doUnmock('../src/routes/index.js');
|
|
97
|
+
vi.doUnmock('../src/routes/health.routes.js');
|
|
98
|
+
vi.resetModules();
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('does not serve the docs', async () => {
|
|
102
|
+
vi.stubEnv('API_DOCS_ENABLED', 'false');
|
|
103
|
+
vi.resetModules();
|
|
104
|
+
// Stub the DB-backed routers, since mongoose models cannot be compiled twice.
|
|
105
|
+
vi.doMock('../src/routes/index.js', async () => ({
|
|
106
|
+
apiRouter: (await import('express')).Router(),
|
|
107
|
+
}));
|
|
108
|
+
vi.doMock('../src/routes/health.routes.js', async () => ({
|
|
109
|
+
healthRouter: (await import('express')).Router(),
|
|
110
|
+
}));
|
|
111
|
+
const { createApp: createFreshApp } = await import('../src/app.js');
|
|
112
|
+
const res = await request(createFreshApp()).get('/api-docs.json');
|
|
113
|
+
expect(res.status).toBe(404);
|
|
114
|
+
});
|
|
115
|
+
});
|