Published source
Download source ZIP
CH-J Server Manager
Browse directories and files for a specific application release.
Source is provided under the CH-J Proprietary Software License 1.14. Its availability does not change the license terms or grant additional rights.
1
"use strict";2
const net = require("node:net");3
const tls = require("node:tls");4
const { X509Certificate } = require("node:crypto");5
const { domainToASCII } = require("node:url");6
const { performance } = require("node:perf_hooks");7
const TOOLS = ["dns", "ping", "traceroute", "http", "compression", "tls", "tcp", "websocket"];8
const SERVICES = { 21: "FTP", 22: "SSH", 25: "SMTP", 53: "DNS TCP", 80: "HTTP", 110: "POP3", 143: "IMAP", 443: "HTTPS", 445: "SMB", 587: "SMTP Submission", 993: "IMAPS", 995: "POP3S", 3306: "MySQL", 3389: "RDP", 5432: "PostgreSQL", 6379: "Redis" };9
class DiagnosticError extends Error {10
constructor(code, message = code) { super(message); this.code = code; }11
}12
// Verify IP SANs directly. Node TLS releases that IDNA-normalize every host can13
// misclassify an unbracketed IPv6 literal as a DNS name. Trust verification stays on.14
function verifyPeerIdentity(host, cert) {15
if (!net.isIP(host)) return tls.checkServerIdentity(host, cert);16
try { if (new X509Certificate(cert.raw).checkIP(host)) return undefined; } catch {}17
return new DiagnosticError("ERR_TLS_CERT_ALTNAME_INVALID", "Certificate IP SAN does not match the requested IP address.");18
}19
function hostname(raw) {20
const value = String(raw || "").replace(/^\[|\]$/g, "");21
if (net.isIP(value)) return value;22
const ascii = domainToASCII(value.replace(/\.$/, "")).toLowerCase();23
if (!ascii || ascii.length > 253 || !ascii.split(".").every((label) => /^[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?$/i.test(label))) throw new DiagnosticError("INVALID_HOST");24
return ascii;25
}26
function parseTarget(raw) {27
const input = String(raw || "").trim();28
if (!input || input.length > 2048 || /[\x00-\x20\x7f\\]/.test(input)) throw new DiagnosticError("INVALID_TARGET");29
let url;30
const literal = net.isIP(input.replace(/^\[|\]$/g, ""));31
try { url = new URL(literal === 6 ? `https://[${hostname(input)}]/` : /^[a-z][a-z0-9+.-]*:\/\//i.test(input) ? input : `https://${input}`); }32
catch { throw new DiagnosticError("INVALID_URL"); }33
if (!["http:", "https:", "ws:", "wss:"].includes(url.protocol) || url.username || url.password) throw new DiagnosticError("URL_AUTH_OR_SCHEME_FORBIDDEN");34
const host = hostname(url.hostname);35
url.hash = "";36
return { input, host, url: url.href, port: Number(url.port || (["https:", "wss:"].includes(url.protocol) ? 443 : 80)), type: net.isIP(host) ? `ipv${net.isIP(host)}` : input.includes("://") ? "url" : "hostname" };37
}38
function integer(value, fallback, min, max) {39
if (value === undefined || value === "") return fallback;40
const number = Number(value);41
if (!Number.isInteger(number) || number < min || number > max) throw new DiagnosticError("INVALID_PARAMETER");42
return number;43
}44
function normalizeOptions(source = {}) {45
const target = parseTarget(source.target);46
const mode = source.mode || "auto";47
if (!["auto", "ipv4", "ipv6", "both"].includes(mode)) throw new DiagnosticError("INVALID_IP_MODE");48
const tools = source.tools === undefined ? TOOLS.filter((tool) => tool !== "websocket") : source.tools;49
if (!Array.isArray(tools) || !tools.length || tools.length > TOOLS.length || tools.some((tool) => !TOOLS.includes(tool))) throw new DiagnosticError("INVALID_TOOLS");50
const portsText = String(source.ports || "22,80,443");51
if (portsText.length > 512) throw new DiagnosticError("PORT_LIMIT");52
const ports = [...new Set(portsText.split(/[,;\s]+/).filter(Boolean).map((port) => integer(port, 443, 1, 65535)))];53
if (!ports.length || ports.length > 16) throw new DiagnosticError("PORT_LIMIT");54
const resolver = source.resolver || "system";55
if (!["system", "custom", "cloudflare", "google", "quad9"].includes(resolver)) throw new DiagnosticError("INVALID_RESOLVER");56
const customDns = String(source.customDns || "");57
if (resolver === "custom" && !net.isIP(customDns)) throw new DiagnosticError("INVALID_DNS_SERVER");58
const selectedIp = String(source.selectedIp || "");59
if (selectedIp && !net.isIP(selectedIp)) throw new DiagnosticError("INVALID_IP");60
const protocols = source.protocols || ["1.1", "2", "3"];61
if (!Array.isArray(protocols) || !protocols.length || protocols.length > 3 || protocols.some((p) => !["1.1", "2", "3"].includes(p))) throw new DiagnosticError("INVALID_PROTOCOL");62
return { target, tools: [...new Set(tools)], mode, selectedIp, resolver, customDns,63
timeoutMs: integer(source.timeoutMs, 5000, 250, 30000), count: integer(source.count, 4, 1, 100),64
repetitions: integer(source.repetitions, 1, 1, 20), maxHops: integer(source.maxHops, 20, 1, 40),65
continuous: source.continuous === true, warm: source.warm === true, protocols: [...new Set(protocols)], ports,66
compareSchemes: source.compareSchemes === true };67
}68
function stats(values) {69
const list = values.filter((v) => typeof v === "number" && Number.isFinite(v)).sort((a, b) => a - b);70
if (!list.length) return { min: null, average: null, median: null, max: null, p95: null, stddev: null, jitter: null };71
const average = list.reduce((a, b) => a + b, 0) / list.length;72
const sequence = values.filter((v) => typeof v === "number" && Number.isFinite(v));73
return { min: list[0], average, median: list.length % 2 ? list[(list.length - 1) / 2] : (list[list.length / 2 - 1] + list[list.length / 2]) / 2,74
max: list.at(-1), p95: list[Math.ceil(list.length * 0.95) - 1], stddev: Math.sqrt(list.reduce((sum, v) => sum + (v - average) ** 2, 0) / list.length),75
jitter: sequence.length < 2 ? null : sequence.slice(1).reduce((sum, v, index) => sum + Math.abs(v - sequence[index]), 0) / (sequence.length - 1) };76
}77
function checkAbort(signal) { if (signal?.aborted) throw new DiagnosticError("CANCELLED"); }78
function errorResult(error) { return { status: error?.code === "CANCELLED" || error?.name === "AbortError" ? "cancelled" : "error", code: error?.code || "DIAGNOSTIC_ERROR", reason: String(error?.message || error).slice(0, 400) }; }79
async function mapLimit(items, limit, fn) {80
const results = new Array(items.length); let cursor = 0;81
const outcomes = await Promise.allSettled(Array.from({ length: Math.min(limit, items.length) }, async () => { while (cursor < items.length) { const index = cursor++; results[index] = await fn(items[index], index); } }));82
const failure = outcomes.find((entry) => entry.status === "rejected");83
if (failure) throw failure.reason;84
return results;85
}86
function boundedSignal(parent, timeoutMs) {87
const controller = new AbortController();88
const abort = () => controller.abort(parent?.reason);89
parent?.addEventListener("abort", abort, { once: true });90
if (parent?.aborted) abort();91
const timer = setTimeout(() => controller.abort(new DiagnosticError("TIMEOUT")), timeoutMs);92
return { signal: controller.signal, close() { clearTimeout(timer); parent?.removeEventListener("abort", abort); } };93
}94
module.exports = { verifyPeerIdentity, DiagnosticError, TOOLS, SERVICES, hostname, parseTarget, normalizeOptions, integer, stats, checkAbort, errorResult, mapLimit, boundedSignal, now: () => performance.now() };SHA-256: 5903a84224bf946a12f50a6840e8f6be185df697fea76817fecf7313066bb673
Archive SHA-256: 5ac91caf4fa32a6fdb114f2430deed486fbe7489d5eea343d1f034169fafb5e0