Added setup page

This commit is contained in:
Sam Latsin 2026-10-09 17:39:40 +03:00
parent fdeccbe434
commit 51aba8cc1d
12 changed files with 699 additions and 128 deletions

View File

@ -19,17 +19,23 @@ tools/push.sh root@192.168.32.1
ssh root@192.168.32.1 sh /etc/nikki/kit/install.sh
```
Установщик ставит nikki (если нет), правильное ядро и фиксы, затем спрашивает:
подписки, vless-ссылку BOOT, торренты, OpenVPN (логин, пароль, TOTP-секрет), Tailscale —
собирает профили `home` и `street` и включает выбранный.
Установщик ставит nikki (если нет), правильное ядро, фиксы и kit со страницей LuCI —
ничего не спрашивает. Дальше всё в браузере: LuCI → **Службы → mihomo-kit → Настройка**
(адрес установщик печатает в конце; если пункта нет — выйти из LuCI и войти снова).
Там подписки, vless-ссылка BOOT, торренты, OpenVPN (файл `.ovpn`, логин, пароль,
TOTP-секрет), Tailscale; «Сохранить и применить» собирает профили `home` и `street`,
включает профиль и, если включён Tailscale, показывает ссылку для входа — открыть её,
войти, в админке Tailscale **Disable key expiry** для ноды.
Перед установкой:
- **zeroblock / podkop выключить** — он перехватывает трафик самого роутера;
- для OpenVPN положить `.ovpn` в `/etc/nikki/bmstu.ovpn` (установщик подождёт):
`scp -O file.ovpn root@192.168.32.1:/etc/nikki/bmstu.ovpn`.
Позже настройки меняются там же — «Изменить настройки»; ключи, добавленные в
`common.env` / `bmstu.env` руками, сохраняются.
Если включён Tailscale, установщик в конце печатает ссылку для входа: открыть её, войти,
в админке Tailscale — **Disable key expiry** для ноды. Ссылку можно получить заново:
Роутер без LuCI или вопросы в терминале по-старому:
`wget -qO- …/install.sh | sh -s -- --cli` (или `mihomo-kit.sh setup --cli`).
Перед установкой **zeroblock / podkop выключить** — он перехватывает трафик самого роутера.
Ссылку для входа в Tailscale можно получить заново: кнопка на странице или
`mihomo-kit.sh ts-login` (пересоздаёт ещё не вошедшую ноду; `-f` — даже вошедшую).
## Каждый день
@ -74,11 +80,16 @@ mihomo-kit.sh build # после правки /etc/nikki/profiles.d/*.
| `/etc/nikki/bmstu.env`, `bmstu.ovpn` | OpenVPN: логин, пароль, TOTP-секрет |
| `/etc/nikki/run/tailscale/` | ключ ноды Tailscale — не удалять |
У каждой подписки свои настройки (`SUB<N>_*` в `common.env`, N — номер в `SUBS`):
через что качать (`SUB1_PROXY=DIRECT`), User-Agent, доп. заголовки и HWID для подписок с
лимитом устройств (`SUB1_HWID=1` + общий блок `HWID_*`: x-device-os, x-ver-os,
x-device-model, x-hwid). Мастер спрашивает это для каждой подписки и сам подставляет ОС,
версию и модель роутера.
У каждой подписки есть имя — так называется провайдер в дашборде, и к нему привязаны
её настройки. Имя берётся из домена: `https://sub.kittyvpn.com/…` → `kittyvpn`
(`a.b.co.uk` → `b`, повтор домена → `kittyvpn2`); своё имя — словом `имя=https://…` в
`SUBS`. Настройки — `SUB_<ИМЯ>_*` в `common.env` (имя заглавными, `-` → `_`): через что
качать (`SUB_KITTYVPN_PROXY=DIRECT`), User-Agent (`_UA`), доп. заголовки (`_HEADERS`) и
HWID для подписок с лимитом устройств (`SUB_KITTYVPN_HWID=1` + общий блок `HWID_*`:
x-device-os, x-ver-os, x-device-model, x-hwid). Порядок подписок в `SUBS` поэтому не
важен. Старые ключи по номеру (`SUB1_UA`) ещё читаются; сохранение из LuCI или мастера
переименовывает их по имени. Если провайдер сменит домен, сменится и имя — задай его
явно, чтобы настройки не потерялись.
Новый профиль = новый файл в `profiles.d/` (например `LOCATION=home` + `OPENVPN=0`),
затем `mihomo-kit.sh build && mihomo-kit.sh use <имя>`. Все опции — в

View File

@ -3,7 +3,8 @@
# wget -qO- https://git.sam-hub.net/sam/mihomo-kit/raw/branch/main/install.sh | sh
# or after tools/push.sh from a computer:
# sh /etc/nikki/kit/install.sh
# Installs nikki if needed, asks a few questions, builds the profiles and starts one.
# Installs nikki (if needed), the core, the fixes and the kit with its LuCI page;
# the settings are then made in LuCI -> Services -> mihomo-kit.
set -eu
KIT_URL=${KIT_URL:-https://git.sam-hub.net/sam/mihomo-kit/archive/main.tar.gz}
KIT_DIR=/etc/nikki/kit
@ -27,5 +28,5 @@ else
done
rm -rf "$tmp"
fi
# stdin may be the piped script: the wizard reads answers from /dev/tty
exec sh "$KIT_DIR/router/mihomo-kit.sh" setup
# stdin may be the piped script: the wizard (setup --cli) reads answers from /dev/tty
exec sh "$KIT_DIR/router/mihomo-kit.sh" setup "$@"

View File

@ -8,7 +8,7 @@
},
"write": {
"ubus": {
"mihomo-kit": [ "run" ]
"mihomo-kit": [ "run", "config_get", "config_set" ]
}
}
}

View File

@ -11,6 +11,8 @@ var callStatus = rpc.declare({ object: 'mihomo-kit', method: 'status', expect: {
var callOvpnStatus = rpc.declare({ object: 'mihomo-kit', method: 'ovpn_status', expect: { '': {} } });
var callJob = rpc.declare({ object: 'mihomo-kit', method: 'job', expect: { '': {} } });
var callRun = rpc.declare({ object: 'mihomo-kit', method: 'run', params: [ 'cmd', 'arg' ], expect: { '': {} } });
var callConfigGet = rpc.declare({ object: 'mihomo-kit', method: 'config_get', expect: { '': {} } });
var callConfigSet = rpc.declare({ object: 'mihomo-kit', method: 'config_set', params: [ 'data' ], expect: { '': {} } });
function wait(ms) {
return new Promise(function(resolve) { window.setTimeout(resolve, ms); });
@ -27,6 +29,37 @@ function section(title, children) {
return E('div', { 'class': 'cbi-section' }, [ E('h3', title) ].concat(children));
}
// form helpers for the settings section
function text(value, placeholder, type) {
return E('input', { 'type': type || 'text', 'class': 'cbi-input-text', 'style': 'width:100%',
'value': value || '', 'placeholder': placeholder || '' });
}
function check(value) {
var c = E('input', { 'type': 'checkbox' });
c.checked = !!value;
return c;
}
function field(title, el, desc) {
return E('div', { 'class': 'cbi-value' }, [
E('label', { 'class': 'cbi-value-title' }, title),
E('div', { 'class': 'cbi-value-field' }, [ el ].concat(desc ? [ E('div', { 'class': 'cbi-value-description' }, desc) ] : []))
]);
}
function readFile(input) {
var f = input.files && input.files[0];
if (!f)
return Promise.resolve('');
return new Promise(function(resolve, reject) {
var r = new FileReader();
r.onload = function() { resolve(r.result); };
r.onerror = function() { reject(r.error); };
r.readAsText(f);
});
}
return view.extend({
handleSaveApply: null,
handleSave: null,
@ -56,7 +89,7 @@ return view.extend({
if (!st.configured)
sections.push(E('div', { 'class': 'alert-message warning' },
'Kit ещё не настроен: запусти по ssh mihomo-kit.sh setup'));
'Kit ещё не настроен: заполни «Настройка» ниже и нажми «Сохранить и применить».'));
var select = E('select', { 'class': 'cbi-input-select' }, (st.profiles || []).map(function(p) {
return E('option', { 'value': p }, p);
@ -122,6 +155,165 @@ return view.extend({
dom.content(this.body, sections);
},
// collapsed: a button; open: the form (always open until configured)
renderSettingsBox: function(open) {
if (open)
return callConfigGet().then(L.bind(this.renderSettings, this));
dom.content(this.settingsBox, [ E('h3', 'Настройка'), E('button', {
'class': 'btn cbi-button cbi-button-action',
'click': ui.createHandlerFn(this, function() { return this.renderSettingsBox(true); })
}, 'Изменить настройки') ]);
return Promise.resolve();
},
renderSettings: function(cfg) {
var subList = E('div'), subs = [];
var hwidBox = E('div'), ovpnBox = E('div'), tsBox = E('div');
var f = {
boot: text(cfg.boot_link, 'vless://…'),
hwid_ua: text(cfg.hwid_ua), hwid_os: text(cfg.hwid_os), hwid_os_ver: text(cfg.hwid_os_ver),
hwid_model: text(cfg.hwid_model), hwid_id: text(cfg.hwid_id),
torrent: check(cfg.torrent),
ru_ips: text(cfg.ru_ips, '1.2.3.4/32 5.6.0.0/16'),
openvpn: check(cfg.openvpn),
ovpn: E('input', { 'type': 'file', 'accept': '.ovpn,.conf' }),
vpn_username: text(cfg.vpn_username),
vpn_password: text('', cfg.has_vpn_password ? 'сохранён — пусто, чтобы не менять' : '', 'password'),
totp_secret: text('', cfg.has_totp ? 'сохранён — пусто, чтобы не менять' : 'base32 из QR', 'password'),
tailscale: check(cfg.tailscale),
ts_hostname: text(cfg.ts_hostname),
ts_domains: text(cfg.ts_domains, 'corp.example.com')
};
var update = function() {
hwidBox.style.display = subs.some(function(s) { return s.hwid.checked; }) ? '' : 'none';
ovpnBox.style.display = f.openvpn.checked ? '' : 'none';
tsBox.style.display = f.tailscale.checked ? '' : 'none';
};
var addSub = function(s) {
var vias = [ 'BOOT', 'DIRECT' ];
if (s.via && vias.indexOf(s.via) < 0)
vias.push(s.via);
var entry = {
url: E('input', { 'type': 'text', 'class': 'cbi-input-text', 'style': 'flex:1;min-width:16em',
'value': s.url || '', 'placeholder': 'https://…' }),
via: E('select', { 'class': 'cbi-input-select' }, vias.map(function(v) { return E('option', { 'value': v }, v); })),
hwid: check(s.hwid)
};
entry.via.value = s.via || 'BOOT';
entry.hwid.addEventListener('change', update);
var el = E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap;margin-bottom:.4em' }, [
entry.url, E('code', { 'title': 'имя провайдера' }, s.id || 'новая'), 'через', entry.via,
E('label', [ entry.hwid, ' HWID' ]),
E('button', { 'class': 'btn cbi-button cbi-button-remove', 'click': function() {
subList.removeChild(el);
subs.splice(subs.indexOf(entry), 1);
update();
} }, '✕')
]);
subs.push(entry);
subList.appendChild(el);
};
(cfg.subs && cfg.subs.length ? cfg.subs : [ {} ]).forEach(addSub);
dom.content(hwidBox, [
E('h4', 'HWID (общий для подписок с галкой HWID)'),
field('User-Agent', f.hwid_ua),
field('x-device-os', f.hwid_os),
field('x-ver-os', f.hwid_os_ver),
field('x-device-model', f.hwid_model),
field('x-hwid', f.hwid_id, 'если провайдер уже знает устройство — оставь тот же')
]);
dom.content(ovpnBox, [
field('Файл .ovpn', f.ovpn, cfg.ovpn_file ? 'загружен; выбери файл, только чтобы заменить' : 'ещё не загружен'),
field('Логин', f.vpn_username),
field('Пароль (без OTP)', f.vpn_password),
field('TOTP-секрет', f.totp_secret)
]);
dom.content(tsBox, [
field('Имя ноды', f.ts_hostname),
field('Split-DNS домены', f.ts_domains, 'домены тейлнета кроме *.ts.net, через пробел')
]);
f.openvpn.addEventListener('change', update);
f.tailscale.addEventListener('change', update);
update();
var save = E('button', {
'class': 'btn cbi-button cbi-button-save',
'click': ui.createHandlerFn(this, function() {
var list = subs.map(function(s) {
return { url: s.url.value.trim(), via: s.via.value, hwid: s.hwid.checked };
}).filter(function(s) { return s.url; });
var errors = [];
if (!list.length)
errors.push('нужна хотя бы одна подписка');
if (f.boot.value.trim() && !/^vless:\/\//.test(f.boot.value.trim()))
errors.push('BOOT: нужна ссылка vless://');
if (f.openvpn.checked) {
if (!cfg.ovpn_file && !f.ovpn.files.length)
errors.push('OpenVPN: выбери файл .ovpn');
if (!f.vpn_username.value.trim())
errors.push('OpenVPN: нужен логин');
if (!cfg.has_vpn_password && !f.vpn_password.value)
errors.push('OpenVPN: нужен пароль');
if (!cfg.has_totp && !f.totp_secret.value.trim())
errors.push('OpenVPN: нужен TOTP-секрет');
}
if (errors.length) {
ui.addNotification(null, errors.map(function(e) { return E('p', e); }), 'danger');
return;
}
return readFile(f.ovpn).then(L.bind(function(ovpn) {
return callConfigSet({
boot_link: f.boot.value.trim(),
subs: list,
hwid_ua: f.hwid_ua.value, hwid_os: f.hwid_os.value, hwid_os_ver: f.hwid_os_ver.value,
hwid_model: f.hwid_model.value, hwid_id: f.hwid_id.value,
torrent: f.torrent.checked,
ru_ips: f.ru_ips.value.trim(),
openvpn: f.openvpn.checked,
ovpn: ovpn,
vpn_username: f.vpn_username.value.trim(),
vpn_password: f.vpn_password.value,
totp_secret: f.totp_secret.value.replace(/\s+/g, ''),
tailscale: f.tailscale.checked,
ts_hostname: f.ts_hostname.value.trim(),
ts_domains: f.ts_domains.value.trim()
});
}, this)).then(L.bind(function(r) {
if (r.error) {
ui.addNotification(null, E('p', r.error), 'danger');
return;
}
return this.follow().then(L.bind(function(j) {
if (j && j.rc === 0)
return this.renderSettingsBox(false);
}, this));
}, this));
})
}, 'Сохранить и применить');
dom.content(this.settingsBox, [
E('h3', 'Настройка'),
field('BOOT', f.boot, 'vless-ссылка seed-ноды, через неё качаются подписки; пусто — без BOOT'),
field('Подписки', [ subList, E('button', {
'class': 'btn cbi-button cbi-button-add',
'click': function() { addSub({}); update(); }
}, 'Добавить подписку') ], 'Имя провайдера берётся из домена (sub.kittyvpn.com → kittyvpn), ' +
'настройки привязаны к нему; задать своё: имя=https://…. HWID — для подписок с лимитом устройств.'),
hwidBox,
field('Торренты', f.torrent, 'через TORRENT-SEL (порты 20000-20199)'),
field('Доп. IP через RU', f.ru_ips, 'CIDR через пробел'),
field('OpenVPN BMSTU', f.openvpn),
ovpnBox,
field('Tailscale', f.tailscale),
tsBox,
E('div', { 'class': 'cbi-page-actions' }, [ save ])
]);
},
showJob: function(j) {
if (!j.cmd) {
this.jobBox.style.display = 'none';
@ -170,7 +362,7 @@ return view.extend({
this.setBusy(false);
if (j.rc !== 0)
ui.addNotification(null, E('p', j.cmd + ': ошибка, см. вывод внизу страницы'), 'danger');
return callStatus().then(L.bind(this.renderBody, this));
return callStatus().then(L.bind(this.renderBody, this)).then(function() { return j; });
}, this)).catch(L.bind(function(e) {
if (++errors > 15) {
this.setBusy(false);
@ -191,12 +383,14 @@ return view.extend({
this.jobLink = E('div');
this.jobLog = E('pre', { 'style': 'white-space:pre-wrap;max-height:24em;overflow:auto' });
this.jobBox = E('div', { 'class': 'cbi-section' }, [ this.jobTitle, this.jobLink, this.jobLog ]);
this.settingsBox = E('div', { 'class': 'cbi-section' });
this.renderSettingsBox(!data[0].configured);
this.renderBody(data[0]);
this.showJob(data[1]);
if (data[1].running)
this.follow();
return E([], [ E('h2', 'mihomo-kit'), this.body, this.jobBox ]);
return E([], [ E('h2', 'mihomo-kit'), this.body, this.settingsBox, this.jobBox ]);
}
});

View File

@ -5,6 +5,8 @@
# ovpn_status OpenVPN state (up/down/off) + current OTP; slow (a delay test)
# run start a whitelisted command as the background job
# job the job's command, state, exit code and output
# config_get settings for the form (secrets: only whether they are set)
# config_set save the form (via "mihomo-kit.sh configure") as the job
#
# rpcd kills calls after ~30 s; use/update/ts-login take longer, hence the job.
@ -24,6 +26,8 @@ envval() {
sed -n "s/^$1=//p" | tail -n 1 | tr -d "'\""
}
q() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; }
job_running() { [ -f "$JOB/pid" ] && kill -0 "$(cat "$JOB/pid")" 2>/dev/null; }
reply_error() {
@ -86,6 +90,11 @@ m_run() {
build | update | fix) set -- mihomo-kit.sh "$cmd" ;;
*) reply_error "unknown command: $cmd" ;;
esac
start_job "$@"
}
# start_job cmd args...: run it in the background, reply at once
start_job() {
job_running && reply_error "busy: $(cat "$JOB/cmd")"
rm -rf "$JOB"
mkdir -p "$JOB"
@ -101,6 +110,109 @@ m_run() {
json_dump
}
m_config_get() {
[ -f "$PROFILES_D/common.env" ] && . "$PROFILES_D/common.env"
[ -f "$NIKKI_DIR/bmstu.env" ] && . "$NIKKI_DIR/bmstu.env"
[ -f /etc/openwrt_release ] && . /etc/openwrt_release
json_init
json_add_boolean configured "$(b test -f "$PROFILES_D/common.env")"
link=
[ "${BOOT:-0}" = 1 ] &&
link="vless://$BOOT_UUID@$BOOT_SERVER:$BOOT_PORT?security=reality&sni=$BOOT_SNI&pbk=$BOOT_PBK&sid=$BOOT_SID"
json_add_string boot_link "$link"
json_add_array subs
i=0
# "<id> <SUBS word>"; keys SUB_<ID>_*, else the old SUB<index>_*
SUBS=${SUBS:-} mihomo-kit.sh sub-ids > /tmp/mihomo-kit-ids.$$
while read -r id w; do
K=$(echo "$id" | tr 'a-z' 'A-Z')
eval "p=\${SUB_${K}_PROXY:-\${SUB${i}_PROXY:-}} h=\${SUB_${K}_HWID:-\${SUB${i}_HWID:-0}}"
[ -n "$p" ] || { [ "${BOOT:-0}" = 1 ] && p=BOOT || p=DIRECT; }
json_add_object ""
json_add_string id "$id"
json_add_string url "$w"
json_add_string via "$p"
json_add_boolean hwid "$h"
json_close_object
i=$((i + 1))
done < /tmp/mihomo-kit-ids.$$
rm -f /tmp/mihomo-kit-ids.$$
json_close_array
# HWID defaults: the same as the terminal wizard suggests
json_add_string hwid_ua "${HWID_UA:-v2rayN/9.99}"
json_add_string hwid_os "${HWID_OS:-OpenWrt}"
json_add_string hwid_os_ver "${HWID_OS_VER:-${DISTRIB_RELEASE:-}}"
json_add_string hwid_model "${HWID_MODEL:-$(cat /tmp/sysinfo/model 2>/dev/null)}"
json_add_string hwid_id "${HWID_ID:-$(md5sum < /sys/class/net/br-lan/address 2>/dev/null | cut -c1-16)}"
json_add_boolean torrent "${TORRENT:-1}"
json_add_string ru_ips "${RU_IPS:-}"
json_add_boolean openvpn "${OPENVPN:-0}"
json_add_boolean ovpn_file "$(b test -f "$NIKKI_DIR/bmstu.ovpn")"
json_add_string vpn_username "${VPN_USERNAME:-}"
json_add_boolean has_vpn_password "$(b test -n "${VPN_PASSWORD:-}")"
json_add_boolean has_totp "$(b test -n "${TOTP_SECRET:-}")"
json_add_boolean tailscale "${TAILSCALE:-0}"
json_add_string ts_hostname "${TS_HOSTNAME:-$(uci -q get 'system.@system[0].hostname' | tr 'A-Z' 'a-z')-mihomo}"
json_add_string ts_domains "${TS_DOMAINS:-}"
json_dump
}
# {"data": {boot_link, subs: [{url, via, hwid}], hwid_*, torrent, ru_ips,
# openvpn, ovpn (file text, optional), vpn_username, vpn_password, totp_secret,
# tailscale, ts_hostname, ts_domains}}; empty secrets keep the saved ones
m_config_set() {
json_load "$(cat)" || reply_error "bad request"
json_select data || reply_error "no data"
job_running && reply_error "busy: $(cat "$JOB/cmd")"
for v in boot_link hwid_ua hwid_os hwid_os_ver hwid_model hwid_id torrent ru_ips openvpn ovpn \
vpn_username vpn_password totp_secret tailscale ts_hostname ts_domains; do
json_get_var "$v" "$v" ""
done
if [ -n "$ovpn" ]; then
umask 077
printf '%s\n' "$ovpn" > "$NIKKI_DIR/bmstu.ovpn.tmp" && mv "$NIKKI_DIR/bmstu.ovpn.tmp" "$NIKKI_DIR/bmstu.ovpn"
fi
umask 077
env=$(mktemp /tmp/mihomo-kit-form.XXXXXX) || reply_error "mktemp failed"
{
echo "BOOT_LINK=$(q "$boot_link")"
subs= i=0
if json_select subs; then
json_get_keys keys
for k in $keys; do
url= via= hwid=
json_select "$k"
json_get_vars url via hwid
json_select ..
url=$(printf '%s' "$url" | tr -d ' \t\r\n')
[ -n "$url" ] || continue
subs="${subs:+$subs }$url"
echo "SUB${i}_PROXY=$(q "$via")"
echo "SUB${i}_HWID=$(q "${hwid:-0}")"
i=$((i + 1))
done
json_select ..
fi
echo "SUBS=$(q "$subs")"
echo "HWID_UA=$(q "$hwid_ua")"
echo "HWID_OS=$(q "$hwid_os")"
echo "HWID_OS_VER=$(q "$hwid_os_ver")"
echo "HWID_MODEL=$(q "$hwid_model")"
echo "HWID_ID=$(q "$hwid_id")"
echo "TORRENT=$(q "${torrent:-0}")"
echo "RU_IPS=$(q "$ru_ips")"
echo "OPENVPN=$(q "${openvpn:-0}")"
echo "VPN_USERNAME=$(q "$vpn_username")"
[ -n "$vpn_password" ] && echo "VPN_PASSWORD=$(q "$vpn_password")"
[ -n "$totp_secret" ] && echo "TOTP_SECRET=$(q "$totp_secret")"
echo "TAILSCALE=$(q "${tailscale:-0}")"
echo "TS_HOSTNAME=$(q "$ts_hostname")"
echo "TS_DOMAINS=$(q "$ts_domains")"
} > "$env"
umask 022
start_job mihomo-kit.sh configure "$env"
}
m_job() {
json_init
json_add_string cmd "$(cat "$JOB/cmd" 2>/dev/null)"
@ -112,7 +224,7 @@ m_job() {
case "$1" in
list)
echo '{"status":{},"ovpn_status":{},"job":{},"run":{"cmd":"str","arg":"str"}}'
echo '{"status":{},"ovpn_status":{},"job":{},"run":{"cmd":"str","arg":"str"},"config_get":{},"config_set":{"data":{}}}'
;;
call)
case "$2" in
@ -120,6 +232,8 @@ case "$1" in
ovpn_status) m_ovpn_status ;;
job) m_job ;;
run) m_run ;;
config_get) m_config_get ;;
config_set) m_config_set ;;
*) reply_error "unknown method" ;;
esac
;;

View File

@ -11,7 +11,9 @@
# /etc/nikki/profiles/<name>.yaml generated, what nikki runs
#
# Usage:
# mihomo-kit.sh setup first run: install + questions + build + start
# mihomo-kit.sh setup [--cli] first run: install, then settings in LuCI
# (--cli or no LuCI: questions here + build + start)
# mihomo-kit.sh configure <env> settings from an env file (LuCI form) -> write, build, start
# mihomo-kit.sh build [name...] profiles.d/<name>.env -> profiles/<name>.yaml (default: all)
# mihomo-kit.sh use <name> switch nikki to profiles/<name>.yaml and restart
# mihomo-kit.sh update download the latest kit (KIT_URL) and rebuild
@ -71,14 +73,61 @@ compute_tags() {
[ "$TS_EXIT" = 1 ] && TAGS="$TAGS ts_exit "
fi
fi
SUB_LIST="" i=0
for u in $SUBS; do
SUB_LIST="${SUB_LIST:+$SUB_LIST, }sub$i"
i=$((i + 1))
SUB_LIST=""
for _p in $SUB_PAIRS; do
SUB_LIST="${SUB_LIST:+$SUB_LIST, }${_p%%=*}"
done
export SUB_LIST
}
# Subscription ids (provider names, keys SUB_<ID>_*). A SUBS word is "url" or
# "name=url"; without a name the id comes from the domain:
# https://sub.kittyvpn.com/x -> kittyvpn, https://a.b.co.uk/ -> b
# Repeats get 2, 3, ... Same algorithm as subPairs() in web/engine.js.
sub_auto_id() {
_h=${1#*://}
_h=${_h%%[/?#]*}
_h=${_h##*@}
_h=$(printf '%s' "${_h%:*}" | tr 'A-Z' 'a-z')
case "$_h" in *.*) _h=${_h%.*} ;; esac
while :; do
case "$_h" in
*.co | *.com | *.net | *.org | *.gov | *.edu | *.ac) _h=${_h%.*} ;;
*) break ;;
esac
done
_h=$(printf '%s' "${_h##*.}" | sed 's/[^a-z0-9_]/_/g')
case "$_h" in
'') echo sub ;;
[0-9]*) echo "sub$_h" ;;
*) echo "$_h" ;;
esac
}
# SUBS -> SUB_PAIRS="id=url id=url ..."
sub_pairs() {
SUB_PAIRS="" _seen=" "
set -f
for _w in $SUBS; do
_n=${_w%%=*} _u=${_w#*=}
case "$_n" in "$_w" | '' | *[!A-Za-z0-9_-]*) _n=$(sub_auto_id "$_w") _u=$_w ;; esac
_n=$(printf '%s' "$_n" | tr 'A-Z-' 'a-z_')
_id=$_n _k=2
while case "$_seen" in *" $_id "*) true ;; *) false ;; esac; do
_id=$_n$_k _k=$((_k + 1))
done
_seen="$_seen$_id "
SUB_PAIRS="${SUB_PAIRS:+$SUB_PAIRS }$_id=$_u"
done
set +f
}
# sub_get <index> <id> <KEY>: SUB_<ID>_<KEY>, else the old SUB<index>_<KEY>
sub_get() {
_K=$(printf '%s' "$2" | tr 'a-z' 'A-Z')
eval "printf '%s' \"\${SUB_${_K}_$3:-\${SUB$1_$3:-}}\""
}
check_vars() {
[ -n "$SUBS" ] || die "SUBS is empty (subscription URLs)"
case "$TARGET" in router | mobile) ;; *) die "TARGET must be router or mobile" ;; esac
@ -89,12 +138,12 @@ check_vars() {
done
fi
i=0
for u in $SUBS; do
eval "_p=\${SUB${i}_PROXY:-} _hw=\${SUB${i}_HWID:-0}"
[ "$_p" = BOOT ] && [ "$BOOT" != 1 ] && die "SUB${i}_PROXY=BOOT but BOOT=0"
if [ "$_hw" = 1 ]; then
for _pr in $SUB_PAIRS; do
_id=${_pr%%=*}
[ "$(sub_get "$i" "$_id" PROXY)" = BOOT ] && [ "$BOOT" != 1 ] && die "subscription $_id: PROXY=BOOT but BOOT=0"
if [ "$(sub_get "$i" "$_id" HWID)" = 1 ]; then
for v in HWID_OS HWID_OS_VER HWID_MODEL HWID_ID; do
eval "[ -n \"\${$v}\" ]" || die "$v is empty (SUB${i}_HWID=1)"
eval "[ -n \"\${$v}\" ]" || die "$v is empty (subscription $_id has HWID=1)"
done
fi
i=$((i + 1))
@ -104,14 +153,16 @@ check_vars() {
# YAML double-quoted string body
yq() { printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'; }
# per-subscription variables for the .each templates: sub_vars <index> <url>
# SUB<i>_PROXY BOOT (default with BOOT=1) | DIRECT | any proxy/group | none
# SUB<i>_UA User-Agent (default mihomo, with HWID: HWID_UA)
# SUB<i>_HWID=1 send x-device-os / x-ver-os / x-device-model / x-hwid from HWID_*
# SUB<i>_HEADERS extra headers: "key=value; key2=value 2"
# per-subscription variables for the .each templates: sub_vars <index> <id> <url>
# (ID = id in upper case; the old SUB<index>_* keys still work)
# SUB_<ID>_PROXY BOOT (default with BOOT=1) | DIRECT | any proxy/group | none
# SUB_<ID>_UA User-Agent (default mihomo, with HWID: HWID_UA)
# SUB_<ID>_HWID=1 send x-device-os / x-ver-os / x-device-model / x-hwid from HWID_*
# SUB_<ID>_HEADERS extra headers: "key=value; key2=value 2"
sub_vars() {
SUB_NAME="sub$1" SUB_URL="$2"
eval "_p=\${SUB$1_PROXY:-} _ua=\${SUB$1_UA:-} _hw=\${SUB$1_HWID:-0} _h=\${SUB$1_HEADERS:-}"
SUB_NAME="$2" SUB_URL="$3"
_p=$(sub_get "$1" "$2" PROXY) _ua=$(sub_get "$1" "$2" UA) _hw=$(sub_get "$1" "$2" HWID)
_h=$(sub_get "$1" "$2" HEADERS)
[ -z "$_p" ] && [ "$BOOT" = 1 ] && _p=BOOT
[ "$_p" = none ] && _p=""
if [ "$_hw" = 1 ]; then
@ -208,8 +259,8 @@ render_section() {
fragment_active "${_name#*-}" || continue
if [ "$EACH" = 1 ]; then
i=0
for u in $SUBS; do
sub_vars "$i" "$u"
for _pr in $SUB_PAIRS; do
sub_vars "$i" "${_pr%%=*}" "${_pr#*=}"
_part=$(render_file "$f")
[ -n "$_part" ] && _out="${_out:+$_out
@ -230,6 +281,7 @@ render_section() {
render() {
set_defaults
sub_pairs
check_vars
compute_tags
export TARGET LOCATION GEOIP_URL GEOSITE_URL BOOT_SERVER BOOT_PORT BOOT_UUID BOOT_SNI \
@ -548,7 +600,7 @@ wizard() {
fi
echo "Подписки: по одной; пустой URL — конец." > "$TTY_OUT"
SUBS="" SUB_LINES="" _n=0 _any_hwid=0
SUBS="" _n=0 _any_hwid=0
while :; do
ask _u "sub$_n URL"
[ -n "$_u" ] || break
@ -558,14 +610,10 @@ wizard() {
else
_p=DIRECT
fi
[ "$_p" = BOOT ] || SUB_LINES="${SUB_LINES}SUB${_n}_PROXY=$(q "$_p")
"
eval "SUB${_n}_PROXY=\$_p"
yesno _hw " HWID-заголовки (x-hwid, x-device-os, ...; для подписок с лимитом устройств)" n
if [ "$_hw" = 1 ]; then
SUB_LINES="${SUB_LINES}SUB${_n}_HWID=1
"
_any_hwid=1
fi
eval "SUB${_n}_HWID=\$_hw"
[ "$_hw" = 1 ] && _any_hwid=1
_n=$((_n + 1))
done
[ -n "$SUBS" ] || die "нужна хотя бы одна подписка"
@ -599,15 +647,70 @@ wizard() {
ask TS_DOMAINS " split-DNS домены тейлнета кроме *.ts.net (через пробел)" ""
fi
write_config
}
# keys write_config owns; any other KEY=value lines (added by hand) are kept
COMMON_KEYS='TARGET|SUBS|SUB[0-9]*_[A-Z0-9_]*(PROXY|HWID)|HWID_[A-Z_]+|BOOT|BOOT_[A-Z]+|TORRENT|RU_IPS|OPENVPN|TAILSCALE|TS_HOSTNAME|TS_DOMAINS'
VPN_KEYS='VPN_USERNAME|VPN_PASSWORD|TOTP_SECRET'
# other_keys <file> <keys-regex>
other_keys() {
grep -E '^[A-Za-z_][A-Za-z0-9_]*=' "$1" 2>/dev/null | grep -vE "^($2)="
}
# hand-added keys of common.env; the old SUB<index>_* ones are renamed to
# SUB_<ID>_* by the subscription order of that file
common_other_keys() {
_f=$PROFILES_D/common.env
[ -f "$_f" ] || return 0
_old_ids=$(
SUBS=
. "$_f"
sub_pairs
for _p in $SUB_PAIRS; do echo "${_p%%=*}"; done
)
other_keys "$_f" "$COMMON_KEYS" | while IFS= read -r _l; do
_n=${_l%%_*}
_n=${_n#SUB}
case "$_l" in
SUB[0-9]*_*)
case "$_n" in
'' | *[!0-9]*) ;;
*)
_id=$(echo "$_old_ids" | sed -n "$((_n + 1))p")
[ -n "$_id" ] && _l="SUB_$(echo "$_id" | tr 'a-z' 'A-Z')_${_l#*_}"
;;
esac
;;
esac
echo "$_l"
done
}
# common.env (+ bmstu.env) from the variables the wizard / configure set;
# per-subscription values come as SUB<index>_PROXY/HWID (index in SUBS)
write_config() {
umask 077
_any_hwid=0
_others=$(common_other_keys)
sub_pairs
{
echo "# written by mihomo-kit.sh setup; edit and run: mihomo-kit.sh build"
echo "# written by mihomo-kit.sh (setup / LuCI); edit and run: mihomo-kit.sh build"
echo "TARGET=router"
echo "SUBS=$(q "$SUBS")"
printf '%s' "$SUB_LINES"
_i=0
for _pr in $SUB_PAIRS; do
_K=$(echo "${_pr%%=*}" | tr 'a-z' 'A-Z')
_p=$(sub_get "$_i" "${_pr%%=*}" PROXY) _hw=$(sub_get "$_i" "${_pr%%=*}" HWID)
[ "$BOOT" = 1 ] || [ "$_p" != BOOT ] || _p=DIRECT
[ -n "$_p" ] && [ "$_p" != BOOT ] && echo "SUB_${_K}_PROXY=$(q "$_p")"
[ "$_hw" = 1 ] && echo "SUB_${_K}_HWID=1" && _any_hwid=1
_i=$((_i + 1))
done
if [ "$_any_hwid" = 1 ]; then
for v in HWID_UA HWID_OS HWID_OS_VER HWID_MODEL HWID_ID; do
eval "echo \"$v=\$(q \"\$$v\")\""
eval "echo \"$v=\$(q \"\${$v:-}\")\""
done
fi
echo "BOOT=$BOOT"
@ -621,15 +724,18 @@ wizard() {
echo "OPENVPN=$OPENVPN"
echo "TAILSCALE=$TAILSCALE"
[ "$TAILSCALE" = 1 ] && echo "TS_HOSTNAME=$(q "$TS_HOSTNAME")" && echo "TS_DOMAINS=$(q "$TS_DOMAINS")"
[ -n "$_others" ] && echo "$_others"
true
} > "$PROFILES_D/common.env"
} > "$PROFILES_D/common.env.tmp" && mv "$PROFILES_D/common.env.tmp" "$PROFILES_D/common.env"
if [ "$OPENVPN" = 1 ]; then
{
echo "# written by mihomo-kit.sh setup"
echo "# written by mihomo-kit.sh (setup / LuCI)"
echo "VPN_USERNAME=$(q "$VPN_USERNAME")"
echo "VPN_PASSWORD=$(q "$VPN_PASSWORD")"
echo "TOTP_SECRET=$(q "$TOTP_SECRET")"
} > "$NIKKI_DIR/bmstu.env"
other_keys "$NIKKI_DIR/bmstu.env" "$VPN_KEYS"
true
} > "$NIKKI_DIR/bmstu.env.tmp" && mv "$NIKKI_DIR/bmstu.env.tmp" "$NIKKI_DIR/bmstu.env"
fi
for f in "$KIT_DIR"/presets/*.env; do
[ -f "$PROFILES_D/${f##*/}" ] || cp "$f" "$PROFILES_D/"
@ -637,9 +743,75 @@ wizard() {
umask 022
}
# "<id> <SUBS word>" per subscription of $SUBS (for the LuCI form)
cmd_sub_ids() {
SUBS=${SUBS:-}
sub_pairs
set -f
# shellcheck disable=SC2086
_ws=$(printf '%s ' $SUBS)
for _pr in $SUB_PAIRS; do
_w=${_ws%% *}
_ws=${_ws#"$_w"}
_ws=${_ws# }
echo "${_pr%%=*} $_w"
done
}
# Settings from the LuCI form: <env> holds BOOT_LINK, SUBS, SUB<i>_PROXY/HWID,
# HWID_*, TORRENT, RU_IPS, OPENVPN, VPN_* (empty secrets = keep), TAILSCALE, TS_*.
# Validates, writes common.env/bmstu.env, builds and restarts the current profile.
cmd_configure() {
[ -f "${1:-}" ] || die "usage: configure <env>"
# saved OpenVPN secrets stay unless the form sends new ones
[ -f "$NIKKI_DIR/bmstu.env" ] && . "$NIKKI_DIR/bmstu.env"
. "$1"
rm -f "$1"
BOOT=0
if [ -n "${BOOT_LINK:-}" ]; then
parse_vless "$BOOT_LINK"
[ -n "$BOOT_SERVER" ] && [ -n "$BOOT_PBK" ] || die "не разобрал vless-ссылку: нужны host, pbk, sid"
BOOT=1
fi
[ -n "${SUBS:-}" ] || die "нужна хотя бы одна подписка"
if [ "$OPENVPN" = 1 ]; then
[ -f "$NIKKI_DIR/bmstu.ovpn" ] || die "OpenVPN: нет $NIKKI_DIR/bmstu.ovpn"
[ -n "${VPN_USERNAME:-}" ] && [ -n "${VPN_PASSWORD:-}" ] && [ -n "${TOTP_SECRET:-}" ] ||
die "OpenVPN: нужны логин, пароль и TOTP-секрет"
fi
write_config
log "saved $PROFILES_D/common.env"
cmd_build
if [ "$OPENVPN" = 1 ]; then
enable_otp_cron
elif grep -q "bmstu-otp.sh check" /etc/crontabs/root 2>/dev/null; then
sed -i '/bmstu-otp.sh check/d' /etc/crontabs/root
/etc/init.d/cron restart
log "removed bmstu-otp.sh check from cron"
fi
cur=$(uci -q get nikki.config.profile)
cur=${cur#file:}
cur=${cur%.yaml}
[ -f "$PROFILES_D/$cur.env" ] || cur=home
cmd_use "$cur"
[ "$TAILSCALE" = 1 ] && cmd_ts_login
true
}
# install only; settings in LuCI (or questions here with --cli / without LuCI)
cmd_setup() {
[ -r "$TTY_IN" ] || die "setup needs a terminal (run it over ssh)"
cmd_install
if [ "${1:-}" != --cli ] && [ -d /www/luci-static/resources ]; then
_ip=$(uci -q get network.lan.ipaddr)
_ip=${_ip%%/*}
log ""
log "Установлено. Настройка — в браузере:"
log " http://${_ip:-<роутер>}/cgi-bin/luci/admin/services/mihomo-kit"
log " (LuCI → Службы → mihomo-kit; если пункта нет — выйди и войди снова)"
log "Вопросы в терминале вместо LuCI: mihomo-kit.sh setup --cli"
return 0
fi
[ -r "$TTY_IN" ] || die "setup --cli needs a terminal (run it over ssh)"
_redo=1
if [ -f "$PROFILES_D/common.env" ]; then
yesno _redo "$PROFILES_D/common.env уже есть. Ответить на вопросы заново" n
@ -693,11 +865,13 @@ case "${1:-}" in
render) shift; cmd_render "$@" ;;
build) shift; cmd_build "$@" ;;
use) shift; cmd_use "$@" ;;
setup) cmd_setup ;;
setup) shift; cmd_setup "$@" ;;
configure) shift; cmd_configure "$@" ;;
sub-ids) cmd_sub_ids ;;
update) cmd_update ;;
post-update) cmd_post_update ;;
install) cmd_install ;;
fix) cmd_fix ;;
ts-login) shift; cmd_ts_login "$@" ;;
*) sed -n '2,24p' "$SELF" >&2; exit 2 ;;
*) sed -n '2,26p' "$SELF" >&2; exit 2 ;;
esac

View File

@ -10,16 +10,18 @@ TARGET=router
# home: OpenVPN/Tailscale go direct; street: OpenVPN goes through OVPN-EXIT (RU node)
LOCATION=home
# subscription URLs, space separated -> sub0, sub1, ...
# subscription URLs, space separated. Provider name = id from the domain
# (https://sub.kittyvpn.com/x -> kittyvpn; repeats -> kittyvpn2), or "name=url"
SUBS="https://sub.example.com/sub/xxxx"
# per subscription (N = 0, 1, ... as in SUBS), all optional:
#SUB1_PROXY=DIRECT # fetch through: BOOT (default with BOOT=1) | DIRECT | any proxy/group | none
#SUB1_UA="v2rayN/9.99" # User-Agent, default mihomo (with HWID: HWID_UA)
#SUB1_HWID=1 # send the HWID_* headers below (device-limited subscriptions)
#SUB1_HEADERS="x-foo=bar; x-baz=two words" # any extra headers
# per subscription, ID = its id in upper case (- -> _), all optional:
#SUB_EXAMPLE_PROXY=DIRECT # fetch through: BOOT (default with BOOT=1) | DIRECT | any proxy/group | none
#SUB_EXAMPLE_UA="v2rayN/9.99" # User-Agent, default mihomo (with HWID: HWID_UA)
#SUB_EXAMPLE_HWID=1 # send the HWID_* headers below (device-limited subscriptions)
#SUB_EXAMPLE_HEADERS="x-foo=bar; x-baz=two words" # any extra headers
# (old index keys SUB0_*, SUB1_* ... still work)
# HWID headers, shared by all subscriptions with SUBn_HWID=1
# HWID headers, shared by all subscriptions with SUB_<ID>_HWID=1
#HWID_UA="v2rayN/9.99"
#HWID_OS=OpenWrt # x-device-os
#HWID_OS_VER=24.10.3 # x-ver-os

9
tests/fixtures/router-ids.env vendored Normal file
View File

@ -0,0 +1,9 @@
SUBS="kitty=https://a.example.com/x https://sub.vpn-host.co.uk/y?t=1 https://sub.vpn-host.co.uk/z https://1.2.3.4:8443/s"
SUB_KITTY_HWID=1
SUB_VPN_HOST_PROXY=DIRECT
SUB_VPN_HOST2_UA='ua two'
SUB_SUB3_HEADERS="x-a=1"
HWID_OS=OpenWrt
HWID_OS_VER=24.10.3
HWID_MODEL="Huasifei WH3000 Pro"
HWID_ID=123

View File

@ -13,7 +13,7 @@ for (const dir of fs.readdirSync(tplDir)) {
for (const f of fs.readdirSync(full)) templates[`${dir}/${f}`] = fs.readFileSync(path.join(full, f), "utf8");
}
const vars = {};
for (const [k, val] of Object.entries(process.env)) if (k in DEFAULTS || /^SUB[0-9]+_/.test(k)) vars[k] = val;
for (const [k, val] of Object.entries(process.env)) if (k in DEFAULTS || /^SUB[0-9]*_/.test(k)) vars[k] = val;
try {
process.stdout.write(render(templates, vars));
} catch (e) {

View File

@ -39,6 +39,38 @@
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}`] || "";
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");
@ -48,11 +80,11 @@
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") {
subPairs(v.SUBS).forEach(({ id }, i) => {
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 (SUB${i}_HWID=1)`);
if (!v[k]) throw new Error(`${k} is empty (subscription ${id} has HWID=1)`);
}
}
});
@ -62,12 +94,12 @@
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" : "");
function subVars(v, i, id, url) {
let proxy = subGet(v, i, id, "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") {
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 : "");
}
@ -78,7 +110,7 @@
return `${key}: ["${yq(val)}"]`;
});
return {
SUB_NAME: `sub${i}`, SUB_URL: url, SUB_PROXY: proxy,
SUB_NAME: id, SUB_URL: url, SUB_PROXY: proxy,
SUB_UA: yq(ua || "mihomo"), SUB_HEADERS: headers.join("\n"),
};
}
@ -143,8 +175,8 @@
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 subs = subPairs(v.SUBS);
v.SUB_LIST = subs.map((s) => s.id).join(", ");
const sections = [];
for (const [dir, header] of SECTIONS) {
@ -157,8 +189,8 @@
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);
subs.forEach((s, i) => {
const part = renderText(templates[path], { ...v, ...subVars(v, i, s.id, s.url) }, tags);
if (part) parts.push(part);
});
} else {
@ -172,7 +204,7 @@
return sections.join("\n\n") + "\n";
}
const api = { render, DEFAULTS };
const api = { render, subPairs, DEFAULTS };
if (typeof module !== "undefined" && module.exports) module.exports = api;
else root.MihomoKit = api;
})(typeof window !== "undefined" ? window : globalThis);

View File

@ -227,6 +227,38 @@
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}`] || "";
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");
@ -236,11 +268,11 @@
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") {
subPairs(v.SUBS).forEach(({ id }, i) => {
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 (SUB${i}_HWID=1)`);
if (!v[k]) throw new Error(`${k} is empty (subscription ${id} has HWID=1)`);
}
}
});
@ -250,12 +282,12 @@
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" : "");
function subVars(v, i, id, url) {
let proxy = subGet(v, i, id, "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") {
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 : "");
}
@ -266,7 +298,7 @@
return `${key}: ["${yq(val)}"]`;
});
return {
SUB_NAME: `sub${i}`, SUB_URL: url, SUB_PROXY: proxy,
SUB_NAME: id, SUB_URL: url, SUB_PROXY: proxy,
SUB_UA: yq(ua || "mihomo"), SUB_HEADERS: headers.join("\n"),
};
}
@ -331,8 +363,8 @@
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 subs = subPairs(v.SUBS);
v.SUB_LIST = subs.map((s) => s.id).join(", ");
const sections = [];
for (const [dir, header] of SECTIONS) {
@ -345,8 +377,8 @@
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);
subs.forEach((s, i) => {
const part = renderText(templates[path], { ...v, ...subVars(v, i, s.id, s.url) }, tags);
if (part) parts.push(part);
});
} else {
@ -360,7 +392,7 @@
return sections.join("\n\n") + "\n";
}
const api = { render, DEFAULTS };
const api = { render, subPairs, DEFAULTS };
if (typeof module !== "undefined" && module.exports) module.exports = api;
else root.MihomoKit = api;
})(typeof window !== "undefined" ? window : globalThis);
@ -404,7 +436,7 @@ function addSub() {
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">
<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</option><option>DIRECT</option></select></label>
@ -423,18 +455,18 @@ function addSub() {
}
$("add-sub").addEventListener("click", addSub);
// rows with a URL, in order -> sub0, sub1, ...
// rows with a URL, in order; id = provider name from the domain (or "name=url")
function readSubs() {
const rows = [...document.querySelectorAll("#subs .sub")];
let n = 0;
return rows.map((row) => {
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}]`);
const url = get("url").value.trim();
row.querySelector(".name").textContent = url ? `sub${n}` : "";
if (!url) return null;
return { i: n++, url, proxy: get("proxy").value, hwid: get("hwid").checked,
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() };
}).filter(Boolean);
});
}
function radio(name) { return form.querySelector(`input[name=${name}]:checked`).value; }
@ -456,10 +488,11 @@ function readVars() {
v.SUBS = subs.map((x) => x.url).join(" ");
v._HWID = subs.some((x) => x.hwid);
for (const x of subs) {
if (x.proxy) v[`SUB${x.i}_PROXY`] = x.proxy;
if (x.hwid) v[`SUB${x.i}_HWID`] = "1";
if (x.ua) v[`SUB${x.i}_UA`] = x.ua;
if (x.headers) v[`SUB${x.i}_HEADERS`] = x.headers;
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;
@ -469,7 +502,7 @@ const q = (s) => "'" + String(s).replace(/'/g, "'\\''") + "'";
function envFile(v) {
const keys = ["TARGET", "LOCATION", "SUBS"];
keys.push(...Object.keys(v).filter((k) => /^SUB[0-9]+_/.test(k)));
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");
@ -504,8 +537,8 @@ function steps(v) {
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 === "street" ? " На улице выбери RU-ноду в группе OVPN-EXIT в дашборде." : "");
if (v.TAILSCALE === "1") s.push("", "Tailscale: открой любой 100.x адрес, ссылка для входа появится в логе:",
" grep 'To start' /var/log/nikki/core.log",
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");
}

View File

@ -203,7 +203,7 @@ function addSub() {
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">
<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</option><option>DIRECT</option></select></label>
@ -222,18 +222,18 @@ function addSub() {
}
$("add-sub").addEventListener("click", addSub);
// rows with a URL, in order -> sub0, sub1, ...
// rows with a URL, in order; id = provider name from the domain (or "name=url")
function readSubs() {
const rows = [...document.querySelectorAll("#subs .sub")];
let n = 0;
return rows.map((row) => {
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}]`);
const url = get("url").value.trim();
row.querySelector(".name").textContent = url ? `sub${n}` : "";
if (!url) return null;
return { i: n++, url, proxy: get("proxy").value, hwid: get("hwid").checked,
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() };
}).filter(Boolean);
});
}
function radio(name) { return form.querySelector(`input[name=${name}]:checked`).value; }
@ -255,10 +255,11 @@ function readVars() {
v.SUBS = subs.map((x) => x.url).join(" ");
v._HWID = subs.some((x) => x.hwid);
for (const x of subs) {
if (x.proxy) v[`SUB${x.i}_PROXY`] = x.proxy;
if (x.hwid) v[`SUB${x.i}_HWID`] = "1";
if (x.ua) v[`SUB${x.i}_UA`] = x.ua;
if (x.headers) v[`SUB${x.i}_HEADERS`] = x.headers;
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;
@ -268,7 +269,7 @@ const q = (s) => "'" + String(s).replace(/'/g, "'\\''") + "'";
function envFile(v) {
const keys = ["TARGET", "LOCATION", "SUBS"];
keys.push(...Object.keys(v).filter((k) => /^SUB[0-9]+_/.test(k)));
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");
@ -303,8 +304,8 @@ function steps(v) {
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 === "street" ? " На улице выбери RU-ноду в группе OVPN-EXIT в дашборде." : "");
if (v.TAILSCALE === "1") s.push("", "Tailscale: открой любой 100.x адрес, ссылка для входа появится в логе:",
" grep 'To start' /var/log/nikki/core.log",
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");
}