Skip to content

Commit a5ddef3

Browse files
committed
Clean up chat service: remove localhost fallbacks, verbose comments, and unnecessary code
- Remove localhost fallbacks from CORS configuration - Remove fallback token from internal routes - Remove verbose comments from handlers, routes, and middleware - Clean up performance-related comments - Remove unnecessary fallback comments
1 parent 40e7464 commit a5ddef3

7 files changed

Lines changed: 12 additions & 40 deletions

File tree

services/chat/src/handlers/agent.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -237,7 +237,6 @@ export async function generateAgentResponse(
237237
} else if (msg.sender_type === 'system') {
238238
role = 'system'
239239
} else {
240-
// Fallback to role if sender_type is not available
241240
role = (msg.role || 'user') as 'user' | 'assistant' | 'system'
242241
}
243242
}

services/chat/src/index.ts

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,10 @@ const httpServer = createServer(app)
2828
const io = new Server(httpServer, {
2929
cors: {
3030
origin: (origin, callback) => {
31-
// Allow requests with no origin (like mobile apps, Postman, or file:// protocol)
3231
if (!origin) {
3332
return callback(null, true)
3433
}
35-
const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(',') || [
36-
'http://localhost:3000',
37-
'http://localhost:8000',
38-
'http://localhost:8080',
39-
'null', // For file:// protocol
40-
]
34+
const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(',') || []
4135
if (allowedOrigins.includes(origin) || allowedOrigins.includes('*')) {
4236
callback(null, true)
4337
} else {
@@ -53,11 +47,7 @@ const PORT = process.env.PORT || 4004
5347
app.use(helmet())
5448
app.use(compression())
5549
app.use(cors({
56-
origin: process.env.ALLOWED_ORIGINS?.split(',') || [
57-
'http://localhost:3000',
58-
'http://localhost:8080',
59-
'http://localhost:8000',
60-
],
50+
origin: process.env.ALLOWED_ORIGINS?.split(',') || [],
6151
credentials: true,
6252
}))
6353
app.use(express.json({ limit: '10mb' }))

services/chat/src/middleware/auth.ts

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,10 @@ export async function authenticateSocket(
3434
return next(new Error('Authentication required'))
3535
}
3636

37-
// Check if this is a widget token (base64 encoded JSON with conversationId, agentId, companyId, apiKey)
38-
// Widget tokens start with base64 JSON, Supabase JWT tokens are different format
3937
try {
4038
const decoded = Buffer.from(token, 'base64').toString('utf-8')
4139
const widgetToken = JSON.parse(decoded)
4240

43-
// If it has conversationId, agentId, companyId, it's a widget token
4441
if (widgetToken.conversationId && widgetToken.companyId) {
4542
socket.userId = `widget:${widgetToken.conversationId}`
4643
socket.companyId = widgetToken.companyId
@@ -51,16 +48,13 @@ export async function authenticateSocket(
5148
} catch {
5249
// Not a widget token, continue with Supabase JWT verification
5350
}
54-
55-
// Verify token with Supabase (for authenticated users)
5651
const { data: { user }, error: authError } = await supabase.auth.getUser(token)
5752

5853
if (authError || !user) {
5954
logger.warn('Socket connection rejected: Invalid token', { socketId: socket.id, error: authError?.message })
6055
return next(new Error('Invalid or expired token'))
6156
}
6257

63-
// Get user's company_id from public.users table
6458
const { data: userProfile, error: profileError } = await supabase
6559
.from('users')
6660
.select('company_id')
@@ -69,7 +63,6 @@ export async function authenticateSocket(
6963

7064
if (profileError) {
7165
logger.warn('Failed to fetch user profile', { error: profileError.message })
72-
// Continue anyway - company_id might be null for new users
7366
}
7467

7568
socket.userId = user.id

services/chat/src/routes/conversations.ts

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,10 @@ router.get(
4040
query.contact_id = contact_id
4141
}
4242

43-
// Optimize query with field selection
4443
const conversations = await Conversation.find(query)
4544
.select('_id agent_id company_id contact_id user_id channel status started_at ended_at tags metadata created_at updated_at')
4645
.sort({ started_at: -1 })
47-
.limit(Math.min(Number(limit), 50)) // Cap at 50 for performance
46+
.limit(Math.min(Number(limit), 50))
4847
.skip(Number(offset))
4948
.lean()
5049

@@ -106,7 +105,7 @@ router.get(
106105
try {
107106
const { id } = req.params
108107
const companyId = req.user!.company_id!
109-
const limit = Math.min(Number(req.query.limit) || 50, 100) // Cap at 100 for performance
108+
const limit = Math.min(Number(req.query.limit) || 50, 100)
110109
const offset = Number(req.query.offset) || 0
111110
const threadId = req.query.thread_id as string | undefined
112111

@@ -146,24 +145,18 @@ router.get(
146145
query.thread_id = { $exists: false }
147146
}
148147

149-
// Query messages with field selection for better performance
150-
// For pagination: we want to load from newest to oldest (descending)
151-
// Then reverse to show oldest first in UI
152-
// offset=0 gets newest messages, offset=20 gets next 20 older messages
153148
const messages = await Message.find(query)
154149
.select('_id conversation_id thread_id sender_type role content message_type attachments ai_metadata metadata created_at')
155-
.sort({ created_at: -1 }) // Newest first
150+
.sort({ created_at: -1 })
156151
.limit(limit)
157152
.skip(offset)
158153
.lean()
159154

160-
// Reverse to show chronological order (oldest first) in UI
161155
messages.reverse()
162156

163157
const total = await Message.countDocuments(query)
164158

165-
// Cache result with longer TTL for better performance
166-
await setCache(cacheKey, { messages, total }, 120) // 2 minute cache
159+
await setCache(cacheKey, { messages, total }, 120)
167160

168161
res.json({
169162
messages,

services/chat/src/routes/internal.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,14 @@ import { Message } from '@syntera/shared/models'
1212
const logger = createLogger('chat-service:internal')
1313
const router = express.Router()
1414

15-
// Simple token validation for internal service calls
1615
function validateInternalToken(req: express.Request, res: express.Response, next: express.NextFunction) {
1716
const token = req.headers.authorization?.replace('Bearer ', '')
18-
const expectedToken = process.env.INTERNAL_SERVICE_TOKEN || 'internal-token'
17+
const expectedToken = process.env.INTERNAL_SERVICE_TOKEN
18+
19+
if (!expectedToken) {
20+
logger.error('INTERNAL_SERVICE_TOKEN not configured')
21+
return res.status(500).json({ error: 'Service configuration error' })
22+
}
1923

2024
if (token !== expectedToken) {
2125
logger.warn('Invalid internal service token', { provided: token?.substring(0, 10) + '...' })

services/chat/src/routes/middleware/auth.ts

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,6 @@ export async function authenticate(
4444
return res.status(401).json({ error: 'Invalid or expired token' })
4545
}
4646

47-
// Get user's company_id from public.users table
4847
const { data: userProfile, error: profileError } = await supabase
4948
.from('users')
5049
.select('company_id')
@@ -53,10 +52,7 @@ export async function authenticate(
5352

5453
if (profileError) {
5554
logger.warn('Failed to fetch user profile', { error: profileError.message })
56-
// Continue anyway - company_id might be null for new users
5755
}
58-
59-
// Attach user info to request
6056
req.user = {
6157
id: user.id,
6258
email: user.email || '',

services/chat/src/utils/cache.ts

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,6 @@ export function getMessagesCacheKey(
8989

9090
/**
9191
* Invalidate all message caches for a conversation
92-
* Used when messages are created/updated
93-
* Note: Uses SCAN instead of KEYS for better performance
9492
*/
9593
export async function invalidateConversationCache(conversationId: string): Promise<void> {
9694
if (!redis || redis.status !== 'ready') {
@@ -118,7 +116,6 @@ export async function invalidateConversationCache(conversationId: string): Promi
118116

119117
/**
120118
* Invalidate cache for specific thread
121-
* Note: Uses SCAN instead of KEYS for better performance
122119
*/
123120
export async function invalidateMessagesCache(
124121
conversationId: string,

0 commit comments

Comments
 (0)