wacrm/src/lib/rate-limit.ts
Arnas Donauskas 339b1fe94f
feat(inbox): reactions, reply-to, and copy on chat messages
Adds three WhatsApp-standard affordances to the inbox: per-message
emoji reactions, reply-with-quote, and copy-text. Bubbles stay pure
presenters — actions layer on by composition (MessageActions wraps
MessageBubble). Hover toolbar on desktop, long-press (onContextMenu)
on touch.

Data model (migration 009):
- messages.reply_to_message_id (self-FK, ON DELETE SET NULL) so replies
  survive a deleted parent
- message_reactions table — one row per (message, actor) with a unique
  constraint, conversation_id denormalised so Supabase Realtime can
  filter without a join
- RLS scoped via conversation ownership; service-role bypass for the
  webhook

API:
- /api/whatsapp/send accepts reply_to_message_id, resolves the parent's
  Meta message_id and forwards it as context.message_id
- /api/whatsapp/react (new) sends Meta reaction payloads and mirrors
  the upsert/delete into message_reactions
- Webhook stops storing inbound reactions as fake text messages and
  instead upserts/deletes message_reactions; inbound replies (context.id)
  resolve to internal UUID and populate reply_to_message_id

UI:
- MessageActions hover toolbar with inline 6-emoji Popover (static set;
  no emoji-picker library)
- ReplyQuote shared between the in-bubble quote and the composer chip
- MessageReactions pill row with click-to-toggle
- Thread subscribes to message_reactions filtered by conversation_id;
  optimistic upsert with rollback on failure

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 16:17:26 +03:00

136 lines
4.1 KiB
TypeScript

/**
* In-memory per-key rate limiter.
*
* Fixed-window counter (not token bucket): every identifier gets a
* fresh N-request budget each window. Simple, allocation-light, and
* fine for a single-instance VPS — which is how forkers of this
* template will usually deploy.
*
* Trade-off: a single Node process holds the Map, so horizontal scale
* (multiple regions, multiple Hostinger nodes, Vercel serverless fan-
* out) silently defeats the limit. If you scale beyond one instance,
* swap the `check` implementation for Redis / Upstash / Cloudflare
* Durable Objects keeping the same return shape. The call sites won't
* change.
*
* Memory: entries are ~50 bytes each. With LIGHT_SWEEP below, expired
* keys get cleared opportunistically on every ~1 000th call, so a
* healthy instance stays in the low-MB range even with thousands of
* distinct users. No background timer — works in serverless edge
* runtimes that don't keep timers alive across requests.
*/
import { NextResponse } from 'next/server';
export interface RateLimitOptions {
/** Max requests allowed in `windowMs`. */
limit: number;
/** Window size, milliseconds. */
windowMs: number;
}
export interface RateLimitResult {
success: boolean;
/** Requests still allowed in the current window. */
remaining: number;
/** Unix ms when the bucket refills. */
reset: number;
limit: number;
}
interface Entry {
count: number;
resetAt: number;
}
const buckets = new Map<string, Entry>();
// Opportunistic cleanup. Running a sweep on every call would be
// quadratic; running it 1-in-N lets the Map self-drain without a
// background timer.
const LIGHT_SWEEP_EVERY = 1000;
let callsSinceSweep = 0;
function sweepExpired(now: number) {
for (const [k, v] of buckets) {
if (v.resetAt <= now) buckets.delete(k);
}
}
export function checkRateLimit(
key: string,
{ limit, windowMs }: RateLimitOptions,
): RateLimitResult {
const now = Date.now();
callsSinceSweep += 1;
if (callsSinceSweep >= LIGHT_SWEEP_EVERY) {
callsSinceSweep = 0;
sweepExpired(now);
}
const entry = buckets.get(key);
if (!entry || entry.resetAt <= now) {
buckets.set(key, { count: 1, resetAt: now + windowMs });
return { success: true, remaining: limit - 1, reset: now + windowMs, limit };
}
if (entry.count >= limit) {
return { success: false, remaining: 0, reset: entry.resetAt, limit };
}
entry.count += 1;
return {
success: true,
remaining: limit - entry.count,
reset: entry.resetAt,
limit,
};
}
/**
* Standard 429 response with the headers clients expect (RFC 6585 +
* draft-ietf-httpapi-ratelimit-headers). Callers just `return` this.
*/
export function rateLimitResponse(result: RateLimitResult): NextResponse {
const retryAfterSec = Math.max(1, Math.ceil((result.reset - Date.now()) / 1000));
return NextResponse.json(
{
error: 'Rate limit exceeded',
retry_after_seconds: retryAfterSec,
},
{
status: 429,
headers: {
'Retry-After': String(retryAfterSec),
'X-RateLimit-Limit': String(result.limit),
'X-RateLimit-Remaining': String(result.remaining),
'X-RateLimit-Reset': String(Math.ceil(result.reset / 1000)),
},
},
);
}
/** Preconfigured budgets, tweak here not at call sites. */
export const RATE_LIMITS = {
/** Individual message send. 60/min per user = one per second
* sustained, comfortable for a live human typing. */
send: { limit: 60, windowMs: 60_000 },
/** Broadcast dispatch. 5/min per user — even a 1 000-recipient
* broadcast is one call; this caps the rate at which a single user
* can launch campaigns, not the messages inside one. */
broadcast: { limit: 5, windowMs: 60_000 },
/** Reaction add/swap/remove. More permissive than send — users
* fidget with reactions and a single "swap" is actually two calls
* (remove + add) under the hood. */
react: { limit: 120, windowMs: 60_000 },
} as const;
/** Test-only helper. Clears the in-memory state so unit tests don't
* leak buckets across files. Not wired up in production code. */
export function __resetRateLimitForTests() {
buckets.clear();
callsSinceSweep = 0;
}