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,24 @@
|
|
|
1
|
+
import { sendSuccess } from '../../utils/apiResponse.ts';
|
|
2
|
+
import * as userService from './user.service.ts';
|
|
3
|
+
import type { Request, Response } from 'express';
|
|
4
|
+
import type { ValidatedRequest } from '../../middlewares/validate.ts';
|
|
5
|
+
import type { ListUsersInput, UserIdInput } from './user.validation.ts';
|
|
6
|
+
|
|
7
|
+
export function getMe(req: Request, res: Response) {
|
|
8
|
+
return sendSuccess(res, { message: 'Profile fetched successfully', data: { user: req.user } });
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export async function getUsers(req: ValidatedRequest<ListUsersInput>, res: Response) {
|
|
12
|
+
const { users, meta } = await userService.listUsers(req.validated!.query);
|
|
13
|
+
return sendSuccess(res, { message: 'Users fetched successfully', data: { users }, meta });
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function getUser(req: ValidatedRequest<UserIdInput>, res: Response) {
|
|
17
|
+
const user = await userService.getUserById(req.validated!.params.id);
|
|
18
|
+
return sendSuccess(res, { message: 'User fetched successfully', data: { user } });
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function removeUser(req: ValidatedRequest<UserIdInput>, res: Response) {
|
|
22
|
+
await userService.deleteUser({ targetId: req.validated!.params.id, actorId: req.user!.id });
|
|
23
|
+
return res.status(204).end();
|
|
24
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { Router } from 'express';
|
|
2
|
+
import { authenticate } from '../../middlewares/authenticate.ts';
|
|
3
|
+
import { authorize } from '../../middlewares/authorize.ts';
|
|
4
|
+
import { validate } from '../../middlewares/validate.ts';
|
|
5
|
+
import { ROLES } from '../../constants/roles.ts';
|
|
6
|
+
import * as userController from './user.controller.ts';
|
|
7
|
+
import { listUsersSchema, userIdParamSchema } from './user.validation.ts';
|
|
8
|
+
|
|
9
|
+
export const userRouter = Router();
|
|
10
|
+
|
|
11
|
+
userRouter.use(authenticate);
|
|
12
|
+
|
|
13
|
+
// `/me` must be declared before `/:id`.
|
|
14
|
+
userRouter.get('/me', userController.getMe);
|
|
15
|
+
userRouter.get('/', authorize(ROLES.ADMIN), validate(listUsersSchema), userController.getUsers);
|
|
16
|
+
userRouter.get('/:id', authorize(ROLES.ADMIN), validate(userIdParamSchema), userController.getUser);
|
|
17
|
+
userRouter.delete(
|
|
18
|
+
'/:id',
|
|
19
|
+
authorize(ROLES.ADMIN),
|
|
20
|
+
validate(userIdParamSchema),
|
|
21
|
+
userController.removeUser,
|
|
22
|
+
);
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { ApiError } from '../../utils/ApiError.ts';
|
|
2
|
+
import * as userRepository from './user.repository.ts';
|
|
3
|
+
import type { Role } from '../../constants/roles.ts';
|
|
4
|
+
import type { PublicUser } from '../../docs/openapi.registry.ts';
|
|
5
|
+
import type { ListUsersInput } from './user.validation.ts';
|
|
6
|
+
|
|
7
|
+
export type UserWithPassword = PublicUser & { password: string };
|
|
8
|
+
|
|
9
|
+
export interface StoredRefreshToken {
|
|
10
|
+
userId: string;
|
|
11
|
+
expiresAt: Date;
|
|
12
|
+
revokedAt: Date | null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface UserRepository {
|
|
16
|
+
// What every database's user.repository must provide. The services only use this.
|
|
17
|
+
findById(id: string): Promise<PublicUser | null>;
|
|
18
|
+
findByEmail(email: string, options?: { withPassword?: false }): Promise<PublicUser | null>;
|
|
19
|
+
findByEmail(email: string, options: { withPassword: true }): Promise<UserWithPassword | null>;
|
|
20
|
+
create(input: {
|
|
21
|
+
name: string;
|
|
22
|
+
email: string;
|
|
23
|
+
password: string;
|
|
24
|
+
role?: Role;
|
|
25
|
+
}): Promise<PublicUser>;
|
|
26
|
+
findMany(input: { page: number; limit: number }): Promise<{ users: PublicUser[]; total: number }>;
|
|
27
|
+
updateRole(id: string, role: Role): Promise<PublicUser | null>;
|
|
28
|
+
deleteById(id: string): Promise<boolean>;
|
|
29
|
+
saveRefreshToken(input: { userId: string; tokenHash: string; expiresAt: Date }): Promise<void>;
|
|
30
|
+
findRefreshToken(tokenHash: string): Promise<StoredRefreshToken | null>;
|
|
31
|
+
revokeRefreshToken(tokenHash: string): Promise<boolean>;
|
|
32
|
+
revokeAllRefreshTokens(userId: string): Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
type Implements<T extends UserRepository> = T;
|
|
36
|
+
|
|
37
|
+
export type CheckedUserRepository = Implements<
|
|
38
|
+
// Fails to compile unless the database's user.repository matches UserRepository.
|
|
39
|
+
typeof userRepository
|
|
40
|
+
>;
|
|
41
|
+
|
|
42
|
+
export async function getUserById(id: string) {
|
|
43
|
+
const user = await userRepository.findById(id);
|
|
44
|
+
if (!user) throw ApiError.notFound('User not found');
|
|
45
|
+
return user;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function listUsers({ page, limit }: ListUsersInput['query']) {
|
|
49
|
+
const { users, total } = await userRepository.findMany({ page, limit });
|
|
50
|
+
return { users, meta: { page, limit, total, totalPages: Math.ceil(total / limit) } };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function deleteUser({ targetId, actorId }: { targetId: string; actorId: string }) {
|
|
54
|
+
if (targetId === actorId) throw ApiError.badRequest('You cannot delete your own account');
|
|
55
|
+
const deleted = await userRepository.deleteById(targetId);
|
|
56
|
+
if (!deleted) throw ApiError.notFound('User not found');
|
|
57
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { PAGINATION } from '../../constants/user.rules.ts';
|
|
3
|
+
import { idSchema } from '../../database/id.schema.ts';
|
|
4
|
+
import { emptyObject } from '../../utils/zod.ts';
|
|
5
|
+
|
|
6
|
+
export const userIdParamSchema = z.strictObject({
|
|
7
|
+
body: emptyObject(),
|
|
8
|
+
params: z.strictObject({ id: idSchema }),
|
|
9
|
+
query: emptyObject(),
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
export const listUsersSchema = z.strictObject({
|
|
13
|
+
body: emptyObject(),
|
|
14
|
+
params: emptyObject(),
|
|
15
|
+
query: z.strictObject({
|
|
16
|
+
page: z.coerce.number().int().min(1).default(PAGINATION.DEFAULT_PAGE),
|
|
17
|
+
limit: z.coerce
|
|
18
|
+
.number()
|
|
19
|
+
.int()
|
|
20
|
+
.min(1)
|
|
21
|
+
.max(PAGINATION.MAX_LIMIT)
|
|
22
|
+
.default(PAGINATION.DEFAULT_LIMIT),
|
|
23
|
+
}),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
export type UserIdInput = z.output<typeof userIdParamSchema>;
|
|
27
|
+
export type ListUsersInput = z.output<typeof listUsersSchema>;
|
|
@@ -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.ts';
|
|
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.ts';
|
|
3
|
+
import { sendSuccess } from '../utils/apiResponse.ts';
|
|
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.ts';
|
|
3
|
+
import { userRouter } from '../modules/user/user.routes.ts';
|
|
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,51 @@
|
|
|
1
|
+
import { env } from './config/env.ts';
|
|
2
|
+
import { logger } from './config/logger.ts';
|
|
3
|
+
import { connectDatabase, disconnectDatabase } from './database/connection.ts';
|
|
4
|
+
import { createApp } from './app.ts';
|
|
5
|
+
import type { Server } from 'node:http';
|
|
6
|
+
|
|
7
|
+
const FORCE_EXIT_MS = 10_000;
|
|
8
|
+
|
|
9
|
+
let server: Server;
|
|
10
|
+
try {
|
|
11
|
+
await connectDatabase();
|
|
12
|
+
server = createApp().listen(env.PORT, (err) => {
|
|
13
|
+
// Express 5 also calls this on a listen error, which the handler below reports.
|
|
14
|
+
if (!err) logger.info(`Server listening on port ${env.PORT} (${env.NODE_ENV})`);
|
|
15
|
+
});
|
|
16
|
+
// For example the port is already in use.
|
|
17
|
+
server.on('error', (err) => {
|
|
18
|
+
logger.fatal({ err }, 'Server error');
|
|
19
|
+
process.exit(1);
|
|
20
|
+
});
|
|
21
|
+
} catch (err) {
|
|
22
|
+
logger.fatal({ err }, 'Failed to start');
|
|
23
|
+
process.exit(1);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
let shuttingDown = false;
|
|
27
|
+
|
|
28
|
+
function shutdown(signal: NodeJS.Signals) {
|
|
29
|
+
if (shuttingDown) return;
|
|
30
|
+
shuttingDown = true;
|
|
31
|
+
logger.info(`${signal} received, shutting down`);
|
|
32
|
+
|
|
33
|
+
// Do not wait forever for open connections.
|
|
34
|
+
setTimeout(() => {
|
|
35
|
+
logger.error('Shutdown timed out, forcing exit');
|
|
36
|
+
process.exit(1);
|
|
37
|
+
}, FORCE_EXIT_MS).unref();
|
|
38
|
+
|
|
39
|
+
server.close(async () => {
|
|
40
|
+
await disconnectDatabase();
|
|
41
|
+
process.exit(0);
|
|
42
|
+
});
|
|
43
|
+
server.closeIdleConnections?.();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
process.on('SIGINT', () => shutdown('SIGINT'));
|
|
47
|
+
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
48
|
+
process.on('unhandledRejection', (reason) => {
|
|
49
|
+
logger.error({ err: reason }, 'Unhandled rejection');
|
|
50
|
+
process.exit(1);
|
|
51
|
+
});
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Adds the user that `authenticate` sets to every Express request (TypeScript only).
|
|
2
|
+
// `req.validated` is typed per handler instead, with ValidatedRequest from validate.ts.
|
|
3
|
+
import type { PublicUser } from '../docs/openapi.registry.ts';
|
|
4
|
+
|
|
5
|
+
declare global {
|
|
6
|
+
namespace Express {
|
|
7
|
+
interface Request {
|
|
8
|
+
// Set by `authenticate`.
|
|
9
|
+
user?: PublicUser;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export {};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export class ApiError extends Error {
|
|
2
|
+
declare statusCode: number;
|
|
3
|
+
declare errors?: unknown;
|
|
4
|
+
|
|
5
|
+
constructor(statusCode: number, message: string, errors?: unknown) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = 'ApiError';
|
|
8
|
+
this.statusCode = statusCode;
|
|
9
|
+
if (errors !== undefined) this.errors = errors;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
static badRequest(message: string, errors?: unknown) {
|
|
13
|
+
return new ApiError(400, message, errors);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
static unauthorized(message = 'Unauthorized') {
|
|
17
|
+
return new ApiError(401, message);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
static forbidden(message = 'Forbidden') {
|
|
21
|
+
return new ApiError(403, message);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
static notFound(message = 'Resource not found') {
|
|
25
|
+
return new ApiError(404, message);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
static conflict(message: string) {
|
|
29
|
+
return new ApiError(409, message);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
static tooManyRequests(message: string) {
|
|
33
|
+
return new ApiError(429, message);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { Response } from 'express';
|
|
2
|
+
|
|
3
|
+
interface SuccessOptions {
|
|
4
|
+
statusCode?: number;
|
|
5
|
+
message?: string;
|
|
6
|
+
data?: unknown;
|
|
7
|
+
meta?: unknown;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
interface SuccessBody {
|
|
11
|
+
success: true;
|
|
12
|
+
message: string;
|
|
13
|
+
data: unknown;
|
|
14
|
+
meta?: unknown;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function sendSuccess(
|
|
18
|
+
res: Response,
|
|
19
|
+
{ statusCode = 200, message = 'Success', data = null, meta }: SuccessOptions = {},
|
|
20
|
+
) {
|
|
21
|
+
const body: SuccessBody = { success: true, message, data };
|
|
22
|
+
if (meta !== undefined) body.meta = meta;
|
|
23
|
+
return res.status(statusCode).json(body);
|
|
24
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import argon2 from 'argon2';
|
|
2
|
+
|
|
3
|
+
export function hashPassword(plain: string): Promise<string> {
|
|
4
|
+
return argon2.hash(plain, { type: argon2.argon2id });
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export async function verifyPassword(hash: string, plain: string): Promise<boolean> {
|
|
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,60 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import jwt from 'jsonwebtoken';
|
|
3
|
+
import { env } from '../config/env.ts';
|
|
4
|
+
import { ApiError } from './ApiError.ts';
|
|
5
|
+
import type { SignOptions } from 'jsonwebtoken';
|
|
6
|
+
import type { Role } from '../constants/roles.ts';
|
|
7
|
+
|
|
8
|
+
const TOKEN_TYPES = Object.freeze({ ACCESS: 'access', REFRESH: 'refresh' });
|
|
9
|
+
|
|
10
|
+
type TokenType = (typeof TOKEN_TYPES)[keyof typeof TOKEN_TYPES];
|
|
11
|
+
type ExpiresIn = SignOptions['expiresIn'];
|
|
12
|
+
|
|
13
|
+
interface RefreshPayload {
|
|
14
|
+
sub: string;
|
|
15
|
+
type: TokenType;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface AccessPayload extends RefreshPayload {
|
|
19
|
+
role: Role;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function signAccessToken({ userId, role }: { userId: string; role: Role }) {
|
|
23
|
+
return jwt.sign({ sub: userId, role, type: TOKEN_TYPES.ACCESS }, env.JWT_ACCESS_SECRET, {
|
|
24
|
+
expiresIn: env.JWT_ACCESS_EXPIRES_IN as ExpiresIn,
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function signRefreshToken({ userId }: { userId: string }) {
|
|
29
|
+
const token = jwt.sign(
|
|
30
|
+
{ sub: userId, type: TOKEN_TYPES.REFRESH, jti: randomUUID() },
|
|
31
|
+
env.JWT_REFRESH_SECRET,
|
|
32
|
+
{ expiresIn: env.JWT_REFRESH_EXPIRES_IN as ExpiresIn },
|
|
33
|
+
);
|
|
34
|
+
const { exp } = jwt.decode(token) as { exp: number };
|
|
35
|
+
return { token, expiresAt: new Date(exp * 1000) };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function verify<T extends RefreshPayload>(token: string, secret: string, type: TokenType): T {
|
|
39
|
+
try {
|
|
40
|
+
const payload = jwt.verify(token, secret, { algorithms: ['HS256'] }) as T;
|
|
41
|
+
if (payload.type !== type) throw new Error('wrong token type');
|
|
42
|
+
return payload;
|
|
43
|
+
} catch {
|
|
44
|
+
throw ApiError.unauthorized('Invalid or expired token');
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function verifyAccessToken(token: string) {
|
|
49
|
+
const payload = verify<AccessPayload>(token, env.JWT_ACCESS_SECRET, TOKEN_TYPES.ACCESS);
|
|
50
|
+
return { userId: payload.sub, role: payload.role };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function verifyRefreshToken(token: string) {
|
|
54
|
+
const payload = verify<RefreshPayload>(token, env.JWT_REFRESH_SECRET, TOKEN_TYPES.REFRESH);
|
|
55
|
+
return { userId: payload.sub };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function hashToken(token: string) {
|
|
59
|
+
return createHash('sha256').update(token).digest('hex');
|
|
60
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import request from 'supertest';
|
|
2
|
+
import { describe, expect, it } from 'vitest';
|
|
3
|
+
import { createApp } from '../src/app.ts';
|
|
4
|
+
import { isDatabaseConnected } from '../src/database/connection.ts';
|
|
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,194 @@
|
|
|
1
|
+
import request from 'supertest';
|
|
2
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
3
|
+
import { createApp } from '../src/app.ts';
|
|
4
|
+
import { signAccessToken } from '../src/utils/token.ts';
|
|
5
|
+
import { createUser, getRefreshCookie, loginAs } from './helpers/auth.helper.ts';
|
|
6
|
+
|
|
7
|
+
type Credentials = { email: string; password: string };
|
|
8
|
+
|
|
9
|
+
const app = createApp();
|
|
10
|
+
const validBody = { name: 'Foo Bar', email: 'foo@x.com', password: 'Passw0rd!' };
|
|
11
|
+
|
|
12
|
+
const register = (body: object = validBody) =>
|
|
13
|
+
request(app).post('/api/v1/auth/register').send(body);
|
|
14
|
+
const login = (body: Credentials) => request(app).post('/api/v1/auth/login').send(body);
|
|
15
|
+
const refresh = (cookie?: string | null) => {
|
|
16
|
+
const req = request(app).post('/api/v1/auth/refresh');
|
|
17
|
+
return cookie ? req.set('Cookie', cookie) : req;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
describe('POST /auth/register', () => {
|
|
21
|
+
it('creates a user without exposing the password', async () => {
|
|
22
|
+
const res = await register();
|
|
23
|
+
expect(res.status).toBe(201);
|
|
24
|
+
expect(res.body.message).toBe('User registered successfully');
|
|
25
|
+
expect(res.body.data.user).not.toHaveProperty('password');
|
|
26
|
+
expect(res.body.data.user.role).toBe('user');
|
|
27
|
+
expect(res.body.data.user.email).toBe('foo@x.com');
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('rejects a role field', async () => {
|
|
31
|
+
const res = await register({ ...validBody, role: 'admin' });
|
|
32
|
+
expect(res.status).toBe(400);
|
|
33
|
+
expect(res.body.errors.some((e: { field: string }) => e.field === 'role')).toBe(true);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('treats emails case- and whitespace-insensitively', async () => {
|
|
37
|
+
expect((await register({ ...validBody, email: ' Foo@X.com ' })).status).toBe(201);
|
|
38
|
+
expect((await register({ ...validBody, email: 'foo@x.com' })).status).toBe(409);
|
|
39
|
+
const res = await login({ email: 'FOO@x.com', password: validBody.password });
|
|
40
|
+
expect(res.status).toBe(200);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('rejects a weak password', async () => {
|
|
44
|
+
const res = await register({ ...validBody, password: 'weak' });
|
|
45
|
+
expect(res.status).toBe(400);
|
|
46
|
+
expect(res.body.errors[0].field).toBe('password');
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
describe('POST /auth/login', () => {
|
|
51
|
+
it('gives the same 401 for a wrong password and an unknown email', async () => {
|
|
52
|
+
const { user } = await createUser();
|
|
53
|
+
const wrong = await login({ email: user.email, password: 'Wrong1234' });
|
|
54
|
+
const unknown = await login({ email: 'nobody@test.com', password: 'Wrong1234' });
|
|
55
|
+
expect(wrong.status).toBe(401);
|
|
56
|
+
expect(unknown.status).toBe(401);
|
|
57
|
+
expect(wrong.body.message).toBe('Invalid email or password');
|
|
58
|
+
expect(unknown.body).toEqual(wrong.body);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('returns an access token and sets a hardened refresh cookie', async () => {
|
|
62
|
+
const { user, password } = await createUser();
|
|
63
|
+
const res = await login({ email: user.email, password });
|
|
64
|
+
expect(res.status).toBe(200);
|
|
65
|
+
expect(res.body.message).toBe('Logged in successfully');
|
|
66
|
+
expect(res.body.data.accessToken).toEqual(expect.any(String));
|
|
67
|
+
expect(res.body.data.user).not.toHaveProperty('password');
|
|
68
|
+
|
|
69
|
+
const cookie = (res.headers['set-cookie'] as unknown as string[]).find((c) =>
|
|
70
|
+
c.startsWith('refreshToken='),
|
|
71
|
+
);
|
|
72
|
+
expect(cookie).toContain('HttpOnly');
|
|
73
|
+
expect(cookie).toContain('SameSite=Strict');
|
|
74
|
+
expect(cookie).toContain('Path=/api/v1/auth');
|
|
75
|
+
|
|
76
|
+
const tokenValue = getRefreshCookie(res)!.split('=')[1];
|
|
77
|
+
expect(JSON.stringify(res.body)).not.toContain(tokenValue);
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
describe('POST /auth/refresh', () => {
|
|
82
|
+
it('rotates the refresh token', async () => {
|
|
83
|
+
const { user, password } = await createUser();
|
|
84
|
+
const { refreshCookie } = await loginAs(app, { email: user.email, password });
|
|
85
|
+
const res = await refresh(refreshCookie);
|
|
86
|
+
expect(res.status).toBe(200);
|
|
87
|
+
expect(res.body.message).toBe('Token refreshed');
|
|
88
|
+
expect(res.body.data.accessToken).toEqual(expect.any(String));
|
|
89
|
+
const newCookie = getRefreshCookie(res);
|
|
90
|
+
expect(newCookie).not.toBeNull();
|
|
91
|
+
expect(newCookie).not.toBe(refreshCookie);
|
|
92
|
+
expect(JSON.stringify(res.body)).not.toContain(newCookie!.split('=')[1]);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('revokes every token when a rotated token is reused', async () => {
|
|
96
|
+
const { user, password } = await createUser();
|
|
97
|
+
const { refreshCookie: oldCookie } = await loginAs(app, { email: user.email, password });
|
|
98
|
+
const rotated = await refresh(oldCookie);
|
|
99
|
+
const newCookie = getRefreshCookie(rotated);
|
|
100
|
+
|
|
101
|
+
expect((await refresh(oldCookie)).status).toBe(401);
|
|
102
|
+
expect((await refresh(newCookie)).status).toBe(401);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('lets exactly one of two concurrent refreshes win', async () => {
|
|
106
|
+
const { user, password } = await createUser();
|
|
107
|
+
const { refreshCookie } = await loginAs(app, { email: user.email, password });
|
|
108
|
+
const results = await Promise.all([refresh(refreshCookie), refresh(refreshCookie)]);
|
|
109
|
+
const statuses = results.map((res) => res.status).sort();
|
|
110
|
+
// Whether the winner's new cookie survives depends on timing, so only the race itself is checked.
|
|
111
|
+
expect(statuses).toEqual([200, 401]);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it('rejects a tampered cookie', async () => {
|
|
115
|
+
const { user, password } = await createUser();
|
|
116
|
+
const { refreshCookie } = await loginAs(app, { email: user.email, password });
|
|
117
|
+
const [name, value] = refreshCookie.split('=');
|
|
118
|
+
const [header, payload, signature] = value.split('.');
|
|
119
|
+
const forged = JSON.parse(Buffer.from(payload, 'base64url').toString());
|
|
120
|
+
forged.sub = 'someone-else';
|
|
121
|
+
const tampered = `${header}.${Buffer.from(JSON.stringify(forged)).toString('base64url')}.${signature}`;
|
|
122
|
+
expect((await refresh(`${name}=${tampered}`)).status).toBe(401);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it('rejects an expired cookie', async () => {
|
|
126
|
+
const { user, password } = await createUser();
|
|
127
|
+
const { refreshCookie } = await loginAs(app, { email: user.email, password });
|
|
128
|
+
vi.useFakeTimers({ toFake: ['Date'] });
|
|
129
|
+
try {
|
|
130
|
+
vi.setSystemTime(Date.now() + 8 * 24 * 60 * 60 * 1000);
|
|
131
|
+
expect((await refresh(refreshCookie)).status).toBe(401);
|
|
132
|
+
} finally {
|
|
133
|
+
vi.useRealTimers();
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it('rejects a missing cookie', async () => {
|
|
138
|
+
expect((await refresh()).status).toBe(401);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it('rejects an access token used as the refresh cookie', async () => {
|
|
142
|
+
const { user } = await createUser();
|
|
143
|
+
const accessToken = signAccessToken({ userId: user.id, role: user.role });
|
|
144
|
+
expect((await refresh(`refreshToken=${accessToken}`)).status).toBe(401);
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
describe('POST /auth/logout', () => {
|
|
149
|
+
it('revokes the token and clears the cookie', async () => {
|
|
150
|
+
const { user, password } = await createUser();
|
|
151
|
+
const { refreshCookie } = await loginAs(app, { email: user.email, password });
|
|
152
|
+
const res = await request(app).post('/api/v1/auth/logout').set('Cookie', refreshCookie);
|
|
153
|
+
expect(res.status).toBe(200);
|
|
154
|
+
expect(res.body.message).toBe('Logged out successfully');
|
|
155
|
+
const cleared = (res.headers['set-cookie'] as unknown as string[]).find((c) =>
|
|
156
|
+
c.startsWith('refreshToken='),
|
|
157
|
+
);
|
|
158
|
+
expect(cleared).toMatch(/refreshToken=;/);
|
|
159
|
+
expect(cleared).toContain('Path=/api/v1/auth');
|
|
160
|
+
expect((await refresh(refreshCookie)).status).toBe(401);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it('succeeds without a cookie', async () => {
|
|
164
|
+
const res = await request(app).post('/api/v1/auth/logout');
|
|
165
|
+
expect(res.status).toBe(200);
|
|
166
|
+
expect(res.body.message).toBe('Logged out successfully');
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it('succeeds with a malformed cookie and still clears it', async () => {
|
|
170
|
+
const res = await request(app)
|
|
171
|
+
.post('/api/v1/auth/logout')
|
|
172
|
+
.set('Cookie', 'refreshToken=not-a-jwt');
|
|
173
|
+
expect(res.status).toBe(200);
|
|
174
|
+
const cleared = (res.headers['set-cookie'] as unknown as string[]).find((c) =>
|
|
175
|
+
c.startsWith('refreshToken='),
|
|
176
|
+
);
|
|
177
|
+
expect(cleared).toMatch(/refreshToken=;/);
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
describe('Bearer authentication', () => {
|
|
182
|
+
it('rejects a tampered access token', async () => {
|
|
183
|
+
const { user } = await createUser();
|
|
184
|
+
const token = signAccessToken({ userId: user.id, role: user.role });
|
|
185
|
+
const [header, payload, signature] = token.split('.');
|
|
186
|
+
const forged = JSON.parse(Buffer.from(payload, 'base64url').toString());
|
|
187
|
+
forged.role = 'admin';
|
|
188
|
+
const tampered = `${header}.${Buffer.from(JSON.stringify(forged)).toString('base64url')}.${signature}`;
|
|
189
|
+
const res = await request(app)
|
|
190
|
+
.get('/api/v1/users/me')
|
|
191
|
+
.set('Authorization', `Bearer ${tampered}`);
|
|
192
|
+
expect(res.status).toBe(401);
|
|
193
|
+
});
|
|
194
|
+
});
|