Skip to content
Closed
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
16 changes: 16 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
groups:
nestjs:
patterns:
- "@nestjs/*"
next:
patterns:
- "next"
- "react"
- "react-dom"
open-pull-requests-limit: 10
99 changes: 99 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
name: CI

on:
pull_request:
branches: [main]
push:
branches: [main]

jobs:
lint:
name: Lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: pnpm/action-setup@v4

- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'pnpm'

- run: pnpm install --frozen-lockfile

- name: Generate Prisma client
run: pnpm --filter api exec prisma generate
env:
DATABASE_URL: 'postgresql://dummy:dummy@localhost:5432/dummy'

- run: pnpm lint

type-check:
name: Type Check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: pnpm/action-setup@v4

- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'pnpm'

- run: pnpm install --frozen-lockfile

- name: Generate Prisma client
run: pnpm --filter api exec prisma generate
env:
DATABASE_URL: 'postgresql://dummy:dummy@localhost:5432/dummy'

- name: Build shared packages
run: pnpm --filter @repo/ui build:components

- run: pnpm check-types

test:
name: API Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: pnpm/action-setup@v4

- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'pnpm'

- run: pnpm install --frozen-lockfile

- name: Generate Prisma client
run: pnpm --filter api exec prisma generate
env:
DATABASE_URL: 'postgresql://dummy:dummy@localhost:5432/dummy'

- run: pnpm --filter api test

build:
name: Build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: pnpm/action-setup@v4

- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'pnpm'

- run: pnpm install --frozen-lockfile

- name: Generate Prisma client
run: pnpm --filter api exec prisma generate
env:
DATABASE_URL: 'postgresql://dummy:dummy@localhost:5432/dummy'

- run: pnpm build
2 changes: 1 addition & 1 deletion apps/api/fly.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ primary_region = 'sin'
internal_port = 2525

[[services.ports]]
port = 2525
port = 25

[[vm]]
memory = '256mb'
Expand Down
12 changes: 6 additions & 6 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
Expand All @@ -23,12 +23,12 @@
"dependencies": {
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.3",
"@nestjs/core": "^11.0.1",
"@nestjs/core": "^11.1.16",
"@nestjs/jwt": "^10.2.0",
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^11.0.1",
"@nestjs/platform-express": "^11.1.16",
"@nestjs/swagger": "^11.2.6",
"@nestjs/throttler": "^6.2.1",
"@nestjs/throttler": "^6.5.0",
"@prisma/client": "^6.19.2",
"@types/cookie-parser": "^1.4.10",
"@types/csurf": "^1.11.5",
Expand All @@ -48,9 +48,9 @@
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@eslint/js": "^9.18.0",
"@nestjs/cli": "^11.0.0",
"@nestjs/cli": "^11.0.16",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.0.1",
"@nestjs/testing": "^11.1.16",
"@swc/cli": "^0.6.0",
"@swc/core": "^1.10.7",
"@types/bcrypt": "^5.0.2",
Expand Down
28 changes: 21 additions & 7 deletions apps/api/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ export class AuthController {
@Public()
@Post('setup')
@HttpCode(HttpStatus.CREATED)
@ApiOperation({ summary: 'Initial user setup (only works if no users exist)' })
@ApiOperation({
summary: 'Initial user setup (only works if no users exist)',
})
@ApiResponse({
status: 201,
description: 'User created successfully',
Expand Down Expand Up @@ -70,7 +72,11 @@ export class AuthController {
const result = await this.authService.login(dto);

// Set httpOnly cookies for token storage
this.authService.setAuthCookies(res, result.accessToken, result.refreshToken);
this.authService.setAuthCookies(
res,
result.accessToken,
result.refreshToken,
);

// Return user info and tokens (tokens for backward compatibility)
return {
Expand Down Expand Up @@ -99,7 +105,9 @@ export class AuthController {
) {
// Try to get refresh token from cookie first, fallback to body for backward compatibility
const refreshToken =
req.cookies?.refreshToken || dto?.refreshToken;
((req.cookies as Record<string, string>)?.refreshToken as
| string
| undefined) || dto?.refreshToken;

if (!refreshToken) {
throw new Error('No refresh token provided');
Expand All @@ -108,7 +116,11 @@ export class AuthController {
const result = await this.authService.refreshTokens(refreshToken);

// Set httpOnly cookies for token storage
this.authService.setAuthCookies(res, result.accessToken, result.refreshToken);
this.authService.setAuthCookies(
res,
result.accessToken,
result.refreshToken,
);

// Return user info and tokens (tokens for backward compatibility)
return {
Expand All @@ -133,7 +145,9 @@ export class AuthController {
) {
// Try to get refresh token from cookie first, fallback to body for backward compatibility
const refreshToken =
req.cookies?.refreshToken || dto?.refreshToken;
((req.cookies as Record<string, string>)?.refreshToken as
| string
| undefined) || dto?.refreshToken;

if (refreshToken) {
await this.authService.revokeRefreshToken(refreshToken);
Expand All @@ -158,7 +172,7 @@ export class AuthController {
description: 'Current password is incorrect',
})
async changePassword(@Req() req: Request, @Body() dto: ChangePasswordDto) {
const userId = req.user!['id'];
const userId = (req.user as { id: string }).id;
return this.authService.changePassword(userId, dto);
}

Expand All @@ -170,7 +184,7 @@ export class AuthController {
description: 'User information retrieved successfully',
})
async getMe(@Req() req: Request) {
const userId = req.user!['id'];
const userId = (req.user as { id: string }).id;
return this.authService.getCurrentUser(userId);
}
}
33 changes: 16 additions & 17 deletions apps/api/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,9 @@ export class AuthService {
return null;
}

// Return user without password
const { password: _, ...result } = user;
// Return user without password - using destructuring to omit it
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { password: _pw, ...result } = user;
return result;
}

Expand Down Expand Up @@ -336,21 +337,19 @@ export class AuthService {

// Token metadata cookie - NOT httpOnly (readable by JavaScript)
// Used by frontend to know token expiration for proactive refresh
const tokenPayload = this.jwtService.decode(accessToken) as any;
res.cookie(
'tokenMeta',
JSON.stringify({
exp: tokenPayload.exp,
iat: tokenPayload.iat,
}),
{
httpOnly: false, // Readable by JavaScript
secure: isProduction,
sameSite: 'lax',
maxAge: 24 * 60 * 60 * 1000,
path: '/',
},
);
// jwtService.decode() returns any - safely extract known JWT claims
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */
const tokenPayload = this.jwtService.decode(accessToken);
const exp = tokenPayload.exp as number;
const iat = tokenPayload.iat as number;
/* eslint-enable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */
res.cookie('tokenMeta', JSON.stringify({ exp, iat }), {
httpOnly: false, // Readable by JavaScript
secure: isProduction,
sameSite: 'lax',
maxAge: 24 * 60 * 60 * 1000,
path: '/',
});
}

/**
Expand Down
5 changes: 4 additions & 1 deletion apps/api/src/auth/guards/jwt-auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ export class JwtAuthGuard extends AuthGuard(['jwt-cookie', 'jwt']) {
return super.canActivate(context);
}

handleRequest(err: any, user: any, info: any) {
handleRequest<TUser = { id: string; email: string; name: string | null }>(
err: Error | null,
user: TUser | false,
): TUser {
// If error or no user found with either strategy, throw unauthorized
if (err || !user) {
throw (
Expand Down
13 changes: 4 additions & 9 deletions apps/api/src/auth/strategies/jwt-cookie.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,13 @@ export class JwtCookieStrategy extends PassportStrategy(
// Extract JWT from cookie instead of Authorization header
jwtFromRequest: ExtractJwt.fromExtractors([
(request: Request) => {
// Try to get token from cookie
const token = request?.cookies?.accessToken;

if (!token) {
return null;
}

return token;
return (
(request?.cookies as Record<string, string>)?.accessToken ?? null
);
},
]),
ignoreExpiration: false,
secretOrKey: config.get('JWT_SECRET'),
secretOrKey: config.get<string>('JWT_SECRET'),
});
}

Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/auth/strategies/jwt.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: config.get('JWT_SECRET'),
secretOrKey: config.get<string>('JWT_SECRET'),
});
}

Expand Down
16 changes: 10 additions & 6 deletions apps/api/src/emails/emails.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export class EmailsController {
@Query('limit') limit?: string,
@Query('offset') offset?: string,
) {
const userId = req.user!['id'];
const userId = (req.user as { id: string }).id;
return this.emailsService.findAllByProject(
userId,
projectId,
Expand All @@ -79,7 +79,7 @@ export class EmailsController {
@Param('projectId') projectId: string,
@Param('emailId') emailId: string,
) {
const userId = req.user!['id'];
const userId = (req.user as { id: string }).id;
return this.emailsService.findOne(userId, projectId, emailId);
}

Expand All @@ -101,7 +101,7 @@ export class EmailsController {
@Param('emailId') emailId: string,
@Body('isRead') isRead: boolean,
) {
const userId = req.user!['id'];
const userId = (req.user as { id: string }).id;
return this.emailsService.markAsRead(userId, projectId, emailId, isRead);
}

Expand All @@ -122,7 +122,7 @@ export class EmailsController {
@Param('projectId') projectId: string,
@Param('emailId') emailId: string,
) {
const userId = req.user!['id'];
const userId = (req.user as { id: string }).id;
return this.emailsService.remove(userId, projectId, emailId);
}

Expand All @@ -145,8 +145,12 @@ export class EmailsController {
@Param('attachmentId') attachmentId: string,
@Res({ passthrough: true }) res: Response,
) {
const userId = req.user!['id'];
const attachment = await this.emailsService.getAttachment(userId, projectId, attachmentId);
const userId = (req.user as { id: string }).id;
const attachment = await this.emailsService.getAttachment(
userId,
projectId,
attachmentId,
);

const file = fs.createReadStream(attachment.storagePath);

Expand Down
Loading