cg / hackerproducts

63 files · 5,740 lines · 159.1 KB — Next.js 15, React 19, TypeScript, PostgreSQL, Object Storage, plain CSS.

Quick jump: page.tsx / page.tsx / globals.css / schema.sql / package.json

root / src / lib / antispam.ts

src/lib/antispam.ts · 80 lines · 2.4 KB← back to folder
1import crypto from "node:crypto";
2import { query } from "@/db";
3
4export const PRODUCT_COOLDOWN_DAYS = 7;
5
6export function getHashedClientIp(request: Request): string {
7 const forwarded = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
8 const realIp = request.headers.get("x-real-ip")?.trim();
9 const raw = forwarded || realIp || "unknown";
10 return crypto.createHash("sha256").update(`hp_ip:${raw}`).digest("hex").slice(0, 32);
11}
12
13export async function checkAndRecordRateLimit(opts: {
14 action: string;
15 key: string;
16 maxCount: number;
17 windowSeconds: number;
18}): Promise<{ allowed: boolean; count: number }> {
19 const res = await query<{ count: string }>(
20 `SELECT COUNT(*)::int AS count
21 FROM rate_limits
22 WHERE action = $1
23 AND key = $2
24 AND created_at > NOW() - ($3::text || ' seconds')::interval`,
25 [opts.action, opts.key, String(opts.windowSeconds)]
26 );
27
28 const count = Number(res.rows[0]?.count ?? 0);
29 if (count >= opts.maxCount) {
30 return { allowed: false, count };
31 }
32
33 await query(`INSERT INTO rate_limits (action, key) VALUES ($1, $2)`, [
34 opts.action,
35 opts.key,
36 ]);
37 return { allowed: true, count: count + 1 };
38}
39
40export async function getProductSubmissionCooldown(userId: string): Promise<{
41 allowed: boolean;
42 nextAllowedAt?: Date;
43 daysRemaining?: number;
44}> {
45 const res = await query<{ created_at: string }>(
46 `SELECT created_at
47 FROM products
48 WHERE owner_id = $1 AND status <> 'removed'
49 ORDER BY created_at DESC
50 LIMIT 1`,
51 [userId]
52 );
53
54 const latest = res.rows[0];
55 if (!latest) return { allowed: true };
56
57 const lastCreated = new Date(latest.created_at);
58 const cooldownMs = PRODUCT_COOLDOWN_DAYS * 24 * 60 * 60 * 1000;
59 const nextAllowedAt = new Date(lastCreated.getTime() + cooldownMs);
60 const remainingMs = nextAllowedAt.getTime() - Date.now();
61
62 if (remainingMs <= 0) {
63 return { allowed: true };
64 }
65
66 const daysRemaining = Math.max(1, Math.ceil(remainingMs / (24 * 60 * 60 * 1000)));
67 return { allowed: false, nextAllowedAt, daysRemaining };
68}
69
70export function normalizeWebsiteForDedup(url: string): string {
71 try {
72 const parsed = new URL(url);
73 const host = parsed.hostname.toLowerCase().replace(/^www\./, "");
74 const pathname = parsed.pathname.replace(/\/+$/, "");
75 return `${host}${pathname}`.toLowerCase();
76 } catch {
77 return url.trim().toLowerCase();
78 }
79}
80
cg / hackerproducts — hacker products