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} />
|
<Sidebar user={session?.user} />
|
||||||
</Suspense>
|
</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}
|
{children}
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { rateLimit } from '@/lib/rate-limit'
|
||||||
import { NextRequest, NextResponse } from 'next/server'
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
import { auth } from '@/auth'
|
import { auth } from '@/auth'
|
||||||
import { autoLabelCreationService } from '@/lib/ai/services'
|
import { autoLabelCreationService } from '@/lib/ai/services'
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { rateLimit } from '@/lib/rate-limit'
|
||||||
import { NextRequest, NextResponse } from 'next/server'
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
import { auth } from '@/auth'
|
import { auth } from '@/auth'
|
||||||
import { markdownToHtml } from '@/lib/markdown-to-html'
|
import { markdownToHtml } from '@/lib/markdown-to-html'
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { rateLimit } from '@/lib/rate-limit'
|
||||||
import { NextRequest, NextResponse } from 'next/server'
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
import { auth } from '@/auth'
|
import { auth } from '@/auth'
|
||||||
import { notebookSummaryService } from '@/lib/ai/services'
|
import { notebookSummaryService } from '@/lib/ai/services'
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { rateLimit } from '@/lib/rate-limit'
|
||||||
import { NextRequest, NextResponse } from 'next/server'
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
import { auth } from '@/auth'
|
import { auth } from '@/auth'
|
||||||
import { searchOverviewService } from '@/lib/ai/services/search-overview.service'
|
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 { NextRequest, NextResponse } from 'next/server';
|
||||||
import { auth } from '@/auth';
|
import { auth } from '@/auth';
|
||||||
import { contextualAutoTagService } from '@/lib/ai/services/contextual-auto-tag.service';
|
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 { NextRequest, NextResponse } from 'next/server'
|
||||||
import { runLaneWithBillingUser, willUseByokForLane } from '@/lib/ai/provider-for-user'
|
import { runLaneWithBillingUser, willUseByokForLane } from '@/lib/ai/provider-for-user'
|
||||||
import { getSystemConfig } from '@/lib/config'
|
import { getSystemConfig } from '@/lib/config'
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import { trackFeatureUsage } from '@/lib/usage-tracker'
|
|||||||
import { readFile } from 'fs/promises'
|
import { readFile } from 'fs/promises'
|
||||||
import path from 'path'
|
import path from 'path'
|
||||||
import { logAuditEvent, getClientIp } from '@/lib/audit-log'
|
import { logAuditEvent, getClientIp } from '@/lib/audit-log'
|
||||||
|
import { rateLimit } from '@/lib/rate-limit'
|
||||||
|
|
||||||
export const maxDuration = 60
|
export const maxDuration = 60
|
||||||
|
|
||||||
@@ -53,6 +54,14 @@ export async function POST(req: Request) {
|
|||||||
}
|
}
|
||||||
const userId = session.user.id
|
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
|
// GDPR AI Consent check
|
||||||
if (!(await hasUserAiConsent())) {
|
if (!(await hasUserAiConsent())) {
|
||||||
return new Response(JSON.stringify({ error: 'ai_consent_required' }), {
|
return new Response(JSON.stringify({ error: 'ai_consent_required' }), {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { NextRequest, NextResponse } from 'next/server'
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
import { auth } from '@/auth'
|
import { auth } from '@/auth'
|
||||||
|
import { redis } from '@/lib/redis'
|
||||||
|
|
||||||
export async function GET(req: NextRequest) {
|
export async function GET(req: NextRequest) {
|
||||||
const session = await auth()
|
const session = await auth()
|
||||||
@@ -12,6 +13,16 @@ export async function GET(req: NextRequest) {
|
|||||||
return NextResponse.json({ error: 'Missing url' }, { status: 400 })
|
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 {
|
try {
|
||||||
const parsed = new URL(url)
|
const parsed = new URL(url)
|
||||||
if (!['http:', 'https:'].includes(parsed.protocol)) {
|
if (!['http:', 'https:'].includes(parsed.protocol)) {
|
||||||
@@ -69,6 +80,8 @@ export async function GET(req: NextRequest) {
|
|||||||
const html = await res.text()
|
const html = await res.text()
|
||||||
const data = extractMetadata(html, parsed)
|
const data = extractMetadata(html, parsed)
|
||||||
|
|
||||||
|
try { await redis.setex(cacheKey, 300, JSON.stringify(data)) } catch {}
|
||||||
|
|
||||||
return NextResponse.json(data, {
|
return NextResponse.json(data, {
|
||||||
headers: { 'Cache-Control': 'public, s-maxage=86400' },
|
headers: { 'Cache-Control': 'public, s-maxage=86400' },
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -127,7 +127,7 @@ export function NoteActions({
|
|||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="sm"
|
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')}
|
title={t('reminder.setReminder')}
|
||||||
onClick={() => setShowReminder(true)}
|
onClick={() => setShowReminder(true)}
|
||||||
>
|
>
|
||||||
@@ -154,7 +154,7 @@ export function NoteActions({
|
|||||||
{/* Color Palette */}
|
{/* Color Palette */}
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<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" />
|
<Palette className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
@@ -198,7 +198,7 @@ export function NoteActions({
|
|||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="sm"
|
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")}
|
title={historyEnabled ? (t('notes.history') || 'Historique') : (t('notes.enableHistory') || "Activer l'historique")}
|
||||||
onClick={onOpenHistory}
|
onClick={onOpenHistory}
|
||||||
>
|
>
|
||||||
@@ -209,7 +209,7 @@ export function NoteActions({
|
|||||||
{/* More Options */}
|
{/* More Options */}
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<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" />
|
<MoreVertical className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
|
|||||||
@@ -372,11 +372,20 @@ export function SearchModal({ isOpen, onClose }: SearchModalProps) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Keyboard navigation
|
// Keyboard navigation + focus trap
|
||||||
|
const modalRef = useRef<HTMLDivElement>(null)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isOpen) return
|
if (!isOpen) return
|
||||||
const handleKeyDown = (e: KeyboardEvent) => {
|
const handleKeyDown = (e: KeyboardEvent) => {
|
||||||
if (e.key === 'Escape') { e.preventDefault(); onClose() }
|
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 === '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 === 'ArrowUp') { e.preventDefault(); setSelectedIndex(p => Math.max(p - 1, 0)) }
|
||||||
else if (e.key === 'Enter') {
|
else if (e.key === 'Enter') {
|
||||||
@@ -412,6 +421,7 @@ export function SearchModal({ isOpen, onClose }: SearchModalProps) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<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"
|
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"
|
role="dialog"
|
||||||
aria-modal="true"
|
aria-modal="true"
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ export function buildAuthProviders() {
|
|||||||
|
|
||||||
const { email, password } = parsedCredentials.data;
|
const { email, password } = parsedCredentials.data;
|
||||||
|
|
||||||
const { allowed } = rateLimit(`login:${email.toLowerCase()}`);
|
const { allowed } = await rateLimit(`login:${email.toLowerCase()}`, 'login', 5, 300);
|
||||||
if (!allowed) {
|
if (!allowed) {
|
||||||
return null;
|
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 WINDOW_SECONDS = 60
|
||||||
const MAX_ATTEMPTS = 5
|
const MAX_REQUESTS = 20
|
||||||
|
|
||||||
export function rateLimit(key: string): { allowed: boolean; retryAfterMs: number } {
|
export async function rateLimit(
|
||||||
const now = Date.now()
|
userId: string,
|
||||||
const entry = attempts.get(key)
|
feature: string,
|
||||||
|
max: number = MAX_REQUESTS,
|
||||||
if (!entry || now > entry.resetAt) {
|
windowSec: number = WINDOW_SECONDS,
|
||||||
attempts.set(key, { count: 1, resetAt: now + WINDOW_MS })
|
): Promise<{ allowed: boolean; remaining: number }> {
|
||||||
return { allowed: true, retryAfterMs: 0 }
|
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(() => {
|
export function rateLimitResponse(remaining: number): NextResponse | null {
|
||||||
const now = Date.now()
|
return null
|
||||||
for (const [k, v] of attempts) {
|
}
|
||||||
if (now > v.resetAt) attempts.delete(k)
|
|
||||||
}
|
|
||||||
}, 60_000)
|
|
||||||
|
|||||||
Reference in New Issue
Block a user