mihomo-kit/web/index.html
2026-10-15 16:05:45 +03:00

722 lines
44 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mihomo-kit</title>
<style>
:root {
--bg: #f6f6f3; --panel: #ffffff; --text: #1d1d1b; --muted: #6b6b66; --line: #e2e1dc;
--accent: #2f6f4f; --accent-soft: #e4efe8; --err: #b3261e; --code-bg: #f1f0ec;
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #161715; --panel: #1f201e; --text: #e8e7e2; --muted: #9a9a93; --line: #33342f;
--accent: #7cc59d; --accent-soft: #23352b; --err: #f2b8b5; --code-bg: #191a18;
color-scheme: dark;
}
}
:root[data-theme="dark"] {
--bg: #161715; --panel: #1f201e; --text: #e8e7e2; --muted: #9a9a93; --line: #33342f;
--accent: #7cc59d; --accent-soft: #23352b; --err: #f2b8b5; --code-bg: #191a18;
color-scheme: dark;
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--text);
font: 14px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif;
}
.wrap { max-width: 1280px; margin: 0 auto; padding: 24px 16px 48px; }
header h1 { font-size: 20px; margin: 0 0 4px; }
header p { margin: 0 0 20px; color: var(--muted); }
.grid { display: grid; grid-template-columns: minmax(0, 420px) minmax(0, 1fr); gap: 20px; align-items: start; }
@media (max-width: 900px) { .grid { grid-template-columns: 1fr; } }
.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 16px; }
fieldset { border: 0; border-top: 1px solid var(--line); margin: 0; padding: 14px 0 4px; }
fieldset:first-child { border-top: 0; padding-top: 0; }
legend { font-weight: 600; padding: 0; margin-bottom: 8px; }
label { display: block; margin: 8px 0 4px; color: var(--muted); font-size: 13px; }
input[type=text], textarea {
width: 100%; padding: 7px 9px; border: 1px solid var(--line); border-radius: 6px;
background: var(--bg); color: var(--text); font: 13px ui-monospace, SFMono-Regular, Menlo, monospace;
}
textarea { min-height: 64px; resize: vertical; }
.seg { display: inline-flex; border: 1px solid var(--line); border-radius: 7px; overflow: hidden; }
.seg label { margin: 0; padding: 6px 12px; cursor: pointer; color: var(--text); font-size: 13px; }
.seg input { display: none; }
.seg label:has(input:checked) { background: var(--accent-soft); color: var(--accent); font-weight: 600; }
.row { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }
.check { display: flex; gap: 8px; align-items: center; margin: 6px 0; color: var(--text); font-size: 14px; }
.check input { margin: 0; }
.hint { color: var(--muted); font-size: 12px; margin: 4px 0 0; }
.two { display: grid; grid-template-columns: 1fr 1fr; gap: 0 10px; }
details summary { cursor: pointer; color: var(--muted); font-size: 13px; margin-top: 8px; }
.tabs { display: flex; gap: 4px; flex-wrap: wrap; margin-bottom: 10px; }
.tabs button, .actions button {
border: 1px solid var(--line); background: var(--panel); color: var(--text);
padding: 6px 12px; border-radius: 6px; cursor: pointer; font: inherit; font-size: 13px;
}
.tabs button[aria-selected=true] { background: var(--accent-soft); color: var(--accent); border-color: var(--accent); font-weight: 600; }
.actions { display: flex; gap: 6px; margin-left: auto; }
.out-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
pre {
margin: 0; padding: 14px; background: var(--code-bg); border: 1px solid var(--line); border-radius: 8px;
overflow: auto; max-height: 78vh; font: 12.5px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre;
}
.error { color: var(--err); margin: 0 0 10px; font-weight: 600; }
.note { color: var(--muted); font-size: 12px; margin-top: 10px; }
.sub { border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px 6px; margin-top: 8px; }
.sub-head { display: flex; gap: 8px; align-items: center; }
.sub-head .name { font: 12px ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--muted); min-width: 34px; }
.sub-head input { flex: 1; min-width: 0; }
.sub-opts { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; margin-top: 6px; font-size: 13px; }
.sub-opts select { padding: 4px 6px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--text); font: inherit; }
.sub-opts .check { margin: 0; font-size: 13px; }
.link-btn { border: 0; background: none; color: var(--accent); cursor: pointer; font: inherit; font-size: 13px; padding: 6px 0 0; }
.x-btn { border: 0; background: none; color: var(--muted); cursor: pointer; font-size: 16px; line-height: 1; padding: 2px 4px; }
[hidden] { display: none !important; }
</style>
</head>
<body>
<div class="wrap">
<header>
<h1>mihomo-kit — конструктор конфига</h1>
<p>Всё считается в браузере, ничего никуда не отправляется. Те же шаблоны, что у <code>mihomo-kit.sh</code> на роутере.</p>
</header>
<div class="grid">
<form class="panel" id="form" autocomplete="off">
<fieldset>
<legend>Куда</legend>
<div class="row">
<div class="seg">
<label><input type="radio" name="TARGET" value="router" checked>Роутер (nikki)</label>
<label><input type="radio" name="TARGET" value="mobile">Телефон (FlClash)</label>
</div>
<div class="seg" data-router>
<label><input type="radio" name="LOCATION" value="main" checked>Обычный</label>
<label><input type="radio" name="LOCATION" value="whitelist">Белые списки</label>
<label><input type="radio" name="LOCATION" value="foreign">За рубежом</label>
</div>
</div>
<p class="hint" data-router>Обычный — дома в России или за рубежом. Белые списки: OpenVPN через выбранную RU-ноду (группа OVPN-EXIT), свои серверы через MY-EXIT.</p>
<label for="PROFILE_NAME" data-router>Имя профиля на роутере</label>
<input type="text" id="PROFILE_NAME" value="main" data-router>
</fieldset>
<fieldset>
<legend>Подписки</legend>
<div id="subs"></div>
<button type="button" class="link-btn" id="add-sub">+ подписка</button>
<p class="hint">«Через»: откуда качать подписку. Авто = BOOT-AUTO: BOOT (если включён), иначе ноды сохранённых подписок, иначе напрямую.
HWID — для подписок с лимитом устройств (x-hwid, x-device-os, …).</p>
<label for="RU_IPS">Доп. IP через RU (CIDR через пробел)</label>
<input type="text" id="RU_IPS" value="194.190.191.112/32">
</fieldset>
<fieldset>
<legend>BOOT</legend>
<label class="check"><input type="checkbox" id="BOOT" checked>Качать подписки через BOOT (seed)</label>
<div data-boot>
<label for="vless">Вставить vless:// ссылку — поля заполнятся сами</label>
<input type="text" id="vless" placeholder="vless://uuid@host:443?security=reality&sni=…&pbk=…&sid=…">
<div class="two">
<div><label for="BOOT_SERVER">server</label><input type="text" id="BOOT_SERVER"></div>
<div><label for="BOOT_PORT">port</label><input type="text" id="BOOT_PORT" value="443"></div>
</div>
<label for="BOOT_UUID">uuid</label><input type="text" id="BOOT_UUID">
<div class="two">
<div><label for="BOOT_SNI">servername (SNI)</label><input type="text" id="BOOT_SNI" value="eh.vk.ru"></div>
<div><label for="BOOT_SID">short-id</label><input type="text" id="BOOT_SID"></div>
</div>
<label for="BOOT_PBK">public-key</label><input type="text" id="BOOT_PBK">
</div>
</fieldset>
<fieldset data-hwid>
<legend>HWID</legend>
<p class="hint">Общий для всех подписок с галкой HWID. Если провайдер уже знает устройство — тот же x-hwid.</p>
<label for="HWID_UA">User-Agent</label><input type="text" id="HWID_UA" value="v2rayN/9.99">
<div class="two">
<div><label for="HWID_OS">x-device-os</label><input type="text" id="HWID_OS" value="OpenWrt"></div>
<div><label for="HWID_OS_VER">x-ver-os</label><input type="text" id="HWID_OS_VER" placeholder="24.10.3"></div>
</div>
<label for="HWID_MODEL">x-device-model</label><input type="text" id="HWID_MODEL" placeholder="Huasifei WH3000 Pro">
<label for="HWID_ID">x-hwid</label><input type="text" id="HWID_ID">
</fieldset>
<fieldset data-router>
<legend>Модули роутера</legend>
<label class="check"><input type="checkbox" id="TORRENT" checked>Торренты (порты 20000–20199 → TORRENT-SEL)</label>
<label class="check"><input type="checkbox" id="PUSH" checked>Обход для пушей (APNs, FCM → группа PUSH)</label>
<label class="check"><input type="checkbox" id="CSQTT">CSQTT (интерфейс csqtt0 от star-panel-csqtt → группа UPLINK)</label>
<label class="check"><input type="checkbox" id="OPENVPN">OpenVPN (BMSTU, OTP через bmstu-otp.sh)</label>
<details data-openvpn>
<summary>параметры OpenVPN</summary>
<label for="OVPN_SERVER_HOST">сервер</label><input type="text" id="OVPN_SERVER_HOST">
<label for="OVPN_SERVER_IPS">IP сервера (не пускать в туннель)</label><input type="text" id="OVPN_SERVER_IPS">
<label for="OVPN_ROUTES">сети через туннель</label><input type="text" id="OVPN_ROUTES">
</details>
<label class="check"><input type="checkbox" id="TAILSCALE">Tailscale</label>
<div data-tailscale>
<label for="TS_HOSTNAME">hostname ноды</label><input type="text" id="TS_HOSTNAME" value="fudy-mihomo">
<label for="TS_DOMAINS">split-DNS домены тейлнета, кроме *.ts.net</label><input type="text" id="TS_DOMAINS">
<label class="check"><input type="checkbox" id="TS_EXIT">Через TS-EXIT (только ss/hysteria2/tuic ноды)</label>
</div>
</fieldset>
</form>
<section class="panel">
<div class="out-head">
<div class="tabs" role="tablist">
<button type="button" data-tab="yaml" aria-selected="true">config.yaml</button>
<button type="button" data-tab="env" aria-selected="false" data-router>profile .env</button>
<button type="button" data-tab="steps" aria-selected="false">Что дальше</button>
</div>
<div class="actions">
<button type="button" id="copy">Копировать</button>
<button type="button" id="download">Скачать</button>
</div>
</div>
<p class="error" id="error" hidden></p>
<pre id="out"></pre>
<p class="note">На роутере удобнее держать <code>.env</code> и собирать там: <code>mihomo-kit.sh build</code>. YAML отсюда — для телефона или разовой проверки.</p>
</section>
</div>
</div>
<script>
// 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: "main",
BOOT: "1", TORRENT: "1", PUSH: "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",
CSQTT: "0", CSQTT_IFACE: "csqtt0", CSQTT_PROCESS: "csqtt",
};
const SECTIONS = [
["head", ""], ["proxies", "proxies:"], ["providers", "proxy-providers:"], ["rule-providers", "rule-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);
}
// old names of the profiles (see set_defaults)
v.LOCATION = { home: "main", street: "whitelist" }[v.LOCATION] || v.LOCATION;
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 (!["main", "whitelist", "foreign"].includes(v.LOCATION)) throw new Error("LOCATION must be main, whitelist or foreign");
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 (subGet(v, i, id, "PROXY") === "BOOT" && 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") || "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.PUSH === "1") t.add("push");
if (v.OPENVPN === "1") t.add("openvpn");
if (v.TAILSCALE === "1") {
t.add("tailscale");
if (v.TS_EXIT === "1") t.add("ts_exit");
}
if (v.CSQTT === "1") t.add("csqtt");
}
// OpenVPN through OVPN-EXIT: whitelist and abroad (see compute_tags)
if (t.has("router") && (t.has("whitelist") || t.has("foreign"))) t.add("ovpn_exit");
// own servers through MY-EXIT: whitelist and the phone (see compute_tags)
if (t.has("hy2") && (t.has("whitelist") || t.has("mobile"))) t.add("hy2_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, " : "";
// CSQTT tunnel (star-panel-csqtt): last in MAIN (plain exit through its server)
v.CSQTT_MAIN = tags.has("csqtt") ? ", CSQTT" : "";
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);
</script>
<script>
const TEMPLATES = {
"dns/10-base.yaml": "dns:\n enable: true\n ipv6: false\n respect-rules: true\n enhanced-mode: fake-ip\n fake-ip-range: 198.18.0.1/16\n fake-ip-filter:\n - '*.lan'\n - '*.local' #@router\n - '+.ru' #@!foreign\n - '+.xn--p1ai' #@router,!foreign\n - geosite:ru-inside #@router,!foreign\n # tailnet names: real 100.x addresses from MagicDNS (nameserver-policy below) #@tailscale\n - '+.ts.net' #@tailscale\n - '+.${@TS_DOMAINS}' #@tailscale\n\n default-nameserver:\n - 77.88.8.8\n - 1.1.1.1 #@router\n - 223.5.5.5 #@mobile\n\n proxy-server-nameserver:\n - https://77.88.8.8/dns-query\n\n direct-nameserver:\n - 77.88.8.8 #@!foreign\n - 77.88.8.1 #@!foreign\n - 1.1.1.1 #@foreign\n - 8.8.8.8 #@foreign\n\n nameserver:\n - https://1.1.1.1/dns-query #@router\n - https://dns.google/dns-query\n - https://1.1.1.1/dns-query #@mobile\n\n # MagicDNS of the embedded Tailscale (the proxy named \"tailscale\") #@tailscale\n nameserver-policy: #@tailscale\n '+.ts.net': tailscale://tailscale #@tailscale\n '+.${@TS_DOMAINS}': tailscale://tailscale #@tailscale\n",
"groups/10-boot.yaml": " # BOOT: whitelisted entry nodes (BOOT_LINKS), the first alive one\n - name: BOOT\n type: fallback\n proxies: [${SEED_LIST}]\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300\n lazy: false\n",
"groups/15-sub.yaml": " # default for downloading subscriptions: BOOT (if set), else the nodes of the\n # saved subscriptions (providers are cached on disk), else direct. FOREIGN goes\n # before DIRECT: the health check of DIRECT (gstatic) passes in Russia even when\n # the subscription site itself is blocked.\n - name: BOOT-AUTO\n type: fallback\n proxies: [BOOT, FOREIGN, DIRECT] #@boot\n proxies: [FOREIGN, DIRECT] #@!boot\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300\n lazy: false\n",
"groups/20-sub.yaml": " - name: RU\n type: url-test\n use: [${SUB_LIST}]\n filter: \"(?i)🇷🇺|\\\\bru\\\\b|russia|росси|моск\"\n url: \"https://ya.ru\"\n interval: 300\n tolerance: 50\n lazy: false\n\n - name: FOREIGN\n type: url-test\n use: [${SUB_LIST}]\n exclude-filter: \"(?i)🇷🇺|\\\\bru\\\\b|russia|росси|моск\"\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300\n tolerance: 50\n lazy: false\n",
"groups/30-torrent.yaml": " - name: TORRENT\n type: url-test\n use: [${SUB_LIST}]\n filter: \"(?i)torrent|\\\\[tor\\\\]\"\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300\n timeout: 6000\n tolerance: 500\n max-failed-times: 5\n lazy: false\n",
"groups/40-openvpn.yaml": " # url: what the dashboard's delay test opens through the tunnel;\n # interval 0: no background checks (they would redial with a stale OTP)\n - name: ${OVPN_GROUP}\n type: select\n use: [${OVPN_PROVIDER}]\n url: \"${OVPN_CHECK_URL}\"\n interval: 0\n",
"groups/41-openvpn.ovpn_exit.yaml": " # what the OpenVPN tunnel itself goes through on whitelist and foreign (ovpn_exit).\n # select, not url-test: switching nodes would break the tunnel.\n # Pick a concrete RU node in the dashboard, the choice is remembered.\n - name: OVPN-EXIT\n type: select\n use: [${SUB_LIST}]\n filter: \"(?i)🇷🇺|\\\\bru\\\\b|russia|росси|моск\"\n",
"groups/45-hy2.yaml": " # own hysteria2 servers: the fastest alive one; pin one in the dashboard if needed\n - name: MY\n type: url-test\n proxies: [${HY2_LIST}]\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300\n tolerance: 50\n lazy: false\n\n # whitelist and mobile (hy2_exit): what own servers are reached through; switches only when the node is\n # clearly worse or dead (each switch breaks everything going through MY)\n - name: MY-EXIT #@hy2_exit\n type: url-test #@hy2_exit\n use: [${SUB_LIST}] #@hy2_exit\n exclude-filter: \"(?i)🇷🇺|\\\\bru\\\\b|russia|росси|моск\" #@hy2_exit\n url: \"https://www.gstatic.com/generate_204\" #@hy2_exit\n interval: 300 #@hy2_exit\n tolerance: 300 #@hy2_exit\n lazy: false #@hy2_exit\n",
"groups/50-tailscale.yaml": " # url (TS_CHECK_URL, optional): a tailnet service for the dashboard's delay test\n - name: TAILSCALE\n type: select\n proxies: [tailscale]\n url: \"${@TS_CHECK_URL}\"\n interval: 0\n",
"groups/51-tailscale.ts_exit.yaml": " # Tailscale needs full-cone UDP from its dialer-proxy: vless/vmess/trojan\n # cannot do it in mihomo, so only ss / hysteria2 / tuic / socks5 nodes here.\n - name: TS-EXIT\n type: select\n proxies: [MY] #@hy2\n use: [${SUB_LIST}]\n exclude-type: \"vless|vmess|trojan\"\n",
"groups/60-csqtt.yaml": " # UPLINK: what the subscription nodes, BOOT seeds and own servers connect\n # through. DIRECT - as before; CSQTT - through csqtt0 first (out of the\n # whitelist), then FOREIGN / MY / RU work on top of it as usual.\n # On whitelist own servers go MY-EXIT -> node -> UPLINK.\n - name: UPLINK\n type: select\n proxies: [DIRECT, CSQTT]\n",
"groups/90-base.yaml": " - name: MAIN\n type: select\n proxies: [FOREIGN, ${HY2_MAIN}RU, DIRECT${CSQTT_MAIN}] #@!foreign\n # abroad: direct by default, own servers / pools by hand #@foreign\n proxies: [DIRECT, ${HY2_MAIN}FOREIGN, RU${CSQTT_MAIN}] #@foreign\n",
"groups/91-torrent.yaml": " - name: TORRENT-SEL\n type: select\n proxies: [TORRENT, FOREIGN, DIRECT]\n",
"groups/92-push.yaml": " - name: PUSH\n type: select\n proxies: [DIRECT, ${HY2_MAIN}FOREIGN] #@!whitelist\n proxies: [${HY2_MAIN}FOREIGN, DIRECT] #@whitelist\n",
"head/10-base.yaml": "geodata-mode: true\ngeodata-loader: memconservative\ngeo-auto-update: true\ngeo-update-interval: 24\ngeox-url:\n geoip: \"${GEOIP_URL}\"\n geosite: \"${GEOSITE_URL}\"\n",
"providers/10-sub.each.yaml": " ${SUB_NAME}:\n type: http\n url: \"${SUB_URL}\"\n path: ./providers/${SUB_NAME}.yaml\n interval: 3600\n proxy: ${@SUB_PROXY}\n exclude-filter: \"(?i)app not supported|приложение не|свяжитесь\"\n override: #@csqtt\n dialer-proxy: UPLINK #@csqtt\n header:\n User-Agent: [\"${SUB_UA}\"]\n ${@@SUB_HEADERS}\n health-check:\n enable: true\n url: \"https://www.gstatic.com/generate_204\"\n interval: 300\n timeout: 3000\n lazy: false\n",
"providers/20-openvpn.yaml": " # OpenVPN: file written on the router by bmstu-otp.sh (fresh TOTP in the\n # password). No health-check here: a dead tunnel would be redialed with a\n # stale OTP; the cron watchdog (bmstu-otp.sh check) handles it.\n ${OVPN_PROVIDER}:\n type: file\n path: ./providers/${OVPN_PROVIDER}.yaml\n health-check:\n enable: false\n override: #@ovpn_exit\n dialer-proxy: OVPN-EXIT #@ovpn_exit\n",
"proxies/10-boot.each.yaml": " - name: ${SEED_NAME}\n type: vless\n server: ${SEED_SERVER}\n port: ${SEED_PORT}\n uuid: ${SEED_UUID}\n network: tcp\n udp: true\n tls: true\n flow: xtls-rprx-vision\n servername: ${SEED_SNI}\n client-fingerprint: firefox\n reality-opts:\n public-key: ${SEED_PBK}\n short-id: ${SEED_SID}\n dialer-proxy: UPLINK #@csqtt\n",
"proxies/20-tailscale.yaml": " # Tailscale: userspace node, starts on first use. First login: open the URL\n # from the nikki log (\"To start this tsnet server ... go to: ...\"), then\n # disable key expiry for this node. Needs TS_FORCE_NOISE_443=true in the\n # mihomo environment (mihomo-kit.sh fix).\n - name: tailscale\n type: tailscale\n hostname: ${TS_HOSTNAME}\n state-dir: ./tailscale\n udp: true\n accept-routes: true\n dialer-proxy: TS-EXIT #@ts_exit\n # whitelist: control and DERP over TCP through own servers (MY -> hysteria2 -> MY-EXIT); #@whitelist,hy2,!ts_exit\n # needs the kit's core (v1.19.32-ts1, tools/core/*.patch, MetaCubeX/mihomo#3142) #@whitelist,hy2,!ts_exit\n dialer-proxy: MY #@whitelist,hy2,!ts_exit\n",
"proxies/30-hy2.each.yaml": " - name: ${HY2_NAME}\n type: hysteria2\n server: ${HY2_SERVER}\n port: ${HY2_PORT}\n password: \"${HY2_PASSWORD}\"\n obfs: ${@HY2_OBFS}\n obfs-password: \"${@@HY2_OBFS_PASSWORD}\"\n sni: ${@HY2_SNI}\n skip-cert-verify: ${HY2_INSECURE}\n up: \"${@@HY2_UP}\"\n down: \"${@@HY2_DOWN}\"\n udp: true\n dialer-proxy: MY-EXIT #@hy2_exit\n dialer-proxy: UPLINK #@csqtt,!hy2_exit\n",
"proxies/40-csqtt.yaml": " # CSQTT (star-panel-csqtt): tunnel interface csqtt0 on the router, mihomo\n # just sends the connection out of it (the interface does not change routes)\n - name: CSQTT\n type: direct\n interface-name: ${CSQTT_IFACE}\n udp: true\n",
"rule-providers/20-openvpn.yaml": " # OpenVPN routes (OVPN_ROUTES): the file is written by mihomo-kit.sh build and\n # emptied by bmstu-otp.sh off, so with the tunnel off these addresses follow\n # the normal rules instead of a dead BMSTU group\n ${OVPN_PROVIDER}-routes:\n type: file\n behavior: ipcidr\n path: ./providers/${OVPN_PROVIDER}-routes.yaml\n",
"rules/05-csqtt.yaml": " # the CSQTT client's own connections (peer, VK TURN) must not go into its tunnel\n - PROCESS-NAME,${@CSQTT_PROCESS},DIRECT\n",
"rules/10-tailscale.yaml": " # Tailscale: tailnet IPs and MagicDNS names (resolved by tailscale itself)\n - IP-CIDR,100.64.0.0/10,TAILSCALE,no-resolve\n - DOMAIN-SUFFIX,ts.net,TAILSCALE\n - DOMAIN-SUFFIX,${@TS_DOMAINS},TAILSCALE\n",
"rules/20-openvpn.yaml": " # OpenVPN server itself must not go into its own tunnel\n - IP-CIDR,${@OVPN_SERVER_IPS}/32,DIRECT,no-resolve #@!ovpn_exit\n - IP-CIDR,${@OVPN_SERVER_IPS}/32,OVPN-EXIT,no-resolve #@ovpn_exit\n - DOMAIN,${OVPN_SERVER_HOST},DIRECT #@!ovpn_exit\n - DOMAIN,${OVPN_SERVER_HOST},OVPN-EXIT #@ovpn_exit\n # networks pushed by the server (before the private-range DIRECT rules);\n # a rule-provider so that bmstu-otp.sh off can drop them without a restart\n - RULE-SET,${OVPN_PROVIDER}-routes,${OVPN_GROUP},no-resolve\n",
"rules/30-base.yaml": " - IP-CIDR,192.168.0.0/16,DIRECT,no-resolve\n - IP-CIDR,10.0.0.0/8,DIRECT,no-resolve\n - IP-CIDR,172.16.0.0/12,DIRECT,no-resolve\n",
"rules/35-push.yaml": " # push notifications (Apple APNs, Google FCM): long-lived connections on a\n # stable path - group PUSH (main/foreign: DIRECT, whitelist: MY)\n - DOMAIN-SUFFIX,push.apple.com,PUSH\n - IP-CIDR,17.249.0.0/16,PUSH,no-resolve\n - IP-CIDR,17.252.0.0/16,PUSH,no-resolve\n - IP-CIDR,17.57.144.0/22,PUSH,no-resolve\n - IP-CIDR,17.188.128.0/18,PUSH,no-resolve\n - IP-CIDR,17.188.20.0/23,PUSH,no-resolve\n - DOMAIN-REGEX,^(alt[0-9]+-)?mtalk[0-9]*\\.google\\.com$,PUSH\n - DST-PORT,5228-5230,PUSH\n",
"rules/40-base.yaml": " # main (home, own white IP): reachable directly; whitelist/abroad: through RU\n - IP-CIDR,${@RU_IPS},DIRECT #@main\n - IP-CIDR,${@RU_IPS},RU #@!main\n",
"rules/50-torrent.yaml": " - SRC-PORT,20000-20199,TORRENT-SEL\n",
"rules/90-base.yaml": " - GEOSITE,ru-inside,DIRECT #@!foreign\n # abroad: Russian services through the RU pool too #@foreign\n - GEOSITE,ru-inside,RU #@foreign\n # main (home, own white IP): .ru/.рф directly; elsewhere through RU\n - DOMAIN-SUFFIX,ru,DIRECT #@main\n - DOMAIN-SUFFIX,xn--p1ai,DIRECT #@main\n - DOMAIN-SUFFIX,ru,RU #@!main\n - DOMAIN-SUFFIX,xn--p1ai,RU #@!main\n - MATCH,MAIN\n",
"sniffer/10-base.yaml": "sniffer:\n enable: true\n force-dns-mapping: true\n parse-pure-ip: true\n override-destination: false\n sniff:\n HTTP:\n ports: [80, 8080-8880]\n TLS:\n ports: [443, 8443]\n QUIC:\n ports: [443, 8443]\n"
};
const D = MihomoKit.DEFAULTS;
const $ = (id) => document.getElementById(id);
const form = $("form");
let tab = "yaml";
let current = { yaml: "", env: "", steps: "" };
for (const k of ["OVPN_SERVER_HOST", "OVPN_SERVER_IPS", "OVPN_ROUTES"]) $(k).value = D[k];
function addSub() {
const row = document.createElement("div");
row.className = "sub";
row.innerHTML = `
<div class="sub-head"><span class="name"></span>
<input type="text" data-k="url" placeholder="https://sub.example.com/sub/xxxx или имя=https://…">
<button type="button" class="x-btn" title="убрать">×</button></div>
<div class="sub-opts">
<label>через <select data-k="proxy"><option value="">авто</option><option>BOOT-AUTO</option><option>BOOT</option><option>DIRECT</option><option>FOREIGN</option></select></label>
<label class="check"><input type="checkbox" data-k="hwid">HWID</label>
</div>
<details><summary>User-Agent и заголовки</summary>
<label>User-Agent (пусто = mihomo, с HWID — из блока HWID)</label><input type="text" data-k="ua">
<label>доп. заголовки: key=value; key2=value 2</label><input type="text" data-k="headers">
</details>`;
row.querySelector(".x-btn").addEventListener("click", () => {
if (document.querySelectorAll("#subs .sub").length > 1) row.remove();
update();
});
$("subs").appendChild(row);
update();
}
$("add-sub").addEventListener("click", addSub);
// rows with a URL, in order; id = provider name from the domain (or "name=url")
function readSubs() {
const rows = [...document.querySelectorAll("#subs .sub")];
const filled = rows.filter((row) => row.querySelector("[data-k=url]").value.trim());
const ids = MihomoKit.subPairs(filled.map((row) => row.querySelector("[data-k=url]").value.trim()).join(" "));
rows.forEach((row) => (row.querySelector(".name").textContent = ""));
return filled.map((row, n) => {
const get = (k) => row.querySelector(`[data-k=${k}]`);
row.querySelector(".name").textContent = ids[n].id;
return { id: ids[n].id, url: ids[n].word, proxy: get("proxy").value, hwid: get("hwid").checked,
ua: get("ua").value.trim(), headers: get("headers").value.trim() };
});
}
function radio(name) { return form.querySelector(`input[name=${name}]:checked`).value; }
function flag(id) { return $(id).checked ? "1" : "0"; }
function readVars() {
const v = {
TARGET: radio("TARGET"), LOCATION: radio("LOCATION"),
SUBS: "",
RU_IPS: $("RU_IPS").value.trim(),
BOOT: flag("BOOT"), TORRENT: flag("TORRENT"), PUSH: flag("PUSH"), OPENVPN: flag("OPENVPN"),
TAILSCALE: flag("TAILSCALE"), TS_EXIT: flag("TS_EXIT"), CSQTT: flag("CSQTT"),
};
for (const k of ["BOOT_SERVER", "BOOT_PORT", "BOOT_UUID", "BOOT_SNI", "BOOT_PBK", "BOOT_SID",
"TS_HOSTNAME", "TS_DOMAINS", "OVPN_SERVER_HOST", "OVPN_SERVER_IPS", "OVPN_ROUTES"]) {
v[k] = $(k).value.trim();
}
const subs = readSubs();
v.SUBS = subs.map((x) => x.url).join(" ");
v._HWID = subs.some((x) => x.hwid);
for (const x of subs) {
const p = `SUB_${x.id.toUpperCase()}_`;
if (x.proxy) v[p + "PROXY"] = x.proxy;
if (x.hwid) v[p + "HWID"] = "1";
if (x.ua) v[p + "UA"] = x.ua;
if (x.headers) v[p + "HEADERS"] = x.headers;
}
for (const k of ["HWID_UA", "HWID_OS", "HWID_OS_VER", "HWID_MODEL", "HWID_ID"]) v[k] = $(k).value.trim();
return v;
}
const q = (s) => "'" + String(s).replace(/'/g, "'\\''") + "'";
function envFile(v) {
const keys = ["TARGET", "LOCATION", "SUBS"];
keys.push(...Object.keys(v).filter((k) => /^SUB_/.test(k) && k !== "SUB_LIST"));
if (v._HWID) keys.push("HWID_UA", "HWID_OS", "HWID_OS_VER", "HWID_MODEL", "HWID_ID");
keys.push("BOOT");
if (v.BOOT === "1") keys.push("BOOT_SERVER", "BOOT_PORT", "BOOT_UUID", "BOOT_SNI", "BOOT_PBK", "BOOT_SID");
keys.push("TORRENT", "PUSH", "RU_IPS", "OPENVPN");
if (v.OPENVPN === "1") keys.push("OVPN_SERVER_HOST", "OVPN_SERVER_IPS", "OVPN_ROUTES");
keys.push("CSQTT", "TAILSCALE");
if (v.TAILSCALE === "1") keys.push("TS_HOSTNAME", "TS_DOMAINS", "TS_EXIT");
return "# mihomo-kit profile (secrets inside: chmod 600)\n" +
keys.map((k) => `${k}=${q(v[k] ?? "")}`).join("\n") + "\n";
}
function steps(v) {
const name = $("PROFILE_NAME").value.trim() || "main";
if (v.TARGET === "mobile") {
return [
"Телефон (FlClash):",
"1. Скачай config.yaml (кнопка «Скачать»).",
"2. FlClash → Профили → + → Файл → выбери config.yaml.",
"3. Включи профиль; геобазы скачаются при первом запуске.",
].join("\n");
}
const s = [
"Роутер (nikki). Один раз на новом роутере — см. README, раздел «Новый роутер».",
"",
`1. Сохрани profile .env как /etc/nikki/profiles.d/${name}.env`,
` (общие секреты можно вынести в /etc/nikki/profiles.d/common.env)`,
` chmod 600 /etc/nikki/profiles.d/*.env`,
"2. Собери и включи:",
` mihomo-kit.sh build ${name}`,
` mihomo-kit.sh use ${name}`,
];
if (v.OPENVPN === "1") s.push("", "OpenVPN: заполни /etc/nikki/bmstu.env, положи .ovpn в /etc/nikki/bmstu.ovpn,",
" cron (bmstu-otp.sh check) ставит mihomo-kit.sh install.",
v.LOCATION === "whitelist" ? " На белых списках выбери RU-ноду в группе OVPN-EXIT в дашборде." : "");
if (v.TAILSCALE === "1") s.push("", "Tailscale: ссылка для входа — LuCI → Службы → mihomo-kit или",
" mihomo-kit.sh ts-login",
" Потом в админке Tailscale: Disable key expiry для " + (v.TS_HOSTNAME || "ноды") + ".");
return s.join("\n");
}
function update() {
const v = readVars();
const router = v.TARGET === "router";
document.querySelectorAll("[data-router]").forEach((el) => (el.hidden = !router));
document.querySelectorAll("[data-boot]").forEach((el) => (el.hidden = v.BOOT !== "1"));
document.querySelectorAll("[data-openvpn]").forEach((el) => (el.hidden = v.OPENVPN !== "1"));
document.querySelectorAll("[data-tailscale]").forEach((el) => (el.hidden = v.TAILSCALE !== "1"));
document.querySelectorAll("[data-hwid]").forEach((el) => (el.hidden = !v._HWID));
if (!router && tab === "env") setTab("yaml");
const err = $("error");
try {
current.yaml = MihomoKit.render(TEMPLATES, v);
err.hidden = true;
} catch (e) {
current.yaml = "";
err.textContent = e.message;
err.hidden = false;
}
current.env = envFile(v);
current.steps = steps(v);
$("out").textContent = current[tab];
}
function setTab(t) {
tab = t;
document.querySelectorAll("[data-tab]").forEach((b) => b.setAttribute("aria-selected", String(b.dataset.tab === t)));
$("out").textContent = current[t];
}
function parseVless(link) {
try {
const u = new URL(link.trim());
if (u.protocol !== "vless:") return;
const p = u.searchParams;
$("BOOT_UUID").value = decodeURIComponent(u.username);
$("BOOT_SERVER").value = u.hostname.replace(/^\[|\]$/g, "");
$("BOOT_PORT").value = u.port || "443";
if (p.get("sni")) $("BOOT_SNI").value = p.get("sni");
if (p.get("pbk")) $("BOOT_PBK").value = p.get("pbk");
if (p.get("sid")) $("BOOT_SID").value = p.get("sid");
} catch (_) { /* not a full link yet */ }
}
form.addEventListener("change", update);
form.addEventListener("input", (e) => {
if (e.target.id === "vless") parseVless(e.target.value);
update();
});
document.querySelectorAll("[data-tab]").forEach((b) => b.addEventListener("click", () => setTab(b.dataset.tab)));
$("copy").addEventListener("click", async () => {
try { await navigator.clipboard.writeText(current[tab]); $("copy").textContent = "Скопировано"; }
catch (_) { $("copy").textContent = "Не вышло"; }
setTimeout(() => ($("copy").textContent = "Копировать"), 1200);
});
$("download").addEventListener("click", () => {
const name = tab === "env" ? `${$("PROFILE_NAME").value.trim() || "main"}.env`
: tab === "yaml" ? (radio("TARGET") === "mobile" ? "flclash.yaml" : `${$("PROFILE_NAME").value.trim() || "main"}.yaml`)
: "steps.txt";
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([current[tab]], { type: "text/plain" }));
a.download = name;
a.click();
URL.revokeObjectURL(a.href);
});
addSub();
</script>
</body>
</html>