perf: optimize MCP server (O(1) auth, compact JSON, trashedAt fix) + memento-note performance (lazy loading, server-side filtering, XSS fixes, dead code removal, security hardening)
All checks were successful
Deploy to Production / Build and Deploy (push) Successful in 1m35s
All checks were successful
Deploy to Production / Build and Deploy (push) Successful in 1m35s
MCP Server: - Fix validateApiKey: O(1) direct lookup by shortId instead of loading all keys - Add trashedAt:null filter to ALL note queries (trashed notes leaked in results) - Compact JSON output (~40% smaller responses) - Bounded session cache (Map with MAX_SESSIONS=500) to prevent memory leaks - PostgreSQL connection pooling (connection_limit=10) - Rewrite all 22 tool descriptions in clear English - Fix /sse fallback to proper 307 redirect memento-note Performance: - loading=lazy on all note images - Split notebooksRefreshKey from global refreshKey (note CRUD no longer re-fetches notebooks) - Remove searchKey from trash count deps (no re-fetch on every keystroke) - Server-side notebookId filter in getAllNotes() (biggest win) - Skip collaborator fetch for non-shared notes (eliminates N+1 API calls) - next/dynamic for MarkdownContent + 4 modals (code-split remark/rehype/KaTeX) - Memoize DOMPurify sanitize with useMemo Security: - XSS: DOMPurify sanitize in note-card and note-history-modal - Auth anti-enumeration: uniform errors in auth.ts - CRON_SECRET mandatory on cron endpoints - Rate limiting on login (5 attempts/min per email) - Centralized API auth helpers (requireAuth/requireAdmin) - randomize-labels changed GET→POST - Removed debug endpoints (/api/debug/config, /api/debug/test-chat) Cleanup: - Removed dead code: .backup-keep, settings-backup, fix-*.js, debug-theme, fix-labels route - Removed sensitive console.error in auth.ts - Ollama fetchWithTimeout (30s/60s AbortController) - i18n: full Arabic translation, Farsi missing keys - Masonry drag-and-drop fix (localOrderMap, cross-section block) - Sidebar notebook tooltip on truncation
This commit is contained in:
@@ -5,7 +5,7 @@ import { auth } from '@/auth';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function GET() {
|
||||
export async function POST() {
|
||||
try {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id || (session.user as any).role !== 'ADMIN') {
|
||||
|
||||
@@ -14,13 +14,14 @@ export const dynamic = 'force-dynamic'
|
||||
* Authorization: Bearer <CRON_SECRET>
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
// Optional auth
|
||||
const cronSecret = process.env.CRON_SECRET
|
||||
if (cronSecret) {
|
||||
const authHeader = request.headers.get('authorization')
|
||||
if (authHeader !== `Bearer ${cronSecret}`) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
if (!cronSecret) {
|
||||
console.error('[CronAgents] CRON_SECRET env var is required but not set')
|
||||
return NextResponse.json({ error: 'Server misconfiguration' }, { status: 500 })
|
||||
}
|
||||
const authHeader = request.headers.get('authorization')
|
||||
if (authHeader !== `Bearer ${cronSecret}`) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
@@ -4,14 +4,14 @@ import prisma from '@/lib/prisma';
|
||||
export const dynamic = 'force-dynamic'; // No caching
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
// Optional auth: set CRON_SECRET env var, callers must pass
|
||||
// Authorization: Bearer <CRON_SECRET>
|
||||
const cronSecret = process.env.CRON_SECRET
|
||||
if (cronSecret) {
|
||||
const authHeader = request.headers.get('authorization')
|
||||
if (authHeader !== `Bearer ${cronSecret}`) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
if (!cronSecret) {
|
||||
console.error('[CronReminders] CRON_SECRET env var is required but not set')
|
||||
return NextResponse.json({ error: 'Server misconfiguration' }, { status: 500 })
|
||||
}
|
||||
const authHeader = request.headers.get('authorization')
|
||||
if (authHeader !== `Bearer ${cronSecret}`) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json()
|
||||
// Visible directement dans `docker logs memento-web`
|
||||
console.error('[CLIENT-ERROR-REPORT]', JSON.stringify(body, null, 2))
|
||||
} catch {
|
||||
// ignore
|
||||
// ignore malformed payload
|
||||
}
|
||||
return NextResponse.json({ ok: true })
|
||||
}
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { getSystemConfig } from '@/lib/config';
|
||||
import { auth } from '@/auth';
|
||||
|
||||
/**
|
||||
* Debug endpoint to check AI configuration
|
||||
* This helps verify that OpenAI is properly configured
|
||||
*/
|
||||
export async function GET() {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
if ((session.user as any).role !== 'ADMIN') {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
try {
|
||||
const config = await getSystemConfig();
|
||||
|
||||
// Return only AI-related config for debugging
|
||||
const aiConfig = {
|
||||
AI_PROVIDER_TAGS: config.AI_PROVIDER_TAGS || 'not set',
|
||||
AI_PROVIDER_EMBEDDING: config.AI_PROVIDER_EMBEDDING || 'not set',
|
||||
AI_MODEL_TAGS: config.AI_MODEL_TAGS || 'not set',
|
||||
AI_MODEL_EMBEDDING: config.AI_MODEL_EMBEDDING || 'not set',
|
||||
OPENAI_API_KEY: config.OPENAI_API_KEY ? 'set (hidden)' : 'not set',
|
||||
OLLAMA_BASE_URL: config.OLLAMA_BASE_URL || 'not set',
|
||||
OLLAMA_MODEL: config.OLLAMA_MODEL || 'not set',
|
||||
CUSTOM_OPENAI_BASE_URL: config.CUSTOM_OPENAI_BASE_URL || 'not set',
|
||||
CUSTOM_OPENAI_API_KEY: config.CUSTOM_OPENAI_API_KEY ? 'set (hidden)' : 'not set',
|
||||
};
|
||||
|
||||
return NextResponse.json(aiConfig);
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to get config', details: error },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { chatService } from '@/lib/ai/services/chat.service';
|
||||
import { auth } from '@/auth';
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
if ((session.user as any).role !== 'ADMIN') {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await req.json();
|
||||
console.log("TEST ROUTE INCOMING BODY:", body);
|
||||
|
||||
// Simulate what the server action does
|
||||
const result = await chatService.chat(body.message, body.conversationId, body.notebookId);
|
||||
|
||||
return NextResponse.json({ success: true, result });
|
||||
} catch (err: any) {
|
||||
console.error("====== TEST ROUTE CHAT ERROR ======");
|
||||
console.error("NAME:", err.name);
|
||||
console.error("MSG:", err.message);
|
||||
if (err.cause) console.error("CAUSE:", JSON.stringify(err.cause, null, 2));
|
||||
if (err.data) console.error("DATA:", JSON.stringify(err.data, null, 2));
|
||||
if (err.stack) console.error("STACK:", err.stack);
|
||||
console.error("===================================");
|
||||
return NextResponse.json({
|
||||
success: false,
|
||||
error: err.message,
|
||||
name: err.name,
|
||||
cause: err.cause,
|
||||
data: err.data
|
||||
}, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import prisma from '@/lib/prisma'
|
||||
import { revalidatePath } from 'next/cache'
|
||||
import { auth } from '@/auth'
|
||||
|
||||
function getHashColor(name: string): string {
|
||||
const colors = ['red', 'blue', 'green', 'yellow', 'purple', 'pink', 'orange', 'gray']
|
||||
let hash = 0
|
||||
for (let i = 0; i < name.length; i++) {
|
||||
hash = name.charCodeAt(i) + ((hash << 5) - hash)
|
||||
}
|
||||
return colors[Math.abs(hash) % colors.length]
|
||||
}
|
||||
|
||||
export async function POST() {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
if ((session.user as any).role !== 'ADMIN') {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
}
|
||||
|
||||
try {
|
||||
const result = { created: 0, deleted: 0, missing: [] as string[] }
|
||||
|
||||
// Get ALL users
|
||||
const users = await prisma.user.findMany({
|
||||
select: { id: true, email: true }
|
||||
})
|
||||
|
||||
|
||||
for (const user of users) {
|
||||
const userId = user.id
|
||||
|
||||
// 1. Get all labels from notes
|
||||
const allNotes = await prisma.note.findMany({
|
||||
where: { userId },
|
||||
select: { labels: true }
|
||||
})
|
||||
|
||||
const labelsInNotes = new Set<string>()
|
||||
allNotes.forEach(note => {
|
||||
if (note.labels) {
|
||||
try {
|
||||
const parsed: string[] = Array.isArray(note.labels) ? (note.labels as string[]) : []
|
||||
if (Array.isArray(parsed)) {
|
||||
parsed.forEach(l => {
|
||||
if (l && l.trim()) labelsInNotes.add(l.trim())
|
||||
})
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
// 2. Get existing Label records
|
||||
const existingLabels = await prisma.label.findMany({
|
||||
where: { userId },
|
||||
select: { id: true, name: true }
|
||||
})
|
||||
|
||||
|
||||
const existingLabelMap = new Map<string, any>()
|
||||
existingLabels.forEach(label => {
|
||||
existingLabelMap.set(label.name.toLowerCase(), label)
|
||||
})
|
||||
|
||||
// 3. Create missing Label records
|
||||
for (const labelName of labelsInNotes) {
|
||||
if (!existingLabelMap.has(labelName.toLowerCase())) {
|
||||
try {
|
||||
await prisma.label.create({
|
||||
data: {
|
||||
userId,
|
||||
name: labelName,
|
||||
color: getHashColor(labelName)
|
||||
}
|
||||
})
|
||||
result.created++
|
||||
} catch (e: any) {
|
||||
console.error(`[FIX] ✗ Failed to create "${labelName}":`, e.message, e.code)
|
||||
result.missing.push(labelName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Delete orphan Label records
|
||||
const usedLabelsSet = new Set<string>()
|
||||
allNotes.forEach(note => {
|
||||
if (note.labels) {
|
||||
try {
|
||||
const parsed: string[] = Array.isArray(note.labels) ? (note.labels as string[]) : []
|
||||
if (Array.isArray(parsed)) {
|
||||
parsed.forEach(l => usedLabelsSet.add(l.toLowerCase()))
|
||||
}
|
||||
} catch (e) {}
|
||||
}
|
||||
})
|
||||
|
||||
for (const label of existingLabels) {
|
||||
if (!usedLabelsSet.has(label.name.toLowerCase())) {
|
||||
try {
|
||||
await prisma.label.delete({
|
||||
where: { id: label.id }
|
||||
})
|
||||
result.deleted++
|
||||
} catch (e) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
revalidatePath('/')
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
...result,
|
||||
message: `Created ${result.created} labels, deleted ${result.deleted} orphans`
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('[FIX] Error:', error)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: String(error) },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user