mirror of
https://git.coastit.co.za/caitlin/CRM_ENVR.git
synced 2026-07-12 12:07:06 +02:00
1adc4806fa
Security Fixes
File Change
.env.local Placeholder JWT secret (rotate to random value: openssl rand -base64 64)
src/middleware.ts Removed /api/auth/me bypass; API routes return JSON 401 (not 302 redirect)
src/lib/auth.ts sameSite: "lax" → "strict" (create + destroy cookie); SVG name chars are pre-computed (no injection)
src/lib/avatar.ts Added sanitizeName() — strips non-alphanumeric/safe chars, max 50 chars
src/app/api/users/route.ts POST restricted to super_admin; validates role against whitelist ["sales","admin","super_admin","dev"]; validates active defaults to true
src/app/api/users/[id]/route.ts DELETE restricted to super_admin; blocks self-deletion
src/app/api/leads/[id]/route.ts GET: non-admin users filtered by assigned_to; PATCH: ownership check + score validated 0-100 range
src/app/api/leads/route.ts DELETE: ownership + admin check; GET: ownership filter for non-admin users
src/app/api/conversations/[id]/messages/route.ts GET/POST: verify user is a conversation_participant before access
rust-ai/src/main.rs CORS: AllowOrigin::list(["localhost:3006", "127.0.0.1:3006"]) (was Any)
Performance Fixes
File Change
src/app/api/leads/route.ts Added limit (default 50), offset query params; ownership filter in SQL
src/app/api/users/route.ts Added limit (default 50), offset query params
src/app/api/conversations/route.ts Added LIMIT 50
src/app/api/leads/[id]/notes/route.ts Added limit (default 50), offset query params
src/app/api/conversations/[id]/messages/route.ts Added limit (default 100), offset, before query params
src/app/(dashboard)/chats/page.tsx Pruned to 5 cached conversations; useMemo wraps messages/conversation/filteredConversations; otherParticipant moved outside component; added 10MB file size limit; recordingChunksRef cleared on discard
src/app/(dashboard)/leads/[id]/page.tsx Optimistic status update rolls back on fetch failure
database/migrations/003_chat.sql Added composite index idx_messages_conversation_created on (conversation_id, created_at DESC)
Code Quality Fixes
File Change
src/lib/ai.ts Removed dead getInstructions()/updateInstructions() (called nonexistent /ai/instructions)
src/lib/auth.ts bcrypt.hash(password, 12) — kept (acceptable, OWASP-recommended)
src/app/login/page.tsx "Forgot password?" button now shows alert to contact admin (was no-op)
src/components/users/user-form-dialog.tsx Password min 6 → 8 chars
26 silent catch {} blocks across 16 files (see below) Added console.warn("...") context messages
148 lines
4.7 KiB
TypeScript
148 lines
4.7 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server"
|
|
import { getSessionUser } from "@/lib/auth"
|
|
import { query } from "@/lib/db"
|
|
import { avatarSvgUrl } from "@/lib/avatar"
|
|
|
|
export async function GET(
|
|
_request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> },
|
|
) {
|
|
try {
|
|
const user = await getSessionUser()
|
|
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
|
|
|
const { id } = await params
|
|
|
|
const { searchParams } = new URL(_request.url)
|
|
const limit = parseInt(searchParams.get("limit") || "100", 10)
|
|
const offset = parseInt(searchParams.get("offset") || "0", 10)
|
|
const before = searchParams.get("before") || ""
|
|
|
|
// Verify user is a participant
|
|
const partCheck = await query(
|
|
`SELECT 1 FROM conversation_participants WHERE conversation_id = $1 AND user_id = $2`,
|
|
[id, user.id]
|
|
)
|
|
if (partCheck.rows.length === 0) {
|
|
return NextResponse.json({ error: "Not a participant" }, { status: 403 })
|
|
}
|
|
|
|
let msgSql = `SELECT m.id, m.sender_id, m.content, m.created_at, m.updated_at, m.deleted_at,
|
|
u.first_name || ' ' || u.last_name AS sender_name,
|
|
u.email AS sender_email,
|
|
u.avatar_url AS sender_avatar_url
|
|
FROM messages m
|
|
JOIN users u ON u.id = m.sender_id
|
|
WHERE m.conversation_id = $1 AND m.deleted_at IS NULL`
|
|
const msgParams: any[] = [id]
|
|
|
|
if (before) {
|
|
msgSql += ` AND m.created_at < $2`
|
|
msgParams.push(before)
|
|
}
|
|
|
|
msgSql += ` ORDER BY m.created_at ASC`
|
|
msgSql += ` LIMIT $${msgParams.length + 1} OFFSET $${msgParams.length + 2}`
|
|
msgParams.push(limit, offset)
|
|
|
|
const [msgResult, otherReadResult] = await Promise.all([
|
|
query(msgSql, msgParams),
|
|
query(
|
|
`SELECT last_read_at FROM conversation_participants
|
|
WHERE conversation_id = $1 AND user_id != $2`,
|
|
[id, user.id],
|
|
),
|
|
])
|
|
|
|
const otherLastReadAt = otherReadResult.rows[0]?.last_read_at
|
|
? new Date(otherReadResult.rows[0].last_read_at).getTime()
|
|
: 0
|
|
|
|
const messages = msgResult.rows.map((row: any) => ({
|
|
id: row.id,
|
|
conversationId: id,
|
|
senderId: row.sender_id,
|
|
senderName: row.sender_name,
|
|
senderAvatar: avatarSvgUrl(row.sender_name),
|
|
content: row.content,
|
|
timestamp: formatTime(new Date(row.created_at)),
|
|
createdAt: row.created_at,
|
|
read: row.sender_id === user.id
|
|
? new Date(row.created_at).getTime() <= otherLastReadAt
|
|
: true,
|
|
}))
|
|
|
|
return NextResponse.json({ messages })
|
|
} catch (error) {
|
|
console.error("Messages error:", error)
|
|
return NextResponse.json({ error: "Failed to load messages" }, { status: 500 })
|
|
}
|
|
}
|
|
|
|
export async function POST(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> },
|
|
) {
|
|
try {
|
|
const user = await getSessionUser()
|
|
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
|
|
|
const { id } = await params
|
|
|
|
// Verify user is a participant
|
|
const partCheck = await query(
|
|
`SELECT 1 FROM conversation_participants WHERE conversation_id = $1 AND user_id = $2`,
|
|
[id, user.id]
|
|
)
|
|
if (partCheck.rows.length === 0) {
|
|
return NextResponse.json({ error: "Not a participant" }, { status: 403 })
|
|
}
|
|
|
|
const { content } = await request.json()
|
|
if (!content?.trim()) {
|
|
return NextResponse.json({ error: "Message content is required" }, { status: 400 })
|
|
}
|
|
|
|
const result = await query(
|
|
`INSERT INTO messages (conversation_id, sender_id, content)
|
|
VALUES ($1, $2, $3)
|
|
RETURNING id, created_at`,
|
|
[id, user.id, content.trim()],
|
|
)
|
|
|
|
await query(
|
|
`UPDATE conversations SET updated_at = NOW() WHERE id = $1`,
|
|
[id],
|
|
)
|
|
|
|
const msg = result.rows[0]
|
|
|
|
return NextResponse.json({
|
|
message: {
|
|
id: msg.id,
|
|
conversationId: id,
|
|
senderId: user.id,
|
|
senderName: `${user.firstName} ${user.lastName}`,
|
|
senderAvatar: user.avatar,
|
|
content: content.trim(),
|
|
timestamp: formatTime(new Date(msg.created_at)),
|
|
createdAt: msg.created_at,
|
|
read: false,
|
|
},
|
|
})
|
|
} catch (error) {
|
|
console.error("Send message error:", error)
|
|
return NextResponse.json({ error: "Failed to send message" }, { status: 500 })
|
|
}
|
|
}
|
|
|
|
function formatTime(date: Date): string {
|
|
const now = new Date()
|
|
const isToday = date.toDateString() === now.toDateString()
|
|
if (isToday) {
|
|
return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
|
|
}
|
|
return date.toLocaleDateString([], { month: "short", day: "numeric" }) + " " +
|
|
date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
|
|
}
|