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:
@@ -27,6 +27,16 @@ export class OllamaProvider implements AIProvider {
|
||||
this.model = ollamaClient.chat(modelName);
|
||||
}
|
||||
|
||||
private async fetchWithTimeout(url: string, options: RequestInit, timeoutMs: number = 30_000): Promise<Response> {
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
||||
try {
|
||||
return await fetch(url, { ...options, signal: controller.signal })
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
async generateTags(content: string, language: string = "en"): Promise<TagSuggestion[]> {
|
||||
try {
|
||||
const promptText = language === 'fa'
|
||||
@@ -55,7 +65,7 @@ Rules:
|
||||
Respond ONLY as a JSON list of objects: [{"tag": "string", "confidence": number}].
|
||||
Note content: "${content}"`;
|
||||
|
||||
const response = await fetch(`${this.baseUrl}/generate`, {
|
||||
const response = await this.fetchWithTimeout(`${this.baseUrl}/generate`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
@@ -75,7 +85,6 @@ Note content: "${content}"`;
|
||||
return JSON.parse(jsonMatch[0]);
|
||||
}
|
||||
|
||||
// Support for { "tags": [...] } format
|
||||
const objectMatch = text.match(/\{\s*"tags"\s*:\s*(\[[\s\S]*\])\s*\}/);
|
||||
if (objectMatch && objectMatch[1]) {
|
||||
return JSON.parse(objectMatch[1]);
|
||||
@@ -90,14 +99,14 @@ Note content: "${content}"`;
|
||||
|
||||
async getEmbeddings(text: string): Promise<number[]> {
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}/embeddings`, {
|
||||
const response = await this.fetchWithTimeout(`${this.baseUrl}/embeddings`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
model: this.embeddingModelName,
|
||||
prompt: text,
|
||||
}),
|
||||
});
|
||||
}, 60_000);
|
||||
|
||||
if (!response.ok) throw new Error(`Ollama error: ${response.statusText}`);
|
||||
|
||||
@@ -111,7 +120,7 @@ Note content: "${content}"`;
|
||||
|
||||
async generateTitles(prompt: string): Promise<TitleSuggestion[]> {
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}/generate`, {
|
||||
const response = await this.fetchWithTimeout(`${this.baseUrl}/generate`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
@@ -126,7 +135,6 @@ Note content: "${content}"`;
|
||||
const data = await response.json();
|
||||
const text = data.response;
|
||||
|
||||
// Extract JSON from response
|
||||
const jsonMatch = text.match(/\[\s*\{[\s\S]*\}\s*\]/);
|
||||
if (jsonMatch) {
|
||||
return JSON.parse(jsonMatch[0]);
|
||||
@@ -141,7 +149,7 @@ Note content: "${content}"`;
|
||||
|
||||
async generateText(prompt: string): Promise<string> {
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}/generate`, {
|
||||
const response = await this.fetchWithTimeout(`${this.baseUrl}/generate`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
@@ -172,7 +180,7 @@ Note content: "${content}"`;
|
||||
ollamaMessages.unshift({ role: 'system', content: systemPrompt });
|
||||
}
|
||||
|
||||
const response = await fetch(`${this.baseUrl}/chat`, {
|
||||
const response = await this.fetchWithTimeout(`${this.baseUrl}/chat`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
|
||||
19
memento-note/lib/api-auth.ts
Normal file
19
memento-note/lib/api-auth.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { auth } from '@/auth'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
export async function requireAuth() {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return { session: null, error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) }
|
||||
}
|
||||
return { session, error: null }
|
||||
}
|
||||
|
||||
export async function requireAdmin() {
|
||||
const result = await requireAuth()
|
||||
if (result.error) return result
|
||||
if ((result.session!.user as any).role !== 'ADMIN') {
|
||||
return { session: null, error: NextResponse.json({ error: 'Forbidden' }, { status: 403 }) }
|
||||
}
|
||||
return result
|
||||
}
|
||||
29
memento-note/lib/rate-limit.ts
Normal file
29
memento-note/lib/rate-limit.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
const attempts = new Map<string, { count: number; resetAt: number }>()
|
||||
|
||||
const WINDOW_MS = 60_000
|
||||
const MAX_ATTEMPTS = 5
|
||||
|
||||
export function rateLimit(key: string): { allowed: boolean; retryAfterMs: number } {
|
||||
const now = Date.now()
|
||||
const entry = attempts.get(key)
|
||||
|
||||
if (!entry || now > entry.resetAt) {
|
||||
attempts.set(key, { count: 1, resetAt: now + WINDOW_MS })
|
||||
return { allowed: true, retryAfterMs: 0 }
|
||||
}
|
||||
|
||||
entry.count++
|
||||
|
||||
if (entry.count > MAX_ATTEMPTS) {
|
||||
return { allowed: false, retryAfterMs: entry.resetAt - now }
|
||||
}
|
||||
|
||||
return { allowed: true, retryAfterMs: 0 }
|
||||
}
|
||||
|
||||
setInterval(() => {
|
||||
const now = Date.now()
|
||||
for (const [k, v] of attempts) {
|
||||
if (now > v.resetAt) attempts.delete(k)
|
||||
}
|
||||
}, 60_000)
|
||||
Reference in New Issue
Block a user