Skip to content

Commit 8828749

Browse files
committed
Add annoyance-level-warning.user.js
1 parent f0f65c9 commit 8828749

File tree

1 file changed

+237
-0
lines changed

1 file changed

+237
-0
lines changed

annoyance-level-warning.user.js

Lines changed: 237 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,237 @@
1+
// ==UserScript==
2+
// @name Cross off the links with CAPTCHA/PoW annoyance
3+
// @description Helps to prefer visiting sites that aren't associated with the irrational businesses that keep "fighting" the spammy traffic by disrupting the UX with cringe challenges (rather than transforming the traffic into useful (UPoW) and profitable computations) as well as sites with PoW-based DDoS-protection pages (useless anti-ecological computations).
4+
// @version 0.1
5+
// @downloadURL https://userscripts.codonaft.com/annoyance-level-warning.user.js
6+
// @grant GM.getValue
7+
// @grant GM.xmlHttpRequest
8+
// @grant GM_addStyle
9+
// @grant GM_setValue
10+
// ==/UserScript==
11+
12+
(async _ => {
13+
'use strict';
14+
15+
const RECHECK_DURATION_SECS = 7 * 24 * 60 * 60;
16+
const QUEUE_LIMIT = 32;
17+
const RECORD_KEY = '__annoyance_level_warning';
18+
19+
const LEVEL_UNKNOWN = 'unknown';
20+
const LEVEL_OK = 'ok';
21+
const LEVEL_POW = 'pow';
22+
const LEVEL_MAYBE_CAPTCHA = 'maybe_captcha';
23+
const LEVEL_CAPTCHA = 'captcha';
24+
25+
const NUMBER_TO_LEVEL = [LEVEL_UNKNOWN, LEVEL_OK, LEVEL_POW, LEVEL_MAYBE_CAPTCHA, LEVEL_CAPTCHA];
26+
const LEVEL_TO_NUMBER = Object.fromEntries(NUMBER_TO_LEVEL.entries().map(xs => xs.reverse()));
27+
28+
const STRIKE_COLOR = '#828282';
29+
GM_addStyle(`
30+
.${RECORD_KEY} {
31+
text-decoration-thickness: 0.1px !important;
32+
}
33+
.${RECORD_KEY}:hover {
34+
opacity: 1 !important;
35+
text-decoration: none !important;
36+
}
37+
.${RECORD_KEY}_${LEVEL_POW} {
38+
opacity: 0.7 !important;
39+
text-decoration: line-through ${STRIKE_COLOR} dashed !important;
40+
}
41+
.${RECORD_KEY}_${LEVEL_MAYBE_CAPTCHA} {
42+
opacity: 0.4 !important;
43+
text-decoration: line-through ${STRIKE_COLOR} !important;
44+
}
45+
.${RECORD_KEY}_${LEVEL_CAPTCHA} {
46+
opacity: 0.2 !important;
47+
text-decoration: line-through ${STRIKE_COLOR} double !important;
48+
`);
49+
50+
// TODO: hover
51+
52+
const currentTime = _ => Math.round(Date.now() / 1000);
53+
const now = currentTime();
54+
55+
const b = document.body;
56+
const records = await GM.getValue(RECORD_KEY, {});
57+
console.log('annoyance records', records);
58+
59+
const newRecord = (level, updated = now) => { return { level: LEVEL_TO_NUMBER[level], updated }; };
60+
const setRecord = (hostname, level) => {
61+
console.log(`setRecord ${hostname} ${level}`);
62+
records[hostname] = newRecord(level);
63+
GM_setValue(RECORD_KEY, records);
64+
};
65+
const removeRecord = hostname => {
66+
if (!records[hostname]) return;
67+
delete records[hostname];
68+
GM_setValue(RECORD_KEY, records);
69+
};
70+
const getRecord = hostname => (records[hostname] || newRecord(LEVEL_UNKNOWN, 0));
71+
const isUnknown = record => NUMBER_TO_LEVEL[record.level] === LEVEL_UNKNOWN;
72+
const setThisHostname = level => setRecord(window.location.hostname, level);
73+
74+
const err = (e, data) => {
75+
console.log(data);
76+
console.error(e);
77+
};
78+
79+
const setWarning = (node, level) => {
80+
if ([LEVEL_UNKNOWN, LEVEL_OK].includes(level)) return;
81+
node.classList.add(RECORD_KEY);
82+
node.classList.add(`${RECORD_KEY}_${level}`);
83+
84+
const warning = level.replaceAll('_', ' ');
85+
node.title = node.title?.length > 0 ? `(${warning}) ${node.title}` : warning; // TODO: css?
86+
};
87+
88+
const isIPv4 = s => s.split('.').length === 4 && s.split('.').every(n => n >= 0 && n <= 255 && n === String(Number(n)));
89+
const isIPv6 = s => s.split(':').every(h => h.length === 0 || /^[0-9a-fA-F]{1,4}$/.test(h));
90+
const isIP = s => s.includes('.') ? isIPv4(s) : isIPv6(s);
91+
92+
const enqueuedChecks = new Set;
93+
const check = async hostname => {
94+
try {
95+
if (enqueuedChecks.size >= QUEUE_LIMIT || enqueuedChecks.has(hostname) || hostname.trim().length === 0) return;
96+
enqueuedChecks.add(hostname);
97+
const record = getRecord(hostname)
98+
99+
const wasUnknown = isUnknown(record);
100+
if (now <= record.updated + RECHECK_DURATION_SECS) return;
101+
console.log(`check ${hostname}`);
102+
103+
const rawDnsResponse = await GM.xmlHttpRequest({ url: `https://dns.google/resolve?name=${hostname}` });
104+
if (rawDnsResponse?.status !== 200) {
105+
throw `unexpected dns response, hostname=${hostname}`;
106+
}
107+
const dnsResponse = JSON.parse(rawDnsResponse.responseText);
108+
if (dnsResponse?.Status !== 0) {
109+
throw `dns failure, hostname=${hostname}`;
110+
}
111+
const ip = dnsResponse?.Answer?.find(i => i?.data && isIP(i.data))?.data;
112+
if (!ip) {
113+
throw `dns resolve failure hostname=${hostname}`;
114+
}
115+
116+
const rawCompanyResponse = await GM.xmlHttpRequest({ url: `https://api.ipapi.is/?q=${ip}` });
117+
if (rawCompanyResponse?.status !== 200) {
118+
throw `unexpected company response, hostname=${hostname}`;
119+
}
120+
const companyResponse = JSON.parse(rawCompanyResponse.responseText);
121+
const company = companyResponse?.company?.name;
122+
if (!company) {
123+
throw `company failure, ip=${ip}, hostname=${hostname}`;
124+
}
125+
126+
if (company === 'Cloudflare, Inc.') {
127+
if (record.level < LEVEL_TO_NUMBER[LEVEL_MAYBE_CAPTCHA]) {
128+
setRecord(hostname, LEVEL_MAYBE_CAPTCHA);
129+
b.querySelectorAll(`a[href^="http://${hostname}/"], a[href^="https://${hostname}/"]`).forEach(i => setWarning(i, LEVEL_MAYBE_CAPTCHA));
130+
}
131+
} else if (wasUnknown) {
132+
setRecord(hostname, LEVEL_OK);
133+
}
134+
} catch (e) {
135+
removeRecord(hostname);
136+
err(e, hostname);
137+
}
138+
};
139+
140+
const subscribeOnChanges = (node, selector, f) => {
141+
const apply = (node, observer) => {
142+
if (node?.nodeType !== 1) return;
143+
144+
let observeChildren = true;
145+
if (node?.matches?.(selector)) {
146+
try {
147+
observeChildren = f(node, observer);
148+
} catch (e) {
149+
err(e, node);
150+
if (e.name === 'SecurityError') {
151+
observer.disconnect();
152+
return;
153+
}
154+
}
155+
}
156+
157+
if (observeChildren) {
158+
const children = node?.childNodes || [];
159+
children.forEach(i => apply(i, observer));
160+
}
161+
};
162+
163+
const observer = new MutationObserver(mutations => mutations.forEach(m => m.addedNodes.forEach(i => apply(i, observer))));
164+
observer.observe(node, { childList: true, subtree: true });
165+
node.querySelectorAll(selector).forEach(i => apply(i, observer));
166+
};
167+
168+
subscribeOnChanges(document.head, 'title', (node, observer) => {
169+
if (node.textContent !== 'DDOS-GUARD' && !node.textContent.includes("Making sure you're not a bot")) return;
170+
observer.disconnect();
171+
console.warn('anti-ddos detected');
172+
setThisHostname(LEVEL_POW);
173+
return false;
174+
});
175+
176+
const CLOUDFLARE_SCRIPT = 'script[src^="https://challenges.cloudflare.com/"]';
177+
subscribeOnChanges(document, CLOUDFLARE_SCRIPT, (_, observer) => {
178+
observer.disconnect();
179+
console.warn('captcha possible');
180+
setThisHostname(LEVEL_MAYBE_CAPTCHA);
181+
return false;
182+
});
183+
184+
subscribeOnChanges(b, 'iframe[src^="https://newassets.hcaptcha.com/"], iframe[title="reCAPTCHA"], iframe[src^="https://client-api.arkoselabs.com/"], iframe[src^="https://geo.captcha-delivery.com/"], iframe[src^="https://global.frcapi.com/"], div#captcha div[aria-label="Click to verify"], button#TencentCaptcha', (_, observer) => {
185+
observer.disconnect();
186+
console.warn('captcha detected');
187+
setThisHostname(LEVEL_CAPTCHA);
188+
return false;
189+
});
190+
191+
subscribeOnChanges(b, 'p[class="h2"]', (node, observer) => {
192+
if (['Verify you are human', 'Verifying you are human'].find(i => node.textContent.includes(i)) && document.querySelector(CLOUDFLARE_SCRIPT)) {
193+
observer.disconnect();
194+
console.warn('captcha started');
195+
setThisHostname(LEVEL_CAPTCHA);
196+
}
197+
return false;
198+
});
199+
200+
subscribeOnChanges(b, 'a[href]', node => {
201+
if (!node.href) return;
202+
const url = new URL(node.href);
203+
const hostname = url.hostname;
204+
const record = getRecord(hostname);
205+
if (hostname !== window.location.hostname) {
206+
setWarning(node, NUMBER_TO_LEVEL[record.level]);
207+
}
208+
check(hostname);
209+
return true;
210+
});
211+
212+
setTimeout(_ => {
213+
const hostname = window.location.hostname;
214+
const result = getRecord(hostname);
215+
if (now > result.updated + RECHECK_DURATION_SECS && (enqueuedChecks.size < QUEUE_LIMIT || !enqueuedChecks.has(hostname))) {
216+
console.log('perhaps there is no captcha or pow');
217+
setThisHostname(LEVEL_OK);
218+
}
219+
}, 5 * 60 * 1000);
220+
221+
const checkUnknown = _ => Object
222+
.entries(records)
223+
.forEach(([hostname, record]) => {
224+
if (isUnknown(record)) {
225+
check(hostname)
226+
}
227+
});
228+
229+
checkUnknown();
230+
231+
window.addEventListener('pageshow', event => {
232+
if (!event.persisted) return;
233+
console.log('back button is probably pressed');
234+
enqueuedChecks.clear();
235+
checkUnknown();
236+
});
237+
})();

0 commit comments

Comments
 (0)