-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathipReputation.js
More file actions
423 lines (387 loc) · 15 KB
/
Copy pathipReputation.js
File metadata and controls
423 lines (387 loc) · 15 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
'use strict';
const ipaddr = require('ipaddr.js');
const { isPrivateOrLoopback, normalizeIpString } = require('./ip');
const { readBodyLimited } = require('./httpClient');
const PROXYCHECK_MAX_RESPONSE_BYTES = 64 * 1024;
const DEFAULTS = Object.freeze({
timeoutMs: 2500,
cacheTtlMs: 60 * 60 * 1000,
cacheMaxEntries: 4096,
maxInflight: 128,
datacenterBlockRisk: 66,
residentialReviewRisk: 90,
sweeperIntervalMs: 5 * 60 * 1000,
});
// These are process-wide ceilings, even when a caller supplies unsafe settings.
const HARD_LIMITS = Object.freeze({
timeoutMinMs: 100,
timeoutMaxMs: 10000,
cacheTtlMinMs: 1000,
cacheTtlMaxMs: 24 * 60 * 60 * 1000,
cacheMaxEntries: 50000,
maxInflight: 1024,
sweeperIntervalMinMs: 1000,
sweeperIntervalMaxMs: 60 * 60 * 1000,
});
// Cache raw provider signals, not policy decisions. This lets an administrator
// change policy or thresholds without waiting for old verdicts to expire.
const cache = new Map(); // canonical IP -> { signal, createdAt, expires }
const inFlight = new Map(); // canonical IP -> Promise<signal>
const counters = new Map();
let sweeperTimer = null;
let sweeperClearInterval = clearInterval;
let sweeperMetrics = null;
function clampFinite(value, fallback, min, max) {
const parsed = Number(value);
const finite = Number.isFinite(parsed) ? parsed : fallback;
return Math.min(max, Math.max(min, finite));
}
function clampInteger(value, fallback, min, max) {
return Math.floor(clampFinite(value, fallback, min, max));
}
function boundedText(value, maxLength) {
return String(value || '')
.replace(/[\u0000-\u001f\u007f]/g, ' ')
.trim()
.slice(0, maxLength);
}
function incrementMetric(metrics, name, amount = 1) {
counters.set(name, (counters.get(name) || 0) + amount);
try { metrics?.increment?.(name, amount); } catch (error) { /* observability must fail open */ }
}
function setGauge(metrics, name, value) {
try { metrics?.setGauge?.(name, value); } catch (error) { /* observability must fail open */ }
}
function updateSizeGauges(metrics) {
setGauge(metrics, 'ip_reputation_cache_entries', cache.size);
setGauge(metrics, 'ip_reputation_inflight', inFlight.size);
}
function normalizeConfig(cfg = {}) {
const policy = ['log-only', 'datacenter', 'strict'].includes(cfg.policy)
? cfg.policy
: 'log-only';
return {
enabled: cfg.enabled !== false,
policy,
apiKey: typeof cfg.apiKey === 'string' ? cfg.apiKey : '',
timeoutMs: clampInteger(
cfg.timeoutMs,
DEFAULTS.timeoutMs,
HARD_LIMITS.timeoutMinMs,
HARD_LIMITS.timeoutMaxMs,
),
cacheTtlMs: clampInteger(
cfg.cacheTtlMs,
DEFAULTS.cacheTtlMs,
HARD_LIMITS.cacheTtlMinMs,
HARD_LIMITS.cacheTtlMaxMs,
),
cacheMaxEntries: clampInteger(
cfg.cacheMaxEntries,
DEFAULTS.cacheMaxEntries,
1,
HARD_LIMITS.cacheMaxEntries,
),
maxInflight: clampInteger(
cfg.maxInflight,
DEFAULTS.maxInflight,
1,
HARD_LIMITS.maxInflight,
),
datacenterBlockRisk: clampFinite(cfg.datacenterBlockRisk, DEFAULTS.datacenterBlockRisk, 0, 100),
residentialReviewRisk: clampFinite(cfg.residentialReviewRisk, DEFAULTS.residentialReviewRisk, 0, 100),
fetchFn: typeof cfg.fetchFn === 'function' ? cfg.fetchFn : globalThis.fetch,
setTimeoutFn: typeof cfg.setTimeoutFn === 'function' ? cfg.setTimeoutFn : setTimeout,
clearTimeoutFn: typeof cfg.clearTimeoutFn === 'function' ? cfg.clearTimeoutFn : clearTimeout,
nowFn: typeof cfg.nowFn === 'function' ? cfg.nowFn : Date.now,
metrics: cfg.metrics,
};
}
const isMobile = type => ['wireless', 'mobile'].includes(String(type || '').toLowerCase());
const isDatacenter = type => ['hosting', 'datacenter', 'data center'].includes(String(type || '').toLowerCase());
const isVpnLike = type => ['vpn', 'tor', 'proxy'].includes(String(type || '').toLowerCase());
async function queryProxycheck(ip, config) {
if (typeof config.fetchFn !== 'function') throw new Error('proxycheck fetch unavailable');
const url = `https://proxycheck.io/v2/${encodeURIComponent(ip)}`
+ '?vpn=1&risk=1&asn=1'
+ (config.apiKey ? `&key=${encodeURIComponent(config.apiKey)}` : '');
const controller = new AbortController();
const requestPromise = (async () => {
const response = await config.fetchFn(url, {
signal: controller.signal,
headers: { Accept: 'application/json' },
});
if (!response || !response.ok) {
const status = Number.isFinite(Number(response?.status)) ? Number(response.status) : 'unknown';
throw new Error(`proxycheck HTTP ${status}`);
}
const body = await readBodyLimited(response, PROXYCHECK_MAX_RESPONSE_BYTES);
const data = JSON.parse(body.toString('utf8'));
if (data?.status && data.status !== 'ok' && data.status !== 'warning') {
throw new Error(`proxycheck status=${boundedText(data.status, 24)}`);
}
const record = data?.[ip];
if (!record || typeof record !== 'object') throw new Error('proxycheck: no record for ip');
return {
proxy: record.proxy === true || String(record.proxy || '').toLowerCase() === 'yes',
type: boundedText(record.type || 'Unknown', 40) || 'Unknown',
risk: clampFinite(record.risk, 0, 0, 100),
provider: boundedText(record.provider || record.organisation, 120),
asn: boundedText(record.asn, 32),
country: boundedText(record.country || record.isocode, 64),
};
})();
// If the deadline wins, the injected/provider promise may ignore abort and
// settle later. Attach a rejection handler so that losing work can never
// become an unhandled rejection.
requestPromise.catch(() => {});
let timer;
let settleTimeout;
const timeoutPromise = new Promise((resolve, reject) => {
settleTimeout = resolve;
timer = config.setTimeoutFn(() => {
controller.abort();
reject(new Error('proxycheck timeout'));
}, config.timeoutMs);
timer?.unref?.();
});
try {
return await Promise.race([requestPromise, timeoutPromise]);
} finally {
settleTimeout?.();
if (timer !== undefined) {
try { config.clearTimeoutFn(timer); } catch (error) { /* preserve fail-open semantics */ }
}
}
}
function classify(signal, config) {
if (isMobile(signal.type) && !signal.proxy) {
// Deliberate false-positive boundary: shared carrier/CGNAT addresses
// remain Turnstile-gated, but an explicitly confirmed proxy signal
// still proceeds to the policy layer (and strict mode blocks it).
return { rawDecision: 'allow', rawFlagged: false, reason: `mobile-network(${signal.risk})` };
}
if (isDatacenter(signal.type)) {
if (signal.risk >= config.datacenterBlockRisk || signal.proxy) {
return { rawDecision: 'block', rawFlagged: true, reason: `datacenter-high-risk(risk=${signal.risk})` };
}
return { rawDecision: 'challenge', rawFlagged: true, reason: `datacenter-low-risk(risk=${signal.risk})` };
}
if (signal.proxy || isVpnLike(signal.type)) {
return { rawDecision: 'challenge', rawFlagged: true, reason: `vpn/proxy(${signal.type})` };
}
if (signal.risk >= config.residentialReviewRisk) {
return { rawDecision: 'challenge', rawFlagged: true, reason: `residential-very-high-risk(risk=${signal.risk})` };
}
return { rawDecision: 'allow', rawFlagged: signal.risk >= 66, reason: `${signal.type}(risk=${signal.risk})` };
}
function applyPolicy(raw, signal, policy) {
if (policy === 'strict') {
const decision = raw.rawDecision === 'allow' ? 'allow' : 'block';
return { decision, flagged: decision !== 'allow', reason: raw.reason };
}
if (policy === 'datacenter') {
if (raw.rawDecision === 'block' && isDatacenter(signal.type)) {
return { decision: 'block', flagged: true, reason: raw.reason };
}
return {
decision: 'allow',
flagged: raw.rawFlagged || raw.rawDecision !== 'allow',
reason: raw.reason,
};
}
return {
decision: 'allow',
flagged: raw.rawFlagged || raw.rawDecision !== 'allow',
reason: raw.reason,
};
}
function baseVerdict(reason, source) {
return {
decision: 'allow',
flagged: false,
reason,
type: 'Unknown',
risk: 0,
provider: '',
asn: '',
country: '',
proxy: false,
source,
};
}
function verdictFromSignal(signal, config, source) {
const raw = classify(signal, config);
const policied = applyPolicy(raw, signal, config.policy);
return {
decision: policied.decision,
flagged: policied.flagged,
reason: policied.reason,
type: signal.type,
risk: signal.risk,
provider: signal.provider,
asn: signal.asn,
country: signal.country,
proxy: signal.proxy,
source,
};
}
function evictOldest(metrics) {
const oldestKey = cache.keys().next().value;
if (oldestKey === undefined) return false;
cache.delete(oldestKey);
incrementMetric(metrics, 'ip_reputation_cache_eviction');
return true;
}
function trimCache(maxEntries, metrics) {
while (cache.size > maxEntries) evictOldest(metrics);
updateSizeGauges(metrics);
}
function getCachedSignal(ip, config, now) {
const entry = cache.get(ip);
if (!entry) return null;
// A caller may lower the TTL after this entry was created. Honour the
// current setting as well as the creator's expiry.
const effectiveExpiry = Math.min(entry.expires, entry.createdAt + config.cacheTtlMs);
if (effectiveExpiry <= now) {
cache.delete(ip);
incrementMetric(config.metrics, 'ip_reputation_cache_expired');
updateSizeGauges(config.metrics);
return null;
}
// Map insertion order doubles as a bounded LRU approximation.
cache.delete(ip);
cache.set(ip, entry);
incrementMetric(config.metrics, 'ip_reputation_cache_hit');
return entry.signal;
}
function storeSignal(ip, signal, config) {
if (cache.has(ip)) cache.delete(ip);
while (cache.size >= config.cacheMaxEntries) evictOldest(config.metrics);
const createdAt = config.nowFn();
cache.set(ip, {
signal,
createdAt,
expires: createdAt + config.cacheTtlMs,
});
updateSizeGauges(config.metrics);
}
function canonicalIp(ip) {
if (typeof ip !== 'string') return null;
const candidate = ip.trim();
if (!candidate || !ipaddr.isValid(candidate)) return null;
return normalizeIpString(candidate);
}
async function evaluateIp(ip, cfg = {}) {
const config = normalizeConfig(cfg);
const normalizedIp = canonicalIp(ip);
if (!normalizedIp) return baseVerdict(ip ? 'invalid-ip' : 'no-ip', 'invalid');
if (isPrivateOrLoopback(normalizedIp)) {
return {
...baseVerdict('local-network', 'local'),
type: 'Local',
country: 'Local',
};
}
if (!config.enabled) return baseVerdict('ip-check-disabled', 'disabled');
trimCache(config.cacheMaxEntries, config.metrics);
const cachedSignal = getCachedSignal(normalizedIp, config, config.nowFn());
if (cachedSignal) return verdictFromSignal(cachedSignal, config, 'cache');
incrementMetric(config.metrics, 'ip_reputation_cache_miss');
let pending = inFlight.get(normalizedIp);
let source = 'coalesced';
if (pending) {
incrementMetric(config.metrics, 'ip_reputation_inflight_join');
} else {
if (inFlight.size >= config.maxInflight || inFlight.size >= HARD_LIMITS.maxInflight) {
incrementMetric(config.metrics, 'ip_reputation_capacity_failopen');
updateSizeGauges(config.metrics);
return baseVerdict('ipcheck-capacity', 'capacity');
}
source = 'proxycheck';
incrementMetric(config.metrics, 'ip_reputation_upstream_request');
pending = queryProxycheck(normalizedIp, config)
.then(signal => {
storeSignal(normalizedIp, signal, config);
return signal;
})
.finally(() => {
if (inFlight.get(normalizedIp) === pending) inFlight.delete(normalizedIp);
updateSizeGauges(config.metrics);
});
inFlight.set(normalizedIp, pending);
updateSizeGauges(config.metrics);
}
try {
const signal = await pending;
return verdictFromSignal(signal, config, source);
} catch (error) {
incrementMetric(config.metrics, 'ip_reputation_failopen');
const detail = boundedText(error?.message || 'upstream-failure', 160);
return baseVerdict(`ipcheck-failopen: ${detail}`, 'failopen');
}
}
function clearCache(metrics) {
cache.clear();
updateSizeGauges(metrics);
}
function sweepCache(options = {}) {
const opts = typeof options === 'number' ? { now: options } : (options || {});
const now = Number.isFinite(Number(opts.now)) ? Number(opts.now) : Date.now();
let removed = 0;
for (const [key, entry] of cache) {
if (entry.expires <= now) {
cache.delete(key);
removed += 1;
}
}
if (removed) incrementMetric(opts.metrics, 'ip_reputation_cache_swept', removed);
updateSizeGauges(opts.metrics);
return removed;
}
function stopCacheSweeper() {
if (sweeperTimer === null) return false;
sweeperClearInterval(sweeperTimer);
sweeperTimer = null;
setGauge(sweeperMetrics, 'ip_reputation_sweeper_running', 0);
sweeperMetrics = null;
sweeperClearInterval = clearInterval;
return true;
}
function startCacheSweeper(value = {}) {
const opts = typeof value === 'number' ? { intervalMs: value } : (value || {});
stopCacheSweeper();
const intervalMs = clampInteger(
opts.intervalMs,
DEFAULTS.sweeperIntervalMs,
HARD_LIMITS.sweeperIntervalMinMs,
HARD_LIMITS.sweeperIntervalMaxMs,
);
const setIntervalFn = typeof opts.setIntervalFn === 'function' ? opts.setIntervalFn : setInterval;
sweeperClearInterval = typeof opts.clearIntervalFn === 'function' ? opts.clearIntervalFn : clearInterval;
sweeperMetrics = opts.metrics;
sweeperTimer = setIntervalFn(() => sweepCache({ metrics: opts.metrics }), intervalMs);
sweeperTimer?.unref?.();
updateSizeGauges(opts.metrics);
setGauge(opts.metrics, 'ip_reputation_sweeper_running', 1);
return sweeperTimer;
}
function getReputationMetrics() {
return {
cacheSize: cache.size,
inFlightSize: inFlight.size,
sweeperRunning: sweeperTimer !== null,
counters: Object.fromEntries(counters),
};
}
module.exports = {
evaluateIp,
clearCache,
sweepCache,
startCacheSweeper,
stopCacheSweeper,
getReputationMetrics,
normalizeConfig,
DEFAULTS,
HARD_LIMITS,
};