dns-worker 1.1.0 → 1.1.1-canary.4bc7820

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
  <img src="https://raw.githubusercontent.com/Obein/DNS-Worker/main/web/src/assets/obex_cat_eye_logo-256.webp" alt="DNS Worker Logo" width="128">
3
3
  <h1>DNS Worker</h1>
4
4
  <p>Privacy-First Protective DNS Resolver & DoH / DoT Server</p>
5
- <p>Protect your first hop on the internet · Dual-Engine: Cloudflare Workers Edge or Standalone Server (VPS / Linux / macOS / Windows)</p>
5
+ <p>Protect your first hop on the internet</p>
6
6
  <p align="center">
7
7
  English | <a href="README_zh-CN.md">中文 (简体)</a> | <a href="README_zh-TW.md">中文 (正體)</a>
8
8
  </p>
@@ -51,23 +51,6 @@
51
51
 
52
52
  ---
53
53
 
54
- ## 🔐 Advanced Privacy: Local-First & Post-Quantum E2EE
55
-
56
- DNS Worker redefines personal DNS observability by combining local-first browser computation with cutting-edge post-quantum cryptography:
57
-
58
- ### ⚡ Local-First Browser SQLite (OPFS + WASM)
59
- * **Instantaneous 0ms Queries**: Resolution logs and analytical charts render immediately from an in-browser SQLite database powered by Origin Private File System (OPFS) and Dedicated Web Workers.
60
- * **Quota Preservation & Offline Analytics**: High-frequency filtering, pagination, and multi-dimensional analytics run locally without issuing remote D1 read queries, drastically reducing Cloudflare D1 quota consumption and enabling full offline inspection.
61
- * **Smart Bidirectional Sync**: Automatically reconciles local storage with remote D1 in the background with zero UI freeze.
62
-
63
- ### 🛡️ Post-Quantum End-to-End Encryption (P256-MLKEM768)
64
- * **Zero-Knowledge Cloud Storage**: Sensitive log fields (domains, client IPs, answers, geo locations, and upstream servers) are encrypted before reaching persistent cloud storage. Cloudflare Workers and D1 database store only ciphertexts.
65
- * **Quantum-Resistant Hybrid Lattice KEM**: Adopts the NIST FIPS 203 standardized **P256-MLKEM768** (ML-KEM-768 + ECDH P-256) hybrid algorithm, defending user query logs against future "Harvest Now, Decrypt Later" quantum attacks.
66
- * **Decoupled Hourly Envelope Encryption**: Automatically encapsulates and provisions hourly Data Encryption Keys (DEK), compressing KEM database overhead by ~80% while sustaining hot-path pipeline encryption throughput of **20,000+ queries/second**.
67
- * **Hardware Passkey Protection**: The private key seed is wrapped with hardware Passkeys (WebAuthn PRF) and single-use self-rotating Recovery Keys; no plaintext secret ever touches the server.
68
-
69
- ---
70
-
71
54
  ## 🖼️ Quick Look
72
55
 
73
56
  | User Login |
@@ -1347,11 +1347,13 @@ function decodeName(buffer, offset) {
1347
1347
  let jumped = false;
1348
1348
  let consumed = 0;
1349
1349
  let iterations = 0;
1350
+ let terminated = false;
1350
1351
  while (iterations < 128) {
1351
1352
  if (curr >= buffer.length) break;
1352
1353
  const len = buffer[curr];
1353
1354
  if (len === 0) {
1354
1355
  if (!jumped) consumed++;
1356
+ terminated = true;
1355
1357
  break;
1356
1358
  }
1357
1359
  if ((len & 192) === 192) {
@@ -1365,6 +1367,9 @@ function decodeName(buffer, offset) {
1365
1367
  iterations++;
1366
1368
  continue;
1367
1369
  }
1370
+ if ((len & 192) !== 0) {
1371
+ break;
1372
+ }
1368
1373
  if (name.length > 0) name += ".";
1369
1374
  if (curr + 1 + len > buffer.length) break;
1370
1375
  for (let i = 0; i < len; i++) {
@@ -1374,6 +1379,9 @@ function decodeName(buffer, offset) {
1374
1379
  curr += len + 1;
1375
1380
  iterations++;
1376
1381
  }
1382
+ if (!terminated) {
1383
+ return { name: "", read: 0 };
1384
+ }
1377
1385
  return { name, read: consumed };
1378
1386
  }
1379
1387
  function getQTypeName(type) {
@@ -1383,6 +1391,7 @@ function parseDNSQueryFromRaw(raw) {
1383
1391
  try {
1384
1392
  if (raw.length < 16) return null;
1385
1393
  const { name, read } = decodeName(raw, 12);
1394
+ if (read === 0) return null;
1386
1395
  const qtypeOffset = 12 + read;
1387
1396
  if (qtypeOffset + 4 > raw.length) return null;
1388
1397
  const qtypeCode = raw[qtypeOffset] << 8 | raw[qtypeOffset + 1];
@@ -1432,12 +1441,14 @@ function parseDNSAnswer(raw) {
1432
1441
  for (let i = 0; i < qCount; i++) {
1433
1442
  if (offset >= raw.length) return [];
1434
1443
  const { read } = decodeName(raw, offset);
1444
+ if (read === 0) return [];
1435
1445
  offset += read + 4;
1436
1446
  if (offset > raw.length) return [];
1437
1447
  }
1438
1448
  for (let i = 0; i < ansCount; i++) {
1439
1449
  if (offset >= raw.length) break;
1440
1450
  const { name, read: nameRead } = decodeName(raw, offset);
1451
+ if (nameRead === 0) break;
1441
1452
  offset += nameRead;
1442
1453
  if (offset + 10 > raw.length) {
1443
1454
  break;
@@ -1609,18 +1620,21 @@ function rebuildEchWithFronting(rawBase64, newFrontingDomain = DEFAULT_ECH_FRONT
1609
1620
  const pkLen = bytes[9] << 8 | bytes[10];
1610
1621
  const pkStart = 11;
1611
1622
  const pkEnd = pkStart + pkLen;
1612
- if (pkEnd > bytes.length) return rawBase64;
1623
+ if (pkEnd + 4 > bytes.length) return rawBase64;
1613
1624
  const publicKey = bytes.slice(pkStart, pkEnd);
1614
1625
  let offset = pkEnd;
1615
1626
  const csLen = bytes[offset] << 8 | bytes[offset + 1];
1616
1627
  offset += 2;
1628
+ if (offset + csLen + 2 > bytes.length) return rawBase64;
1617
1629
  const cipherSuites = bytes.slice(offset, offset + csLen);
1618
1630
  offset += csLen;
1619
1631
  const maxNameLen = bytes[offset++];
1620
1632
  const oldNameLen = bytes[offset++];
1633
+ if (offset + oldNameLen + 2 > bytes.length) return rawBase64;
1621
1634
  offset += oldNameLen;
1622
1635
  const extLen = bytes[offset] << 8 | bytes[offset + 1];
1623
1636
  offset += 2;
1637
+ if (offset + extLen > bytes.length) return rawBase64;
1624
1638
  const extensions = bytes.slice(offset, offset + extLen);
1625
1639
  const targetName = (newFrontingDomain || DEFAULT_ECH_FRONTING_DOMAIN).trim().toLowerCase();
1626
1640
  const nameBytes = new Uint8Array(targetName.length);
@@ -2098,21 +2112,6 @@ var SystemSettingsModel = class {
2098
2112
  // src/utils/ech/sync.ts
2099
2113
  var cachedActiveCfEchConfig = null;
2100
2114
  var loadPromise = null;
2101
- function setActiveCfEchConfig(echBase64) {
2102
- if (echBase64 && echBase64 !== cachedActiveCfEchConfig) {
2103
- cachedActiveCfEchConfig = echBase64;
2104
- }
2105
- }
2106
- async function saveActiveCfEchConfig(db, echBase64) {
2107
- if (!echBase64) return;
2108
- setActiveCfEchConfig(echBase64);
2109
- try {
2110
- const settingsModel = new SystemSettingsModel(db);
2111
- await settingsModel.set("cf_active_ech_config", echBase64);
2112
- } catch (e) {
2113
- console.warn("[ECH] Could not persist active ECH config to DB:", e);
2114
- }
2115
- }
2116
2115
  async function ensureCloudflareIpRangesLoaded(db) {
2117
2116
  const currentCidrs = getActiveCfProxyCidrs();
2118
2117
  if (currentCidrs.length > 0) {
@@ -2310,13 +2309,19 @@ function buildDNSQuery(name, type) {
2310
2309
  raw.set(new Uint8Array(question), header.length);
2311
2310
  return raw;
2312
2311
  }
2312
+ function createServFail(queryRaw) {
2313
+ const res = new Uint8Array(12);
2314
+ if (queryRaw && queryRaw.length >= 12) {
2315
+ res.set(queryRaw.slice(0, 12));
2316
+ }
2317
+ res[2] = res[2] & 1 | 128;
2318
+ res[3] = res[3] & 240 | 2;
2319
+ return res;
2320
+ }
2313
2321
  function buildResponseMulti(queryRaw, records, rcode = 0) {
2314
2322
  try {
2315
2323
  if (!queryRaw || queryRaw.length < 12) {
2316
- const err = new Uint8Array(12);
2317
- err[2] = 129;
2318
- err[3] = 130;
2319
- return err;
2324
+ return createServFail(queryRaw);
2320
2325
  }
2321
2326
  const header = new Uint8Array(12);
2322
2327
  header.set(queryRaw.slice(0, 12));
@@ -2326,14 +2331,12 @@ function buildResponseMulti(queryRaw, records, rcode = 0) {
2326
2331
  const qCount = queryRaw[4] << 8 | queryRaw[5];
2327
2332
  for (let i = 0; i < qCount; i++) {
2328
2333
  const { read } = decodeName(queryRaw, qEnd);
2329
- if (read === 0 && qEnd < queryRaw.length) {
2330
- qEnd++;
2331
- } else {
2332
- qEnd += read + 4;
2334
+ if (read === 0) {
2335
+ return createServFail(queryRaw);
2333
2336
  }
2337
+ qEnd += read + 4;
2334
2338
  if (qEnd > queryRaw.length) {
2335
- qEnd = queryRaw.length;
2336
- break;
2339
+ return createServFail(queryRaw);
2337
2340
  }
2338
2341
  }
2339
2342
  const questionSection = queryRaw.slice(12, qEnd);
@@ -2408,10 +2411,7 @@ function buildResponseMulti(queryRaw, records, rcode = 0) {
2408
2411
  function buildResponse(queryRaw, type, value, ttl = 60, rcode = 0) {
2409
2412
  try {
2410
2413
  if (!queryRaw || queryRaw.length < 12) {
2411
- const err = new Uint8Array(12);
2412
- err[2] = 129;
2413
- err[3] = 130;
2414
- return err;
2414
+ return createServFail(queryRaw);
2415
2415
  }
2416
2416
  const header = new Uint8Array(12);
2417
2417
  header.set(queryRaw.slice(0, 12));
@@ -2421,14 +2421,12 @@ function buildResponse(queryRaw, type, value, ttl = 60, rcode = 0) {
2421
2421
  const qCount = queryRaw[4] << 8 | queryRaw[5];
2422
2422
  for (let i = 0; i < qCount; i++) {
2423
2423
  const { read } = decodeName(queryRaw, qEnd);
2424
- if (read === 0 && qEnd < queryRaw.length) {
2425
- qEnd++;
2426
- } else {
2427
- qEnd += read + 4;
2424
+ if (read === 0) {
2425
+ return createServFail(queryRaw);
2428
2426
  }
2427
+ qEnd += read + 4;
2429
2428
  if (qEnd > queryRaw.length) {
2430
- qEnd = queryRaw.length;
2431
- break;
2429
+ return createServFail(queryRaw);
2432
2430
  }
2433
2431
  }
2434
2432
  const questionSection = queryRaw.slice(12, qEnd);
@@ -3051,18 +3049,31 @@ var BloomFilter = class _BloomFilter {
3051
3049
  * 从原始二进制流恢复 (零拷贝/对齐安全反序列化)
3052
3050
  */
3053
3051
  static fromUint8Array(buffer) {
3052
+ if (!buffer || buffer.byteLength < 8) {
3053
+ throw new Error("Invalid bloom filter buffer: header too short");
3054
+ }
3054
3055
  const view = new DataView(buffer.buffer, buffer.byteOffset, 8);
3055
3056
  const size = view.getUint32(0, true);
3056
3057
  const hashes = view.getUint32(4, true);
3058
+ if (size === 0 || hashes === 0) {
3059
+ throw new Error("Invalid bloom filter parameters: size and hashes must be positive integers");
3060
+ }
3057
3061
  const offset = buffer.byteOffset + 8;
3058
3062
  const length = buffer.byteLength - 8;
3063
+ const expectedWords = size + 31 >>> 5;
3064
+ const actualWords = length >> 2;
3065
+ if (actualWords < expectedWords) {
3066
+ throw new Error(
3067
+ `Invalid bloom filter buffer: bit array truncated (expected ${expectedWords} words, got ${actualWords})`
3068
+ );
3069
+ }
3059
3070
  let bitData;
3060
3071
  if (offset % 4 === 0) {
3061
- bitData = new Uint32Array(buffer.buffer, offset, length >> 2);
3072
+ bitData = new Uint32Array(buffer.buffer, offset, expectedWords);
3062
3073
  } else {
3063
- const copy = new Uint8Array(length);
3064
- copy.set(buffer.subarray(8));
3065
- bitData = new Uint32Array(copy.buffer, 0, length >> 2);
3074
+ const copy = new Uint8Array(expectedWords << 2);
3075
+ copy.set(buffer.subarray(8, 8 + (expectedWords << 2)));
3076
+ bitData = new Uint32Array(copy.buffer, 0, expectedWords);
3066
3077
  }
3067
3078
  return new _BloomFilter(size, hashes, bitData);
3068
3079
  }
@@ -3522,9 +3533,29 @@ var FORBIDDEN_HOSTNAMES = [
3522
3533
  "localhost",
3523
3534
  "metadata.google.internal",
3524
3535
  // GCP
3525
- "169.254.169.254"
3536
+ "metadata.goog",
3537
+ "169.254.169.254",
3526
3538
  // AWS/GCP/Azure IMDS
3539
+ "instance-data",
3540
+ "localtest.me"
3541
+ ];
3542
+ var FORBIDDEN_HOSTNAME_SUFFIXES = [
3543
+ ".localhost",
3544
+ ".local",
3545
+ ".internal",
3546
+ ".lan",
3547
+ ".home.arpa",
3548
+ ".corp",
3549
+ ".home",
3550
+ ".localtest.me"
3527
3551
  ];
3552
+ function extractEmbeddedDnsIp(hostname) {
3553
+ const dotMatch = hostname.match(/(?:^|\.)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\.(?:nip\.io|sslip\.io)$/i);
3554
+ if (dotMatch) return dotMatch[1];
3555
+ const dashMatch = hostname.match(/(?:^|\.)(\d{1,3})-(\d{1,3})-(\d{1,3})-(\d{1,3})\.(?:nip\.io|sslip\.io)$/i);
3556
+ if (dashMatch) return `${dashMatch[1]}.${dashMatch[2]}.${dashMatch[3]}.${dashMatch[4]}`;
3557
+ return null;
3558
+ }
3528
3559
  var PRIVATE_AND_RESERVED_CIDRS = [
3529
3560
  // IPv4 Special/Private Ranges
3530
3561
  "0.0.0.0/8",
@@ -3622,6 +3653,20 @@ function isSafeUrl(urlString) {
3622
3653
  if (FORBIDDEN_HOSTNAMES.includes(rawHostname) || FORBIDDEN_HOSTNAMES.includes(url.hostname.toLowerCase())) {
3623
3654
  return false;
3624
3655
  }
3656
+ for (const suffix of FORBIDDEN_HOSTNAME_SUFFIXES) {
3657
+ if (rawHostname.endsWith(suffix) || rawHostname === suffix.slice(1)) {
3658
+ return false;
3659
+ }
3660
+ }
3661
+ if (rawHostname.includes("metadata.google")) {
3662
+ return false;
3663
+ }
3664
+ const embeddedIp = extractEmbeddedDnsIp(rawHostname);
3665
+ if (embeddedIp) {
3666
+ if (!isPublicInternetIP(embeddedIp)) {
3667
+ return false;
3668
+ }
3669
+ }
3625
3670
  if ((isIPv4(rawHostname) || isIPv6(rawHostname)) && !isPublicInternetIP(rawHostname)) {
3626
3671
  return false;
3627
3672
  }
@@ -4005,7 +4050,6 @@ async function processBestEffortEch(query, initialParsedAnswers, initialAnswer,
4005
4050
  const echMatch = a.data.match(/ech=([A-Za-z0-9+/=]+)/);
4006
4051
  if (echMatch) {
4007
4052
  existingEch = echMatch[1];
4008
- context.ctx.waitUntil(saveActiveCfEchConfig(context.env.DB, existingEch));
4009
4053
  }
4010
4054
  }
4011
4055
  let isCf = existingIpv4s.some(isCloudflareIp) || existingIpv6s.some(isCloudflareIp);
@@ -10602,6 +10646,146 @@ async function handleDoHRequest(request, env, ctx, profileKey) {
10602
10646
  }
10603
10647
  }
10604
10648
 
10649
+ // src/serverfull/format.ts
10650
+ function formatHelpMenu(config) {
10651
+ const { name, description, usage, commands, options, services, envVars } = config;
10652
+ const indent = " ";
10653
+ const gap = 4;
10654
+ const cmdAndOptItems = [...commands || [], ...options || []];
10655
+ const cmdAndOptWidth = Math.max(...cmdAndOptItems.map((item) => item.label.length), 0);
10656
+ const renderSection = (title, items, customWidth) => {
10657
+ if (!items || items.length === 0) return "";
10658
+ const width = customWidth ?? Math.max(...items.map((item) => item.label.length), 0);
10659
+ const lines = items.map(
10660
+ (item) => `${indent}${item.label.padEnd(width + gap)}${item.desc}`
10661
+ );
10662
+ return `
10663
+ ${title}:
10664
+ ${lines.join("\n")}`;
10665
+ };
10666
+ const usageText = Array.isArray(usage) ? usage.map((u) => `${indent}${u}`).join("\n") : `${indent}${usage}`;
10667
+ const sections = [
10668
+ `${name} - ${description}`,
10669
+ `
10670
+ Usage:
10671
+ ${usageText}`,
10672
+ renderSection("Commands", commands, cmdAndOptWidth),
10673
+ renderSection("Options", options, cmdAndOptWidth),
10674
+ renderSection("Current Service Ports", services),
10675
+ renderSection("Environment Variables", envVars)
10676
+ ];
10677
+ return sections.filter(Boolean).join("\n") + "\n";
10678
+ }
10679
+ function formatKeyValueSection(config) {
10680
+ const { title, bullet = "\u2022 ", items, indent = " ", gap = 2 } = config;
10681
+ if (!items || items.length === 0) return "";
10682
+ const maxLabelWidth = Math.max(...items.map((item) => item.label.length), 0);
10683
+ const lines = items.map(
10684
+ (item) => `${indent}${bullet}${item.label.padEnd(maxLabelWidth + gap)}: ${item.value}`
10685
+ );
10686
+ if (title) {
10687
+ return `${title}
10688
+ ${lines.join("\n")}`;
10689
+ }
10690
+ return lines.join("\n");
10691
+ }
10692
+ function formatBanner(config) {
10693
+ const { title, subtitle, borderChar = "-", bullet = "\u2022 ", minWidth = 54, items } = config;
10694
+ const contentLengths = [
10695
+ title.length + 6,
10696
+ subtitle ? subtitle.length + 6 : 0,
10697
+ ...(items || []).map((i) => i.label.length + i.value.length + 10)
10698
+ ];
10699
+ const calculatedWidth = Math.max(minWidth, ...contentLengths);
10700
+ const border = borderChar.repeat(calculatedWidth);
10701
+ const centerText = (text) => {
10702
+ const pad = Math.max(0, Math.floor((calculatedWidth - text.length) / 2));
10703
+ return " ".repeat(pad) + text;
10704
+ };
10705
+ const lines = [border, centerText(title)];
10706
+ if (subtitle) {
10707
+ lines.push(centerText(subtitle));
10708
+ }
10709
+ lines.push(border);
10710
+ if (items && items.length > 0) {
10711
+ const maxLabelWidth = Math.max(...items.map((item) => item.label.length), 0);
10712
+ const itemLines = items.map(
10713
+ (item) => ` ${bullet}${item.label.padEnd(maxLabelWidth + 2)}: ${item.value}`
10714
+ );
10715
+ lines.push(...itemLines);
10716
+ lines.push(border);
10717
+ }
10718
+ return lines.join("\n");
10719
+ }
10720
+ function formatDiagnostic(config) {
10721
+ const { title, message, details, causes, solutions } = config;
10722
+ const indent = " ";
10723
+ const subIndent = " ";
10724
+ const sections = [
10725
+ `[${title}] ${message}`
10726
+ ];
10727
+ if (details && details.length > 0) {
10728
+ sections.push(details.map((d) => `${indent}${d}`).join("\n"));
10729
+ }
10730
+ if (causes && causes.length > 0) {
10731
+ const causesHeader = `${indent}Possible causes:`;
10732
+ const causeLines = causes.map((c) => `${subIndent}- ${c}`).join("\n");
10733
+ sections.push(`${causesHeader}
10734
+ ${causeLines}`);
10735
+ }
10736
+ if (solutions && solutions.length > 0) {
10737
+ const solHeader = solutions.length === 1 ? `${indent}Solution:` : `${indent}Solutions:`;
10738
+ const solLines = solutions.map((s) => `${subIndent}- ${s}`).join("\n");
10739
+ sections.push(`${solHeader}
10740
+ ${solLines}`);
10741
+ }
10742
+ return "\n" + sections.filter(Boolean).join("\n") + "\n";
10743
+ }
10744
+ function formatPortError(config) {
10745
+ const { serviceName, protocol, port, err, alternateOption, disableOption } = config;
10746
+ const errCode = err?.code;
10747
+ if (errCode === "EADDRINUSE") {
10748
+ const causes = [];
10749
+ if (protocol === "UDP" && port === 53) {
10750
+ causes.push("Linux: systemd-resolved is listening on port 53 (stop it or configure DNSStubListener=no).");
10751
+ causes.push("Another DNS server (bind9, dnsmasq, AdGuard Home) is running.");
10752
+ } else {
10753
+ causes.push(`Another service or application is already listening on ${protocol} port ${port}.`);
10754
+ }
10755
+ const solutions = [
10756
+ `Use ${alternateOption} to specify an alternate port.`,
10757
+ disableOption ? `Or use ${disableOption} to disable this transport.` : null
10758
+ ].filter(Boolean);
10759
+ return formatDiagnostic({
10760
+ level: "error",
10761
+ title: "Port Conflict",
10762
+ message: `${serviceName} port ${port} is already in use.`,
10763
+ causes,
10764
+ solutions
10765
+ });
10766
+ }
10767
+ if (errCode === "EACCES") {
10768
+ const causes = [
10769
+ "Port numbers below 1024 require elevated privileges on Linux/macOS.",
10770
+ "On Windows, the port may fall within a reserved NAT/Hyper-V port exclusion range."
10771
+ ];
10772
+ const solutions = [
10773
+ "Run with elevated privileges (e.g. sudo npx dns-worker).",
10774
+ `Or use ${alternateOption} to bind to an unprivileged or available port.`
10775
+ ];
10776
+ return formatDiagnostic({
10777
+ level: "error",
10778
+ title: "Permission Denied",
10779
+ message: `Permission denied binding to ${serviceName} port ${port}.`,
10780
+ causes,
10781
+ solutions
10782
+ });
10783
+ }
10784
+ return `
10785
+ [${serviceName}] Startup Error: ${err?.message || String(err)}
10786
+ `;
10787
+ }
10788
+
10605
10789
  // src/serverfull/udp.ts
10606
10790
  var UdpDnsServer = class {
10607
10791
  constructor(options) {
@@ -10620,26 +10804,14 @@ var UdpDnsServer = class {
10620
10804
  } catch {
10621
10805
  }
10622
10806
  this.socket = null;
10623
- if (err.code === "EADDRINUSE") {
10624
- console.error(`
10625
- [Port Conflict] UDP port ${this.options.port} is already in use.`);
10626
- console.error(" Possible causes:");
10627
- console.error(" - Linux: systemd-resolved is listening on port 53 (stop it or configure DNSStubListener=no).");
10628
- console.error(" - Another DNS server (bind9, dnsmasq, AdGuard Home) is running.");
10629
- console.error(" Solutions:");
10630
- console.error(` - Use --dns-port <port> (e.g. --dns-port 5353) to specify an alternate port.`);
10631
- console.error(` - Or use --disable-udp to run only the Web Dashboard & DoH.
10632
- `);
10633
- } else if (err.code === "EACCES") {
10634
- console.error(`
10635
- [Permission Denied] Permission denied binding to UDP port ${this.options.port}.`);
10636
- console.error(" Port numbers below 1024 require elevated privileges on Linux/macOS.");
10637
- console.error(" Solutions:");
10638
- console.error(" - Run with sudo (e.g. sudo npx dns-worker).");
10639
- console.error(" - Or use --dns-port 5353 to bind to an unprivileged port.\n");
10640
- } else {
10641
- console.error("[UDP DNS] Failed to bind socket:", err.message || err);
10642
- }
10807
+ console.error(formatPortError({
10808
+ serviceName: "UDP DNS",
10809
+ protocol: "UDP",
10810
+ port: this.options.port,
10811
+ err,
10812
+ alternateOption: "--dns-port <port> (e.g. --dns-port 5353)",
10813
+ disableOption: "--disable-udp"
10814
+ }));
10643
10815
  reject(err);
10644
10816
  };
10645
10817
  this.socket.once("error", startupErrorHandler);
@@ -10693,7 +10865,8 @@ var UdpDnsServer = class {
10693
10865
  env,
10694
10866
  ctx
10695
10867
  };
10696
- const request = new Request(`http://${rinfo.address}/dns-query`, {
10868
+ const host = rinfo.address.includes(":") ? `[${rinfo.address}]` : rinfo.address;
10869
+ const request = new Request(`http://${host}/dns-query`, {
10697
10870
  headers: {
10698
10871
  "CF-Connecting-IP": rinfo.address,
10699
10872
  "Accept": "application/dns-message",
@@ -10764,16 +10937,30 @@ var DotDnsServer = class {
10764
10937
  return new Promise((resolve, reject) => {
10765
10938
  const { tlsKeyPath, tlsCertPath, port, host } = this.options;
10766
10939
  if (!tlsKeyPath || !tlsCertPath) {
10767
- console.warn("[DoT] TLS key or certificate path not configured. Skipping DoT server start.");
10768
- console.warn("[DoT] Set SERVERFULL_TLS_KEY_PATH and SERVERFULL_TLS_CERT_PATH to enable DoT.");
10940
+ console.warn(formatDiagnostic({
10941
+ level: "warning",
10942
+ title: "DoT - TLS Not Configured",
10943
+ message: "TLS key or certificate path not provided. Skipping DoT server startup.",
10944
+ solutions: [
10945
+ "Set SERVERFULL_TLS_KEY_PATH and SERVERFULL_TLS_CERT_PATH to enable DNS over TLS (DoT)."
10946
+ ]
10947
+ }));
10769
10948
  resolve();
10770
10949
  return;
10771
10950
  }
10772
10951
  if (!fs3.existsSync(tlsKeyPath) || !fs3.existsSync(tlsCertPath)) {
10773
- console.warn(`[DoT] TLS files not found:
10774
- Key: ${tlsKeyPath}
10775
- Cert: ${tlsCertPath}
10776
- Skipping DoT server.`);
10952
+ console.warn(formatDiagnostic({
10953
+ level: "warning",
10954
+ title: "DoT - TLS Files Missing",
10955
+ message: "Configured TLS key or certificate files were not found on disk. Skipping DoT server startup.",
10956
+ details: [
10957
+ `Key path : ${tlsKeyPath}`,
10958
+ `Cert path : ${tlsCertPath}`
10959
+ ],
10960
+ solutions: [
10961
+ "Verify the file paths or generate TLS certificates before enabling DoT."
10962
+ ]
10963
+ }));
10777
10964
  resolve();
10778
10965
  return;
10779
10966
  }
@@ -10788,24 +10975,14 @@ Skipping DoT server.`);
10788
10975
  });
10789
10976
  const startupErrorHandler = (err) => {
10790
10977
  this.server = null;
10791
- if (err.code === "EADDRINUSE") {
10792
- console.error(`
10793
- [Port Conflict] DoT port ${port} is already in use.`);
10794
- console.error(" Solution:");
10795
- console.error(` - Use --dot-port <port> (e.g. --dot-port 8853) to specify an alternate DoT port.`);
10796
- console.error(` - Or use --disable-dot to disable DoT.
10797
- `);
10798
- } else if (err.code === "EACCES") {
10799
- console.error(`
10800
- [Permission Denied] Permission denied binding to DoT port ${port}.`);
10801
- console.error(" Port numbers below 1024 require elevated privileges on Linux/macOS.");
10802
- console.error(" Solution:");
10803
- console.error(" - Run with sudo (e.g. sudo npx dns-worker).");
10804
- console.error(` - Or use --dot-port 8853 to bind to an unprivileged port.
10805
- `);
10806
- } else {
10807
- console.error("[DoT] Server error:", err.message || err);
10808
- }
10978
+ console.error(formatPortError({
10979
+ serviceName: "DNS over TLS (DoT)",
10980
+ protocol: "DoT",
10981
+ port,
10982
+ err,
10983
+ alternateOption: "--dot-port <port> (e.g. --dot-port 8853)",
10984
+ disableOption: "--disable-dot"
10985
+ }));
10809
10986
  reject(err);
10810
10987
  };
10811
10988
  this.server.once("error", startupErrorHandler);
@@ -10835,12 +11012,20 @@ Skipping DoT server.`);
10835
11012
  candidateKey = firstPart;
10836
11013
  }
10837
11014
  }
11015
+ socket.setTimeout(3e4, () => {
11016
+ socket.destroy();
11017
+ });
10838
11018
  socket.on("error", (err) => {
10839
11019
  if (err.code !== "ECONNRESET") {
10840
11020
  console.warn(`[DoT] Socket error from ${remoteIp}:`, err.message);
10841
11021
  }
10842
11022
  });
11023
+ const MAX_DOT_BUFFER = 65537;
10843
11024
  socket.on("data", async (chunk) => {
11025
+ if (buffer.length + chunk.length > MAX_DOT_BUFFER) {
11026
+ socket.destroy();
11027
+ return;
11028
+ }
10844
11029
  buffer = Buffer2.concat([buffer, chunk]);
10845
11030
  while (buffer.length >= 2) {
10846
11031
  const msgLen = buffer.readUInt16BE(0);
@@ -10884,7 +11069,8 @@ Skipping DoT server.`);
10884
11069
  env,
10885
11070
  ctx
10886
11071
  };
10887
- const request = new Request(`http://${remoteIp}/dns-query`, {
11072
+ const host = remoteIp.includes(":") ? `[${remoteIp}]` : remoteIp;
11073
+ const request = new Request(`http://${host}/dns-query`, {
10888
11074
  headers: {
10889
11075
  "CF-Connecting-IP": remoteIp,
10890
11076
  "Accept": "application/dns-message",
@@ -11235,7 +11421,8 @@ async function verifyTurnstile(token, secret, ip) {
11235
11421
  body: params,
11236
11422
  headers: {
11237
11423
  "Content-Type": "application/x-www-form-urlencoded"
11238
- }
11424
+ },
11425
+ signal: AbortSignal.timeout(5e3)
11239
11426
  });
11240
11427
  const outcome = await result.json();
11241
11428
  return !!outcome.success;
@@ -11721,20 +11908,15 @@ async function verifyRegistrationResponse(options) {
11721
11908
  }
11722
11909
  const clientOriginUrl = new URL(clientData.origin);
11723
11910
  const expectedOriginUrl = expectedOrigin.includes("://") ? new URL(expectedOrigin) : new URL(`https://${expectedOrigin}`);
11724
- if (clientOriginUrl.hostname.toLowerCase() !== expectedOriginUrl.hostname.toLowerCase()) {
11911
+ if (clientOriginUrl.origin.toLowerCase() !== expectedOriginUrl.origin.toLowerCase()) {
11725
11912
  throw new Error(
11726
- `WebAuthn origin mismatch: expected ${expectedOriginUrl.hostname}, received ${clientOriginUrl.hostname}`
11913
+ `WebAuthn origin mismatch: expected ${expectedOriginUrl.origin}, received ${clientOriginUrl.origin}`
11727
11914
  );
11728
11915
  }
11729
11916
  const isLocalhost = clientOriginUrl.hostname === "localhost" || clientOriginUrl.hostname === "127.0.0.1";
11730
11917
  if (!isLocalhost && clientOriginUrl.protocol !== "https:") {
11731
11918
  throw new Error(`WebAuthn requires HTTPS origin, received: ${clientOriginUrl.protocol}`);
11732
11919
  }
11733
- if (clientOriginUrl.protocol !== expectedOriginUrl.protocol) {
11734
- throw new Error(
11735
- `WebAuthn protocol mismatch: expected ${expectedOriginUrl.protocol}, received ${clientOriginUrl.protocol}`
11736
- );
11737
- }
11738
11920
  const attestationBytes = base64UrlDecode(attestationObject);
11739
11921
  const { value: attestation } = decodeCbor(attestationBytes);
11740
11922
  if (!attestation.authData) {
@@ -11778,20 +11960,15 @@ async function verifyAuthenticationResponse(options) {
11778
11960
  }
11779
11961
  const clientOriginUrl = new URL(clientData.origin);
11780
11962
  const expectedOriginUrl = expectedOrigin.includes("://") ? new URL(expectedOrigin) : new URL(`https://${expectedOrigin}`);
11781
- if (clientOriginUrl.hostname.toLowerCase() !== expectedOriginUrl.hostname.toLowerCase()) {
11963
+ if (clientOriginUrl.origin.toLowerCase() !== expectedOriginUrl.origin.toLowerCase()) {
11782
11964
  throw new Error(
11783
- `WebAuthn origin mismatch: expected ${expectedOriginUrl.hostname}, received ${clientOriginUrl.hostname}`
11965
+ `WebAuthn origin mismatch: expected ${expectedOriginUrl.origin}, received ${clientOriginUrl.origin}`
11784
11966
  );
11785
11967
  }
11786
11968
  const isLocalhost = clientOriginUrl.hostname === "localhost" || clientOriginUrl.hostname === "127.0.0.1";
11787
11969
  if (!isLocalhost && clientOriginUrl.protocol !== "https:") {
11788
11970
  throw new Error(`WebAuthn requires HTTPS origin, received: ${clientOriginUrl.protocol}`);
11789
11971
  }
11790
- if (clientOriginUrl.protocol !== expectedOriginUrl.protocol) {
11791
- throw new Error(
11792
- `WebAuthn protocol mismatch: expected ${expectedOriginUrl.protocol}, received ${clientOriginUrl.protocol}`
11793
- );
11794
- }
11795
11972
  const authDataBytes = base64UrlDecode(authenticatorData);
11796
11973
  if (authDataBytes.length < 37) {
11797
11974
  throw new Error("Invalid authenticatorData length");
@@ -12052,7 +12229,9 @@ async function handleLoginRequest(request, env) {
12052
12229
  } else if ((hasTotp || hasPasskeys || hasRecoveryKeys) && recoveryKey) {
12053
12230
  let storedHashes = [];
12054
12231
  try {
12055
- storedHashes = JSON.parse(user.totp_recovery_keys || "[]");
12232
+ const raw = user.totp_recovery_keys;
12233
+ storedHashes = typeof raw === "string" ? JSON.parse(raw || "[]") : raw || [];
12234
+ if (!Array.isArray(storedHashes)) storedHashes = [storedHashes];
12056
12235
  } catch {
12057
12236
  }
12058
12237
  const matchIndex = await findMatchingRecoveryKey(recoveryKey, storedHashes);
@@ -12444,14 +12623,18 @@ async function handleForgotPasswordRequest(request, env) {
12444
12623
  const passkeyModel = new PasskeyModel(env.DB);
12445
12624
  const passkeys = await passkeyModel.listByUser(user.id);
12446
12625
  const has_passkey = passkeys.length > 0;
12447
- const has_totp = !!user.totp_enabled && !!user.totp_secret;
12626
+ const has_totp = !!user.totp_enabled && (!!user.totp_secret || !!user.totp_secret_encrypted);
12448
12627
  let has_recovery_keys = false;
12449
- if (user.totp_recovery_keys) {
12628
+ const rawRecoveryKeys = user.totp_recovery_keys;
12629
+ if (rawRecoveryKeys) {
12450
12630
  try {
12451
- const parsed = JSON.parse(user.totp_recovery_keys);
12631
+ const parsed = typeof rawRecoveryKeys === "string" ? JSON.parse(rawRecoveryKeys) : rawRecoveryKeys;
12452
12632
  has_recovery_keys = Array.isArray(parsed) && parsed.length > 0;
12453
12633
  } catch {
12634
+ has_recovery_keys = typeof rawRecoveryKeys === "string" && rawRecoveryKeys.length > 0;
12454
12635
  }
12636
+ } else if (user.totp_recovery_keys_encrypted) {
12637
+ has_recovery_keys = true;
12455
12638
  }
12456
12639
  if (!has_passkey && !has_totp && !has_recovery_keys) {
12457
12640
  return new Response(JSON.stringify({
@@ -12548,7 +12731,9 @@ async function handleForgotPasswordRequest(request, env) {
12548
12731
  } else if (recoveryKey) {
12549
12732
  let storedHashes = [];
12550
12733
  try {
12551
- storedHashes = JSON.parse(user.totp_recovery_keys || "[]");
12734
+ const raw = user.totp_recovery_keys;
12735
+ storedHashes = typeof raw === "string" ? JSON.parse(raw || "[]") : raw || [];
12736
+ if (!Array.isArray(storedHashes)) storedHashes = [storedHashes];
12552
12737
  } catch {
12553
12738
  }
12554
12739
  const matchIndex = await findMatchingRecoveryKey(recoveryKey, storedHashes);
@@ -12560,12 +12745,22 @@ async function handleForgotPasswordRequest(request, env) {
12560
12745
  await userModel.consumeRecoveryKey(user.id, matchIndex, storedHashes);
12561
12746
  await activityLog.record(user.id, "recovery_key_used", clientIp, userAgent, { flow: "forgot_password", remaining: storedHashes.length - 1 });
12562
12747
  } else if (totpTokenHash && user.totp_secret) {
12563
- const isValid = await verifyTOTP(user.totp_secret, totpTokenHash, totpSalt);
12564
- if (!isValid) {
12748
+ const totpResult = await verifyTOTPWithStep(user.totp_secret, totpTokenHash, totpSalt);
12749
+ if (!totpResult.valid) {
12565
12750
  state.failedAttempts++;
12566
12751
  await cacheUtils.set(cache, cacheKey, state, 300);
12567
12752
  return new Response("Invalid TOTP code", { status: 400 });
12568
12753
  }
12754
+ if (totpResult.timeStep !== void 0) {
12755
+ const stepKey = `totp_step:${user.id}:${totpResult.timeStep}`;
12756
+ const replayed = await cacheUtils.get(cache, stepKey);
12757
+ if (replayed) {
12758
+ state.failedAttempts++;
12759
+ await cacheUtils.set(cache, cacheKey, state, 300);
12760
+ return new Response("TOTP code already used, please wait for next code", { status: 400 });
12761
+ }
12762
+ await cacheUtils.set(cache, stepKey, true, 180);
12763
+ }
12569
12764
  await activityLog.record(user.id, "totp_verify_success", clientIp, userAgent, { flow: "forgot_password" });
12570
12765
  } else {
12571
12766
  return new Response("No valid MFA credential provided", { status: 400 });
@@ -13345,14 +13540,62 @@ function parseLine(line) {
13345
13540
 
13346
13541
  // src/utils/listFetcher.ts
13347
13542
  async function fetchListContent(url, maxBytes, timeoutMs, onDomain) {
13348
- if (!isSafeUrl(url)) {
13349
- return {
13350
- count: 0,
13351
- error: "Invalid list URL. Private networks and localhosts are not allowed."
13352
- };
13353
- }
13543
+ const deadline = Date.now() + timeoutMs;
13544
+ let currentUrl = url;
13545
+ let redirectCount = 0;
13546
+ const MAX_REDIRECTS = 5;
13547
+ let response;
13354
13548
  try {
13355
- const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
13549
+ while (true) {
13550
+ if (!isSafeUrl(currentUrl)) {
13551
+ return {
13552
+ count: 0,
13553
+ error: "Invalid list URL. Private networks, localhosts, and internal domains are not allowed."
13554
+ };
13555
+ }
13556
+ const remainingTimeout = deadline - Date.now();
13557
+ if (remainingTimeout <= 0) {
13558
+ return { count: 0, error: "Request timed out" };
13559
+ }
13560
+ response = await fetch(currentUrl, {
13561
+ redirect: "manual",
13562
+ signal: AbortSignal.timeout(remainingTimeout)
13563
+ });
13564
+ if (response.status >= 300 && response.status < 400) {
13565
+ const location = response.headers.get("location");
13566
+ if (!location) {
13567
+ return {
13568
+ count: 0,
13569
+ error: `Redirect status ${response.status} without Location header`
13570
+ };
13571
+ }
13572
+ redirectCount++;
13573
+ if (redirectCount > MAX_REDIRECTS) {
13574
+ return {
13575
+ count: 0,
13576
+ error: `Too many redirects (max ${MAX_REDIRECTS})`
13577
+ };
13578
+ }
13579
+ try {
13580
+ const nextUrl = new URL(location, currentUrl).toString();
13581
+ const nextProto = new URL(nextUrl).protocol;
13582
+ if (nextProto !== "http:" && nextProto !== "https:") {
13583
+ return {
13584
+ count: 0,
13585
+ error: `Invalid redirect protocol: ${nextProto}`
13586
+ };
13587
+ }
13588
+ currentUrl = nextUrl;
13589
+ continue;
13590
+ } catch {
13591
+ return {
13592
+ count: 0,
13593
+ error: `Invalid redirect location: ${location}`
13594
+ };
13595
+ }
13596
+ }
13597
+ break;
13598
+ }
13356
13599
  if (!response.ok) {
13357
13600
  return {
13358
13601
  count: 0,
@@ -14836,23 +15079,22 @@ async function handlePasskeysRequest(request, env, user, pathParts, _ctx) {
14836
15079
  const dbUser = await userModel.getById(user.id);
14837
15080
  let recoveryKeys = [];
14838
15081
  if (dbUser) {
15082
+ let hasExistingRecoveryKeys = false;
14839
15083
  if (dbUser.totp_recovery_keys) {
14840
- let parsedKeys = null;
14841
15084
  try {
14842
- parsedKeys = typeof dbUser.totp_recovery_keys === "string" ? JSON.parse(dbUser.totp_recovery_keys) : dbUser.totp_recovery_keys;
15085
+ const parsed2 = typeof dbUser.totp_recovery_keys === "string" ? JSON.parse(dbUser.totp_recovery_keys) : dbUser.totp_recovery_keys;
15086
+ if (Array.isArray(parsed2) && parsed2.length > 0) {
15087
+ hasExistingRecoveryKeys = true;
15088
+ }
14843
15089
  } catch {
14844
- parsedKeys = [dbUser.totp_recovery_keys];
14845
- }
14846
- if (!Array.isArray(parsedKeys)) parsedKeys = [parsedKeys];
14847
- for (const item of parsedKeys) {
14848
- if (typeof item === "object" && item?.key) {
14849
- recoveryKeys.push(item.key);
14850
- } else if (typeof item === "string" && !/^[a-fA-F0-9]{64}$/.test(item.trim())) {
14851
- recoveryKeys.push(item);
15090
+ if (dbUser.totp_recovery_keys.length > 0) {
15091
+ hasExistingRecoveryKeys = true;
14852
15092
  }
14853
15093
  }
15094
+ } else if (dbUser.totp_recovery_keys_encrypted) {
15095
+ hasExistingRecoveryKeys = true;
14854
15096
  }
14855
- if (recoveryKeys.length === 0) {
15097
+ if (!hasExistingRecoveryKeys) {
14856
15098
  const plaintextKeys = generateRecoveryKeys();
14857
15099
  const storedItems = await Promise.all(
14858
15100
  plaintextKeys.map(async (k) => ({
@@ -14864,10 +15106,16 @@ async function handlePasskeysRequest(request, env, user, pathParts, _ctx) {
14864
15106
  }
14865
15107
  }
14866
15108
  await activityLog.record(user.id, "passkey_registered", clientIp, userAgent, { name: passkeyName }, sessionHash);
14867
- return new Response(JSON.stringify({ ...created, recovery_keys: recoveryKeys }), {
14868
- status: 201,
14869
- headers: { "Content-Type": "application/json" }
14870
- });
15109
+ return new Response(
15110
+ JSON.stringify({
15111
+ ...created,
15112
+ recovery_keys: recoveryKeys.length > 0 ? recoveryKeys : void 0
15113
+ }),
15114
+ {
15115
+ status: 201,
15116
+ headers: { "Content-Type": "application/json" }
15117
+ }
15118
+ );
14871
15119
  } catch (err) {
14872
15120
  console.warn("[Passkey Registration] Verification failed:", err.message || err);
14873
15121
  return new Response(err.message || "Passkey registration failed", { status: 400 });
@@ -15882,23 +16130,13 @@ var HttpServer = class {
15882
16130
  });
15883
16131
  const startupErrorHandler = (err) => {
15884
16132
  this.server = null;
15885
- if (err.code === "EADDRINUSE") {
15886
- console.error(`
15887
- [Port Conflict] HTTP port ${port} is already in use.`);
15888
- console.error(" Solution:");
15889
- console.error(` - Use -p, --port <port> (e.g. --port ${port + 1}) to specify an alternate HTTP port.`);
15890
- console.error(` - Or set the PORT environment variable (e.g. PORT=${port + 1}).
15891
- `);
15892
- } else if (err.code === "EACCES") {
15893
- console.error(`
15894
- [Permission Denied] Permission denied binding to HTTP port ${port}.`);
15895
- console.error(" Port numbers below 1024 require elevated privileges on Linux/macOS.");
15896
- console.error(" Solution:");
15897
- console.error(` - Run with sudo, or use --port 3000 to bind to an unprivileged port.
15898
- `);
15899
- } else {
15900
- console.error("[HTTP Server] Failed to start:", err.message || err);
15901
- }
16133
+ console.error(formatPortError({
16134
+ serviceName: "Web Dashboard & DoH (HTTP)",
16135
+ protocol: "HTTP",
16136
+ port,
16137
+ err,
16138
+ alternateOption: `-p, --port <port> (e.g. --port ${port + 1})`
16139
+ }));
15902
16140
  reject(err);
15903
16141
  };
15904
16142
  this.server.once("error", startupErrorHandler);
@@ -15931,6 +16169,12 @@ var HttpServer = class {
15931
16169
  const remoteIp = req.socket.remoteAddress?.replace(/^::ffff:/, "") || "127.0.0.1";
15932
16170
  headers.set("CF-Connecting-IP", remoteIp);
15933
16171
  }
16172
+ if (!headers.has("CF-IPLatitude")) {
16173
+ headers.set("CF-IPLatitude", "0.0");
16174
+ }
16175
+ if (!headers.has("CF-IPLongitude")) {
16176
+ headers.set("CF-IPLongitude", "0.0");
16177
+ }
15934
16178
  let body = null;
15935
16179
  if (req.method !== "GET" && req.method !== "HEAD") {
15936
16180
  const chunks = [];
@@ -15997,45 +16241,62 @@ init_jwt();
15997
16241
  function checkNodeVersion() {
15998
16242
  const [major, minor] = process.versions.node.split(".").map(Number);
15999
16243
  if (major < 22 || major === 22 && minor < 5) {
16000
- console.error("\n[DNS Worker] Error: Node.js >= 22.5.0 is required (found v" + process.versions.node + ").");
16001
- console.error("Please upgrade Node.js to version 22.5.0 or higher to use built-in SQLite (node:sqlite).\n");
16244
+ console.error(formatDiagnostic({
16245
+ level: "error",
16246
+ title: "DNS Worker - Environment Error",
16247
+ message: `Node.js >= 22.5.0 is required (found v${process.versions.node}).`,
16248
+ solutions: [
16249
+ "Please upgrade Node.js to version 22.5.0 or higher to use built-in SQLite (node:sqlite)."
16250
+ ]
16251
+ }));
16002
16252
  process.exit(1);
16003
16253
  }
16004
16254
  }
16005
- function printHelp() {
16255
+ function printHelp(cliArgs) {
16006
16256
  const version = getPackageVersion();
16007
- console.log(`
16008
- DNS Worker v${version} (Serverfull Mode) - Privacy-first DNS & DoH Resolver
16009
-
16010
- Usage:
16011
- dns-worker [options]
16012
- npx dns-worker [options]
16013
-
16014
- Options:
16015
- -p, --port <number> Web Dashboard & DoH HTTP port (default: 3000)
16016
- --dns-port <number> Classic UDP DNS port (default: 53)
16017
- --dot-port <number> DoT (DNS over TLS) port (default: 853)
16018
- -h, --host <address> Network address to bind (default: 0.0.0.0)
16019
- --db <path> SQLite database file path (default: ./data/dns_worker.sqlite)
16020
- --default-profile <key> Default Profile Key or Access Point Token for standard queries
16021
- --disable-udp Disable Classic UDP DNS server
16022
- --disable-dot Disable DoT server
16023
- -v, --version Display version number
16024
- --help Display this help message
16025
-
16026
- Environment Variables:
16027
- PORT / SERVERFULL_HTTP_PORT Web Dashboard & DoH port
16028
- DNS_PORT / SERVERFULL_UDP_PORT Classic UDP DNS port
16029
- DOT_PORT / SERVERFULL_DOT_PORT DoT port
16030
- DB_PATH / SERVERFULL_DB_PATH SQLite database file path
16031
- JWT_SECRET JWT secret key (recommended >= 32 characters)
16032
- SERVERFULL_TLS_KEY_PATH Path to TLS private key for DoT
16033
- SERVERFULL_TLS_CERT_PATH Path to TLS certificate for DoT
16034
- `);
16257
+ const { config } = getServerfullConfig(cliArgs);
16258
+ const udpStatus = config.disableUdp ? "Disabled" : String(config.udpPort);
16259
+ const dotStatus = config.disableDot ? "Disabled" : String(config.dotPort);
16260
+ const httpStatus = String(config.httpPort);
16261
+ const menu = formatHelpMenu({
16262
+ name: `DNS Worker v${version} (Serverfull Mode)`,
16263
+ description: "Privacy-first DNS & DoH Resolver",
16264
+ usage: [
16265
+ "dns-worker [options]",
16266
+ "npx dns-worker [options]"
16267
+ ],
16268
+ options: [
16269
+ { label: "-p, --port <number>", desc: `Web Dashboard & DoH HTTP port (current: ${httpStatus}, default: 3000)` },
16270
+ { label: "--dns-port <number>", desc: `Classic UDP DNS port (current: ${udpStatus}, default: 53)` },
16271
+ { label: "--dot-port <number>", desc: `DoT (DNS over TLS) port (current: ${dotStatus}, default: 853)` },
16272
+ { label: "-h, --host <address>", desc: `Network address to bind (current: ${config.host}, default: 0.0.0.0)` },
16273
+ { label: "--db <path>", desc: `SQLite database file path (current: ${config.dbPath})` },
16274
+ { label: "--default-profile <key>", desc: "Default Profile Key or Access Point Token for standard queries" },
16275
+ { label: "--disable-udp", desc: `Disable Classic UDP DNS server (current: ${config.disableUdp})` },
16276
+ { label: "--disable-dot", desc: `Disable DoT server (current: ${config.disableDot})` },
16277
+ { label: "-v, --version", desc: "Display version number" },
16278
+ { label: "--help", desc: "Display this help message" }
16279
+ ],
16280
+ services: [
16281
+ { label: "\u2022 Web Dashboard & DoH (HTTP)", desc: `http://${config.host}:${httpStatus}` },
16282
+ { label: "\u2022 Classic UDP DNS", desc: config.disableUdp ? "Disabled" : `udp://${config.host}:${udpStatus}` },
16283
+ { label: "\u2022 DNS over TLS (DoT)", desc: config.disableDot ? "Disabled" : `tls://${config.host}:${dotStatus}` }
16284
+ ],
16285
+ envVars: [
16286
+ { label: "PORT / SERVERFULL_HTTP_PORT", desc: "Web Dashboard & DoH port" },
16287
+ { label: "DNS_PORT / SERVERFULL_UDP_PORT", desc: "Classic UDP DNS port" },
16288
+ { label: "DOT_PORT / SERVERFULL_DOT_PORT", desc: "DoT port" },
16289
+ { label: "DB_PATH / SERVERFULL_DB_PATH", desc: "SQLite database file path" },
16290
+ { label: "JWT_SECRET", desc: "JWT secret key (recommended >= 32 characters)" },
16291
+ { label: "SERVERFULL_TLS_KEY_PATH", desc: "Path to TLS private key for DoT" },
16292
+ { label: "SERVERFULL_TLS_CERT_PATH", desc: "Path to TLS certificate for DoT" }
16293
+ ]
16294
+ });
16295
+ console.log(menu);
16035
16296
  }
16036
16297
  function parseCli() {
16037
16298
  try {
16038
- const { values } = parseArgs({
16299
+ const { values, positionals } = parseArgs({
16039
16300
  options: {
16040
16301
  port: { type: "string", short: "p" },
16041
16302
  "dns-port": { type: "string" },
@@ -16050,33 +16311,63 @@ function parseCli() {
16050
16311
  },
16051
16312
  allowPositionals: true
16052
16313
  });
16053
- if (values.help) {
16054
- printHelp();
16314
+ if (values.help || positionals[0]?.toLowerCase() === "help") {
16315
+ printHelp(values);
16055
16316
  process.exit(0);
16056
16317
  }
16057
16318
  if (values.version) {
16058
16319
  console.log(`dns-worker v${getPackageVersion()}`);
16059
16320
  process.exit(0);
16060
16321
  }
16322
+ if (positionals.length > 0) {
16323
+ console.error(formatDiagnostic({
16324
+ level: "error",
16325
+ title: "DNS Worker - CLI Argument Error",
16326
+ message: `Unrecognized command or argument "${positionals.join(" ")}".`,
16327
+ solutions: ["Run dns-worker --help to inspect supported options and usage."]
16328
+ }));
16329
+ printHelp(values);
16330
+ process.exit(1);
16331
+ }
16061
16332
  return values;
16062
16333
  } catch (err) {
16063
- console.error(`[DNS Worker] CLI Argument Error: ${err.message}`);
16064
- console.error('Run "dns-worker --help" for available options.\n');
16334
+ const errorMsg = err instanceof Error ? err.message : String(err);
16335
+ console.error(formatDiagnostic({
16336
+ level: "error",
16337
+ title: "DNS Worker - CLI Argument Error",
16338
+ message: errorMsg,
16339
+ solutions: ["Run dns-worker --help to inspect supported options and usage."]
16340
+ }));
16341
+ printHelp();
16065
16342
  process.exit(1);
16066
16343
  }
16067
16344
  }
16068
16345
  async function bootstrap() {
16069
16346
  checkNodeVersion();
16070
16347
  const cliArgs = parseCli();
16071
- console.log("------------------------------------------------------");
16072
- console.log(` Initializing DNS Worker v${getPackageVersion()} (Serverfull) `);
16073
- console.log("------------------------------------------------------");
16348
+ console.log(formatBanner({
16349
+ title: `Initializing DNS Worker v${getPackageVersion()} (Serverfull)`,
16350
+ borderChar: "-"
16351
+ }));
16074
16352
  initNodeGlobals();
16075
16353
  const { config, env } = getServerfullConfig(cliArgs);
16354
+ console.log(formatKeyValueSection({
16355
+ title: "[Services] Configured Ports & Transports:",
16356
+ items: [
16357
+ { label: "Web Dashboard & DoH", value: `http://${config.host}:${config.httpPort}` },
16358
+ { label: "Classic UDP DNS", value: config.disableUdp ? "Disabled" : `udp://${config.host}:${config.udpPort}` },
16359
+ { label: "DNS over TLS (DoT)", value: config.disableDot ? "Disabled" : `tls://${config.host}:${config.dotPort}` }
16360
+ ]
16361
+ }));
16076
16362
  if (isUsableJwtSecret(env.JWT_SECRET) && !isStrongJwtSecret(env.JWT_SECRET)) {
16077
- console.warn("\n[SECURITY WARNING] JWT_SECRET is shorter than 32 characters.");
16078
- console.warn(" Please configure KEK_v1 in your environment before rotating JWT_SECRET");
16079
- console.warn(" to prevent existing encrypted credentials from becoming unrecoverable.\n");
16363
+ console.warn(formatDiagnostic({
16364
+ level: "warning",
16365
+ title: "SECURITY WARNING",
16366
+ message: "JWT_SECRET is shorter than 32 characters.",
16367
+ solutions: [
16368
+ "Please configure KEK_v1 in your environment before rotating JWT_SECRET to prevent existing encrypted credentials from becoming unrecoverable."
16369
+ ]
16370
+ }));
16080
16371
  }
16081
16372
  const db = initServerfullDb(config.dbPath);
16082
16373
  env.DB = db;
@@ -16123,22 +16414,30 @@ async function bootstrap() {
16123
16414
  console.error("[Cron Scheduler Error]:", err);
16124
16415
  }
16125
16416
  }, 6e4);
16126
- console.log("======================================================");
16127
- console.log(" DNS Worker (Serverfull Mode) Started Successfully ");
16128
- console.log("======================================================");
16129
- if (udpServer) {
16130
- console.log(` * Classic UDP DNS : udp://${config.host}:${config.udpPort}`);
16131
- } else {
16132
- console.log(` * Classic UDP DNS : Disabled (--disable-udp)`);
16133
- }
16134
- if (dotServer && config.tlsKeyPath && config.tlsCertPath) {
16135
- console.log(` * DoT (TLS DNS) : tls://${config.host}:${config.dotPort}`);
16136
- } else {
16137
- console.log(` * DoT (TLS DNS) : Disabled / Not Configured`);
16138
- }
16139
- console.log(` * Web UI & DoH : http://${config.host}:${config.httpPort}`);
16140
- console.log(` * SQLite Database : ${config.dbPath}`);
16141
- console.log("======================================================");
16417
+ const hasTls = !!(dotServer && config.tlsKeyPath && config.tlsCertPath);
16418
+ console.log(formatBanner({
16419
+ title: "DNS Worker (Serverfull Mode) Started Successfully",
16420
+ borderChar: "=",
16421
+ bullet: "\u2022 ",
16422
+ items: [
16423
+ {
16424
+ label: "Classic UDP DNS",
16425
+ value: udpServer ? `udp://${config.host}:${config.udpPort}` : "Disabled (--disable-udp)"
16426
+ },
16427
+ {
16428
+ label: "DoT (TLS DNS)",
16429
+ value: hasTls ? `tls://${config.host}:${config.dotPort}` : "Disabled / Not Configured"
16430
+ },
16431
+ {
16432
+ label: "Web UI & DoH",
16433
+ value: `http://${config.host}:${config.httpPort}`
16434
+ },
16435
+ {
16436
+ label: "SQLite Database",
16437
+ value: config.dbPath
16438
+ }
16439
+ ]
16440
+ }));
16142
16441
  const shutdown = async (signal) => {
16143
16442
  console.log(`
16144
16443
  [Serverfull] Received ${signal}. Shutting down gracefully...`);
@@ -16164,7 +16463,11 @@ async function bootstrap() {
16164
16463
  process.on("SIGTERM", () => shutdown("SIGTERM"));
16165
16464
  }
16166
16465
  bootstrap().catch((err) => {
16167
- console.error("[Serverfull] Fatal startup error:", err.message || err);
16466
+ console.error(formatDiagnostic({
16467
+ level: "error",
16468
+ title: "Serverfull - Fatal Startup Error",
16469
+ message: err?.message || String(err)
16470
+ }));
16168
16471
  process.exit(1);
16169
16472
  });
16170
16473
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dns-worker",
3
- "version": "1.1.0",
3
+ "version": "1.1.1-canary.4bc7820",
4
4
  "private": false,
5
5
  "description": "Privacy-first DNS & DoH Resolver with modern Web Dashboard, built for Cloudflare Workers & Node.js",
6
6
  "main": "./dist/serverfull.mjs",
@@ -29,7 +29,7 @@
29
29
  "deploy:skipdb": "npm run build && wrangler deploy",
30
30
  "build": "npm run ui:build",
31
31
  "build:pages": "npm run ui:build && npx esbuild src/index.ts --bundle --outfile=static/_worker.js --platform=neutral --format=esm --minify --external:cloudflare:* --external:node:*",
32
- "postinstall": "npm run ui:install",
32
+ "prepare": "npm run ui:install",
33
33
  "db:setup": "wrangler d1 create dns_worker_db",
34
34
  "db:migrate:dev": "wrangler d1 migrations apply dns_worker_db --local",
35
35
  "db:migrate:prod": "echo \"y\" | wrangler d1 migrations apply dns_worker_db --remote",
@@ -40,7 +40,7 @@
40
40
  "lint": "eslint . --ext .ts,.tsx",
41
41
  "ui:dev": "cd web && npm run dev",
42
42
  "ui:build": "cd web && npm run build",
43
- "ui:install": "cd web && npm install -f"
43
+ "ui:install": "cd web && npm install"
44
44
  },
45
45
  "keywords": [
46
46
  "dns",