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
182 lines
6.1 KiB
TypeScript
182 lines
6.1 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server"
|
|
import { getSessionUser } from "@/lib/auth"
|
|
import { query } from "@/lib/db"
|
|
import { avatarSvgUrl } from "@/lib/avatar"
|
|
|
|
function stageToStatus(name: string): string {
|
|
switch (name) {
|
|
case "New": return "open"
|
|
case "Contacted": return "contacted"
|
|
case "Qualified":
|
|
case "Interested":
|
|
case "Demo Scheduled":
|
|
case "Negotiation": return "pending"
|
|
case "Closed Won": return "closed"
|
|
case "Closed Lost": return "ignored"
|
|
default: return "open"
|
|
}
|
|
}
|
|
|
|
function getPeriodDateRange(period: string): { start: Date; end: Date } | null {
|
|
if (period === "all") return null
|
|
const end = new Date()
|
|
let start: Date
|
|
switch (period) {
|
|
case "7days": start = new Date(end); start.setDate(start.getDate() - 7); break
|
|
case "30days": start = new Date(end); start.setDate(start.getDate() - 30); break
|
|
case "12months": start = new Date(end); start.setFullYear(start.getFullYear() - 12); break
|
|
case "6months": default: start = new Date(end); start.setMonth(start.getMonth() - 6); break
|
|
}
|
|
return { start, end }
|
|
}
|
|
|
|
export async function GET(request: NextRequest) {
|
|
try {
|
|
const user = await getSessionUser()
|
|
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
|
|
|
const { searchParams } = new URL(request.url)
|
|
const search = searchParams.get("search") || ""
|
|
const status = searchParams.get("status") || "all"
|
|
const period = searchParams.get("period") || "all"
|
|
const limit = parseInt(searchParams.get("limit") || "50", 10)
|
|
const offset = parseInt(searchParams.get("offset") || "0", 10)
|
|
const isAdmin = user.role === "admin" || user.role === "super_admin"
|
|
|
|
let sql = `SELECT l.id, l.company_name, l.contact_name, l.email, l.phone, l.score,
|
|
l.assigned_to, l.created_at, l.updated_at, l.notes, l.source_id,
|
|
ls.name AS stage_name,
|
|
u.id AS user_id, u.first_name, u.last_name, u.email AS user_email, u.avatar_url
|
|
FROM leads l
|
|
JOIN lead_stages ls ON ls.id = l.stage_id
|
|
LEFT JOIN users u ON u.id = l.assigned_to
|
|
WHERE l.deleted_at IS NULL`
|
|
|
|
const params: any[] = []
|
|
let paramIdx = 1
|
|
|
|
if (period !== "all") {
|
|
const range = getPeriodDateRange(period)
|
|
if (range) {
|
|
sql += ` AND l.created_at >= $${paramIdx} AND l.created_at <= $${paramIdx + 1}`
|
|
params.push(range.start.toISOString(), range.end.toISOString())
|
|
paramIdx += 2
|
|
}
|
|
}
|
|
|
|
if (search) {
|
|
sql += ` AND (l.contact_name ILIKE $${paramIdx} OR l.company_name ILIKE $${paramIdx} OR l.email ILIKE $${paramIdx} OR l.phone ILIKE $${paramIdx})`
|
|
params.push(`%${search}%`)
|
|
paramIdx++
|
|
}
|
|
|
|
if (!isAdmin) {
|
|
sql += ` AND l.assigned_to = $${paramIdx}`
|
|
params.push(user.id)
|
|
paramIdx++
|
|
}
|
|
|
|
sql += ` ORDER BY l.created_at DESC`
|
|
sql += ` LIMIT $${paramIdx} OFFSET $${paramIdx + 1}`
|
|
params.push(limit, offset)
|
|
paramIdx += 2
|
|
|
|
const result = await query(sql, params)
|
|
|
|
let leads = result.rows.map((r: any) => {
|
|
const s = stageToStatus(r.stage_name)
|
|
return {
|
|
id: r.id,
|
|
companyName: r.company_name || "",
|
|
contactName: r.contact_name,
|
|
email: r.email || "",
|
|
phone: r.phone || "",
|
|
source: "",
|
|
description: r.notes || "",
|
|
status: s,
|
|
assignedUserId: r.assigned_to,
|
|
assignedUser: r.assigned_to ? {
|
|
id: r.user_id,
|
|
name: `${r.first_name} ${r.last_name}`,
|
|
email: r.user_email,
|
|
avatar: avatarSvgUrl(`${r.first_name} ${r.last_name}`),
|
|
} : null,
|
|
createdAt: r.created_at,
|
|
updatedAt: r.updated_at,
|
|
}
|
|
})
|
|
|
|
if (status !== "all") {
|
|
leads = leads.filter((l: any) => l.status === status)
|
|
}
|
|
|
|
return NextResponse.json(leads)
|
|
} catch (error) {
|
|
console.error("Leads API error:", error)
|
|
return NextResponse.json({ error: "Failed to load leads" }, { status: 500 })
|
|
}
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const user = await getSessionUser()
|
|
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
|
|
|
const body = await request.json()
|
|
|
|
const stageResult = await query(
|
|
"SELECT id FROM lead_stages WHERE name = $1",
|
|
[body.status === "open" ? "New" : "Contacted"]
|
|
)
|
|
const stageId = stageResult.rows[0]?.id || 1
|
|
|
|
const result = await query(
|
|
`INSERT INTO leads (company_name, contact_name, email, phone, notes, source_id, stage_id, assigned_to, created_at, updated_at)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NOW(), NOW())
|
|
RETURNING id`,
|
|
[
|
|
body.companyName,
|
|
body.contactName,
|
|
body.email,
|
|
body.phone || null,
|
|
body.description || null,
|
|
body.source || null,
|
|
stageId,
|
|
body.assignedUserId === "none" ? null : body.assignedUserId,
|
|
]
|
|
)
|
|
|
|
return NextResponse.json({ success: true, id: result.rows[0].id }, { status: 201 })
|
|
} catch (error) {
|
|
console.error("Leads POST error:", error)
|
|
return NextResponse.json({ error: "Failed to create lead" }, { status: 500 })
|
|
}
|
|
}
|
|
|
|
export async function DELETE(request: NextRequest) {
|
|
try {
|
|
const user = await getSessionUser()
|
|
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
|
|
|
|
const isAdmin = user.role === "admin" || user.role === "super_admin"
|
|
|
|
const { searchParams } = new URL(request.url)
|
|
const id = searchParams.get("id")
|
|
if (!id) return NextResponse.json({ error: "id is required" }, { status: 400 })
|
|
|
|
const result = await query(
|
|
"UPDATE leads SET deleted_at = NOW() WHERE id = $1 AND deleted_at IS NULL AND ($2 = true OR assigned_to = $3) RETURNING id",
|
|
[id, isAdmin, user.id]
|
|
)
|
|
|
|
if (result.rows.length === 0) {
|
|
return NextResponse.json({ error: "Lead not found" }, { status: 404 })
|
|
}
|
|
|
|
return NextResponse.json({ success: true })
|
|
} catch (error) {
|
|
console.error("Leads DELETE error:", error)
|
|
return NextResponse.json({ error: "Failed to delete lead" }, { status: 500 })
|
|
}
|
|
}
|