mihomo-kit/web/engine.js

295 lines
12 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 item of the module:
// sub - subscription, hy2 - own server
// 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: "", HY2: "",
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_LINKS: "",
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",
OVPN_CHECK_URL: "https://eu.bmstu.ru", TS_CHECK_URL: "http://100.69.216.50:8080",
};
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;
}
// Subscription ids (provider names, keys SUB_<ID>_*), see sub_pairs in
// mihomo-kit.sh: a SUBS word is "url" or "name=url"; without a name the id
// comes from the domain (sub.kittyvpn.com -> kittyvpn); repeats get 2, 3, ...
function autoId(url) {
let h = url.replace(/^.*?:\/\//, "").replace(/[/?#].*$/, "").replace(/^.*@/, "");
h = h.replace(/:[^:]*$/, "").replace(/[A-Z]/g, (c) => c.toLowerCase());
if (h.includes(".")) h = h.replace(/\.[^.]*$/, "");
while (/\.(co|com|net|org|gov|edu|ac)$/.test(h)) h = h.replace(/\.[^.]*$/, "");
const id = h.slice(h.lastIndexOf(".") + 1).replace(/[^a-z0-9_]/g, "_");
return !id ? "sub" : /^[0-9]/.test(id) ? "sub" + id : id;
}
function subPairs(subs) {
const seen = new Set();
return words(subs).map((w) => {
const eq = w.indexOf("=");
let name = "", url = w;
if (eq > 0 && /^[A-Za-z0-9_-]+$/.test(w.slice(0, eq))) {
name = w.slice(0, eq);
url = w.slice(eq + 1);
} else name = autoId(w);
name = name.replace(/[A-Z]/g, (c) => c.toLowerCase()).replace(/-/g, "_");
let id = name;
for (let k = 2; seen.has(id); k++) id = name + k;
seen.add(id);
return { id, url, word: w };
});
}
// SUB_<ID>_<key>, else the old SUB<index>_<key>
const subGet = (v, i, id, key) => v[`SUB_${id.toUpperCase()}_${key}`] || v[`SUB${i}_${key}`] || "";
// SUB_<ID>_DISABLED=1: kept (id, settings) but left out of the profile
const subOff = (v, i, id) => subGet(v, i, id, "DISABLED") === "1";
// vless://uuid@host:port?...&sni=..&pbk=..&sid=..#name (see vless_parse in mihomo-kit.sh)
function parseVless(link) {
const l = link.replace(/^vless:\/\//, "").replace(/#.*$/, "");
const at = l.indexOf("@");
let hp = (at < 0 ? l : l.slice(at + 1)).replace(/\?.*$/, "");
const c = hp.lastIndexOf(":");
const server = c < 0 ? hp : hp.slice(0, c);
let port = c < 0 ? hp : hp.slice(c + 1);
if (!/^[0-9]+$/.test(port)) port = "443";
const qm = l.indexOf("?");
const q = "&" + (qm < 0 ? l : l.slice(qm + 1)) + "&";
const qv = (k) => {
const i = q.indexOf("&" + k + "=");
if (i < 0) return "";
const rest = q.slice(i + k.length + 2);
return rest.slice(0, rest.indexOf("&"));
};
return { server, port, uuid: at < 0 ? l : l.slice(0, at), sni: qv("sni"), pbk: qv("pbk"), sid: qv("sid") };
}
// BOOT seeds: BOOT_LINKS or the old single BOOT_* (see boot_seeds)
function bootSeeds(v) {
if (words(v.BOOT_LINKS).length)
return words(v.BOOT_LINKS).map((l, i) => ({ name: i ? `seed${i + 1}` : "seed", ...parseVless(l) }));
if (v.BOOT_SERVER)
return [{ name: "seed", server: v.BOOT_SERVER, port: v.BOOT_PORT, uuid: v.BOOT_UUID,
sni: v.BOOT_SNI, pbk: v.BOOT_PBK, sid: v.BOOT_SID }];
return [];
}
const seedVars = (s) => ({ SEED_NAME: s.name, SEED_SERVER: s.server, SEED_PORT: s.port, SEED_UUID: s.uuid,
SEED_SNI: s.sni, SEED_PBK: s.pbk, SEED_SID: s.sid });
// HY2_<NAME> prefix of an own hysteria2 server's keys (see hy2_key)
const hy2Key = (name) => "HY2_" + name.replace(/[a-z]/g, (c) => c.toUpperCase()).replace(/-/g, "_");
// variables for templates/proxies/*-hy2.each.yaml (see hy2_vars in mihomo-kit.sh)
function hy2Vars(v, name) {
const k = (key) => v[`${hy2Key(name)}_${key}`] || "";
const obfs = k("OBFS_PASSWORD");
return {
HY2_NAME: name, HY2_SERVER: k("SERVER"), HY2_PORT: k("PORT"), HY2_PASSWORD: yq(k("PASSWORD")),
HY2_OBFS: obfs ? "salamander" : "", HY2_OBFS_PASSWORD: obfs ? yq(obfs) : "",
HY2_SNI: k("SNI"), HY2_INSECURE: k("INSECURE") === "1" ? "true" : "false",
HY2_UP: yq(k("UP")), HY2_DOWN: yq(k("DOWN")),
};
}
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") {
const seeds = bootSeeds(v);
if (!seeds.length) throw new Error("BOOT=1 but no BOOT_LINKS (vless links of the seed nodes)");
for (const s of seeds) {
for (const k of ["server", "uuid", "sni", "pbk", "sid"]) {
if (!s[k]) throw new Error(`BOOT ${s.name}: ${k.toUpperCase()} is empty (vless link needs host, uuid, sni, pbk, sid)`);
}
}
}
let on = 0;
subPairs(v.SUBS).forEach(({ id }, i) => {
if (subOff(v, i, id)) return;
on++;
if (/^BOOT(-AUTO)?$/.test(subGet(v, i, id, "PROXY")) && v.BOOT !== "1") throw new Error(`subscription ${id}: PROXY=BOOT but BOOT=0`);
if (subGet(v, i, id, "HWID") === "1") {
for (const k of ["HWID_OS", "HWID_OS_VER", "HWID_MODEL", "HWID_ID"]) {
if (!v[k]) throw new Error(`${k} is empty (subscription ${id} has HWID=1)`);
}
}
});
if (!on) throw new Error("all subscriptions are disabled (SUB_<ID>_DISABLED=1)");
for (const name of words(v.HY2)) {
if (!/^[A-Za-z0-9_-]+$/.test(name)) throw new Error(`HY2: bad server name ${name} (letters, digits, _ -)`);
for (const key of ["SERVER", "PORT", "PASSWORD"]) {
if (!v[`${hy2Key(name)}_${key}`]) throw new Error(`${hy2Key(name)}_${key} is empty (hysteria2 server ${name})`);
}
}
}
// 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, id, url) {
let proxy = subGet(v, i, id, "PROXY") || (v.BOOT === "1" ? "BOOT-AUTO" : "");
if (proxy === "none") proxy = "";
let ua = subGet(v, i, id, "UA");
let h = subGet(v, i, id, "HEADERS");
if (subGet(v, i, id, "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: id, 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 (words(v.HY2).length) t.add("hy2");
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, mod };
for (const t of rest) {
if (t === "each") { each = true; continue; }
if (!tags.has(t)) return { active: false, each, mod };
}
return { active: true, each, mod };
}
function render(templates, input) {
const v = withDefaults(input);
check(v);
const tags = computeTags(v);
const subs = subPairs(v.SUBS);
v.SUB_LIST = subs.filter((s, i) => !subOff(v, i, s.id)).map((s) => s.id).join(", ");
const seeds = bootSeeds(v);
v.SEED_LIST = seeds.map((s) => s.name).join(", ");
const hy2 = words(v.HY2);
v.HY2_LIST = hy2.join(", ");
v.HY2_MAIN = hy2.length ? "MY, " : "";
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 && info.mod === "boot") {
for (const s of seeds) {
const part = renderText(templates[path], { ...v, ...seedVars(s) }, tags);
if (part) parts.push(part);
}
} else if (info.each && info.mod === "hy2") {
for (const name of hy2) {
const part = renderText(templates[path], { ...v, ...hy2Vars(v, name) }, tags);
if (part) parts.push(part);
}
} else if (info.each) {
subs.forEach((s, i) => {
if (subOff(v, i, s.id)) return;
const part = renderText(templates[path], { ...v, ...subVars(v, i, s.id, s.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, subPairs, DEFAULTS };
if (typeof module !== "undefined" && module.exports) module.exports = api;
else root.MihomoKit = api;
})(typeof window !== "undefined" ? window : globalThis);