@rasyid2567/urlscanner 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +122 -2
- package/dist/cli.js +3612 -0
- package/dist/web/assets/index-B-RXOJoS.js +211 -0
- package/dist/web/assets/index-DtDzeyWK.css +1 -0
- package/dist/web/index.html +24 -0
- package/package.json +71 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,3612 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { spawn as spawn2 } from "child_process";
|
|
5
|
+
import fs4 from "fs";
|
|
6
|
+
import os2 from "os";
|
|
7
|
+
import path4 from "path";
|
|
8
|
+
import { parseArgs } from "util";
|
|
9
|
+
|
|
10
|
+
// src/config.ts
|
|
11
|
+
var APP_VERSION = "1.0.0";
|
|
12
|
+
var DEFAULT_PORT = 3847;
|
|
13
|
+
var DEFAULT_HOST = "127.0.0.1";
|
|
14
|
+
var CHROME_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36";
|
|
15
|
+
var ASSET_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
16
|
+
".css",
|
|
17
|
+
".js",
|
|
18
|
+
".mjs",
|
|
19
|
+
".cjs",
|
|
20
|
+
".png",
|
|
21
|
+
".jpg",
|
|
22
|
+
".jpeg",
|
|
23
|
+
".gif",
|
|
24
|
+
".webp",
|
|
25
|
+
".svg",
|
|
26
|
+
".ico",
|
|
27
|
+
".woff",
|
|
28
|
+
".woff2",
|
|
29
|
+
".ttf",
|
|
30
|
+
".eot",
|
|
31
|
+
".otf",
|
|
32
|
+
".mp4",
|
|
33
|
+
".webm",
|
|
34
|
+
".mp3",
|
|
35
|
+
".wav",
|
|
36
|
+
".ogg",
|
|
37
|
+
".pdf",
|
|
38
|
+
".zip",
|
|
39
|
+
".rar",
|
|
40
|
+
".tar",
|
|
41
|
+
".gz",
|
|
42
|
+
".xml",
|
|
43
|
+
".json",
|
|
44
|
+
".map",
|
|
45
|
+
".avif",
|
|
46
|
+
".bmp",
|
|
47
|
+
".txt"
|
|
48
|
+
]);
|
|
49
|
+
var DEFAULT_KEYWORDS = [
|
|
50
|
+
{ term: "slot gacor", category: "slot", weight: 32 },
|
|
51
|
+
{ term: "maxwin", category: "slot", weight: 28 },
|
|
52
|
+
{ term: "rtp live", category: "slot", weight: 30 },
|
|
53
|
+
{ term: "rtp slot", category: "slot", weight: 30 },
|
|
54
|
+
{ term: "bocoran rtp", category: "slot", weight: 28 },
|
|
55
|
+
{ term: "situs slot", category: "slot", weight: 28 },
|
|
56
|
+
{ term: "judi online", category: "generic", weight: 35 },
|
|
57
|
+
{ term: "judi slot", category: "slot", weight: 32 },
|
|
58
|
+
{ term: "slot88", category: "slot", weight: 26 },
|
|
59
|
+
{ term: "slot online", category: "slot", weight: 26 },
|
|
60
|
+
{ term: "togel online", category: "togel", weight: 32 },
|
|
61
|
+
{ term: "bandar togel", category: "togel", weight: 32 },
|
|
62
|
+
{ term: "situs togel", category: "togel", weight: 30 },
|
|
63
|
+
{ term: "toto macau", category: "togel", weight: 26 },
|
|
64
|
+
{ term: "hk pools", category: "togel", weight: 22 },
|
|
65
|
+
{ term: "sgp pools", category: "togel", weight: 22 },
|
|
66
|
+
{ term: "sdy pools", category: "togel", weight: 22 },
|
|
67
|
+
{ term: "pragmatic play", category: "slot", weight: 22 },
|
|
68
|
+
{ term: "pg soft", category: "slot", weight: 20 },
|
|
69
|
+
{ term: "gates of olympus", category: "slot", weight: 24 },
|
|
70
|
+
{ term: "starlight princess", category: "slot", weight: 24 },
|
|
71
|
+
{ term: "mahjong ways", category: "slot", weight: 24 },
|
|
72
|
+
{ term: "spaceman", category: "slot", weight: 16 },
|
|
73
|
+
{ term: "scatter hitam", category: "slot", weight: 24 },
|
|
74
|
+
{ term: "sbobet", category: "bola", weight: 28 },
|
|
75
|
+
{ term: "mix parlay", category: "bola", weight: 24 },
|
|
76
|
+
{ term: "taruhan bola", category: "bola", weight: 26 },
|
|
77
|
+
{ term: "judi bola", category: "bola", weight: 30 },
|
|
78
|
+
{ term: "sabung ayam", category: "casino", weight: 28 },
|
|
79
|
+
{ term: "sv388", category: "casino", weight: 28 },
|
|
80
|
+
{ term: "live casino", category: "casino", weight: 22 },
|
|
81
|
+
{ term: "idn poker", category: "casino", weight: 26 },
|
|
82
|
+
{ term: "nexus engine", category: "slot", weight: 22 },
|
|
83
|
+
{ term: "slot depo", category: "slot", weight: 25 },
|
|
84
|
+
{ term: "depo 10k", category: "generic", weight: 20 },
|
|
85
|
+
{ term: "depo 5k", category: "generic", weight: 20 },
|
|
86
|
+
{ term: "qris slot", category: "slot", weight: 26 },
|
|
87
|
+
{ term: "deposit pulsa tanpa potongan", category: "generic", weight: 24 },
|
|
88
|
+
{ term: "link alternatif", category: "amp", weight: 14 },
|
|
89
|
+
{ term: "daftar slot", category: "slot", weight: 22 },
|
|
90
|
+
{ term: "login slot", category: "slot", weight: 22 },
|
|
91
|
+
{ term: "bonus new member", category: "generic", weight: 16 },
|
|
92
|
+
{ term: "freespin", category: "slot", weight: 14 },
|
|
93
|
+
{ term: "jackpot", category: "generic", weight: 12 },
|
|
94
|
+
{ term: "withdraw", category: "generic", weight: 10 }
|
|
95
|
+
];
|
|
96
|
+
var DEFAULT_BLACKLIST_DOMAINS = [
|
|
97
|
+
// Web standards & schemas
|
|
98
|
+
{ domain: "w3.org", reason: "standard" },
|
|
99
|
+
{ domain: "schema.org", reason: "standard" },
|
|
100
|
+
{ domain: "xmlns.com", reason: "standard" },
|
|
101
|
+
{ domain: "purl.org", reason: "standard" },
|
|
102
|
+
{ domain: "ogp.me", reason: "standard" },
|
|
103
|
+
// Google / CDN / Fonts / Analytics
|
|
104
|
+
{ domain: "google.com", reason: "cdn" },
|
|
105
|
+
{ domain: "google.co.id", reason: "search" },
|
|
106
|
+
{ domain: "googleapis.com", reason: "cdn" },
|
|
107
|
+
{ domain: "gstatic.com", reason: "cdn" },
|
|
108
|
+
{ domain: "googletagmanager.com", reason: "analytics" },
|
|
109
|
+
{ domain: "google-analytics.com", reason: "analytics" },
|
|
110
|
+
{ domain: "googlesyndication.com", reason: "ads" },
|
|
111
|
+
{ domain: "doubleclick.net", reason: "ads" },
|
|
112
|
+
{ domain: "ampproject.org", reason: "cdn" },
|
|
113
|
+
{ domain: "cloudflare.com", reason: "cdn" },
|
|
114
|
+
{ domain: "cloudflareinsights.com", reason: "analytics" },
|
|
115
|
+
{ domain: "jsdelivr.net", reason: "cdn" },
|
|
116
|
+
{ domain: "unpkg.com", reason: "cdn" },
|
|
117
|
+
{ domain: "jquery.com", reason: "cdn" },
|
|
118
|
+
{ domain: "bootstrapcdn.com", reason: "cdn" },
|
|
119
|
+
{ domain: "fontawesome.com", reason: "cdn" },
|
|
120
|
+
{ domain: "gravatar.com", reason: "cdn" },
|
|
121
|
+
{ domain: "wp.com", reason: "platform" },
|
|
122
|
+
{ domain: "wordpress.org", reason: "platform" },
|
|
123
|
+
{ domain: "w.org", reason: "standard" },
|
|
124
|
+
{ domain: "typekit.net", reason: "cdn" },
|
|
125
|
+
// Social Media & Messaging
|
|
126
|
+
{ domain: "facebook.com", reason: "social" },
|
|
127
|
+
{ domain: "fb.com", reason: "social" },
|
|
128
|
+
{ domain: "fbcdn.net", reason: "cdn" },
|
|
129
|
+
{ domain: "instagram.com", reason: "social" },
|
|
130
|
+
{ domain: "twitter.com", reason: "social" },
|
|
131
|
+
{ domain: "x.com", reason: "social" },
|
|
132
|
+
{ domain: "t.co", reason: "social" },
|
|
133
|
+
{ domain: "tiktok.com", reason: "social" },
|
|
134
|
+
{ domain: "youtube.com", reason: "social" },
|
|
135
|
+
{ domain: "youtu.be", reason: "social" },
|
|
136
|
+
{ domain: "linkedin.com", reason: "social" },
|
|
137
|
+
{ domain: "pinterest.com", reason: "social" },
|
|
138
|
+
{ domain: "reddit.com", reason: "social" },
|
|
139
|
+
{ domain: "whatsapp.com", reason: "messaging" },
|
|
140
|
+
{ domain: "wa.me", reason: "messaging" },
|
|
141
|
+
{ domain: "t.me", reason: "messaging" },
|
|
142
|
+
{ domain: "telegram.org", reason: "messaging" },
|
|
143
|
+
{ domain: "telegram.me", reason: "messaging" },
|
|
144
|
+
{ domain: "line.me", reason: "messaging" },
|
|
145
|
+
{ domain: "discord.com", reason: "messaging" },
|
|
146
|
+
{ domain: "discord.gg", reason: "messaging" },
|
|
147
|
+
// Livechat & Support Widgets
|
|
148
|
+
{ domain: "livechatinc.com", reason: "widget" },
|
|
149
|
+
{ domain: "tawk.to", reason: "widget" },
|
|
150
|
+
{ domain: "zendesk.com", reason: "widget" },
|
|
151
|
+
{ domain: "crisp.chat", reason: "widget" },
|
|
152
|
+
{ domain: "intercom.io", reason: "widget" },
|
|
153
|
+
{ domain: "freshchat.com", reason: "widget" },
|
|
154
|
+
{ domain: "lc.chat", reason: "widget" },
|
|
155
|
+
// Big Tech / Infra / OSINT / Misc Noise
|
|
156
|
+
{ domain: "apple.com", reason: "vendor" },
|
|
157
|
+
{ domain: "microsoft.com", reason: "vendor" },
|
|
158
|
+
{ domain: "live.com", reason: "vendor" },
|
|
159
|
+
{ domain: "github.com", reason: "dev" },
|
|
160
|
+
{ domain: "githubusercontent.com", reason: "dev" },
|
|
161
|
+
{ domain: "gitlab.com", reason: "dev" },
|
|
162
|
+
{ domain: "npmjs.com", reason: "dev" },
|
|
163
|
+
{ domain: "wikipedia.org", reason: "reference" },
|
|
164
|
+
{ domain: "wikimedia.org", reason: "reference" },
|
|
165
|
+
{ domain: "dmca.com", reason: "badge" },
|
|
166
|
+
{ domain: "trustpilot.com", reason: "badge" },
|
|
167
|
+
{ domain: "crt.sh", reason: "osint" },
|
|
168
|
+
{ domain: "urlscan.io", reason: "osint" },
|
|
169
|
+
{ domain: "komdigi.go.id", reason: "gov" },
|
|
170
|
+
{ domain: "kominfo.go.id", reason: "gov" },
|
|
171
|
+
{ domain: "aduankonten.id", reason: "gov" },
|
|
172
|
+
{ domain: "uzone.id", reason: "isp" },
|
|
173
|
+
{ domain: "amazonaws.com", reason: "cdn" },
|
|
174
|
+
{ domain: "bing.com", reason: "search" },
|
|
175
|
+
{ domain: "yahoo.com", reason: "search" },
|
|
176
|
+
{ domain: "duckduckgo.com", reason: "search" },
|
|
177
|
+
{ domain: "yandex.ru", reason: "search" },
|
|
178
|
+
{ domain: "adobe.com", reason: "vendor" }
|
|
179
|
+
];
|
|
180
|
+
var DEFAULT_SETTINGS_RAW = {
|
|
181
|
+
copy_format: "https",
|
|
182
|
+
concurrency: "20",
|
|
183
|
+
timeout_ms: "10000",
|
|
184
|
+
claimer_name: "me",
|
|
185
|
+
urlscan_api_key: "",
|
|
186
|
+
dns_check_enabled: "true",
|
|
187
|
+
dns_filter_server: "180.131.144.144",
|
|
188
|
+
trustpositif_source_url: "https://raw.githubusercontent.com/alsyundawy/TrustPositif/main/alsyundawy_gambling_v2.txt",
|
|
189
|
+
trustpositif_last_sync: ""
|
|
190
|
+
};
|
|
191
|
+
var ISP_BLOCK_URL_PATTERNS = [
|
|
192
|
+
"trustpositif.komdigi.go.id",
|
|
193
|
+
"trustpositif.kominfo.go.id",
|
|
194
|
+
"internetpositif.id",
|
|
195
|
+
"internetpositif.uzone.id",
|
|
196
|
+
"mercusuar.uzone.id",
|
|
197
|
+
"internetbaik.telkomsel.com",
|
|
198
|
+
"lamanlabuh.aduankonten.id",
|
|
199
|
+
"blockpage.indihome.co.id",
|
|
200
|
+
"nawala.org"
|
|
201
|
+
];
|
|
202
|
+
var ISP_BLOCK_TEXT_PATTERNS = [
|
|
203
|
+
"trustpositif",
|
|
204
|
+
"internet positif",
|
|
205
|
+
"internet sehat",
|
|
206
|
+
"laman labuh",
|
|
207
|
+
"aduankonten",
|
|
208
|
+
"situs ini diblokir",
|
|
209
|
+
"halaman ini diblokir",
|
|
210
|
+
"konten negatif",
|
|
211
|
+
"undang-undang nomor 19 tahun 2016",
|
|
212
|
+
"permenkominfo",
|
|
213
|
+
"kementerian komunikasi dan informatika",
|
|
214
|
+
"kementerian komunikasi dan digital"
|
|
215
|
+
];
|
|
216
|
+
var ISP_SINKHOLE_IPS = /* @__PURE__ */ new Set([
|
|
217
|
+
"0.0.0.0",
|
|
218
|
+
"127.0.0.1",
|
|
219
|
+
"36.86.63.185",
|
|
220
|
+
// Telkom Mercusuar / Internet Positif
|
|
221
|
+
"118.97.115.174",
|
|
222
|
+
"118.97.115.175",
|
|
223
|
+
"180.131.146.7",
|
|
224
|
+
// Nawala sinkhole
|
|
225
|
+
"202.134.2.15",
|
|
226
|
+
"103.10.222.12"
|
|
227
|
+
]);
|
|
228
|
+
var PARKING_URL_PATTERNS = [
|
|
229
|
+
"sedoparking.com",
|
|
230
|
+
"sedo.com",
|
|
231
|
+
"bodis.com",
|
|
232
|
+
"dan.com",
|
|
233
|
+
"afternic.com",
|
|
234
|
+
"hugedomains.com",
|
|
235
|
+
"parkingcrew.net",
|
|
236
|
+
"above.com",
|
|
237
|
+
"sav.com",
|
|
238
|
+
"godaddy.com/forsale",
|
|
239
|
+
"namecheap.com/domains",
|
|
240
|
+
"domainmarket.com",
|
|
241
|
+
"squadhelp.com"
|
|
242
|
+
];
|
|
243
|
+
var PARKING_TEXT_PATTERNS = [
|
|
244
|
+
"this domain is for sale",
|
|
245
|
+
"buy this domain",
|
|
246
|
+
"domain is available for purchase",
|
|
247
|
+
"this domain has expired",
|
|
248
|
+
"domain name is parked",
|
|
249
|
+
"parked free, courtesy of",
|
|
250
|
+
"inquire about this domain",
|
|
251
|
+
"get this domain",
|
|
252
|
+
"sedo domain parking",
|
|
253
|
+
"courtesy of godaddy",
|
|
254
|
+
"related searches"
|
|
255
|
+
];
|
|
256
|
+
var CF_CHALLENGE_PATTERNS = [
|
|
257
|
+
"just a moment...",
|
|
258
|
+
"checking your browser",
|
|
259
|
+
"challenges.cloudflare.com",
|
|
260
|
+
"cf-turnstile",
|
|
261
|
+
"cf-chl-bypass",
|
|
262
|
+
"_cf_chl_opt",
|
|
263
|
+
"enable javascript and cookies to continue",
|
|
264
|
+
"ddos-guard",
|
|
265
|
+
"attention required! | cloudflare"
|
|
266
|
+
];
|
|
267
|
+
var KNOWN_CDN_IPS_PREFIXES = [
|
|
268
|
+
"104.16.",
|
|
269
|
+
"104.17.",
|
|
270
|
+
"104.18.",
|
|
271
|
+
"104.19.",
|
|
272
|
+
"104.20.",
|
|
273
|
+
"104.21.",
|
|
274
|
+
"104.22.",
|
|
275
|
+
"104.24.",
|
|
276
|
+
"104.25.",
|
|
277
|
+
"104.26.",
|
|
278
|
+
"104.27.",
|
|
279
|
+
"172.64.",
|
|
280
|
+
"172.65.",
|
|
281
|
+
"172.66.",
|
|
282
|
+
"172.67.",
|
|
283
|
+
"162.158.",
|
|
284
|
+
"162.159.",
|
|
285
|
+
"188.114.",
|
|
286
|
+
"141.101."
|
|
287
|
+
];
|
|
288
|
+
|
|
289
|
+
// src/db.ts
|
|
290
|
+
import fs from "fs";
|
|
291
|
+
import path from "path";
|
|
292
|
+
import { DatabaseSync } from "node:sqlite";
|
|
293
|
+
function safeJsonParse(raw, fallback) {
|
|
294
|
+
if (!raw) return fallback;
|
|
295
|
+
try {
|
|
296
|
+
return JSON.parse(raw);
|
|
297
|
+
} catch {
|
|
298
|
+
return fallback;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
function rowToDomainItem(row) {
|
|
302
|
+
return {
|
|
303
|
+
id: row.id,
|
|
304
|
+
normalized_domain: row.normalized_domain,
|
|
305
|
+
original_url: row.original_url,
|
|
306
|
+
final_url: row.final_url,
|
|
307
|
+
redirect_chain: safeJsonParse(row.redirect_chain_json, []),
|
|
308
|
+
outbound_links: safeJsonParse(row.outbound_links_json, []),
|
|
309
|
+
source_type: row.source_type,
|
|
310
|
+
source_seed: row.source_seed,
|
|
311
|
+
health_status: row.health_status,
|
|
312
|
+
triage_status: row.triage_status,
|
|
313
|
+
http_status: row.http_status,
|
|
314
|
+
ip_address: row.ip_address,
|
|
315
|
+
page_title: row.page_title,
|
|
316
|
+
meta_description: row.meta_description,
|
|
317
|
+
confidence_score: row.confidence_score,
|
|
318
|
+
matched_keywords: safeJsonParse(row.matched_keywords_json, []),
|
|
319
|
+
detection_notes: row.detection_notes,
|
|
320
|
+
trustpositif_blocked: row.trustpositif_blocked === 1,
|
|
321
|
+
claimed_by: row.claimed_by,
|
|
322
|
+
claimed_at: row.claimed_at,
|
|
323
|
+
last_checked_at: row.last_checked_at,
|
|
324
|
+
created_at: row.created_at,
|
|
325
|
+
updated_at: row.updated_at
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
function rowToJobItem(row) {
|
|
329
|
+
return {
|
|
330
|
+
id: row.id,
|
|
331
|
+
job_type: row.job_type,
|
|
332
|
+
target: row.target,
|
|
333
|
+
status: row.status,
|
|
334
|
+
total_items: row.total_items,
|
|
335
|
+
processed_items: row.processed_items,
|
|
336
|
+
found_new: row.found_new,
|
|
337
|
+
skipped_duplicate: row.skipped_duplicate,
|
|
338
|
+
logs: safeJsonParse(row.log_json, []),
|
|
339
|
+
error_message: row.error_message,
|
|
340
|
+
created_at: row.created_at,
|
|
341
|
+
finished_at: row.finished_at
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
var AppDatabase = class {
|
|
345
|
+
db;
|
|
346
|
+
dbPath;
|
|
347
|
+
constructor(dbPath) {
|
|
348
|
+
this.dbPath = dbPath;
|
|
349
|
+
if (dbPath !== ":memory:") {
|
|
350
|
+
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
|
351
|
+
}
|
|
352
|
+
this.db = new DatabaseSync(dbPath);
|
|
353
|
+
this.init();
|
|
354
|
+
}
|
|
355
|
+
init() {
|
|
356
|
+
this.db.exec(`
|
|
357
|
+
PRAGMA journal_mode = WAL;
|
|
358
|
+
PRAGMA busy_timeout = 5000;
|
|
359
|
+
PRAGMA foreign_keys = ON;
|
|
360
|
+
|
|
361
|
+
CREATE TABLE IF NOT EXISTS domains (
|
|
362
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
363
|
+
normalized_domain TEXT NOT NULL UNIQUE,
|
|
364
|
+
original_url TEXT NOT NULL,
|
|
365
|
+
final_url TEXT,
|
|
366
|
+
redirect_chain_json TEXT NOT NULL DEFAULT '[]',
|
|
367
|
+
outbound_links_json TEXT NOT NULL DEFAULT '[]',
|
|
368
|
+
source_type TEXT NOT NULL,
|
|
369
|
+
source_seed TEXT,
|
|
370
|
+
health_status TEXT NOT NULL DEFAULT 'pending',
|
|
371
|
+
triage_status TEXT NOT NULL DEFAULT 'new',
|
|
372
|
+
http_status INTEGER,
|
|
373
|
+
ip_address TEXT,
|
|
374
|
+
page_title TEXT,
|
|
375
|
+
meta_description TEXT,
|
|
376
|
+
confidence_score INTEGER NOT NULL DEFAULT 0,
|
|
377
|
+
matched_keywords_json TEXT NOT NULL DEFAULT '[]',
|
|
378
|
+
detection_notes TEXT,
|
|
379
|
+
trustpositif_blocked INTEGER NOT NULL DEFAULT 0,
|
|
380
|
+
claimed_by TEXT,
|
|
381
|
+
claimed_at TEXT,
|
|
382
|
+
last_checked_at TEXT,
|
|
383
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
384
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
385
|
+
);
|
|
386
|
+
|
|
387
|
+
CREATE INDEX IF NOT EXISTS idx_domains_queue
|
|
388
|
+
ON domains(health_status, triage_status, confidence_score DESC);
|
|
389
|
+
CREATE INDEX IF NOT EXISTS idx_domains_seed
|
|
390
|
+
ON domains(source_seed);
|
|
391
|
+
|
|
392
|
+
CREATE TABLE IF NOT EXISTS jobs (
|
|
393
|
+
id TEXT PRIMARY KEY,
|
|
394
|
+
job_type TEXT NOT NULL,
|
|
395
|
+
target TEXT,
|
|
396
|
+
status TEXT NOT NULL DEFAULT 'running',
|
|
397
|
+
total_items INTEGER NOT NULL DEFAULT 0,
|
|
398
|
+
processed_items INTEGER NOT NULL DEFAULT 0,
|
|
399
|
+
found_new INTEGER NOT NULL DEFAULT 0,
|
|
400
|
+
skipped_duplicate INTEGER NOT NULL DEFAULT 0,
|
|
401
|
+
log_json TEXT NOT NULL DEFAULT '[]',
|
|
402
|
+
error_message TEXT,
|
|
403
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
404
|
+
finished_at TEXT
|
|
405
|
+
);
|
|
406
|
+
|
|
407
|
+
CREATE TABLE IF NOT EXISTS settings (
|
|
408
|
+
key TEXT PRIMARY KEY,
|
|
409
|
+
value TEXT NOT NULL
|
|
410
|
+
);
|
|
411
|
+
|
|
412
|
+
CREATE TABLE IF NOT EXISTS keywords (
|
|
413
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
414
|
+
term TEXT NOT NULL UNIQUE,
|
|
415
|
+
category TEXT NOT NULL DEFAULT 'judol',
|
|
416
|
+
weight INTEGER NOT NULL DEFAULT 15,
|
|
417
|
+
enabled INTEGER NOT NULL DEFAULT 1
|
|
418
|
+
);
|
|
419
|
+
|
|
420
|
+
CREATE TABLE IF NOT EXISTS blacklist_domains (
|
|
421
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
422
|
+
domain TEXT NOT NULL UNIQUE,
|
|
423
|
+
reason TEXT NOT NULL DEFAULT 'noise'
|
|
424
|
+
);
|
|
425
|
+
|
|
426
|
+
CREATE TABLE IF NOT EXISTS trustpositif_blocklist (
|
|
427
|
+
domain TEXT PRIMARY KEY
|
|
428
|
+
);
|
|
429
|
+
`);
|
|
430
|
+
this.seedDefaults();
|
|
431
|
+
}
|
|
432
|
+
seedDefaults() {
|
|
433
|
+
const insertSetting = this.db.prepare(
|
|
434
|
+
"INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)"
|
|
435
|
+
);
|
|
436
|
+
for (const [k, v] of Object.entries(DEFAULT_SETTINGS_RAW)) {
|
|
437
|
+
insertSetting.run(k, v);
|
|
438
|
+
}
|
|
439
|
+
const kwCount = this.db.prepare("SELECT COUNT(*) AS cnt FROM keywords").get().cnt;
|
|
440
|
+
if (kwCount === 0) {
|
|
441
|
+
const insertKw = this.db.prepare(
|
|
442
|
+
"INSERT OR IGNORE INTO keywords (term, category, weight, enabled) VALUES (?, ?, ?, 1)"
|
|
443
|
+
);
|
|
444
|
+
for (const kw of DEFAULT_KEYWORDS) {
|
|
445
|
+
insertKw.run(kw.term, kw.category, kw.weight);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
const blCount = this.db.prepare("SELECT COUNT(*) AS cnt FROM blacklist_domains").get().cnt;
|
|
449
|
+
if (blCount === 0) {
|
|
450
|
+
const insertBl = this.db.prepare(
|
|
451
|
+
"INSERT OR IGNORE INTO blacklist_domains (domain, reason) VALUES (?, ?)"
|
|
452
|
+
);
|
|
453
|
+
for (const bl of DEFAULT_BLACKLIST_DOMAINS) {
|
|
454
|
+
insertBl.run(bl.domain, bl.reason);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
close() {
|
|
459
|
+
this.db.close();
|
|
460
|
+
}
|
|
461
|
+
// ---- Domains ----
|
|
462
|
+
insertDomainIgnore(input) {
|
|
463
|
+
const stmt = this.db.prepare(`
|
|
464
|
+
INSERT OR IGNORE INTO domains (
|
|
465
|
+
normalized_domain, original_url, source_type, source_seed, health_status
|
|
466
|
+
) VALUES (?, ?, ?, ?, ?)
|
|
467
|
+
`);
|
|
468
|
+
const info = stmt.run(
|
|
469
|
+
input.normalized_domain,
|
|
470
|
+
input.original_url,
|
|
471
|
+
input.source_type,
|
|
472
|
+
input.source_seed ?? null,
|
|
473
|
+
input.health_status ?? "pending"
|
|
474
|
+
);
|
|
475
|
+
if (info.changes > 0) {
|
|
476
|
+
return { inserted: true, id: Number(info.lastInsertRowid) };
|
|
477
|
+
}
|
|
478
|
+
return { inserted: false, id: null };
|
|
479
|
+
}
|
|
480
|
+
getDomainById(id) {
|
|
481
|
+
const row = this.db.prepare("SELECT * FROM domains WHERE id = ?").get(id);
|
|
482
|
+
return row ? rowToDomainItem(row) : null;
|
|
483
|
+
}
|
|
484
|
+
getDomainByNormalized(domain) {
|
|
485
|
+
const row = this.db.prepare("SELECT * FROM domains WHERE normalized_domain = ?").get(domain.toLowerCase());
|
|
486
|
+
return row ? rowToDomainItem(row) : null;
|
|
487
|
+
}
|
|
488
|
+
getDomainsByIds(ids) {
|
|
489
|
+
if (ids.length === 0) return [];
|
|
490
|
+
const placeholders = ids.map(() => "?").join(",");
|
|
491
|
+
const rows = this.db.prepare(`SELECT * FROM domains WHERE id IN (${placeholders})`).all(...ids);
|
|
492
|
+
return rows.map(rowToDomainItem);
|
|
493
|
+
}
|
|
494
|
+
getPendingDomains(limit = 500) {
|
|
495
|
+
const rows = this.db.prepare("SELECT * FROM domains WHERE health_status IN ('pending', 'checking') LIMIT ?").all(limit);
|
|
496
|
+
return rows.map(rowToDomainItem);
|
|
497
|
+
}
|
|
498
|
+
listDomains(params = {}) {
|
|
499
|
+
const where = [];
|
|
500
|
+
const args = [];
|
|
501
|
+
const view = params.view ?? "queue";
|
|
502
|
+
if (view === "queue") {
|
|
503
|
+
where.push("health_status = 'alive'");
|
|
504
|
+
} else if (view === "manual") {
|
|
505
|
+
where.push("health_status = 'cf_challenge'");
|
|
506
|
+
} else if (view === "archive") {
|
|
507
|
+
where.push("health_status IN ('cf_challenge', 'dead', 'parked', 'blocked_isp', 'blocked_trustpositif', 'pending', 'checking')");
|
|
508
|
+
}
|
|
509
|
+
if (params.health_status) {
|
|
510
|
+
if (params.health_status === "blocked_any") {
|
|
511
|
+
where.push("health_status IN ('blocked_isp', 'blocked_trustpositif')");
|
|
512
|
+
} else {
|
|
513
|
+
where.push("health_status = ?");
|
|
514
|
+
args.push(params.health_status);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
if (params.triage_status) {
|
|
518
|
+
where.push("triage_status = ?");
|
|
519
|
+
args.push(params.triage_status);
|
|
520
|
+
}
|
|
521
|
+
if (typeof params.min_score === "number" && params.min_score > 0) {
|
|
522
|
+
where.push("confidence_score >= ?");
|
|
523
|
+
args.push(params.min_score);
|
|
524
|
+
}
|
|
525
|
+
if (params.search && params.search.trim().length > 0) {
|
|
526
|
+
const q = `%${params.search.trim().toLowerCase()}%`;
|
|
527
|
+
where.push(
|
|
528
|
+
"(LOWER(normalized_domain) LIKE ? OR LOWER(COALESCE(page_title, '')) LIKE ? OR LOWER(COALESCE(source_seed, '')) LIKE ?)"
|
|
529
|
+
);
|
|
530
|
+
args.push(q, q, q);
|
|
531
|
+
}
|
|
532
|
+
const whereSql = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
|
|
533
|
+
let orderSql = "ORDER BY confidence_score DESC, id DESC";
|
|
534
|
+
if (params.sort === "newest") {
|
|
535
|
+
orderSql = "ORDER BY id DESC";
|
|
536
|
+
} else if (params.sort === "domain_asc") {
|
|
537
|
+
orderSql = "ORDER BY normalized_domain ASC";
|
|
538
|
+
}
|
|
539
|
+
const totalRow = this.db.prepare(`SELECT COUNT(*) AS cnt FROM domains ${whereSql}`).get(...args);
|
|
540
|
+
const limit = Math.min(Math.max(params.limit ?? 100, 1), 1e3);
|
|
541
|
+
const offset = Math.max(params.offset ?? 0, 0);
|
|
542
|
+
const rows = this.db.prepare(`SELECT * FROM domains ${whereSql} ${orderSql} LIMIT ? OFFSET ?`).all(...args, limit, offset);
|
|
543
|
+
return {
|
|
544
|
+
items: rows.map(rowToDomainItem),
|
|
545
|
+
total: totalRow.cnt,
|
|
546
|
+
counts: this.getQueueCounts()
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
getQueueCounts() {
|
|
550
|
+
const row = this.db.prepare(`
|
|
551
|
+
SELECT
|
|
552
|
+
SUM(CASE WHEN health_status = 'alive' THEN 1 ELSE 0 END) AS queue_total,
|
|
553
|
+
SUM(CASE WHEN health_status = 'alive' AND triage_status = 'new' THEN 1 ELSE 0 END) AS new_count,
|
|
554
|
+
SUM(CASE WHEN health_status = 'alive' AND triage_status = 'claimed' THEN 1 ELSE 0 END) AS claimed_count,
|
|
555
|
+
SUM(CASE WHEN health_status = 'alive' AND triage_status = 'submitted' THEN 1 ELSE 0 END) AS submitted_count,
|
|
556
|
+
SUM(CASE WHEN health_status = 'alive' AND triage_status = 'valid' THEN 1 ELSE 0 END) AS valid_count,
|
|
557
|
+
SUM(CASE WHEN health_status = 'alive' AND triage_status = 'duplicate' THEN 1 ELSE 0 END) AS duplicate_count,
|
|
558
|
+
SUM(CASE WHEN health_status = 'alive' AND triage_status = 'rejected' THEN 1 ELSE 0 END) AS rejected_count,
|
|
559
|
+
SUM(CASE WHEN health_status IN ('pending', 'checking') THEN 1 ELSE 0 END) AS pending_count,
|
|
560
|
+
SUM(CASE WHEN health_status = 'cf_challenge' THEN 1 ELSE 0 END) AS manual_count,
|
|
561
|
+
SUM(CASE WHEN health_status IN ('blocked_isp', 'blocked_trustpositif') THEN 1 ELSE 0 END) AS blocked_count,
|
|
562
|
+
SUM(CASE WHEN health_status = 'parked' THEN 1 ELSE 0 END) AS parked_count,
|
|
563
|
+
SUM(CASE WHEN health_status = 'dead' THEN 1 ELSE 0 END) AS dead_count
|
|
564
|
+
FROM domains
|
|
565
|
+
`).get();
|
|
566
|
+
return {
|
|
567
|
+
queue_total: row.queue_total ?? 0,
|
|
568
|
+
new_count: row.new_count ?? 0,
|
|
569
|
+
claimed_count: row.claimed_count ?? 0,
|
|
570
|
+
submitted_count: row.submitted_count ?? 0,
|
|
571
|
+
valid_count: row.valid_count ?? 0,
|
|
572
|
+
duplicate_count: row.duplicate_count ?? 0,
|
|
573
|
+
rejected_count: row.rejected_count ?? 0,
|
|
574
|
+
pending_count: row.pending_count ?? 0,
|
|
575
|
+
manual_count: row.manual_count ?? 0,
|
|
576
|
+
blocked_count: row.blocked_count ?? 0,
|
|
577
|
+
parked_count: row.parked_count ?? 0,
|
|
578
|
+
dead_count: row.dead_count ?? 0
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
markDomainChecking(id) {
|
|
582
|
+
this.db.prepare("UPDATE domains SET health_status = 'checking', updated_at = datetime('now') WHERE id = ?").run(id);
|
|
583
|
+
}
|
|
584
|
+
updateDomainValidation(id, data) {
|
|
585
|
+
this.db.prepare(`
|
|
586
|
+
UPDATE domains SET
|
|
587
|
+
health_status = ?,
|
|
588
|
+
final_url = ?,
|
|
589
|
+
redirect_chain_json = ?,
|
|
590
|
+
outbound_links_json = ?,
|
|
591
|
+
http_status = ?,
|
|
592
|
+
ip_address = ?,
|
|
593
|
+
page_title = ?,
|
|
594
|
+
meta_description = ?,
|
|
595
|
+
confidence_score = ?,
|
|
596
|
+
matched_keywords_json = ?,
|
|
597
|
+
detection_notes = ?,
|
|
598
|
+
trustpositif_blocked = ?,
|
|
599
|
+
last_checked_at = datetime('now'),
|
|
600
|
+
updated_at = datetime('now')
|
|
601
|
+
WHERE id = ?
|
|
602
|
+
`).run(
|
|
603
|
+
data.health_status,
|
|
604
|
+
data.final_url,
|
|
605
|
+
JSON.stringify(data.redirect_chain),
|
|
606
|
+
JSON.stringify(data.outbound_links),
|
|
607
|
+
data.http_status,
|
|
608
|
+
data.ip_address,
|
|
609
|
+
data.page_title,
|
|
610
|
+
data.meta_description,
|
|
611
|
+
data.confidence_score,
|
|
612
|
+
JSON.stringify(data.matched_keywords),
|
|
613
|
+
data.detection_notes,
|
|
614
|
+
data.trustpositif_blocked ? 1 : 0,
|
|
615
|
+
id
|
|
616
|
+
);
|
|
617
|
+
return this.getDomainById(id);
|
|
618
|
+
}
|
|
619
|
+
claimDomain(id, claimerName) {
|
|
620
|
+
this.db.prepare(`
|
|
621
|
+
UPDATE domains SET
|
|
622
|
+
triage_status = CASE WHEN triage_status = 'new' THEN 'claimed' ELSE triage_status END,
|
|
623
|
+
claimed_by = COALESCE(claimed_by, ?),
|
|
624
|
+
claimed_at = COALESCE(claimed_at, datetime('now')),
|
|
625
|
+
updated_at = datetime('now')
|
|
626
|
+
WHERE id = ?
|
|
627
|
+
`).run(claimerName || "me", id);
|
|
628
|
+
return this.getDomainById(id);
|
|
629
|
+
}
|
|
630
|
+
updateDomainTriage(id, patch) {
|
|
631
|
+
const current = this.getDomainById(id);
|
|
632
|
+
if (!current) return null;
|
|
633
|
+
const nextTriage = patch.triage_status ?? current.triage_status;
|
|
634
|
+
const nextHealth = patch.health_status ?? current.health_status;
|
|
635
|
+
const nextNotes = patch.detection_notes !== void 0 ? patch.detection_notes : current.detection_notes;
|
|
636
|
+
const claimer = this.getSettings().claimer_name || "me";
|
|
637
|
+
const setClaim = nextTriage === "claimed" && !current.claimed_at ? `, claimed_by = ?, claimed_at = datetime('now')` : "";
|
|
638
|
+
const sql = `
|
|
639
|
+
UPDATE domains SET
|
|
640
|
+
triage_status = ?,
|
|
641
|
+
health_status = ?,
|
|
642
|
+
detection_notes = ?,
|
|
643
|
+
updated_at = datetime('now')
|
|
644
|
+
${setClaim}
|
|
645
|
+
WHERE id = ?
|
|
646
|
+
`;
|
|
647
|
+
if (setClaim) {
|
|
648
|
+
this.db.prepare(sql).run(nextTriage, nextHealth, nextNotes, claimer, id);
|
|
649
|
+
} else {
|
|
650
|
+
this.db.prepare(sql).run(nextTriage, nextHealth, nextNotes, id);
|
|
651
|
+
}
|
|
652
|
+
return this.getDomainById(id);
|
|
653
|
+
}
|
|
654
|
+
bulkUpdateTriage(ids, triageStatus) {
|
|
655
|
+
if (ids.length === 0) return 0;
|
|
656
|
+
const placeholders = ids.map(() => "?").join(",");
|
|
657
|
+
const info = this.db.prepare(
|
|
658
|
+
`UPDATE domains SET triage_status = ?, updated_at = datetime('now') WHERE id IN (${placeholders})`
|
|
659
|
+
).run(triageStatus, ...ids);
|
|
660
|
+
return Number(info.changes);
|
|
661
|
+
}
|
|
662
|
+
deleteDomain(id) {
|
|
663
|
+
const info = this.db.prepare("DELETE FROM domains WHERE id = ?").run(id);
|
|
664
|
+
return info.changes > 0;
|
|
665
|
+
}
|
|
666
|
+
// ---- Jobs ----
|
|
667
|
+
createJob(id, jobType, target, totalItems = 0) {
|
|
668
|
+
this.db.prepare(
|
|
669
|
+
`INSERT INTO jobs (id, job_type, target, status, total_items) VALUES (?, ?, ?, 'running', ?)`
|
|
670
|
+
).run(id, jobType, target, totalItems);
|
|
671
|
+
return this.getJob(id);
|
|
672
|
+
}
|
|
673
|
+
updateJob(id, patch) {
|
|
674
|
+
const cur = this.getJob(id);
|
|
675
|
+
if (!cur) return null;
|
|
676
|
+
this.db.prepare(`
|
|
677
|
+
UPDATE jobs SET
|
|
678
|
+
status = ?,
|
|
679
|
+
total_items = ?,
|
|
680
|
+
processed_items = ?,
|
|
681
|
+
found_new = ?,
|
|
682
|
+
skipped_duplicate = ?,
|
|
683
|
+
error_message = ?,
|
|
684
|
+
finished_at = CASE WHEN ? = 1 THEN datetime('now') ELSE finished_at END
|
|
685
|
+
WHERE id = ?
|
|
686
|
+
`).run(
|
|
687
|
+
patch.status ?? cur.status,
|
|
688
|
+
patch.total_items ?? cur.total_items,
|
|
689
|
+
patch.processed_items ?? cur.processed_items,
|
|
690
|
+
patch.found_new ?? cur.found_new,
|
|
691
|
+
patch.skipped_duplicate ?? cur.skipped_duplicate,
|
|
692
|
+
patch.error_message !== void 0 ? patch.error_message : cur.error_message,
|
|
693
|
+
patch.finished ? 1 : 0,
|
|
694
|
+
id
|
|
695
|
+
);
|
|
696
|
+
return this.getJob(id);
|
|
697
|
+
}
|
|
698
|
+
appendJobLog(id, message) {
|
|
699
|
+
const cur = this.getJob(id);
|
|
700
|
+
if (!cur) return null;
|
|
701
|
+
const logs = [...cur.logs, `[${(/* @__PURE__ */ new Date()).toISOString().slice(11, 19)}] ${message}`].slice(-80);
|
|
702
|
+
this.db.prepare("UPDATE jobs SET log_json = ? WHERE id = ?").run(JSON.stringify(logs), id);
|
|
703
|
+
return this.getJob(id);
|
|
704
|
+
}
|
|
705
|
+
getJob(id) {
|
|
706
|
+
const row = this.db.prepare("SELECT * FROM jobs WHERE id = ?").get(id);
|
|
707
|
+
return row ? rowToJobItem(row) : null;
|
|
708
|
+
}
|
|
709
|
+
listJobs(limit = 25) {
|
|
710
|
+
const rows = this.db.prepare("SELECT * FROM jobs ORDER BY created_at DESC, rowid DESC LIMIT ?").all(limit);
|
|
711
|
+
return rows.map(rowToJobItem);
|
|
712
|
+
}
|
|
713
|
+
// ---- Settings / Keywords / Blacklist / TrustPositif ----
|
|
714
|
+
getSettings() {
|
|
715
|
+
const rows = this.db.prepare("SELECT key, value FROM settings").all();
|
|
716
|
+
const map = { ...DEFAULT_SETTINGS_RAW };
|
|
717
|
+
for (const r of rows) map[r.key] = r.value;
|
|
718
|
+
return {
|
|
719
|
+
copy_format: map.copy_format === "bare" ? "bare" : "https",
|
|
720
|
+
concurrency: Math.min(Math.max(Number.parseInt(map.concurrency, 10) || 20, 1), 60),
|
|
721
|
+
timeout_ms: Math.min(Math.max(Number.parseInt(map.timeout_ms, 10) || 1e4, 2e3), 3e4),
|
|
722
|
+
claimer_name: map.claimer_name || "me",
|
|
723
|
+
urlscan_api_key: map.urlscan_api_key || "",
|
|
724
|
+
dns_check_enabled: map.dns_check_enabled !== "false",
|
|
725
|
+
dns_filter_server: map.dns_filter_server || "180.131.144.144",
|
|
726
|
+
trustpositif_source_url: map.trustpositif_source_url || DEFAULT_SETTINGS_RAW.trustpositif_source_url,
|
|
727
|
+
trustpositif_last_sync: map.trustpositif_last_sync || ""
|
|
728
|
+
};
|
|
729
|
+
}
|
|
730
|
+
setSettings(partial) {
|
|
731
|
+
const stmt = this.db.prepare(
|
|
732
|
+
"INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
|
|
733
|
+
);
|
|
734
|
+
for (const [k, v] of Object.entries(partial)) {
|
|
735
|
+
if (v !== void 0) {
|
|
736
|
+
stmt.run(k, String(v));
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
return this.getSettings();
|
|
740
|
+
}
|
|
741
|
+
listKeywords(onlyEnabled = false) {
|
|
742
|
+
const sql = onlyEnabled ? "SELECT * FROM keywords WHERE enabled = 1 ORDER BY weight DESC, term ASC" : "SELECT * FROM keywords ORDER BY weight DESC, term ASC";
|
|
743
|
+
return this.db.prepare(sql).all();
|
|
744
|
+
}
|
|
745
|
+
addKeyword(term, category, weight) {
|
|
746
|
+
const clean = term.trim().toLowerCase();
|
|
747
|
+
this.db.prepare("INSERT INTO keywords (term, category, weight, enabled) VALUES (?, ?, ?, 1)").run(clean, category || "judol", Math.min(Math.max(weight, 1), 100));
|
|
748
|
+
return this.db.prepare("SELECT * FROM keywords WHERE term = ?").get(clean);
|
|
749
|
+
}
|
|
750
|
+
updateKeyword(id, patch) {
|
|
751
|
+
const cur = this.db.prepare("SELECT * FROM keywords WHERE id = ?").get(id);
|
|
752
|
+
if (!cur) return null;
|
|
753
|
+
this.db.prepare("UPDATE keywords SET term = ?, category = ?, weight = ?, enabled = ? WHERE id = ?").run(
|
|
754
|
+
patch.term !== void 0 ? patch.term.trim().toLowerCase() : cur.term,
|
|
755
|
+
patch.category !== void 0 ? patch.category : cur.category,
|
|
756
|
+
patch.weight !== void 0 ? Math.min(Math.max(patch.weight, 1), 100) : cur.weight,
|
|
757
|
+
patch.enabled !== void 0 ? patch.enabled ? 1 : 0 : cur.enabled,
|
|
758
|
+
id
|
|
759
|
+
);
|
|
760
|
+
return this.db.prepare("SELECT * FROM keywords WHERE id = ?").get(id);
|
|
761
|
+
}
|
|
762
|
+
deleteKeyword(id) {
|
|
763
|
+
return this.db.prepare("DELETE FROM keywords WHERE id = ?").run(id).changes > 0;
|
|
764
|
+
}
|
|
765
|
+
listBlacklist() {
|
|
766
|
+
return this.db.prepare("SELECT * FROM blacklist_domains ORDER BY domain ASC").all();
|
|
767
|
+
}
|
|
768
|
+
getBlacklistSet() {
|
|
769
|
+
const rows = this.db.prepare("SELECT domain FROM blacklist_domains").all();
|
|
770
|
+
return new Set(rows.map((r) => r.domain.toLowerCase()));
|
|
771
|
+
}
|
|
772
|
+
addBlacklist(domain, reason = "custom") {
|
|
773
|
+
const clean = domain.trim().toLowerCase().replace(/^https?:\/\//, "").replace(/\/.*$/, "");
|
|
774
|
+
this.db.prepare("INSERT OR IGNORE INTO blacklist_domains (domain, reason) VALUES (?, ?)").run(clean, reason);
|
|
775
|
+
return this.db.prepare("SELECT * FROM blacklist_domains WHERE domain = ?").get(clean);
|
|
776
|
+
}
|
|
777
|
+
deleteBlacklist(id) {
|
|
778
|
+
return this.db.prepare("DELETE FROM blacklist_domains WHERE id = ?").run(id).changes > 0;
|
|
779
|
+
}
|
|
780
|
+
replaceTrustPositifBlocklist(domains) {
|
|
781
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
782
|
+
try {
|
|
783
|
+
this.db.exec("DELETE FROM trustpositif_blocklist");
|
|
784
|
+
const insert = this.db.prepare("INSERT OR IGNORE INTO trustpositif_blocklist (domain) VALUES (?)");
|
|
785
|
+
for (const d of domains) {
|
|
786
|
+
insert.run(d);
|
|
787
|
+
}
|
|
788
|
+
this.db.exec("COMMIT");
|
|
789
|
+
} catch (err) {
|
|
790
|
+
this.db.exec("ROLLBACK");
|
|
791
|
+
throw err;
|
|
792
|
+
}
|
|
793
|
+
return this.getTrustPositifCount();
|
|
794
|
+
}
|
|
795
|
+
getTrustPositifCount() {
|
|
796
|
+
const row = this.db.prepare("SELECT COUNT(*) AS cnt FROM trustpositif_blocklist").get();
|
|
797
|
+
return row.cnt;
|
|
798
|
+
}
|
|
799
|
+
loadTrustPositifSet() {
|
|
800
|
+
const rows = this.db.prepare("SELECT domain FROM trustpositif_blocklist").all();
|
|
801
|
+
return new Set(rows.map((r) => r.domain));
|
|
802
|
+
}
|
|
803
|
+
};
|
|
804
|
+
|
|
805
|
+
// src/server.ts
|
|
806
|
+
import fs2 from "fs";
|
|
807
|
+
import path2 from "path";
|
|
808
|
+
import { fileURLToPath } from "url";
|
|
809
|
+
import { serve } from "@hono/node-server";
|
|
810
|
+
import { Hono as Hono5 } from "hono";
|
|
811
|
+
|
|
812
|
+
// src/routes/domains.ts
|
|
813
|
+
import { Hono } from "hono";
|
|
814
|
+
|
|
815
|
+
// src/services/normalizer.ts
|
|
816
|
+
import { parse } from "tldts";
|
|
817
|
+
var URL_IN_TEXT_REGEX = /(?:https?:\/\/[^\s"'<>()[\]{},;]+)|(?:(?<![a-zA-Z0-9_-])(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,24}(?:\/[^\s"'<>()[\]{},;]*)?)/gi;
|
|
818
|
+
function hasAssetExtension(inputUrl) {
|
|
819
|
+
const withoutHash = inputUrl.split("#")[0] ?? "";
|
|
820
|
+
const withoutQuery = withoutHash.split("?")[0] ?? "";
|
|
821
|
+
const lower = withoutQuery.toLowerCase().trim();
|
|
822
|
+
const dotIdx = lower.lastIndexOf(".");
|
|
823
|
+
if (dotIdx === -1) return false;
|
|
824
|
+
const ext = lower.slice(dotIdx);
|
|
825
|
+
if (!ASSET_EXTENSIONS.has(ext)) return false;
|
|
826
|
+
if (lower.includes("/")) {
|
|
827
|
+
const afterHost = lower.replace(/^https?:\/\//, "").split("/").slice(1).join("/");
|
|
828
|
+
if (afterHost.length > 0) return true;
|
|
829
|
+
}
|
|
830
|
+
return ASSET_EXTENSIONS.has(ext);
|
|
831
|
+
}
|
|
832
|
+
function isBlacklistedHost(hostname, domain, blacklistSet) {
|
|
833
|
+
const h = hostname.toLowerCase();
|
|
834
|
+
const d = domain.toLowerCase();
|
|
835
|
+
if (blacklistSet.has(h) || blacklistSet.has(d)) return true;
|
|
836
|
+
const parts = h.split(".");
|
|
837
|
+
for (let i = 1; i < parts.length - 1; i++) {
|
|
838
|
+
const suffix = parts.slice(i).join(".");
|
|
839
|
+
if (blacklistSet.has(suffix)) return true;
|
|
840
|
+
}
|
|
841
|
+
return false;
|
|
842
|
+
}
|
|
843
|
+
function normalizeCandidate(rawInput, blacklistSet = /* @__PURE__ */ new Set()) {
|
|
844
|
+
let trimmed = rawInput.trim().replace(/^["'`(<[]+|[>"'`)\],;]+$/g, "");
|
|
845
|
+
if (!trimmed || trimmed.length > 2048) {
|
|
846
|
+
return { ok: false, reason: "invalid" };
|
|
847
|
+
}
|
|
848
|
+
if (/^(mailto:|javascript:|tel:|data:|sms:|whatsapp:)/i.test(trimmed)) {
|
|
849
|
+
return { ok: false, reason: "invalid" };
|
|
850
|
+
}
|
|
851
|
+
trimmed = trimmed.replace(/^\*\./, "");
|
|
852
|
+
if (trimmed.includes("*")) {
|
|
853
|
+
return { ok: false, reason: "invalid" };
|
|
854
|
+
}
|
|
855
|
+
if (hasAssetExtension(trimmed)) {
|
|
856
|
+
return { ok: false, reason: "asset" };
|
|
857
|
+
}
|
|
858
|
+
const withScheme = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
|
|
859
|
+
let hostnameRaw = "";
|
|
860
|
+
try {
|
|
861
|
+
const u = new URL(withScheme);
|
|
862
|
+
hostnameRaw = u.hostname.toLowerCase();
|
|
863
|
+
} catch {
|
|
864
|
+
return { ok: false, reason: "invalid" };
|
|
865
|
+
}
|
|
866
|
+
if (!hostnameRaw || hostnameRaw === "localhost" || hostnameRaw.endsWith(".localhost") || hostnameRaw.endsWith(".local") || hostnameRaw.endsWith(".internal") || hostnameRaw.endsWith(".arpa")) {
|
|
867
|
+
return { ok: false, reason: "private_ip" };
|
|
868
|
+
}
|
|
869
|
+
const parsed = parse(withScheme, { allowPrivateDomains: true });
|
|
870
|
+
if (parsed.isIp) {
|
|
871
|
+
return { ok: false, reason: "private_ip" };
|
|
872
|
+
}
|
|
873
|
+
if (!parsed.domain || !parsed.publicSuffix || !parsed.hostname) {
|
|
874
|
+
return { ok: false, reason: "invalid" };
|
|
875
|
+
}
|
|
876
|
+
const normalizedDomain = parsed.domain.toLowerCase();
|
|
877
|
+
const hostname = parsed.hostname.toLowerCase();
|
|
878
|
+
if (isBlacklistedHost(hostname, normalizedDomain, blacklistSet)) {
|
|
879
|
+
return { ok: false, reason: "blacklisted" };
|
|
880
|
+
}
|
|
881
|
+
return {
|
|
882
|
+
ok: true,
|
|
883
|
+
normalized_domain: normalizedDomain,
|
|
884
|
+
original_url: withScheme,
|
|
885
|
+
hostname
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
function extractUrlsFromText(rawText) {
|
|
889
|
+
const seen = /* @__PURE__ */ new Set();
|
|
890
|
+
const results = [];
|
|
891
|
+
const matches = rawText.match(URL_IN_TEXT_REGEX) ?? [];
|
|
892
|
+
for (const m of matches) {
|
|
893
|
+
const cleaned = m.trim().replace(/[.,;:!?)\]]+$/, "");
|
|
894
|
+
if (!cleaned || cleaned.includes("@")) continue;
|
|
895
|
+
if (!seen.has(cleaned)) {
|
|
896
|
+
seen.add(cleaned);
|
|
897
|
+
results.push(cleaned);
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
return results;
|
|
901
|
+
}
|
|
902
|
+
function formatCopyUrl(normalizedDomain, copyFormat) {
|
|
903
|
+
if (copyFormat === "bare") {
|
|
904
|
+
return normalizedDomain;
|
|
905
|
+
}
|
|
906
|
+
return `https://${normalizedDomain}`;
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
// src/routes/domains.ts
|
|
910
|
+
var VALID_TRIAGE = /* @__PURE__ */ new Set([
|
|
911
|
+
"new",
|
|
912
|
+
"claimed",
|
|
913
|
+
"submitted",
|
|
914
|
+
"valid",
|
|
915
|
+
"duplicate",
|
|
916
|
+
"rejected"
|
|
917
|
+
]);
|
|
918
|
+
var VALID_HEALTH = /* @__PURE__ */ new Set([
|
|
919
|
+
"pending",
|
|
920
|
+
"checking",
|
|
921
|
+
"alive",
|
|
922
|
+
"cf_challenge",
|
|
923
|
+
"dead",
|
|
924
|
+
"parked",
|
|
925
|
+
"blocked_isp",
|
|
926
|
+
"blocked_trustpositif",
|
|
927
|
+
"blocked_any"
|
|
928
|
+
]);
|
|
929
|
+
function csvEscape(val) {
|
|
930
|
+
const s = val === null || val === void 0 ? "" : String(val);
|
|
931
|
+
if (s.includes(",") || s.includes('"') || s.includes("\n")) {
|
|
932
|
+
return `"${s.replace(/"/g, '""')}"`;
|
|
933
|
+
}
|
|
934
|
+
return s;
|
|
935
|
+
}
|
|
936
|
+
function createDomainsRouter(ctx) {
|
|
937
|
+
const app = new Hono();
|
|
938
|
+
app.get("/", (c) => {
|
|
939
|
+
const view = c.req.query("view") || "queue";
|
|
940
|
+
const healthRaw = c.req.query("health_status") || "";
|
|
941
|
+
const triageRaw = c.req.query("triage_status") || "";
|
|
942
|
+
const minScore = Number.parseInt(c.req.query("min_score") || "0", 10) || 0;
|
|
943
|
+
const search = c.req.query("search") || "";
|
|
944
|
+
const sort = c.req.query("sort") || "confidence_desc";
|
|
945
|
+
const limit = Number.parseInt(c.req.query("limit") || "150", 10) || 150;
|
|
946
|
+
const offset = Number.parseInt(c.req.query("offset") || "0", 10) || 0;
|
|
947
|
+
const result = ctx.db.listDomains({
|
|
948
|
+
view,
|
|
949
|
+
health_status: VALID_HEALTH.has(healthRaw) ? healthRaw : "",
|
|
950
|
+
triage_status: VALID_TRIAGE.has(triageRaw) ? triageRaw : "",
|
|
951
|
+
min_score: minScore,
|
|
952
|
+
search,
|
|
953
|
+
sort,
|
|
954
|
+
limit,
|
|
955
|
+
offset
|
|
956
|
+
});
|
|
957
|
+
return c.json(result);
|
|
958
|
+
});
|
|
959
|
+
app.get("/export", (c) => {
|
|
960
|
+
const format = c.req.query("format") === "csv" ? "csv" : "txt";
|
|
961
|
+
const view = c.req.query("view") || "queue";
|
|
962
|
+
const healthRaw = c.req.query("health_status") || "";
|
|
963
|
+
const triageRaw = c.req.query("triage_status") || "";
|
|
964
|
+
const minScore = Number.parseInt(c.req.query("min_score") || "0", 10) || 0;
|
|
965
|
+
const search = c.req.query("search") || "";
|
|
966
|
+
const settings = ctx.db.getSettings();
|
|
967
|
+
const res = ctx.db.listDomains({
|
|
968
|
+
view,
|
|
969
|
+
health_status: VALID_HEALTH.has(healthRaw) ? healthRaw : "",
|
|
970
|
+
triage_status: VALID_TRIAGE.has(triageRaw) ? triageRaw : "",
|
|
971
|
+
min_score: minScore,
|
|
972
|
+
search,
|
|
973
|
+
sort: "confidence_desc",
|
|
974
|
+
limit: 1e3,
|
|
975
|
+
offset: 0
|
|
976
|
+
});
|
|
977
|
+
const dateTag = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
978
|
+
if (format === "txt") {
|
|
979
|
+
const lines = res.items.map(
|
|
980
|
+
(d) => formatCopyUrl(d.normalized_domain, settings.copy_format)
|
|
981
|
+
);
|
|
982
|
+
return c.text(lines.join("\n") + (lines.length ? "\n" : ""), 200, {
|
|
983
|
+
"Content-Disposition": `attachment; filename="urlscanner-${view}-${dateTag}.txt"`,
|
|
984
|
+
"Content-Type": "text/plain; charset=utf-8"
|
|
985
|
+
});
|
|
986
|
+
}
|
|
987
|
+
const header = [
|
|
988
|
+
"url",
|
|
989
|
+
"normalized_domain",
|
|
990
|
+
"health_status",
|
|
991
|
+
"triage_status",
|
|
992
|
+
"confidence_score",
|
|
993
|
+
"http_status",
|
|
994
|
+
"ip_address",
|
|
995
|
+
"page_title",
|
|
996
|
+
"source_type",
|
|
997
|
+
"source_seed",
|
|
998
|
+
"claimed_by"
|
|
999
|
+
].join(",");
|
|
1000
|
+
const rows = res.items.map(
|
|
1001
|
+
(d) => [
|
|
1002
|
+
formatCopyUrl(d.normalized_domain, settings.copy_format),
|
|
1003
|
+
d.normalized_domain,
|
|
1004
|
+
d.health_status,
|
|
1005
|
+
d.triage_status,
|
|
1006
|
+
d.confidence_score,
|
|
1007
|
+
d.http_status,
|
|
1008
|
+
d.ip_address,
|
|
1009
|
+
d.page_title,
|
|
1010
|
+
d.source_type,
|
|
1011
|
+
d.source_seed,
|
|
1012
|
+
d.claimed_by
|
|
1013
|
+
].map(csvEscape).join(",")
|
|
1014
|
+
);
|
|
1015
|
+
const csv = [header, ...rows].join("\n") + "\n";
|
|
1016
|
+
return c.text(csv, 200, {
|
|
1017
|
+
"Content-Disposition": `attachment; filename="urlscanner-${view}-${dateTag}.csv"`,
|
|
1018
|
+
"Content-Type": "text/csv; charset=utf-8"
|
|
1019
|
+
});
|
|
1020
|
+
});
|
|
1021
|
+
app.post("/bulk-status", async (c) => {
|
|
1022
|
+
const body = await c.req.json().catch(() => ({}));
|
|
1023
|
+
if (!Array.isArray(body.ids) || !body.triage_status || !VALID_TRIAGE.has(body.triage_status)) {
|
|
1024
|
+
return c.json({ error: "ids dan triage_status valid diperlukan" }, 400);
|
|
1025
|
+
}
|
|
1026
|
+
const updated = ctx.db.bulkUpdateTriage(body.ids, body.triage_status);
|
|
1027
|
+
return c.json({ updated, counts: ctx.db.getQueueCounts() });
|
|
1028
|
+
});
|
|
1029
|
+
app.get("/:id", (c) => {
|
|
1030
|
+
const id = Number.parseInt(c.req.param("id"), 10);
|
|
1031
|
+
if (Number.isNaN(id)) return c.json({ error: "ID tidak valid" }, 400);
|
|
1032
|
+
const domain = ctx.db.getDomainById(id);
|
|
1033
|
+
if (!domain) return c.json({ error: "Domain tidak ditemukan" }, 404);
|
|
1034
|
+
return c.json({ domain });
|
|
1035
|
+
});
|
|
1036
|
+
app.post("/:id/claim", (c) => {
|
|
1037
|
+
const id = Number.parseInt(c.req.param("id"), 10);
|
|
1038
|
+
if (Number.isNaN(id)) return c.json({ error: "ID tidak valid" }, 400);
|
|
1039
|
+
const settings = ctx.db.getSettings();
|
|
1040
|
+
const updated = ctx.db.claimDomain(id, settings.claimer_name);
|
|
1041
|
+
if (!updated) return c.json({ error: "Domain tidak ditemukan" }, 404);
|
|
1042
|
+
return c.json({
|
|
1043
|
+
domain: updated,
|
|
1044
|
+
copy_text: formatCopyUrl(updated.normalized_domain, settings.copy_format),
|
|
1045
|
+
counts: ctx.db.getQueueCounts()
|
|
1046
|
+
});
|
|
1047
|
+
});
|
|
1048
|
+
app.patch("/:id", async (c) => {
|
|
1049
|
+
const id = Number.parseInt(c.req.param("id"), 10);
|
|
1050
|
+
if (Number.isNaN(id)) return c.json({ error: "ID tidak valid" }, 400);
|
|
1051
|
+
const body = await c.req.json().catch(() => ({}));
|
|
1052
|
+
if (body.triage_status && !VALID_TRIAGE.has(body.triage_status)) {
|
|
1053
|
+
return c.json({ error: "triage_status tidak valid" }, 400);
|
|
1054
|
+
}
|
|
1055
|
+
if (body.health_status && (!VALID_HEALTH.has(body.health_status) || body.health_status === "blocked_any")) {
|
|
1056
|
+
return c.json({ error: "health_status tidak valid" }, 400);
|
|
1057
|
+
}
|
|
1058
|
+
const updated = ctx.db.updateDomainTriage(id, {
|
|
1059
|
+
triage_status: body.triage_status,
|
|
1060
|
+
health_status: body.health_status,
|
|
1061
|
+
detection_notes: body.detection_notes
|
|
1062
|
+
});
|
|
1063
|
+
if (!updated) return c.json({ error: "Domain tidak ditemukan" }, 404);
|
|
1064
|
+
return c.json({ domain: updated, counts: ctx.db.getQueueCounts() });
|
|
1065
|
+
});
|
|
1066
|
+
app.post("/:id/recheck", (c) => {
|
|
1067
|
+
const id = Number.parseInt(c.req.param("id"), 10);
|
|
1068
|
+
if (Number.isNaN(id)) return c.json({ error: "ID tidak valid" }, 400);
|
|
1069
|
+
const domain = ctx.db.getDomainById(id);
|
|
1070
|
+
if (!domain) return c.json({ error: "Domain tidak ditemukan" }, 404);
|
|
1071
|
+
const job = ctx.jobs.startValidationJob([id], `Re-check ${domain.normalized_domain}`);
|
|
1072
|
+
return c.json({ job });
|
|
1073
|
+
});
|
|
1074
|
+
app.delete("/:id", (c) => {
|
|
1075
|
+
const id = Number.parseInt(c.req.param("id"), 10);
|
|
1076
|
+
if (Number.isNaN(id)) return c.json({ error: "ID tidak valid" }, 400);
|
|
1077
|
+
const deleted = ctx.db.deleteDomain(id);
|
|
1078
|
+
if (!deleted) return c.json({ error: "Domain tidak ditemukan" }, 404);
|
|
1079
|
+
return c.json({ deleted: true, counts: ctx.db.getQueueCounts() });
|
|
1080
|
+
});
|
|
1081
|
+
return app;
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
// src/routes/ingest.ts
|
|
1085
|
+
import { Hono as Hono2 } from "hono";
|
|
1086
|
+
var ALL_SOURCES = ["crtsh", "urlscan", "html"];
|
|
1087
|
+
function createIngestRouter(ctx) {
|
|
1088
|
+
const app = new Hono2();
|
|
1089
|
+
app.post("/bulk", async (c) => {
|
|
1090
|
+
let rawText = "";
|
|
1091
|
+
let sourceSeed = "bulk_import";
|
|
1092
|
+
let autoValidate = true;
|
|
1093
|
+
const contentType = c.req.header("content-type") || "";
|
|
1094
|
+
if (contentType.includes("multipart/form-data")) {
|
|
1095
|
+
const form = await c.req.parseBody();
|
|
1096
|
+
const textField = form.raw_text;
|
|
1097
|
+
if (typeof textField === "string") rawText += `${textField}
|
|
1098
|
+
`;
|
|
1099
|
+
const seedField = form.source_seed;
|
|
1100
|
+
if (typeof seedField === "string" && seedField.trim()) sourceSeed = seedField.trim();
|
|
1101
|
+
const fileField = form.file;
|
|
1102
|
+
if (fileField && typeof fileField === "object" && "text" in fileField) {
|
|
1103
|
+
rawText += await fileField.text();
|
|
1104
|
+
}
|
|
1105
|
+
if (form.auto_validate === "false") autoValidate = false;
|
|
1106
|
+
} else {
|
|
1107
|
+
const body = await c.req.json().catch(() => ({}));
|
|
1108
|
+
rawText = body.raw_text ?? "";
|
|
1109
|
+
if (body.source_seed) sourceSeed = body.source_seed;
|
|
1110
|
+
if (body.auto_validate === false) autoValidate = false;
|
|
1111
|
+
}
|
|
1112
|
+
if (!rawText.trim()) {
|
|
1113
|
+
return c.json({ error: "Teks URL atau file tidak boleh kosong" }, 400);
|
|
1114
|
+
}
|
|
1115
|
+
const blacklistSet = ctx.db.getBlacklistSet();
|
|
1116
|
+
const extracted = extractUrlsFromText(rawText);
|
|
1117
|
+
let inserted = 0;
|
|
1118
|
+
let duplicates = 0;
|
|
1119
|
+
let blacklisted = 0;
|
|
1120
|
+
let invalid = 0;
|
|
1121
|
+
const insertedIds = [];
|
|
1122
|
+
const seenInBatch = /* @__PURE__ */ new Set();
|
|
1123
|
+
for (const candidate of extracted) {
|
|
1124
|
+
const norm = normalizeCandidate(candidate, blacklistSet);
|
|
1125
|
+
if (!norm.ok) {
|
|
1126
|
+
if (norm.reason === "blacklisted") blacklisted++;
|
|
1127
|
+
else invalid++;
|
|
1128
|
+
continue;
|
|
1129
|
+
}
|
|
1130
|
+
if (seenInBatch.has(norm.normalized_domain)) {
|
|
1131
|
+
duplicates++;
|
|
1132
|
+
continue;
|
|
1133
|
+
}
|
|
1134
|
+
seenInBatch.add(norm.normalized_domain);
|
|
1135
|
+
const res = ctx.db.insertDomainIgnore({
|
|
1136
|
+
normalized_domain: norm.normalized_domain,
|
|
1137
|
+
original_url: norm.original_url,
|
|
1138
|
+
source_type: "bulk_import",
|
|
1139
|
+
source_seed: sourceSeed
|
|
1140
|
+
});
|
|
1141
|
+
if (res.inserted && res.id !== null) {
|
|
1142
|
+
inserted++;
|
|
1143
|
+
insertedIds.push(res.id);
|
|
1144
|
+
} else {
|
|
1145
|
+
duplicates++;
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
let jobId = null;
|
|
1149
|
+
if (autoValidate && insertedIds.length > 0) {
|
|
1150
|
+
const job = ctx.jobs.startValidationJob(
|
|
1151
|
+
insertedIds,
|
|
1152
|
+
`Bulk Import (${insertedIds.length} domain)`
|
|
1153
|
+
);
|
|
1154
|
+
jobId = job.id;
|
|
1155
|
+
}
|
|
1156
|
+
const result = {
|
|
1157
|
+
total_extracted: extracted.length,
|
|
1158
|
+
inserted,
|
|
1159
|
+
duplicates,
|
|
1160
|
+
blacklisted,
|
|
1161
|
+
invalid,
|
|
1162
|
+
inserted_ids: insertedIds,
|
|
1163
|
+
job_id: jobId
|
|
1164
|
+
};
|
|
1165
|
+
return c.json(result);
|
|
1166
|
+
});
|
|
1167
|
+
app.post("/pivot", async (c) => {
|
|
1168
|
+
const body = await c.req.json().catch(() => ({}));
|
|
1169
|
+
let seed = (body.seed ?? "").trim();
|
|
1170
|
+
let knownIp = null;
|
|
1171
|
+
let knownTitle = null;
|
|
1172
|
+
if (typeof body.domain_id === "number") {
|
|
1173
|
+
const existing = ctx.db.getDomainById(body.domain_id);
|
|
1174
|
+
if (!existing) {
|
|
1175
|
+
return c.json({ error: "Domain tidak ditemukan" }, 404);
|
|
1176
|
+
}
|
|
1177
|
+
seed = existing.normalized_domain;
|
|
1178
|
+
knownIp = existing.ip_address;
|
|
1179
|
+
knownTitle = existing.page_title;
|
|
1180
|
+
}
|
|
1181
|
+
if (!seed) {
|
|
1182
|
+
return c.json({ error: "Seed URL/brand atau domain_id wajib diisi" }, 400);
|
|
1183
|
+
}
|
|
1184
|
+
const requestedSources = Array.isArray(body.sources) ? body.sources.filter(
|
|
1185
|
+
(s) => ALL_SOURCES.includes(s)
|
|
1186
|
+
) : ALL_SOURCES;
|
|
1187
|
+
const sources = requestedSources.length > 0 ? requestedSources : ALL_SOURCES;
|
|
1188
|
+
const job = ctx.jobs.startPivotJob({
|
|
1189
|
+
seed,
|
|
1190
|
+
sources,
|
|
1191
|
+
knownIp,
|
|
1192
|
+
knownTitle
|
|
1193
|
+
});
|
|
1194
|
+
return c.json({ job });
|
|
1195
|
+
});
|
|
1196
|
+
return app;
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
// src/routes/jobs.ts
|
|
1200
|
+
import { Hono as Hono3 } from "hono";
|
|
1201
|
+
import { streamSSE } from "hono/streaming";
|
|
1202
|
+
function createJobsRouter(ctx) {
|
|
1203
|
+
const app = new Hono3();
|
|
1204
|
+
app.get("/", (c) => {
|
|
1205
|
+
return c.json({ jobs: ctx.db.listJobs(25) });
|
|
1206
|
+
});
|
|
1207
|
+
app.get("/stream", (c) => {
|
|
1208
|
+
return streamSSE(c, async (stream) => {
|
|
1209
|
+
let alive = true;
|
|
1210
|
+
const sendEvent = async (event, data) => {
|
|
1211
|
+
if (!alive) return;
|
|
1212
|
+
try {
|
|
1213
|
+
await stream.writeSSE({
|
|
1214
|
+
event,
|
|
1215
|
+
data: JSON.stringify(data)
|
|
1216
|
+
});
|
|
1217
|
+
} catch {
|
|
1218
|
+
alive = false;
|
|
1219
|
+
}
|
|
1220
|
+
};
|
|
1221
|
+
await sendEvent("snapshot", {
|
|
1222
|
+
jobs: ctx.db.listJobs(15),
|
|
1223
|
+
counts: ctx.db.getQueueCounts()
|
|
1224
|
+
});
|
|
1225
|
+
const unsubscribe = ctx.jobs.subscribe((ev) => {
|
|
1226
|
+
void sendEvent(ev.type, ev);
|
|
1227
|
+
});
|
|
1228
|
+
const heartbeat = setInterval(() => {
|
|
1229
|
+
void sendEvent("ping", { ts: Date.now() });
|
|
1230
|
+
}, 2e4);
|
|
1231
|
+
stream.onAbort(() => {
|
|
1232
|
+
alive = false;
|
|
1233
|
+
clearInterval(heartbeat);
|
|
1234
|
+
unsubscribe();
|
|
1235
|
+
});
|
|
1236
|
+
while (alive) {
|
|
1237
|
+
await stream.sleep(1e3);
|
|
1238
|
+
}
|
|
1239
|
+
});
|
|
1240
|
+
});
|
|
1241
|
+
return app;
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
// src/routes/settings.ts
|
|
1245
|
+
import { Hono as Hono4 } from "hono";
|
|
1246
|
+
function createSettingsRouter(ctx) {
|
|
1247
|
+
const app = new Hono4();
|
|
1248
|
+
app.get("/", (c) => {
|
|
1249
|
+
return c.json({
|
|
1250
|
+
settings: ctx.db.getSettings(),
|
|
1251
|
+
trustpositif_count: ctx.trustPositif.getCount()
|
|
1252
|
+
});
|
|
1253
|
+
});
|
|
1254
|
+
app.put("/", async (c) => {
|
|
1255
|
+
const body = await c.req.json().catch(() => ({}));
|
|
1256
|
+
const patch = {};
|
|
1257
|
+
if (body.copy_format === "https" || body.copy_format === "bare") {
|
|
1258
|
+
patch.copy_format = body.copy_format;
|
|
1259
|
+
}
|
|
1260
|
+
if (typeof body.concurrency === "number" && body.concurrency >= 1 && body.concurrency <= 60) {
|
|
1261
|
+
patch.concurrency = body.concurrency;
|
|
1262
|
+
}
|
|
1263
|
+
if (typeof body.timeout_ms === "number" && body.timeout_ms >= 2e3 && body.timeout_ms <= 3e4) {
|
|
1264
|
+
patch.timeout_ms = body.timeout_ms;
|
|
1265
|
+
}
|
|
1266
|
+
if (typeof body.claimer_name === "string") {
|
|
1267
|
+
patch.claimer_name = body.claimer_name.trim() || "me";
|
|
1268
|
+
}
|
|
1269
|
+
if (typeof body.urlscan_api_key === "string") {
|
|
1270
|
+
patch.urlscan_api_key = body.urlscan_api_key.trim();
|
|
1271
|
+
}
|
|
1272
|
+
if (typeof body.dns_check_enabled === "boolean") {
|
|
1273
|
+
patch.dns_check_enabled = body.dns_check_enabled;
|
|
1274
|
+
}
|
|
1275
|
+
if (typeof body.dns_filter_server === "string") {
|
|
1276
|
+
patch.dns_filter_server = body.dns_filter_server.trim();
|
|
1277
|
+
}
|
|
1278
|
+
if (typeof body.trustpositif_source_url === "string" && body.trustpositif_source_url.trim()) {
|
|
1279
|
+
patch.trustpositif_source_url = body.trustpositif_source_url.trim();
|
|
1280
|
+
}
|
|
1281
|
+
const updated = ctx.db.setSettings(patch);
|
|
1282
|
+
return c.json({ settings: updated });
|
|
1283
|
+
});
|
|
1284
|
+
app.get("/keywords", (c) => {
|
|
1285
|
+
return c.json({ keywords: ctx.db.listKeywords(false) });
|
|
1286
|
+
});
|
|
1287
|
+
app.post("/keywords", async (c) => {
|
|
1288
|
+
const body = await c.req.json().catch(() => ({}));
|
|
1289
|
+
if (!body.term || !body.term.trim()) {
|
|
1290
|
+
return c.json({ error: "Kata kunci wajib diisi" }, 400);
|
|
1291
|
+
}
|
|
1292
|
+
try {
|
|
1293
|
+
const keyword = ctx.db.addKeyword(
|
|
1294
|
+
body.term,
|
|
1295
|
+
body.category ?? "judol",
|
|
1296
|
+
Number(body.weight ?? 15)
|
|
1297
|
+
);
|
|
1298
|
+
return c.json({ keyword }, 201);
|
|
1299
|
+
} catch {
|
|
1300
|
+
return c.json({ error: "Kata kunci sudah ada" }, 409);
|
|
1301
|
+
}
|
|
1302
|
+
});
|
|
1303
|
+
app.put("/keywords/:id", async (c) => {
|
|
1304
|
+
const id = Number.parseInt(c.req.param("id"), 10);
|
|
1305
|
+
if (Number.isNaN(id)) return c.json({ error: "ID tidak valid" }, 400);
|
|
1306
|
+
const body = await c.req.json().catch(() => ({}));
|
|
1307
|
+
const updated = ctx.db.updateKeyword(id, body);
|
|
1308
|
+
if (!updated) return c.json({ error: "Keyword tidak ditemukan" }, 404);
|
|
1309
|
+
return c.json({ keyword: updated });
|
|
1310
|
+
});
|
|
1311
|
+
app.delete("/keywords/:id", (c) => {
|
|
1312
|
+
const id = Number.parseInt(c.req.param("id"), 10);
|
|
1313
|
+
if (Number.isNaN(id)) return c.json({ error: "ID tidak valid" }, 400);
|
|
1314
|
+
const ok = ctx.db.deleteKeyword(id);
|
|
1315
|
+
if (!ok) return c.json({ error: "Keyword tidak ditemukan" }, 404);
|
|
1316
|
+
return c.json({ deleted: true });
|
|
1317
|
+
});
|
|
1318
|
+
app.get("/blacklist", (c) => {
|
|
1319
|
+
return c.json({ blacklist: ctx.db.listBlacklist() });
|
|
1320
|
+
});
|
|
1321
|
+
app.post("/blacklist", async (c) => {
|
|
1322
|
+
const body = await c.req.json().catch(() => ({}));
|
|
1323
|
+
if (!body.domain || !body.domain.trim()) {
|
|
1324
|
+
return c.json({ error: "Domain blacklist wajib diisi" }, 400);
|
|
1325
|
+
}
|
|
1326
|
+
const item = ctx.db.addBlacklist(body.domain, body.reason ?? "custom");
|
|
1327
|
+
return c.json({ item }, 201);
|
|
1328
|
+
});
|
|
1329
|
+
app.delete("/blacklist/:id", (c) => {
|
|
1330
|
+
const id = Number.parseInt(c.req.param("id"), 10);
|
|
1331
|
+
if (Number.isNaN(id)) return c.json({ error: "ID tidak valid" }, 400);
|
|
1332
|
+
const ok = ctx.db.deleteBlacklist(id);
|
|
1333
|
+
if (!ok) return c.json({ error: "Blacklist tidak ditemukan" }, 404);
|
|
1334
|
+
return c.json({ deleted: true });
|
|
1335
|
+
});
|
|
1336
|
+
app.get("/trustpositif/status", (c) => {
|
|
1337
|
+
const settings = ctx.db.getSettings();
|
|
1338
|
+
return c.json({
|
|
1339
|
+
count: ctx.trustPositif.getCount(),
|
|
1340
|
+
last_sync: settings.trustpositif_last_sync,
|
|
1341
|
+
source_url: settings.trustpositif_source_url
|
|
1342
|
+
});
|
|
1343
|
+
});
|
|
1344
|
+
app.post("/trustpositif/sync", async (c) => {
|
|
1345
|
+
const body = await c.req.json().catch(() => ({}));
|
|
1346
|
+
const settings = ctx.db.getSettings();
|
|
1347
|
+
const url = (body.source_url || settings.trustpositif_source_url).trim();
|
|
1348
|
+
const job = ctx.jobs.startTrustPositifSyncJob(url);
|
|
1349
|
+
return c.json({ job });
|
|
1350
|
+
});
|
|
1351
|
+
return app;
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
// src/services/jobs.ts
|
|
1355
|
+
import crypto from "crypto";
|
|
1356
|
+
|
|
1357
|
+
// src/services/pivoter.ts
|
|
1358
|
+
import { Agent as Agent2, fetch as undiciFetch2 } from "undici";
|
|
1359
|
+
|
|
1360
|
+
// src/services/validator.ts
|
|
1361
|
+
import dns from "dns/promises";
|
|
1362
|
+
import * as cheerio2 from "cheerio";
|
|
1363
|
+
import { Agent, fetch as undiciFetch } from "undici";
|
|
1364
|
+
|
|
1365
|
+
// src/services/scorer.ts
|
|
1366
|
+
import * as cheerio from "cheerio";
|
|
1367
|
+
var DOMAIN_JUDOL_REGEX = /(slot|gacor|maxwin|togel|toto|rtp|casino|sbobet|poker|jackpot|scatter|jp\d*|bet\d*|88|777|138|303)/i;
|
|
1368
|
+
function scoreHtml(html, normalizedDomain, _finalUrl, enabledKeywords) {
|
|
1369
|
+
const $ = cheerio.load(html);
|
|
1370
|
+
const rawTitle = $("title").first().text().trim() || $('meta[property="og:title"]').attr("content")?.trim() || "";
|
|
1371
|
+
const title = rawTitle ? rawTitle.slice(0, 300) : null;
|
|
1372
|
+
const rawMeta = $('meta[name="description"]').attr("content")?.trim() || $('meta[property="og:description"]').attr("content")?.trim() || "";
|
|
1373
|
+
const metaDescription = rawMeta ? rawMeta.slice(0, 500) : null;
|
|
1374
|
+
const headingsText = $("h1, h2").map((_, el) => $(el).text().trim()).get().join(" ");
|
|
1375
|
+
const ampHref = $('link[rel="amphtml"]').attr("href")?.trim() || null;
|
|
1376
|
+
const isAmpPage = Boolean(ampHref) || $("html").attr("amp") !== void 0 || $("html").attr("\u26A1") !== void 0;
|
|
1377
|
+
$("script, style, noscript, svg").remove();
|
|
1378
|
+
const bodyText = $("body").text().replace(/\s+/g, " ").trim().slice(0, 3e4);
|
|
1379
|
+
const titleLower = (rawTitle || "").toLowerCase();
|
|
1380
|
+
const metaAndHeadingsLower = `${rawMeta} ${headingsText}`.toLowerCase();
|
|
1381
|
+
const bodyLower = bodyText.toLowerCase();
|
|
1382
|
+
let score = 0;
|
|
1383
|
+
const matched = [];
|
|
1384
|
+
const signals = [];
|
|
1385
|
+
for (const kw of enabledKeywords) {
|
|
1386
|
+
if (!kw.enabled) continue;
|
|
1387
|
+
const term = kw.term.toLowerCase().trim();
|
|
1388
|
+
if (!term) continue;
|
|
1389
|
+
if (titleLower.includes(term)) {
|
|
1390
|
+
const pts = Math.round(kw.weight * 1.5);
|
|
1391
|
+
score += pts;
|
|
1392
|
+
matched.push({ keyword: kw.term, weight: pts, location: "title" });
|
|
1393
|
+
} else if (metaAndHeadingsLower.includes(term)) {
|
|
1394
|
+
const pts = Math.round(kw.weight * 1.2);
|
|
1395
|
+
score += pts;
|
|
1396
|
+
matched.push({ keyword: kw.term, weight: pts, location: "meta" });
|
|
1397
|
+
} else if (bodyLower.includes(term)) {
|
|
1398
|
+
score += kw.weight;
|
|
1399
|
+
matched.push({ keyword: kw.term, weight: kw.weight, location: "body" });
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
if (DOMAIN_JUDOL_REGEX.test(normalizedDomain)) {
|
|
1403
|
+
score += 15;
|
|
1404
|
+
signals.push("domain-pattern");
|
|
1405
|
+
matched.push({ keyword: "domain-pattern", weight: 15, location: "domain" });
|
|
1406
|
+
}
|
|
1407
|
+
if (isAmpPage && matched.some((m) => m.location !== "domain")) {
|
|
1408
|
+
score += 10;
|
|
1409
|
+
signals.push("amp-judol");
|
|
1410
|
+
matched.push({ keyword: "amphtml", weight: 10, location: "signal" });
|
|
1411
|
+
} else if (isAmpPage) {
|
|
1412
|
+
signals.push("amp-present");
|
|
1413
|
+
}
|
|
1414
|
+
const fullLower = `${titleLower} ${metaAndHeadingsLower} ${bodyLower}`;
|
|
1415
|
+
const hasLogin = /\blogin\b|\bmasuk\b/.test(fullLower);
|
|
1416
|
+
const hasDaftar = /\bdaftar\b|\bregister\b/.test(fullLower);
|
|
1417
|
+
const hasAlt = /link alternatif|rtp live|deposit|withdraw/.test(fullLower);
|
|
1418
|
+
if (hasLogin && hasDaftar && hasAlt) {
|
|
1419
|
+
score += 10;
|
|
1420
|
+
signals.push("cta-login-daftar-alt");
|
|
1421
|
+
matched.push({ keyword: "login+daftar+alt", weight: 10, location: "signal" });
|
|
1422
|
+
}
|
|
1423
|
+
const clamped = Math.min(100, Math.max(0, score));
|
|
1424
|
+
matched.sort((a, b) => b.weight - a.weight);
|
|
1425
|
+
return {
|
|
1426
|
+
title,
|
|
1427
|
+
meta_description: metaDescription,
|
|
1428
|
+
confidence_score: clamped,
|
|
1429
|
+
matched_keywords: matched,
|
|
1430
|
+
signals,
|
|
1431
|
+
has_amp: isAmpPage,
|
|
1432
|
+
amp_url: ampHref
|
|
1433
|
+
};
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
// src/services/validator.ts
|
|
1437
|
+
var insecureAgent = new Agent({
|
|
1438
|
+
connect: {
|
|
1439
|
+
rejectUnauthorized: false
|
|
1440
|
+
}
|
|
1441
|
+
});
|
|
1442
|
+
var PRIORITY_CTA_REGEX = /(login|daftar|register|alternatif|rtp|amp|masuk|main|bonus|slot)/i;
|
|
1443
|
+
async function defaultFetch(url, init) {
|
|
1444
|
+
return undiciFetch(url, {
|
|
1445
|
+
...init,
|
|
1446
|
+
dispatcher: insecureAgent
|
|
1447
|
+
});
|
|
1448
|
+
}
|
|
1449
|
+
async function defaultResolveIp(hostname) {
|
|
1450
|
+
try {
|
|
1451
|
+
const res = await dns.lookup(hostname, { family: 4 });
|
|
1452
|
+
return res.address;
|
|
1453
|
+
} catch {
|
|
1454
|
+
return null;
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
function detectIspBlock(finalUrl, title, bodyLower, ip) {
|
|
1458
|
+
const urlLower = finalUrl.toLowerCase();
|
|
1459
|
+
for (const pat of ISP_BLOCK_URL_PATTERNS) {
|
|
1460
|
+
if (urlLower.includes(pat)) {
|
|
1461
|
+
return `Redirect ke halaman blokir ISP/Komdigi (${pat})`;
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
if (ip && ISP_SINKHOLE_IPS.has(ip)) {
|
|
1465
|
+
return `IP sinkhole ISP terdeteksi (${ip})`;
|
|
1466
|
+
}
|
|
1467
|
+
const combined = `${title.toLowerCase()} ${bodyLower}`;
|
|
1468
|
+
for (const pat of ISP_BLOCK_TEXT_PATTERNS) {
|
|
1469
|
+
if (combined.includes(pat)) {
|
|
1470
|
+
return `Konten halaman blokir Komdigi/ISP (${pat})`;
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
return null;
|
|
1474
|
+
}
|
|
1475
|
+
function detectCloudflareChallenge(status, headers, bodyLower, titleLower) {
|
|
1476
|
+
const cfMitigated = headers.get("cf-mitigated")?.toLowerCase() ?? "";
|
|
1477
|
+
if (cfMitigated.includes("challenge")) {
|
|
1478
|
+
return "Cloudflare challenge header (cf-mitigated) \u2014 Perlu Cek Manual";
|
|
1479
|
+
}
|
|
1480
|
+
if (status === 403 || status === 503 || status === 429) {
|
|
1481
|
+
const combined = `${titleLower} ${bodyLower}`;
|
|
1482
|
+
for (const pat of CF_CHALLENGE_PATTERNS) {
|
|
1483
|
+
if (combined.includes(pat)) {
|
|
1484
|
+
return `Proteksi bot/Cloudflare (${status}: ${pat}) \u2014 Perlu Cek Manual`;
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
return null;
|
|
1489
|
+
}
|
|
1490
|
+
function detectParking(finalUrl, titleLower, bodyLower) {
|
|
1491
|
+
const urlLower = finalUrl.toLowerCase();
|
|
1492
|
+
for (const pat of PARKING_URL_PATTERNS) {
|
|
1493
|
+
if (urlLower.includes(pat)) {
|
|
1494
|
+
return `Halaman parkir domain (${pat})`;
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
const combined = `${titleLower} ${bodyLower}`;
|
|
1498
|
+
for (const pat of PARKING_TEXT_PATTERNS) {
|
|
1499
|
+
if (combined.includes(pat)) {
|
|
1500
|
+
return `Sinyal halaman parkir (${pat})`;
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
return null;
|
|
1504
|
+
}
|
|
1505
|
+
function extractMetaRefreshUrl(html, baseUrl) {
|
|
1506
|
+
const $ = cheerio2.load(html);
|
|
1507
|
+
const content = $('meta[http-equiv="refresh" i]').attr("content");
|
|
1508
|
+
if (!content) return null;
|
|
1509
|
+
const match = content.match(/url\s*=\s*['"]?([^'";\s]+)['"]?/i);
|
|
1510
|
+
if (!match?.[1]) return null;
|
|
1511
|
+
try {
|
|
1512
|
+
return new URL(match[1], baseUrl).toString();
|
|
1513
|
+
} catch {
|
|
1514
|
+
return null;
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
function extractOutboundLinks(html, baseUrl, currentNormalizedDomain, blacklistSet) {
|
|
1518
|
+
const $ = cheerio2.load(html);
|
|
1519
|
+
const byDomain = /* @__PURE__ */ new Map();
|
|
1520
|
+
const addCandidate = (rawHref, label, forcedPriority = false) => {
|
|
1521
|
+
if (!rawHref) return;
|
|
1522
|
+
let absUrl = rawHref.trim();
|
|
1523
|
+
if (/^(mailto:|javascript:|tel:|#|data:)/i.test(absUrl)) return;
|
|
1524
|
+
try {
|
|
1525
|
+
absUrl = new URL(absUrl, baseUrl).toString();
|
|
1526
|
+
} catch {
|
|
1527
|
+
return;
|
|
1528
|
+
}
|
|
1529
|
+
const norm = normalizeCandidate(absUrl, blacklistSet);
|
|
1530
|
+
if (!norm.ok) return;
|
|
1531
|
+
if (norm.normalized_domain === currentNormalizedDomain) return;
|
|
1532
|
+
const cleanLabel = label.replace(/\s+/g, " ").trim().slice(0, 60) || norm.normalized_domain;
|
|
1533
|
+
const isPriority = forcedPriority || PRIORITY_CTA_REGEX.test(`${cleanLabel} ${absUrl}`);
|
|
1534
|
+
const existing = byDomain.get(norm.normalized_domain);
|
|
1535
|
+
if (!existing || !existing.priority && isPriority) {
|
|
1536
|
+
byDomain.set(norm.normalized_domain, {
|
|
1537
|
+
url: absUrl,
|
|
1538
|
+
normalized_domain: norm.normalized_domain,
|
|
1539
|
+
label: cleanLabel,
|
|
1540
|
+
priority: isPriority
|
|
1541
|
+
});
|
|
1542
|
+
}
|
|
1543
|
+
};
|
|
1544
|
+
$('link[rel="amphtml"], link[rel="canonical"]').each((_, el) => {
|
|
1545
|
+
const href = $(el).attr("href");
|
|
1546
|
+
const rel = $(el).attr("rel") ?? "link";
|
|
1547
|
+
if (href) addCandidate(href, rel, rel.includes("amphtml"));
|
|
1548
|
+
});
|
|
1549
|
+
$("a[href]").each((_, el) => {
|
|
1550
|
+
const href = $(el).attr("href");
|
|
1551
|
+
const text = $(el).text().trim() || $(el).attr("title") || "";
|
|
1552
|
+
if (href) addCandidate(href, text);
|
|
1553
|
+
});
|
|
1554
|
+
$("iframe[src]").each((_, el) => {
|
|
1555
|
+
const src = $(el).attr("src");
|
|
1556
|
+
if (src) addCandidate(src, "iframe");
|
|
1557
|
+
});
|
|
1558
|
+
$("[onclick]").each((_, el) => {
|
|
1559
|
+
const onclick = $(el).attr("onclick") ?? "";
|
|
1560
|
+
const urls = extractUrlsFromText(onclick);
|
|
1561
|
+
for (const u of urls) {
|
|
1562
|
+
addCandidate(u, $(el).text().trim() || "onclick", true);
|
|
1563
|
+
}
|
|
1564
|
+
});
|
|
1565
|
+
const inlineUrls = extractUrlsFromText(html);
|
|
1566
|
+
for (const u of inlineUrls) {
|
|
1567
|
+
if (/^https?:\/\//i.test(u)) {
|
|
1568
|
+
addCandidate(u, "html-regex", false);
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
return Array.from(byDomain.values()).sort((a, b) => Number(b.priority) - Number(a.priority));
|
|
1572
|
+
}
|
|
1573
|
+
async function fetchWithRedirects(startUrl, timeoutMs, fetchFn) {
|
|
1574
|
+
const chain = [];
|
|
1575
|
+
let currentUrl = startUrl;
|
|
1576
|
+
for (let hop = 0; hop < 8; hop++) {
|
|
1577
|
+
const controller = new AbortController();
|
|
1578
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
1579
|
+
try {
|
|
1580
|
+
const resp = await fetchFn(currentUrl, {
|
|
1581
|
+
method: "GET",
|
|
1582
|
+
redirect: "manual",
|
|
1583
|
+
signal: controller.signal,
|
|
1584
|
+
headers: {
|
|
1585
|
+
"User-Agent": CHROME_USER_AGENT,
|
|
1586
|
+
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
|
1587
|
+
"Accept-Language": "id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7"
|
|
1588
|
+
}
|
|
1589
|
+
});
|
|
1590
|
+
chain.push({ url: currentUrl, status_code: resp.status });
|
|
1591
|
+
if (resp.status >= 300 && resp.status < 400) {
|
|
1592
|
+
const loc = resp.headers.get("location");
|
|
1593
|
+
if (loc) {
|
|
1594
|
+
currentUrl = new URL(loc, currentUrl).toString();
|
|
1595
|
+
continue;
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
const body = await resp.text();
|
|
1599
|
+
if (hop < 7 && body.length < 4096) {
|
|
1600
|
+
const metaUrl = extractMetaRefreshUrl(body, currentUrl);
|
|
1601
|
+
if (metaUrl && metaUrl !== currentUrl) {
|
|
1602
|
+
currentUrl = metaUrl;
|
|
1603
|
+
continue;
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
return {
|
|
1607
|
+
finalUrl: currentUrl,
|
|
1608
|
+
status: resp.status,
|
|
1609
|
+
headers: resp.headers,
|
|
1610
|
+
body,
|
|
1611
|
+
chain
|
|
1612
|
+
};
|
|
1613
|
+
} finally {
|
|
1614
|
+
clearTimeout(timer);
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
throw new Error("Too many redirects");
|
|
1618
|
+
}
|
|
1619
|
+
async function validateDomain(domain, deps) {
|
|
1620
|
+
const fetchFn = deps.fetchFn ?? defaultFetch;
|
|
1621
|
+
const resolveIpFn = deps.resolveIpFn ?? defaultResolveIp;
|
|
1622
|
+
if (deps.trustPositif.isLocallyBlocked(domain.normalized_domain)) {
|
|
1623
|
+
return {
|
|
1624
|
+
health_status: "blocked_trustpositif",
|
|
1625
|
+
final_url: null,
|
|
1626
|
+
redirect_chain: [],
|
|
1627
|
+
outbound_links: [],
|
|
1628
|
+
http_status: null,
|
|
1629
|
+
ip_address: null,
|
|
1630
|
+
page_title: null,
|
|
1631
|
+
meta_description: null,
|
|
1632
|
+
confidence_score: 0,
|
|
1633
|
+
matched_keywords: [],
|
|
1634
|
+
detection_notes: "Terdaftar di blocklist TrustPositif lokal",
|
|
1635
|
+
trustpositif_blocked: true
|
|
1636
|
+
};
|
|
1637
|
+
}
|
|
1638
|
+
if (deps.settings.dns_check_enabled) {
|
|
1639
|
+
const dnsCheck = await deps.trustPositif.checkIndonesianDns(
|
|
1640
|
+
domain.normalized_domain,
|
|
1641
|
+
deps.settings.dns_filter_server,
|
|
1642
|
+
2500,
|
|
1643
|
+
deps.dnsLookupFn
|
|
1644
|
+
);
|
|
1645
|
+
if (dnsCheck.blocked) {
|
|
1646
|
+
return {
|
|
1647
|
+
health_status: "blocked_trustpositif",
|
|
1648
|
+
final_url: null,
|
|
1649
|
+
redirect_chain: [],
|
|
1650
|
+
outbound_links: [],
|
|
1651
|
+
http_status: null,
|
|
1652
|
+
ip_address: dnsCheck.resolved_ips[0] ?? null,
|
|
1653
|
+
page_title: null,
|
|
1654
|
+
meta_description: null,
|
|
1655
|
+
confidence_score: 0,
|
|
1656
|
+
matched_keywords: [],
|
|
1657
|
+
detection_notes: dnsCheck.reason,
|
|
1658
|
+
trustpositif_blocked: true
|
|
1659
|
+
};
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
const targetHost = new URL(
|
|
1663
|
+
domain.original_url.startsWith("http") ? domain.original_url : `https://${domain.normalized_domain}`
|
|
1664
|
+
).hostname;
|
|
1665
|
+
const ipAddress = await resolveIpFn(targetHost);
|
|
1666
|
+
const primaryUrl = domain.original_url.startsWith("http") ? domain.original_url : `https://${domain.normalized_domain}`;
|
|
1667
|
+
const fallbackUrl = primaryUrl.replace(/^https:\/\//i, "http://");
|
|
1668
|
+
let response = null;
|
|
1669
|
+
let lastError = null;
|
|
1670
|
+
for (const candidateUrl of primaryUrl === fallbackUrl ? [primaryUrl] : [primaryUrl, fallbackUrl]) {
|
|
1671
|
+
try {
|
|
1672
|
+
response = await fetchWithRedirects(candidateUrl, deps.settings.timeout_ms, fetchFn);
|
|
1673
|
+
break;
|
|
1674
|
+
} catch (err) {
|
|
1675
|
+
lastError = err instanceof Error ? err.message : String(err);
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
if (!response) {
|
|
1679
|
+
return {
|
|
1680
|
+
health_status: "dead",
|
|
1681
|
+
final_url: null,
|
|
1682
|
+
redirect_chain: [],
|
|
1683
|
+
outbound_links: [],
|
|
1684
|
+
http_status: null,
|
|
1685
|
+
ip_address: ipAddress,
|
|
1686
|
+
page_title: null,
|
|
1687
|
+
meta_description: null,
|
|
1688
|
+
confidence_score: 0,
|
|
1689
|
+
matched_keywords: [],
|
|
1690
|
+
detection_notes: lastError ? `Koneksi gagal: ${lastError}` : "Domain tidak merespon",
|
|
1691
|
+
trustpositif_blocked: false
|
|
1692
|
+
};
|
|
1693
|
+
}
|
|
1694
|
+
const $ = cheerio2.load(response.body);
|
|
1695
|
+
const titleText = $("title").first().text().trim();
|
|
1696
|
+
const titleLower = titleText.toLowerCase();
|
|
1697
|
+
const bodyLower = response.body.slice(0, 4e4).toLowerCase();
|
|
1698
|
+
const ispBlock = detectIspBlock(response.finalUrl, titleText, bodyLower, ipAddress);
|
|
1699
|
+
if (ispBlock) {
|
|
1700
|
+
return {
|
|
1701
|
+
health_status: "blocked_isp",
|
|
1702
|
+
final_url: response.finalUrl,
|
|
1703
|
+
redirect_chain: response.chain,
|
|
1704
|
+
outbound_links: [],
|
|
1705
|
+
http_status: response.status,
|
|
1706
|
+
ip_address: ipAddress,
|
|
1707
|
+
page_title: titleText || null,
|
|
1708
|
+
meta_description: null,
|
|
1709
|
+
confidence_score: 0,
|
|
1710
|
+
matched_keywords: [],
|
|
1711
|
+
detection_notes: ispBlock,
|
|
1712
|
+
trustpositif_blocked: true
|
|
1713
|
+
};
|
|
1714
|
+
}
|
|
1715
|
+
const cfChallenge = detectCloudflareChallenge(response.status, response.headers, bodyLower, titleLower);
|
|
1716
|
+
if (cfChallenge) {
|
|
1717
|
+
return {
|
|
1718
|
+
health_status: "cf_challenge",
|
|
1719
|
+
final_url: response.finalUrl,
|
|
1720
|
+
redirect_chain: response.chain,
|
|
1721
|
+
outbound_links: [],
|
|
1722
|
+
http_status: response.status,
|
|
1723
|
+
ip_address: ipAddress,
|
|
1724
|
+
page_title: titleText || null,
|
|
1725
|
+
meta_description: null,
|
|
1726
|
+
confidence_score: 0,
|
|
1727
|
+
matched_keywords: [],
|
|
1728
|
+
detection_notes: cfChallenge,
|
|
1729
|
+
trustpositif_blocked: false
|
|
1730
|
+
};
|
|
1731
|
+
}
|
|
1732
|
+
if (response.status === 404 || response.status === 410 || response.status >= 500) {
|
|
1733
|
+
return {
|
|
1734
|
+
health_status: "dead",
|
|
1735
|
+
final_url: response.finalUrl,
|
|
1736
|
+
redirect_chain: response.chain,
|
|
1737
|
+
outbound_links: [],
|
|
1738
|
+
http_status: response.status,
|
|
1739
|
+
ip_address: ipAddress,
|
|
1740
|
+
page_title: titleText || null,
|
|
1741
|
+
meta_description: null,
|
|
1742
|
+
confidence_score: 0,
|
|
1743
|
+
matched_keywords: [],
|
|
1744
|
+
detection_notes: `HTTP status ${response.status}`,
|
|
1745
|
+
trustpositif_blocked: false
|
|
1746
|
+
};
|
|
1747
|
+
}
|
|
1748
|
+
const parking = detectParking(response.finalUrl, titleLower, bodyLower);
|
|
1749
|
+
if (parking) {
|
|
1750
|
+
return {
|
|
1751
|
+
health_status: "parked",
|
|
1752
|
+
final_url: response.finalUrl,
|
|
1753
|
+
redirect_chain: response.chain,
|
|
1754
|
+
outbound_links: [],
|
|
1755
|
+
http_status: response.status,
|
|
1756
|
+
ip_address: ipAddress,
|
|
1757
|
+
page_title: titleText || null,
|
|
1758
|
+
meta_description: null,
|
|
1759
|
+
confidence_score: 0,
|
|
1760
|
+
matched_keywords: [],
|
|
1761
|
+
detection_notes: parking,
|
|
1762
|
+
trustpositif_blocked: false
|
|
1763
|
+
};
|
|
1764
|
+
}
|
|
1765
|
+
const scored = scoreHtml(
|
|
1766
|
+
response.body,
|
|
1767
|
+
domain.normalized_domain,
|
|
1768
|
+
response.finalUrl,
|
|
1769
|
+
deps.keywords
|
|
1770
|
+
);
|
|
1771
|
+
const outboundLinks = extractOutboundLinks(
|
|
1772
|
+
response.body,
|
|
1773
|
+
response.finalUrl,
|
|
1774
|
+
domain.normalized_domain,
|
|
1775
|
+
deps.blacklistSet
|
|
1776
|
+
);
|
|
1777
|
+
return {
|
|
1778
|
+
health_status: "alive",
|
|
1779
|
+
final_url: response.finalUrl,
|
|
1780
|
+
redirect_chain: response.chain,
|
|
1781
|
+
outbound_links: outboundLinks,
|
|
1782
|
+
http_status: response.status,
|
|
1783
|
+
ip_address: ipAddress,
|
|
1784
|
+
page_title: scored.title,
|
|
1785
|
+
meta_description: scored.meta_description,
|
|
1786
|
+
confidence_score: scored.confidence_score,
|
|
1787
|
+
matched_keywords: scored.matched_keywords,
|
|
1788
|
+
detection_notes: scored.signals.length > 0 ? `Sinyal: ${scored.signals.join(", ")}` : null,
|
|
1789
|
+
trustpositif_blocked: false
|
|
1790
|
+
};
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
// src/services/pivoter.ts
|
|
1794
|
+
var insecureAgent2 = new Agent2({ connect: { rejectUnauthorized: false } });
|
|
1795
|
+
async function defaultFetch2(url, init) {
|
|
1796
|
+
return undiciFetch2(url, {
|
|
1797
|
+
...init,
|
|
1798
|
+
dispatcher: insecureAgent2
|
|
1799
|
+
});
|
|
1800
|
+
}
|
|
1801
|
+
function isSharedCdnIp(ip) {
|
|
1802
|
+
if (!ip) return true;
|
|
1803
|
+
return KNOWN_CDN_IPS_PREFIXES.some((prefix) => ip.startsWith(prefix));
|
|
1804
|
+
}
|
|
1805
|
+
function extractBrandKeyword(seed) {
|
|
1806
|
+
const clean = seed.trim().toLowerCase().replace(/^https?:\/\//, "").replace(/^www\./, "").split("/")[0] ?? "";
|
|
1807
|
+
if (clean.includes(".")) {
|
|
1808
|
+
return clean.split(".")[0] || clean;
|
|
1809
|
+
}
|
|
1810
|
+
return clean;
|
|
1811
|
+
}
|
|
1812
|
+
async function pivotCrtSh(seed, blacklistSet, fetchFn = defaultFetch2) {
|
|
1813
|
+
const logs = [];
|
|
1814
|
+
const candidates = [];
|
|
1815
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1816
|
+
const queryTerm = extractBrandKeyword(seed);
|
|
1817
|
+
if (!queryTerm || queryTerm.length < 3) {
|
|
1818
|
+
return { candidates: [], logs: ["CRT.sh skipped: keyword must be at least 3 characters"] };
|
|
1819
|
+
}
|
|
1820
|
+
const url = `https://crt.sh/?q=${encodeURIComponent(`%${queryTerm}%`)}&output=json`;
|
|
1821
|
+
let body = "";
|
|
1822
|
+
let lastStatus = 0;
|
|
1823
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1824
|
+
const controller = new AbortController();
|
|
1825
|
+
const timer = setTimeout(() => controller.abort(), 2e4);
|
|
1826
|
+
try {
|
|
1827
|
+
const resp = await fetchFn(url, {
|
|
1828
|
+
method: "GET",
|
|
1829
|
+
signal: controller.signal,
|
|
1830
|
+
headers: {
|
|
1831
|
+
"User-Agent": CHROME_USER_AGENT,
|
|
1832
|
+
Accept: "application/json"
|
|
1833
|
+
}
|
|
1834
|
+
});
|
|
1835
|
+
lastStatus = resp.status;
|
|
1836
|
+
if (resp.status === 200) {
|
|
1837
|
+
body = await resp.text();
|
|
1838
|
+
break;
|
|
1839
|
+
}
|
|
1840
|
+
if (resp.status === 502 || resp.status === 503 || resp.status === 429) {
|
|
1841
|
+
await new Promise((r) => setTimeout(r, 1e3));
|
|
1842
|
+
continue;
|
|
1843
|
+
}
|
|
1844
|
+
logs.push(`CRT.sh HTTP ${resp.status}`);
|
|
1845
|
+
return { candidates, logs };
|
|
1846
|
+
} catch (err) {
|
|
1847
|
+
if (attempt === 1) {
|
|
1848
|
+
logs.push(`CRT.sh failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1849
|
+
return { candidates, logs };
|
|
1850
|
+
}
|
|
1851
|
+
} finally {
|
|
1852
|
+
clearTimeout(timer);
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
if (!body) {
|
|
1856
|
+
logs.push(`CRT.sh returned no data (HTTP ${lastStatus})`);
|
|
1857
|
+
return { candidates, logs };
|
|
1858
|
+
}
|
|
1859
|
+
try {
|
|
1860
|
+
const entries = JSON.parse(body);
|
|
1861
|
+
for (const entry of entries) {
|
|
1862
|
+
const rawNames = [entry.common_name ?? "", ...(entry.name_value ?? "").split("\n")];
|
|
1863
|
+
for (const raw of rawNames) {
|
|
1864
|
+
const norm = normalizeCandidate(raw, blacklistSet);
|
|
1865
|
+
if (norm.ok && !seen.has(norm.normalized_domain)) {
|
|
1866
|
+
seen.add(norm.normalized_domain);
|
|
1867
|
+
candidates.push({
|
|
1868
|
+
normalized_domain: norm.normalized_domain,
|
|
1869
|
+
original_url: norm.original_url,
|
|
1870
|
+
source_type: "seed_crtsh"
|
|
1871
|
+
});
|
|
1872
|
+
}
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
logs.push(`CRT.sh: found ${candidates.length} unique domains for "${queryTerm}"`);
|
|
1876
|
+
} catch {
|
|
1877
|
+
logs.push("CRT.sh returned non-JSON response");
|
|
1878
|
+
}
|
|
1879
|
+
return { candidates, logs };
|
|
1880
|
+
}
|
|
1881
|
+
async function pivotUrlScan(seed, options, blacklistSet, fetchFn = defaultFetch2) {
|
|
1882
|
+
const logs = [];
|
|
1883
|
+
const candidates = [];
|
|
1884
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1885
|
+
const brand = extractBrandKeyword(seed);
|
|
1886
|
+
const hasApiKey = Boolean(options.apiKey && options.apiKey.trim());
|
|
1887
|
+
const queries = [];
|
|
1888
|
+
if (seed.includes(".")) {
|
|
1889
|
+
const cleanDomain = seed.replace(/^https?:\/\//i, "").split("/")[0] ?? seed;
|
|
1890
|
+
queries.push(
|
|
1891
|
+
hasApiKey ? `domain:*${brand}* OR page.domain:${cleanDomain}` : `page.domain:${cleanDomain} OR domain:${cleanDomain}`
|
|
1892
|
+
);
|
|
1893
|
+
} else if (brand) {
|
|
1894
|
+
queries.push(
|
|
1895
|
+
hasApiKey ? `domain:*${brand}* OR page.title:"${brand}"` : `page.title:"${brand}"`
|
|
1896
|
+
);
|
|
1897
|
+
}
|
|
1898
|
+
if (options.knownIp && !isSharedCdnIp(options.knownIp)) {
|
|
1899
|
+
queries.push(`page.ip:${options.knownIp}`);
|
|
1900
|
+
}
|
|
1901
|
+
if (options.knownTitle && options.knownTitle.trim().length >= 8) {
|
|
1902
|
+
const safeTitle = options.knownTitle.replace(/["\\]/g, "").slice(0, 60);
|
|
1903
|
+
queries.push(`page.title:"${safeTitle}"`);
|
|
1904
|
+
}
|
|
1905
|
+
const headers = {
|
|
1906
|
+
"User-Agent": CHROME_USER_AGENT,
|
|
1907
|
+
Accept: "application/json"
|
|
1908
|
+
};
|
|
1909
|
+
if (hasApiKey && options.apiKey) {
|
|
1910
|
+
headers["API-Key"] = options.apiKey.trim();
|
|
1911
|
+
}
|
|
1912
|
+
for (const q of queries.slice(0, 2)) {
|
|
1913
|
+
const url = `https://urlscan.io/api/v1/search/?q=${encodeURIComponent(q)}&size=100`;
|
|
1914
|
+
const controller = new AbortController();
|
|
1915
|
+
const timer = setTimeout(() => controller.abort(), 15e3);
|
|
1916
|
+
try {
|
|
1917
|
+
const resp = await fetchFn(url, {
|
|
1918
|
+
method: "GET",
|
|
1919
|
+
signal: controller.signal,
|
|
1920
|
+
headers
|
|
1921
|
+
});
|
|
1922
|
+
if (resp.status === 429) {
|
|
1923
|
+
const resetAfter = resp.headers.get("X-Rate-Limit-Reset-After") ?? "60";
|
|
1924
|
+
logs.push(`URLScan.io rate limit (429), resets in ${resetAfter}s`);
|
|
1925
|
+
break;
|
|
1926
|
+
}
|
|
1927
|
+
if (resp.status === 403) {
|
|
1928
|
+
logs.push(
|
|
1929
|
+
`URLScan.io HTTP 403 for "${q}" (add a free URLScan API Key in Settings for wildcard search)`
|
|
1930
|
+
);
|
|
1931
|
+
continue;
|
|
1932
|
+
}
|
|
1933
|
+
if (resp.status !== 200) {
|
|
1934
|
+
logs.push(`URLScan.io HTTP ${resp.status} for query "${q}"`);
|
|
1935
|
+
continue;
|
|
1936
|
+
}
|
|
1937
|
+
const data = JSON.parse(await resp.text());
|
|
1938
|
+
for (const item of data.results ?? []) {
|
|
1939
|
+
const raw = item.page?.url ?? item.page?.domain ?? item.task?.url ?? "";
|
|
1940
|
+
const norm = normalizeCandidate(raw, blacklistSet);
|
|
1941
|
+
if (norm.ok && !seen.has(norm.normalized_domain)) {
|
|
1942
|
+
seen.add(norm.normalized_domain);
|
|
1943
|
+
candidates.push({
|
|
1944
|
+
normalized_domain: norm.normalized_domain,
|
|
1945
|
+
original_url: norm.original_url,
|
|
1946
|
+
source_type: "seed_urlscan"
|
|
1947
|
+
});
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
} catch (err) {
|
|
1951
|
+
logs.push(`URLScan.io failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1952
|
+
} finally {
|
|
1953
|
+
clearTimeout(timer);
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
logs.push(`URLScan.io: found ${candidates.length} unique domains`);
|
|
1957
|
+
return { candidates, logs };
|
|
1958
|
+
}
|
|
1959
|
+
async function pivotHtmlAmp(seed, blacklistSet, fetchFn = defaultFetch2) {
|
|
1960
|
+
const logs = [];
|
|
1961
|
+
const candidates = [];
|
|
1962
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1963
|
+
const seedNorm = normalizeCandidate(seed, /* @__PURE__ */ new Set());
|
|
1964
|
+
if (!seedNorm.ok) {
|
|
1965
|
+
return { candidates: [], logs: ["HTML/AMP Extractor skipped: seed is not a URL or domain"] };
|
|
1966
|
+
}
|
|
1967
|
+
let currentUrl = seedNorm.original_url;
|
|
1968
|
+
let finalHtml = "";
|
|
1969
|
+
let finalStatus = 0;
|
|
1970
|
+
for (let hop = 0; hop < 8; hop++) {
|
|
1971
|
+
const controller = new AbortController();
|
|
1972
|
+
const timer = setTimeout(() => controller.abort(), 12e3);
|
|
1973
|
+
try {
|
|
1974
|
+
const resp = await fetchFn(currentUrl, {
|
|
1975
|
+
method: "GET",
|
|
1976
|
+
redirect: "manual",
|
|
1977
|
+
signal: controller.signal,
|
|
1978
|
+
headers: {
|
|
1979
|
+
"User-Agent": CHROME_USER_AGENT,
|
|
1980
|
+
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
|
1981
|
+
"Accept-Language": "id-ID,id;q=0.9,en-US;q=0.8"
|
|
1982
|
+
}
|
|
1983
|
+
});
|
|
1984
|
+
finalStatus = resp.status;
|
|
1985
|
+
if (resp.status >= 300 && resp.status < 400) {
|
|
1986
|
+
const loc = resp.headers.get("location");
|
|
1987
|
+
if (loc) {
|
|
1988
|
+
currentUrl = new URL(loc, currentUrl).toString();
|
|
1989
|
+
const hopNorm = normalizeCandidate(currentUrl, blacklistSet);
|
|
1990
|
+
if (hopNorm.ok && !seen.has(hopNorm.normalized_domain)) {
|
|
1991
|
+
seen.add(hopNorm.normalized_domain);
|
|
1992
|
+
candidates.push({
|
|
1993
|
+
normalized_domain: hopNorm.normalized_domain,
|
|
1994
|
+
original_url: currentUrl,
|
|
1995
|
+
source_type: "seed_html"
|
|
1996
|
+
});
|
|
1997
|
+
}
|
|
1998
|
+
continue;
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
finalHtml = await resp.text();
|
|
2002
|
+
break;
|
|
2003
|
+
} catch (err) {
|
|
2004
|
+
logs.push(`HTML Extractor failed (${currentUrl}): ${err instanceof Error ? err.message : String(err)}`);
|
|
2005
|
+
return { candidates, logs };
|
|
2006
|
+
} finally {
|
|
2007
|
+
clearTimeout(timer);
|
|
2008
|
+
}
|
|
2009
|
+
}
|
|
2010
|
+
const seedFiltered = normalizeCandidate(seedNorm.original_url, blacklistSet);
|
|
2011
|
+
if (seedFiltered.ok && !seen.has(seedFiltered.normalized_domain)) {
|
|
2012
|
+
seen.add(seedFiltered.normalized_domain);
|
|
2013
|
+
candidates.push({
|
|
2014
|
+
normalized_domain: seedFiltered.normalized_domain,
|
|
2015
|
+
original_url: seedFiltered.original_url,
|
|
2016
|
+
source_type: "seed_html"
|
|
2017
|
+
});
|
|
2018
|
+
}
|
|
2019
|
+
if (finalHtml) {
|
|
2020
|
+
const links = extractOutboundLinks(
|
|
2021
|
+
finalHtml,
|
|
2022
|
+
currentUrl,
|
|
2023
|
+
seedNorm.normalized_domain,
|
|
2024
|
+
blacklistSet
|
|
2025
|
+
);
|
|
2026
|
+
for (const link of links) {
|
|
2027
|
+
if (!seen.has(link.normalized_domain)) {
|
|
2028
|
+
seen.add(link.normalized_domain);
|
|
2029
|
+
candidates.push({
|
|
2030
|
+
normalized_domain: link.normalized_domain,
|
|
2031
|
+
original_url: link.url,
|
|
2032
|
+
source_type: "seed_html"
|
|
2033
|
+
});
|
|
2034
|
+
}
|
|
2035
|
+
}
|
|
2036
|
+
logs.push(
|
|
2037
|
+
`HTML/Redirect/AMP (HTTP ${finalStatus}): extracted ${candidates.length} outbound domains`
|
|
2038
|
+
);
|
|
2039
|
+
}
|
|
2040
|
+
return { candidates, logs };
|
|
2041
|
+
}
|
|
2042
|
+
async function runSeedPivotSources(seed, sources, options, blacklistSet, fetchFn = defaultFetch2) {
|
|
2043
|
+
const tasks = [];
|
|
2044
|
+
if (sources.includes("crtsh")) {
|
|
2045
|
+
tasks.push(pivotCrtSh(seed, blacklistSet, fetchFn));
|
|
2046
|
+
}
|
|
2047
|
+
if (sources.includes("urlscan")) {
|
|
2048
|
+
tasks.push(pivotUrlScan(seed, options, blacklistSet, fetchFn));
|
|
2049
|
+
}
|
|
2050
|
+
if (sources.includes("html")) {
|
|
2051
|
+
tasks.push(pivotHtmlAmp(seed, blacklistSet, fetchFn));
|
|
2052
|
+
}
|
|
2053
|
+
const settled = await Promise.all(tasks);
|
|
2054
|
+
const merged = [];
|
|
2055
|
+
const logs = [];
|
|
2056
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2057
|
+
for (const res of settled) {
|
|
2058
|
+
logs.push(...res.logs);
|
|
2059
|
+
for (const c of res.candidates) {
|
|
2060
|
+
if (!seen.has(c.normalized_domain)) {
|
|
2061
|
+
seen.add(c.normalized_domain);
|
|
2062
|
+
merged.push(c);
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
}
|
|
2066
|
+
return { candidates: merged, logs };
|
|
2067
|
+
}
|
|
2068
|
+
|
|
2069
|
+
// src/services/jobs.ts
|
|
2070
|
+
var JobManager = class {
|
|
2071
|
+
db;
|
|
2072
|
+
trustPositif;
|
|
2073
|
+
subscribers = /* @__PURE__ */ new Set();
|
|
2074
|
+
activeTasks = /* @__PURE__ */ new Set();
|
|
2075
|
+
constructor(db, trustPositif) {
|
|
2076
|
+
this.db = db;
|
|
2077
|
+
this.trustPositif = trustPositif;
|
|
2078
|
+
}
|
|
2079
|
+
subscribe(fn) {
|
|
2080
|
+
this.subscribers.add(fn);
|
|
2081
|
+
return () => {
|
|
2082
|
+
this.subscribers.delete(fn);
|
|
2083
|
+
};
|
|
2084
|
+
}
|
|
2085
|
+
emit(event) {
|
|
2086
|
+
for (const sub of this.subscribers) {
|
|
2087
|
+
try {
|
|
2088
|
+
sub(event);
|
|
2089
|
+
} catch {
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
}
|
|
2093
|
+
emitJob(jobId) {
|
|
2094
|
+
const job = this.db.getJob(jobId);
|
|
2095
|
+
if (job) {
|
|
2096
|
+
this.emit({ type: "job_update", job });
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
emitCounts() {
|
|
2100
|
+
this.emit({ type: "stats_update", counts: this.db.getQueueCounts() });
|
|
2101
|
+
}
|
|
2102
|
+
track(promise) {
|
|
2103
|
+
this.activeTasks.add(promise);
|
|
2104
|
+
promise.finally(() => {
|
|
2105
|
+
this.activeTasks.delete(promise);
|
|
2106
|
+
});
|
|
2107
|
+
}
|
|
2108
|
+
async waitForIdle() {
|
|
2109
|
+
await Promise.allSettled(Array.from(this.activeTasks));
|
|
2110
|
+
}
|
|
2111
|
+
startValidationJob(domainIds, targetLabel = "Bulk Validation") {
|
|
2112
|
+
const id = crypto.randomUUID().slice(0, 8);
|
|
2113
|
+
const job = this.db.createJob(id, "validate", targetLabel, domainIds.length);
|
|
2114
|
+
this.emitJob(id);
|
|
2115
|
+
this.track(this.runValidationPool(id, domainIds));
|
|
2116
|
+
return job;
|
|
2117
|
+
}
|
|
2118
|
+
startPivotJob(input) {
|
|
2119
|
+
const id = crypto.randomUUID().slice(0, 8);
|
|
2120
|
+
const job = this.db.createJob(id, "pivot", input.seed, 0);
|
|
2121
|
+
this.emitJob(id);
|
|
2122
|
+
this.track(this.runPivotPipeline(id, input));
|
|
2123
|
+
return job;
|
|
2124
|
+
}
|
|
2125
|
+
startTrustPositifSyncJob(sourceUrl) {
|
|
2126
|
+
const id = crypto.randomUUID().slice(0, 8);
|
|
2127
|
+
const job = this.db.createJob(id, "trustpositif_sync", sourceUrl, 1);
|
|
2128
|
+
this.emitJob(id);
|
|
2129
|
+
this.track(
|
|
2130
|
+
(async () => {
|
|
2131
|
+
try {
|
|
2132
|
+
this.db.appendJobLog(id, `Downloading blocklist from ${sourceUrl}...`);
|
|
2133
|
+
this.emitJob(id);
|
|
2134
|
+
const result = await this.trustPositif.syncBlocklist(sourceUrl);
|
|
2135
|
+
this.db.appendJobLog(id, `Synced ${result.count} TrustPositif domains.`);
|
|
2136
|
+
this.db.updateJob(id, {
|
|
2137
|
+
status: "completed",
|
|
2138
|
+
processed_items: 1,
|
|
2139
|
+
found_new: result.count,
|
|
2140
|
+
finished: true
|
|
2141
|
+
});
|
|
2142
|
+
} catch (err) {
|
|
2143
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2144
|
+
this.db.appendJobLog(id, `Sync failed: ${msg}`);
|
|
2145
|
+
this.db.updateJob(id, {
|
|
2146
|
+
status: "failed",
|
|
2147
|
+
error_message: msg,
|
|
2148
|
+
finished: true
|
|
2149
|
+
});
|
|
2150
|
+
}
|
|
2151
|
+
this.emitJob(id);
|
|
2152
|
+
})()
|
|
2153
|
+
);
|
|
2154
|
+
return job;
|
|
2155
|
+
}
|
|
2156
|
+
async runPivotPipeline(jobId, input) {
|
|
2157
|
+
try {
|
|
2158
|
+
const settings = this.db.getSettings();
|
|
2159
|
+
const blacklistSet = this.db.getBlacklistSet();
|
|
2160
|
+
this.db.appendJobLog(
|
|
2161
|
+
jobId,
|
|
2162
|
+
`Starting Seed Pivot "${input.seed}" [${input.sources.join(", ")}]`
|
|
2163
|
+
);
|
|
2164
|
+
this.emitJob(jobId);
|
|
2165
|
+
const pivotRes = await runSeedPivotSources(
|
|
2166
|
+
input.seed,
|
|
2167
|
+
input.sources,
|
|
2168
|
+
{
|
|
2169
|
+
apiKey: settings.urlscan_api_key,
|
|
2170
|
+
knownIp: input.knownIp,
|
|
2171
|
+
knownTitle: input.knownTitle
|
|
2172
|
+
},
|
|
2173
|
+
blacklistSet
|
|
2174
|
+
);
|
|
2175
|
+
for (const line of pivotRes.logs) {
|
|
2176
|
+
this.db.appendJobLog(jobId, line);
|
|
2177
|
+
}
|
|
2178
|
+
const newIds = [];
|
|
2179
|
+
let duplicates = 0;
|
|
2180
|
+
for (const c of pivotRes.candidates) {
|
|
2181
|
+
const res = this.db.insertDomainIgnore({
|
|
2182
|
+
normalized_domain: c.normalized_domain,
|
|
2183
|
+
original_url: c.original_url,
|
|
2184
|
+
source_type: c.source_type,
|
|
2185
|
+
source_seed: input.seed
|
|
2186
|
+
});
|
|
2187
|
+
if (res.inserted && res.id !== null) {
|
|
2188
|
+
newIds.push(res.id);
|
|
2189
|
+
} else {
|
|
2190
|
+
duplicates++;
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
this.db.updateJob(jobId, {
|
|
2194
|
+
total_items: newIds.length,
|
|
2195
|
+
found_new: newIds.length,
|
|
2196
|
+
skipped_duplicate: duplicates
|
|
2197
|
+
});
|
|
2198
|
+
this.db.appendJobLog(
|
|
2199
|
+
jobId,
|
|
2200
|
+
`Pivot result: ${newIds.length} new domain(s) queued, ${duplicates} duplicate(s) skipped.`
|
|
2201
|
+
);
|
|
2202
|
+
this.emitJob(jobId);
|
|
2203
|
+
this.emitCounts();
|
|
2204
|
+
await this.runValidationPool(jobId, newIds);
|
|
2205
|
+
} catch (err) {
|
|
2206
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2207
|
+
this.db.appendJobLog(jobId, `Pivot error: ${msg}`);
|
|
2208
|
+
this.db.updateJob(jobId, {
|
|
2209
|
+
status: "failed",
|
|
2210
|
+
error_message: msg,
|
|
2211
|
+
finished: true
|
|
2212
|
+
});
|
|
2213
|
+
this.emitJob(jobId);
|
|
2214
|
+
}
|
|
2215
|
+
}
|
|
2216
|
+
async runValidationPool(jobId, domainIds) {
|
|
2217
|
+
if (domainIds.length === 0) {
|
|
2218
|
+
this.db.updateJob(jobId, { status: "completed", finished: true });
|
|
2219
|
+
this.emitJob(jobId);
|
|
2220
|
+
this.emitCounts();
|
|
2221
|
+
return;
|
|
2222
|
+
}
|
|
2223
|
+
const settings = this.db.getSettings();
|
|
2224
|
+
const keywords = this.db.listKeywords(true);
|
|
2225
|
+
const blacklistSet = this.db.getBlacklistSet();
|
|
2226
|
+
const concurrency = Math.max(1, settings.concurrency);
|
|
2227
|
+
let index = 0;
|
|
2228
|
+
let processed = 0;
|
|
2229
|
+
const worker = async () => {
|
|
2230
|
+
while (index < domainIds.length) {
|
|
2231
|
+
const currentIdx = index++;
|
|
2232
|
+
const domainId = domainIds[currentIdx];
|
|
2233
|
+
if (domainId === void 0) break;
|
|
2234
|
+
const row = this.db.getDomainById(domainId);
|
|
2235
|
+
if (!row) {
|
|
2236
|
+
processed++;
|
|
2237
|
+
continue;
|
|
2238
|
+
}
|
|
2239
|
+
this.db.markDomainChecking(domainId);
|
|
2240
|
+
try {
|
|
2241
|
+
const result = await validateDomain(row, {
|
|
2242
|
+
settings,
|
|
2243
|
+
keywords,
|
|
2244
|
+
blacklistSet,
|
|
2245
|
+
trustPositif: this.trustPositif
|
|
2246
|
+
});
|
|
2247
|
+
const updated = this.db.updateDomainValidation(domainId, result);
|
|
2248
|
+
if (updated) {
|
|
2249
|
+
this.emit({ type: "domain_update", domain: updated });
|
|
2250
|
+
}
|
|
2251
|
+
} catch (err) {
|
|
2252
|
+
const updated = this.db.updateDomainValidation(domainId, {
|
|
2253
|
+
health_status: "dead",
|
|
2254
|
+
final_url: null,
|
|
2255
|
+
redirect_chain: [],
|
|
2256
|
+
outbound_links: [],
|
|
2257
|
+
http_status: null,
|
|
2258
|
+
ip_address: null,
|
|
2259
|
+
page_title: null,
|
|
2260
|
+
meta_description: null,
|
|
2261
|
+
confidence_score: 0,
|
|
2262
|
+
matched_keywords: [],
|
|
2263
|
+
detection_notes: err instanceof Error ? err.message : "Validation failed",
|
|
2264
|
+
trustpositif_blocked: false
|
|
2265
|
+
});
|
|
2266
|
+
if (updated) {
|
|
2267
|
+
this.emit({ type: "domain_update", domain: updated });
|
|
2268
|
+
}
|
|
2269
|
+
}
|
|
2270
|
+
processed++;
|
|
2271
|
+
if (processed % 3 === 0 || processed === domainIds.length) {
|
|
2272
|
+
this.db.updateJob(jobId, { processed_items: processed });
|
|
2273
|
+
this.emitJob(jobId);
|
|
2274
|
+
this.emitCounts();
|
|
2275
|
+
}
|
|
2276
|
+
}
|
|
2277
|
+
};
|
|
2278
|
+
const workers = Array.from({ length: Math.min(concurrency, domainIds.length) }, () => worker());
|
|
2279
|
+
await Promise.all(workers);
|
|
2280
|
+
this.db.appendJobLog(jobId, `Validation finished (${processed}/${domainIds.length} domains).`);
|
|
2281
|
+
this.db.updateJob(jobId, {
|
|
2282
|
+
status: "completed",
|
|
2283
|
+
processed_items: processed,
|
|
2284
|
+
finished: true
|
|
2285
|
+
});
|
|
2286
|
+
this.emitJob(jobId);
|
|
2287
|
+
this.emitCounts();
|
|
2288
|
+
}
|
|
2289
|
+
};
|
|
2290
|
+
|
|
2291
|
+
// src/services/trustpositif.ts
|
|
2292
|
+
import { Resolver } from "dns/promises";
|
|
2293
|
+
import { parse as parse2 } from "tldts";
|
|
2294
|
+
var BLOCK_CNAME_MARKERS = [
|
|
2295
|
+
"internetpositif",
|
|
2296
|
+
"trustpositif",
|
|
2297
|
+
"lamanlabuh",
|
|
2298
|
+
"blockpage",
|
|
2299
|
+
"nawala",
|
|
2300
|
+
"mercusuar",
|
|
2301
|
+
"aduankonten"
|
|
2302
|
+
];
|
|
2303
|
+
async function defaultDnsLookup(domain, dnsServer) {
|
|
2304
|
+
const resolver = new Resolver();
|
|
2305
|
+
resolver.setServers([dnsServer]);
|
|
2306
|
+
const [ipsRes, cnameRes] = await Promise.allSettled([
|
|
2307
|
+
resolver.resolve4(domain),
|
|
2308
|
+
resolver.resolveCname(domain)
|
|
2309
|
+
]);
|
|
2310
|
+
return {
|
|
2311
|
+
ips: ipsRes.status === "fulfilled" ? ipsRes.value : [],
|
|
2312
|
+
cnames: cnameRes.status === "fulfilled" ? cnameRes.value : []
|
|
2313
|
+
};
|
|
2314
|
+
}
|
|
2315
|
+
var TrustPositifService = class {
|
|
2316
|
+
blockedSet;
|
|
2317
|
+
db;
|
|
2318
|
+
constructor(db) {
|
|
2319
|
+
this.db = db;
|
|
2320
|
+
this.blockedSet = db.loadTrustPositifSet();
|
|
2321
|
+
}
|
|
2322
|
+
refreshFromDb() {
|
|
2323
|
+
this.blockedSet = this.db.loadTrustPositifSet();
|
|
2324
|
+
}
|
|
2325
|
+
getCount() {
|
|
2326
|
+
return this.blockedSet.size;
|
|
2327
|
+
}
|
|
2328
|
+
isLocallyBlocked(domain) {
|
|
2329
|
+
const clean = domain.toLowerCase().trim();
|
|
2330
|
+
if (this.blockedSet.has(clean)) return true;
|
|
2331
|
+
const parsed = parse2(clean, { allowPrivateDomains: true });
|
|
2332
|
+
if (parsed.domain && this.blockedSet.has(parsed.domain.toLowerCase())) {
|
|
2333
|
+
return true;
|
|
2334
|
+
}
|
|
2335
|
+
return false;
|
|
2336
|
+
}
|
|
2337
|
+
async checkIndonesianDns(domain, dnsServer, timeoutMs = 2500, lookupFn = defaultDnsLookup) {
|
|
2338
|
+
if (!dnsServer.trim()) {
|
|
2339
|
+
return { blocked: false, reason: null, resolved_ips: [] };
|
|
2340
|
+
}
|
|
2341
|
+
try {
|
|
2342
|
+
const result = await Promise.race([
|
|
2343
|
+
lookupFn(domain, dnsServer.trim()),
|
|
2344
|
+
new Promise((resolve) => setTimeout(() => resolve(null), timeoutMs))
|
|
2345
|
+
]);
|
|
2346
|
+
if (!result) {
|
|
2347
|
+
return { blocked: false, reason: null, resolved_ips: [] };
|
|
2348
|
+
}
|
|
2349
|
+
for (const cname of result.cnames) {
|
|
2350
|
+
const lower = cname.toLowerCase();
|
|
2351
|
+
if (BLOCK_CNAME_MARKERS.some((marker) => lower.includes(marker))) {
|
|
2352
|
+
return {
|
|
2353
|
+
blocked: true,
|
|
2354
|
+
reason: `DNS filter CNAME redirect: ${cname}`,
|
|
2355
|
+
resolved_ips: result.ips
|
|
2356
|
+
};
|
|
2357
|
+
}
|
|
2358
|
+
}
|
|
2359
|
+
for (const ip of result.ips) {
|
|
2360
|
+
if (ISP_SINKHOLE_IPS.has(ip)) {
|
|
2361
|
+
return {
|
|
2362
|
+
blocked: true,
|
|
2363
|
+
reason: `DNS filter sinkhole IP (${dnsServer}): ${ip}`,
|
|
2364
|
+
resolved_ips: result.ips
|
|
2365
|
+
};
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
return { blocked: false, reason: null, resolved_ips: result.ips };
|
|
2369
|
+
} catch {
|
|
2370
|
+
return { blocked: false, reason: null, resolved_ips: [] };
|
|
2371
|
+
}
|
|
2372
|
+
}
|
|
2373
|
+
async syncBlocklist(sourceUrl, fetchFn = fetch) {
|
|
2374
|
+
const controller = new AbortController();
|
|
2375
|
+
const timer = setTimeout(() => controller.abort(), 3e4);
|
|
2376
|
+
try {
|
|
2377
|
+
const resp = await fetchFn(sourceUrl, {
|
|
2378
|
+
signal: controller.signal,
|
|
2379
|
+
headers: { "User-Agent": `URLScanner/${APP_VERSION}` }
|
|
2380
|
+
});
|
|
2381
|
+
if (!resp.ok) {
|
|
2382
|
+
throw new Error(`TrustPositif sync HTTP ${resp.status}`);
|
|
2383
|
+
}
|
|
2384
|
+
const text = await resp.text();
|
|
2385
|
+
const domains = parseBlocklistText(text);
|
|
2386
|
+
const count = this.db.replaceTrustPositifBlocklist(domains);
|
|
2387
|
+
const syncedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2388
|
+
this.db.setSettings({
|
|
2389
|
+
trustpositif_source_url: sourceUrl,
|
|
2390
|
+
trustpositif_last_sync: syncedAt
|
|
2391
|
+
});
|
|
2392
|
+
this.refreshFromDb();
|
|
2393
|
+
return { count, synced_at: syncedAt };
|
|
2394
|
+
} finally {
|
|
2395
|
+
clearTimeout(timer);
|
|
2396
|
+
}
|
|
2397
|
+
}
|
|
2398
|
+
};
|
|
2399
|
+
function parseBlocklistText(raw) {
|
|
2400
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2401
|
+
const out = [];
|
|
2402
|
+
const lines = raw.split(/\r?\n/);
|
|
2403
|
+
for (const line of lines) {
|
|
2404
|
+
const trimmed = line.trim();
|
|
2405
|
+
if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith(";") || trimmed.startsWith("!")) {
|
|
2406
|
+
continue;
|
|
2407
|
+
}
|
|
2408
|
+
const parts = trimmed.split(/\s+/);
|
|
2409
|
+
let candidate = parts[0] ?? "";
|
|
2410
|
+
if ((candidate === "0.0.0.0" || candidate === "127.0.0.1") && parts[1]) {
|
|
2411
|
+
candidate = parts[1];
|
|
2412
|
+
}
|
|
2413
|
+
candidate = candidate.toLowerCase().replace(/^\*\./, "").replace(/\.$/, "");
|
|
2414
|
+
if (/^[a-z0-9.-]+\.[a-z]{2,24}$/.test(candidate) && !seen.has(candidate)) {
|
|
2415
|
+
seen.add(candidate);
|
|
2416
|
+
out.push(candidate);
|
|
2417
|
+
}
|
|
2418
|
+
}
|
|
2419
|
+
return out;
|
|
2420
|
+
}
|
|
2421
|
+
|
|
2422
|
+
// src/server.ts
|
|
2423
|
+
var MIME_TYPES = {
|
|
2424
|
+
".html": "text/html; charset=utf-8",
|
|
2425
|
+
".js": "application/javascript; charset=utf-8",
|
|
2426
|
+
".mjs": "application/javascript; charset=utf-8",
|
|
2427
|
+
".css": "text/css; charset=utf-8",
|
|
2428
|
+
".json": "application/json; charset=utf-8",
|
|
2429
|
+
".svg": "image/svg+xml",
|
|
2430
|
+
".png": "image/png",
|
|
2431
|
+
".jpg": "image/jpeg",
|
|
2432
|
+
".jpeg": "image/jpeg",
|
|
2433
|
+
".ico": "image/x-icon",
|
|
2434
|
+
".woff": "font/woff",
|
|
2435
|
+
".woff2": "font/woff2",
|
|
2436
|
+
".txt": "text/plain; charset=utf-8"
|
|
2437
|
+
};
|
|
2438
|
+
function resolveWebDistDir() {
|
|
2439
|
+
const here = path2.dirname(fileURLToPath(import.meta.url));
|
|
2440
|
+
const candidates = [
|
|
2441
|
+
path2.resolve(here, "web"),
|
|
2442
|
+
path2.resolve(here, "../dist/web"),
|
|
2443
|
+
path2.resolve(process.cwd(), "dist/web")
|
|
2444
|
+
];
|
|
2445
|
+
for (const dir of candidates) {
|
|
2446
|
+
if (fs2.existsSync(path2.join(dir, "index.html"))) {
|
|
2447
|
+
return dir;
|
|
2448
|
+
}
|
|
2449
|
+
}
|
|
2450
|
+
return null;
|
|
2451
|
+
}
|
|
2452
|
+
function createContext(db) {
|
|
2453
|
+
const trustPositif = new TrustPositifService(db);
|
|
2454
|
+
const jobs = new JobManager(db, trustPositif);
|
|
2455
|
+
return { db, trustPositif, jobs };
|
|
2456
|
+
}
|
|
2457
|
+
function createApp(ctx, webDistDir = resolveWebDistDir()) {
|
|
2458
|
+
const app = new Hono5();
|
|
2459
|
+
app.get("/api/health", (c) => {
|
|
2460
|
+
return c.json({
|
|
2461
|
+
status: "ok",
|
|
2462
|
+
version: APP_VERSION,
|
|
2463
|
+
counts: ctx.db.getQueueCounts()
|
|
2464
|
+
});
|
|
2465
|
+
});
|
|
2466
|
+
app.route("/api/domains", createDomainsRouter(ctx));
|
|
2467
|
+
app.route("/api/ingest", createIngestRouter(ctx));
|
|
2468
|
+
app.route("/api/jobs", createJobsRouter(ctx));
|
|
2469
|
+
app.route("/api/settings", createSettingsRouter(ctx));
|
|
2470
|
+
app.get("*", (c) => {
|
|
2471
|
+
if (c.req.path.startsWith("/api/")) {
|
|
2472
|
+
return c.json({ error: "Not found" }, 404);
|
|
2473
|
+
}
|
|
2474
|
+
if (!webDistDir) {
|
|
2475
|
+
return c.html(
|
|
2476
|
+
`<!doctype html><html><body style="font-family:sans-serif;padding:2rem;">
|
|
2477
|
+
<h1>URLScanner API Running</h1>
|
|
2478
|
+
<p>Frontend bundle belum tersedia di <code>dist/web</code>. Jalankan <code>npm run build:web</code> atau akses dev server Vite di port 5173.</p>
|
|
2479
|
+
</body></html>`,
|
|
2480
|
+
200
|
|
2481
|
+
);
|
|
2482
|
+
}
|
|
2483
|
+
const reqPath = c.req.path === "/" ? "/index.html" : c.req.path;
|
|
2484
|
+
const safeRel = path2.normalize(reqPath).replace(/^(\.\.[/\\])+/, "");
|
|
2485
|
+
const fullPath = path2.join(webDistDir, safeRel);
|
|
2486
|
+
if (fullPath.startsWith(webDistDir) && fs2.existsSync(fullPath) && fs2.statSync(fullPath).isFile()) {
|
|
2487
|
+
const ext = path2.extname(fullPath).toLowerCase();
|
|
2488
|
+
const contentType = MIME_TYPES[ext] || "application/octet-stream";
|
|
2489
|
+
const data = fs2.readFileSync(fullPath);
|
|
2490
|
+
return c.body(data, 200, { "Content-Type": contentType });
|
|
2491
|
+
}
|
|
2492
|
+
const indexHtml = fs2.readFileSync(path2.join(webDistDir, "index.html"));
|
|
2493
|
+
return c.body(indexHtml, 200, { "Content-Type": "text/html; charset=utf-8" });
|
|
2494
|
+
});
|
|
2495
|
+
return app;
|
|
2496
|
+
}
|
|
2497
|
+
function startHttpServer(app, host, port) {
|
|
2498
|
+
return new Promise((resolve, reject) => {
|
|
2499
|
+
const server = serve(
|
|
2500
|
+
{
|
|
2501
|
+
fetch: app.fetch,
|
|
2502
|
+
hostname: host,
|
|
2503
|
+
port
|
|
2504
|
+
},
|
|
2505
|
+
(info) => {
|
|
2506
|
+
resolve({ server, port: info.port });
|
|
2507
|
+
}
|
|
2508
|
+
);
|
|
2509
|
+
server.on("error", reject);
|
|
2510
|
+
});
|
|
2511
|
+
}
|
|
2512
|
+
|
|
2513
|
+
// src/tui/browser.ts
|
|
2514
|
+
import { spawn } from "child_process";
|
|
2515
|
+
function openBrowser(url) {
|
|
2516
|
+
try {
|
|
2517
|
+
const platform = process.platform;
|
|
2518
|
+
let cmd = "xdg-open";
|
|
2519
|
+
let args = [url];
|
|
2520
|
+
if (platform === "darwin") {
|
|
2521
|
+
cmd = "open";
|
|
2522
|
+
args = [url];
|
|
2523
|
+
} else if (platform === "win32") {
|
|
2524
|
+
cmd = "cmd";
|
|
2525
|
+
args = ["/c", "start", "", url];
|
|
2526
|
+
}
|
|
2527
|
+
const child = spawn(cmd, args, {
|
|
2528
|
+
detached: true,
|
|
2529
|
+
stdio: "ignore",
|
|
2530
|
+
windowsHide: true
|
|
2531
|
+
});
|
|
2532
|
+
child.unref();
|
|
2533
|
+
return true;
|
|
2534
|
+
} catch {
|
|
2535
|
+
return false;
|
|
2536
|
+
}
|
|
2537
|
+
}
|
|
2538
|
+
|
|
2539
|
+
// src/tui/ansi.ts
|
|
2540
|
+
var ANSI = {
|
|
2541
|
+
reset: "\x1B[0m",
|
|
2542
|
+
bold: "\x1B[1m",
|
|
2543
|
+
dim: "\x1B[2m",
|
|
2544
|
+
amber: "\x1B[38;5;209m",
|
|
2545
|
+
brand: "\x1B[38;5;43m",
|
|
2546
|
+
green: "\x1B[38;5;78m",
|
|
2547
|
+
cyan: "\x1B[38;5;37m",
|
|
2548
|
+
red: "\x1B[38;5;203m",
|
|
2549
|
+
yellow: "\x1B[38;5;221m",
|
|
2550
|
+
selectedBg: "\x1B[48;5;153m\x1B[38;5;16m",
|
|
2551
|
+
clearScreen: "\x1B[2J\x1B[H",
|
|
2552
|
+
altBufferEnter: "\x1B[?1049h",
|
|
2553
|
+
altBufferExit: "\x1B[?1049l",
|
|
2554
|
+
hideCursor: "\x1B[?25l",
|
|
2555
|
+
showCursor: "\x1B[?25h"
|
|
2556
|
+
};
|
|
2557
|
+
function padEnd(str, width) {
|
|
2558
|
+
if (str.length >= width) return str.slice(0, width - 1) + (width > 1 ? "\u2026" : "");
|
|
2559
|
+
return str + " ".repeat(width - str.length);
|
|
2560
|
+
}
|
|
2561
|
+
function padStart(str, width) {
|
|
2562
|
+
if (str.length >= width) return str.slice(0, width);
|
|
2563
|
+
return " ".repeat(width - str.length) + str;
|
|
2564
|
+
}
|
|
2565
|
+
|
|
2566
|
+
// src/tui/clipboard.ts
|
|
2567
|
+
import { spawnSync } from "child_process";
|
|
2568
|
+
function copyToClipboard(text) {
|
|
2569
|
+
const candidates = process.platform === "darwin" ? [{ cmd: "pbcopy", args: [] }] : process.platform === "win32" ? [{ cmd: "clip", args: [] }] : [
|
|
2570
|
+
{ cmd: "wl-copy", args: [] },
|
|
2571
|
+
{ cmd: "xclip", args: ["-selection", "clipboard"] },
|
|
2572
|
+
{ cmd: "xsel", args: ["--clipboard", "--input"] }
|
|
2573
|
+
];
|
|
2574
|
+
for (const c of candidates) {
|
|
2575
|
+
try {
|
|
2576
|
+
const res = spawnSync(c.cmd, c.args, {
|
|
2577
|
+
input: text,
|
|
2578
|
+
encoding: "utf8",
|
|
2579
|
+
timeout: 2e3
|
|
2580
|
+
});
|
|
2581
|
+
if (res.status === 0 && !res.error) {
|
|
2582
|
+
return true;
|
|
2583
|
+
}
|
|
2584
|
+
} catch {
|
|
2585
|
+
}
|
|
2586
|
+
}
|
|
2587
|
+
return false;
|
|
2588
|
+
}
|
|
2589
|
+
|
|
2590
|
+
// src/tui/interactive.ts
|
|
2591
|
+
async function runInteractiveTui(url, ctx) {
|
|
2592
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
2593
|
+
return "menu";
|
|
2594
|
+
}
|
|
2595
|
+
let view = "queue";
|
|
2596
|
+
let cursor = 0;
|
|
2597
|
+
let statusBanner = "Ready. Use j/k navigate, c Copy & Mark, n New Pivot, i Quick Import.";
|
|
2598
|
+
let inputMode = null;
|
|
2599
|
+
let inputBuffer = "";
|
|
2600
|
+
const loadRows = () => {
|
|
2601
|
+
return ctx.db.listDomains({
|
|
2602
|
+
view,
|
|
2603
|
+
sort: "confidence_desc",
|
|
2604
|
+
limit: 50
|
|
2605
|
+
}).items;
|
|
2606
|
+
};
|
|
2607
|
+
let rows = loadRows();
|
|
2608
|
+
const render = () => {
|
|
2609
|
+
const cols = Math.max(process.stdout.columns || 100, 76);
|
|
2610
|
+
const counts = ctx.db.getQueueCounts();
|
|
2611
|
+
if (rows.length > 0 && cursor >= rows.length) cursor = rows.length - 1;
|
|
2612
|
+
if (cursor < 0) cursor = 0;
|
|
2613
|
+
const lines = [];
|
|
2614
|
+
lines.push(
|
|
2615
|
+
`${ANSI.brand}${ANSI.bold} URLScanner Terminal UI v${APP_VERSION}${ANSI.reset} ${ANSI.dim}\u2502${ANSI.reset} ${ANSI.green}${url}${ANSI.reset}`
|
|
2616
|
+
);
|
|
2617
|
+
lines.push(
|
|
2618
|
+
` New: ${ANSI.bold}${counts.new_count}${ANSI.reset} In Progress: ${counts.claimed_count} Submitted: ${counts.submitted_count} Valid: ${counts.valid_count} CF Manual: ${counts.manual_count} Archive: ${counts.blocked_count + counts.parked_count + counts.dead_count}`
|
|
2619
|
+
);
|
|
2620
|
+
const tabs = [
|
|
2621
|
+
{ id: "queue", label: `Triage Queue (${counts.queue_total})` },
|
|
2622
|
+
{ id: "manual", label: `CF Manual (${counts.manual_count})` },
|
|
2623
|
+
{ id: "archive", label: "Archive" }
|
|
2624
|
+
];
|
|
2625
|
+
const tabStr = tabs.map(
|
|
2626
|
+
(t) => t.id === view ? `${ANSI.selectedBg} ${t.label} ${ANSI.reset}` : `${ANSI.dim} ${t.label} ${ANSI.reset}`
|
|
2627
|
+
).join(" ");
|
|
2628
|
+
lines.push(` ${tabStr}`);
|
|
2629
|
+
lines.push(`${ANSI.dim}${"\u2500".repeat(cols)}${ANSI.reset}`);
|
|
2630
|
+
const domainW = 30;
|
|
2631
|
+
const scoreW = 5;
|
|
2632
|
+
const statusW = 12;
|
|
2633
|
+
const titleW = Math.max(18, cols - domainW - scoreW - statusW - 9);
|
|
2634
|
+
lines.push(
|
|
2635
|
+
` ${ANSI.dim}${padEnd("Domain", domainW)} ${padStart("Score", scoreW)} ${padEnd("Status", statusW)} ${padEnd("Title / Notes", titleW)}${ANSI.reset}`
|
|
2636
|
+
);
|
|
2637
|
+
const visibleRows = Math.max(8, (process.stdout.rows || 28) - 10);
|
|
2638
|
+
const startIdx = Math.max(0, cursor - Math.floor(visibleRows / 2));
|
|
2639
|
+
const slice = rows.slice(startIdx, startIdx + visibleRows);
|
|
2640
|
+
if (slice.length === 0) {
|
|
2641
|
+
lines.push("", ` ${ANSI.dim}No domains in this tab yet. Press [n] Seed Pivot or [i] Import URLs.${ANSI.reset}`);
|
|
2642
|
+
} else {
|
|
2643
|
+
slice.forEach((item, i) => {
|
|
2644
|
+
const realIdx = startIdx + i;
|
|
2645
|
+
const selected = realIdx === cursor;
|
|
2646
|
+
const rawStatus = view === "queue" ? item.triage_status : item.health_status;
|
|
2647
|
+
const statusLabel = rawStatus === "claimed" ? "in-progress" : rawStatus;
|
|
2648
|
+
const titleOrNote = item.page_title || item.detection_notes || "-";
|
|
2649
|
+
const rowText = `${padEnd(item.normalized_domain, domainW)} ${padStart(String(item.confidence_score), scoreW)} ${padEnd(statusLabel, statusW)} ${padEnd(titleOrNote, titleW)}`;
|
|
2650
|
+
if (selected) {
|
|
2651
|
+
lines.push(`${ANSI.selectedBg}\u25B8 ${rowText}${ANSI.reset}`);
|
|
2652
|
+
} else {
|
|
2653
|
+
lines.push(` ${rowText}`);
|
|
2654
|
+
}
|
|
2655
|
+
});
|
|
2656
|
+
}
|
|
2657
|
+
lines.push("");
|
|
2658
|
+
lines.push(`${ANSI.dim}${"\u2500".repeat(cols)}${ANSI.reset}`);
|
|
2659
|
+
if (inputMode) {
|
|
2660
|
+
const promptTitle = inputMode === "pivot" ? "Seed Pivot (enter URL or brand name): " : "Quick Import (enter URLs separated by space/comma): ";
|
|
2661
|
+
lines.push(` ${ANSI.amber}${promptTitle}${ANSI.reset}${inputBuffer}\u2588`);
|
|
2662
|
+
lines.push(` ${ANSI.dim}Enter submit \xB7 Esc cancel${ANSI.reset}`);
|
|
2663
|
+
} else {
|
|
2664
|
+
lines.push(` ${ANSI.cyan}${statusBanner}${ANSI.reset}`);
|
|
2665
|
+
lines.push(
|
|
2666
|
+
` ${ANSI.dim}[j/k] Select [c] Copy&Mark [o] Open [s/v/d/r] Status [p] Pivot [n] New Seed [i] Import [Tab] Switch Tab [m] Menu [q] Exit${ANSI.reset}`
|
|
2667
|
+
);
|
|
2668
|
+
}
|
|
2669
|
+
process.stdout.write(ANSI.clearScreen + lines.join("\n"));
|
|
2670
|
+
};
|
|
2671
|
+
return new Promise((resolve) => {
|
|
2672
|
+
const stdin = process.stdin;
|
|
2673
|
+
stdin.setRawMode(true);
|
|
2674
|
+
stdin.resume();
|
|
2675
|
+
process.stdout.write(ANSI.altBufferEnter + ANSI.hideCursor);
|
|
2676
|
+
render();
|
|
2677
|
+
const refreshTimer = setInterval(() => {
|
|
2678
|
+
if (!inputMode) {
|
|
2679
|
+
rows = loadRows();
|
|
2680
|
+
render();
|
|
2681
|
+
}
|
|
2682
|
+
}, 2e3);
|
|
2683
|
+
const cleanup = () => {
|
|
2684
|
+
clearInterval(refreshTimer);
|
|
2685
|
+
stdin.off("data", onData);
|
|
2686
|
+
stdin.setRawMode(false);
|
|
2687
|
+
stdin.pause();
|
|
2688
|
+
process.stdout.write(ANSI.showCursor + ANSI.altBufferExit);
|
|
2689
|
+
};
|
|
2690
|
+
const setTriage = (status) => {
|
|
2691
|
+
const target = rows[cursor];
|
|
2692
|
+
if (!target) return;
|
|
2693
|
+
ctx.db.updateDomainTriage(target.id, { triage_status: status });
|
|
2694
|
+
statusBanner = `${target.normalized_domain} \u2192 ${status}`;
|
|
2695
|
+
rows = loadRows();
|
|
2696
|
+
render();
|
|
2697
|
+
};
|
|
2698
|
+
const onData = (buf) => {
|
|
2699
|
+
const s = buf.toString("utf8");
|
|
2700
|
+
if (inputMode) {
|
|
2701
|
+
if (s === "\x1B") {
|
|
2702
|
+
inputMode = null;
|
|
2703
|
+
inputBuffer = "";
|
|
2704
|
+
statusBanner = "Cancelled.";
|
|
2705
|
+
render();
|
|
2706
|
+
return;
|
|
2707
|
+
}
|
|
2708
|
+
if (s === "\r" || s === "\n") {
|
|
2709
|
+
const val = inputBuffer.trim();
|
|
2710
|
+
const mode = inputMode;
|
|
2711
|
+
inputMode = null;
|
|
2712
|
+
inputBuffer = "";
|
|
2713
|
+
if (val) {
|
|
2714
|
+
if (mode === "pivot") {
|
|
2715
|
+
ctx.jobs.startPivotJob({ seed: val, sources: ["crtsh", "urlscan", "html"] });
|
|
2716
|
+
statusBanner = `Seed Pivot started for "${val}"`;
|
|
2717
|
+
} else {
|
|
2718
|
+
const bl = ctx.db.getBlacklistSet();
|
|
2719
|
+
const urls = extractUrlsFromText(val);
|
|
2720
|
+
const ids = [];
|
|
2721
|
+
for (const u of urls) {
|
|
2722
|
+
const n = normalizeCandidate(u, bl);
|
|
2723
|
+
if (n.ok) {
|
|
2724
|
+
const res = ctx.db.insertDomainIgnore({
|
|
2725
|
+
normalized_domain: n.normalized_domain,
|
|
2726
|
+
original_url: n.original_url,
|
|
2727
|
+
source_type: "bulk_import",
|
|
2728
|
+
source_seed: "tui_import"
|
|
2729
|
+
});
|
|
2730
|
+
if (res.inserted && res.id !== null) ids.push(res.id);
|
|
2731
|
+
}
|
|
2732
|
+
}
|
|
2733
|
+
if (ids.length > 0) ctx.jobs.startValidationJob(ids, "TUI Quick Import");
|
|
2734
|
+
statusBanner = `Imported ${ids.length} new domains to validation queue.`;
|
|
2735
|
+
rows = loadRows();
|
|
2736
|
+
}
|
|
2737
|
+
}
|
|
2738
|
+
render();
|
|
2739
|
+
return;
|
|
2740
|
+
}
|
|
2741
|
+
if (s === "\x7F" || s === "\b") {
|
|
2742
|
+
inputBuffer = inputBuffer.slice(0, -1);
|
|
2743
|
+
render();
|
|
2744
|
+
return;
|
|
2745
|
+
}
|
|
2746
|
+
if (s >= " ") {
|
|
2747
|
+
inputBuffer += s;
|
|
2748
|
+
render();
|
|
2749
|
+
}
|
|
2750
|
+
return;
|
|
2751
|
+
}
|
|
2752
|
+
if (s === "" || s === "q") {
|
|
2753
|
+
cleanup();
|
|
2754
|
+
resolve("exit");
|
|
2755
|
+
return;
|
|
2756
|
+
}
|
|
2757
|
+
if (s === "m" || s === "\x1B") {
|
|
2758
|
+
cleanup();
|
|
2759
|
+
resolve("menu");
|
|
2760
|
+
return;
|
|
2761
|
+
}
|
|
2762
|
+
if (s === " ") {
|
|
2763
|
+
const order = ["queue", "manual", "archive"];
|
|
2764
|
+
view = order[(order.indexOf(view) + 1) % order.length];
|
|
2765
|
+
cursor = 0;
|
|
2766
|
+
rows = loadRows();
|
|
2767
|
+
render();
|
|
2768
|
+
return;
|
|
2769
|
+
}
|
|
2770
|
+
if (s === "j" || s === "\x1B[B") {
|
|
2771
|
+
if (cursor < rows.length - 1) cursor++;
|
|
2772
|
+
render();
|
|
2773
|
+
return;
|
|
2774
|
+
}
|
|
2775
|
+
if (s === "k" || s === "\x1B[A") {
|
|
2776
|
+
if (cursor > 0) cursor--;
|
|
2777
|
+
render();
|
|
2778
|
+
return;
|
|
2779
|
+
}
|
|
2780
|
+
if (s === "c") {
|
|
2781
|
+
const target = rows[cursor];
|
|
2782
|
+
if (!target) return;
|
|
2783
|
+
const settings = ctx.db.getSettings();
|
|
2784
|
+
ctx.db.claimDomain(target.id, settings.claimer_name);
|
|
2785
|
+
const text = formatCopyUrl(target.normalized_domain, settings.copy_format);
|
|
2786
|
+
const copied = copyToClipboard(text);
|
|
2787
|
+
statusBanner = copied ? `Copied & Marked In Progress: ${text}` : `Marked In Progress (${text}) \u2014 OS clipboard utility not found`;
|
|
2788
|
+
rows = loadRows();
|
|
2789
|
+
render();
|
|
2790
|
+
return;
|
|
2791
|
+
}
|
|
2792
|
+
if (s === "o") {
|
|
2793
|
+
const target = rows[cursor];
|
|
2794
|
+
if (!target) return;
|
|
2795
|
+
openBrowser(target.final_url || `https://${target.normalized_domain}`);
|
|
2796
|
+
statusBanner = `Opening ${target.normalized_domain} in browser`;
|
|
2797
|
+
render();
|
|
2798
|
+
return;
|
|
2799
|
+
}
|
|
2800
|
+
if (s === "s") {
|
|
2801
|
+
setTriage("submitted");
|
|
2802
|
+
return;
|
|
2803
|
+
}
|
|
2804
|
+
if (s === "v") {
|
|
2805
|
+
setTriage("valid");
|
|
2806
|
+
return;
|
|
2807
|
+
}
|
|
2808
|
+
if (s === "d") {
|
|
2809
|
+
setTriage("duplicate");
|
|
2810
|
+
return;
|
|
2811
|
+
}
|
|
2812
|
+
if (s === "r") {
|
|
2813
|
+
setTriage("rejected");
|
|
2814
|
+
return;
|
|
2815
|
+
}
|
|
2816
|
+
if (s === "p") {
|
|
2817
|
+
const target = rows[cursor];
|
|
2818
|
+
if (!target) return;
|
|
2819
|
+
ctx.jobs.startPivotJob({
|
|
2820
|
+
seed: target.normalized_domain,
|
|
2821
|
+
sources: ["crtsh", "urlscan", "html"],
|
|
2822
|
+
knownIp: target.ip_address,
|
|
2823
|
+
knownTitle: target.page_title
|
|
2824
|
+
});
|
|
2825
|
+
statusBanner = `1-hop pivot started for ${target.normalized_domain}`;
|
|
2826
|
+
render();
|
|
2827
|
+
return;
|
|
2828
|
+
}
|
|
2829
|
+
if (s === "n") {
|
|
2830
|
+
inputMode = "pivot";
|
|
2831
|
+
inputBuffer = "";
|
|
2832
|
+
render();
|
|
2833
|
+
return;
|
|
2834
|
+
}
|
|
2835
|
+
if (s === "i") {
|
|
2836
|
+
inputMode = "import";
|
|
2837
|
+
inputBuffer = "";
|
|
2838
|
+
render();
|
|
2839
|
+
}
|
|
2840
|
+
};
|
|
2841
|
+
stdin.on("data", onData);
|
|
2842
|
+
});
|
|
2843
|
+
}
|
|
2844
|
+
|
|
2845
|
+
// src/tui/launcher.ts
|
|
2846
|
+
function getMenuItems(_alreadyRunning = false) {
|
|
2847
|
+
return [
|
|
2848
|
+
{ key: "web", label: "Web UI (Open in Browser)" },
|
|
2849
|
+
{ key: "tui", label: "Terminal UI (Interactive CLI)" },
|
|
2850
|
+
{ key: "daemon", label: "Hide to Tray (Background)" },
|
|
2851
|
+
{ key: "exit", label: "Exit" }
|
|
2852
|
+
];
|
|
2853
|
+
}
|
|
2854
|
+
function renderLauncherMenu(url, selectedIdx, alreadyRunning = false) {
|
|
2855
|
+
const divider = `${ANSI.brand}============================================${ANSI.reset}`;
|
|
2856
|
+
const items = getMenuItems(alreadyRunning);
|
|
2857
|
+
const statusSuffix = alreadyRunning ? ` ${ANSI.dim}(running in background)${ANSI.reset}` : "";
|
|
2858
|
+
const lines = [
|
|
2859
|
+
"",
|
|
2860
|
+
divider,
|
|
2861
|
+
` ${ANSI.brand}${ANSI.bold}Choose Interface (v${APP_VERSION})${ANSI.reset}`,
|
|
2862
|
+
` \u25CF ${ANSI.dim}Server:${ANSI.reset} ${ANSI.green}${url}${ANSI.reset}${statusSuffix}`,
|
|
2863
|
+
divider,
|
|
2864
|
+
""
|
|
2865
|
+
];
|
|
2866
|
+
items.forEach((item, idx) => {
|
|
2867
|
+
if (idx === selectedIdx) {
|
|
2868
|
+
lines.push(` ${ANSI.selectedBg} \u2605 ${item.label} ${ANSI.reset}`);
|
|
2869
|
+
} else {
|
|
2870
|
+
lines.push(` ${ANSI.dim}\u2606${ANSI.reset} ${item.label}`);
|
|
2871
|
+
}
|
|
2872
|
+
});
|
|
2873
|
+
lines.push("", `${ANSI.dim} Use \u2191/\u2193 (or j/k) and Enter to select, Ctrl+C to quit${ANSI.reset}`, "");
|
|
2874
|
+
return lines.join("\n");
|
|
2875
|
+
}
|
|
2876
|
+
async function runLauncherMenu(url, options) {
|
|
2877
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
2878
|
+
return "web";
|
|
2879
|
+
}
|
|
2880
|
+
const alreadyRunning = Boolean(options?.alreadyRunning);
|
|
2881
|
+
const items = getMenuItems(alreadyRunning);
|
|
2882
|
+
let selected = 0;
|
|
2883
|
+
const draw = () => {
|
|
2884
|
+
process.stdout.write(ANSI.clearScreen + renderLauncherMenu(url, selected, alreadyRunning));
|
|
2885
|
+
};
|
|
2886
|
+
return new Promise((resolve) => {
|
|
2887
|
+
const stdin = process.stdin;
|
|
2888
|
+
const wasRaw = stdin.isRaw;
|
|
2889
|
+
stdin.setRawMode(true);
|
|
2890
|
+
stdin.resume();
|
|
2891
|
+
process.stdout.write(ANSI.hideCursor);
|
|
2892
|
+
draw();
|
|
2893
|
+
const cleanup = () => {
|
|
2894
|
+
stdin.off("data", onData);
|
|
2895
|
+
if (!wasRaw) stdin.setRawMode(false);
|
|
2896
|
+
stdin.pause();
|
|
2897
|
+
process.stdout.write(ANSI.showCursor);
|
|
2898
|
+
};
|
|
2899
|
+
const onData = (buf) => {
|
|
2900
|
+
const s = buf.toString("utf8");
|
|
2901
|
+
if (s === "" || s === "q") {
|
|
2902
|
+
cleanup();
|
|
2903
|
+
resolve("exit");
|
|
2904
|
+
return;
|
|
2905
|
+
}
|
|
2906
|
+
if (s === "\r" || s === "\n") {
|
|
2907
|
+
cleanup();
|
|
2908
|
+
resolve(items[selected].key);
|
|
2909
|
+
return;
|
|
2910
|
+
}
|
|
2911
|
+
if (s === "\x1B[A" || s === "k") {
|
|
2912
|
+
selected = (selected - 1 + items.length) % items.length;
|
|
2913
|
+
draw();
|
|
2914
|
+
return;
|
|
2915
|
+
}
|
|
2916
|
+
if (s === "\x1B[B" || s === "j") {
|
|
2917
|
+
selected = (selected + 1) % items.length;
|
|
2918
|
+
draw();
|
|
2919
|
+
return;
|
|
2920
|
+
}
|
|
2921
|
+
if (s >= "1" && s <= String(items.length)) {
|
|
2922
|
+
const idx = Number.parseInt(s, 10) - 1;
|
|
2923
|
+
selected = idx;
|
|
2924
|
+
cleanup();
|
|
2925
|
+
resolve(items[selected].key);
|
|
2926
|
+
}
|
|
2927
|
+
};
|
|
2928
|
+
stdin.on("data", onData);
|
|
2929
|
+
});
|
|
2930
|
+
}
|
|
2931
|
+
async function runWebWaitingLoop(url, ctx, shouldOpen = true) {
|
|
2932
|
+
if (shouldOpen) {
|
|
2933
|
+
openBrowser(url);
|
|
2934
|
+
}
|
|
2935
|
+
const draw = () => {
|
|
2936
|
+
const counts = ctx.db.getQueueCounts();
|
|
2937
|
+
const divider = `${ANSI.brand}============================================${ANSI.reset}`;
|
|
2938
|
+
process.stdout.write(
|
|
2939
|
+
ANSI.clearScreen + [
|
|
2940
|
+
"",
|
|
2941
|
+
divider,
|
|
2942
|
+
` ${ANSI.brand}${ANSI.bold}URLScanner Dashboard Active (v${APP_VERSION})${ANSI.reset}`,
|
|
2943
|
+
` \u25CF ${ANSI.dim}URL:${ANSI.reset} ${ANSI.green}${url}${ANSI.reset}`,
|
|
2944
|
+
divider,
|
|
2945
|
+
"",
|
|
2946
|
+
` Ready Queue (New) : ${ANSI.bold}${counts.new_count}${ANSI.reset}`,
|
|
2947
|
+
` In Progress / Submitted: ${counts.claimed_count} / ${counts.submitted_count}`,
|
|
2948
|
+
` Manual Check (CF) : ${counts.manual_count}`,
|
|
2949
|
+
"",
|
|
2950
|
+
` ${ANSI.dim}[b] Open Browser [t] Terminal UI [m] Menu [q] Exit${ANSI.reset}`,
|
|
2951
|
+
""
|
|
2952
|
+
].join("\n")
|
|
2953
|
+
);
|
|
2954
|
+
};
|
|
2955
|
+
if (!process.stdin.isTTY) {
|
|
2956
|
+
return new Promise(() => {
|
|
2957
|
+
});
|
|
2958
|
+
}
|
|
2959
|
+
return new Promise((resolve) => {
|
|
2960
|
+
const stdin = process.stdin;
|
|
2961
|
+
stdin.setRawMode(true);
|
|
2962
|
+
stdin.resume();
|
|
2963
|
+
draw();
|
|
2964
|
+
const timer = setInterval(draw, 3e3);
|
|
2965
|
+
const cleanup = () => {
|
|
2966
|
+
clearInterval(timer);
|
|
2967
|
+
stdin.off("data", onData);
|
|
2968
|
+
stdin.setRawMode(false);
|
|
2969
|
+
stdin.pause();
|
|
2970
|
+
};
|
|
2971
|
+
const onData = (buf) => {
|
|
2972
|
+
const s = buf.toString("utf8").toLowerCase();
|
|
2973
|
+
if (s === "" || s === "q") {
|
|
2974
|
+
cleanup();
|
|
2975
|
+
resolve("exit");
|
|
2976
|
+
} else if (s === "b") {
|
|
2977
|
+
openBrowser(url);
|
|
2978
|
+
} else if (s === "t") {
|
|
2979
|
+
cleanup();
|
|
2980
|
+
resolve("tui");
|
|
2981
|
+
} else if (s === "m" || s === "\x1B") {
|
|
2982
|
+
cleanup();
|
|
2983
|
+
resolve("menu");
|
|
2984
|
+
}
|
|
2985
|
+
};
|
|
2986
|
+
stdin.on("data", onData);
|
|
2987
|
+
});
|
|
2988
|
+
}
|
|
2989
|
+
|
|
2990
|
+
// src/tui/tray.ts
|
|
2991
|
+
import fs3 from "fs";
|
|
2992
|
+
import { createRequire } from "module";
|
|
2993
|
+
import os from "os";
|
|
2994
|
+
import path3 from "path";
|
|
2995
|
+
|
|
2996
|
+
// src/tui/trayIcon.ts
|
|
2997
|
+
import { deflateSync } from "zlib";
|
|
2998
|
+
var CRC_TABLE = (() => {
|
|
2999
|
+
const table = new Uint32Array(256);
|
|
3000
|
+
for (let n = 0; n < 256; n++) {
|
|
3001
|
+
let c = n;
|
|
3002
|
+
for (let k = 0; k < 8; k++) {
|
|
3003
|
+
c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
|
|
3004
|
+
}
|
|
3005
|
+
table[n] = c >>> 0;
|
|
3006
|
+
}
|
|
3007
|
+
return table;
|
|
3008
|
+
})();
|
|
3009
|
+
function crc32(buf) {
|
|
3010
|
+
let c = 4294967295;
|
|
3011
|
+
for (let i = 0; i < buf.length; i++) {
|
|
3012
|
+
c = CRC_TABLE[(c ^ buf[i]) & 255] ^ c >>> 8;
|
|
3013
|
+
}
|
|
3014
|
+
return (c ^ 4294967295) >>> 0;
|
|
3015
|
+
}
|
|
3016
|
+
function pngChunk(type, data) {
|
|
3017
|
+
const len = Buffer.alloc(4);
|
|
3018
|
+
len.writeUInt32BE(data.length, 0);
|
|
3019
|
+
const typeBuf = Buffer.from(type, "ascii");
|
|
3020
|
+
const crcBuf = Buffer.alloc(4);
|
|
3021
|
+
crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0);
|
|
3022
|
+
return Buffer.concat([len, typeBuf, data, crcBuf]);
|
|
3023
|
+
}
|
|
3024
|
+
function renderUrlScannerPixels(size) {
|
|
3025
|
+
const pixels = new Uint8Array(size * size * 4);
|
|
3026
|
+
const bg = [20, 36, 35, 255];
|
|
3027
|
+
const bgBorder = [20, 184, 166, 96];
|
|
3028
|
+
const teal = [20, 184, 166, 255];
|
|
3029
|
+
const white = [237, 237, 237, 235];
|
|
3030
|
+
const setPixel = (x, y, color) => {
|
|
3031
|
+
if (x < 0 || y < 0 || x >= size || y >= size) return;
|
|
3032
|
+
const idx = (y * size + x) * 4;
|
|
3033
|
+
pixels[idx] = color[0];
|
|
3034
|
+
pixels[idx + 1] = color[1];
|
|
3035
|
+
pixels[idx + 2] = color[2];
|
|
3036
|
+
pixels[idx + 3] = color[3];
|
|
3037
|
+
};
|
|
3038
|
+
const radius = size * 0.24;
|
|
3039
|
+
const cx = (size - 1) / 2;
|
|
3040
|
+
const cy = (size - 1) / 2;
|
|
3041
|
+
const half = size / 2 - 1;
|
|
3042
|
+
for (let y = 0; y < size; y++) {
|
|
3043
|
+
for (let x = 0; x < size; x++) {
|
|
3044
|
+
const dx = Math.max(Math.abs(x - cx) - (half - radius), 0);
|
|
3045
|
+
const dy = Math.max(Math.abs(y - cy) - (half - radius), 0);
|
|
3046
|
+
const dist = Math.hypot(dx, dy);
|
|
3047
|
+
if (dist <= radius) {
|
|
3048
|
+
if (dist >= radius - 1.2) {
|
|
3049
|
+
setPixel(x, y, bgBorder);
|
|
3050
|
+
} else {
|
|
3051
|
+
setPixel(x, y, bg);
|
|
3052
|
+
}
|
|
3053
|
+
}
|
|
3054
|
+
}
|
|
3055
|
+
}
|
|
3056
|
+
const s = (v) => v / 24 * size;
|
|
3057
|
+
const stroke = Math.max(1.5, size / 14);
|
|
3058
|
+
const drawRect = (x1, y1, x2, y2, color) => {
|
|
3059
|
+
const ix1 = Math.floor(s(x1));
|
|
3060
|
+
const iy1 = Math.floor(s(y1));
|
|
3061
|
+
const ix2 = Math.ceil(s(x2));
|
|
3062
|
+
const iy2 = Math.ceil(s(y2));
|
|
3063
|
+
for (let y = iy1; y <= iy2; y++) {
|
|
3064
|
+
for (let x = ix1; x <= ix2; x++) {
|
|
3065
|
+
setPixel(x, y, color);
|
|
3066
|
+
}
|
|
3067
|
+
}
|
|
3068
|
+
};
|
|
3069
|
+
const arm = 4.6;
|
|
3070
|
+
const t = 1.9;
|
|
3071
|
+
const pad = 4.2;
|
|
3072
|
+
drawRect(pad, pad, pad + arm, pad + t, teal);
|
|
3073
|
+
drawRect(pad, pad, pad + t, pad + arm, teal);
|
|
3074
|
+
drawRect(24 - pad - arm, pad, 24 - pad, pad + t, teal);
|
|
3075
|
+
drawRect(24 - pad - t, pad, 24 - pad, pad + arm, teal);
|
|
3076
|
+
drawRect(pad, 24 - pad - t, pad + arm, 24 - pad, teal);
|
|
3077
|
+
drawRect(pad, 24 - pad - arm, pad + t, 24 - pad, teal);
|
|
3078
|
+
drawRect(24 - pad - arm, 24 - pad - t, 24 - pad, 24 - pad, teal);
|
|
3079
|
+
drawRect(24 - pad - t, 24 - pad - arm, 24 - pad, 24 - pad, teal);
|
|
3080
|
+
const ringR = s(4.2);
|
|
3081
|
+
for (let y = 0; y < size; y++) {
|
|
3082
|
+
for (let x = 0; x < size; x++) {
|
|
3083
|
+
const dist = Math.hypot(x - cx, y - cy);
|
|
3084
|
+
if (Math.abs(dist - ringR) <= stroke * 0.48) {
|
|
3085
|
+
setPixel(x, y, white);
|
|
3086
|
+
}
|
|
3087
|
+
}
|
|
3088
|
+
}
|
|
3089
|
+
drawRect(5.2, 11.1, 18.8, 12.9, teal);
|
|
3090
|
+
const dotR = s(1.7);
|
|
3091
|
+
for (let y = 0; y < size; y++) {
|
|
3092
|
+
for (let x = 0; x < size; x++) {
|
|
3093
|
+
if (Math.hypot(x - cx, y - cy) <= dotR) {
|
|
3094
|
+
setPixel(x, y, teal);
|
|
3095
|
+
}
|
|
3096
|
+
}
|
|
3097
|
+
}
|
|
3098
|
+
return pixels;
|
|
3099
|
+
}
|
|
3100
|
+
function buildPngBase64(size = 64) {
|
|
3101
|
+
const rgba = renderUrlScannerPixels(size);
|
|
3102
|
+
const stride = size * 4;
|
|
3103
|
+
const raw = Buffer.alloc((stride + 1) * size);
|
|
3104
|
+
for (let y = 0; y < size; y++) {
|
|
3105
|
+
const rowStart = y * (stride + 1);
|
|
3106
|
+
raw[rowStart] = 0;
|
|
3107
|
+
Buffer.from(rgba.buffer, y * stride, stride).copy(raw, rowStart + 1);
|
|
3108
|
+
}
|
|
3109
|
+
const ihdr = Buffer.alloc(13);
|
|
3110
|
+
ihdr.writeUInt32BE(size, 0);
|
|
3111
|
+
ihdr.writeUInt32BE(size, 4);
|
|
3112
|
+
ihdr[8] = 8;
|
|
3113
|
+
ihdr[9] = 6;
|
|
3114
|
+
ihdr[10] = 0;
|
|
3115
|
+
ihdr[11] = 0;
|
|
3116
|
+
ihdr[12] = 0;
|
|
3117
|
+
const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
|
3118
|
+
const compressed = deflateSync(raw);
|
|
3119
|
+
return Buffer.concat([
|
|
3120
|
+
signature,
|
|
3121
|
+
pngChunk("IHDR", ihdr),
|
|
3122
|
+
pngChunk("IDAT", compressed),
|
|
3123
|
+
pngChunk("IEND", Buffer.alloc(0))
|
|
3124
|
+
]).toString("base64");
|
|
3125
|
+
}
|
|
3126
|
+
function buildIcoBase64(size = 32) {
|
|
3127
|
+
const rgba = renderUrlScannerPixels(size);
|
|
3128
|
+
const pixelBytes = size * size * 4;
|
|
3129
|
+
const andMaskRowBytes = Math.ceil(size / 32) * 4;
|
|
3130
|
+
const andMaskBytes = andMaskRowBytes * size;
|
|
3131
|
+
const imageSize = 40 + pixelBytes + andMaskBytes;
|
|
3132
|
+
const out = Buffer.alloc(6 + 16 + imageSize);
|
|
3133
|
+
out.writeUInt16LE(0, 0);
|
|
3134
|
+
out.writeUInt16LE(1, 2);
|
|
3135
|
+
out.writeUInt16LE(1, 4);
|
|
3136
|
+
out[6] = size === 256 ? 0 : size;
|
|
3137
|
+
out[7] = size === 256 ? 0 : size;
|
|
3138
|
+
out[8] = 0;
|
|
3139
|
+
out[9] = 0;
|
|
3140
|
+
out.writeUInt16LE(1, 10);
|
|
3141
|
+
out.writeUInt16LE(32, 12);
|
|
3142
|
+
out.writeUInt32LE(imageSize, 14);
|
|
3143
|
+
out.writeUInt32LE(22, 18);
|
|
3144
|
+
const bmpOffset = 22;
|
|
3145
|
+
out.writeUInt32LE(40, bmpOffset);
|
|
3146
|
+
out.writeInt32LE(size, bmpOffset + 4);
|
|
3147
|
+
out.writeInt32LE(size * 2, bmpOffset + 8);
|
|
3148
|
+
out.writeUInt16LE(1, bmpOffset + 12);
|
|
3149
|
+
out.writeUInt16LE(32, bmpOffset + 14);
|
|
3150
|
+
out.writeUInt32LE(0, bmpOffset + 16);
|
|
3151
|
+
out.writeUInt32LE(pixelBytes + andMaskBytes, bmpOffset + 20);
|
|
3152
|
+
let dst = bmpOffset + 40;
|
|
3153
|
+
for (let y = size - 1; y >= 0; y--) {
|
|
3154
|
+
for (let x = 0; x < size; x++) {
|
|
3155
|
+
const src = (y * size + x) * 4;
|
|
3156
|
+
out[dst++] = rgba[src + 2];
|
|
3157
|
+
out[dst++] = rgba[src + 1];
|
|
3158
|
+
out[dst++] = rgba[src];
|
|
3159
|
+
out[dst++] = rgba[src + 3];
|
|
3160
|
+
}
|
|
3161
|
+
}
|
|
3162
|
+
return out.toString("base64");
|
|
3163
|
+
}
|
|
3164
|
+
var TRAY_ICON_PNG_BASE64 = buildPngBase64(64);
|
|
3165
|
+
var TRAY_ICON_ICO_BASE64 = buildIcoBase64(32);
|
|
3166
|
+
function getTrayIconForPlatform(platform = process.platform) {
|
|
3167
|
+
return platform === "win32" ? TRAY_ICON_ICO_BASE64 : TRAY_ICON_PNG_BASE64;
|
|
3168
|
+
}
|
|
3169
|
+
|
|
3170
|
+
// src/tui/tray.ts
|
|
3171
|
+
function shouldEnableTray(options) {
|
|
3172
|
+
if (options.noTray) return false;
|
|
3173
|
+
const platform = options.platform ?? process.platform;
|
|
3174
|
+
const env = options.env ?? process.env;
|
|
3175
|
+
if (platform === "linux") {
|
|
3176
|
+
return Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
|
|
3177
|
+
}
|
|
3178
|
+
return platform === "win32" || platform === "darwin";
|
|
3179
|
+
}
|
|
3180
|
+
function getBinName(platform) {
|
|
3181
|
+
if (platform === "win32") return "tray_windows_release.exe";
|
|
3182
|
+
if (platform === "darwin") return "tray_darwin_release";
|
|
3183
|
+
if (platform === "linux") return "tray_linux_release";
|
|
3184
|
+
return null;
|
|
3185
|
+
}
|
|
3186
|
+
function prepareExecutableCopyDir() {
|
|
3187
|
+
const binName = getBinName(process.platform);
|
|
3188
|
+
if (!binName) return true;
|
|
3189
|
+
try {
|
|
3190
|
+
const require2 = createRequire(import.meta.url);
|
|
3191
|
+
const entryPath = require2.resolve("systray2");
|
|
3192
|
+
const pkgDir = path3.dirname(entryPath);
|
|
3193
|
+
const pkgJson = JSON.parse(fs3.readFileSync(path3.join(pkgDir, "package.json"), "utf8"));
|
|
3194
|
+
const version = pkgJson.version || "2.1.4";
|
|
3195
|
+
const srcBin = path3.join(pkgDir, "traybin", binName);
|
|
3196
|
+
const cacheRoot = path3.join(os.homedir(), ".cache", "node-systray");
|
|
3197
|
+
const destDir = path3.join(cacheRoot, version);
|
|
3198
|
+
const destBin = path3.join(destDir, binName);
|
|
3199
|
+
fs3.mkdirSync(destDir, { recursive: true });
|
|
3200
|
+
if (!fs3.existsSync(destBin)) {
|
|
3201
|
+
fs3.copyFileSync(srcBin, destBin);
|
|
3202
|
+
}
|
|
3203
|
+
if (process.platform !== "win32") {
|
|
3204
|
+
fs3.chmodSync(destBin, 493);
|
|
3205
|
+
}
|
|
3206
|
+
return cacheRoot;
|
|
3207
|
+
} catch {
|
|
3208
|
+
return true;
|
|
3209
|
+
}
|
|
3210
|
+
}
|
|
3211
|
+
async function startSystemTray(options) {
|
|
3212
|
+
if (!shouldEnableTray({ noTray: options.noTray })) {
|
|
3213
|
+
return null;
|
|
3214
|
+
}
|
|
3215
|
+
let systray = null;
|
|
3216
|
+
try {
|
|
3217
|
+
const copyDir = prepareExecutableCopyDir();
|
|
3218
|
+
const mod = await import("systray2");
|
|
3219
|
+
const SysTrayCtor = mod.default?.default ?? mod.default;
|
|
3220
|
+
const statusItem = {
|
|
3221
|
+
title: `URLScanner (:${options.port})`,
|
|
3222
|
+
tooltip: options.serverUrl,
|
|
3223
|
+
checked: false,
|
|
3224
|
+
enabled: false
|
|
3225
|
+
};
|
|
3226
|
+
const openItem = {
|
|
3227
|
+
title: "Open Dashboard",
|
|
3228
|
+
tooltip: `Open ${options.serverUrl} in browser`,
|
|
3229
|
+
checked: false,
|
|
3230
|
+
enabled: true
|
|
3231
|
+
};
|
|
3232
|
+
const quitItem = {
|
|
3233
|
+
title: "Quit",
|
|
3234
|
+
tooltip: "Stop URLScanner daemon",
|
|
3235
|
+
checked: false,
|
|
3236
|
+
enabled: true
|
|
3237
|
+
};
|
|
3238
|
+
const items = SysTrayCtor.separator ? [statusItem, SysTrayCtor.separator, openItem, quitItem] : [statusItem, openItem, quitItem];
|
|
3239
|
+
systray = new SysTrayCtor({
|
|
3240
|
+
menu: {
|
|
3241
|
+
icon: getTrayIconForPlatform(),
|
|
3242
|
+
title: "",
|
|
3243
|
+
tooltip: `URLScanner \u2014 ${options.serverUrl}`,
|
|
3244
|
+
items
|
|
3245
|
+
},
|
|
3246
|
+
debug: false,
|
|
3247
|
+
copyDir
|
|
3248
|
+
});
|
|
3249
|
+
await Promise.race([
|
|
3250
|
+
systray.ready(),
|
|
3251
|
+
new Promise(
|
|
3252
|
+
(_, reject) => setTimeout(() => reject(new Error("Tray initialization timed out")), 4e3)
|
|
3253
|
+
)
|
|
3254
|
+
]);
|
|
3255
|
+
systray.onError((err) => {
|
|
3256
|
+
console.error(`Tray warning: ${err.message}`);
|
|
3257
|
+
});
|
|
3258
|
+
await systray.onClick((action) => {
|
|
3259
|
+
const clickedTitle = action.item?.title ?? "";
|
|
3260
|
+
if (clickedTitle === "Open Dashboard") {
|
|
3261
|
+
openBrowser(options.serverUrl);
|
|
3262
|
+
} else if (clickedTitle === "Quit") {
|
|
3263
|
+
options.onQuit();
|
|
3264
|
+
}
|
|
3265
|
+
});
|
|
3266
|
+
const activeTray = systray;
|
|
3267
|
+
return {
|
|
3268
|
+
kill: async () => {
|
|
3269
|
+
try {
|
|
3270
|
+
if (activeTray.process && !activeTray.killed) {
|
|
3271
|
+
await activeTray.kill(false);
|
|
3272
|
+
}
|
|
3273
|
+
} catch {
|
|
3274
|
+
try {
|
|
3275
|
+
activeTray.process?.kill("SIGKILL");
|
|
3276
|
+
} catch {
|
|
3277
|
+
}
|
|
3278
|
+
}
|
|
3279
|
+
}
|
|
3280
|
+
};
|
|
3281
|
+
} catch (err) {
|
|
3282
|
+
try {
|
|
3283
|
+
systray?.process?.kill("SIGKILL");
|
|
3284
|
+
} catch {
|
|
3285
|
+
}
|
|
3286
|
+
console.error(
|
|
3287
|
+
`System tray unavailable (${err instanceof Error ? err.message : String(err)}); running headless daemon.`
|
|
3288
|
+
);
|
|
3289
|
+
return null;
|
|
3290
|
+
}
|
|
3291
|
+
}
|
|
3292
|
+
|
|
3293
|
+
// src/cli.ts
|
|
3294
|
+
function defaultDataDir() {
|
|
3295
|
+
return process.env.URLSCANNER_DATA_DIR || path4.join(os2.homedir(), ".urlscanner");
|
|
3296
|
+
}
|
|
3297
|
+
function isProcessAlive(pid) {
|
|
3298
|
+
try {
|
|
3299
|
+
process.kill(pid, 0);
|
|
3300
|
+
return true;
|
|
3301
|
+
} catch {
|
|
3302
|
+
return false;
|
|
3303
|
+
}
|
|
3304
|
+
}
|
|
3305
|
+
function readPidFile(pidPath) {
|
|
3306
|
+
try {
|
|
3307
|
+
if (!fs4.existsSync(pidPath)) return null;
|
|
3308
|
+
const info = JSON.parse(fs4.readFileSync(pidPath, "utf8"));
|
|
3309
|
+
if (info && typeof info.pid === "number" && isProcessAlive(info.pid)) {
|
|
3310
|
+
return info;
|
|
3311
|
+
}
|
|
3312
|
+
fs4.rmSync(pidPath, { force: true });
|
|
3313
|
+
return null;
|
|
3314
|
+
} catch {
|
|
3315
|
+
return null;
|
|
3316
|
+
}
|
|
3317
|
+
}
|
|
3318
|
+
function printHelp() {
|
|
3319
|
+
console.log(`URLScanner v${APP_VERSION} \u2014 Local URL Scanner & OSINT Triage Workbench
|
|
3320
|
+
|
|
3321
|
+
Usage:
|
|
3322
|
+
urlscanner [options]
|
|
3323
|
+
urlscanner status [--data-dir <path>]
|
|
3324
|
+
urlscanner stop [--data-dir <path>]
|
|
3325
|
+
|
|
3326
|
+
Options:
|
|
3327
|
+
-p, --port <port> HTTP port (default: ${DEFAULT_PORT})
|
|
3328
|
+
--host <host> Bind host (default: ${DEFAULT_HOST})
|
|
3329
|
+
--data-dir <path> Local data directory (default: ~/.urlscanner)
|
|
3330
|
+
--web Open Web UI directly (skip Choose Interface menu)
|
|
3331
|
+
--tui Open Interactive Terminal UI directly
|
|
3332
|
+
--no-open Do not auto-open browser in Web UI mode
|
|
3333
|
+
--no-menu Run headless server without interactive terminal menu
|
|
3334
|
+
--no-tray Disable system tray icon in background daemon mode
|
|
3335
|
+
--daemon Run in background daemon mode
|
|
3336
|
+
-v, --version Print version
|
|
3337
|
+
-h, --help Show this help message
|
|
3338
|
+
`);
|
|
3339
|
+
}
|
|
3340
|
+
async function waitForHealth(url, timeoutMs = 6e3) {
|
|
3341
|
+
const deadline = Date.now() + timeoutMs;
|
|
3342
|
+
while (Date.now() < deadline) {
|
|
3343
|
+
try {
|
|
3344
|
+
const resp = await fetch(`${url}/api/health`);
|
|
3345
|
+
if (resp.ok) return true;
|
|
3346
|
+
} catch {
|
|
3347
|
+
}
|
|
3348
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
3349
|
+
}
|
|
3350
|
+
return false;
|
|
3351
|
+
}
|
|
3352
|
+
async function checkExistingUrlScanner(host, port) {
|
|
3353
|
+
try {
|
|
3354
|
+
const resp = await fetch(`http://${host}:${port}/api/health`, {
|
|
3355
|
+
signal: AbortSignal.timeout(800)
|
|
3356
|
+
});
|
|
3357
|
+
if (!resp.ok) return false;
|
|
3358
|
+
const data = await resp.json();
|
|
3359
|
+
return data?.status === "ok" && typeof data.counts === "object";
|
|
3360
|
+
} catch {
|
|
3361
|
+
return false;
|
|
3362
|
+
}
|
|
3363
|
+
}
|
|
3364
|
+
async function handleStatus(dataDir) {
|
|
3365
|
+
const pidPath = path4.join(dataDir, "server.pid");
|
|
3366
|
+
const info = readPidFile(pidPath);
|
|
3367
|
+
if (!info) {
|
|
3368
|
+
console.log("URLScanner daemon is not running.");
|
|
3369
|
+
return;
|
|
3370
|
+
}
|
|
3371
|
+
const url = `http://${info.host}:${info.port}`;
|
|
3372
|
+
const healthy = await waitForHealth(url, 1500);
|
|
3373
|
+
console.log(`URLScanner daemon running (PID ${info.pid}) at ${url} [${healthy ? "healthy" : "unresponsive"}]`);
|
|
3374
|
+
console.log(`Data dir: ${info.dataDir}`);
|
|
3375
|
+
}
|
|
3376
|
+
async function handleStop(dataDir) {
|
|
3377
|
+
const pidPath = path4.join(dataDir, "server.pid");
|
|
3378
|
+
const info = readPidFile(pidPath);
|
|
3379
|
+
if (!info) {
|
|
3380
|
+
console.log("URLScanner daemon is not running.");
|
|
3381
|
+
return false;
|
|
3382
|
+
}
|
|
3383
|
+
try {
|
|
3384
|
+
process.kill(info.pid, "SIGTERM");
|
|
3385
|
+
} catch {
|
|
3386
|
+
}
|
|
3387
|
+
const deadline = Date.now() + 4e3;
|
|
3388
|
+
while (Date.now() < deadline && isProcessAlive(info.pid)) {
|
|
3389
|
+
await new Promise((r) => setTimeout(r, 150));
|
|
3390
|
+
}
|
|
3391
|
+
fs4.rmSync(pidPath, { force: true });
|
|
3392
|
+
console.log(`Stopped URLScanner daemon (PID ${info.pid}).`);
|
|
3393
|
+
return true;
|
|
3394
|
+
}
|
|
3395
|
+
async function spawnDaemon(host, port, dataDir, noTray = false) {
|
|
3396
|
+
fs4.mkdirSync(dataDir, { recursive: true });
|
|
3397
|
+
const logPath = path4.join(dataDir, "server.log");
|
|
3398
|
+
const logFd = fs4.openSync(logPath, "a");
|
|
3399
|
+
const scriptPath = process.argv[1];
|
|
3400
|
+
const args = [
|
|
3401
|
+
scriptPath,
|
|
3402
|
+
"--daemon",
|
|
3403
|
+
"--host",
|
|
3404
|
+
host,
|
|
3405
|
+
"--port",
|
|
3406
|
+
String(port),
|
|
3407
|
+
"--data-dir",
|
|
3408
|
+
dataDir
|
|
3409
|
+
];
|
|
3410
|
+
if (noTray) {
|
|
3411
|
+
args.push("--no-tray");
|
|
3412
|
+
}
|
|
3413
|
+
const child = spawn2(process.execPath, args, {
|
|
3414
|
+
detached: true,
|
|
3415
|
+
stdio: ["ignore", logFd, logFd],
|
|
3416
|
+
windowsHide: true
|
|
3417
|
+
});
|
|
3418
|
+
child.unref();
|
|
3419
|
+
const url = `http://${host === "127.0.0.1" ? "localhost" : host}:${port}`;
|
|
3420
|
+
const ok = await waitForHealth(`http://${host}:${port}`, 6e3);
|
|
3421
|
+
if (ok) {
|
|
3422
|
+
const trayEnabled = shouldEnableTray({ noTray });
|
|
3423
|
+
console.log(`
|
|
3424
|
+
\u{1F680} URLScanner running in background (PID ${child.pid})`);
|
|
3425
|
+
console.log(` Dashboard : ${url}`);
|
|
3426
|
+
console.log(
|
|
3427
|
+
` Tray : ${trayEnabled ? "Enabled (Open Dashboard / Quit)" : noTray ? "Disabled (--no-tray)" : "Headless"}`
|
|
3428
|
+
);
|
|
3429
|
+
console.log(` Log : ${logPath}`);
|
|
3430
|
+
console.log(` Manage : urlscanner status | urlscanner stop
|
|
3431
|
+
`);
|
|
3432
|
+
} else {
|
|
3433
|
+
console.error(`Failed to start daemon. Check logs at ${logPath}`);
|
|
3434
|
+
process.exitCode = 1;
|
|
3435
|
+
}
|
|
3436
|
+
}
|
|
3437
|
+
async function main() {
|
|
3438
|
+
const { values, positionals } = parseArgs({
|
|
3439
|
+
allowPositionals: true,
|
|
3440
|
+
options: {
|
|
3441
|
+
port: { type: "string", short: "p" },
|
|
3442
|
+
host: { type: "string" },
|
|
3443
|
+
"data-dir": { type: "string" },
|
|
3444
|
+
web: { type: "boolean", default: false },
|
|
3445
|
+
tui: { type: "boolean", default: false },
|
|
3446
|
+
"no-open": { type: "boolean", default: false },
|
|
3447
|
+
"no-menu": { type: "boolean", default: false },
|
|
3448
|
+
"no-tray": { type: "boolean", default: false },
|
|
3449
|
+
daemon: { type: "boolean", default: false },
|
|
3450
|
+
version: { type: "boolean", short: "v", default: false },
|
|
3451
|
+
help: { type: "boolean", short: "h", default: false }
|
|
3452
|
+
}
|
|
3453
|
+
});
|
|
3454
|
+
if (values.help) {
|
|
3455
|
+
printHelp();
|
|
3456
|
+
return;
|
|
3457
|
+
}
|
|
3458
|
+
if (values.version) {
|
|
3459
|
+
console.log(APP_VERSION);
|
|
3460
|
+
return;
|
|
3461
|
+
}
|
|
3462
|
+
const dataDir = path4.resolve(values["data-dir"] || defaultDataDir());
|
|
3463
|
+
const subcommand = positionals[0];
|
|
3464
|
+
if (subcommand === "status") {
|
|
3465
|
+
await handleStatus(dataDir);
|
|
3466
|
+
return;
|
|
3467
|
+
}
|
|
3468
|
+
if (subcommand === "stop") {
|
|
3469
|
+
await handleStop(dataDir);
|
|
3470
|
+
return;
|
|
3471
|
+
}
|
|
3472
|
+
const host = values.host || DEFAULT_HOST;
|
|
3473
|
+
const port = Number.parseInt(values.port || String(DEFAULT_PORT), 10) || DEFAULT_PORT;
|
|
3474
|
+
const displayHost = host === "127.0.0.1" ? "localhost" : host;
|
|
3475
|
+
const dbPath = path4.join(dataDir, "scanner.db");
|
|
3476
|
+
const db = new AppDatabase(dbPath);
|
|
3477
|
+
const ctx = createContext(db);
|
|
3478
|
+
const app = createApp(ctx);
|
|
3479
|
+
const alreadyRunning = !values.daemon && await checkExistingUrlScanner(host, port);
|
|
3480
|
+
let started = null;
|
|
3481
|
+
if (!alreadyRunning) {
|
|
3482
|
+
try {
|
|
3483
|
+
started = await startHttpServer(app, host, port);
|
|
3484
|
+
} catch (err) {
|
|
3485
|
+
const code = err?.code;
|
|
3486
|
+
if (code === "EADDRINUSE") {
|
|
3487
|
+
console.error(
|
|
3488
|
+
`Port ${port} is already in use by another application. Try: urlscanner --port ${port + 1}`
|
|
3489
|
+
);
|
|
3490
|
+
} else {
|
|
3491
|
+
console.error(err);
|
|
3492
|
+
}
|
|
3493
|
+
db.close();
|
|
3494
|
+
process.exitCode = 1;
|
|
3495
|
+
return;
|
|
3496
|
+
}
|
|
3497
|
+
}
|
|
3498
|
+
const activePort = started ? started.port : port;
|
|
3499
|
+
const serverUrl = `http://${displayHost}:${activePort}`;
|
|
3500
|
+
const pidPath = path4.join(dataDir, "server.pid");
|
|
3501
|
+
if (values.daemon) {
|
|
3502
|
+
const pidInfo = {
|
|
3503
|
+
pid: process.pid,
|
|
3504
|
+
port: activePort,
|
|
3505
|
+
host,
|
|
3506
|
+
dataDir,
|
|
3507
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3508
|
+
};
|
|
3509
|
+
fs4.writeFileSync(pidPath, JSON.stringify(pidInfo, null, 2));
|
|
3510
|
+
}
|
|
3511
|
+
let trayHandle = null;
|
|
3512
|
+
let shuttingDown = false;
|
|
3513
|
+
const shutdown = () => {
|
|
3514
|
+
if (shuttingDown) return;
|
|
3515
|
+
shuttingDown = true;
|
|
3516
|
+
void trayHandle?.kill();
|
|
3517
|
+
try {
|
|
3518
|
+
started?.server.close();
|
|
3519
|
+
} catch {
|
|
3520
|
+
}
|
|
3521
|
+
if (values.daemon) {
|
|
3522
|
+
fs4.rmSync(pidPath, { force: true });
|
|
3523
|
+
}
|
|
3524
|
+
try {
|
|
3525
|
+
db.close();
|
|
3526
|
+
} catch {
|
|
3527
|
+
}
|
|
3528
|
+
};
|
|
3529
|
+
process.on("SIGINT", () => {
|
|
3530
|
+
shutdown();
|
|
3531
|
+
process.exit(0);
|
|
3532
|
+
});
|
|
3533
|
+
process.on("SIGTERM", () => {
|
|
3534
|
+
shutdown();
|
|
3535
|
+
process.exit(0);
|
|
3536
|
+
});
|
|
3537
|
+
if (values.daemon) {
|
|
3538
|
+
console.log(`URLScanner v${APP_VERSION} listening on ${serverUrl} (DB: ${dbPath})`);
|
|
3539
|
+
trayHandle = await startSystemTray({
|
|
3540
|
+
serverUrl,
|
|
3541
|
+
port: activePort,
|
|
3542
|
+
noTray: values["no-tray"],
|
|
3543
|
+
onQuit: () => {
|
|
3544
|
+
shutdown();
|
|
3545
|
+
setTimeout(() => process.exit(0), 150);
|
|
3546
|
+
}
|
|
3547
|
+
});
|
|
3548
|
+
return;
|
|
3549
|
+
}
|
|
3550
|
+
if (values["no-menu"]) {
|
|
3551
|
+
if (alreadyRunning) {
|
|
3552
|
+
console.log(`URLScanner is already running on ${serverUrl}`);
|
|
3553
|
+
if (values.web && !values["no-open"]) {
|
|
3554
|
+
openBrowser(serverUrl);
|
|
3555
|
+
}
|
|
3556
|
+
db.close();
|
|
3557
|
+
return;
|
|
3558
|
+
}
|
|
3559
|
+
console.log(`URLScanner v${APP_VERSION} listening on ${serverUrl} (DB: ${dbPath})`);
|
|
3560
|
+
if (values.web && !values["no-open"]) {
|
|
3561
|
+
openBrowser(serverUrl);
|
|
3562
|
+
}
|
|
3563
|
+
return;
|
|
3564
|
+
}
|
|
3565
|
+
let mode = values.tui ? "tui" : values.web ? "web" : "menu";
|
|
3566
|
+
let firstWebOpen = !values["no-open"];
|
|
3567
|
+
while (true) {
|
|
3568
|
+
if (mode === "menu") {
|
|
3569
|
+
const choice = await runLauncherMenu(serverUrl, { alreadyRunning });
|
|
3570
|
+
if (choice === "exit") {
|
|
3571
|
+
shutdown();
|
|
3572
|
+
process.exit(0);
|
|
3573
|
+
}
|
|
3574
|
+
if (choice === "stop") {
|
|
3575
|
+
shutdown();
|
|
3576
|
+
await handleStop(dataDir);
|
|
3577
|
+
process.exit(0);
|
|
3578
|
+
}
|
|
3579
|
+
if (choice === "daemon") {
|
|
3580
|
+
shutdown();
|
|
3581
|
+
if (alreadyRunning) {
|
|
3582
|
+
await handleStop(dataDir);
|
|
3583
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
3584
|
+
}
|
|
3585
|
+
await spawnDaemon(host, activePort, dataDir, values["no-tray"]);
|
|
3586
|
+
process.exit(0);
|
|
3587
|
+
}
|
|
3588
|
+
mode = choice;
|
|
3589
|
+
}
|
|
3590
|
+
if (mode === "web") {
|
|
3591
|
+
const next = await runWebWaitingLoop(serverUrl, ctx, firstWebOpen);
|
|
3592
|
+
firstWebOpen = true;
|
|
3593
|
+
if (next === "exit") {
|
|
3594
|
+
shutdown();
|
|
3595
|
+
process.exit(0);
|
|
3596
|
+
}
|
|
3597
|
+
mode = next;
|
|
3598
|
+
}
|
|
3599
|
+
if (mode === "tui") {
|
|
3600
|
+
const next = await runInteractiveTui(serverUrl, ctx);
|
|
3601
|
+
if (next === "exit") {
|
|
3602
|
+
shutdown();
|
|
3603
|
+
process.exit(0);
|
|
3604
|
+
}
|
|
3605
|
+
mode = "menu";
|
|
3606
|
+
}
|
|
3607
|
+
}
|
|
3608
|
+
}
|
|
3609
|
+
main().catch((err) => {
|
|
3610
|
+
console.error(err);
|
|
3611
|
+
process.exit(1);
|
|
3612
|
+
});
|