teqo/src/utilities/ai/rateLimit.ts
Francisco Solla 4668c018bf feat(B173): consulta por voz no chat da Sollinha (STT → rascunho)
Adiciona entrada por voz ao chat: botão de mic no InputGroup grava no
browser (getUserMedia + MediaRecorder), envia o clip multipart para a nova
rota POST /campanha/api/ai-transcribe (auth cookie + rate limit no mesmo
balde + same-origin) e injeta a transcrição como rascunho editável — o
envio segue o fluxo normal do chat. O áudio nunca é persistido.

STT via Deep Infra whisper-large-v3 (DEEPINFRA_API_KEY, mesma do B174);
a costura de rede vive em utilities/ai/deepInfraTranscribe.ts; a máquina
de captura em useMicTranscript. Falha de permissão/provedor degrada a
mensagem em pt-BR sem quebrar o chat por texto.

Closes #448
2026-08-09 01:47:03 -03:00

50 lines
1.2 KiB
TypeScript

/**
* In-memory rate limiter for the AI chat endpoint.
* Survives a single instance; resets on deploy. Sufficient for v1 abuse prevention.
*/
type RateLimitWindow = {
count: number
resetAt: number
}
const store = new Map<number, RateLimitWindow>()
const MAX_MESSAGES = 50
const WINDOW_MS = 15 * 60 * 1000 // 15 minutes
/** Shared message returned by every rate-limited AI surface (chat send, voice transcribe). */
export const RATE_LIMIT_EXCEEDED_MESSAGE =
'Você atingiu o limite de mensagens. Aguarde alguns minutos e tente novamente.'
/** Cleans up expired windows. Called on every check to prevent memory leaks. */
const cleanup = (now: number) => {
for (const [userId, window] of store) {
if (now >= window.resetAt) {
store.delete(userId)
}
}
}
/**
* Returns `true` if the user is within their rate limit.
* Returns `false` if they've exceeded it.
*/
export const checkRateLimit = (userId: number): boolean => {
const now = Date.now()
cleanup(now)
const existing = store.get(userId)
if (!existing || now >= existing.resetAt) {
store.set(userId, { count: 1, resetAt: now + WINDOW_MS })
return true
}
if (existing.count >= MAX_MESSAGES) {
return false
}
existing.count++
return true
}