1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
|
import { Hono } from "hono";
import { cors } from "hono/cors";
import { serveStatic } from "hono/bun";
import pino from "pino";
const app = new Hono();
const reqLogger = pino(pino.destination("req"));
const resLogger = pino(pino.destination("res"));
// CORS
app.use(
"*",
cors({
origin: (origin) => origin || "*",
credentials: true,
}),
);
// Static files
app.use("/public/*", serveStatic({ root: "/home/bun/app/data/uploads", rewriteRequestPath: (p) => p.replace("/public", "") }));
// Rate limiting (disabled in development)
const prod = process.env.NODE_ENV === "production";
const rateLimits = new Map<string, { count: number; reset: number }>();
const strictLimits = new Map<string, { count: number; reset: number }>();
if (prod) {
app.use("*", async (c, next) => {
const url = c.req.path;
// Skip rate limiting for public assets
if (url.includes("public")) return next();
const ip = (c.req.header("cf-connecting-ip") as string) || (c.env as any)?.ip || "unknown";
const ua = c.req.header("user-agent") || "unknown-ua";
const rateLimitBy = c.req.header("rate-limit-by");
const key = rateLimitBy === "ua" ? ua : ip;
const now = Date.now();
// General rate limit: 2000 req / 2s
const gen = rateLimits.get(key);
if (gen && now < gen.reset) {
gen.count++;
if (gen.count > 2000) {
return c.json(
{ statusCode: 429, error: "Too Many Requests", message: "Rate limit exceeded, retry in 2 seconds" },
429,
);
}
} else {
rateLimits.set(key, { count: 1, reset: now + 2000 });
}
// Strict rate limit for /login and /send: 10 req / 10s
const isStrict = url.includes("/login") || url.includes("/send");
if (isStrict) {
const strictKey = `strict:${ua}`;
const s = strictLimits.get(strictKey);
if (s && now < s.reset) {
s.count++;
if (s.count > 10) {
return c.json(
{ statusCode: 429, error: "Too Many Requests", message: "Rate limit exceeded" },
429,
);
}
} else {
strictLimits.set(strictKey, { count: 1, reset: now + 10000 });
}
}
return next();
});
// Clean up rate limit maps periodically
setInterval(() => {
const now = Date.now();
for (const [k, v] of rateLimits) if (now >= v.reset) rateLimits.delete(k);
for (const [k, v] of strictLimits) if (now >= v.reset) strictLimits.delete(k);
}, 5000);
}
// Request logging
app.use("*", async (c, next) => {
const start = Date.now();
const url = c.req.path;
const ignore = [
"/ws",
"/me",
"/confirm",
"/public",
"/rates",
"/challenge",
"/rate",
"/lnurlp",
"/subscriptions",
"/accounts",
"/contacts",
];
const shouldLog = !ignore.some((path) => url.startsWith(path)) &&
!(c.req.method === "GET" && url.startsWith("/users"));
if (shouldLog) {
const xff = c.req.header("x-forwarded-for");
const forwardedIp = xff?.split(",")[0]?.trim();
const ip = c.req.header("cf-connecting-ip") || forwardedIp || (c.env as any)?.ip || "unknown";
let body;
// Only parse body for non-GET requests
if (c.req.method !== "GET" && c.req.method !== "HEAD") {
try {
body = await c.req.raw.clone().json();
} catch {}
}
reqLogger.info({
method: c.req.method,
url,
ip,
query: c.req.query(),
body,
user: (c.get("user" as never) as any)?.username,
});
}
await next();
const rawCookies = c.req.header("cookie") || "";
const cookies: any = rawCookies.split(";").reduce((acc, cookie) => {
const [key, value] = cookie.split("=").map((s) => s.trim());
if (key && value) acc[key] = value;
return acc;
}, {});
resLogger.info({
url,
statusCode: c.res.status,
durationMs: Date.now() - start,
username: cookies.username,
});
});
// Error handler
app.onError((err, c) => {
console.error("unhandled error:", c.req.method, c.req.path, err?.message || err);
return c.json({ ok: false }, 500);
});
// Not found handler
app.notFound((c) => c.text("Not Found", 404));
export default app;
|