-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
484 lines (428 loc) · 13.4 KB
/
index.ts
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
import { Hono } from 'hono'
const app = new Hono<{ Bindings: Env }>();
interface Env {
AI: Ai;
DB: D1Database;
RATELIMIT_KV: KVNamespace;
}
app.get('/', (c) => {
return c.text('Hello Hono!')
})
function getErrorBadgeSVG(message: string) {
return getBadgeSVG(0, {
label: "Error: Too many requests",
color: "red",
labelColor: "gray",
style: "flat",
message: message
});
}
async function rateLimit(c: any, next: () => Promise<any>) {
const ip = c.req.raw.headers.get("cf-connecting-ip") || "unknown";
const KEY_PREFIX = "ratelimit:";
const LIMIT = 10;
const WINDOW = 300;
try {
const key = `${KEY_PREFIX}${ip}`;
const currentValue = await c.env.RATELIMIT_KV.get(key);
const now = Math.floor(Date.now() / 1000);
let count: number;
let resetTime: number;
if (!currentValue) {
count = 1;
resetTime = now + WINDOW;
await c.env.RATELIMIT_KV.put(key, JSON.stringify({ count, resetTime }), {
expirationTtl: WINDOW
});
} else {
const data = JSON.parse(currentValue);
if (now > data.resetTime) {
count = 1;
resetTime = now + WINDOW;
} else {
count = data.count + 1;
resetTime = data.resetTime;
}
await c.env.RATELIMIT_KV.put(key, JSON.stringify({ count, resetTime }), {
expirationTtl: WINDOW
});
}
if (count > LIMIT) {
const remainingTime = resetTime - now;
return new Response(getErrorBadgeSVG("Rate Limited"), {
status: 429,
headers: {
"Content-Type": "image/svg+xml; charset=utf-8",
"X-RateLimit-Limit": LIMIT.toString(),
"X-RateLimit-Remaining": "0",
"X-RateLimit-Reset": resetTime.toString(),
"Retry-After": remainingTime.toString(),
"Cache-Control": "no-cache, no-store, must-revalidate",
},
});
}
const response = await next();
return new Response(response.body, {
status: response.status,
headers: {
...response.headers,
"X-RateLimit-Limit": LIMIT.toString(),
"X-RateLimit-Remaining": (LIMIT - count).toString(),
"X-RateLimit-Reset": resetTime.toString(),
},
});
} catch (error) {
console.error("Rate limit error:", error);
return next();
}
}
interface BadgeStyle {
label?: string;
style?: "flat" | "flat-square" | "plastic" | "for-the-badge" | "social";
color?: string;
labelColor?: string;
logo?: string;
logoWidth?: number;
scale?: number;
format?: "svg" | "json";
message?: string;
}
const namedColors: { [key: string]: string } = {
brightgreen: "44cc11",
green: "97ca00",
yellow: "dfb317",
yellowgreen: "a4a61d",
orange: "fe7d37",
red: "e05d44",
blue: "007ec6",
grey: "555",
gray: "555",
lightgrey: "9f9f9f",
lightgray: "9f9f9f",
};
function getBadgeSVG(count: number, options: BadgeStyle = {}) {
const {
label = "Profile views",
style = "flat",
color = "blue",
labelColor = "gray",
logo = "",
logoWidth = 14,
scale = 1,
} = options;
const labelText = label.trim();
const countText = count.toLocaleString();
const bgColor = namedColors[color] || color.replace(/^#/, "");
const lblColor = namedColors[labelColor] || labelColor.replace(/^#/, "");
const styles = {
flat: {
height: 20,
radius: 3,
fontSize: 11,
paddingH: 8,
gradient: false,
shadow: false,
},
"flat-square": {
height: 20,
radius: 0,
fontSize: 11,
paddingH: 8,
gradient: false,
shadow: false,
},
plastic: {
height: 20,
radius: 4,
fontSize: 11,
paddingH: 8,
gradient: true,
shadow: true,
},
"for-the-badge": {
height: 28,
radius: 4,
fontSize: 14,
paddingH: 12,
gradient: false,
shadow: false,
uppercase: true,
},
social: {
height: 20,
radius: 4,
fontSize: 11,
paddingH: 8,
gradient: true,
shadow: true,
rounded: true,
},
}[style];
const config = styles;
const height = config.height * scale;
const labelWidth =
(labelText.length * config.fontSize * 0.6 + config.paddingH * 2) * scale;
const countWidth =
(countText.length * config.fontSize * 0.6 + config.paddingH * 2) * scale;
const totalWidth =
(labelWidth + countWidth + (logo ? logoWidth + 4 : 0)) * scale;
return `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${totalWidth}" height="${height}">
<title>${labelText}: ${countText}</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#fff" stop-opacity=".7"/>
<stop offset=".1" stop-color="#aaa" stop-opacity=".1"/>
<stop offset=".9" stop-color="#000" stop-opacity=".3"/>
<stop offset="1" stop-color="#000" stop-opacity=".5"/>
</linearGradient>
<clipPath id="r">
<rect width="${totalWidth}" height="${height}" rx="${config.radius}" fill="#fff"/>
</clipPath>
<g clip-path="url(#r)">
<rect width="${labelWidth}" height="${height}" fill="#${lblColor}"/>
<rect x="${labelWidth}" width="${countWidth}" height="${height}" fill="#${bgColor}"/>
${config.gradient ? `<rect width="${totalWidth}" height="${height}" fill="url(#s)"/>` : ""}
</g>
${config.shadow ? `<g fill="#000" fill-opacity=".3">
<rect x="1" width="${labelWidth}" height="1"/>
<rect x="${labelWidth + 1}" width="${countWidth}" height="1"/>
</g>` : ""}
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="${config.fontSize * scale}">
${logo ? `<image x="5" y="${(height - logoWidth) / 2}" width="${logoWidth}" height="${logoWidth}" xlink:href="${logo}"/>` : ""}
<text x="${labelWidth / 2 + (logo ? logoWidth : 0)}" y="${height / 2}" dominant-baseline="middle">
${config.uppercase ? labelText.toUpperCase() : labelText}
</text>
<text x="${labelWidth + countWidth / 2}" y="${height / 2}" dominant-baseline="middle">
${config.uppercase ? countText.toUpperCase() : countText}
</text>
</g>
</svg>`;
}
interface GitHubUser {
login: string;
followers: number;
following: number;
}
async function getGitHubUser(username: string): Promise<GitHubUser | null> {
try {
const response = await fetch(`https://api.github.com/users/${username}`, {
headers: {
'User-Agent': 'GitHub-Profile-Views-Counter',
}
});
if (!response.ok) return null;
return await response.json();
} catch (error) {
console.error("GitHub API error:", error);
return null;
}
}
app.get("/visitor-badge/:repo", async (c) => {
try {
const rateLimitResponse = await rateLimit(c, async () => {
const repo = c.req.param("repo");
const username = repo.split('/')[0];
await c.env.DB.batch([
c.env.DB.prepare(`
CREATE TABLE IF NOT EXISTS github_users (
username TEXT PRIMARY KEY,
followers INTEGER,
following INTEGER,
last_updated DATETIME DEFAULT CURRENT_TIMESTAMP
)
`),
c.env.DB.prepare(`
CREATE TABLE IF NOT EXISTS visitors (
repo TEXT PRIMARY KEY,
count INTEGER DEFAULT 0,
last_updated DATETIME DEFAULT CURRENT_TIMESTAMP
)
`)
]);
const [userResult, visitorResult] = await Promise.all([
c.env.DB.prepare(`
SELECT * FROM github_users
WHERE username = ?1
AND (julianday(CURRENT_TIMESTAMP) - julianday(last_updated)) * 24 < 24
`)
.bind(username)
.first(),
c.env.DB.prepare(`
INSERT INTO visitors (repo, count, last_updated)
VALUES (?1, 1, CURRENT_TIMESTAMP)
ON CONFLICT(repo) DO UPDATE SET
count = count + 1,
last_updated = CURRENT_TIMESTAMP
RETURNING count
`)
.bind(repo)
.first()
]);
if (!userResult) {
const githubUser = await getGitHubUser(username);
if (githubUser) {
await c.env.DB.prepare(`
INSERT INTO github_users (username, followers, following, last_updated)
VALUES (?1, ?2, ?3, CURRENT_TIMESTAMP)
ON CONFLICT(username) DO UPDATE SET
followers = ?2,
following = ?3,
last_updated = CURRENT_TIMESTAMP
`)
.bind(username, githubUser.followers, githubUser.following)
.run();
}
}
const count = visitorResult?.count || 1;
const style = (c.req.query("style") as BadgeStyle["style"]) || "flat";
const color = c.req.query("color") || "blue";
const labelColor = c.req.query("label_color") || "gray";
const label = c.req.query("label") || "Profile views";
const logo = c.req.query("logo") || "";
const scale = Number(c.req.query("scale")) || 1;
const svg = getBadgeSVG(Number(count), {
style,
color,
labelColor,
label,
logo,
scale,
logoWidth: logo ? 14 : 0,
});
return new Response(svg, {
headers: {
"Content-Type": "image/svg+xml; charset=utf-8",
"Cache-Control": "public, max-age=60, s-maxage=60, stale-while-revalidate=300",
"CDN-Cache-Control": "max-age=60",
"Surrogate-Control": "max-age=60",
"Edge-Control": "max-age=60",
"Age": "0",
"Vary": "Accept-Encoding",
"ETag": `"${count}"`
},
});
});
return rateLimitResponse;
} catch (error) {
console.error("Visitor badge error:", error);
return new Response(getErrorBadgeSVG("Server Error"), {
status: 500,
headers: {
"Content-Type": "image/svg+xml; charset=utf-8",
"Cache-Control": "no-cache"
}
});
}
});
function sanitizeText(text: string): string {
return text
.replace(/[<>&'"]/g, '')
.replace(/[^\x20-\x7E]/g, '')
.trim()
.slice(0, 50);
}
function getAIBadgeSVG(text: string, options: BadgeStyle = {}) {
const {
label = "AI Says",
style = "flat",
color = "blue",
labelColor = "gray",
scale = 1.5,
} = options;
const height = 28 * scale;
const fontSize = 12 * scale;
const padding = 10 * scale;
const labelText = label.trim();
const messageText = text.trim();
const labelWidth = Math.max(
(labelText.length * fontSize * 0.6 + padding * 2),
80
);
const messageWidth = Math.max(
(messageText.length * fontSize * 0.6 + padding * 2),
200
);
const totalWidth = labelWidth + messageWidth;
const bgColor = namedColors[color] || color.replace(/^#/, "");
const lblColor = namedColors[labelColor] || labelColor.replace(/^#/, "");
return `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="${totalWidth}" height="${height}">
<title>${labelText}: ${messageText}</title>
<g>
<rect width="${totalWidth}" height="${height}" fill="#${lblColor}" rx="4"/>
<rect x="${labelWidth}" width="${messageWidth}" height="${height}" fill="#${bgColor}" rx="4"/>
</g>
<g fill="#fff" text-anchor="start" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="${fontSize}">
<text x="${padding}" y="${height/2}" dominant-baseline="middle">
${labelText}
</text>
<text x="${labelWidth + padding}" y="${height/2}" dominant-baseline="middle">
${messageText}
</text>
</g>
</svg>`;
}
app.get("/ai-badge", async (c) => {
const ip = c.req.raw.headers.get("cf-connecting-ip") || "unknown";
try {
const result = await c.env.DB.prepare(`
SELECT COUNT(*) as count FROM rate_limits
WHERE ip = ?1
AND (julianday(CURRENT_TIMESTAMP) - julianday(last_reset)) * 24 * 60 < 1
`)
.bind(ip)
.first();
if (((result?.count as number) || 0) >= 5) {
return new Response(getErrorBadgeSVG("Rate Limited"), {
status: 429,
headers: {
"Content-Type": "image/svg+xml; charset=utf-8",
"Retry-After": "60"
}
});
}
const prompt = c.req.query("prompt") || "Generate a short inspirational message";
const style = (c.req.query("style") as BadgeStyle["style"]) || "flat";
const color = c.req.query("color") || "blue";
const labelColor = c.req.query("label_color") || "gray";
const label = c.req.query("label") || "AI Says";
const scale = Number(c.req.query("scale")) || 1.5;
const response = await c.env.AI.run("@cf/meta/llama-3.1-8b-instruct", {
messages: [
{
role: "system",
content: "You are a chatbot. Keep responses under 50 characters.",
},
{ role: "user", content: prompt },
],
stream: false,
max_tokens: 50,
});
let aiText = "Hello World!";
if (response && typeof response === 'object' && 'response' in response) {
aiText = (response as any).response
} else if (response) {
aiText = String(response);
}
const svg = getAIBadgeSVG(aiText, {
style,
color,
labelColor,
label,
scale,
});
return new Response(svg, {
headers: {
"Content-Type": "image/svg+xml; charset=utf-8",
"Cache-Control": "public, max-age=1800",
"CDN-Cache-Control": "public, max-age=1800",
},
});
} catch (error) {
console.error("AI badge error:", error);
return new Response(getErrorBadgeSVG("AI Error"), {
headers: { "Content-Type": "image/svg+xml; charset=utf-8" },
});
}
});
export default app