CognxSafeTrack Claude Sonnet 4.6 commited on
Commit ·
aa4f69f
1
Parent(s): 2859b85
fix: security hardening, log all silent catch blocks, remove prisma cast
Browse filesSecurity:
- whatsapp.ts: remove WHATSAPP_VERIFY_TOKEN hardcoded fallback — return 500
if env var is missing instead of silently accepting a public default
- rateLimit.ts: key by req.ip (not spoofable x-organization-id header)
Code quality — 7 empty catch blocks now log with context:
- NudgeHandler, AdminHandler (+ missing logger import), EnrollHandler (x2),
MediaHandler (x2), organization.ts invalidateOrgCache
- admin.ts: remove (prisma as any).normalizationRule — model is in schema,
cast was unnecessary
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Files changed (8)
- apps/api/src/middleware/rateLimit.ts+1-1
- apps/api/src/routes/admin.ts+1-1
- apps/api/src/routes/whatsapp.ts+2-1
- apps/whatsapp-worker/src/handlers/AdminHandler.ts+4-1
- apps/whatsapp-worker/src/handlers/EnrollHandler.ts+7-2
- apps/whatsapp-worker/src/handlers/MediaHandler.ts+6-2
- apps/whatsapp-worker/src/handlers/NudgeHandler.ts+3-1
- apps/whatsapp-worker/src/services/organization.ts+3-1
6 unmodified lines789101112136 unmodified linesawait server.register(rateLimit as any, {max: 100,timeWindow: '1 minute',keyGenerator: (req: FastifyRequest) => (req.headers['x-organization-id'] as string) || req.ip,errorResponseBuilder: (_request: FastifyRequest, context: { after: string }) => {return {statusCode: 429,6 unmodified lines789101112136 unmodified linesawait server.register(rateLimit as any, {max: 100,timeWindow: '1 minute',keyGenerator: (req: FastifyRequest) => req.ip as string,errorResponseBuilder: (_request: FastifyRequest, context: { after: string }) => {return {statusCode: 429,
447 unmodified lines448449450451452453454447 unmodified lines// List current normalization rules from DBfastify.get('/training/rules', async () => {return (prisma as any).normalizationRule.findMany({orderBy: { original: 'asc' }});});447 unmodified lines448449450451452453454447 unmodified lines// List current normalization rules from DBfastify.get('/training/rules', async () => {return prisma.normalizationRule.findMany({orderBy: { original: 'asc' }});});
44 unmodified lines4546474849505144 unmodified linesconst token = query['hub.verify_token'];const challenge = query['hub.challenge'];const VERIFY_TOKEN = process.env.WHATSAPP_VERIFY_TOKEN || 'xamle_studio_secret_token';if (mode && token) {if (mode === 'subscribe' && token === VERIFY_TOKEN) {44 unmodified lines454647484950515244 unmodified linesconst token = query['hub.verify_token'];const challenge = query['hub.challenge'];const VERIFY_TOKEN = process.env.WHATSAPP_VERIFY_TOKEN;if (!VERIFY_TOKEN) return reply.code(500).send({ error: 'WHATSAPP_VERIFY_TOKEN not configured' });if (mode && token) {if (mode === 'subscribe' && token === VERIFY_TOKEN) {
1 unmodified line2345677 unmodified lines151617181920211 unmodified lineimport Redis from 'ioredis';import { JobHandler, JobData } from './types';import { prisma } from '../services/prisma';import { sendTextMessage } from '../whatsapp-cloud';interface TenantConfig {7 unmodified linestry {const cached = await connection.get(cacheKey);if (cached) return JSON.parse(cached);} catch (err) {}const org = await prisma.organization.findUnique({where: { id: organizationId },1 unmodified line23456787 unmodified lines1617181920212223241 unmodified lineimport Redis from 'ioredis';import { JobHandler, JobData } from './types';import { prisma } from '../services/prisma';import { logger } from '../logger';import { sendTextMessage } from '../whatsapp-cloud';interface TenantConfig {7 unmodified linestry {const cached = await connection.get(cacheKey);if (cached) return JSON.parse(cached);} catch (err) {logger.warn({ err, organizationId }, '[AdminHandler] Redis cache lookup failed');}const org = await prisma.organization.findUnique({where: { id: organizationId },
1 unmodified line2345678 unmodified lines1617181920212237 unmodified lines606162636465661 unmodified lineimport Redis from 'ioredis';import { JobHandler, JobData } from './types';import { prisma } from '../services/prisma';import { sendTextMessage } from '../whatsapp-cloud';import { getApiUrl, getAdminApiKey } from '../config';8 unmodified linestry {const cached = await connection.get(cacheKey);if (cached) return JSON.parse(cached);} catch (err) {}const org = await prisma.organization.findUnique({where: { id: organizationId },37 unmodified linesawait sendTextMessage(user.phone, `💳 Cette formation est Premium. Complétez votre paiement ici :\n${checkoutData.url}`, tenantConfig);}}} catch (err) {}} else {const existing = await prisma.enrollment.findFirst({ where: { userId, trackId } });if (!existing) {1 unmodified line23456788 unmodified lines17181920212223242537 unmodified lines6364656667686970711 unmodified lineimport Redis from 'ioredis';import { JobHandler, JobData } from './types';import { prisma } from '../services/prisma';import { logger } from '../logger';import { sendTextMessage } from '../whatsapp-cloud';import { getApiUrl, getAdminApiKey } from '../config';8 unmodified linestry {const cached = await connection.get(cacheKey);if (cached) return JSON.parse(cached);} catch (err) {logger.warn({ err, organizationId }, '[EnrollHandler] Redis cache lookup failed');}const org = await prisma.organization.findUnique({where: { id: organizationId },37 unmodified linesawait sendTextMessage(user.phone, `💳 Cette formation est Premium. Complétez votre paiement ici :\n${checkoutData.url}`, tenantConfig);}}} catch (err) {logger.error({ err, userId, trackId }, '[EnrollHandler] Premium checkout failed');}} else {const existing = await prisma.enrollment.findFirst({ where: { userId, trackId } });if (!existing) {
19 unmodified lines2021222324252641 unmodified lines6869707172737419 unmodified linestry {const cached = await connection.get(cacheKey);if (cached) return JSON.parse(cached);} catch (err) {}const org = await prisma.organization.findUnique({where: { id: organizationId },41 unmodified linesheaders: { 'x-organization-id': organizationId as string }});audioUrl = storeRes.data.url;} catch (err) {}const user = await prisma.user.findFirst({ where: { phone } });if (user) {19 unmodified lines20212223242526272841 unmodified lines70717273747576777819 unmodified linestry {const cached = await connection.get(cacheKey);if (cached) return JSON.parse(cached);} catch (err) {logger.warn({ err, organizationId }, '[MediaHandler] Redis cache lookup failed');}const org = await prisma.organization.findUnique({where: { id: organizationId },41 unmodified linesheaders: { 'x-organization-id': organizationId as string }});audioUrl = storeRes.data.url;} catch (err) {logger.warn({ err, mediaId }, '[MediaHandler] Failed to store audio to R2');}const user = await prisma.user.findFirst({ where: { phone } });if (user) {
15 unmodified lines1617181920212215 unmodified linestry {const cached = await connection.get(cacheKey);if (cached) return JSON.parse(cached);} catch (err) {}const org = await prisma.organization.findUnique({where: { id: organizationId },15 unmodified lines16171819202122232415 unmodified linestry {const cached = await connection.get(cacheKey);if (cached) return JSON.parse(cached);} catch (err) {logger.warn({ err, organizationId }, '[NudgeHandler] Redis cache lookup failed');}const org = await prisma.organization.findUnique({where: { id: organizationId },
81 unmodified lines8283848586878881 unmodified linestry {localCache.delete(`org:full:${id}`);await redis.del(`org:full:${id}`);} catch (err) {}}export async function getOrganizationByPhoneNumberId(phoneNumberId: string): Promise<string> {81 unmodified lines82838485868788899081 unmodified linestry {localCache.delete(`org:full:${id}`);await redis.del(`org:full:${id}`);} catch (err) {logger.warn({ err, id }, '[OrgCache] Cache invalidation failed');}}export async function getOrganizationByPhoneNumberId(phoneNumberId: string): Promise<string> {
apps/api/src/middleware/rateLimit.ts+1-1
apps/api/src/routes/admin.ts+1-1
apps/api/src/routes/whatsapp.ts+2-1
apps/whatsapp-worker/src/handlers/AdminHandler.ts+4-1
apps/whatsapp-worker/src/handlers/EnrollHandler.ts+7-2
apps/whatsapp-worker/src/handlers/MediaHandler.ts+6-2
apps/whatsapp-worker/src/handlers/NudgeHandler.ts+3-1
apps/whatsapp-worker/src/services/organization.ts+3-1