-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
315 lines (270 loc) · 11.5 KB
/
Copy pathscript.js
File metadata and controls
315 lines (270 loc) · 11.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
/* ==========================================================================
THREAT REGISTRY DASHBOARD CONTROLLER (script.js)
--------------------------------------------------------------------------
Manages client-side database lookup (with subdomain matching), statistics
parsing, dynamic lists, tab controls, and clipboard copy operations.
========================================================================== */
let blacklistData = null;
let globalStats = null;
document.addEventListener("DOMContentLoaded", () => {
initDashboard();
setupTabs();
});
// Fetch stats.json compiled by pipeline
function initDashboard() {
fetch("stats.json")
.then(response => {
if (!response.ok) throw new Error("Stats not available");
return response.json();
})
.then(data => {
globalStats = data;
renderAnalytics(data);
})
.catch(err => {
console.error("Error loading registry stats:", err);
const stamp = document.getElementById("update-timestamp");
if (stamp) stamp.innerText = "Error loading stats database.";
});
}
// Render dynamic elements
function renderAnalytics(stats) {
// Update timestamp
const date = new Date(stats.last_updated);
const timeStr = date.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const updateEl = document.getElementById("update-timestamp");
if (updateEl) {
updateEl.innerText = `Updated: ${timeStr} (${timezone})`;
}
// Counters (with simple countUp transition effect)
animateCounter("stat-total", stats.total_domains);
animateCounter("stat-categories", Object.keys(stats.categories).length);
animateCounter("stat-feeds", stats.feeds.length);
// Categories Grid Cards
const categoryContainer = document.getElementById("categories-container");
if (categoryContainer) {
categoryContainer.innerHTML = "";
Object.entries(stats.categories).forEach(([name, count]) => {
const card = document.createElement("div");
card.className = "card card--category";
card.innerHTML = `
<div class="category-header">
<span class="category-title">${name}</span>
<span class="category-count">${count.toLocaleString()}</span>
</div>
<div class="category-download-actions">
<a href="categories/${name}.txt" class="btn btn-secondary btn-sm" download>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
<span>List</span>
</a>
<button class="btn btn-secondary btn-sm" onclick="copyText('categories/${name}.txt')">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path></svg>
<span>Copy URL</span>
</button>
</div>
`;
categoryContainer.appendChild(card);
});
}
// Upstream Feed Status Table
const tableBody = document.getElementById("feeds-table-body");
if (tableBody) {
tableBody.innerHTML = "";
// Sort feeds by success status then name
const sortedFeeds = [...stats.feeds].sort((a, b) => {
if (a.success === b.success) return a.name.localeCompare(b.name);
return a.success ? -1 : 1;
});
sortedFeeds.forEach(feed => {
const row = document.createElement("tr");
const statusBadge = feed.success
? `<span class="badge-status status-online"><span class="badge-status-dot"></span>Active</span>`
: `<span class="badge-status status-offline" title="${feed.error || 'Unknown Connection Failure'}"><span class="badge-status-dot"></span>Offline</span>`;
row.innerHTML = `
<td class="table-primary">${feed.name}</td>
<td class="table-secondary">${feed.category}</td>
<td>${statusBadge}</td>
<td class="table-mono-right">${feed.count.toLocaleString()}</td>
`;
tableBody.appendChild(row);
});
}
}
// Animate Counters
function animateCounter(id, target) {
const el = document.getElementById(id);
if (!el) return;
let start = 0;
const duration = 1000;
const stepTime = Math.abs(Math.floor(duration / target));
// Cap stepTime so it runs smoothly
const increment = Math.ceil(target / 40);
const timer = setInterval(() => {
start += increment;
if (start >= target) {
el.innerText = target.toLocaleString();
clearInterval(timer);
} else {
el.innerText = start.toLocaleString();
}
}, 20);
}
// Setup Tab Controls
function setupTabs() {
const tabs = document.querySelectorAll(".tab-btn");
const views = document.querySelectorAll(".tab-view");
tabs.forEach(tab => {
tab.addEventListener("click", () => {
const targetView = tab.getAttribute("data-tab");
tabs.forEach(t => t.classList.remove("active"));
views.forEach(v => v.classList.remove("active"));
tab.classList.add("active");
const activeView = document.getElementById(`view-${targetView}`);
if (activeView) activeView.classList.add("active");
});
});
}
// Check domain (with Wildcard Subdomain matching using sharded lookup database)
async function checkDomain() {
const queryInput = document.getElementById("domain-query");
const searchResult = document.getElementById("search-result");
if (!queryInput || !searchResult) return;
let query = queryInput.value.trim().toLowerCase();
if (!query) {
searchResult.style.display = "none";
return;
}
// Parse URLs
try {
if (query.includes("://") || query.startsWith("www.")) {
let temp = query;
if (!temp.includes("://")) temp = "http://" + temp;
query = new URL(temp).hostname;
}
} catch(e) {}
query = query.replace(/^www\./, "");
// Show loading indicator
searchResult.style.display = "block";
searchResult.className = "search-result loading";
searchResult.innerHTML = `
<span class="spinner"></span>
<span>Checking security registry database...</span>
`;
// Helper to fetch shard and check domain
async function lookupInShard(domain) {
try {
// 1. Compute SHA-256 hex string of domain in Javascript
const msgBuffer = new TextEncoder().encode(domain);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
// First 2 hex characters determine the shard file
const shardPrefix = hashHex.substring(0, 2);
// Fetch the specific shard file (only ~50KB)
const response = await fetch(`lookup/${shardPrefix}.json`);
if (!response.ok) {
// If file doesn't exist, domain is not blocked
if (response.status === 404) return null;
throw new Error(`Failed to load lookup shard ${shardPrefix}`);
}
const shardData = await response.json();
return shardData[domain] || null;
} catch (err) {
console.error("Lookup error:", err);
return null;
}
}
// 1. Direct Match Check
const directCategories = await lookupInShard(query);
if (directCategories) {
renderMatchResult(query, directCategories);
return;
}
// 2. Wildcard Parent Domain Check (e.g. sub.badsite.com -> badsite.com)
const parts = query.split('.');
for (let i = 1; i < parts.length; i++) {
const parent = parts.slice(i).join('.');
const parentCategories = await lookupInShard(parent);
if (parentCategories) {
renderMatchResult(query, parentCategories, parent);
return;
}
}
// Safe result
searchResult.className = "search-result result-safe";
searchResult.innerHTML = `
<div class="result-row">
<svg class="check-icon" xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>
<div>
<strong>Domain is Safe:</strong> "${query}" is not found in active blacklist registries.
</div>
</div>
`;
}
// Render blocked results
function renderMatchResult(queriedDomain, categories, blockedParent = null) {
const searchResult = document.getElementById("search-result");
const categoryBadges = categories.map(cat => `<span class="threat-badge">${cat.toUpperCase()}</span>`).join(" ");
let matchedMessage = `Blocked under: ${categoryBadges}`;
if (blockedParent) {
matchedMessage = `Blocked by wildcard parent domain: <strong>${blockedParent}</strong><br><div class="result-meta">Categories: ${categoryBadges}</div>`;
}
searchResult.className = "search-result result-blocked";
searchResult.innerHTML = `
<div class="result-row result-row--top">
<svg class="alert-icon" xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path><line x1="12" y1="9" x2="12" y2="13"></line><line x1="12" y1="17" x2="12.01" y2="17"></line></svg>
<div>
<strong>⚠️ Security Threat Blocked:</strong> "${queriedDomain}" is blacklisted.
<div class="result-meta">${matchedMessage}</div>
</div>
</div>
`;
}
// Clipboard Copy Helper
function copyText(subpath) {
const absoluteUrl = window.location.origin + window.location.pathname.replace("index.html", "") + subpath;
navigator.clipboard.writeText(absoluteUrl).then(() => {
const btn = event.currentTarget;
const originalContent = btn.innerHTML;
btn.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>
<span>Copied!</span>
`;
btn.classList.add("copy-success");
setTimeout(() => {
btn.innerHTML = originalContent;
btn.classList.remove("copy-success");
}, 1500);
}).catch(err => {
console.error("Could not copy URL:", err);
});
}
// Disclaimer Modal Controller
function openDisclaimer() {
const modal = document.getElementById("disclaimer-modal");
if (modal) {
modal.classList.add("active");
modal.setAttribute("aria-hidden", "false");
// Add event listeners to close elements
const closeElements = modal.querySelectorAll(".modal-close-btn, .modal-overlay, .modal-close-btn-action");
closeElements.forEach(el => {
el.addEventListener("click", closeDisclaimer);
});
// Close on Escape key press
document.addEventListener("keydown", handleEscapeKey);
}
}
function closeDisclaimer() {
const modal = document.getElementById("disclaimer-modal");
if (modal) {
modal.classList.remove("active");
modal.setAttribute("aria-hidden", "true");
document.removeEventListener("keydown", handleEscapeKey);
}
}
function handleEscapeKey(e) {
if (e.key === "Escape") {
closeDisclaimer();
}
}