-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
576 lines (487 loc) · 16.5 KB
/
worker.js
File metadata and controls
576 lines (487 loc) · 16.5 KB
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/**
* ADMENSION Cloudflare Worker API
* Handles link creation and retrieval using KV storage
* Features: Progressive rate limiting, abuse prevention, smart throttling
*/
// CORS headers for cross-origin requests
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
};
// Rate limiting configuration (very lenient but protective)
const RATE_LIMITS = {
// Link creation limits (POST /api/links)
create: {
perMinute: 10, // 10 links per minute
perHour: 100, // 100 links per hour
perDay: 500, // 500 links per day (0.5% of daily quota)
},
// Link fetching limits (GET /api/links/:code)
fetch: {
perMinute: 60, // 60 fetches per minute
perHour: 1000, // 1,000 fetches per hour
perDay: 5000, // 5,000 fetches per day (5% of daily quota)
},
// Update limits (PUT /api/links/:code)
update: {
perMinute: 10, // 10 updates per minute
perHour: 50, // 50 updates per hour
perDay: 200, // 200 updates per day
},
// Event collection limits (POST /api/events)
events: {
perMinute: 30, // 30 events per minute per IP
perHour: 500, // 500 events per hour
perDay: 5000, // 5,000 events per day
},
};
// Progressive timeout durations (in seconds)
const TIMEOUT_DURATIONS = {
1: 60, // 1st violation: 1 minute
2: 300, // 2nd violation: 5 minutes
3: 900, // 3rd violation: 15 minutes
4: 3600, // 4th violation: 1 hour
5: 7200, // 5th+ violations: 2 hours
};
export default {
async fetch(request, env) {
// Handle CORS preflight
if (request.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders });
}
const url = new URL(request.url);
const path = url.pathname;
const clientIP = request.headers.get('CF-Connecting-IP') || 'unknown';
try {
// GET /api/health - Health check (no rate limit)
if (request.method === 'GET' && path === '/api/health') {
return jsonResponse({ status: 'ok', timestamp: Date.now() });
}
// GET /api/stats - Global link statistics (no rate limit)
if (request.method === 'GET' && path === '/api/stats') {
return await getGlobalStats(env);
}
// GET /api/limits/:ip - Check rate limit status (admin)
if (request.method === 'GET' && path.startsWith('/api/limits/')) {
const ip = path.split('/').pop();
return await getRateLimitStatus(ip, env);
}
// Apply rate limiting to all other endpoints
const rateLimitCheck = await checkRateLimit(request, clientIP, path, env);
if (!rateLimitCheck.allowed) {
return jsonResponse({
error: 'Rate limit exceeded',
message: rateLimitCheck.message,
retryAfter: rateLimitCheck.retryAfter,
violationCount: rateLimitCheck.violationCount,
}, 429, {
'Retry-After': rateLimitCheck.retryAfter.toString(),
});
}
// GET /api/links/:code - Fetch link data
if (request.method === 'GET' && path.startsWith('/api/links/')) {
const code = path.split('/').pop().toUpperCase();
return await getLink(code, env);
}
// POST /api/links - Create new link
if (request.method === 'POST' && path === '/api/links') {
const body = await request.json();
return await createLink(body, env);
}
// PUT /api/links/:code - Update link (wallet address)
if (request.method === 'PUT' && path.startsWith('/api/links/') && !path.includes('/pageview')) {
const code = path.split('/').pop().toUpperCase();
const body = await request.json();
return await updateLink(code, body, env);
}
// POST /api/links/:code/pageview - Track a pageview
if (request.method === 'POST' && path.match(/\/api\/links\/[A-Z0-9]+\/pageview$/i)) {
const code = path.split('/').slice(-2, -1)[0].toUpperCase();
return await trackPageview(code, env);
}
// POST /api/events - Collect analytics events
if (request.method === 'POST' && path === '/api/events') {
const body = await request.json();
return await collectEvent(body, clientIP, env);
}
return jsonResponse({ error: 'Not found' }, 404);
} catch (error) {
console.error('Worker error:', error);
return jsonResponse({ error: error.message }, 500);
}
},
};
/**
* Create a new link
*/
async function createLink(data, env) {
// Validate required fields
if (!data.linkName || !data.destUrl) {
return jsonResponse({ error: 'linkName and destUrl are required' }, 400);
}
// Generate unique 6-character code
const code = generateCode();
// Prepare link data
const linkData = {
code,
linkName: data.linkName,
destUrl: data.destUrl,
message: data.message || '',
chain: data.chain || 'TRON',
addr: data.addr || '',
created: Date.now(),
lastPageview: 0,
totalPageviews: 0,
};
// Store in KV (expires in 90 days = 7776000 seconds)
await env.ADMENSION_LINKS.put(
`link:${code}`,
JSON.stringify(linkData),
{ expirationTtl: 7776000 }
);
// Update global stats: increment total created
await incrementGlobalStat(env, 'created');
// Live site base URL (configurable via Cloudflare Worker env variable)
const SITE_BASE = env.SITE_BASE_URL || 'https://garebear99.github.io/ADMENSION';
return jsonResponse({
success: true,
code,
shortLink: `${SITE_BASE}/interstitial.html?code=${code}`,
fullLink: `${SITE_BASE}/interstitial.html?code=${code}&adm=${code}`,
}, 201);
}
/**
* Get link data by code
*/
async function getLink(code, env) {
if (!code || code.length !== 6) {
return jsonResponse({ error: 'Invalid code format' }, 400);
}
const data = await env.ADMENSION_LINKS.get(`link:${code}`);
if (!data) {
return jsonResponse({ error: 'Link not found or expired' }, 404);
}
const linkData = JSON.parse(data);
// Note: Pageview tracking is handled by dedicated POST /api/links/:code/pageview endpoint
// This endpoint only fetches data without modifying stats
return jsonResponse({
success: true,
data: linkData,
});
}
/**
* Track a pageview for a link
*/
async function trackPageview(code, env) {
if (!code || code.length !== 6) {
return jsonResponse({ error: 'Invalid code format' }, 400);
}
const data = await env.ADMENSION_LINKS.get(`link:${code}`);
if (!data) {
return jsonResponse({ error: 'Link not found or expired' }, 404);
}
const linkData = JSON.parse(data);
// Update traffic stats
linkData.lastPageview = Date.now();
linkData.totalPageviews = (linkData.totalPageviews || 0) + 1;
// Save updated stats back to KV (resets 90-day expiration)
await env.ADMENSION_LINKS.put(
`link:${code}`,
JSON.stringify(linkData),
{ expirationTtl: 7776000 }
);
return jsonResponse({
success: true,
totalPageviews: linkData.totalPageviews,
});
}
/**
* Update link (wallet address)
*/
async function updateLink(code, updates, env) {
if (!code || code.length !== 6) {
return jsonResponse({ error: 'Invalid code format' }, 400);
}
const data = await env.ADMENSION_LINKS.get(`link:${code}`);
if (!data) {
return jsonResponse({ error: 'Link not found or expired' }, 404);
}
const linkData = JSON.parse(data);
// Update allowed fields
if (updates.addr !== undefined) linkData.addr = updates.addr;
if (updates.chain !== undefined) linkData.chain = updates.chain;
// Save back to KV
await env.ADMENSION_LINKS.put(
`link:${code}`,
JSON.stringify(linkData),
{ expirationTtl: 7776000 }
);
return jsonResponse({
success: true,
message: 'Link updated successfully',
});
}
/**
* Generate random 6-character alphanumeric code
*/
function generateCode() {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // Exclude similar chars (0, O, 1, I)
let code = '';
for (let i = 0; i < 6; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
return code;
}
/**
* Check rate limit for IP and endpoint
*/
async function checkRateLimit(request, clientIP, path, env) {
// Check if IP is currently timed out
const timeoutKey = `timeout:${clientIP}`;
const timeout = await env.ADMENSION_LINKS.get(timeoutKey);
if (timeout) {
const timeoutData = JSON.parse(timeout);
const now = Date.now();
if (now < timeoutData.until) {
const secondsRemaining = Math.ceil((timeoutData.until - now) / 1000);
return {
allowed: false,
message: `Too many requests. Please wait ${formatDuration(secondsRemaining)} before trying again.`,
retryAfter: secondsRemaining,
violationCount: timeoutData.violationCount,
};
} else {
// Timeout expired, clean up
await env.ADMENSION_LINKS.delete(timeoutKey);
}
}
// Determine action type
let action = 'fetch';
if (request.method === 'POST' && path === '/api/links') action = 'create';
else if (request.method === 'POST' && path === '/api/events') action = 'events';
else if (request.method === 'PUT') action = 'update';
const limits = RATE_LIMITS[action];
// Check minute limit
const minuteKey = `ratelimit:${clientIP}:${action}:minute:${getCurrentMinute()}`;
const minuteCount = await incrementCounter(env, minuteKey, 60);
if (minuteCount > limits.perMinute) {
await recordViolation(env, clientIP, action, 'minute');
return await createTimeoutResponse(env, clientIP);
}
// Check hour limit
const hourKey = `ratelimit:${clientIP}:${action}:hour:${getCurrentHour()}`;
const hourCount = await incrementCounter(env, hourKey, 3600);
if (hourCount > limits.perHour) {
await recordViolation(env, clientIP, action, 'hour');
return await createTimeoutResponse(env, clientIP);
}
// Check day limit
const dayKey = `ratelimit:${clientIP}:${action}:day:${getCurrentDay()}`;
const dayCount = await incrementCounter(env, dayKey, 86400);
if (dayCount > limits.perDay) {
await recordViolation(env, clientIP, action, 'day');
return await createTimeoutResponse(env, clientIP);
}
return { allowed: true };
}
/**
* Increment counter in KV with expiration
*/
async function incrementCounter(env, key, ttl) {
const current = await env.ADMENSION_LINKS.get(key);
const count = current ? parseInt(current) + 1 : 1;
await env.ADMENSION_LINKS.put(key, count.toString(), { expirationTtl: ttl });
return count;
}
/**
* Record rate limit violation
*/
async function recordViolation(env, clientIP, action, period) {
const violationKey = `violations:${clientIP}`;
const existing = await env.ADMENSION_LINKS.get(violationKey);
let violations = existing ? JSON.parse(existing) : { count: 0, history: [] };
violations.count += 1;
violations.history.push({
timestamp: Date.now(),
action,
period,
});
// Keep only last 10 violations
if (violations.history.length > 10) {
violations.history = violations.history.slice(-10);
}
// Store for 7 days
await env.ADMENSION_LINKS.put(violationKey, JSON.stringify(violations), {
expirationTtl: 604800,
});
return violations;
}
/**
* Create timeout response based on violation count
*/
async function createTimeoutResponse(env, clientIP) {
const violationKey = `violations:${clientIP}`;
const existing = await env.ADMENSION_LINKS.get(violationKey);
const violations = existing ? JSON.parse(existing) : { count: 1 };
// Get timeout duration based on violation count
const violationCount = violations.count;
const timeoutSeconds = TIMEOUT_DURATIONS[Math.min(violationCount, 5)];
const until = Date.now() + (timeoutSeconds * 1000);
// Store timeout
const timeoutKey = `timeout:${clientIP}`;
await env.ADMENSION_LINKS.put(
timeoutKey,
JSON.stringify({ until, violationCount }),
{ expirationTtl: timeoutSeconds }
);
return {
allowed: false,
message: `Rate limit exceeded. This is violation #${violationCount}. Please wait ${formatDuration(timeoutSeconds)}.`,
retryAfter: timeoutSeconds,
violationCount,
};
}
/**
* Get rate limit status for an IP (admin endpoint)
*/
async function getRateLimitStatus(ip, env) {
const timeoutKey = `timeout:${ip}`;
const violationKey = `violations:${ip}`;
const timeout = await env.ADMENSION_LINKS.get(timeoutKey);
const violations = await env.ADMENSION_LINKS.get(violationKey);
const status = {
ip,
isTimedOut: !!timeout,
violations: violations ? JSON.parse(violations) : null,
};
if (timeout) {
const timeoutData = JSON.parse(timeout);
const secondsRemaining = Math.ceil((timeoutData.until - Date.now()) / 1000);
status.timeoutUntil = new Date(timeoutData.until).toISOString();
status.secondsRemaining = Math.max(0, secondsRemaining);
}
return jsonResponse({ success: true, status });
}
/**
* Helper functions for time periods
*/
function getCurrentMinute() {
return Math.floor(Date.now() / 60000);
}
function getCurrentHour() {
return Math.floor(Date.now() / 3600000);
}
function getCurrentDay() {
return Math.floor(Date.now() / 86400000);
}
/**
* Format duration in human-readable format
*/
function formatDuration(seconds) {
if (seconds < 60) return `${seconds} seconds`;
if (seconds < 3600) return `${Math.ceil(seconds / 60)} minutes`;
return `${Math.ceil(seconds / 3600)} hours`;
}
/**
* Get global link statistics
*/
async function getGlobalStats(env) {
try {
const stats = await env.ADMENSION_LINKS.get('global:stats');
if (!stats) {
// Initialize if doesn't exist
const initialStats = {
totalCreated: 0,
totalActive: 0,
totalRemoved: 0,
lastUpdated: Date.now(),
};
return jsonResponse({
success: true,
stats: initialStats,
});
}
return jsonResponse({
success: true,
stats: JSON.parse(stats),
});
} catch (error) {
return jsonResponse({
success: false,
error: error.message,
}, 500);
}
}
/**
* Increment global statistic counter
*/
async function incrementGlobalStat(env, statName) {
try {
const stats = await env.ADMENSION_LINKS.get('global:stats');
let statsData = stats ? JSON.parse(stats) : {
totalCreated: 0,
totalActive: 0,
totalRemoved: 0,
lastUpdated: Date.now(),
};
// Increment the specified stat
if (statName === 'created') {
statsData.totalCreated = (statsData.totalCreated || 0) + 1;
statsData.totalActive = (statsData.totalActive || 0) + 1;
} else if (statName === 'removed') {
statsData.totalRemoved = (statsData.totalRemoved || 0) + 1;
statsData.totalActive = Math.max(0, (statsData.totalActive || 0) - 1);
}
statsData.lastUpdated = Date.now();
// Store without expiration (permanent stats)
await env.ADMENSION_LINKS.put('global:stats', JSON.stringify(statsData));
} catch (error) {
console.error('Failed to increment global stat:', error);
}
}
/**
* Collect an analytics event (pageview, ad_request, ad_viewable, wallet_submit)
*/
async function collectEvent(body, clientIP, env) {
const allowedTypes = ['pageview', 'ad_request', 'ad_viewable', 'wallet_submit', 'create_link', 'list_links'];
const type = body.type || '';
if (!type || !allowedTypes.includes(type)) {
return jsonResponse({ ok: false, error: 'invalid_type' }, 400);
}
const event = {
ts: Date.now(),
type,
ip_hash: await hashIP(clientIP),
payload: body.payload || {},
};
// Store in KV with a unique key; 30-day TTL
const key = `event:${type}:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`;
await env.ADMENSION_LINKS.put(key, JSON.stringify(event), { expirationTtl: 2592000 });
// Increment daily event counter for simple analytics
const dayKey = `eventcount:${getCurrentDay()}`;
await incrementCounter(env, dayKey, 172800); // 2-day TTL
return jsonResponse({ ok: true });
}
/**
* Hash an IP address for privacy-safe storage
*/
async function hashIP(ip) {
const data = new TextEncoder().encode(ip + ':admension-salt');
const hash = await crypto.subtle.digest('SHA-256', data);
const bytes = new Uint8Array(hash);
return Array.from(bytes.slice(0, 8)).map(b => b.toString(16).padStart(2, '0')).join('');
}
/**
* Helper to return JSON response with CORS headers
*/
function jsonResponse(data, status = 200, additionalHeaders = {}) {
return new Response(JSON.stringify(data), {
status,
headers: {
'Content-Type': 'application/json',
...corsHeaders,
...additionalHeaders,
},
});
}