mihomo-kit/web/engine.js
2026-10-09 16:11:08 +03:00

179 lines
7.0 KiB
JavaScript

// mihomo-kit renderer, the browser twin of render() in router/mihomo-kit.sh.
// Keep both in sync: tools/test.sh renders the fixtures with both and diffs.
//
// Template syntax:
// file NN-<module>[.<tag>...][.each].yaml included if module and tags are active;
// .each = once per subscription
// line ... #@tag[,!tag] kept only if the conditions hold
// line ... ${@VAR} ... repeated for every word of VAR
// line ... ${@@VAR} ... repeated for every line of VAR
// text ${VAR} replaced with the variable
(function (root) {
const DEFAULTS = {
TARGET: "router", LOCATION: "home",
BOOT: "1", TORRENT: "1", OPENVPN: "0", TAILSCALE: "0", TS_EXIT: "0",
SUBS: "", RU_IPS: "",
GEOIP_URL: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/geoip.dat",
GEOSITE_URL: "https://cdn.jsdelivr.net/gh/SamLatsin/russia-only@release/geosite.dat",
BOOT_SERVER: "", BOOT_PORT: "443", BOOT_UUID: "", BOOT_SNI: "", BOOT_PBK: "", BOOT_SID: "",
TS_HOSTNAME: "mihomo", TS_DOMAINS: "",
HWID_UA: "v2rayN/9.99", HWID_OS: "", HWID_OS_VER: "", HWID_MODEL: "", HWID_ID: "",
OVPN_PROVIDER: "bmstu", OVPN_GROUP: "BMSTU", OVPN_SERVER_HOST: "openvpn4.bmstu.ru",
OVPN_SERVER_IPS: "195.19.40.7 195.19.33.86",
OVPN_ROUTES: "172.16.0.0/16 172.19.33.0/24 195.19.32.0/19",
};
const SECTIONS = [
["head", ""], ["proxies", "proxies:"], ["providers", "proxy-providers:"],
["sniffer", ""], ["dns", ""], ["groups", "proxy-groups:"], ["rules", "rules:"],
];
const words = (s) => (s || "").split(/\s+/).filter(Boolean);
function withDefaults(input) {
const v = { ...DEFAULTS };
for (const [k, val] of Object.entries(input || {})) {
if (val !== undefined && val !== null && val !== "") v[k] = String(val);
}
return v;
}
function check(v) {
if (!words(v.SUBS).length) throw new Error("SUBS is empty (subscription URLs)");
if (!["router", "mobile"].includes(v.TARGET)) throw new Error("TARGET must be router or mobile");
if (!["home", "street"].includes(v.LOCATION)) throw new Error("LOCATION must be home or street");
if (v.BOOT === "1") {
for (const k of ["BOOT_SERVER", "BOOT_UUID", "BOOT_SNI", "BOOT_PBK", "BOOT_SID"]) {
if (!v[k]) throw new Error(`${k} is empty (BOOT=1)`);
}
}
words(v.SUBS).forEach((_, i) => {
if (v[`SUB${i}_PROXY`] === "BOOT" && v.BOOT !== "1") throw new Error(`SUB${i}_PROXY=BOOT but BOOT=0`);
if (v[`SUB${i}_HWID`] === "1") {
for (const k of ["HWID_OS", "HWID_OS_VER", "HWID_MODEL", "HWID_ID"]) {
if (!v[k]) throw new Error(`${k} is empty (SUB${i}_HWID=1)`);
}
}
});
}
// YAML double-quoted string body
const yq = (s) => String(s).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
// per-subscription variables for the .each templates (see sub_vars in mihomo-kit.sh)
function subVars(v, i, url) {
let proxy = v[`SUB${i}_PROXY`] || (v.BOOT === "1" ? "BOOT" : "");
if (proxy === "none") proxy = "";
let ua = v[`SUB${i}_UA`] || "";
let h = v[`SUB${i}_HEADERS`] || "";
if (v[`SUB${i}_HWID`] === "1") {
ua = ua || v.HWID_UA;
h = `x-device-os=${v.HWID_OS};x-ver-os=${v.HWID_OS_VER};x-device-model=${v.HWID_MODEL};x-hwid=${v.HWID_ID}` + (h ? ";" + h : "");
}
const headers = h.split(";").map((x) => x.trim()).filter(Boolean).map((item) => {
const eq = item.indexOf("=");
const key = (eq < 0 ? item : item.slice(0, eq)).replace(/\s+$/, "");
const val = eq < 0 ? item : item.slice(eq + 1).replace(/^\s+/, "");
return `${key}: ["${yq(val)}"]`;
});
return {
SUB_NAME: `sub${i}`, SUB_URL: url, SUB_PROXY: proxy,
SUB_UA: yq(ua || "mihomo"), SUB_HEADERS: headers.join("\n"),
};
}
function computeTags(v) {
const t = new Set(["base", "sub", v.TARGET]);
if (v.BOOT === "1") t.add("boot");
if (v.TARGET === "router") {
t.add(v.LOCATION);
if (v.TORRENT === "1") t.add("torrent");
if (v.OPENVPN === "1") t.add("openvpn");
if (v.TAILSCALE === "1") {
t.add("tailscale");
if (v.TS_EXIT === "1") t.add("ts_exit");
}
}
return t;
}
function subst(s, v) {
return s.replace(/\$\{([A-Za-z0-9_]+)\}/g, (_, name) => v[name] ?? "");
}
function renderText(text, v, tags) {
const out = [];
for (let line of text.replace(/\n$/, "").split("\n")) {
const p = line.indexOf("#@");
if (p >= 0) {
const conds = line.slice(p + 2).split(",");
line = line.slice(0, p).replace(/[ \t]+$/, "");
const ok = conds.every((c) => (c.startsWith("!") ? !tags.has(c.slice(1)) : tags.has(c)));
if (!ok) continue;
}
const m = line.match(/\$\{(@@?)([A-Za-z0-9_]+)\}/);
if (m) {
const pre = line.slice(0, m.index);
const post = line.slice(m.index + m[0].length);
const items = m[1] === "@@" ? (v[m[2]] || "").split("\n").filter(Boolean) : words(v[m[2]]);
for (const w of items) out.push(subst(pre + w + post, v));
continue;
}
out.push(subst(line, v));
}
// like $(...) in sh: drop trailing empty lines
while (out.length && out[out.length - 1] === "") out.pop();
return out.join("\n");
}
// "<module>.<tag>...[.each]" -> {active, each}
function fragmentInfo(spec, tags) {
const [mod, ...rest] = spec.split(".");
let each = false;
if (!tags.has(mod)) return { active: false, each };
for (const t of rest) {
if (t === "each") { each = true; continue; }
if (!tags.has(t)) return { active: false, each };
}
return { active: true, each };
}
function render(templates, input) {
const v = withDefaults(input);
check(v);
const tags = computeTags(v);
const subs = words(v.SUBS);
v.SUB_LIST = subs.map((_, i) => `sub${i}`).join(", ");
const sections = [];
for (const [dir, header] of SECTIONS) {
const files = Object.keys(templates)
.filter((p) => p.startsWith(dir + "/") && p.endsWith(".yaml"))
.sort();
const parts = [];
for (const path of files) {
const name = path.slice(dir.length + 1, -".yaml".length);
const info = fragmentInfo(name.slice(name.indexOf("-") + 1), tags);
if (!info.active) continue;
if (info.each) {
subs.forEach((url, i) => {
const part = renderText(templates[path], { ...v, ...subVars(v, i, url) }, tags);
if (part) parts.push(part);
});
} else {
const part = renderText(templates[path], v, tags);
if (part) parts.push(part);
}
}
if (!parts.length) continue;
sections.push((header ? header + "\n" : "") + parts.join("\n\n"));
}
return sections.join("\n\n") + "\n";
}
const api = { render, DEFAULTS };
if (typeof module !== "undefined" && module.exports) module.exports = api;
else root.MihomoKit = api;
})(typeof window !== "undefined" ? window : globalThis);