mihomo-kit/luci/mihomo-kit.js

1220 lines
68 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.

'use strict';
'require view';
'require rpc';
'require ui';
'require dom';
// Backend: /usr/libexec/rpcd/mihomo-kit (luci/rpcd.sh in the kit).
// Commands run as one background job; the page polls its output.
var callStatus = rpc.declare({ object: 'mihomo-kit', method: 'status', expect: { '': {} } });
// slow calls (delay tests, the git server) go as their own requests: LuCI batches calls
// made at the same moment into one request, and uhttpd runs a batch one call after another
var callOvpnStatus = rpc.declare({ object: 'mihomo-kit', method: 'ovpn_status', nobatch: true, expect: { '': {} } });
var callOvpnProbe = rpc.declare({ object: 'mihomo-kit', method: 'ovpn_probe', nobatch: true, 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 callCsqttStatus = rpc.declare({ object: 'mihomo-kit', method: 'csqtt_status', nobatch: true, expect: { '': {} } });
var callTsCheck = rpc.declare({ object: 'mihomo-kit', method: 'ts_check', nobatch: true, expect: { '': {} } });
var callUpdateCheck = rpc.declare({ object: 'mihomo-kit', method: 'update_check', nobatch: true, expect: { '': {} } });
var callExport = rpc.declare({ object: 'mihomo-kit', method: 'export', expect: { '': {} } });
var callImport = rpc.declare({ object: 'mihomo-kit', method: 'import', params: [ 'data', 'keep_local' ], 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); });
}
function row(title, value) {
return E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td left', 'width': '33%' }, title),
E('td', { 'class': 'td left' }, value)
]);
}
function section(title, children) {
return E('div', { 'class': 'cbi-section' }, [ E('h3', title) ].concat(children));
}
// OpenVPN: what decides the tunnel now and what happens next, from
// bmstu-otp.sh state (via ovpn_status) -> { now, next, pending }
function ovpnMode(o) {
var at = function(hm, day) {
return (day == 'today' ? 'сегодня' : day == 'tomorrow' ? 'завтра' : day) + ' в ' + hm;
};
var r = {};
switch (o.mode) {
case 'timer':
r.now = 'включён таймером до ' + o.until_hm +
(o.until_day == 'today' ? '' : o.until_day == 'tomorrow' ? ' завтра' : ' ' + o.until_day);
if (o.after == 'off')
r.next = 'потом выключится: ' + (o.why == 'manual'
? 'снова действует ручное «Выключить»'
: 'это вне расписания' + (o.next && o.next_to == 'on' ? ', включится ' + at(o.next_hm, o.next_day) : ''));
else
r.next = 'потом останется включённым: ' + (o.why == 'always' ? 'расписание выключено' : 'это внутри расписания');
break;
case 'manual':
r.now = 'выключен вручную';
r.next = 'сам не включится: «Включить», «Включить расписание» или «на 1 ч»';
break;
case 'schedule':
r.now = o.want ? 'включён по расписанию' : 'выключен по расписанию';
if (o.next)
r.next = (o.next_to == 'off' ? 'выключится ' : 'включится ') + at(o.next_hm, o.next_day);
break;
case 'always':
r.now = 'включён постоянно';
r.next = 'сам не выключится: расписание выключено';
break;
default:
r.now = 'неизвестно';
}
if (o.want && o.tunnel == 'down')
r.pending = 'туннель ещё закрыт, cron поднимет в течение минуты';
else if (!o.want && o.tunnel == 'up')
r.pending = 'туннель ещё открыт, cron закроет в течение минуты';
return r;
}
// 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' }, [].concat(el, desc ? [ E('div', { 'class': 'cbi-value-description' }, desc) ] : []))
]);
}
// qrcode-generator (luci/qrcode.js, installed with the page): a global "qrcode"
function loadQr() {
if (window.qrcode && window.qrcodeVersion === '__MIHOMO_KIT_ASSETS__')
return Promise.resolve(window.qrcode);
return new Promise(function(resolve, reject) {
var s = document.createElement('script');
s.src = L.resource('mihomo-kit/qrcode.js') + '?v=__MIHOMO_KIT_ASSETS__';
s.onload = function() { window.qrcodeVersion = '__MIHOMO_KIT_ASSETS__'; resolve(window.qrcode); };
s.onerror = function() { reject(new Error('qrcode.js not loaded')); };
document.head.appendChild(s);
});
}
// own servers: luci/servers.js (links and YAML -> proxies), a global "mkServers"
function loadServers() {
if (window.mkServers && window.mkServersVersion === '__MIHOMO_KIT_ASSETS__')
return Promise.resolve(window.mkServers);
return new Promise(function(resolve, reject) {
var s = document.createElement('script');
s.src = L.resource('mihomo-kit/servers.js') + '?v=__MIHOMO_KIT_ASSETS__';
s.onload = function() { window.mkServersVersion = '__MIHOMO_KIT_ASSETS__'; resolve(window.mkServers); };
s.onerror = function() { reject(new Error('servers.js not loaded')); };
document.head.appendChild(s);
});
}
// clipboard: navigator.clipboard needs https, LuCI is usually plain http;
// then execCommand('copy'), and if that fails too, show the text to copy by hand
function copyText(text) {
if (navigator.clipboard && window.isSecureContext)
return navigator.clipboard.writeText(text).then(function() { return true; });
var ta = E('textarea', { 'style': 'position:fixed;top:0;left:0;opacity:0' }, text);
document.body.appendChild(ta);
ta.select();
var ok = false;
try { ok = document.execCommand('copy'); } catch (e) {}
document.body.removeChild(ta);
return Promise.resolve(ok);
}
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,
handleReset: null,
load: function() {
return Promise.all([ callStatus(), callJob() ]);
},
button: function(label, style, cmd, arg, confirmText) {
var btn = E('button', {
'class': 'btn cbi-button cbi-button-' + style,
'click': ui.createHandlerFn(this, function() {
if (confirmText && !window.confirm(confirmText))
return;
return this.run(cmd, typeof arg == 'function' ? arg() : arg);
})
}, label);
btn.disabled = this.busy;
this.buttons.push(btn);
return btn;
},
renderBody: function(st) {
var sections = [];
this.buttons = [];
if (!st.configured)
sections.push(E('div', { 'class': 'alert-message warning' },
'Kit ещё не настроен: заполни «Настройка» ниже и нажми «Сохранить и применить».'));
var select = E('select', { 'class': 'cbi-input-select' }, (st.profiles || []).map(function(p) {
return E('option', { 'value': p }, p);
}));
select.value = st.profile;
// mihomo serves its external-ui at /ui; metacubexd/zashboard take the API from the query
var updState = E('em', 'проверяю обновления…');
callUpdateCheck().then(function(u) {
if (u.error)
return dom.content(updState, '— не удалось проверить обновления: ' + u.error);
var link = function(href, text) { return E('a', { 'href': href, 'target': '_blank', 'rel': 'noreferrer' }, text); };
if (u.installed && u.installed.indexOf(u.latest) == 0)
return dom.content(updState, '— актуальная');
dom.content(updState, [ '— ', E('strong', 'есть обновление: '), link(u.commit, u.latest), ' ' + (u.message || '') ]
.concat(u.compare ? [ ' (', link(u.compare, 'что изменилось'), ')' ] : []));
}).catch(function(e) { dom.content(updState, '— не удалось проверить обновления: ' + e); });
var host = window.location.hostname;
var dash = 'http://' + host + ':' + st.api_port + '/ui/?hostname=' + encodeURIComponent(host) +
'&port=' + st.api_port + (st.api_secret ? '&secret=' + encodeURIComponent(st.api_secret) : '');
sections.push(section('Состояние', [
E('table', { 'class': 'table' }, [
row('nikki', st.running ? [ 'работает — ',
E('a', { 'href': dash, 'target': '_blank', 'rel': 'noreferrer' }, 'открыть дашборд') ]
: E('strong', 'остановлен')),
row('Ядро mihomo', [ st.core_version || 'не найдено' ]
.concat(/-ts\d+$/.test(st.core_version || '') ? [ ' — сборка kit: официальное ядро с правками kit' ] : [])
.concat(st.core && st.core.ok == '0'
? [ ' — ', E('strong', { 'style': 'color:#c00' }, 'выбрано ' +
(st.core.wanted == 'stock' ? 'ядро из прошивки' : st.core.wanted)),
': нажми «Починить» в «Обслуживании»' ]
: [])),
row('Память mihomo', st.mem_kb ? [ Math.round(st.mem_kb / 1024) + ' МБ (RSS)',
st.lite ? ' — облегчённый режим' : '' ] : '—'),
row('Версия kit', [ st.kit_version || 'неизвестна (появится после «Обновить kit»)', ' ', updState ]),
row('Профиль', [ select, ' ',
this.button('Включить', 'apply', 'use', function() { return select.value; }) ])
])
]));
if (st.openvpn) {
var ovpnState = E('span', '—');
var probeRes = E('span');
var otp = E('span', '—');
var modeNow = E('span', '—');
var modeNext = E('span', '—');
var schedInfo = E('span', '—');
var schedStart = E('input', { 'type': 'time', 'value': '09:00' });
var schedEnd = E('input', { 'type': 'time', 'value': '17:00' });
var dayNames = [ 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс' ];
// at least one day stays checked
var schedDays = dayNames.map(function() {
return E('input', { 'type': 'checkbox', 'checked': true, 'change': function(ev) {
if (!schedDays.some(function(c) { return c.checked; })) ev.target.checked = true;
} });
});
var daysText = function(d) {
return d == '1234567' || !d ? 'каждый день' : d == '12345' ? 'по будням' : d == '67' ? 'по выходным'
: d.split('').map(function(x) { return dayNames[x - 1]; }).join(', ');
};
var schedFilled = false;
var desc = function(t) { return E('span', { 'class': 'cbi-value-description' }, t); };
// the state comes from the kit core through the API: no traffic in the tunnel
var ovpnCheck = function() {
dom.content(ovpnState, E('em', 'обновляю…'));
return callOvpnStatus().then(function(o) {
var since = o.up_hm + (o.up_day == 'today' ? '' : o.up_day == 'tomorrow' ? ' завтра' : ' (' + o.up_day + ')');
dom.content(ovpnState, {
closed: 'закрыт',
up: E('strong', { 'style': 'color:green' }, 'подключён с ' + since),
connecting: [ E('strong', { 'style': 'color:#c60' }, 'подключается'),
o.err ? desc(' — ' + o.err) : '' ],
rejected: [ E('strong', { 'style': 'color:#c00' }, 'сервер не принял сессию'),
desc(o.retry_hm ? ' — cron возьмёт новый OTP после паузы, в ' + o.retry_hm
: ' — cron возьмёт новый OTP в течение минуты') ],
held: [ E('strong', { 'style': 'color:#c60' }, {
kick: 'сервер отключил сессию',
drop: 'туннель оборвался',
failed: 'не подключился'
}[o.retry_why] || 'пауза'),
desc(' — следующая попытка в ' + o.retry_hm + ' (без быстрых переподключений)' +
(o.err ? '; ' + o.err : '')) ],
unknown: [ E('strong', 'ядро не сообщает состояние'),
desc(' — с этим ядром cron проверяет туннель запросом к сайту раз в ~10 минут, ' +
'и маскировка под Connect неполная. Нужно ядро kit («Обслуживание» → ядро).') ]
}[o.link] || o.link || '—');
dom.content(otp, o.otp ? o.otp + ' (ещё ' + o.otp_left + ' с)' : '—');
var m = ovpnMode(o);
dom.content(modeNow, [ E('strong', m.now) ].concat(m.pending
? [ ' — ', E('span', { 'class': 'cbi-value-description' }, m.pending) ] : []));
dom.content(modeNext, m.next || '—');
dom.content(schedInfo, o.sched_start
? (o.sched_active ? 'включено: ' : 'выключено (часы сохранены): ') + daysText(o.sched_days) + ' с ' + o.sched_start + ' до ' + o.sched_end + ' (МСК), границы сдвигаются до ±' + o.jitter +
' мин' + (o.win ? '; сегодня ' + o.win.replace('-', '–') : '')
: 'выключено');
// one of each pair, by the state: timer running or not, schedule on or not
var timer = o.mode == 'timer';
timerStart.style.display = timer ? 'none' : '';
timerMore.style.display = timerStop.style.display = timer ? '' : 'none';
timerMore.disabled = timer && o.until - Date.now() / 1000 > o.timer_max * 60 - 120;
schedStartBtn.style.display = o.sched_active ? 'none' : '';
schedStopBtn.style.display = o.sched_active ? '' : 'none';
if (!schedFilled) {
if (o.sched_start) schedStart.value = o.sched_start;
if (o.sched_end) schedEnd.value = o.sched_end;
if (o.sched_days)
schedDays.forEach(function(c, i) { c.checked = o.sched_days.indexOf(String(i + 1)) >= 0; });
schedFilled = true;
}
}).catch(function(e) { dom.content(ovpnState, String(e)); });
};
var timerStart = this.button('Включить на 1 ч', 'action', 'ovpn-for', '60');
var timerMore = this.button('+1 ч', 'action', 'ovpn-extend', '60');
var timerStop = this.button('Остановить таймер', 'negative', 'ovpn-stop');
timerMore.style.display = timerStop.style.display = 'none';
var schedStartBtn = this.button('Включить расписание', 'positive', 'ovpn-sched', 'on');
var schedStopBtn = this.button('Выключить расписание', 'negative', 'ovpn-sched', 'off',
'Выключить расписание? Туннель выключится и сам не включится, пока не нажмёшь «Включить» или «Включить расписание».');
schedStopBtn.style.display = 'none';
ovpnCheck();
sections.push(section('OpenVPN', [
E('table', { 'class': 'table' }, [
row('Состояние', [ ovpnState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action',
'click': ui.createHandlerFn(this, ovpnCheck) }, 'Обновить') ]),
row('Проверка сайта', [ E('button', { 'class': 'btn cbi-button cbi-button-action',
'click': ui.createHandlerFn(this, function() {
dom.content(probeRes, E('em', 'открываю…'));
return callOvpnProbe().then(function(r) {
dom.content(probeRes, [ r.state == 'up'
? E('strong', { 'style': 'color:green' }, 'открывается, ' + r.delay + ' мс')
: [ E('strong', { 'style': 'color:#c00' }, 'не открывается'), ' ' + (r.message || '') ],
desc(' — ' + (r.url || '')) ]);
}).catch(function(e) { dom.content(probeRes, String(e)); });
}) }, 'Проверить'), ' ', probeRes,
E('div', { 'class': 'cbi-value-description' },
'Открывает адрес проверки через туннель. Только по кнопке: сайт видит такой запрос в логах, ' +
'а сам Connect их не делает. Адрес лучше взять из тех, что и так открываешь в браузере.') ]),
row('OTP сейчас', otp),
row('Сейчас', modeNow),
row('Дальше', modeNext),
row('Расписание', schedInfo)
]),
E('div', { 'class': 'cbi-page-actions' }, [
this.button('Включить', 'positive', 'ovpn-on', null,
'Включить постоянно? Расписание и таймер выключатся.'), ' ',
this.button('Выключить', 'negative', 'ovpn-off', null,
'Закрыть туннель и держать выключенным, пока не нажмёшь «Включить» или «Включить расписание»? ' +
'Расписание и таймер выключатся. ' +
'С ядром kit сессия на сервере освобождается сразу, с другим ядром — через ~5 минут.'), ' ',
schedStartBtn, schedStopBtn, ' ',
timerStart, timerMore, ' ', timerStop, ' ',
this.button('Переподключить', 'action', 'ovpn-refresh')
]),
field('Часы расписания (MSK)', [ schedStart, ' – ', schedEnd, ' ',
E('span', { 'style': 'white-space:nowrap' }, schedDays.reduce(function(a, c, i) {
return a.concat([ ' ', E('label', [ c, ' ', dayNames[i] ]) ]);
}, [])), ' ',
this.button('Сохранить', 'action', 'ovpn-sched', function() {
var d = schedDays.reduce(function(a, c, i) { return c.checked ? a + (i + 1) : a; }, '');
return schedStart.value + ' ' + schedEnd.value + ' ' + d;
}) ],
'«Сохранить» только запоминает часы и дни, включает их «Включить расписание». ' +
'Режим один из трёх: «Включить» — постоянно, «Выключить» — выключен, «Включить расписание» — ' +
'только в эти часы и в отмеченные дни (окно через полночь относится ко дню, в который началось). ' +
'Выключенное расписание туннель не включает. Таймер («на 1 ч», «+1 ч», до 12 ч вперёд) поднимает туннель ' +
'поверх любого режима, а по окончании или «Остановить таймер» возвращает режим.')
]));
}
if (st.csqtt) {
var cqState = E('span', '—');
var cqUplink = E('span', '—');
var cqInfo = E('span', '—');
var cqCheck = function() {
dom.content(cqState, E('em', 'обновляю…'));
return callCsqttStatus().then(function(c) {
dom.content(cqState, [ {
up: E('strong', { 'style': 'color:green' }, 'подключён' + (c.active ? ' (' + c.active + ')' : '')),
connecting: E('strong', { 'style': 'color:#c60' }, 'подключается' + (c.stage ? ' (' + c.stage + ')' : '')),
stopped: E('strong', c.enabled ? 'остановлен' : 'выключен')
}[c.link] || c.link || '—' ]
.concat(c.captcha ? [ ' — ', E('strong', { 'style': 'color:#c00' }, 'капча: ' + c.captcha +
' (star-panel-csqtt → CAPTCHA)') ] : [])
.concat(c.err ? [ E('div', { 'class': 'cbi-value-description' }, 'последняя ошибка: ' + c.err +
(/authorization failed/i.test(c.err) ? ' — нужен новый VK-токен' : '')) ] : []));
dom.content(cqUplink, c.uplink == 'CSQTT'
? E('strong', 'CSQTT — ноды подключаются через туннель')
: c.uplink == 'DIRECT' ? 'DIRECT — как без CSQTT' : (c.uplink || 'mihomo не отвечает'));
dom.content(cqInfo, c.stats || '—');
}).catch(function(e) { dom.content(cqState, String(e)); });
};
if (st.csqtt_installed)
cqCheck();
sections.push(section('CSQTT', st.csqtt_installed ? [
E('table', { 'class': 'table' }, [
row('Туннель', [ cqState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action',
'click': ui.createHandlerFn(this, cqCheck) }, 'Обновить') ]),
row('UPLINK', cqUplink),
row('Трафик', cqInfo)
]),
E('div', { 'class': 'cbi-page-actions' }, [
this.button('Включить', 'positive', 'csqtt-on'), ' ',
this.button('Выключить', 'negative', 'csqtt-off')
]),
E('p', { 'class': 'cbi-value-description' },
'«Включить»: запускает csqtt, ждёт подключения (до 1,5 мин) и ставит UPLINK = CSQTT. ' +
'«Выключить»: UPLINK = DIRECT, затем останавливает csqtt — он не поднимется сам ни после ' +
'перезагрузки, ни при переподключении WAN. Профили и VK-токен — в Службы → star-panel-csqtt.')
] : [ E('p', 'csqtt не установлен: поставь star-panel-csqtt (github.com/starkugz/csqtt-openwrt).') ]));
}
if (st.tailscale) {
var tsState = E('span', '—');
var tsCheck = function() {
dom.content(tsState, E('em', 'проверяю…'));
return callTsCheck().then(function(r) {
dom.content(tsState, {
up: E('strong', { 'style': 'color:green' }, 'отвечает, ' + r.delay + ' мс'),
down: [ E('strong', { 'style': 'color:#c00' }, 'не отвечает'), ' ' + (r.message || '') ]
}[r.state] || r.state);
if (r.url)
tsState.appendChild(E('span', { 'class': 'cbi-value-description' }, [ ' — ', r.url ]));
}).catch(function(e) { dom.content(tsState, String(e)); });
};
if (st.ts_logged_in)
tsCheck();
sections.push(section('Tailscale', [
E('table', { 'class': 'table' }, [
row('Нода', st.ts_logged_in ? 'вошла в аккаунт' : E('strong', 'не вошла')),
row('Связь', [ tsState, ' ', E('button', { 'class': 'btn cbi-button cbi-button-action',
'click': ui.createHandlerFn(this, tsCheck) }, 'Проверить') ])
]),
E('div', { 'class': 'cbi-page-actions' }, st.ts_logged_in
? [ this.button('Войти заново', 'negative', 'ts-relogin', null,
'Удалить ключ ноды и войти заново? Нода получит новый адрес 100.x.') ]
: [ this.button('Получить ссылку для входа', 'positive', 'ts-login', null, st.profile == 'whitelist'
? 'На whitelist Tailscale идёт к серверу входа через MY — ссылка может не появиться. ' +
'Надёжнее включить профиль main (или foreign), войти и вернуться. Всё равно попробовать?'
: null) ])
]));
}
if (st.mobile_path) {
var mobUrl = window.location.protocol + '//' + window.location.host + st.mobile_path;
// the camera opens a plain link in the browser; the import link opens FlClash itself
var importUrl = 'clash://install-config?url=' + encodeURIComponent(mobUrl) + '&name=mihomo-kit';
var qrBox = E('div', { 'style': 'width:220px;max-width:100%;background:#fff;padding:8px;border-radius:4px' }, E('em', 'QR…'));
var copied = E('span', { 'class': 'cbi-value-description' });
var copy = function() {
var done = function() { copied.textContent = ' скопировано'; };
if (navigator.clipboard && window.isSecureContext)
return navigator.clipboard.writeText(mobUrl).then(done);
// http LuCI: no Clipboard API
var t = E('textarea', { 'style': 'position:fixed;opacity:0' }, mobUrl);
document.body.appendChild(t);
t.select();
document.execCommand('copy');
document.body.removeChild(t);
done();
};
loadQr().then(function(qrcode) {
var q = qrcode(0, 'M');
q.addData(importUrl);
q.make();
qrBox.innerHTML = q.createSvgTag({ cellSize: 4, margin: 2, scalable: true });
}).catch(function(e) { dom.content(qrBox, String(e)); });
sections.push(section('Телефон (FlClash)', [
E('div', { 'style': 'display:flex;gap:1.5em;flex-wrap:wrap;align-items:flex-start' }, [
qrBox,
E('div', { 'style': 'flex:1;min-width:16em' }, [
E('p', 'Профиль из тех же подписок и BOOT, без OpenVPN, Tailscale и торрентов; свои серверы — через MY-EXIT. ' +
'QR — камерой телефона: откроется FlClash и добавит профиль. Или скопируй ссылку: ' +
'FlClash → Профили → + → URL.'),
E('p', [ E('code', { 'style': 'word-break:break-all' }, mobUrl) ]),
E('p', [
E('button', { 'class': 'btn cbi-button', 'click': copy }, 'Скопировать ссылку'), ' ',
E('a', { 'class': 'btn cbi-button', 'href': importUrl }, 'Открыть в FlClash'),
copied
]),
E('p', { 'class': 'cbi-value-description' }, 'Ссылка работает только в сети роутера: вне дома FlClash ' +
'просто не обновит профиль. В ней ссылки подписок — не пересылай; «Новая ссылка» отзывает старую.'),
this.button('Новая ссылка', 'negative', 'mobile-new', null,
'Выдать новую ссылку? Старая перестанет работать, в FlClash профиль надо будет добавить заново.')
])
])
]));
}
sections.push(section('Обслуживание', [
E('table', { 'class': 'table' }, [
row(this.button('Пересобрать профили', 'action', 'build'),
'profiles.d/*.env → profiles/*.yaml (применится после «Включить» профиль)'),
row(E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': ui.createHandlerFn(this, function() {
return callExport().then(function(r) {
var a = E('a', { 'href': URL.createObjectURL(new Blob([ r.data ], { 'type': 'text/plain' })), 'download': r.name });
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
}) }, 'Экспорт настроек'), 'один файл: подписки, BOOT, профили, свои серверы, OpenVPN (с паролями и .ovpn) — ' +
'для другого роутера; без выбора ядра, ключа Tailscale и ссылки для телефона'),
row(this.importBox(), 'заменит настройки этого роутера файлом экспорта и перезапустит профиль'),
row(this.coreSelect(st.core || {}), 'ядро mihomo для этого роутера; применяется сразу (перезапуск nikki)'),
row(st.auto_update
? this.button('Выключить автообновление', 'negative', 'autoupdate-off')
: this.button('Включить автообновление', 'positive', 'autoupdate-on'),
[ st.auto_update ? E('strong', 'включено') : 'выключено',
': каждый день в 4:00 (время роутера), если на сервере новый коммит — обновить kit и перезапустить профиль',
st.auto_update_last ? E('div', { 'class': 'cbi-value-description' }, 'последний запуск: ' + st.auto_update_last) : '' ]),
row(this.button('Обновить kit', 'action', 'update', null,
'Скачать свежий kit и пересобрать профили?'),
'шаблоны, скрипты и эта страница; после обновления LuCI может попросить войти заново'),
row(this.button('Починить после обновления nikki', 'action', 'fix', null,
'Перезапустить nikki и вернуть ядро и правки?'),
'версия ядра, TS_FORCE_NOISE_443, reserved_ip')
])
]));
dom.content(this.body, sections);
},
// collapsed: a button; open: the form (always open until configured)
renderSettingsBox: function(open) {
if (open)
return Promise.all([ callConfigGet(), loadServers() ]).then(L.bind(function(r) {
return this.renderSettings(r[0]);
}, 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: E('textarea', { 'class': 'cbi-input-textarea', 'rows': 3, 'style': 'width:100%;font-family:monospace',
'placeholder': 'vless://…\nvless://… (по одной на строку)' }, cfg.boot_links || ''),
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),
push: check(cfg.push),
ru_ips: text(cfg.ru_ips, '1.2.3.4/32 5.6.0.0/16'),
foreign_ips: text(cfg.foreign_ips, '1.2.3.4/32 5.6.0.0/16'),
my_ips: text(cfg.my_ips, '1.2.3.4/32 5.6.0.0/16'),
ru_domains: text(cfg.ru_domains, 'example.ru *.example.com'),
foreign_domains: text(cfg.foreign_domains, 'example.com *.example.org'),
my_domains: text(cfg.my_domains, 'example.com *.example.org'),
local_hosts: text(cfg.local_hosts, 'example.com=192.168.1.10'),
openvpn: check(cfg.openvpn),
csqtt: check(cfg.csqtt),
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'),
ovpn_check_url: text(cfg.ovpn_check_url, 'https://eu.bmstu.ru'),
ts_check_url: text(cfg.ts_check_url, 'http://100.69.216.50:8080'),
mobile: check(cfg.mobile),
lite: check(cfg.lite),
lite_gomemlimit: text(cfg.lite_gomemlimit, '64MiB')
};
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-AUTO', 'BOOT', 'DIRECT', 'FOREIGN' ];
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),
enabled: check(s.enabled !== false)
};
entry.via.value = s.via || 'BOOT-AUTO';
entry.hwid.addEventListener('change', update);
var el = E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap;margin-bottom:.4em' }, [
E('label', { 'title': 'выключенная остаётся в списке, но не попадает в профиль' }, [ entry.enabled, ' вкл' ]),
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);
// services (SERVICES): a site or app with its own group and way, a row each;
// "через": the built-in groups or a pool (pools below, read when the list opens)
var svcList = E('div'), services = [], pools = [];
var viaOptions = function(sel) {
var cur = sel.value || sel.getAttribute('data-via');
var names = pools.length ? pools.map(function(p) { return p.name.value.trim().toUpperCase(); })
: (cfg.pools || []).map(function(p) { return p.name.toUpperCase(); });
dom.content(sel, [
[ 'MY', 'свои серверы (первый живой)' ], [ 'FOREIGN', 'FOREIGN' ], [ 'RU', 'RU' ],
[ 'DIRECT', 'напрямую' ], [ 'MAIN', 'как MAIN' ]
].concat(names.filter(Boolean).map(function(n) { return [ n, 'пул ' + n ]; }))
.map(function(o) { return E('option', { 'value': o[0] }, o[1]); }));
sel.value = cur;
};
// "вход" of a service (SVC_<NAME>_CHAIN): what its exit servers dial through
var chainOptions = function(sel) {
var cur = sel.value || sel.getAttribute('data-chain') || '';
var names = pools.length ? pools.map(function(p) { return p.name.value.trim().toUpperCase(); })
: (cfg.pools || []).map(function(p) { return p.name.toUpperCase(); });
dom.content(sel, [ [ '', 'как обычно' ], [ 'DIRECT', 'напрямую' ], [ 'FOREIGN', 'FOREIGN' ], [ 'RU', 'RU' ],
[ 'MY', 'MY' ], [ 'MY-EXIT', 'MY-EXIT (whitelist, телефон)' ] ]
.concat(names.filter(Boolean).map(function(n) { return [ n, 'пул ' + n ]; }))
.map(function(o) { return E('option', { 'value': o[0] }, o[1]); }));
sel.value = cur;
};
var addService = function(v) {
var e = {
name: text(v.name || '', 'claude'),
via: E('select', { 'class': 'cbi-input-select', 'data-via': v.via || 'MY' }),
chain: E('select', { 'class': 'cbi-input-select', 'data-chain': v.chain || '' }),
server: text(v.server || '', 'пусто — группа / автовыбор'),
provider: text(v.provider || '', 'пусто — свои серверы; иначе ID провайдера'),
geosite: text(v.geosite || '', 'anthropic'),
domains: text(v.domains || '', 'example.com'),
ips: text(v.ips || '', '1.2.3.0/24')
};
e.name.style.width = '9em';
viaOptions(e.via);
e.via.addEventListener('focus', function() { viaOptions(e.via); });
e.via.addEventListener('mousedown', function() { viaOptions(e.via); });
e.via.disabled = !!e.server.value.trim();
e.server.addEventListener('input', function() { e.via.disabled = !!e.server.value.trim(); });
chainOptions(e.chain);
e.chain.addEventListener('focus', function() { chainOptions(e.chain); });
e.chain.addEventListener('mousedown', function() { chainOptions(e.chain); });
var el = E('div', { 'style': 'border:1px solid #8884;border-radius:4px;padding:.5em;margin-bottom:.5em' }, [
E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap' }, [
e.name, 'через', e.via,
E('button', { 'class': 'btn cbi-button cbi-button-remove', 'title': 'удалить сервис', 'click': function() {
svcList.removeChild(el);
services.splice(services.indexOf(e), 1);
} }, '✕')
]),
field('geosite', e.geosite, 'списки MetaCubeX/meta-rules-dat через пробел: anthropic, openai, youtube…'),
field('Домены', e.domains, 'ещё домены, с поддоменами'),
field('IP', e.ips, 'ещё адреса, без маски = /32'),
field('Фиксированный сервер', e.server, 'точное имя; выбор сохраняется во всех профилях. Удобнее выбирать на графе'),
field('Источник сервера', e.provider, 'для подписки — ID провайдера, например sam_hub-my; для своего сервера оставить пустым'),
field('Вход', e.chain, 'для фиксированного сервера, MY или пула: через что подключаться к его серверам (например, ' +
'сервер с нужным IP доступен только через другой пул). «Как обычно» — на whitelist и телефоне через MY-EXIT, ' +
'иначе напрямую')
]);
services.push(e);
svcList.appendChild(el);
};
(cfg.services || []).forEach(addService);
// own servers (luci/servers.js): a card each - the name, type and address, the
// proxy as YAML to edit; share links / YAML pasted below become cards
var S = window.mkServers;
var srvList = E('div'), servers = [];
var taken = function() {
var t = {};
servers.forEach(function(e) { t[e.name.value.trim()] = true; });
return t;
};
var addServer = function(p, open) {
var e = { proxy: {}, error: null };
Object.keys(p).forEach(function(k) {
if (k != 'name' && k != 'dialer-proxy')
e.proxy[k] = p[k];
});
e.name = text(S.freeName(p.name, taken()), 'имя в дашборде');
e.name.style.width = '16em';
e.get = function() {
var o = { name: e.name.value.trim() };
Object.keys(e.proxy).forEach(function(k) { o[k] = e.proxy[k]; });
return o;
};
var info = E('code', {}, S.summary(e.proxy));
var err = E('div', { 'style': 'color:#c33;display:none' });
e.yaml = E('textarea', { 'class': 'cbi-input-textarea', 'rows': 12, 'spellcheck': 'false',
'style': 'width:100%;font-family:monospace;margin-top:.3em' + (open ? '' : ';display:none') }, S.yamlDump(e.proxy));
// the YAML is read as it is typed: an error shows and blocks the save
e.yaml.addEventListener('input', function() {
try {
var v = S.yamlLoad(e.yaml.value);
if (!v || typeof v != 'object' || Array.isArray(v))
throw new Error('нужен один сервер в виде «ключ: значение»');
if (!v.type || v.server === undefined || v.server === null || v.server === '')
throw new Error('нужны type и server');
delete v.name;
delete v['dialer-proxy'];
e.proxy = v;
e.error = null;
info.textContent = S.summary(v);
err.style.display = 'none';
} catch (x) {
e.error = x.message;
err.textContent = 'YAML: ' + x.message;
err.style.display = '';
}
});
var el = E('div', { 'style': 'border:1px solid #8884;border-radius:4px;padding:.5em;margin-bottom:.5em' }, [
E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap' }, [
e.name, info,
E('button', { 'class': 'btn cbi-button', 'click': function() {
e.yaml.style.display = e.yaml.style.display == 'none' ? '' : 'none';
} }, 'Настройки (YAML)'),
E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': function() {
var yaml = S.yamlDump([ e.get() ]) + '\n';
copyText(yaml).then(function(ok) {
if (ok)
return ui.addNotification(null, E('p', 'Сервер ' + e.name.value.trim() +
' скопирован: на другом роутере — «Добавить из ссылки / YAML». В нём пароли, не публикуй.'), 'info');
ui.showModal('Сервер ' + e.name.value.trim(), [
E('p', 'Скопировать автоматически не вышло — выдели и скопируй:'),
E('textarea', { 'class': 'cbi-input-textarea', 'rows': 12, 'readonly': 'readonly',
'style': 'width:100%;font-family:monospace', 'click': function(ev) { ev.target.select(); } }, yaml),
E('div', { 'class': 'right' }, E('button', { 'class': 'btn', 'click': ui.hideModal }, 'Закрыть'))
]);
});
} }, 'Скопировать'),
E('button', { 'class': 'btn cbi-button cbi-button-remove', 'title': 'удалить сервер', 'click': function() {
srvList.removeChild(el);
servers.splice(servers.indexOf(e), 1);
} }, '✕')
]),
e.yaml, err
]);
servers.push(e);
srvList.appendChild(el);
};
S.fromLines(cfg.servers_text).forEach(function(p) { addServer(p); });
// the old settings: hysteria2 by fields (HY2_*) and links (MY_LINKS) become cards,
// the save writes them as own servers and drops the old keys
var moved = 0;
(cfg.hy2 || []).forEach(function(h) {
var o = { name: h.name, type: 'hysteria2', server: h.server,
port: /^[0-9]+$/.test(h.port) ? +h.port : h.port, password: h.password };
if (h.obfs_password) {
o.obfs = 'salamander';
o['obfs-password'] = h.obfs_password;
}
if (h.sni)
o.sni = h.sni;
if (h.insecure == '1')
o['skip-cert-verify'] = true;
if (h.up)
o.up = h.up;
if (h.down)
o.down = h.down;
o.udp = true;
addServer(o);
moved++;
});
S.parseLinks(cfg.my_links || '').forEach(function(p) {
addServer(p);
moved++;
});
// pools (POOLS): own servers (by name) and subscription nodes (providers + filter) picked
// by hand, a card each; group = the name in upper case, a service goes through it
var poolList = E('div');
var poolSubs = [];
(cfg.subs || []).forEach(function(s) {
if (s.id)
poolSubs.push([ s.id, s.id ], [ s.id + '-my', s.id + ' — только [MY]' ]);
});
var boxes = function(all, have, label) {
var list = all.map(function(o) { return { v: o[0], t: o[1] }; });
have.forEach(function(v) {
if (!list.some(function(o) { return o.v == v; }))
list.push({ v: v, t: v + ' (нет в настройках)' });
});
return list.map(function(o) {
o.c = check(have.indexOf(o.v) >= 0);
o.el = E('label', { 'style': 'margin-right:1em;white-space:nowrap;display:inline-block' }, [ o.c, ' ', o.t ]);
return o;
});
};
var addPool = function(v) {
var srvNames = servers.map(function(e) { return e.name.value.trim(); }).filter(Boolean);
var e = {
name: text(v.name || '', 'de'),
type: E('select', { 'class': 'cbi-input-select' }, [
[ 'fallback', 'первый живой' ], [ 'url-test', 'самый быстрый' ], [ 'select', 'вручную (в дашборде / графе)' ]
].map(function(o) { return E('option', { 'value': o[0] }, o[1]); })),
srv: boxes(srvNames.map(function(n) { return [ n, n ]; }),
(v.servers || '').split(';').map(function(x) { return x.trim(); }).filter(Boolean)),
subs: boxes(poolSubs, (v.subs || '').split(/\s+/).filter(Boolean)),
filter: text(v.filter || '', '(?i)🇩🇪|\\bde\\b или \\[WL\\]'),
exclude: text(v.exclude || '', '(?i)torrent'),
uplink: check(v.uplink == '1')
};
e.name.style.width = '9em';
e.type.value = v.type || 'fallback';
var el = E('div', { 'style': 'border:1px solid #8884;border-radius:4px;padding:.5em;margin-bottom:.5em' }, [
E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap' }, [
e.name, e.type,
E('button', { 'class': 'btn cbi-button cbi-button-remove', 'title': 'удалить пул', 'click': function() {
poolList.removeChild(el);
pools.splice(pools.indexOf(e), 1);
} }, '✕')
]),
field('Свои серверы', e.srv.length ? e.srv.map(function(o) { return o.el; }) : E('em', 'нет своих серверов'),
'новые серверы появятся здесь после сохранения'),
field('Подписки', e.subs.length ? e.subs.map(function(o) { return o.el; }) : E('em', 'нет подписок'),
'их ноды — по фильтру ниже; «только [MY]» — ноды с [MY] в имени'),
field('Фильтр', e.filter, 'регулярное выражение по имени ноды подписки (filter в mihomo): ' +
'метка своей подписки — \\[WL\\], страна — (?i)🇩🇪|\\bde\\b; пусто — все ноды. К своим серверам не применяется'),
field('Исключить', e.exclude, 'ноды подписки с таким именем не берутся'),
field('В UPLINK', e.uplink, 'предлагать пул в группе UPLINK: если выбрать его там (дашборд, граф), всё ' +
'сначала идёт через пул, а дальше как обычно — для выхода из блокировок. Серверы пула при этом подключаются напрямую')
]);
pools.push(e);
poolList.appendChild(el);
};
(cfg.pools || []).forEach(addPool);
// import: share links, AmneziaVPN keys, YAML or a WireGuard / AmneziaWG .conf (or a
// file) -> cards; a .conf from a file is named after the file
var importText = E('textarea', { 'class': 'cbi-input-textarea', 'rows': 8, 'spellcheck': 'false',
'style': 'width:100%;font-family:monospace',
'placeholder': 'vless://…\ntrojan://…\nhysteria2://…\nvpn://… (ключ AmneziaVPN)\n\nили .conf AmneziaWG / WireGuard ([Interface] … [Peer] …)\n\nили YAML, как в конфиге mihomo / Clash:\n- name: nl-1\n type: hysteria2\n server: vpn.example.com\n port: 443\n password: ...' });
var importFile = E('input', { 'type': 'file', 'accept': '.yaml,.yml,.txt,.conf,.vpn' });
var importName = '';
importFile.addEventListener('change', function() {
readFile(importFile).then(function(t) {
importText.value = t;
importName = importFile.files[0] ? importFile.files[0].name.replace(/\.[^.]*$/, '') : '';
});
});
importText.addEventListener('input', function() { importName = ''; });
var importBox = E('div', { 'style': 'display:none;margin-bottom:.5em' }, [
importText,
E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap;margin-top:.3em' }, [
E('span', 'или из файла:'), importFile,
E('button', { 'class': 'btn cbi-button cbi-button-apply', 'click': function() {
var r = S.parseText(importText.value, importName);
r.servers.forEach(function(p) { addServer(p); });
var msg = [ E('p', r.servers.length ? 'Добавлено серверов: ' + r.servers.length +
'. Проверь имена и нажми «Сохранить и применить».' : 'Серверов не нашёл.') ];
r.errors.forEach(function(x) { msg.push(E('p', x)); });
ui.addNotification(null, msg, r.servers.length && !r.errors.length ? 'info' : 'warning');
if (r.servers.length) {
importText.value = '';
importBox.style.display = 'none';
}
} }, 'Разобрать')
])
]);
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),
field('Адрес для проверки', f.ovpn_check_url, 'что открывает ручная проверка туннеля (кнопка «Проверить» в блоке OpenVPN, тест задержки в дашборде; с ядром не из kit — ещё и cron раз в ~10 минут). Сайт видит этот запрос, поэтому лучше страница, которую и так открываешь в браузере')
]);
dom.content(tsBox, [
field('Имя ноды', f.ts_hostname),
field('Split-DNS домены', f.ts_domains, 'домены тейлнета кроме *.ts.net, через пробел'),
field('Адрес для проверки', f.ts_check_url, 'HTTP-сервис на ноде тейлнета: проверка в дашборде (группа TAILSCALE) и кнопка «Проверить»')
]);
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, enabled: s.enabled.checked };
}).filter(function(s) { return s.url; });
var errors = [];
if (!list.some(function(s) { return s.enabled; }))
errors.push('нужна хотя бы одна включённая подписка');
f.boot.value.split(/\s+/).filter(Boolean).forEach(function(l) {
if (!/^vless:\/\/[^@]+@[^?]+\?.*\bpbk=/.test(l))
errors.push('BOOT: не похоже на vless-ссылку с reality (нужны host, pbk, sid): ' + l.slice(0, 40) + '…');
});
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-секрет');
}
var poolNames = {}, taken = /^(boot|boot-auto|ru|foreign|torrent|torrent-sel|my|my-exit|main|push|uplink|tailscale|ts-exit|ovpn-exit|csqtt|direct|reject|reject-drop|pass|compatible|global|bmstu)$/;
var poolData = pools.map(function(e) {
return { name: e.name.value.trim().toLowerCase(), type: e.type.value,
servers: e.srv.filter(function(o) { return o.c.checked; }).map(function(o) { return o.v; }).join('; '),
subs: e.subs.filter(function(o) { return o.c.checked; }).map(function(o) { return o.v; }).join(' '),
filter: e.filter.value.trim(), exclude: e.exclude.value.trim(), uplink: e.uplink.checked ? '1' : '' };
});
poolData.forEach(function(v) {
if (!/^[a-z0-9][a-z0-9_-]*$/.test(v.name))
errors.push('Пул «' + v.name + '»: имя — латиница, цифры, _ и -');
else if (poolNames[v.name])
errors.push('Пул «' + v.name + '» повторяется');
else if (taken.test(v.name))
errors.push('Пул «' + v.name + '»: такая группа уже есть, возьми другое имя');
poolNames[v.name] = true;
if (!v.servers && !v.subs)
errors.push('Пул «' + v.name + '»: отметь свои серверы или подписки');
});
var svcNames = {};
var svcData = services.map(function(e) {
return { name: e.name.value.trim().toLowerCase(), via: e.via.value, chain: e.chain.value, geosite: e.geosite.value.trim(),
domains: e.domains.value.trim(), ips: e.ips.value.trim(), server: e.server.value.trim(), provider: e.server.value.trim() ? e.provider.value.trim() : '' };
});
svcData.forEach(function(v) {
if (!/^[a-z0-9][a-z0-9_-]*$/.test(v.name))
errors.push('Сервис «' + v.name + '»: имя — латиница, цифры, _ и -');
else if (svcNames[v.name])
errors.push('Сервис «' + v.name + '» повторяется');
else if (taken.test(v.name) || poolNames[v.name])
errors.push('Сервис «' + v.name + '»: такая группа уже есть, возьми другое имя');
svcNames[v.name] = true;
if (!v.geosite && !v.domains && !v.ips)
errors.push('Сервис «' + v.name + '»: нужен geosite, домены или IP');
var builtin = /^(MY|FOREIGN|RU|DIRECT|MAIN|MY-EXIT)$/;
if (!v.server && !builtin.test(v.via) && !poolNames[v.via.toLowerCase()])
errors.push('Сервис «' + v.name + '»: пула ' + v.via + ' больше нет');
if (v.chain && !builtin.test(v.chain) && !poolNames[v.chain.toLowerCase()])
errors.push('Сервис «' + v.name + '»: пула ' + v.chain + ' (вход) больше нет');
if (v.chain && !v.server && v.via != 'MY' && !poolNames[v.via.toLowerCase()])
errors.push('Сервис «' + v.name + '»: вход — только когда выход через MY или пул');
else if (v.chain && !v.server && v.chain == v.via)
errors.push('Сервис «' + v.name + '»: вход и выход — одно и то же');
});
if (f.lite_gomemlimit.value.trim() && !/^[1-9][0-9]*(B|KiB|MiB|GiB)?$/.test(f.lite_gomemlimit.value.trim()))
errors.push('Лимит памяти: число с единицей, например 64MiB');
var names = {}, srvLines = [];
servers.forEach(function(e) {
var n = e.name.value.trim();
if (!n)
errors.push('Свой сервер: пустое имя');
else if (names[n])
errors.push('Свой сервер: имя «' + n + '» повторяется');
names[n] = true;
if (e.error)
errors.push('Свой сервер ' + n + ': ' + e.error);
else if (e.proxy.server === undefined || e.proxy.server === null || e.proxy.server === '')
errors.push('Свой сервер ' + n + ': пустой server (открой «Настройки (YAML)»)');
srvLines.push(S.toLine(e.get()));
});
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_links: 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,
push: f.push.checked,
ru_ips: f.ru_ips.value.trim(),
foreign_ips: f.foreign_ips.value.trim(),
my_ips: f.my_ips.value.trim(),
ru_domains: f.ru_domains.value.trim(),
foreign_domains: f.foreign_domains.value.trim(),
my_domains: f.my_domains.value.trim(),
local_hosts: f.local_hosts.value.trim(),
my_links: '',
openvpn: f.openvpn.checked,
csqtt: f.csqtt.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(),
ovpn_check_url: f.ovpn_check_url.value.trim(),
ts_check_url: f.ts_check_url.value.trim(),
mobile: f.mobile.checked,
lite: f.lite.checked,
lite_gomemlimit: f.lite_gomemlimit.value.trim(),
hy2: [],
services: svcData,
pools: poolData,
servers_text: srvLines.join('\n')
});
}, 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 берёт первую живую, ' +
'через неё качаются подписки; пусто — без BOOT. Подписки по умолчанию качаются через BOOT-AUTO: ' +
'BOOT, иначе ноды уже скачанных подписок (FOREIGN), иначе напрямую'),
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('Обход для пушей', f.push, 'Apple APNs и Google FCM через группу PUSH (main/foreign — DIRECT, whitelist — MY): ' +
'уведомления не рвутся при смене ноды; выключено — пуши идут по общим правилам'),
field('OpenVPN BMSTU', f.openvpn),
ovpnBox,
field('CSQTT', f.csqtt, 'интерфейс csqtt0 от star-panel-csqtt (Службы → star-panel-csqtt). Группа UPLINK в дашборде: ' +
'DIRECT — как раньше, CSQTT — ноды подписок, BOOT и свои серверы подключаются через csqtt0 ' +
'(выход из белых списков), а MAIN/FOREIGN/MY работают поверх'),
field('Tailscale', f.tailscale),
tsBox,
field('Облегчённый режим', f.lite, 'для роутеров с 256 МБ памяти: лимит памяти ядра (GOMEMLIMIT), ' +
'проверки нод раз в 10 минут и только при трафике, сниффер без QUIC, лог nikki — warning, без поиска процессов ' +
'(кроме CSQTT), перехват без TUN (TCP redirect, UDP tproxy). Что ещё ест память, kit напишет в журнале применения'),
field('Лимит памяти', f.lite_gomemlimit, 'GOMEMLIMIT для облегчённого режима, по умолчанию 64MiB; ' +
'слишком низкий — ядро постоянно чистит память и грузит процессор'),
field('Конфиг для телефона', f.mobile, 'FlClash: QR и ссылка появятся на этой странице после сохранения ' +
'(файл раздаётся роутером внутри LAN по ссылке со случайным токеном)'),
E('h4', 'Пулы'),
E('p', { 'class': 'cbi-value-description' }, 'Свои наборы серверов: свои серверы галками и ноды подписок по фильтру. ' +
'У каждого пула своя группа (имя заглавными, например DE); сервис можно пустить через пул — тогда его выход задан ' +
'настройками, одинаково на роутере и телефоне. Пустой пул (серверы переименованы, подписка выключена) закрывает ' +
'свои сервисы (REJECT), а не пускает их мимо.'),
poolList,
E('div', [ E('button', { 'class': 'btn cbi-button cbi-button-add', 'click': function() { addPool({}); } }, 'Добавить пул') ]),
E('h4', 'Сервисы'),
E('p', { 'class': 'cbi-value-description' }, 'Сайт или приложение, которое всегда идёт своим путём, что бы ни было выбрано ' +
'в MAIN: своя группа в дашборде (имя заглавными, например CLAUDE), правила выше «Своих правил». Через свои серверы — ' +
'первый живой, а не самый быстрый: выходной IP не скачет между странами, пока сервер жив (в дашборде можно ' +
'выбрать другой). На whitelist и телефоне к своим серверам — через MY-EXIT, как обычно. Есть и в конфиге телефона.'),
svcList,
E('div', [
E('button', { 'class': 'btn cbi-button cbi-button-add', 'click': function() { addService({}); } }, 'Добавить сервис'), ' ',
E('button', { 'class': 'btn cbi-button', 'click': function() {
if (!services.some(function(e) { return e.name.value.trim().toLowerCase() == 'claude'; }))
addService({ name: 'claude', geosite: 'anthropic', via: 'MY' });
} }, '+ Claude')
]),
E('h4', 'Свои правила'),
E('p', { 'class': 'cbi-value-description' }, 'Через пробел. Выше торрентов, ru-inside, .ru и MAIN (ниже только ' +
'Tailscale, OpenVPN, локальная сеть, пуши и сервисы). Домен действует вместе с поддоменами (example.com = *.example.com), ' +
'IP без маски = /32. Если адрес попал в несколько списков — побеждает MY, затем FOREIGN, затем RU.'),
field('Домены через RU', f.ru_domains, 'на main (свой белый IP) идут напрямую'),
field('Домены через FOREIGN', f.foreign_domains),
field('Домены через MY', f.my_domains, 'свои серверы: ниже и [MY] из подписок'),
field('Доп. IP через RU', f.ru_ips, 'на main (свой белый IP) идут напрямую'),
field('Доп. IP через FOREIGN', f.foreign_ips),
field('Доп. IP через MY', f.my_ips, 'свои серверы: ниже и [MY] из подписок'),
field('Локальные адреса', f.local_hosts, 'домен=IP в локальной сети (с поддоменами): роутер и клиенты ' +
'ходят к серверу напрямую по LAN, а не через белый IP и обратно. Только для этого роутера (не телефон, ' +
'при импорте не переносится)'),
E('h4', 'Свои серверы'),
E('p', { 'class': 'cbi-value-description' }, 'Собираются в группу MY (автовыбор самого быстрого, в дашборде можно закрепить один). MY — пункт в MAIN ' +
'рядом с FOREIGN. К самим серверам на whitelist и с телефона — через MY-EXIT, на main — напрямую. Ссылки ' +
'vless / vmess / trojan / ss / hysteria2 / tuic / anytls и YAML разбираются так же, как в mihomo; ключ ' +
'AmneziaVPN (vpn://) и .conf AmneziaWG / WireGuard становятся сервером wireguard; серверы ' +
'попадают и в конфиг телефона. Серверы из подписок с [MY] в имени (например «[MY] 🇩🇪 de-1») тоже попадают в MY.'),
moved ? E('p', { 'class': 'alert-message warning' }, 'Перенесено из старых настроек (hysteria2 по полям, ссылки): ' +
moved + '. Нажми «Сохранить и применить», чтобы сохранить их в новом виде.') : '',
srvList,
importBox,
E('div', [
E('button', { 'class': 'btn cbi-button cbi-button-add', 'click': function() {
importBox.style.display = importBox.style.display == 'none' ? '' : 'none';
} }, 'Добавить из ссылки / YAML'), ' ',
E('button', { 'class': 'btn cbi-button', 'click': function() {
addServer({ name: 'new', type: 'hysteria2', server: '', port: 443, password: '' }, true);
} }, 'Добавить вручную')
]),
E('div', { 'class': 'cbi-page-actions' }, [ save ])
]);
},
importBox: function() {
var file = E('input', { 'type': 'file', 'accept': '.kit,.txt' });
var keep = check(true);
var btn = E('button', { 'class': 'btn cbi-button cbi-button-apply', 'click': ui.createHandlerFn(this, function() {
if (!file.files.length)
return ui.addNotification(null, E('p', 'Выбери файл экспорта (.kit)'), 'warning');
if (!window.confirm('Заменить все настройки этого роутера файлом ' + file.files[0].name + '?'))
return;
return readFile(file).then(L.bind(function(text) {
return callImport(text, keep.checked);
}, this)).then(L.bind(function(r) {
if (r.error)
return ui.addNotification(null, E('p', r.error), 'danger');
return this.follow();
}, this));
}) }, 'Импорт настроек');
btn.disabled = this.busy;
this.buttons.push(btn);
return E('div', [ file, ' ', btn, E('div', { 'style': 'margin-top:.3em' }, E('label', [ keep,
' оставить имя ноды Tailscale и x-hwid этого роутера' ])) ]);
},
// select stock / official / kit + "Установить"
coreSelect: function(c) {
var freeMb = Math.floor((+c.free_kb || 0) / 1024), needMb = Math.ceil((+c.need_kb || 0) / 1024);
var low = freeMb < needMb;
var opts = [
[ 'stock', 'Из прошивки' + (c.stock ? ' (' + c.stock + ')' : ' (нет)'), !c.stock ],
[ 'official', 'Официальное ' + (c.official || ''), false ],
[ 'kit', 'Сборка kit ' + (c.kit || '') + ' (официальное + правки kit)', false ]
];
var sel = E('select', { 'class': 'cbi-input-select' }, opts.map(function(o) {
var opt = E('option', { 'value': o[0] }, o[1]);
opt.disabled = o[2];
return opt;
}));
// MIHOMO_VERSION=... in kit.env: shown as is until a choice replaces it
if (c.pinned == '1')
sel.insertBefore(E('option', { 'value': '' }, 'закреплено в kit.env: ' + c.wanted), sel.firstChild);
sel.value = c.pinned == '1' ? '' : (c.choice || 'kit');
var hint = E('div', { 'class': 'cbi-value-description' });
var update = function() {
dom.content(hint, (sel.value == 'official' || sel.value == 'kit') && low
? 'Во флеше свободно ' + freeMb + ' МБ, ядру нужно около ' + needMb +
' МБ: скорее всего не встанет (установка тогда откатится сама)'
: '');
};
sel.addEventListener('change', update);
update();
return E('div', [ sel, ' ', this.button('Установить', 'apply', 'core', function() { return sel.value; },
'Поставить выбранное ядро? nikki перезапустится.'), hint ]);
},
showJob: function(j) {
if (!j.cmd) {
this.jobBox.style.display = 'none';
return;
}
this.jobBox.style.display = '';
var state = j.running ? 'выполняется…' : (j.rc === 0 ? 'готово' : 'ошибка (код ' + j.rc + ')');
dom.content(this.jobTitle, 'Последняя команда: ' + j.cmd + ' — ' + state);
var m = (j.log || '').match(/https:\/\/login\.tailscale\.com\/\S+/g);
dom.content(this.jobLink, m ? E('div', { 'class': 'alert-message notice' }, [
'Вход в Tailscale: ',
E('a', { 'href': m[m.length - 1], 'target': '_blank', 'rel': 'noreferrer' }, m[m.length - 1]),
E('br'), 'После входа в админке Tailscale — Disable key expiry для ноды.'
]) : []);
this.jobLog.textContent = j.log || '';
this.jobLog.scrollTop = this.jobLog.scrollHeight;
},
setBusy: function(busy) {
this.busy = busy;
this.buttons.forEach(function(b) { b.disabled = busy; });
},
run: function(cmd, arg) {
return callRun(cmd, arg || '').then(L.bind(function(r) {
if (r.error) {
ui.addNotification(null, E('p', r.error), 'danger');
return;
}
return this.follow();
}, this));
},
// poll the job until it ends; rpcd may restart under us (kit update)
follow: function() {
var errors = 0;
this.setBusy(true);
var loop = L.bind(function() {
return callJob().then(L.bind(function(j) {
errors = 0;
this.showJob(j);
if (j.running)
return wait(1000).then(loop);
this.setBusy(false);
if (j.rc !== 0)
ui.addNotification(null, E('p', j.cmd + ': ошибка, см. вывод внизу страницы'), 'danger');
return callStatus().then(L.bind(this.renderBody, this)).then(function() { return j; });
}, this)).catch(L.bind(function(e) {
if (++errors > 15) {
this.setBusy(false);
ui.addNotification(null, E('p', 'Нет связи с роутером: ' + e), 'danger');
return;
}
return wait(2000).then(loop);
}, this));
}, this);
return loop();
},
render: function(data) {
this.busy = false;
this.buttons = [];
this.body = E('div');
this.jobTitle = E('h3');
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.settingsBox, this.jobBox ]);
}
});