Repository navigation
Expand file tree
/
Copy pathrate-limiter.js
More file actions
336 lines (294 loc) · 11.6 KB
/
Copy pathrate-limiter.js
File metadata and controls
336 lines (294 loc) · 11.6 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
/**
* ExploitInject Hybrid Cross-Browser Form Rate Limiter & Anonymous Geo Tracker
* Enforces 1 form submission per 5 minutes per IP Address & Email Address.
* Ensures IP Address & Country are attached under all standard field names for FormFarm delivery.
*/
(function () {
const RATE_LIMIT_MS = 5 * 60 * 1000; // 5 minutes
const STORAGE_KEY = 'app_form_submissions';
const GEO_CACHE_KEY = 'user_geo_data';
let cachedGeo = { ip: '', country: '' };
// 1. Fetch IP & Country Anonymously
async function fetchGeoData() {
try {
const cached = sessionStorage.getItem(GEO_CACHE_KEY);
if (cached) {
const parsed = JSON.parse(cached);
if (parsed && parsed.ip) {
cachedGeo = parsed;
updateAllFormGeoFields();
return cachedGeo;
}
}
} catch (e) { }
// Primary API: ipapi.co
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 3000);
const res = await fetch('https://ipapi.co/json/', { signal: controller.signal });
clearTimeout(timeoutId);
if (res.ok) {
const data = await res.json();
if (data && data.ip) {
cachedGeo = {
ip: data.ip,
country: data.country_name || data.country || 'Unknown'
};
saveAndApplyGeo();
return cachedGeo;
}
}
} catch (e) { }
// Fallback 1: country.is
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 3000);
const res = await fetch('https://api.country.is/', { signal: controller.signal });
clearTimeout(timeoutId);
if (res.ok) {
const data = await res.json();
if (data && data.ip) {
cachedGeo = {
ip: data.ip,
country: data.country || 'Unknown'
};
saveAndApplyGeo();
return cachedGeo;
}
}
} catch (e) { }
// Fallback 2: ipify
try {
const res = await fetch('https://api.ipify.org?format=json');
if (res.ok) {
const data = await res.json();
if (data && data.ip) {
cachedGeo = {
ip: data.ip,
country: cachedGeo.country || 'Unknown'
};
saveAndApplyGeo();
return cachedGeo;
}
}
} catch (e) { }
return cachedGeo;
}
function saveAndApplyGeo() {
try {
sessionStorage.setItem(GEO_CACHE_KEY, JSON.stringify(cachedGeo));
} catch (e) { }
updateAllFormGeoFields();
}
// Ensures hidden fields exist with field names FormFarm formats into email notifications
function updateFormGeoFields(form) {
if (!form) return;
const ipVal = cachedGeo.ip || 'Detecting...';
const countryVal = cachedGeo.country || 'Detecting...';
// Target field names that FormFarm and form services include in emails
const fieldMappings = [
{ name: 'IP Address', value: ipVal },
{ name: 'Country', value: countryVal },
{ name: 'user_ip', value: ipVal },
{ name: 'user_country', value: countryVal }
];
fieldMappings.forEach(field => {
let input = form.querySelector(`input[name="${field.name}"]`);
if (!input) {
input = document.createElement('input');
input.type = 'hidden';
input.name = field.name;
form.appendChild(input);
}
if (field.value && field.value !== 'Detecting...') {
input.value = field.value;
} else if (!input.value) {
input.value = field.value;
}
});
}
function updateAllFormGeoFields() {
document.querySelectorAll('form').forEach(updateFormGeoFields);
}
// Get active submissions from localStorage, clearing expired entries (>5 mins)
function getValidSubmissions() {
let submissions = [];
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) {
submissions = JSON.parse(raw);
}
} catch (e) { }
const now = Date.now();
submissions = submissions.filter(item => (now - item.timestamp) < RATE_LIMIT_MS);
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(submissions));
} catch (e) { }
return submissions;
}
function recordLocalSubmission(ip, email) {
const submissions = getValidSubmissions();
submissions.push({
ip: ip,
email: email,
timestamp: Date.now()
});
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(submissions));
} catch (e) { }
}
// Display user-friendly rate limit error message
function showRateLimitError(form, remainingSec) {
const mins = Math.floor(remainingSec / 60);
const secs = remainingSec % 60;
const timeStr = mins > 0 ? `${mins}m ${secs}s` : `${secs}s`;
let msgEl = form.querySelector('.rate-limit-error-banner');
if (!msgEl) {
msgEl = document.createElement('div');
msgEl.className = 'rate-limit-error-banner';
msgEl.style.cssText = `
background-color: rgba(239, 68, 68, 0.15);
border: 1px solid rgba(239, 68, 68, 0.5);
color: #f87171;
padding: 12px 16px;
border-radius: 8px;
margin-top: 15px;
margin-bottom: 15px;
font-size: 14px;
line-height: 1.5;
text-align: center;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
animation: fadeIn 0.3s ease-in-out;
`;
const submitBtn = form.querySelector('button[type="submit"], input[type="submit"]');
if (submitBtn && submitBtn.parentNode) {
submitBtn.parentNode.insertBefore(msgEl, submitBtn);
} else {
form.appendChild(msgEl);
}
}
msgEl.innerHTML = `<strong>⚠️ Rate Limit Exceeded</strong><br>To prevent spam, form submissions are limited to once every 5 minutes. Please wait <strong>${timeStr}</strong> before submitting again.`;
msgEl.style.display = 'block';
try {
msgEl.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
} catch (e) { }
}
function removeRateLimitError(form) {
const msgEl = form.querySelector('.rate-limit-error-banner');
if (msgEl) {
msgEl.style.display = 'none';
}
}
function resetSubmitButtons(form) {
setTimeout(() => {
const btns = form.querySelectorAll('button[type="submit"], input[type="submit"]');
btns.forEach(btn => {
btn.disabled = false;
btn.classList.remove('loading');
});
}, 50);
}
// Check with server-side PHP endpoint (rate-check.php) for cross-browser rate limit
async function checkServerRateLimit(email, ip) {
try {
if (window.location.protocol === 'file:') return null;
const res = await fetch('/rate-check.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: email, ip: ip })
});
if (res.ok) {
return await res.json();
}
} catch (e) { }
return null;
}
// Main Form Submit Interceptor (Capturing Phase)
async function handleFormSubmit(e) {
const form = e.target;
if (!form || form.tagName !== 'FORM') return;
// Skip if already rate-verified for this submission event
if (form.dataset.rateVerified === 'true') {
delete form.dataset.rateVerified;
// Always refresh geo fields right before final post
updateFormGeoFields(form);
return;
}
// Make sure geo data is fetched if still empty
if (!cachedGeo.ip) {
await fetchGeoData();
}
updateFormGeoFields(form);
// Extract Email
let userEmail = '';
const emailInput = form.querySelector('input[type="email"], input[name="email"], input[name="fi-sender-email"], input[name="user_email"]');
if (emailInput && emailInput.value) {
userEmail = emailInput.value.trim().toLowerCase();
}
const userIp = cachedGeo.ip || '';
const now = Date.now();
// 1. Fast Local Check
const submissions = getValidSubmissions();
const localMatch = submissions.find(item => {
const ipMatch = userIp && item.ip && item.ip === userIp;
const emailMatch = userEmail && item.email && item.email === userEmail;
return ipMatch || emailMatch;
});
if (localMatch) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
const elapsed = now - localMatch.timestamp;
const remainingSec = Math.ceil((RATE_LIMIT_MS - elapsed) / 1000);
showRateLimitError(form, remainingSec);
resetSubmitButtons(form);
return false;
}
// 2. Cross-Browser Server Check (rate-check.php)
if (window.location.protocol !== 'file:') {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
const serverRes = await checkServerRateLimit(userEmail, userIp);
if (serverRes) {
if (serverRes.clientIp && !cachedGeo.ip) {
cachedGeo.ip = serverRes.clientIp;
}
if (serverRes.allowed === false) {
recordLocalSubmission(userIp, userEmail);
showRateLimitError(form, serverRes.remainingSec || 300);
resetSubmitButtons(form);
return false;
}
}
// Allowed by server -> sync local and re-trigger submission
removeRateLimitError(form);
recordLocalSubmission(userIp, userEmail);
// Update geo fields again right before final submit
updateFormGeoFields(form);
form.dataset.rateVerified = 'true';
// Re-trigger form submission smoothly
if (typeof form.requestSubmit === 'function') {
form.requestSubmit();
} else {
form.submit();
}
return;
}
// 3. File protocol / Local fallback
removeRateLimitError(form);
recordLocalSubmission(userIp, userEmail);
}
// Initialize
document.addEventListener('DOMContentLoaded', () => {
updateAllFormGeoFields();
fetchGeoData();
});
// Capture submit events BEFORE any other page handlers
document.addEventListener('submit', handleFormSubmit, true);
// Initial fetch in case DOM is already loaded
if (document.readyState === 'interactive' || document.readyState === 'complete') {
updateAllFormGeoFields();
fetchGeoData();
}
})();