@rasyid2567/urlscanner 0.1.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
@@ -2,13 +2,13 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { spawn as spawn2 } from "child_process";
5
- import fs3 from "fs";
6
- import os from "os";
7
- import path3 from "path";
5
+ import fs4 from "fs";
6
+ import os2 from "os";
7
+ import path4 from "path";
8
8
  import { parseArgs } from "util";
9
9
 
10
10
  // src/config.ts
11
- var APP_VERSION = "0.1.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
  }
@@ -2376,7 +3029,7 @@ var TrustPositifService = class {
2376
3029
  try {
2377
3030
  const resp = await fetchFn(sourceUrl, {
2378
3031
  signal: controller.signal,
2379
- headers: { "User-Agent": "URLScanner/0.1.0" }
3032
+ headers: { "User-Agent": `URLScanner/${APP_VERSION}` }
2380
3033
  });
2381
3034
  if (!resp.ok) {
2382
3035
  throw new Error(`TrustPositif sync HTTP ${resp.status}`);
@@ -2510,13 +3163,40 @@ function startHttpServer(app, host, port) {
2510
3163
  });
2511
3164
  }
2512
3165
 
3166
+ // src/tui/browser.ts
3167
+ import { spawn } from "child_process";
3168
+ function openBrowser(url) {
3169
+ try {
3170
+ const platform = process.platform;
3171
+ let cmd = "xdg-open";
3172
+ let args = [url];
3173
+ if (platform === "darwin") {
3174
+ cmd = "open";
3175
+ args = [url];
3176
+ } else if (platform === "win32") {
3177
+ cmd = "cmd";
3178
+ args = ["/c", "start", "", url];
3179
+ }
3180
+ const child = spawn(cmd, args, {
3181
+ detached: true,
3182
+ stdio: "ignore",
3183
+ windowsHide: true
3184
+ });
3185
+ child.unref();
3186
+ return true;
3187
+ } catch {
3188
+ return false;
3189
+ }
3190
+ }
3191
+
2513
3192
  // src/tui/ansi.ts
2514
3193
  var ANSI = {
2515
3194
  reset: "\x1B[0m",
2516
3195
  bold: "\x1B[1m",
2517
3196
  dim: "\x1B[2m",
2518
3197
  amber: "\x1B[38;5;209m",
2519
- green: "\x1B[38;5;71m",
3198
+ brand: "\x1B[38;5;43m",
3199
+ green: "\x1B[38;5;78m",
2520
3200
  cyan: "\x1B[38;5;37m",
2521
3201
  red: "\x1B[38;5;203m",
2522
3202
  yellow: "\x1B[38;5;221m",
@@ -2536,31 +3216,6 @@ function padStart(str, width) {
2536
3216
  return " ".repeat(width - str.length) + str;
2537
3217
  }
2538
3218
 
2539
- // src/tui/browser.ts
2540
- import { spawn } from "child_process";
2541
- function openBrowser(url) {
2542
- try {
2543
- const platform = process.platform;
2544
- let cmd = "xdg-open";
2545
- let args = [url];
2546
- if (platform === "darwin") {
2547
- cmd = "open";
2548
- args = [url];
2549
- } else if (platform === "win32") {
2550
- cmd = "cmd";
2551
- args = ["/c", "start", "", url];
2552
- }
2553
- const child = spawn(cmd, args, {
2554
- detached: true,
2555
- stdio: "ignore"
2556
- });
2557
- child.unref();
2558
- return true;
2559
- } catch {
2560
- return false;
2561
- }
2562
- }
2563
-
2564
3219
  // src/tui/clipboard.ts
2565
3220
  import { spawnSync } from "child_process";
2566
3221
  function copyToClipboard(text) {
@@ -2610,7 +3265,7 @@ async function runInteractiveTui(url, ctx) {
2610
3265
  if (cursor < 0) cursor = 0;
2611
3266
  const lines = [];
2612
3267
  lines.push(
2613
- `${ANSI.amber}${ANSI.bold} URLScanner Terminal UI v${APP_VERSION}${ANSI.reset} ${ANSI.dim}\u2502${ANSI.reset} ${ANSI.green}${url}${ANSI.reset}`
3268
+ `${ANSI.brand}${ANSI.bold} URLScanner Terminal UI v${APP_VERSION}${ANSI.reset} ${ANSI.dim}\u2502${ANSI.reset} ${ANSI.green}${url}${ANSI.reset}`
2614
3269
  );
2615
3270
  lines.push(
2616
3271
  ` 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}`
@@ -2841,23 +3496,27 @@ async function runInteractiveTui(url, ctx) {
2841
3496
  }
2842
3497
 
2843
3498
  // src/tui/launcher.ts
2844
- var MENU_ITEMS = [
2845
- { key: "web", label: "Web UI (Open in Browser)" },
2846
- { key: "tui", label: "Terminal UI (Interactive CLI)" },
2847
- { key: "daemon", label: "Run in Background (Daemon)" },
2848
- { key: "exit", label: "Exit" }
2849
- ];
2850
- function renderLauncherMenu(url, selectedIdx) {
2851
- const divider = `${ANSI.amber}============================================${ANSI.reset}`;
3499
+ function getMenuItems(_alreadyRunning = false) {
3500
+ return [
3501
+ { key: "web", label: "Web UI (Open in Browser)" },
3502
+ { key: "tui", label: "Terminal UI (Interactive CLI)" },
3503
+ { key: "daemon", label: "Hide to Tray (Background)" },
3504
+ { key: "exit", label: "Exit" }
3505
+ ];
3506
+ }
3507
+ function renderLauncherMenu(url, selectedIdx, alreadyRunning = false) {
3508
+ const divider = `${ANSI.brand}============================================${ANSI.reset}`;
3509
+ const items = getMenuItems(alreadyRunning);
3510
+ const statusSuffix = alreadyRunning ? ` ${ANSI.dim}(running in background)${ANSI.reset}` : "";
2852
3511
  const lines = [
2853
3512
  "",
2854
3513
  divider,
2855
- ` ${ANSI.amber}${ANSI.bold}Choose Interface (v${APP_VERSION})${ANSI.reset}`,
2856
- ` \u{1F680} ${ANSI.dim}Server:${ANSI.reset} ${ANSI.green}${url}${ANSI.reset}`,
3514
+ ` ${ANSI.brand}${ANSI.bold}Choose Interface (v${APP_VERSION})${ANSI.reset}`,
3515
+ ` \u25CF ${ANSI.dim}Server:${ANSI.reset} ${ANSI.green}${url}${ANSI.reset}${statusSuffix}`,
2857
3516
  divider,
2858
3517
  ""
2859
3518
  ];
2860
- MENU_ITEMS.forEach((item, idx) => {
3519
+ items.forEach((item, idx) => {
2861
3520
  if (idx === selectedIdx) {
2862
3521
  lines.push(` ${ANSI.selectedBg} \u2605 ${item.label} ${ANSI.reset}`);
2863
3522
  } else {
@@ -2867,13 +3526,15 @@ function renderLauncherMenu(url, selectedIdx) {
2867
3526
  lines.push("", `${ANSI.dim} Use \u2191/\u2193 (or j/k) and Enter to select, Ctrl+C to quit${ANSI.reset}`, "");
2868
3527
  return lines.join("\n");
2869
3528
  }
2870
- async function runLauncherMenu(url) {
3529
+ async function runLauncherMenu(url, options) {
2871
3530
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
2872
3531
  return "web";
2873
3532
  }
3533
+ const alreadyRunning = Boolean(options?.alreadyRunning);
3534
+ const items = getMenuItems(alreadyRunning);
2874
3535
  let selected = 0;
2875
3536
  const draw = () => {
2876
- process.stdout.write(ANSI.clearScreen + renderLauncherMenu(url, selected));
3537
+ process.stdout.write(ANSI.clearScreen + renderLauncherMenu(url, selected, alreadyRunning));
2877
3538
  };
2878
3539
  return new Promise((resolve) => {
2879
3540
  const stdin = process.stdin;
@@ -2897,24 +3558,24 @@ async function runLauncherMenu(url) {
2897
3558
  }
2898
3559
  if (s === "\r" || s === "\n") {
2899
3560
  cleanup();
2900
- resolve(MENU_ITEMS[selected].key);
3561
+ resolve(items[selected].key);
2901
3562
  return;
2902
3563
  }
2903
3564
  if (s === "\x1B[A" || s === "k") {
2904
- selected = (selected - 1 + MENU_ITEMS.length) % MENU_ITEMS.length;
3565
+ selected = (selected - 1 + items.length) % items.length;
2905
3566
  draw();
2906
3567
  return;
2907
3568
  }
2908
3569
  if (s === "\x1B[B" || s === "j") {
2909
- selected = (selected + 1) % MENU_ITEMS.length;
3570
+ selected = (selected + 1) % items.length;
2910
3571
  draw();
2911
3572
  return;
2912
3573
  }
2913
- if (s >= "1" && s <= "4") {
3574
+ if (s >= "1" && s <= String(items.length)) {
2914
3575
  const idx = Number.parseInt(s, 10) - 1;
2915
3576
  selected = idx;
2916
3577
  cleanup();
2917
- resolve(MENU_ITEMS[selected].key);
3578
+ resolve(items[selected].key);
2918
3579
  }
2919
3580
  };
2920
3581
  stdin.on("data", onData);
@@ -2926,13 +3587,13 @@ async function runWebWaitingLoop(url, ctx, shouldOpen = true) {
2926
3587
  }
2927
3588
  const draw = () => {
2928
3589
  const counts = ctx.db.getQueueCounts();
2929
- const divider = `${ANSI.amber}============================================${ANSI.reset}`;
3590
+ const divider = `${ANSI.brand}============================================${ANSI.reset}`;
2930
3591
  process.stdout.write(
2931
3592
  ANSI.clearScreen + [
2932
3593
  "",
2933
3594
  divider,
2934
- ` ${ANSI.amber}${ANSI.bold}URLScanner Web UI Active (v${APP_VERSION})${ANSI.reset}`,
2935
- ` \u{1F680} ${ANSI.dim}URL:${ANSI.reset} ${ANSI.green}${url}${ANSI.reset}`,
3595
+ ` ${ANSI.brand}${ANSI.bold}URLScanner Dashboard Active (v${APP_VERSION})${ANSI.reset}`,
3596
+ ` \u25CF ${ANSI.dim}URL:${ANSI.reset} ${ANSI.green}${url}${ANSI.reset}`,
2936
3597
  divider,
2937
3598
  "",
2938
3599
  ` Ready Queue (New) : ${ANSI.bold}${counts.new_count}${ANSI.reset}`,
@@ -2979,9 +3640,312 @@ async function runWebWaitingLoop(url, ctx, shouldOpen = true) {
2979
3640
  });
2980
3641
  }
2981
3642
 
3643
+ // src/tui/tray.ts
3644
+ import fs3 from "fs";
3645
+ import { createRequire } from "module";
3646
+ import os from "os";
3647
+ import path3 from "path";
3648
+
3649
+ // src/tui/trayIcon.ts
3650
+ import { deflateSync } from "zlib";
3651
+ var CRC_TABLE = (() => {
3652
+ const table = new Uint32Array(256);
3653
+ for (let n = 0; n < 256; n++) {
3654
+ let c = n;
3655
+ for (let k = 0; k < 8; k++) {
3656
+ c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
3657
+ }
3658
+ table[n] = c >>> 0;
3659
+ }
3660
+ return table;
3661
+ })();
3662
+ function crc32(buf) {
3663
+ let c = 4294967295;
3664
+ for (let i = 0; i < buf.length; i++) {
3665
+ c = CRC_TABLE[(c ^ buf[i]) & 255] ^ c >>> 8;
3666
+ }
3667
+ return (c ^ 4294967295) >>> 0;
3668
+ }
3669
+ function pngChunk(type, data) {
3670
+ const len = Buffer.alloc(4);
3671
+ len.writeUInt32BE(data.length, 0);
3672
+ const typeBuf = Buffer.from(type, "ascii");
3673
+ const crcBuf = Buffer.alloc(4);
3674
+ crcBuf.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0);
3675
+ return Buffer.concat([len, typeBuf, data, crcBuf]);
3676
+ }
3677
+ function renderUrlScannerPixels(size) {
3678
+ const pixels = new Uint8Array(size * size * 4);
3679
+ const bg = [20, 36, 35, 255];
3680
+ const bgBorder = [20, 184, 166, 96];
3681
+ const teal = [20, 184, 166, 255];
3682
+ const white = [237, 237, 237, 235];
3683
+ const setPixel = (x, y, color) => {
3684
+ if (x < 0 || y < 0 || x >= size || y >= size) return;
3685
+ const idx = (y * size + x) * 4;
3686
+ pixels[idx] = color[0];
3687
+ pixels[idx + 1] = color[1];
3688
+ pixels[idx + 2] = color[2];
3689
+ pixels[idx + 3] = color[3];
3690
+ };
3691
+ const radius = size * 0.24;
3692
+ const cx = (size - 1) / 2;
3693
+ const cy = (size - 1) / 2;
3694
+ const half = size / 2 - 1;
3695
+ for (let y = 0; y < size; y++) {
3696
+ for (let x = 0; x < size; x++) {
3697
+ const dx = Math.max(Math.abs(x - cx) - (half - radius), 0);
3698
+ const dy = Math.max(Math.abs(y - cy) - (half - radius), 0);
3699
+ const dist = Math.hypot(dx, dy);
3700
+ if (dist <= radius) {
3701
+ if (dist >= radius - 1.2) {
3702
+ setPixel(x, y, bgBorder);
3703
+ } else {
3704
+ setPixel(x, y, bg);
3705
+ }
3706
+ }
3707
+ }
3708
+ }
3709
+ const s = (v) => v / 24 * size;
3710
+ const stroke = Math.max(1.5, size / 14);
3711
+ const drawRect = (x1, y1, x2, y2, color) => {
3712
+ const ix1 = Math.floor(s(x1));
3713
+ const iy1 = Math.floor(s(y1));
3714
+ const ix2 = Math.ceil(s(x2));
3715
+ const iy2 = Math.ceil(s(y2));
3716
+ for (let y = iy1; y <= iy2; y++) {
3717
+ for (let x = ix1; x <= ix2; x++) {
3718
+ setPixel(x, y, color);
3719
+ }
3720
+ }
3721
+ };
3722
+ const arm = 4.6;
3723
+ const t = 1.9;
3724
+ const pad = 4.2;
3725
+ drawRect(pad, pad, pad + arm, pad + t, teal);
3726
+ drawRect(pad, pad, pad + t, pad + arm, teal);
3727
+ drawRect(24 - pad - arm, pad, 24 - pad, pad + t, teal);
3728
+ drawRect(24 - pad - t, pad, 24 - pad, pad + arm, teal);
3729
+ drawRect(pad, 24 - pad - t, pad + arm, 24 - pad, teal);
3730
+ drawRect(pad, 24 - pad - arm, pad + t, 24 - pad, teal);
3731
+ drawRect(24 - pad - arm, 24 - pad - t, 24 - pad, 24 - pad, teal);
3732
+ drawRect(24 - pad - t, 24 - pad - arm, 24 - pad, 24 - pad, teal);
3733
+ const ringR = s(4.2);
3734
+ for (let y = 0; y < size; y++) {
3735
+ for (let x = 0; x < size; x++) {
3736
+ const dist = Math.hypot(x - cx, y - cy);
3737
+ if (Math.abs(dist - ringR) <= stroke * 0.48) {
3738
+ setPixel(x, y, white);
3739
+ }
3740
+ }
3741
+ }
3742
+ drawRect(5.2, 11.1, 18.8, 12.9, teal);
3743
+ const dotR = s(1.7);
3744
+ for (let y = 0; y < size; y++) {
3745
+ for (let x = 0; x < size; x++) {
3746
+ if (Math.hypot(x - cx, y - cy) <= dotR) {
3747
+ setPixel(x, y, teal);
3748
+ }
3749
+ }
3750
+ }
3751
+ return pixels;
3752
+ }
3753
+ function buildPngBase64(size = 64) {
3754
+ const rgba = renderUrlScannerPixels(size);
3755
+ const stride = size * 4;
3756
+ const raw = Buffer.alloc((stride + 1) * size);
3757
+ for (let y = 0; y < size; y++) {
3758
+ const rowStart = y * (stride + 1);
3759
+ raw[rowStart] = 0;
3760
+ Buffer.from(rgba.buffer, y * stride, stride).copy(raw, rowStart + 1);
3761
+ }
3762
+ const ihdr = Buffer.alloc(13);
3763
+ ihdr.writeUInt32BE(size, 0);
3764
+ ihdr.writeUInt32BE(size, 4);
3765
+ ihdr[8] = 8;
3766
+ ihdr[9] = 6;
3767
+ ihdr[10] = 0;
3768
+ ihdr[11] = 0;
3769
+ ihdr[12] = 0;
3770
+ const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
3771
+ const compressed = deflateSync(raw);
3772
+ return Buffer.concat([
3773
+ signature,
3774
+ pngChunk("IHDR", ihdr),
3775
+ pngChunk("IDAT", compressed),
3776
+ pngChunk("IEND", Buffer.alloc(0))
3777
+ ]).toString("base64");
3778
+ }
3779
+ function buildIcoBase64(size = 32) {
3780
+ const rgba = renderUrlScannerPixels(size);
3781
+ const pixelBytes = size * size * 4;
3782
+ const andMaskRowBytes = Math.ceil(size / 32) * 4;
3783
+ const andMaskBytes = andMaskRowBytes * size;
3784
+ const imageSize = 40 + pixelBytes + andMaskBytes;
3785
+ const out = Buffer.alloc(6 + 16 + imageSize);
3786
+ out.writeUInt16LE(0, 0);
3787
+ out.writeUInt16LE(1, 2);
3788
+ out.writeUInt16LE(1, 4);
3789
+ out[6] = size === 256 ? 0 : size;
3790
+ out[7] = size === 256 ? 0 : size;
3791
+ out[8] = 0;
3792
+ out[9] = 0;
3793
+ out.writeUInt16LE(1, 10);
3794
+ out.writeUInt16LE(32, 12);
3795
+ out.writeUInt32LE(imageSize, 14);
3796
+ out.writeUInt32LE(22, 18);
3797
+ const bmpOffset = 22;
3798
+ out.writeUInt32LE(40, bmpOffset);
3799
+ out.writeInt32LE(size, bmpOffset + 4);
3800
+ out.writeInt32LE(size * 2, bmpOffset + 8);
3801
+ out.writeUInt16LE(1, bmpOffset + 12);
3802
+ out.writeUInt16LE(32, bmpOffset + 14);
3803
+ out.writeUInt32LE(0, bmpOffset + 16);
3804
+ out.writeUInt32LE(pixelBytes + andMaskBytes, bmpOffset + 20);
3805
+ let dst = bmpOffset + 40;
3806
+ for (let y = size - 1; y >= 0; y--) {
3807
+ for (let x = 0; x < size; x++) {
3808
+ const src = (y * size + x) * 4;
3809
+ out[dst++] = rgba[src + 2];
3810
+ out[dst++] = rgba[src + 1];
3811
+ out[dst++] = rgba[src];
3812
+ out[dst++] = rgba[src + 3];
3813
+ }
3814
+ }
3815
+ return out.toString("base64");
3816
+ }
3817
+ var TRAY_ICON_PNG_BASE64 = buildPngBase64(64);
3818
+ var TRAY_ICON_ICO_BASE64 = buildIcoBase64(32);
3819
+ function getTrayIconForPlatform(platform = process.platform) {
3820
+ return platform === "win32" ? TRAY_ICON_ICO_BASE64 : TRAY_ICON_PNG_BASE64;
3821
+ }
3822
+
3823
+ // src/tui/tray.ts
3824
+ function shouldEnableTray(options) {
3825
+ if (options.noTray) return false;
3826
+ const platform = options.platform ?? process.platform;
3827
+ const env = options.env ?? process.env;
3828
+ if (platform === "linux") {
3829
+ return Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
3830
+ }
3831
+ return platform === "win32" || platform === "darwin";
3832
+ }
3833
+ function getBinName(platform) {
3834
+ if (platform === "win32") return "tray_windows_release.exe";
3835
+ if (platform === "darwin") return "tray_darwin_release";
3836
+ if (platform === "linux") return "tray_linux_release";
3837
+ return null;
3838
+ }
3839
+ function prepareExecutableCopyDir() {
3840
+ const binName = getBinName(process.platform);
3841
+ if (!binName) return true;
3842
+ try {
3843
+ const require2 = createRequire(import.meta.url);
3844
+ const entryPath = require2.resolve("systray2");
3845
+ const pkgDir = path3.dirname(entryPath);
3846
+ const pkgJson = JSON.parse(fs3.readFileSync(path3.join(pkgDir, "package.json"), "utf8"));
3847
+ const version = pkgJson.version || "2.1.4";
3848
+ const srcBin = path3.join(pkgDir, "traybin", binName);
3849
+ const cacheRoot = path3.join(os.homedir(), ".cache", "node-systray");
3850
+ const destDir = path3.join(cacheRoot, version);
3851
+ const destBin = path3.join(destDir, binName);
3852
+ fs3.mkdirSync(destDir, { recursive: true });
3853
+ if (!fs3.existsSync(destBin)) {
3854
+ fs3.copyFileSync(srcBin, destBin);
3855
+ }
3856
+ if (process.platform !== "win32") {
3857
+ fs3.chmodSync(destBin, 493);
3858
+ }
3859
+ return cacheRoot;
3860
+ } catch {
3861
+ return true;
3862
+ }
3863
+ }
3864
+ async function startSystemTray(options) {
3865
+ if (!shouldEnableTray({ noTray: options.noTray })) {
3866
+ return null;
3867
+ }
3868
+ let systray = null;
3869
+ try {
3870
+ const copyDir = prepareExecutableCopyDir();
3871
+ const mod = await import("systray2");
3872
+ const SysTrayCtor = mod.default?.default ?? mod.default;
3873
+ const statusItem = {
3874
+ title: `URLScanner (:${options.port})`,
3875
+ tooltip: options.serverUrl,
3876
+ checked: false,
3877
+ enabled: false
3878
+ };
3879
+ const openItem = {
3880
+ title: "Open Dashboard",
3881
+ tooltip: `Open ${options.serverUrl} in browser`,
3882
+ checked: false,
3883
+ enabled: true
3884
+ };
3885
+ const quitItem = {
3886
+ title: "Quit",
3887
+ tooltip: "Stop URLScanner daemon",
3888
+ checked: false,
3889
+ enabled: true
3890
+ };
3891
+ const items = SysTrayCtor.separator ? [statusItem, SysTrayCtor.separator, openItem, quitItem] : [statusItem, openItem, quitItem];
3892
+ systray = new SysTrayCtor({
3893
+ menu: {
3894
+ icon: getTrayIconForPlatform(),
3895
+ title: "",
3896
+ tooltip: `URLScanner \u2014 ${options.serverUrl}`,
3897
+ items
3898
+ },
3899
+ debug: false,
3900
+ copyDir
3901
+ });
3902
+ await Promise.race([
3903
+ systray.ready(),
3904
+ new Promise(
3905
+ (_, reject) => setTimeout(() => reject(new Error("Tray initialization timed out")), 4e3)
3906
+ )
3907
+ ]);
3908
+ systray.onError((err) => {
3909
+ console.error(`Tray warning: ${err.message}`);
3910
+ });
3911
+ await systray.onClick((action) => {
3912
+ const clickedTitle = action.item?.title ?? "";
3913
+ if (clickedTitle === "Open Dashboard") {
3914
+ openBrowser(options.serverUrl);
3915
+ } else if (clickedTitle === "Quit") {
3916
+ options.onQuit();
3917
+ }
3918
+ });
3919
+ const activeTray = systray;
3920
+ return {
3921
+ kill: async () => {
3922
+ try {
3923
+ if (activeTray.process && !activeTray.killed) {
3924
+ await activeTray.kill(false);
3925
+ }
3926
+ } catch {
3927
+ try {
3928
+ activeTray.process?.kill("SIGKILL");
3929
+ } catch {
3930
+ }
3931
+ }
3932
+ }
3933
+ };
3934
+ } catch (err) {
3935
+ try {
3936
+ systray?.process?.kill("SIGKILL");
3937
+ } catch {
3938
+ }
3939
+ console.error(
3940
+ `System tray unavailable (${err instanceof Error ? err.message : String(err)}); running headless daemon.`
3941
+ );
3942
+ return null;
3943
+ }
3944
+ }
3945
+
2982
3946
  // src/cli.ts
2983
3947
  function defaultDataDir() {
2984
- return process.env.URLSCANNER_DATA_DIR || path3.join(os.homedir(), ".urlscanner");
3948
+ return process.env.URLSCANNER_DATA_DIR || path4.join(os2.homedir(), ".urlscanner");
2985
3949
  }
2986
3950
  function isProcessAlive(pid) {
2987
3951
  try {
@@ -2993,12 +3957,12 @@ function isProcessAlive(pid) {
2993
3957
  }
2994
3958
  function readPidFile(pidPath) {
2995
3959
  try {
2996
- if (!fs3.existsSync(pidPath)) return null;
2997
- const info = JSON.parse(fs3.readFileSync(pidPath, "utf8"));
3960
+ if (!fs4.existsSync(pidPath)) return null;
3961
+ const info = JSON.parse(fs4.readFileSync(pidPath, "utf8"));
2998
3962
  if (info && typeof info.pid === "number" && isProcessAlive(info.pid)) {
2999
3963
  return info;
3000
3964
  }
3001
- fs3.rmSync(pidPath, { force: true });
3965
+ fs4.rmSync(pidPath, { force: true });
3002
3966
  return null;
3003
3967
  } catch {
3004
3968
  return null;
@@ -3020,6 +3984,7 @@ Options:
3020
3984
  --tui Open Interactive Terminal UI directly
3021
3985
  --no-open Do not auto-open browser in Web UI mode
3022
3986
  --no-menu Run headless server without interactive terminal menu
3987
+ --no-tray Disable system tray icon in background daemon mode
3023
3988
  --daemon Run in background daemon mode
3024
3989
  -v, --version Print version
3025
3990
  -h, --help Show this help message
@@ -3037,8 +4002,20 @@ async function waitForHealth(url, timeoutMs = 6e3) {
3037
4002
  }
3038
4003
  return false;
3039
4004
  }
4005
+ async function checkExistingUrlScanner(host, port) {
4006
+ try {
4007
+ const resp = await fetch(`http://${host}:${port}/api/health`, {
4008
+ signal: AbortSignal.timeout(800)
4009
+ });
4010
+ if (!resp.ok) return false;
4011
+ const data = await resp.json();
4012
+ return data?.status === "ok" && typeof data.counts === "object";
4013
+ } catch {
4014
+ return false;
4015
+ }
4016
+ }
3040
4017
  async function handleStatus(dataDir) {
3041
- const pidPath = path3.join(dataDir, "server.pid");
4018
+ const pidPath = path4.join(dataDir, "server.pid");
3042
4019
  const info = readPidFile(pidPath);
3043
4020
  if (!info) {
3044
4021
  console.log("URLScanner daemon is not running.");
@@ -3050,11 +4027,11 @@ async function handleStatus(dataDir) {
3050
4027
  console.log(`Data dir: ${info.dataDir}`);
3051
4028
  }
3052
4029
  async function handleStop(dataDir) {
3053
- const pidPath = path3.join(dataDir, "server.pid");
4030
+ const pidPath = path4.join(dataDir, "server.pid");
3054
4031
  const info = readPidFile(pidPath);
3055
4032
  if (!info) {
3056
4033
  console.log("URLScanner daemon is not running.");
3057
- return;
4034
+ return false;
3058
4035
  }
3059
4036
  try {
3060
4037
  process.kill(info.pid, "SIGTERM");
@@ -3064,13 +4041,14 @@ async function handleStop(dataDir) {
3064
4041
  while (Date.now() < deadline && isProcessAlive(info.pid)) {
3065
4042
  await new Promise((r) => setTimeout(r, 150));
3066
4043
  }
3067
- fs3.rmSync(pidPath, { force: true });
4044
+ fs4.rmSync(pidPath, { force: true });
3068
4045
  console.log(`Stopped URLScanner daemon (PID ${info.pid}).`);
4046
+ return true;
3069
4047
  }
3070
- async function spawnDaemon(host, port, dataDir) {
3071
- fs3.mkdirSync(dataDir, { recursive: true });
3072
- const logPath = path3.join(dataDir, "server.log");
3073
- const logFd = fs3.openSync(logPath, "a");
4048
+ async function spawnDaemon(host, port, dataDir, noTray = false) {
4049
+ fs4.mkdirSync(dataDir, { recursive: true });
4050
+ const logPath = path4.join(dataDir, "server.log");
4051
+ const logFd = fs4.openSync(logPath, "a");
3074
4052
  const scriptPath = process.argv[1];
3075
4053
  const args = [
3076
4054
  scriptPath,
@@ -3082,22 +4060,30 @@ async function spawnDaemon(host, port, dataDir) {
3082
4060
  "--data-dir",
3083
4061
  dataDir
3084
4062
  ];
4063
+ if (noTray) {
4064
+ args.push("--no-tray");
4065
+ }
3085
4066
  const child = spawn2(process.execPath, args, {
3086
4067
  detached: true,
3087
- stdio: ["ignore", logFd, logFd]
4068
+ stdio: ["ignore", logFd, logFd],
4069
+ windowsHide: true
3088
4070
  });
3089
4071
  child.unref();
3090
4072
  const url = `http://${host === "127.0.0.1" ? "localhost" : host}:${port}`;
3091
4073
  const ok = await waitForHealth(`http://${host}:${port}`, 6e3);
3092
4074
  if (ok) {
4075
+ const trayEnabled = shouldEnableTray({ noTray });
3093
4076
  console.log(`
3094
4077
  \u{1F680} URLScanner running in background (PID ${child.pid})`);
3095
- console.log(` Web UI : ${url}`);
3096
- console.log(` Log : ${logPath}`);
3097
- console.log(` Kelola : urlscanner status | urlscanner stop
4078
+ console.log(` Dashboard : ${url}`);
4079
+ console.log(
4080
+ ` Tray : ${trayEnabled ? "Enabled (Open Dashboard / Quit)" : noTray ? "Disabled (--no-tray)" : "Headless"}`
4081
+ );
4082
+ console.log(` Log : ${logPath}`);
4083
+ console.log(` Manage : urlscanner status | urlscanner stop
3098
4084
  `);
3099
4085
  } else {
3100
- console.error(`Gagal menjalankan daemon. Cek log di ${logPath}`);
4086
+ console.error(`Failed to start daemon. Check logs at ${logPath}`);
3101
4087
  process.exitCode = 1;
3102
4088
  }
3103
4089
  }
@@ -3112,6 +4098,7 @@ async function main() {
3112
4098
  tui: { type: "boolean", default: false },
3113
4099
  "no-open": { type: "boolean", default: false },
3114
4100
  "no-menu": { type: "boolean", default: false },
4101
+ "no-tray": { type: "boolean", default: false },
3115
4102
  daemon: { type: "boolean", default: false },
3116
4103
  version: { type: "boolean", short: "v", default: false },
3117
4104
  help: { type: "boolean", short: "h", default: false }
@@ -3125,7 +4112,7 @@ async function main() {
3125
4112
  console.log(APP_VERSION);
3126
4113
  return;
3127
4114
  }
3128
- const dataDir = path3.resolve(values["data-dir"] || defaultDataDir());
4115
+ const dataDir = path4.resolve(values["data-dir"] || defaultDataDir());
3129
4116
  const subcommand = positionals[0];
3130
4117
  if (subcommand === "status") {
3131
4118
  await handleStatus(dataDir);
@@ -3137,31 +4124,55 @@ async function main() {
3137
4124
  }
3138
4125
  const host = values.host || DEFAULT_HOST;
3139
4126
  const port = Number.parseInt(values.port || String(DEFAULT_PORT), 10) || DEFAULT_PORT;
3140
- const dbPath = path3.join(dataDir, "scanner.db");
4127
+ const displayHost = host === "127.0.0.1" ? "localhost" : host;
4128
+ const dbPath = path4.join(dataDir, "scanner.db");
3141
4129
  const db = new AppDatabase(dbPath);
3142
4130
  const ctx = createContext(db);
3143
4131
  const app = createApp(ctx);
3144
- const started = await startHttpServer(app, host, port);
3145
- const displayHost = host === "127.0.0.1" ? "localhost" : host;
3146
- const serverUrl = `http://${displayHost}:${started.port}`;
3147
- const pidPath = path3.join(dataDir, "server.pid");
4132
+ const alreadyRunning = !values.daemon && await checkExistingUrlScanner(host, port);
4133
+ let started = null;
4134
+ if (!alreadyRunning) {
4135
+ try {
4136
+ started = await startHttpServer(app, host, port);
4137
+ } catch (err) {
4138
+ const code = err?.code;
4139
+ if (code === "EADDRINUSE") {
4140
+ console.error(
4141
+ `Port ${port} is already in use by another application. Try: urlscanner --port ${port + 1}`
4142
+ );
4143
+ } else {
4144
+ console.error(err);
4145
+ }
4146
+ db.close();
4147
+ process.exitCode = 1;
4148
+ return;
4149
+ }
4150
+ }
4151
+ const activePort = started ? started.port : port;
4152
+ const serverUrl = `http://${displayHost}:${activePort}`;
4153
+ const pidPath = path4.join(dataDir, "server.pid");
3148
4154
  if (values.daemon) {
3149
4155
  const pidInfo = {
3150
4156
  pid: process.pid,
3151
- port: started.port,
4157
+ port: activePort,
3152
4158
  host,
3153
4159
  dataDir,
3154
4160
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
3155
4161
  };
3156
- fs3.writeFileSync(pidPath, JSON.stringify(pidInfo, null, 2));
4162
+ fs4.writeFileSync(pidPath, JSON.stringify(pidInfo, null, 2));
3157
4163
  }
4164
+ let trayHandle = null;
4165
+ let shuttingDown = false;
3158
4166
  const shutdown = () => {
4167
+ if (shuttingDown) return;
4168
+ shuttingDown = true;
4169
+ void trayHandle?.kill();
3159
4170
  try {
3160
- started.server.close();
4171
+ started?.server.close();
3161
4172
  } catch {
3162
4173
  }
3163
4174
  if (values.daemon) {
3164
- fs3.rmSync(pidPath, { force: true });
4175
+ fs4.rmSync(pidPath, { force: true });
3165
4176
  }
3166
4177
  try {
3167
4178
  db.close();
@@ -3176,22 +4187,55 @@ async function main() {
3176
4187
  shutdown();
3177
4188
  process.exit(0);
3178
4189
  });
3179
- if (values.daemon || values["no-menu"]) {
4190
+ if (values.daemon) {
4191
+ console.log(`URLScanner v${APP_VERSION} listening on ${serverUrl} (DB: ${dbPath})`);
4192
+ trayHandle = await startSystemTray({
4193
+ serverUrl,
4194
+ port: activePort,
4195
+ noTray: values["no-tray"],
4196
+ onQuit: () => {
4197
+ shutdown();
4198
+ setTimeout(() => process.exit(0), 150);
4199
+ }
4200
+ });
4201
+ return;
4202
+ }
4203
+ if (values["no-menu"]) {
4204
+ if (alreadyRunning) {
4205
+ console.log(`URLScanner is already running on ${serverUrl}`);
4206
+ if (values.web && !values["no-open"]) {
4207
+ openBrowser(serverUrl);
4208
+ }
4209
+ db.close();
4210
+ return;
4211
+ }
3180
4212
  console.log(`URLScanner v${APP_VERSION} listening on ${serverUrl} (DB: ${dbPath})`);
4213
+ if (values.web && !values["no-open"]) {
4214
+ openBrowser(serverUrl);
4215
+ }
3181
4216
  return;
3182
4217
  }
3183
4218
  let mode = values.tui ? "tui" : values.web ? "web" : "menu";
3184
4219
  let firstWebOpen = !values["no-open"];
3185
4220
  while (true) {
3186
4221
  if (mode === "menu") {
3187
- const choice = await runLauncherMenu(serverUrl);
4222
+ const choice = await runLauncherMenu(serverUrl, { alreadyRunning });
3188
4223
  if (choice === "exit") {
3189
4224
  shutdown();
3190
4225
  process.exit(0);
3191
4226
  }
4227
+ if (choice === "stop") {
4228
+ shutdown();
4229
+ await handleStop(dataDir);
4230
+ process.exit(0);
4231
+ }
3192
4232
  if (choice === "daemon") {
3193
4233
  shutdown();
3194
- await spawnDaemon(host, started.port, dataDir);
4234
+ if (alreadyRunning) {
4235
+ await handleStop(dataDir);
4236
+ await new Promise((r) => setTimeout(r, 300));
4237
+ }
4238
+ await spawnDaemon(host, activePort, dataDir, values["no-tray"]);
3195
4239
  process.exit(0);
3196
4240
  }
3197
4241
  mode = choice;