@rasyid2567/urlscanner 1.0.0 → 1.1.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/dist/cli.js CHANGED
@@ -8,7 +8,7 @@ import path4 from "path";
8
8
  import { parseArgs } from "util";
9
9
 
10
10
  // src/config.ts
11
- var APP_VERSION = "1.0.0";
11
+ var APP_VERSION = "1.1.0";
12
12
  var DEFAULT_PORT = 3847;
13
13
  var DEFAULT_HOST = "127.0.0.1";
14
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";
@@ -177,6 +177,58 @@ var DEFAULT_BLACKLIST_DOMAINS = [
177
177
  { domain: "yandex.ru", reason: "search" },
178
178
  { domain: "adobe.com", reason: "vendor" }
179
179
  ];
180
+ var GENERIC_BRAND_STOPWORDS = /* @__PURE__ */ new Set([
181
+ "www",
182
+ "amp",
183
+ "app",
184
+ "web",
185
+ "site",
186
+ "link",
187
+ "login",
188
+ "daftar",
189
+ "register",
190
+ "masuk",
191
+ "play",
192
+ "game",
193
+ "slot",
194
+ "togel",
195
+ "casino",
196
+ "vip",
197
+ "pro",
198
+ "live",
199
+ "info",
200
+ "page",
201
+ "pages",
202
+ "blog",
203
+ "news",
204
+ "home",
205
+ "main",
206
+ "alt",
207
+ "cdn",
208
+ "api",
209
+ "shop",
210
+ "store",
211
+ "online",
212
+ "official",
213
+ "portal",
214
+ "index",
215
+ "redirect",
216
+ "short",
217
+ "bonus",
218
+ "promo",
219
+ "member",
220
+ "user",
221
+ "auth",
222
+ "static",
223
+ "assets",
224
+ "media",
225
+ "img",
226
+ "cdn1",
227
+ "cdn2",
228
+ "demo",
229
+ "test",
230
+ "dev"
231
+ ]);
180
232
  var DEFAULT_SETTINGS_RAW = {
181
233
  copy_format: "https",
182
234
  concurrency: "20",
@@ -186,7 +238,12 @@ var DEFAULT_SETTINGS_RAW = {
186
238
  dns_check_enabled: "true",
187
239
  dns_filter_server: "180.131.144.144",
188
240
  trustpositif_source_url: "https://raw.githubusercontent.com/alsyundawy/TrustPositif/main/alsyundawy_gambling_v2.txt",
189
- trustpositif_last_sync: ""
241
+ trustpositif_last_sync: "",
242
+ auto_pivot_default: "true",
243
+ auto_pivot_max_depth: "5",
244
+ auto_pivot_max_domains: "500",
245
+ auto_pivot_min_score: "25",
246
+ auto_pivot_osint_delay_ms: "800"
190
247
  };
191
248
  var ISP_BLOCK_URL_PATTERNS = [
192
249
  "trustpositif.komdigi.go.id",
@@ -308,6 +365,8 @@ function rowToDomainItem(row) {
308
365
  outbound_links: safeJsonParse(row.outbound_links_json, []),
309
366
  source_type: row.source_type,
310
367
  source_seed: row.source_seed,
368
+ parent_domain: row.parent_domain ?? null,
369
+ pivot_depth: row.pivot_depth ?? 0,
311
370
  health_status: row.health_status,
312
371
  triage_status: row.triage_status,
313
372
  http_status: row.http_status,
@@ -367,6 +426,8 @@ var AppDatabase = class {
367
426
  outbound_links_json TEXT NOT NULL DEFAULT '[]',
368
427
  source_type TEXT NOT NULL,
369
428
  source_seed TEXT,
429
+ parent_domain TEXT,
430
+ pivot_depth INTEGER NOT NULL DEFAULT 0,
370
431
  health_status TEXT NOT NULL DEFAULT 'pending',
371
432
  triage_status TEXT NOT NULL DEFAULT 'new',
372
433
  http_status INTEGER,
@@ -427,8 +488,19 @@ var AppDatabase = class {
427
488
  domain TEXT PRIMARY KEY
428
489
  );
429
490
  `);
491
+ this.migrateSchema();
430
492
  this.seedDefaults();
431
493
  }
494
+ migrateSchema() {
495
+ const cols = this.db.prepare("PRAGMA table_info(domains)").all();
496
+ const names = new Set(cols.map((c) => c.name));
497
+ if (!names.has("parent_domain")) {
498
+ this.db.exec("ALTER TABLE domains ADD COLUMN parent_domain TEXT");
499
+ }
500
+ if (!names.has("pivot_depth")) {
501
+ this.db.exec("ALTER TABLE domains ADD COLUMN pivot_depth INTEGER NOT NULL DEFAULT 0");
502
+ }
503
+ }
432
504
  seedDefaults() {
433
505
  const insertSetting = this.db.prepare(
434
506
  "INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)"
@@ -462,14 +534,16 @@ var AppDatabase = class {
462
534
  insertDomainIgnore(input) {
463
535
  const stmt = this.db.prepare(`
464
536
  INSERT OR IGNORE INTO domains (
465
- normalized_domain, original_url, source_type, source_seed, health_status
466
- ) VALUES (?, ?, ?, ?, ?)
537
+ normalized_domain, original_url, source_type, source_seed, parent_domain, pivot_depth, health_status
538
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
467
539
  `);
468
540
  const info = stmt.run(
469
541
  input.normalized_domain,
470
542
  input.original_url,
471
543
  input.source_type,
472
544
  input.source_seed ?? null,
545
+ input.parent_domain ?? null,
546
+ input.pivot_depth ?? 0,
473
547
  input.health_status ?? "pending"
474
548
  );
475
549
  if (info.changes > 0) {
@@ -698,7 +772,7 @@ var AppDatabase = class {
698
772
  appendJobLog(id, message) {
699
773
  const cur = this.getJob(id);
700
774
  if (!cur) return null;
701
- const logs = [...cur.logs, `[${(/* @__PURE__ */ new Date()).toISOString().slice(11, 19)}] ${message}`].slice(-80);
775
+ const logs = [...cur.logs, `[${(/* @__PURE__ */ new Date()).toISOString().slice(11, 19)}] ${message}`].slice(-300);
702
776
  this.db.prepare("UPDATE jobs SET log_json = ? WHERE id = ?").run(JSON.stringify(logs), id);
703
777
  return this.getJob(id);
704
778
  }
@@ -715,16 +789,25 @@ var AppDatabase = class {
715
789
  const rows = this.db.prepare("SELECT key, value FROM settings").all();
716
790
  const map = { ...DEFAULT_SETTINGS_RAW };
717
791
  for (const r of rows) map[r.key] = r.value;
792
+ const parseBoundedInt = (raw, fallback, min, max) => {
793
+ const n = Number.parseInt(raw ?? "", 10);
794
+ return Number.isNaN(n) ? fallback : Math.min(Math.max(n, min), max);
795
+ };
718
796
  return {
719
797
  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),
798
+ concurrency: parseBoundedInt(map.concurrency, 20, 1, 60),
799
+ timeout_ms: parseBoundedInt(map.timeout_ms, 1e4, 2e3, 3e4),
722
800
  claimer_name: map.claimer_name || "me",
723
801
  urlscan_api_key: map.urlscan_api_key || "",
724
802
  dns_check_enabled: map.dns_check_enabled !== "false",
725
803
  dns_filter_server: map.dns_filter_server || "180.131.144.144",
726
804
  trustpositif_source_url: map.trustpositif_source_url || DEFAULT_SETTINGS_RAW.trustpositif_source_url,
727
- trustpositif_last_sync: map.trustpositif_last_sync || ""
805
+ trustpositif_last_sync: map.trustpositif_last_sync || "",
806
+ auto_pivot_default: map.auto_pivot_default !== "false",
807
+ auto_pivot_max_depth: parseBoundedInt(map.auto_pivot_max_depth, 5, 0, 20),
808
+ auto_pivot_max_domains: parseBoundedInt(map.auto_pivot_max_domains, 500, 10, 5e3),
809
+ auto_pivot_min_score: parseBoundedInt(map.auto_pivot_min_score, 25, 0, 100),
810
+ auto_pivot_osint_delay_ms: parseBoundedInt(map.auto_pivot_osint_delay_ms, 800, 200, 5e3)
728
811
  };
729
812
  }
730
813
  setSettings(partial) {
@@ -1084,12 +1167,48 @@ function createDomainsRouter(ctx) {
1084
1167
  // src/routes/ingest.ts
1085
1168
  import { Hono as Hono2 } from "hono";
1086
1169
  var ALL_SOURCES = ["crtsh", "urlscan", "html"];
1170
+ function sanitizeSources(raw) {
1171
+ if (!Array.isArray(raw)) return ALL_SOURCES;
1172
+ const valid = raw.filter((s) => ALL_SOURCES.includes(s));
1173
+ return valid.length > 0 ? valid : ALL_SOURCES;
1174
+ }
1175
+ function sanitizeDeepConfig(raw) {
1176
+ if (typeof raw === "boolean") {
1177
+ return { enabled: raw };
1178
+ }
1179
+ if (!raw || typeof raw !== "object") return void 0;
1180
+ const obj = raw;
1181
+ const out = {};
1182
+ if (typeof obj.enabled === "boolean") out.enabled = obj.enabled;
1183
+ if (typeof obj.max_depth === "number" && !Number.isNaN(obj.max_depth)) {
1184
+ out.max_depth = obj.max_depth;
1185
+ }
1186
+ if (typeof obj.max_domains === "number" && !Number.isNaN(obj.max_domains)) {
1187
+ out.max_domains = obj.max_domains;
1188
+ }
1189
+ if (typeof obj.min_score_to_expand === "number" && !Number.isNaN(obj.min_score_to_expand)) {
1190
+ out.min_score_to_expand = obj.min_score_to_expand;
1191
+ }
1192
+ if (typeof obj.expand_priority_links === "boolean") {
1193
+ out.expand_priority_links = obj.expand_priority_links;
1194
+ }
1195
+ if (typeof obj.expand_redirects === "boolean") {
1196
+ out.expand_redirects = obj.expand_redirects;
1197
+ }
1198
+ if (typeof obj.osint_delay_ms === "number" && !Number.isNaN(obj.osint_delay_ms)) {
1199
+ out.osint_delay_ms = obj.osint_delay_ms;
1200
+ }
1201
+ return out;
1202
+ }
1087
1203
  function createIngestRouter(ctx) {
1088
1204
  const app = new Hono2();
1089
1205
  app.post("/bulk", async (c) => {
1090
1206
  let rawText = "";
1091
1207
  let sourceSeed = "bulk_import";
1092
1208
  let autoValidate = true;
1209
+ let autoPivot = false;
1210
+ let sources = ALL_SOURCES;
1211
+ let deepOverride;
1093
1212
  const contentType = c.req.header("content-type") || "";
1094
1213
  if (contentType.includes("multipart/form-data")) {
1095
1214
  const form = await c.req.parseBody();
@@ -1103,11 +1222,15 @@ function createIngestRouter(ctx) {
1103
1222
  rawText += await fileField.text();
1104
1223
  }
1105
1224
  if (form.auto_validate === "false") autoValidate = false;
1225
+ if (form.auto_pivot === "true") autoPivot = true;
1106
1226
  } else {
1107
1227
  const body = await c.req.json().catch(() => ({}));
1108
1228
  rawText = body.raw_text ?? "";
1109
1229
  if (body.source_seed) sourceSeed = body.source_seed;
1110
1230
  if (body.auto_validate === false) autoValidate = false;
1231
+ if (body.auto_pivot === true) autoPivot = true;
1232
+ sources = sanitizeSources(body.sources);
1233
+ deepOverride = sanitizeDeepConfig(body.deep);
1111
1234
  }
1112
1235
  if (!rawText.trim()) {
1113
1236
  return c.json({ error: "Teks URL atau file tidak boleh kosong" }, 400);
@@ -1146,7 +1269,15 @@ function createIngestRouter(ctx) {
1146
1269
  }
1147
1270
  }
1148
1271
  let jobId = null;
1149
- if (autoValidate && insertedIds.length > 0) {
1272
+ if (autoPivot && insertedIds.length > 0) {
1273
+ const job = ctx.jobs.startPivotJob({
1274
+ seed: sourceSeed || "bulk_import",
1275
+ initialDomainIds: insertedIds,
1276
+ sources,
1277
+ deep: { ...deepOverride, enabled: true }
1278
+ });
1279
+ jobId = job.id;
1280
+ } else if (autoValidate && insertedIds.length > 0) {
1150
1281
  const job = ctx.jobs.startValidationJob(
1151
1282
  insertedIds,
1152
1283
  `Bulk Import (${insertedIds.length} domain)`
@@ -1167,6 +1298,7 @@ function createIngestRouter(ctx) {
1167
1298
  app.post("/pivot", async (c) => {
1168
1299
  const body = await c.req.json().catch(() => ({}));
1169
1300
  let seed = (body.seed ?? "").trim();
1301
+ const seeds = Array.isArray(body.seeds) ? body.seeds.map((s) => typeof s === "string" ? s.trim() : "").filter(Boolean) : void 0;
1170
1302
  let knownIp = null;
1171
1303
  let knownTitle = null;
1172
1304
  if (typeof body.domain_id === "number") {
@@ -1178,18 +1310,21 @@ function createIngestRouter(ctx) {
1178
1310
  knownIp = existing.ip_address;
1179
1311
  knownTitle = existing.page_title;
1180
1312
  }
1313
+ if (!seed && seeds && seeds.length > 0) {
1314
+ seed = seeds.length === 1 ? seeds[0] : `${seeds[0]} (+${seeds.length - 1})`;
1315
+ }
1181
1316
  if (!seed) {
1182
1317
  return c.json({ error: "Seed URL/brand atau domain_id wajib diisi" }, 400);
1183
1318
  }
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;
1319
+ const sources = sanitizeSources(body.sources);
1320
+ const deep = sanitizeDeepConfig(body.deep);
1188
1321
  const job = ctx.jobs.startPivotJob({
1189
1322
  seed,
1323
+ seeds,
1190
1324
  sources,
1191
1325
  knownIp,
1192
- knownTitle
1326
+ knownTitle,
1327
+ deep
1193
1328
  });
1194
1329
  return c.json({ job });
1195
1330
  });
@@ -1204,6 +1339,14 @@ function createJobsRouter(ctx) {
1204
1339
  app.get("/", (c) => {
1205
1340
  return c.json({ jobs: ctx.db.listJobs(25) });
1206
1341
  });
1342
+ app.post("/:id/cancel", (c) => {
1343
+ const id = c.req.param("id");
1344
+ const job = ctx.jobs.cancelJob(id);
1345
+ if (!job) {
1346
+ return c.json({ error: "Job tidak ditemukan" }, 404);
1347
+ }
1348
+ return c.json({ job });
1349
+ });
1207
1350
  app.get("/stream", (c) => {
1208
1351
  return streamSSE(c, async (stream) => {
1209
1352
  let alive = true;
@@ -1278,6 +1421,21 @@ function createSettingsRouter(ctx) {
1278
1421
  if (typeof body.trustpositif_source_url === "string" && body.trustpositif_source_url.trim()) {
1279
1422
  patch.trustpositif_source_url = body.trustpositif_source_url.trim();
1280
1423
  }
1424
+ if (typeof body.auto_pivot_default === "boolean") {
1425
+ patch.auto_pivot_default = body.auto_pivot_default;
1426
+ }
1427
+ if (typeof body.auto_pivot_max_depth === "number" && !Number.isNaN(body.auto_pivot_max_depth) && body.auto_pivot_max_depth >= 0 && body.auto_pivot_max_depth <= 20) {
1428
+ patch.auto_pivot_max_depth = Math.trunc(body.auto_pivot_max_depth);
1429
+ }
1430
+ if (typeof body.auto_pivot_max_domains === "number" && !Number.isNaN(body.auto_pivot_max_domains) && body.auto_pivot_max_domains >= 10 && body.auto_pivot_max_domains <= 5e3) {
1431
+ patch.auto_pivot_max_domains = Math.trunc(body.auto_pivot_max_domains);
1432
+ }
1433
+ if (typeof body.auto_pivot_min_score === "number" && !Number.isNaN(body.auto_pivot_min_score) && body.auto_pivot_min_score >= 0 && body.auto_pivot_min_score <= 100) {
1434
+ patch.auto_pivot_min_score = Math.trunc(body.auto_pivot_min_score);
1435
+ }
1436
+ if (typeof body.auto_pivot_osint_delay_ms === "number" && !Number.isNaN(body.auto_pivot_osint_delay_ms) && body.auto_pivot_osint_delay_ms >= 200 && body.auto_pivot_osint_delay_ms <= 5e3) {
1437
+ patch.auto_pivot_osint_delay_ms = Math.trunc(body.auto_pivot_osint_delay_ms);
1438
+ }
1281
1439
  const updated = ctx.db.setSettings(patch);
1282
1440
  return c.json({ settings: updated });
1283
1441
  });
@@ -1791,6 +1949,19 @@ async function validateDomain(domain, deps) {
1791
1949
  }
1792
1950
 
1793
1951
  // src/services/pivoter.ts
1952
+ function createPivotSessionDedupe() {
1953
+ return {
1954
+ pivotedDomains: /* @__PURE__ */ new Set(),
1955
+ queriedCrtBrands: /* @__PURE__ */ new Set(),
1956
+ queriedUrlscanQueries: /* @__PURE__ */ new Set(),
1957
+ queriedIps: /* @__PURE__ */ new Set(),
1958
+ queriedTitles: /* @__PURE__ */ new Set(),
1959
+ crtCooldownUntil: 0,
1960
+ urlscanCooldownUntil: 0,
1961
+ lastCrtCallAt: 0,
1962
+ lastUrlscanCallAt: 0
1963
+ };
1964
+ }
1794
1965
  var insecureAgent2 = new Agent2({ connect: { rejectUnauthorized: false } });
1795
1966
  async function defaultFetch2(url, init) {
1796
1967
  return undiciFetch2(url, {
@@ -1798,6 +1969,28 @@ async function defaultFetch2(url, init) {
1798
1969
  dispatcher: insecureAgent2
1799
1970
  });
1800
1971
  }
1972
+ function combineSignals(timeoutSignal, externalSignal) {
1973
+ return externalSignal ? AbortSignal.any([timeoutSignal, externalSignal]) : timeoutSignal;
1974
+ }
1975
+ async function waitWithAbort(ms, signal) {
1976
+ if (signal?.aborted) return false;
1977
+ if (ms <= 0) return true;
1978
+ return new Promise((resolve) => {
1979
+ const timer = setTimeout(() => {
1980
+ signal?.removeEventListener("abort", onAbort);
1981
+ resolve(true);
1982
+ }, ms);
1983
+ const onAbort = () => {
1984
+ clearTimeout(timer);
1985
+ resolve(false);
1986
+ };
1987
+ signal?.addEventListener("abort", onAbort, { once: true });
1988
+ });
1989
+ }
1990
+ function isNoiseRedirectUrl(url) {
1991
+ const lower = url.toLowerCase();
1992
+ return ISP_BLOCK_URL_PATTERNS.some((p) => lower.includes(p)) || PARKING_URL_PATTERNS.some((p) => lower.includes(p));
1993
+ }
1801
1994
  function isSharedCdnIp(ip) {
1802
1995
  if (!ip) return true;
1803
1996
  return KNOWN_CDN_IPS_PREFIXES.some((prefix) => ip.startsWith(prefix));
@@ -1809,7 +2002,10 @@ function extractBrandKeyword(seed) {
1809
2002
  }
1810
2003
  return clean;
1811
2004
  }
1812
- async function pivotCrtSh(seed, blacklistSet, fetchFn = defaultFetch2) {
2005
+ async function pivotCrtSh(seed, blacklistSet, fetchFn = defaultFetch2, opts) {
2006
+ if (opts?.signal?.aborted) {
2007
+ return { candidates: [], logs: [] };
2008
+ }
1813
2009
  const logs = [];
1814
2010
  const candidates = [];
1815
2011
  const seen = /* @__PURE__ */ new Set();
@@ -1817,16 +2013,38 @@ async function pivotCrtSh(seed, blacklistSet, fetchFn = defaultFetch2) {
1817
2013
  if (!queryTerm || queryTerm.length < 3) {
1818
2014
  return { candidates: [], logs: ["CRT.sh skipped: keyword must be at least 3 characters"] };
1819
2015
  }
2016
+ if (!opts?.isRootSeed && GENERIC_BRAND_STOPWORDS.has(queryTerm)) {
2017
+ return { candidates: [], logs: [] };
2018
+ }
2019
+ const dedupe = opts?.dedupe;
2020
+ if (dedupe) {
2021
+ if (dedupe.queriedCrtBrands.has(queryTerm)) {
2022
+ return { candidates: [], logs: [] };
2023
+ }
2024
+ if (dedupe.crtCooldownUntil > Date.now()) {
2025
+ return { candidates: [], logs: [] };
2026
+ }
2027
+ const spacing = Math.max(0, dedupe.lastCrtCallAt + (opts?.osintDelayMs ?? 0) - Date.now());
2028
+ if (spacing > 0) {
2029
+ const ok = await waitWithAbort(spacing, opts?.signal);
2030
+ if (!ok) return { candidates, logs };
2031
+ }
2032
+ dedupe.queriedCrtBrands.add(queryTerm);
2033
+ dedupe.lastCrtCallAt = Date.now();
2034
+ }
1820
2035
  const url = `https://crt.sh/?q=${encodeURIComponent(`%${queryTerm}%`)}&output=json`;
1821
2036
  let body = "";
1822
2037
  let lastStatus = 0;
1823
2038
  for (let attempt = 0; attempt < 2; attempt++) {
2039
+ if (opts?.signal?.aborted) {
2040
+ return { candidates, logs };
2041
+ }
1824
2042
  const controller = new AbortController();
1825
2043
  const timer = setTimeout(() => controller.abort(), 2e4);
1826
2044
  try {
1827
2045
  const resp = await fetchFn(url, {
1828
2046
  method: "GET",
1829
- signal: controller.signal,
2047
+ signal: combineSignals(controller.signal, opts?.signal),
1830
2048
  headers: {
1831
2049
  "User-Agent": CHROME_USER_AGENT,
1832
2050
  Accept: "application/json"
@@ -1838,12 +2056,23 @@ async function pivotCrtSh(seed, blacklistSet, fetchFn = defaultFetch2) {
1838
2056
  break;
1839
2057
  }
1840
2058
  if (resp.status === 502 || resp.status === 503 || resp.status === 429) {
1841
- await new Promise((r) => setTimeout(r, 1e3));
1842
- continue;
2059
+ if (attempt === 0) {
2060
+ const ok = await waitWithAbort(1e3, opts?.signal);
2061
+ if (!ok) return { candidates, logs };
2062
+ continue;
2063
+ }
2064
+ if (dedupe) {
2065
+ dedupe.crtCooldownUntil = Date.now() + 6e4;
2066
+ }
2067
+ logs.push(`CRT.sh HTTP ${resp.status}`);
2068
+ return { candidates, logs };
1843
2069
  }
1844
2070
  logs.push(`CRT.sh HTTP ${resp.status}`);
1845
2071
  return { candidates, logs };
1846
2072
  } catch (err) {
2073
+ if (opts?.signal?.aborted) {
2074
+ return { candidates, logs };
2075
+ }
1847
2076
  if (attempt === 1) {
1848
2077
  logs.push(`CRT.sh failed: ${err instanceof Error ? err.message : String(err)}`);
1849
2078
  return { candidates, logs };
@@ -1879,28 +2108,49 @@ async function pivotCrtSh(seed, blacklistSet, fetchFn = defaultFetch2) {
1879
2108
  return { candidates, logs };
1880
2109
  }
1881
2110
  async function pivotUrlScan(seed, options, blacklistSet, fetchFn = defaultFetch2) {
2111
+ if (options.signal?.aborted) {
2112
+ return { candidates: [], logs: [] };
2113
+ }
2114
+ const dedupe = options.dedupe;
2115
+ if (dedupe && dedupe.urlscanCooldownUntil > Date.now()) {
2116
+ return { candidates: [], logs: [] };
2117
+ }
1882
2118
  const logs = [];
1883
2119
  const candidates = [];
1884
2120
  const seen = /* @__PURE__ */ new Set();
1885
2121
  const brand = extractBrandKeyword(seed);
1886
2122
  const hasApiKey = Boolean(options.apiKey && options.apiKey.trim());
2123
+ const allowBrandWildcard = hasApiKey && Boolean(options.isRootSeed || !GENERIC_BRAND_STOPWORDS.has(brand));
1887
2124
  const queries = [];
1888
2125
  if (seed.includes(".")) {
1889
2126
  const cleanDomain = seed.replace(/^https?:\/\//i, "").split("/")[0] ?? seed;
1890
2127
  queries.push(
1891
- hasApiKey ? `domain:*${brand}* OR page.domain:${cleanDomain}` : `page.domain:${cleanDomain} OR domain:${cleanDomain}`
2128
+ allowBrandWildcard ? `domain:*${brand}* OR page.domain:${cleanDomain}` : `page.domain:${cleanDomain} OR domain:${cleanDomain}`
1892
2129
  );
1893
2130
  } else if (brand) {
1894
2131
  queries.push(
1895
- hasApiKey ? `domain:*${brand}* OR page.title:"${brand}"` : `page.title:"${brand}"`
2132
+ allowBrandWildcard ? `domain:*${brand}* OR page.title:"${brand}"` : `page.title:"${brand}"`
1896
2133
  );
1897
2134
  }
1898
2135
  if (options.knownIp && !isSharedCdnIp(options.knownIp)) {
1899
- queries.push(`page.ip:${options.knownIp}`);
2136
+ if (!dedupe || !dedupe.queriedIps.has(options.knownIp)) {
2137
+ dedupe?.queriedIps.add(options.knownIp);
2138
+ queries.push(`page.ip:${options.knownIp}`);
2139
+ }
1900
2140
  }
1901
2141
  if (options.knownTitle && options.knownTitle.trim().length >= 8) {
1902
- const safeTitle = options.knownTitle.replace(/["\\]/g, "").slice(0, 60);
1903
- queries.push(`page.title:"${safeTitle}"`);
2142
+ const safeTitle = options.knownTitle.replace(/["\\]/g, "").slice(0, 60).trim();
2143
+ if (safeTitle.length >= 8) {
2144
+ const titleKey = safeTitle.toLowerCase();
2145
+ if (!dedupe || !dedupe.queriedTitles.has(titleKey)) {
2146
+ dedupe?.queriedTitles.add(titleKey);
2147
+ queries.push(`page.title:"${safeTitle}"`);
2148
+ }
2149
+ }
2150
+ }
2151
+ const filteredQueries = queries.filter((q) => !dedupe || !dedupe.queriedUrlscanQueries.has(q)).slice(0, 3);
2152
+ if (filteredQueries.length === 0) {
2153
+ return { candidates: [], logs: [] };
1904
2154
  }
1905
2155
  const headers = {
1906
2156
  "User-Agent": CHROME_USER_AGENT,
@@ -1909,18 +2159,36 @@ async function pivotUrlScan(seed, options, blacklistSet, fetchFn = defaultFetch2
1909
2159
  if (hasApiKey && options.apiKey) {
1910
2160
  headers["API-Key"] = options.apiKey.trim();
1911
2161
  }
1912
- for (const q of queries.slice(0, 2)) {
2162
+ for (const q of filteredQueries) {
2163
+ if (options.signal?.aborted) break;
2164
+ if (dedupe) {
2165
+ if (dedupe.urlscanCooldownUntil > Date.now()) break;
2166
+ const spacing = Math.max(
2167
+ 0,
2168
+ dedupe.lastUrlscanCallAt + (options.osintDelayMs ?? 0) - Date.now()
2169
+ );
2170
+ if (spacing > 0) {
2171
+ const ok = await waitWithAbort(spacing, options.signal);
2172
+ if (!ok) break;
2173
+ }
2174
+ dedupe.queriedUrlscanQueries.add(q);
2175
+ dedupe.lastUrlscanCallAt = Date.now();
2176
+ }
1913
2177
  const url = `https://urlscan.io/api/v1/search/?q=${encodeURIComponent(q)}&size=100`;
1914
2178
  const controller = new AbortController();
1915
2179
  const timer = setTimeout(() => controller.abort(), 15e3);
1916
2180
  try {
1917
2181
  const resp = await fetchFn(url, {
1918
2182
  method: "GET",
1919
- signal: controller.signal,
2183
+ signal: combineSignals(controller.signal, options.signal),
1920
2184
  headers
1921
2185
  });
1922
2186
  if (resp.status === 429) {
1923
2187
  const resetAfter = resp.headers.get("X-Rate-Limit-Reset-After") ?? "60";
2188
+ const resetSec = Math.max(1, Number.parseInt(resetAfter, 10) || 60);
2189
+ if (dedupe) {
2190
+ dedupe.urlscanCooldownUntil = Date.now() + resetSec * 1e3;
2191
+ }
1924
2192
  logs.push(`URLScan.io rate limit (429), resets in ${resetAfter}s`);
1925
2193
  break;
1926
2194
  }
@@ -1948,6 +2216,7 @@ async function pivotUrlScan(seed, options, blacklistSet, fetchFn = defaultFetch2
1948
2216
  }
1949
2217
  }
1950
2218
  } catch (err) {
2219
+ if (options.signal?.aborted) break;
1951
2220
  logs.push(`URLScan.io failed: ${err instanceof Error ? err.message : String(err)}`);
1952
2221
  } finally {
1953
2222
  clearTimeout(timer);
@@ -1956,7 +2225,10 @@ async function pivotUrlScan(seed, options, blacklistSet, fetchFn = defaultFetch2
1956
2225
  logs.push(`URLScan.io: found ${candidates.length} unique domains`);
1957
2226
  return { candidates, logs };
1958
2227
  }
1959
- async function pivotHtmlAmp(seed, blacklistSet, fetchFn = defaultFetch2) {
2228
+ async function pivotHtmlAmp(seed, blacklistSet, fetchFn = defaultFetch2, opts) {
2229
+ if (opts?.signal?.aborted) {
2230
+ return { candidates: [], logs: [] };
2231
+ }
1960
2232
  const logs = [];
1961
2233
  const candidates = [];
1962
2234
  const seen = /* @__PURE__ */ new Set();
@@ -1964,17 +2236,32 @@ async function pivotHtmlAmp(seed, blacklistSet, fetchFn = defaultFetch2) {
1964
2236
  if (!seedNorm.ok) {
1965
2237
  return { candidates: [], logs: ["HTML/AMP Extractor skipped: seed is not a URL or domain"] };
1966
2238
  }
2239
+ const addUrlCandidate = (rawUrl) => {
2240
+ if (isNoiseRedirectUrl(rawUrl)) return;
2241
+ const norm = normalizeCandidate(rawUrl, blacklistSet);
2242
+ if (norm.ok && !seen.has(norm.normalized_domain)) {
2243
+ seen.add(norm.normalized_domain);
2244
+ candidates.push({
2245
+ normalized_domain: norm.normalized_domain,
2246
+ original_url: rawUrl,
2247
+ source_type: "seed_html"
2248
+ });
2249
+ }
2250
+ };
1967
2251
  let currentUrl = seedNorm.original_url;
1968
2252
  let finalHtml = "";
1969
2253
  let finalStatus = 0;
1970
2254
  for (let hop = 0; hop < 8; hop++) {
2255
+ if (opts?.signal?.aborted) {
2256
+ return { candidates, logs };
2257
+ }
1971
2258
  const controller = new AbortController();
1972
2259
  const timer = setTimeout(() => controller.abort(), 12e3);
1973
2260
  try {
1974
2261
  const resp = await fetchFn(currentUrl, {
1975
2262
  method: "GET",
1976
2263
  redirect: "manual",
1977
- signal: controller.signal,
2264
+ signal: combineSignals(controller.signal, opts?.signal),
1978
2265
  headers: {
1979
2266
  "User-Agent": CHROME_USER_AGENT,
1980
2267
  Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
@@ -1986,21 +2273,25 @@ async function pivotHtmlAmp(seed, blacklistSet, fetchFn = defaultFetch2) {
1986
2273
  const loc = resp.headers.get("location");
1987
2274
  if (loc) {
1988
2275
  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
- }
2276
+ addUrlCandidate(currentUrl);
2277
+ continue;
2278
+ }
2279
+ }
2280
+ const body = await resp.text();
2281
+ if (hop < 7 && body.length < 4096) {
2282
+ const metaUrl = extractMetaRefreshUrl(body, currentUrl);
2283
+ if (metaUrl && metaUrl !== currentUrl) {
2284
+ currentUrl = metaUrl;
2285
+ addUrlCandidate(currentUrl);
1998
2286
  continue;
1999
2287
  }
2000
2288
  }
2001
- finalHtml = await resp.text();
2289
+ finalHtml = body;
2002
2290
  break;
2003
2291
  } catch (err) {
2292
+ if (opts?.signal?.aborted) {
2293
+ return { candidates, logs };
2294
+ }
2004
2295
  logs.push(`HTML Extractor failed (${currentUrl}): ${err instanceof Error ? err.message : String(err)}`);
2005
2296
  return { candidates, logs };
2006
2297
  } finally {
@@ -2039,16 +2330,57 @@ async function pivotHtmlAmp(seed, blacklistSet, fetchFn = defaultFetch2) {
2039
2330
  }
2040
2331
  return { candidates, logs };
2041
2332
  }
2333
+ function extractCandidatesFromValidatedDomain(domain, blacklistSet, config) {
2334
+ const candidates = [];
2335
+ const seen = /* @__PURE__ */ new Set();
2336
+ const pushCandidate = (rawUrl, sourceType) => {
2337
+ if (isNoiseRedirectUrl(rawUrl)) return;
2338
+ const norm = normalizeCandidate(rawUrl, blacklistSet);
2339
+ if (!norm.ok) return;
2340
+ if (norm.normalized_domain === domain.normalized_domain) return;
2341
+ if (seen.has(norm.normalized_domain)) return;
2342
+ seen.add(norm.normalized_domain);
2343
+ candidates.push({
2344
+ normalized_domain: norm.normalized_domain,
2345
+ original_url: rawUrl.startsWith("http") ? rawUrl : norm.original_url,
2346
+ source_type: sourceType
2347
+ });
2348
+ };
2349
+ if (config.expand_redirects) {
2350
+ for (const hop of domain.redirect_chain) {
2351
+ pushCandidate(hop.url, "pivot_redirect");
2352
+ }
2353
+ if (domain.final_url) {
2354
+ pushCandidate(domain.final_url, "pivot_redirect");
2355
+ }
2356
+ }
2357
+ if (domain.health_status === "alive") {
2358
+ const fullScorePass = domain.confidence_score >= config.min_score_to_expand;
2359
+ for (const link of domain.outbound_links) {
2360
+ if (fullScorePass || config.expand_priority_links && link.priority) {
2361
+ pushCandidate(link.url, "pivot_outbound");
2362
+ }
2363
+ }
2364
+ }
2365
+ return candidates;
2366
+ }
2042
2367
  async function runSeedPivotSources(seed, sources, options, blacklistSet, fetchFn = defaultFetch2) {
2043
2368
  const tasks = [];
2044
2369
  if (sources.includes("crtsh")) {
2045
- tasks.push(pivotCrtSh(seed, blacklistSet, fetchFn));
2370
+ tasks.push(
2371
+ pivotCrtSh(seed, blacklistSet, fetchFn, {
2372
+ dedupe: options.dedupe,
2373
+ osintDelayMs: options.osintDelayMs,
2374
+ signal: options.signal,
2375
+ isRootSeed: options.isRootSeed
2376
+ })
2377
+ );
2046
2378
  }
2047
2379
  if (sources.includes("urlscan")) {
2048
2380
  tasks.push(pivotUrlScan(seed, options, blacklistSet, fetchFn));
2049
2381
  }
2050
2382
  if (sources.includes("html")) {
2051
- tasks.push(pivotHtmlAmp(seed, blacklistSet, fetchFn));
2383
+ tasks.push(pivotHtmlAmp(seed, blacklistSet, fetchFn, { signal: options.signal }));
2052
2384
  }
2053
2385
  const settled = await Promise.all(tasks);
2054
2386
  const merged = [];
@@ -2070,11 +2402,16 @@ async function runSeedPivotSources(seed, sources, options, blacklistSet, fetchFn
2070
2402
  var JobManager = class {
2071
2403
  db;
2072
2404
  trustPositif;
2405
+ validateDomainFn;
2406
+ runPivotFn;
2073
2407
  subscribers = /* @__PURE__ */ new Set();
2074
2408
  activeTasks = /* @__PURE__ */ new Set();
2075
- constructor(db, trustPositif) {
2409
+ jobControllers = /* @__PURE__ */ new Map();
2410
+ constructor(db, trustPositif, deps = {}) {
2076
2411
  this.db = db;
2077
2412
  this.trustPositif = trustPositif;
2413
+ this.validateDomainFn = deps.validateDomainFn ?? validateDomain;
2414
+ this.runPivotFn = deps.runPivotFn ?? runSeedPivotSources;
2078
2415
  }
2079
2416
  subscribe(fn) {
2080
2417
  this.subscribers.add(fn);
@@ -2108,18 +2445,49 @@ var JobManager = class {
2108
2445
  async waitForIdle() {
2109
2446
  await Promise.allSettled(Array.from(this.activeTasks));
2110
2447
  }
2448
+ cancelJob(jobId) {
2449
+ const job = this.db.getJob(jobId);
2450
+ if (!job) return null;
2451
+ const controller = this.jobControllers.get(jobId);
2452
+ if (controller && !controller.signal.aborted) {
2453
+ controller.abort();
2454
+ }
2455
+ if (job.status === "running") {
2456
+ this.db.appendJobLog(jobId, "Stop requested by user.");
2457
+ const updated = this.db.updateJob(jobId, {
2458
+ status: "cancelled",
2459
+ finished: true
2460
+ });
2461
+ this.emitJob(jobId);
2462
+ this.emitCounts();
2463
+ return updated;
2464
+ }
2465
+ return job;
2466
+ }
2111
2467
  startValidationJob(domainIds, targetLabel = "Bulk Validation") {
2112
2468
  const id = crypto.randomUUID().slice(0, 8);
2113
2469
  const job = this.db.createJob(id, "validate", targetLabel, domainIds.length);
2114
2470
  this.emitJob(id);
2115
- this.track(this.runValidationPool(id, domainIds));
2471
+ const controller = new AbortController();
2472
+ this.jobControllers.set(id, controller);
2473
+ this.track(
2474
+ this.runValidationPool(id, domainIds, controller.signal).finally(() => {
2475
+ this.jobControllers.delete(id);
2476
+ })
2477
+ );
2116
2478
  return job;
2117
2479
  }
2118
2480
  startPivotJob(input) {
2119
2481
  const id = crypto.randomUUID().slice(0, 8);
2120
- const job = this.db.createJob(id, "pivot", input.seed, 0);
2482
+ const job = this.db.createJob(id, "pivot", input.seed, input.initialDomainIds?.length ?? 0);
2121
2483
  this.emitJob(id);
2122
- this.track(this.runPivotPipeline(id, input));
2484
+ const controller = new AbortController();
2485
+ this.jobControllers.set(id, controller);
2486
+ this.track(
2487
+ this.runPivotPipeline(id, input, controller.signal).finally(() => {
2488
+ this.jobControllers.delete(id);
2489
+ })
2490
+ );
2123
2491
  return job;
2124
2492
  }
2125
2493
  startTrustPositifSyncJob(sourceUrl) {
@@ -2153,56 +2521,312 @@ var JobManager = class {
2153
2521
  );
2154
2522
  return job;
2155
2523
  }
2156
- async runPivotPipeline(jobId, input) {
2524
+ resolveDeepConfig(settings, override) {
2525
+ const clamp = (val, fallback, min, max) => {
2526
+ if (typeof val !== "number" || Number.isNaN(val)) return fallback;
2527
+ return Math.min(Math.max(Math.trunc(val), min), max);
2528
+ };
2529
+ return {
2530
+ enabled: override?.enabled ?? settings.auto_pivot_default,
2531
+ max_depth: clamp(override?.max_depth, settings.auto_pivot_max_depth, 0, 20),
2532
+ max_domains: clamp(override?.max_domains, settings.auto_pivot_max_domains, 10, 5e3),
2533
+ min_score_to_expand: clamp(
2534
+ override?.min_score_to_expand,
2535
+ settings.auto_pivot_min_score,
2536
+ 0,
2537
+ 100
2538
+ ),
2539
+ expand_priority_links: override?.expand_priority_links ?? true,
2540
+ expand_redirects: override?.expand_redirects ?? true,
2541
+ osint_delay_ms: clamp(override?.osint_delay_ms, settings.auto_pivot_osint_delay_ms, 200, 5e3)
2542
+ };
2543
+ }
2544
+ normalizePivotKey(seed) {
2545
+ const norm = normalizeCandidate(seed, /* @__PURE__ */ new Set());
2546
+ return norm.ok ? norm.normalized_domain : seed.trim().toLowerCase();
2547
+ }
2548
+ async runPivotPipeline(jobId, input, signal) {
2157
2549
  try {
2158
2550
  const settings = this.db.getSettings();
2159
2551
  const blacklistSet = this.db.getBlacklistSet();
2552
+ const config = this.resolveDeepConfig(settings, input.deep);
2553
+ const dedupe = createPivotSessionDedupe();
2554
+ let totalNew = 0;
2555
+ let totalProcessed = 0;
2556
+ let totalDuplicates = 0;
2557
+ let totalTargets = input.initialDomainIds?.length ?? 0;
2558
+ const qualifiesForFullExpansion = (d) => d.health_status === "alive" && d.confidence_score >= config.min_score_to_expand;
2559
+ const qualifiesForBridgeExpansion = (d) => {
2560
+ if (d.health_status === "alive" && config.expand_priority_links) {
2561
+ if (d.outbound_links.some((l) => l.priority)) return true;
2562
+ }
2563
+ if (config.expand_redirects) {
2564
+ for (const hop of d.redirect_chain) {
2565
+ const norm = normalizeCandidate(hop.url, blacklistSet);
2566
+ if (norm.ok && norm.normalized_domain !== d.normalized_domain) {
2567
+ return true;
2568
+ }
2569
+ }
2570
+ if (d.final_url) {
2571
+ const norm = normalizeCandidate(d.final_url, blacklistSet);
2572
+ if (norm.ok && norm.normalized_domain !== d.normalized_domain) {
2573
+ return true;
2574
+ }
2575
+ }
2576
+ }
2577
+ return false;
2578
+ };
2579
+ const depthLabel = config.max_depth === 0 ? "\u221E" : String(config.max_depth);
2580
+ const modeDesc = config.enabled ? `Deep Auto-Pivot (max_depth=${depthLabel}, max_domains=${config.max_domains}, min_score=${config.min_score_to_expand})` : "1-Hop Pivot";
2160
2581
  this.db.appendJobLog(
2161
2582
  jobId,
2162
- `Starting Seed Pivot "${input.seed}" [${input.sources.join(", ")}]`
2583
+ `Starting ${modeDesc} for "${input.seed}" [${input.sources.join(", ")}]`
2163
2584
  );
2164
2585
  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
2586
+ let currentWave = [];
2587
+ if (input.initialDomainIds && input.initialDomainIds.length > 0) {
2588
+ this.db.appendJobLog(
2589
+ jobId,
2590
+ `Hop 0: validating ${input.initialDomainIds.length} imported seed domain(s)...`
2591
+ );
2592
+ this.emitJob(jobId);
2593
+ const initialValidated = await this.runValidationBatch(
2594
+ jobId,
2595
+ input.initialDomainIds,
2596
+ signal,
2597
+ () => totalProcessed,
2598
+ (delta) => {
2599
+ totalProcessed += delta;
2600
+ }
2601
+ );
2602
+ const queuedKeys = /* @__PURE__ */ new Set();
2603
+ for (const d of initialValidated) {
2604
+ if (queuedKeys.has(d.normalized_domain)) continue;
2605
+ const full = qualifiesForFullExpansion(d);
2606
+ const bridge = qualifiesForBridgeExpansion(d);
2607
+ if (full || bridge) {
2608
+ queuedKeys.add(d.normalized_domain);
2609
+ currentWave.push({
2610
+ seed: d.normalized_domain,
2611
+ normalizedDomain: d.normalized_domain,
2612
+ depth: 0,
2613
+ isRootSeed: true,
2614
+ alreadyValidatedHtml: true,
2615
+ osintAllowed: full,
2616
+ existingDomain: d,
2617
+ knownIp: d.ip_address,
2618
+ knownTitle: d.page_title,
2619
+ parentDomain: d.normalized_domain
2620
+ });
2621
+ }
2622
+ }
2623
+ } else {
2624
+ const rawSeeds = input.seeds && input.seeds.length > 0 ? input.seeds : [input.seed];
2625
+ const seenRoots = /* @__PURE__ */ new Set();
2626
+ for (const raw of rawSeeds) {
2627
+ const trimmed = raw.trim();
2628
+ if (!trimmed) continue;
2629
+ const key = this.normalizePivotKey(trimmed);
2630
+ if (seenRoots.has(key)) continue;
2631
+ seenRoots.add(key);
2632
+ currentWave.push({
2633
+ seed: trimmed,
2634
+ normalizedDomain: key,
2635
+ depth: 0,
2636
+ isRootSeed: true,
2637
+ alreadyValidatedHtml: false,
2638
+ osintAllowed: true,
2639
+ knownIp: rawSeeds.length === 1 ? input.knownIp : null,
2640
+ knownTitle: rawSeeds.length === 1 ? input.knownTitle : null,
2641
+ parentDomain: trimmed
2642
+ });
2643
+ }
2644
+ }
2645
+ while (currentWave.length > 0 && !signal.aborted) {
2646
+ const hop = currentWave[0].depth + 1;
2647
+ if (!config.enabled && hop > 1) break;
2648
+ if (config.enabled && config.max_depth > 0 && hop > config.max_depth) {
2649
+ this.db.appendJobLog(jobId, `Reached max depth (${config.max_depth}). Stopping.`);
2650
+ break;
2651
+ }
2652
+ if (config.enabled && totalNew >= config.max_domains) {
2653
+ this.db.appendJobLog(jobId, `Reached max domain limit (${config.max_domains}). Stopping.`);
2654
+ break;
2655
+ }
2656
+ const hopHeader = config.enabled ? `Hop ${hop}/${depthLabel}: pivoting ${currentWave.length} target(s)...` : `Hop 1: pivoting ${currentWave.length} target(s)...`;
2657
+ this.db.appendJobLog(jobId, hopHeader);
2658
+ this.emitJob(jobId);
2659
+ const waveNewIds = [];
2660
+ const traversedExisting = [];
2661
+ const traversedKeys = /* @__PURE__ */ new Set();
2662
+ for (const node of currentWave) {
2663
+ if (signal.aborted) break;
2664
+ if (config.enabled && totalNew >= config.max_domains) break;
2665
+ if (dedupe.pivotedDomains.has(node.normalizedDomain)) continue;
2666
+ dedupe.pivotedDomains.add(node.normalizedDomain);
2667
+ const nodeCandidates = [];
2668
+ const seenNodeDomains = /* @__PURE__ */ new Set();
2669
+ const addCandidate = (c) => {
2670
+ if (!seenNodeDomains.has(c.normalized_domain)) {
2671
+ seenNodeDomains.add(c.normalized_domain);
2672
+ nodeCandidates.push(c);
2673
+ }
2674
+ };
2675
+ if (node.existingDomain && input.sources.includes("html")) {
2676
+ const cached = extractCandidatesFromValidatedDomain(
2677
+ node.existingDomain,
2678
+ blacklistSet,
2679
+ config
2680
+ );
2681
+ for (const c of cached) addCandidate(c);
2682
+ }
2683
+ if (node.osintAllowed) {
2684
+ const osintSources = node.alreadyValidatedHtml ? input.sources.filter((s) => s !== "html") : input.sources;
2685
+ if (osintSources.length > 0) {
2686
+ const res = await this.runPivotFn(
2687
+ node.seed,
2688
+ osintSources,
2689
+ {
2690
+ apiKey: settings.urlscan_api_key,
2691
+ knownIp: node.knownIp,
2692
+ knownTitle: node.knownTitle,
2693
+ dedupe,
2694
+ osintDelayMs: config.osint_delay_ms,
2695
+ signal,
2696
+ isRootSeed: node.isRootSeed
2697
+ },
2698
+ blacklistSet
2699
+ );
2700
+ for (const c of res.candidates) addCandidate(c);
2701
+ if (hop === 1) {
2702
+ for (const line of res.logs) {
2703
+ this.db.appendJobLog(jobId, line);
2704
+ }
2705
+ } else {
2706
+ for (const line of res.logs) {
2707
+ if (res.candidates.length > 0 || /429|403|failed|error/i.test(line)) {
2708
+ this.db.appendJobLog(jobId, `[Hop ${hop} \xB7 ${node.normalizedDomain}] ${line}`);
2709
+ }
2710
+ }
2711
+ }
2712
+ }
2713
+ }
2714
+ for (const c of nodeCandidates) {
2715
+ if (signal.aborted) break;
2716
+ if (config.enabled && totalNew >= config.max_domains) break;
2717
+ const ins = this.db.insertDomainIgnore({
2718
+ normalized_domain: c.normalized_domain,
2719
+ original_url: c.original_url,
2720
+ source_type: c.source_type,
2721
+ source_seed: input.seed,
2722
+ parent_domain: node.parentDomain ?? node.normalizedDomain,
2723
+ pivot_depth: hop
2724
+ });
2725
+ if (ins.inserted && ins.id !== null) {
2726
+ waveNewIds.push(ins.id);
2727
+ totalNew++;
2728
+ totalTargets++;
2729
+ } else {
2730
+ totalDuplicates++;
2731
+ if (config.enabled && !dedupe.pivotedDomains.has(c.normalized_domain) && !traversedKeys.has(c.normalized_domain)) {
2732
+ const existing = this.db.getDomainByNormalized(c.normalized_domain);
2733
+ if (existing && (qualifiesForFullExpansion(existing) || qualifiesForBridgeExpansion(existing))) {
2734
+ traversedKeys.add(c.normalized_domain);
2735
+ traversedExisting.push(existing);
2736
+ }
2737
+ }
2738
+ }
2739
+ }
2740
+ }
2741
+ this.db.updateJob(jobId, {
2742
+ total_items: totalTargets,
2743
+ found_new: totalNew,
2744
+ skipped_duplicate: totalDuplicates
2186
2745
  });
2187
- if (res.inserted && res.id !== null) {
2188
- newIds.push(res.id);
2189
- } else {
2190
- duplicates++;
2746
+ this.db.appendJobLog(
2747
+ jobId,
2748
+ `Hop ${hop} discovery: +${waveNewIds.length} new domain(s) queued (total new: ${totalNew}, duplicates skipped: ${totalDuplicates}).`
2749
+ );
2750
+ this.emitJob(jobId);
2751
+ this.emitCounts();
2752
+ if (signal.aborted) break;
2753
+ const waveValidated = waveNewIds.length > 0 ? await this.runValidationBatch(
2754
+ jobId,
2755
+ waveNewIds,
2756
+ signal,
2757
+ () => totalProcessed,
2758
+ (delta) => {
2759
+ totalProcessed += delta;
2760
+ }
2761
+ ) : [];
2762
+ if (!config.enabled || signal.aborted) break;
2763
+ if (config.max_depth > 0 && hop >= config.max_depth) {
2764
+ this.db.appendJobLog(jobId, `Reached max depth (${config.max_depth}). Stopping.`);
2765
+ break;
2766
+ }
2767
+ if (totalNew >= config.max_domains) {
2768
+ this.db.appendJobLog(jobId, `Reached max domain limit (${config.max_domains}). Stopping.`);
2769
+ break;
2770
+ }
2771
+ const nextWave = [];
2772
+ const nextQueuedKeys = /* @__PURE__ */ new Set();
2773
+ for (const d of [...waveValidated, ...traversedExisting]) {
2774
+ if (dedupe.pivotedDomains.has(d.normalized_domain)) continue;
2775
+ if (nextQueuedKeys.has(d.normalized_domain)) continue;
2776
+ const full = qualifiesForFullExpansion(d);
2777
+ const bridge = qualifiesForBridgeExpansion(d);
2778
+ if (full || bridge) {
2779
+ nextQueuedKeys.add(d.normalized_domain);
2780
+ nextWave.push({
2781
+ seed: d.normalized_domain,
2782
+ normalizedDomain: d.normalized_domain,
2783
+ depth: hop,
2784
+ isRootSeed: false,
2785
+ alreadyValidatedHtml: true,
2786
+ osintAllowed: full,
2787
+ existingDomain: d,
2788
+ knownIp: d.ip_address,
2789
+ knownTitle: d.page_title,
2790
+ parentDomain: d.normalized_domain
2791
+ });
2792
+ }
2793
+ }
2794
+ currentWave = nextWave;
2795
+ if (currentWave.length === 0) {
2796
+ this.db.appendJobLog(jobId, "All branches exhausted \u2014 reached root domains.");
2191
2797
  }
2192
2798
  }
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
- );
2799
+ if (signal.aborted) {
2800
+ this.db.appendJobLog(jobId, `Stopped by user after ${totalNew} new domain(s).`);
2801
+ this.db.updateJob(jobId, {
2802
+ status: "cancelled",
2803
+ processed_items: totalProcessed,
2804
+ found_new: totalNew,
2805
+ skipped_duplicate: totalDuplicates,
2806
+ finished: true
2807
+ });
2808
+ } else {
2809
+ this.db.appendJobLog(
2810
+ jobId,
2811
+ `Pivot completed: ${totalNew} new domain(s) discovered, ${totalDuplicates} duplicate(s) skipped.`
2812
+ );
2813
+ this.db.updateJob(jobId, {
2814
+ status: "completed",
2815
+ processed_items: totalProcessed,
2816
+ found_new: totalNew,
2817
+ skipped_duplicate: totalDuplicates,
2818
+ finished: true
2819
+ });
2820
+ }
2202
2821
  this.emitJob(jobId);
2203
2822
  this.emitCounts();
2204
- await this.runValidationPool(jobId, newIds);
2205
2823
  } catch (err) {
2824
+ if (signal.aborted) {
2825
+ this.db.updateJob(jobId, { status: "cancelled", finished: true });
2826
+ this.emitJob(jobId);
2827
+ this.emitCounts();
2828
+ return;
2829
+ }
2206
2830
  const msg = err instanceof Error ? err.message : String(err);
2207
2831
  this.db.appendJobLog(jobId, `Pivot error: ${msg}`);
2208
2832
  this.db.updateJob(jobId, {
@@ -2213,32 +2837,27 @@ var JobManager = class {
2213
2837
  this.emitJob(jobId);
2214
2838
  }
2215
2839
  }
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
- }
2840
+ async runValidationBatch(jobId, domainIds, signal, getTotalProcessed, addProcessed) {
2841
+ if (domainIds.length === 0) return [];
2223
2842
  const settings = this.db.getSettings();
2224
2843
  const keywords = this.db.listKeywords(true);
2225
2844
  const blacklistSet = this.db.getBlacklistSet();
2226
2845
  const concurrency = Math.max(1, settings.concurrency);
2227
2846
  let index = 0;
2228
- let processed = 0;
2847
+ const validatedItems = [];
2229
2848
  const worker = async () => {
2230
- while (index < domainIds.length) {
2849
+ while (index < domainIds.length && !signal?.aborted) {
2231
2850
  const currentIdx = index++;
2232
2851
  const domainId = domainIds[currentIdx];
2233
2852
  if (domainId === void 0) break;
2234
2853
  const row = this.db.getDomainById(domainId);
2235
2854
  if (!row) {
2236
- processed++;
2855
+ addProcessed(1);
2237
2856
  continue;
2238
2857
  }
2239
2858
  this.db.markDomainChecking(domainId);
2240
2859
  try {
2241
- const result = await validateDomain(row, {
2860
+ const result = await this.validateDomainFn(row, {
2242
2861
  settings,
2243
2862
  keywords,
2244
2863
  blacklistSet,
@@ -2246,6 +2865,7 @@ var JobManager = class {
2246
2865
  });
2247
2866
  const updated = this.db.updateDomainValidation(domainId, result);
2248
2867
  if (updated) {
2868
+ validatedItems.push(updated);
2249
2869
  this.emit({ type: "domain_update", domain: updated });
2250
2870
  }
2251
2871
  } catch (err) {
@@ -2264,12 +2884,14 @@ var JobManager = class {
2264
2884
  trustpositif_blocked: false
2265
2885
  });
2266
2886
  if (updated) {
2887
+ validatedItems.push(updated);
2267
2888
  this.emit({ type: "domain_update", domain: updated });
2268
2889
  }
2269
2890
  }
2270
- processed++;
2271
- if (processed % 3 === 0 || processed === domainIds.length) {
2272
- this.db.updateJob(jobId, { processed_items: processed });
2891
+ addProcessed(1);
2892
+ const totalDone = getTotalProcessed();
2893
+ if (totalDone % 3 === 0 || index >= domainIds.length) {
2894
+ this.db.updateJob(jobId, { processed_items: totalDone });
2273
2895
  this.emitJob(jobId);
2274
2896
  this.emitCounts();
2275
2897
  }
@@ -2277,12 +2899,43 @@ var JobManager = class {
2277
2899
  };
2278
2900
  const workers = Array.from({ length: Math.min(concurrency, domainIds.length) }, () => worker());
2279
2901
  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
- });
2902
+ this.db.updateJob(jobId, { processed_items: getTotalProcessed() });
2903
+ this.emitJob(jobId);
2904
+ this.emitCounts();
2905
+ return validatedItems;
2906
+ }
2907
+ async runValidationPool(jobId, domainIds, signal) {
2908
+ if (domainIds.length === 0) {
2909
+ this.db.updateJob(jobId, { status: "completed", finished: true });
2910
+ this.emitJob(jobId);
2911
+ this.emitCounts();
2912
+ return;
2913
+ }
2914
+ let processed = 0;
2915
+ await this.runValidationBatch(
2916
+ jobId,
2917
+ domainIds,
2918
+ signal,
2919
+ () => processed,
2920
+ (delta) => {
2921
+ processed += delta;
2922
+ }
2923
+ );
2924
+ if (signal?.aborted) {
2925
+ this.db.appendJobLog(jobId, `Validation stopped by user (${processed}/${domainIds.length}).`);
2926
+ this.db.updateJob(jobId, {
2927
+ status: "cancelled",
2928
+ processed_items: processed,
2929
+ finished: true
2930
+ });
2931
+ } else {
2932
+ this.db.appendJobLog(jobId, `Validation finished (${processed}/${domainIds.length} domains).`);
2933
+ this.db.updateJob(jobId, {
2934
+ status: "completed",
2935
+ processed_items: processed,
2936
+ finished: true
2937
+ });
2938
+ }
2286
2939
  this.emitJob(jobId);
2287
2940
  this.emitCounts();
2288
2941
  }