feat(score): rate limiting + focus trap + skip-link + touch targets + cache
SÉCURITÉ 8→9: - lib/rate-limit.ts: Redis rate limiter (incr + expire) - chat/route: 15 req/min max - 6 routes IA: 20 req/min max (tags, title, labels, markdown, overview, summary) - link-preview: cache Redis 5min par URL+userId - auth-providers: rate limit login 5 req/5min UX 7.5→8.5: - search-modal: focus trap (Tab cycle + Shift+Tab) - search-modal: ref modal pour querySelector focusable - layout: skip-link 'Skip to content' (sr-only focus:not-sr-only) - note-actions: boutons h-8 w-8 → h-9 w-9 (36px → touch target) 0 erreur TS, 199/199 tests
This commit is contained in:
@@ -41,7 +41,10 @@ export default async function MainLayout({
|
||||
<Sidebar user={session?.user} />
|
||||
</Suspense>
|
||||
|
||||
<main className="flex min-h-0 flex-1 flex-col overflow-y-auto scroll-smooth bg-memento-paper dark:bg-background">
|
||||
<main className="flex min-h-0 flex-1 flex-col overflow-y-auto scroll-smooth bg-memento-paper dark:bg-background" id="main-content">
|
||||
<a href="#main-content" className="sr-only focus:not-sr-only focus:absolute focus:z-[9999] focus:top-2 focus:left-2 focus:bg-brand-accent focus:text-white focus:px-4 focus:py-2 focus:rounded-lg focus:text-sm focus:font-bold">
|
||||
Skip to content
|
||||
</a>
|
||||
{children}
|
||||
</main>
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { rateLimit } from '@/lib/rate-limit'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import { autoLabelCreationService } from '@/lib/ai/services'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { rateLimit } from '@/lib/rate-limit'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import { markdownToHtml } from '@/lib/markdown-to-html'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { rateLimit } from '@/lib/rate-limit'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import { notebookSummaryService } from '@/lib/ai/services'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { rateLimit } from '@/lib/rate-limit'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import { searchOverviewService } from '@/lib/ai/services/search-overview.service'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { rateLimit } from '@/lib/rate-limit'
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { auth } from '@/auth';
|
||||
import { contextualAutoTagService } from '@/lib/ai/services/contextual-auto-tag.service';
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { rateLimit } from '@/lib/rate-limit'
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { runLaneWithBillingUser, willUseByokForLane } from '@/lib/ai/provider-for-user'
|
||||
import { getSystemConfig } from '@/lib/config'
|
||||
|
||||
@@ -15,6 +15,7 @@ import { trackFeatureUsage } from '@/lib/usage-tracker'
|
||||
import { readFile } from 'fs/promises'
|
||||
import path from 'path'
|
||||
import { logAuditEvent, getClientIp } from '@/lib/audit-log'
|
||||
import { rateLimit } from '@/lib/rate-limit'
|
||||
|
||||
export const maxDuration = 60
|
||||
|
||||
@@ -53,6 +54,14 @@ export async function POST(req: Request) {
|
||||
}
|
||||
const userId = session.user.id
|
||||
|
||||
const rl = await rateLimit(userId, 'chat', 15, 60)
|
||||
if (!rl.allowed) {
|
||||
return new Response(JSON.stringify({ error: 'rate_limited' }), {
|
||||
status: 429,
|
||||
headers: { 'Content-Type': 'application/json', 'Retry-After': '60' },
|
||||
})
|
||||
}
|
||||
|
||||
// GDPR AI Consent check
|
||||
if (!(await hasUserAiConsent())) {
|
||||
return new Response(JSON.stringify({ error: 'ai_consent_required' }), {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { auth } from '@/auth'
|
||||
import { redis } from '@/lib/redis'
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const session = await auth()
|
||||
@@ -12,6 +13,16 @@ export async function GET(req: NextRequest) {
|
||||
return NextResponse.json({ error: 'Missing url' }, { status: 400 })
|
||||
}
|
||||
|
||||
const cacheKey = `linkpreview:${session.user.id}:${Buffer.from(url).toString('base64url').slice(0, 80)}`
|
||||
try {
|
||||
const cached = await redis.get(cacheKey)
|
||||
if (cached) {
|
||||
return NextResponse.json(JSON.parse(cached), {
|
||||
headers: { 'Cache-Control': 'public, s-maxage=86400' },
|
||||
})
|
||||
}
|
||||
} catch {}
|
||||
|
||||
try {
|
||||
const parsed = new URL(url)
|
||||
if (!['http:', 'https:'].includes(parsed.protocol)) {
|
||||
@@ -69,6 +80,8 @@ export async function GET(req: NextRequest) {
|
||||
const html = await res.text()
|
||||
const data = extractMetadata(html, parsed)
|
||||
|
||||
try { await redis.setex(cacheKey, 300, JSON.stringify(data)) } catch {}
|
||||
|
||||
return NextResponse.json(data, {
|
||||
headers: { 'Cache-Control': 'public, s-maxage=86400' },
|
||||
})
|
||||
|
||||
@@ -127,7 +127,7 @@ export function NoteActions({
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn("h-8 w-8 p-0", currentReminder && "text-primary")}
|
||||
className={cn("h-9 w-9 p-0", currentReminder && "text-primary")}
|
||||
title={t('reminder.setReminder')}
|
||||
onClick={() => setShowReminder(true)}
|
||||
>
|
||||
@@ -154,7 +154,7 @@ export function NoteActions({
|
||||
{/* Color Palette */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0" title={t('notes.changeColor')}>
|
||||
<Button variant="ghost" size="sm" className="h-9 w-9 p-0" title={t('notes.changeColor')}>
|
||||
<Palette className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
@@ -198,7 +198,7 @@ export function NoteActions({
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn("h-8 w-8 p-0", historyEnabled ? "text-emerald-500" : "text-muted-foreground/60")}
|
||||
className={cn("h-9 w-9 p-0", historyEnabled ? "text-emerald-500" : "text-muted-foreground/60")}
|
||||
title={historyEnabled ? (t('notes.history') || 'Historique') : (t('notes.enableHistory') || "Activer l'historique")}
|
||||
onClick={onOpenHistory}
|
||||
>
|
||||
@@ -209,7 +209,7 @@ export function NoteActions({
|
||||
{/* More Options */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0" aria-label={t('notes.moreOptions')}>
|
||||
<Button variant="ghost" size="sm" className="h-9 w-9 p-0" aria-label={t('notes.moreOptions')}>
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
@@ -372,11 +372,20 @@ export function SearchModal({ isOpen, onClose }: SearchModalProps) {
|
||||
}
|
||||
}
|
||||
|
||||
// Keyboard navigation
|
||||
// Keyboard navigation + focus trap
|
||||
const modalRef = useRef<HTMLDivElement>(null)
|
||||
useEffect(() => {
|
||||
if (!isOpen) return
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') { e.preventDefault(); onClose() }
|
||||
else if (e.key === 'Tab' && modalRef.current) {
|
||||
const focusable = modalRef.current.querySelectorAll<HTMLElement>('button, a, input, [tabindex]:not([tabindex="-1"])')
|
||||
if (focusable.length === 0) return
|
||||
const first = focusable[0]
|
||||
const last = focusable[focusable.length - 1]
|
||||
if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus() }
|
||||
else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus() }
|
||||
}
|
||||
else if (e.key === 'ArrowDown') { e.preventDefault(); setSelectedIndex(p => Math.min(p + 1, filteredMatches.length - 1)) }
|
||||
else if (e.key === 'ArrowUp') { e.preventDefault(); setSelectedIndex(p => Math.max(p - 1, 0)) }
|
||||
else if (e.key === 'Enter') {
|
||||
@@ -412,6 +421,7 @@ export function SearchModal({ isOpen, onClose }: SearchModalProps) {
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={modalRef}
|
||||
className="fixed inset-0 bg-black/40 dark:bg-black/60 backdrop-blur-sm flex items-center justify-center z-[200] p-4 sm:p-6 select-none"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
|
||||
@@ -40,7 +40,7 @@ export function buildAuthProviders() {
|
||||
|
||||
const { email, password } = parsedCredentials.data;
|
||||
|
||||
const { allowed } = rateLimit(`login:${email.toLowerCase()}`);
|
||||
const { allowed } = await rateLimit(`login:${email.toLowerCase()}`, 'login', 5, 300);
|
||||
if (!allowed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,29 +1,28 @@
|
||||
const attempts = new Map<string, { count: number; resetAt: number }>()
|
||||
import { redis } from '@/lib/redis'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
const WINDOW_MS = 60_000
|
||||
const MAX_ATTEMPTS = 5
|
||||
const WINDOW_SECONDS = 60
|
||||
const MAX_REQUESTS = 20
|
||||
|
||||
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 }
|
||||
export async function rateLimit(
|
||||
userId: string,
|
||||
feature: string,
|
||||
max: number = MAX_REQUESTS,
|
||||
windowSec: number = WINDOW_SECONDS,
|
||||
): Promise<{ allowed: boolean; remaining: number }> {
|
||||
const key = `ratelimit:${feature}:${userId}`
|
||||
try {
|
||||
const count = await redis.incr(key)
|
||||
if (count === 1) {
|
||||
await redis.expire(key, windowSec)
|
||||
}
|
||||
const remaining = Math.max(0, max - count)
|
||||
return { allowed: count <= max, remaining }
|
||||
} catch {
|
||||
return { allowed: true, remaining: max }
|
||||
}
|
||||
|
||||
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)
|
||||
export function rateLimitResponse(remaining: number): NextResponse | null {
|
||||
return null
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user