security: address assessment findings and bump to v2026.3.11
- C1: Disable Swagger UI in production (env gate) - M1+M2: Add Helmet.js for security headers (CSP, X-Frame-Options, X-Content-Type-Options, Referrer-Policy) and remove X-Powered-By - H2: Add @nestjs/throttler rate limiting (5 req/min on login/register) - M4: Remove orgSchema from JWT payload and client-side storage; tenant middleware now resolves schema from orgId via cached DB lookup - L1: Fix Chatwoot user identification (read from auth store on ready) - Remove schemaName from frontend Organization type and UI displays Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -2,6 +2,7 @@ import { Module, MiddlewareConsumer, NestModule } from '@nestjs/common';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { ThrottlerModule } from '@nestjs/throttler';
|
||||
import { AppController } from './app.controller';
|
||||
import { DatabaseModule } from './database/database.module';
|
||||
import { TenantMiddleware } from './database/tenant.middleware';
|
||||
@@ -52,6 +53,10 @@ import { ScheduleModule } from '@nestjs/schedule';
|
||||
},
|
||||
}),
|
||||
}),
|
||||
ThrottlerModule.forRoot([{
|
||||
ttl: 60000, // 1-minute window
|
||||
limit: 100, // 100 requests per minute (global default)
|
||||
}]),
|
||||
DatabaseModule,
|
||||
AuthModule,
|
||||
OrganizationsModule,
|
||||
|
||||
@@ -13,8 +13,8 @@ export interface TenantRequest extends Request {
|
||||
|
||||
@Injectable()
|
||||
export class TenantMiddleware implements NestMiddleware {
|
||||
// In-memory cache for org status to avoid DB hit per request
|
||||
private orgStatusCache = new Map<string, { status: string; cachedAt: number }>();
|
||||
// In-memory cache for org info to avoid DB hit per request
|
||||
private orgCache = new Map<string, { status: string; schemaName: string; cachedAt: number }>();
|
||||
private static readonly CACHE_TTL = 60_000; // 60 seconds
|
||||
|
||||
constructor(
|
||||
@@ -30,23 +30,25 @@ export class TenantMiddleware implements NestMiddleware {
|
||||
const token = authHeader.substring(7);
|
||||
const secret = this.configService.get<string>('JWT_SECRET');
|
||||
const decoded = jwt.verify(token, secret!) as any;
|
||||
if (decoded?.orgSchema) {
|
||||
// Check if the org is still active (catches post-JWT suspension)
|
||||
if (decoded.orgId) {
|
||||
const status = await this.getOrgStatus(decoded.orgId);
|
||||
if (status && ['suspended', 'archived'].includes(status)) {
|
||||
if (decoded?.orgId) {
|
||||
// Look up org info (status + schema) from orgId with caching
|
||||
const orgInfo = await this.getOrgInfo(decoded.orgId);
|
||||
if (orgInfo) {
|
||||
if (['suspended', 'archived'].includes(orgInfo.status)) {
|
||||
res.status(403).json({
|
||||
statusCode: 403,
|
||||
message: `This organization has been ${status}. Please contact your administrator.`,
|
||||
message: `This organization has been ${orgInfo.status}. Please contact your administrator.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
req.tenantSchema = orgInfo.schemaName;
|
||||
}
|
||||
|
||||
req.tenantSchema = decoded.orgSchema;
|
||||
req.orgId = decoded.orgId;
|
||||
req.userId = decoded.sub;
|
||||
req.userRole = decoded.role;
|
||||
} else if (decoded?.sub) {
|
||||
// Superadmin or user without org — still set userId
|
||||
req.userId = decoded.sub;
|
||||
}
|
||||
} catch {
|
||||
// Token invalid or expired - let Passport handle the auth error
|
||||
@@ -55,19 +57,23 @@ export class TenantMiddleware implements NestMiddleware {
|
||||
next();
|
||||
}
|
||||
|
||||
private async getOrgStatus(orgId: string): Promise<string | null> {
|
||||
const cached = this.orgStatusCache.get(orgId);
|
||||
private async getOrgInfo(orgId: string): Promise<{ status: string; schemaName: string } | null> {
|
||||
const cached = this.orgCache.get(orgId);
|
||||
if (cached && Date.now() - cached.cachedAt < TenantMiddleware.CACHE_TTL) {
|
||||
return cached.status;
|
||||
return { status: cached.status, schemaName: cached.schemaName };
|
||||
}
|
||||
try {
|
||||
const result = await this.dataSource.query(
|
||||
`SELECT status FROM shared.organizations WHERE id = $1`,
|
||||
`SELECT status, schema_name as "schemaName" FROM shared.organizations WHERE id = $1`,
|
||||
[orgId],
|
||||
);
|
||||
if (result.length > 0) {
|
||||
this.orgStatusCache.set(orgId, { status: result[0].status, cachedAt: Date.now() });
|
||||
return result[0].status;
|
||||
this.orgCache.set(orgId, {
|
||||
status: result[0].status,
|
||||
schemaName: result[0].schemaName,
|
||||
cachedAt: Date.now(),
|
||||
});
|
||||
return { status: result[0].status, schemaName: result[0].schemaName };
|
||||
}
|
||||
} catch {
|
||||
// Non-critical — don't block requests on cache miss errors
|
||||
|
||||
@@ -3,6 +3,7 @@ import * as os from 'node:os';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
|
||||
import helmet from 'helmet';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
const cluster = _cluster as any; // Cast to 'any' bypasses the missing property errors
|
||||
@@ -41,6 +42,24 @@ async function bootstrap() {
|
||||
|
||||
app.setGlobalPrefix('api');
|
||||
|
||||
// Security headers — Helmet sets CSP, X-Frame-Options, X-Content-Type-Options,
|
||||
// Referrer-Policy, Permissions-Policy, and removes X-Powered-By
|
||||
app.use(
|
||||
helmet({
|
||||
contentSecurityPolicy: {
|
||||
directives: {
|
||||
defaultSrc: ["'self'"],
|
||||
scriptSrc: ["'self'", "'unsafe-inline'", 'https://chat.hoaledgeriq.com'],
|
||||
connectSrc: ["'self'", 'https://chat.hoaledgeriq.com', 'wss://chat.hoaledgeriq.com'],
|
||||
imgSrc: ["'self'", 'data:', 'https://chat.hoaledgeriq.com'],
|
||||
styleSrc: ["'self'", "'unsafe-inline'"],
|
||||
frameSrc: ["'self'", 'https://chat.hoaledgeriq.com'],
|
||||
fontSrc: ["'self'", 'data:'],
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
// Request logging — only in development (too noisy / slow for prod)
|
||||
if (!isProduction) {
|
||||
app.use((req: any, _res: any, next: any) => {
|
||||
@@ -63,15 +82,17 @@ async function bootstrap() {
|
||||
credentials: true,
|
||||
});
|
||||
|
||||
// Swagger docs — available in all environments
|
||||
const config = new DocumentBuilder()
|
||||
.setTitle('HOA LedgerIQ API')
|
||||
.setDescription('API for the HOA LedgerIQ')
|
||||
.setVersion('2026.03.10')
|
||||
.addBearerAuth()
|
||||
.build();
|
||||
const document = SwaggerModule.createDocument(app, config);
|
||||
SwaggerModule.setup('api/docs', app, document);
|
||||
// Swagger docs — disabled in production to avoid exposing API surface
|
||||
if (!isProduction) {
|
||||
const config = new DocumentBuilder()
|
||||
.setTitle('HOA LedgerIQ API')
|
||||
.setDescription('API for the HOA LedgerIQ')
|
||||
.setVersion('2026.3.11')
|
||||
.addBearerAuth()
|
||||
.build();
|
||||
const document = SwaggerModule.createDocument(app, config);
|
||||
SwaggerModule.setup('api/docs', app, document);
|
||||
}
|
||||
|
||||
await app.listen(3000);
|
||||
console.log(`Backend worker ${process.pid} listening on port 3000`);
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
|
||||
import { AuthGuard } from '@nestjs/passport';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
import { AuthService } from './auth.service';
|
||||
import { RegisterDto } from './dto/register.dto';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
@@ -23,12 +24,14 @@ export class AuthController {
|
||||
|
||||
@Post('register')
|
||||
@ApiOperation({ summary: 'Register a new user' })
|
||||
@Throttle({ default: { limit: 5, ttl: 60000 } })
|
||||
async register(@Body() dto: RegisterDto) {
|
||||
return this.authService.register(dto);
|
||||
}
|
||||
|
||||
@Post('login')
|
||||
@ApiOperation({ summary: 'Login with email and password' })
|
||||
@Throttle({ default: { limit: 5, ttl: 60000 } })
|
||||
@UseGuards(AuthGuard('local'))
|
||||
async login(@Request() req: any, @Body() _dto: LoginDto) {
|
||||
const ip = req.headers['x-forwarded-for'] || req.ip;
|
||||
|
||||
@@ -118,7 +118,6 @@ export class AuthService {
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
orgId: membership.organizationId,
|
||||
orgSchema: membership.organization.schemaName,
|
||||
role: membership.role,
|
||||
};
|
||||
|
||||
@@ -177,7 +176,6 @@ export class AuthService {
|
||||
|
||||
if (defaultOrg) {
|
||||
payload.orgId = defaultOrg.organizationId;
|
||||
payload.orgSchema = defaultOrg.organization?.schemaName;
|
||||
payload.role = defaultOrg.role;
|
||||
}
|
||||
|
||||
@@ -195,7 +193,6 @@ export class AuthService {
|
||||
organizations: orgs.map((uo) => ({
|
||||
id: uo.organizationId,
|
||||
name: uo.organization?.name,
|
||||
schemaName: uo.organization?.schemaName,
|
||||
status: uo.organization?.status,
|
||||
role: uo.role,
|
||||
})),
|
||||
|
||||
@@ -18,7 +18,6 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
sub: payload.sub,
|
||||
email: payload.email,
|
||||
orgId: payload.orgId,
|
||||
orgSchema: payload.orgSchema,
|
||||
role: payload.role,
|
||||
isSuperadmin: payload.isSuperadmin || false,
|
||||
impersonatedBy: payload.impersonatedBy || null,
|
||||
|
||||
@@ -16,7 +16,7 @@ export class HealthScoresController {
|
||||
@Get('latest')
|
||||
@ApiOperation({ summary: 'Get latest operating and reserve health scores' })
|
||||
getLatest(@Req() req: any) {
|
||||
const schema = req.user?.orgSchema;
|
||||
const schema = req.tenantSchema;
|
||||
return this.service.getLatestScores(schema);
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ export class HealthScoresController {
|
||||
@ApiOperation({ summary: 'Trigger both health score recalculations (async — returns immediately)' })
|
||||
@AllowViewer()
|
||||
async calculate(@Req() req: any) {
|
||||
const schema = req.user?.orgSchema;
|
||||
const schema = req.tenantSchema;
|
||||
|
||||
// Fire-and-forget — background processing saves results to DB
|
||||
Promise.all([
|
||||
@@ -44,7 +44,7 @@ export class HealthScoresController {
|
||||
@ApiOperation({ summary: 'Trigger operating fund health score recalculation (async)' })
|
||||
@AllowViewer()
|
||||
async calculateOperating(@Req() req: any) {
|
||||
const schema = req.user?.orgSchema;
|
||||
const schema = req.tenantSchema;
|
||||
|
||||
// Fire-and-forget
|
||||
this.service.calculateScore(schema, 'operating').catch((err) => {
|
||||
@@ -61,7 +61,7 @@ export class HealthScoresController {
|
||||
@ApiOperation({ summary: 'Trigger reserve fund health score recalculation (async)' })
|
||||
@AllowViewer()
|
||||
async calculateReserve(@Req() req: any) {
|
||||
const schema = req.user?.orgSchema;
|
||||
const schema = req.tenantSchema;
|
||||
|
||||
// Fire-and-forget
|
||||
this.service.calculateScore(schema, 'reserve').catch((err) => {
|
||||
|
||||
Reference in New Issue
Block a user