Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions packages/backend/.prettierrc
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all",
"tabWidth": 2,
"useTabs": false
}
"printWidth": 120
}
31 changes: 28 additions & 3 deletions packages/backend/eslint.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ import eslint from '@eslint/js';
import globals from 'globals';
import tseslint from 'typescript-eslint';
import eslintPluginJest from 'eslint-plugin-jest';
import eslintPluginImport from 'eslint-plugin-import';
import eslintPluginPrettier from 'eslint-plugin-prettier/recommended';

export default defineConfig(
eslint.configs.recommended,
...tseslint.configs.recommendedTypeChecked,
eslintPluginImport.flatConfigs.recommended,
eslintPluginImport.flatConfigs.typescript,
eslintPluginPrettier,
eslintPluginJest.configs['flat/recommended'],
{
Expand All @@ -24,12 +27,34 @@ export default defineConfig(
tsconfigRootDir: import.meta.dirname,
},
},
settings: {
'import/resolver': {
typescript: {
project: './tsconfig.json',
},
},
},
},
{
rules: {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-floating-promises': 'error',
'@typescript-eslint/no-unsafe-argument': 'error',
'@typescript-eslint/consistent-type-imports': 'error',
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
],
'no-console': ['error', { allow: ['warn', 'error'] }],
'import/order': [
'error',
{
groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index'],
'newlines-between': 'always',
alphabetize: { order: 'asc', caseInsensitive: true },
},
],
'import/no-unresolved': 'off',
},
},
{
Expand Down
6 changes: 4 additions & 2 deletions packages/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
"start:dev": "dotenv -e .env.development.local -- nest start --watch",
"start:debug": "dotenv -e .env.development.local -- nest start --debug --watch",
"start:prod": "prisma migrate deploy && node dist/src/main",
"lint": "eslint src/**/*.ts",
"lint:fix": "eslint --fix src/**/*.ts",
"lint": "eslint \"src/**/*.ts\"",
"lint:fix": "eslint --fix \"src/**/*.ts\"",
"format": "prettier --check src/",
"format:fix": "prettier --write src/",
"pretest": "pnpm build",
Expand Down Expand Up @@ -71,6 +71,8 @@
"dotenv-cli": "10.0.0",
"eslint": "9.39.3",
"eslint-config-prettier": "10.1.8",
"eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-jest": "29.15.0",
"eslint-plugin-prettier": "5.5.5",
"globals": "16.5.0",
Expand Down
17 changes: 5 additions & 12 deletions packages/backend/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,14 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { LoggerModule } from './logger/logger.module.js';
import { PrismaModule } from './prisma/prisma.module.js';

import { AuthModule } from './auth/auth.module.js';
import { BotModule } from './bot/bot.module.js';
import { ClustersModule } from './clusters/clusters.module.js';
import { DockerModule } from './docker/docker.module.js';
import { AuthModule } from './auth/auth.module.js';
import { LoggerModule } from './logger/logger.module.js';
import { PrismaModule } from './prisma/prisma.module.js';

@Module({
imports: [
LoggerModule,
ConfigModule,
PrismaModule,
BotModule,
ClustersModule,
DockerModule,
AuthModule,
],
imports: [LoggerModule, ConfigModule, PrismaModule, BotModule, ClustersModule, DockerModule, AuthModule],
})
export class AppModule {}
9 changes: 6 additions & 3 deletions packages/backend/src/auth/auth.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { Test, TestingModule } from '@nestjs/testing';
import type { TestingModule } from '@nestjs/testing';
import { Test } from '@nestjs/testing';
import type { DeepMockProxy } from 'jest-mock-extended';
import { mockDeep } from 'jest-mock-extended';

import { AuthController } from './auth.controller.js';
import { AuthGuard } from './guards/jwt.guard.js';
import { DeepMockProxy, mockDeep } from 'jest-mock-extended';
import { AuthService } from './auth.service.js';
import { AuthGuard } from './guards/jwt.guard.js';

describe('AuthController', () => {
let controller: AuthController;
Expand Down
3 changes: 2 additions & 1 deletion packages/backend/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@ import {
ApiTags,
ApiUnauthorizedResponse,
} from '@nestjs/swagger';

import { AuthService } from './auth.service.js';
import { RegisterDto } from './dto/register.dto.js';
import { LoginDto } from './dto/login.dto.js';
import { RegisterDto } from './dto/register.dto.js';
import { UserTokenDto } from './entities/user-token.entity.js';

@Controller('auth')
Expand Down
9 changes: 5 additions & 4 deletions packages/backend/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Module } from '@nestjs/common';
import { JwtModule, JwtSignOptions } from '@nestjs/jwt';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtModule, JwtSignOptions } from '@nestjs/jwt';

import { PrismaModule } from '../prisma/prisma.module.js';

import { AuthController } from './auth.controller.js';
import { AuthService } from './auth.service.js';
import { PrismaModule } from '../prisma/prisma.module.js';
import { AuthGuard } from './guards/jwt.guard.js';

@Module({
Expand All @@ -15,8 +17,7 @@ import { AuthGuard } from './guards/jwt.guard.js';
useFactory: (config: ConfigService) => ({
secret: config.getOrThrow<string>('JWT_SECRET'),
signOptions: {
expiresIn:
config.getOrThrow<JwtSignOptions['expiresIn']>('JWT_EXPIRES_IN'),
expiresIn: config.getOrThrow<JwtSignOptions['expiresIn']>('JWT_EXPIRES_IN'),
},
}),
}),
Expand Down
50 changes: 18 additions & 32 deletions packages/backend/src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import type { Prisma } from '@hallmaster/prisma-client';
import { beforeEach, describe, expect, it, jest } from '@jest/globals';
import { Test, TestingModule } from '@nestjs/testing';
import { ConflictException, UnauthorizedException } from '@nestjs/common';
import { JwtModule, JwtService } from '@nestjs/jwt';
import { DeepMockProxy, mockDeep } from 'jest-mock-extended';
import { AuthService } from './auth.service.js';
import type { TestingModule } from '@nestjs/testing';
import { Test } from '@nestjs/testing';
import type { DeepMockProxy } from 'jest-mock-extended';
import { mockDeep } from 'jest-mock-extended';

import { PrismaService } from '../prisma/prisma.service.js';
import { RegisterDto } from './dto/register.dto.js';
import { Prisma } from '@hallmaster/prisma-client';
import { ConflictException, UnauthorizedException } from '@nestjs/common';

import { AuthService } from './auth.service.js';
import type { RegisterDto } from './dto/register.dto.js';

describe('authService', () => {
let service: AuthService;
Expand Down Expand Up @@ -54,9 +58,7 @@ describe('authService', () => {

const hashPasswordMock = jest
.spyOn(AuthService, 'hashPassword')
.mockImplementationOnce((password) =>
Promise.resolve(`${password}-hashed`),
);
.mockImplementationOnce((password) => Promise.resolve(`${password}-hashed`));

const signAsyncMock = jest.spyOn(jwtService, 'signAsync');

Expand Down Expand Up @@ -101,9 +103,7 @@ describe('authService', () => {

prismaService.user.count.mockResolvedValueOnce(1);

await expect(service.register(credentials)).rejects.toBeInstanceOf(
ConflictException,
);
await expect(service.register(credentials)).rejects.toBeInstanceOf(ConflictException);

expect(prismaService.user.count).toHaveBeenCalledTimes(1);
});
Expand All @@ -121,9 +121,7 @@ describe('authService', () => {

const verifyPasswordMock = jest
.spyOn(AuthService, 'verifyPassword')
.mockImplementationOnce((hash: string, password: string) =>
Promise.resolve(hash === `${password}-hashed`),
);
.mockImplementationOnce((hash: string, password: string) => Promise.resolve(hash === `${password}-hashed`));

const signAsyncMock = jest.spyOn(jwtService, 'signAsync');

Expand All @@ -140,10 +138,7 @@ describe('authService', () => {
});
expect(prismaService.user.findFirst).toHaveBeenCalledTimes(1);

expect(verifyPasswordMock).toHaveBeenCalledWith(
`${credentials.password}-hashed`,
credentials.password,
);
expect(verifyPasswordMock).toHaveBeenCalledWith(`${credentials.password}-hashed`, credentials.password);
expect(verifyPasswordMock).toHaveBeenCalledTimes(1);

expect(signAsyncMock).toHaveBeenCalledWith({
Expand All @@ -169,9 +164,7 @@ describe('authService', () => {

prismaService.user.findFirst.mockResolvedValueOnce(null);

await expect(service.login(credentials)).rejects.toBeInstanceOf(
UnauthorizedException,
);
await expect(service.login(credentials)).rejects.toBeInstanceOf(UnauthorizedException);

expect(prismaService.user.findFirst).toHaveBeenCalledWith({
select: {
Expand All @@ -198,13 +191,9 @@ describe('authService', () => {

const verifyPasswordMock = jest
.spyOn(AuthService, 'verifyPassword')
.mockImplementationOnce((hash: string, password: string) =>
Promise.resolve(hash === `${password}-hashed`),
);
.mockImplementationOnce((hash: string, password: string) => Promise.resolve(hash === `${password}-hashed`));

await expect(service.login(credentials)).rejects.toBeInstanceOf(
UnauthorizedException,
);
await expect(service.login(credentials)).rejects.toBeInstanceOf(UnauthorizedException);

expect(prismaService.user.findFirst).toHaveBeenCalledWith({
select: {
Expand All @@ -217,10 +206,7 @@ describe('authService', () => {
});
expect(prismaService.user.findFirst).toHaveBeenCalledTimes(1);

expect(verifyPasswordMock).toHaveBeenCalledWith(
`not-${credentials.password}-hashed`,
credentials.password,
);
expect(verifyPasswordMock).toHaveBeenCalledWith(`not-${credentials.password}-hashed`, credentials.password);
expect(verifyPasswordMock).toHaveBeenCalledTimes(1);
});
});
18 changes: 7 additions & 11 deletions packages/backend/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import { randomBytes } from 'node:crypto';
import {
ConflictException,
Injectable,
UnauthorizedException,
} from '@nestjs/common';

import { ConflictException, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { hash, argon2id, verify } from 'argon2';

import { PrismaService } from '../prisma/prisma.service.js';
import { RegisterDto } from './dto/register.dto.js';

import { LoginDto } from './dto/login.dto.js';
import { UserTokenDto } from './entities/user-token.entity.js';
import { RegisterDto } from './dto/register.dto.js';
import { UserTokenDataDto } from './entities/user-token-data.entity.js';
import { UserTokenDto } from './entities/user-token.entity.js';

/* https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#argon2id */
const OWASP_CONFIGS = [
Expand Down Expand Up @@ -85,10 +84,7 @@ export class AuthService {
throw new UnauthorizedException();
}

const passwordMatch = await AuthService.verifyPassword(
user.password,
dto.password,
);
const passwordMatch = await AuthService.verifyPassword(user.password, dto.password);
if (!passwordMatch) {
throw new UnauthorizedException();
}
Expand Down
1 change: 1 addition & 0 deletions packages/backend/src/auth/dto/login.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createZodDto } from 'nestjs-zod';

import { loginSchema } from '../schemas/login.schema.js';

export class LoginDto extends createZodDto(loginSchema) {}
1 change: 1 addition & 0 deletions packages/backend/src/auth/dto/register.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createZodDto } from 'nestjs-zod';

import { registerSchema } from '../schemas/register.schema.js';

export class RegisterDto extends createZodDto(registerSchema) {}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createZodDto } from 'nestjs-zod';

import { userTokenDataSchema } from '../schemas/user-token-data.schema.js';

export class UserTokenDataDto extends createZodDto(userTokenDataSchema) {}
1 change: 1 addition & 0 deletions packages/backend/src/auth/entities/user-token.entity.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createZodDto } from 'nestjs-zod';

import { userTokenSchema } from '../schemas/user-token.schema.js';

export class UserTokenDto extends createZodDto(userTokenSchema) {}
8 changes: 2 additions & 6 deletions packages/backend/src/auth/guards/jwt.guard.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { FastifyRequest } from 'fastify';

import { AuthService } from '../auth.service.js';

@Injectable()
Expand Down
2 changes: 1 addition & 1 deletion packages/backend/src/auth/schemas/login.schema.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import z from 'zod';
import { z } from 'zod';

export const loginSchema = z.object({
username: z.string().min(1).meta({
Expand Down
2 changes: 1 addition & 1 deletion packages/backend/src/auth/schemas/register.schema.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import z from 'zod';
import { z } from 'zod';

export const registerSchema = z.object({
username: z.string().min(1).meta({
Expand Down
6 changes: 2 additions & 4 deletions packages/backend/src/auth/schemas/user-token-data.schema.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import z from 'zod';
import { z } from 'zod';

export const userTokenDataSchema = z.object({
username: z
.string()
.meta({ description: "The authenticated user's username." }),
username: z.string().meta({ description: "The authenticated user's username." }),
});

export type UserTokenData = z.infer<typeof userTokenDataSchema>;
2 changes: 1 addition & 1 deletion packages/backend/src/auth/schemas/user-token.schema.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import z from 'zod';
import { z } from 'zod';

export const userTokenSchema = z.object({
token: z.jwt().meta({
Expand Down
10 changes: 7 additions & 3 deletions packages/backend/src/bot/bot.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import { Test, TestingModule } from '@nestjs/testing';
import { DeepMockProxy, mockDeep } from 'jest-mock-extended';
import type { TestingModule } from '@nestjs/testing';
import { Test } from '@nestjs/testing';
import type { DeepMockProxy } from 'jest-mock-extended';
import { mockDeep } from 'jest-mock-extended';

import { AuthGuard } from '../auth/guards/jwt.guard.js';

import { BotController } from './bot.controller.js';
import { BotService } from './bot.service.js';
import { AuthGuard } from '../auth/guards/jwt.guard.js';

describe('BotController', () => {
let controller: BotController;
Expand Down
Loading
Loading