fix: comprehensive security, consistency, and dead code cleanup

Security:
- Add auth + file type/size validation to upload API
- Add admin auth to /api/admin/ endpoints
- Add SSRF protection to scrape action
- Whitelist fields in PUT /api/notes/[id] to prevent mass assignment
- Protect /lab, /agents, /chat, /canvas, /notebooks routes in middleware

AI provider fixes:
- Add deepseek/openrouter to factory ProviderType (was silently falling back to ollama)
- Fix title-suggestion.service.ts to use factory instead of hardcoded OpenAI
- Fix getAIProvider→getChatProvider in memory-echo, notebook-summary, agent-executor
- Fix getAIProvider→getTagsProvider in notebook-suggestion, title-suggestions, transform-markdown

Functional bugs:
- Fix ALLOW_REGISTRATION AND→OR logic
- Fix note-editor.tsx passing stale props to useAutoTagging instead of local state
- Fix stale Note.embedding type (migrated to NoteEmbedding table)
- Remove hardcoded SQLite path from prisma.ts

Frontend:
- Add AbortController to useAutoTagging and useTitleSuggestions hooks
- Add error rollback to optimistic UI in note-inline-editor
- Remove stale closure over notebookId/language in useAutoTagging

Cleanup:
- Rename docker-compose from keepnotes→memento
- Remove unused unstable_cache import from config.ts
- Remove dead useUndoRedo hook
- Fix TagSuggestion type (add isNewLabel, reasoning)
- Remove dead AIConfig/AIProviderType types
- Fix ghost-tags unused isEmpty var and as any cast
- Fix note-editor titleSuggestions typed as any[]

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Sepehr Ramezani
2026-04-21 21:39:10 +02:00
parent 3c8e347576
commit 1c659ce42f
27 changed files with 194 additions and 230 deletions

View File

@@ -5,7 +5,7 @@ import prisma from '@/lib/prisma'
import { Note, CheckItem } from '@/lib/types'
import { auth } from '@/auth'
import { getAIProvider } from '@/lib/ai/factory'
import { parseNote as parseNoteUtil, cosineSimilarity, validateEmbedding, calculateRRFK, detectQueryType, getSearchWeights } from '@/lib/utils'
import { parseNote as parseNoteUtil, cosineSimilarity, calculateRRFK, detectQueryType, getSearchWeights } from '@/lib/utils'
import { getSystemConfig, getConfigNumber, getConfigBoolean, SEARCH_DEFAULTS } from '@/lib/config'
import { contextualAutoTagService } from '@/lib/ai/services/contextual-auto-tag.service'
import { cleanupNoteImages, parseImageUrls, deleteImageFileSafely } from '@/lib/image-cleanup'
@@ -50,22 +50,9 @@ const NOTE_LIST_SELECT = {
// embedding: false — volontairement omis (économise ~6KB JSON/note)
} as const
// Wrapper for parseNote that validates embeddings
// Wrapper for parseNote (embedding validation removed - embeddings are now in NoteEmbedding table)
function parseNote(dbNote: any): Note {
const note = parseNoteUtil(dbNote)
// Validate embedding if present
if (note.embedding && Array.isArray(note.embedding)) {
const validation = validateEmbedding(note.embedding)
if (!validation.valid) {
return {
...note,
embedding: null
}
}
}
return note
return parseNoteUtil(dbNote)
}
// Helper to get hash color for labels (copied from utils)

View File

@@ -15,7 +15,7 @@ const RegisterSchema = z.object({
export async function register(prevState: string | undefined, formData: FormData) {
// Check if registration is allowed
const config = await getSystemConfig();
const allowRegister = config.ALLOW_REGISTRATION !== 'false' && process.env.ALLOW_REGISTRATION !== 'false';
const allowRegister = config.ALLOW_REGISTRATION !== 'false' || process.env.ALLOW_REGISTRATION !== 'false';
if (!allowRegister) {
return 'Registration is currently disabled by the administrator.';

View File

@@ -18,6 +18,14 @@ export async function fetchLinkMetadata(url: string): Promise<LinkMetadata | nul
targetUrl = 'https://' + url;
}
// SSRF protection: block internal/private IPs
const parsed = new URL(targetUrl)
const hostname = parsed.hostname.toLowerCase()
const blockedHosts = ['localhost', '127.0.0.1', '0.0.0.0', '::1', '169.254.169.254']
if (blockedHosts.includes(hostname)) return null
if (hostname.startsWith('10.') || hostname.startsWith('172.') || hostname.startsWith('192.168.') || hostname.startsWith('fc') || hostname.startsWith('fd')) return null
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null
const response = await fetch(targetUrl, {
headers: {
// Use a real browser User-Agent to avoid 403 Forbidden from strict sites

View File

@@ -1,11 +1,16 @@
import { NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import { LABEL_COLORS } from '@/lib/types';
import { auth } from '@/auth';
export const dynamic = 'force-dynamic';
export async function GET() {
try {
const session = await auth()
if (!session?.user?.id || (session.user as any).role !== 'ADMIN') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const labels = await prisma.label.findMany();
const colors = Object.keys(LABEL_COLORS).filter(c => c !== 'gray'); // Exclude gray to force colors

View File

@@ -1,10 +1,15 @@
import { NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import { auth } from '@/auth';
export const dynamic = 'force-dynamic';
export async function GET() {
try {
const session = await auth()
if (!session?.user?.id || (session.user as any).role !== 'ADMIN') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
// 1. Get all notes
const notes = await prisma.note.findMany({
select: { labels: true }

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from 'next/server'
import { getAIProvider } from '@/lib/ai/factory'
import { getTagsProvider } from '@/lib/ai/factory'
import { getSystemConfig } from '@/lib/config'
import { z } from 'zod'
@@ -23,7 +23,7 @@ export async function POST(req: NextRequest) {
}
const config = await getSystemConfig()
const provider = getAIProvider(config)
const provider = getTagsProvider(config)
// Détecter la langue du contenu (simple détection basée sur les caractères et mots)
const hasNonLatinChars = /[\u0400-\u04FF\u0600-\u06FF\u4E00-\u9FFF\u0E00-\u0E7F]/.test(content)

View File

@@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/auth'
import { getAIProvider } from '@/lib/ai/factory'
import { getChatProvider } from '@/lib/ai/factory'
import { getSystemConfig } from '@/lib/config'
export async function POST(request: NextRequest) {
@@ -35,7 +35,7 @@ export async function POST(request: NextRequest) {
}
const config = await getSystemConfig()
const provider = getAIProvider(config)
const provider = getChatProvider(config)
// Detect language from text
const hasFrench = /[àâäéèêëïîôùûüÿç]/i.test(text)

View File

@@ -94,7 +94,14 @@ export async function PUT(
}
const body = await request.json()
const updateData: any = { ...body }
// Whitelist allowed fields to prevent mass assignment
const allowedFields = ['title', 'content', 'color', 'isPinned', 'isArchived', 'type', 'isMarkdown', 'size', 'notebookId']
const updateData: Record<string, any> = {}
for (const key of allowedFields) {
if (key in body) {
updateData[key] = body[key]
}
}
if ('checkItems' in body) {
updateData.checkItems = body.checkItems ?? null

View File

@@ -2,9 +2,18 @@ import { NextRequest, NextResponse } from 'next/server'
import { writeFile, mkdir } from 'fs/promises'
import path from 'path'
import { randomUUID } from 'crypto'
import { auth } from '@/auth'
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
const MAX_SIZE = 5 * 1024 * 1024 // 5MB
export async function POST(request: NextRequest) {
try {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const formData = await request.formData()
const file = formData.get('file') as File
@@ -15,8 +24,20 @@ export async function POST(request: NextRequest) {
)
}
if (!ALLOWED_TYPES.includes(file.type)) {
return NextResponse.json({ error: 'Invalid file type' }, { status: 400 })
}
if (file.size > MAX_SIZE) {
return NextResponse.json({ error: 'File too large (max 5MB)' }, { status: 400 })
}
const buffer = Buffer.from(await file.arrayBuffer())
const filename = `${randomUUID()}${path.extname(file.name)}`
const ext = path.extname(file.name).toLowerCase()
if (!['.jpg', '.jpeg', '.png', '.gif', '.webp'].includes(ext)) {
return NextResponse.json({ error: 'Invalid file extension' }, { status: 400 })
}
const filename = `${randomUUID()}${ext}`
// Ensure directory exists
const uploadDir = path.join(process.cwd(), 'public/uploads/notes')