Skip to content

Commit

Permalink
Further debloating and commenting for the ghetto blacklist.
Browse files Browse the repository at this point in the history
  • Loading branch information
00Fjongl committed Jul 25, 2024
1 parent e19dc1d commit a5b5f18
Showing 1 changed file with 33 additions and 13 deletions.
46 changes: 33 additions & 13 deletions views/uv/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,30 +32,50 @@ ww.use({
const uv = new UVServiceWorker();

// Get list of blacklisted domains.
let blacklist;
const blacklist = {};
fetch("/assets/json/blacklist.json").then(request => {
request.json().then(jsonData => {
blacklist = new RegExp(jsonData.map(
domain =>
encodeURIComponent(domain)

// Organize each domain by their tld (top level domain) ending.
jsonData.forEach(domain => {
const domainTld = domain.replace(/.+(?=\.\w)/, "");
if (!blacklist.hasOwnProperty(domainTld))
blacklist[domainTld] = [];

// Store each entry in an array. Each tld has its own array, which will
// later be concatenated into a regular expression.
blacklist[domainTld].push(
encodeURIComponent(domain.slice(0, -domainTld.length))
.replace(/([()])/g, "\\$1")
.replaceAll("*.", "(?:.+\\.)?")
.replaceAll(".", "\\.")
).join("|"));
.replace(/(\*\.)|\./g, (match, firstExpression) =>
firstExpression ? "(?:.+\\.)?" : "\\" + match)
);
});

// Turn each domain list into a regular expression and prevent this
// from being accidentally modified afterward.
for (let [domainTld, domainList] of Object.entries(blacklist))
blacklist[domainTld] = new RegExp(`^(?:${domainList.join("|")})$`);
Object.freeze(blacklist);
});
});

self.addEventListener("fetch", (event) => {
event.respondWith(
(async () => {
if (uv.route(event)) {
// The one and only ghetto domain blacklist.
if (!new URL(event.request.url).pathname.indexOf("/uv/service/")) {
const url = new URL(uv.config.decodeUrl(new URL(event.request.url).pathname.replace(/^\/uv\/service\//, "")));
if (blacklist.test(url.hostname))
return new Response(new Blob(), {status: 406});
}
const domain = new URL(uv.config.decodeUrl(
new URL(event.request.url).pathname
.replace(uv.config.prefix, "")
)).hostname,
domainTld = domain.replace(/.+(?=\.\w)/, "");

// If the domain is in the blacklist, return a 406 response code.
if (blacklist.hasOwnProperty(domainTld) &&
blacklist[domainTld].test(domain.slice(0, -domainTld.length))
) return new Response(new Blob(), {status: 406});

if (uv.route(event)) {
return await uv.fetch(event);
}
return await fetch(event.request);
Expand Down

0 comments on commit a5b5f18

Please sign in to comment.