mihomo-kit/luci/mihomo-kit.js

1455 lines
83 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 callApi = rpc.declare({ object: 'mihomo-kit', method: 'api', params: [ 'path' ], nobatch: true, 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));
}
// the page's tabs, drawn as LuCI draws its own (ul.cbi-tabmenu): [[id, title, pane]];
// the open one is remembered for the browser session
function tabs(list, key) {
var menu = E('ul', { 'class': 'cbi-tabmenu' }), panes = {}, items = {};
var show = function(id) {
list.forEach(function(t) {
panes[t[0]].style.display = t[0] == id ? '' : 'none';
items[t[0]].className = t[0] == id ? 'cbi-tab' : 'cbi-tab-disabled';
});
try { window.sessionStorage.setItem(key, id); } catch (e) {}
};
list.forEach(function(t) {
panes[t[0]] = t[2];
items[t[0]] = E('li', {}, E('a', { 'href': '#', 'click': function(ev) { ev.preventDefault(); show(t[0]); } }, t[1]));
menu.appendChild(items[t[0]]);
});
var cur = null;
try { cur = window.sessionStorage.getItem(key); } catch (e) {}
show(panes[cur] ? cur : list[0][0]);
return E('div', [ menu ].concat(list.map(function(t) { return t[2]; })));
}
// OpenVPN: what decides the tunnel now and what happens next, from
// ovpn.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;
}
// zapret hostlists (cfg.hostlists [{path, lines}]) as buttons under the service's hostlist
// field: a click adds the file to it or takes it out; nothing when zapret has no lists
function hostlistPicker(input, files) {
if (!files || !files.length)
return [];
var words = function() { return input.value.trim().split(/\s+/).filter(Boolean); };
var buttons = files.map(function(f) {
var b = E('button', { 'class': 'btn cbi-button', 'title': f.path, 'style': 'margin:.2em .3em 0 0', 'click': function(ev) {
ev.preventDefault();
var w = words(), i = w.indexOf(f.path);
if (i < 0) w.push(f.path); else w.splice(i, 1);
input.value = w.join(' ');
mark();
} });
b.mkFile = f;
return b;
});
var mark = function() {
var w = words();
buttons.forEach(function(b) {
var on = w.indexOf(b.mkFile.path) >= 0;
b.textContent = (on ? '✓ ' : '+ ') + b.mkFile.path.replace(/^.*\//, '') + ' (' + b.mkFile.lines + ')';
b.className = 'btn cbi-button' + (on ? ' cbi-button-positive' : '');
});
};
input.addEventListener('input', mark);
mark();
return [ E('div', {}, [ E('small', {}, 'из zapret: ') ].concat(buttons)) ];
}
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);
}
// "route <net> [mask]" lines of an .ovpn as CIDR (as ovpn_routes_of in mihomo-kit.sh)
function ovpnRoutes(text) {
return String(text).split('\n').map(function(l) {
var w = l.trim().split(/\s+/);
if (w[0] != 'route' || !/^[0-9.]+$/.test(w[1] || ''))
return null;
var bits = (/^[0-9.]+$/.test(w[2] || '') ? w[2] : '255.255.255.255').split('.').reduce(function(a, o) {
for (var x = +o; x > 0; x = Math.floor(x / 2)) a += x % 2;
return a;
}, 0);
return w[1] + '/' + bits;
}).filter(Boolean).join(' ');
}
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) {
// what goes into the status part of each tab
var out = {};
var put = function(tab, el) { (out[tab] = out[tab] || []).push(el); };
this.buttons = [];
if (!st.configured)
put('overview', 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', 'проверяю обновления…');
// shown only next to "есть обновление"; the same command as on «Система»
var updBtn = this.button('Обновить', 'apply', 'update', null, 'Скачать свежий kit и пересобрать профили?');
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, 'что изменилось'), ')' ] : []).concat([ ' ', updBtn ]));
}).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) : '');
put('overview', 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 ? ' — роутер подключится заново после паузы, в ' + o.retry_hm
: ' — роутер подключится заново в течение минуты') ],
held: [ E('strong', { 'style': 'color:#c60' }, {
kick: 'сервер отключил сессию',
drop: 'туннель оборвался',
failed: 'не подключился'
}[o.retry_why] || 'пауза'),
desc(' — следующая попытка в ' + o.retry_hm + ' (без быстрых переподключений)' +
(o.err ? '; ' + o.err : '')) ],
unknown: [ E('strong', 'ядро не сообщает состояние'),
desc(' — с этим ядром роутер проверяет туннель запросом к адресу проверки раз в ~10 минут, ' +
'и маскировка под OpenVPN 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();
put('ovpn', section('Состояние', [
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' },
'Открывает адрес проверки через туннель. Только по кнопке: сайт видит такой запрос в логах, ' +
'а обычный клиент OpenVPN их не делает. Адрес лучше взять из тех, что и так открываешь в браузере.') ]),
row('Код сейчас', 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('Часы расписания', [ 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();
put('csqtt', section('Состояние', 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();
put('ts', section('Состояние', [
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 QR holds the plain link: any app's "add by QR / URL" takes it; the import link
// (clash://) opens the app straight away when this page is open on the phone 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(mobUrl);
q.make();
qrBox.innerHTML = q.createSvgTag({ cellSize: 4, margin: 2, scalable: true });
}).catch(function(e) { dom.content(qrBox, String(e)); });
put('phone', section('Подключить приложение', [
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', 'Тот же обход в приложении на телефоне или компьютере: те же подписки и правила, ' +
'без OpenVPN, Tailscale и торрентов. Подойдёт приложение на ядре mihomo (Clash Meta):'),
E('ul', [
E('li', [ E('strong', 'Android'), ' — FlClash или Clash Meta for Android' ]),
E('li', [ E('strong', 'iPhone, iPad'), ' — Clash Mi' ]),
E('li', [ E('strong', 'Windows, macOS, Linux'), ' — FlClash или Clash Verge Rev' ])
]),
E('p', 'В приложении: профили (подписки) → добавить → по ссылке или QR-коду. Отсканируй QR сканером ' +
'в приложении или скопируй ссылку и вставь её. Профиль обновляется по этой ссылке сам.'),
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,
'title': 'если эта страница открыта на телефоне: откроет приложение и добавит профиль' }, 'Открыть в приложении'),
copied
]),
E('p', { 'class': 'cbi-value-description' }, 'Добавлять профиль нужно дома, в сети этого роутера: ' +
'снаружи ссылка не открывается, и приложение просто не обновит профиль до возвращения домой. ' +
'В профиле ссылки подписок — не пересылай ссылку чужим; «Новая ссылка» отзывает старую.'),
this.button('Новая ссылка', 'negative', 'mobile-new', null,
'Выдать новую ссылку? Старая перестанет работать, в приложениях профиль надо будет добавить заново.')
])
])
]));
}
put('system', 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')
])
]));
Object.keys(this.slots).forEach(function(k) { dom.content(this.slots[k].status, out[k] || []); }, this);
},
// the settings parts of the tabs, from the saved settings
renderSettingsBox: function() {
return Promise.all([ callConfigGet(), loadServers() ]).then(L.bind(function(r) {
return this.renderSettings(r[0]);
}, this));
},
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 ? 'сохранён — пусто, чтобы не менять' : 'необязательно', 'password'),
totp_clear: check(false),
pass_format: E('select', { 'class': 'cbi-input-select' }, [
[ 'auto', 'сам: как просит файл .ovpn' ],
[ 'scrv1', 'отдельным полем (static-challenge, как OpenVPN Connect)' ],
[ 'otp-last', 'пароль, сразу за ним код' ],
[ 'otp-first', 'код, сразу за ним пароль' ]
].map(function(o) { return E('option', { 'value': o[0] }, o[1]); })),
ovpn_routes: text(cfg.ovpn_routes, '10.0.0.0/8 192.168.50.0/24'),
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://intranet.example.com'),
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')
};
f.pass_format.value = cfg.pass_format || 'auto';
// a new .ovpn: its route lines, unless the networks are filled in already
f.ovpn.addEventListener('change', function() {
readFile(f.ovpn).then(function(t) {
var r = ovpnRoutes(t);
if (r && !f.ovpn_routes.value.trim())
f.ovpn_routes.value = r;
});
});
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'),
hostlist: text(v.hostlist || '', '/opt/zapret2/ipset/zapret_hosts_youtube.txt')
};
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.hostlist ].concat(hostlistPicker(e.hostlist, cfg.hostlists)),
'файлы со списком доменов, по одному в строке (хостлисты zapret), через пробел; читаются при каждой ' +
'сборке профиля — изменился список в zapret: «Применить»'),
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;
};
// "Вход" of an own server (its own dialer-proxy): what it dials through in every
// profile instead of what the kit puts in front (MY-EXIT, UPLINK, directly)
var entryOptions = function(sel) {
var cur = sel.value || sel.getAttribute('data-entry') || '';
var names = pools.map(function(p) { return p.name.value.trim().toUpperCase(); }).filter(Boolean);
var opts = [ [ '', 'вход: как обычно' ], [ 'FOREIGN', 'вход: через FOREIGN' ], [ 'RU', 'вход: через RU' ],
[ 'DIRECT', 'вход: напрямую' ] ].concat(names.map(function(n) { return [ n, 'вход: через пул ' + n ]; }));
if (cur && !opts.some(function(o) { return o[0] == cur; }))
opts.push([ cur, 'вход: ' + cur + ' (такого нет)' ]);
dom.content(sel, opts.map(function(o) { return E('option', { 'value': o[0] }, o[1]); }));
sel.value = cur;
};
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.entry = E('select', { 'class': 'cbi-input-select', 'data-entry': p['dialer-proxy'] || '',
'title': 'через что подключаться к этому серверу, во всех профилях и на телефоне: например, через FOREIGN, ' +
'если сам сервер напрямую недоступен. «Как обычно» — как остальные свои серверы' });
entryOptions(e.entry);
e.entry.addEventListener('focus', function() { entryOptions(e.entry); });
e.entry.addEventListener('mousedown', function() { entryOptions(e.entry); });
// "как обычно" is an empty value: keep the choice for the next rebuild of the list
e.entry.addEventListener('change', function() { e.entry.setAttribute('data-entry', e.entry.value); });
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]; });
if (e.entry.value)
o['dialer-proxy'] = e.entry.value;
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;
// dialer-proxy typed in the YAML: the same as the entry select
if (v['dialer-proxy']) {
e.entry.setAttribute('data-entry', v['dialer-proxy']);
e.entry.value = '';
entryOptions(e.entry);
}
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.entry,
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); });
// [MY] nodes of the subscriptions (providers <id>-my): the same "Вход" per node
// (MY_NODE_ENTRIES). The names come from the running mihomo; saved entries show
// even when it does not run.
var myNodes = [], myNodeBox = E('div', E('em', 'загружаю ноды [MY] из подписок…'));
var addMyNode = function(provider, name, entry) {
if (myNodes.some(function(n) { return n.provider == provider && n.name == name; }))
return;
var n = { provider: provider, name: name,
entry: E('select', { 'class': 'cbi-input-select', 'data-entry': entry || '' }) };
entryOptions(n.entry);
n.entry.addEventListener('focus', function() { entryOptions(n.entry); });
n.entry.addEventListener('mousedown', function() { entryOptions(n.entry); });
n.entry.addEventListener('change', function() { n.entry.setAttribute('data-entry', n.entry.value); });
myNodes.push(n);
};
String(cfg.my_node_entries || '').split('\n').forEach(function(l) {
var m = /^([^|]*)\|([^|]*)\|(.+)$/.exec(l);
if (m)
addMyNode(m[2], m[3], m[1]);
});
var drawMyNodes = function(note) {
dom.content(myNodeBox, [ note ? E('p', { 'class': 'cbi-value-description' }, note) : '' ].concat(myNodes.length
? myNodes.map(function(n) {
return E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap;margin-bottom:.3em' },
[ E('code', n.name), E('span', { 'class': 'cbi-value-description' }, n.provider), n.entry ]);
})
: [ E('em', 'нод [MY] в подписках нет') ]));
};
callApi('/providers/proxies').then(function(r) {
if (r.error)
throw new Error(r.error);
Object.keys(r.providers || {}).sort().forEach(function(pn) {
// <id>-my and <id>-my-via-<entry> (nodes with an entry already); not the chains' <id>-my@<entry>
var m = /^(.+-my)(-via-.+)?$/.exec(pn);
if (!m || pn.indexOf('@') >= 0)
return;
(r.providers[pn].proxies || []).forEach(function(p) { addMyNode(m[1], p.name, ''); });
});
drawMyNodes('');
}).catch(function() {
drawMyNodes('nikki сейчас не работает: видны только ноды, у которых вход уже задан. Запусти профиль, чтобы увидеть все.');
});
// 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 ? 'загружен; выбери файл, только чтобы заменить'
: 'профиль, который выдал администратор VPN (для OpenVPN Connect или openvpn)'),
field('Логин', f.vpn_username),
field('Пароль', f.vpn_password, 'обычный пароль, без одноразового кода'),
field('Сети через VPN', f.ovpn_routes, 'адреса, которые открываются только через VPN, CIDR через пробел. ' +
'При загрузке .ovpn подставляются его строки route; остальной трафик идёт как обычно'),
field('TOTP-секрет', f.totp_secret, 'только если VPN просит одноразовый код из приложения (Google Authenticator и т. п.): ' +
'секрет из QR-кода, строка из букв и цифр (secret=… в ссылке otpauth://). Роутер сам подставляет код при подключении'),
cfg.has_totp ? field('Без кода', f.totp_clear, 'забыть сохранённый секрет: VPN больше не просит код') : '',
field('Как отправлять код', f.pass_format, 'обычно подходит «сам»; если сервер не принимает код — попробуй другие'),
field('Адрес для проверки', f.ovpn_check_url, 'страница за VPN: её открывает кнопка «Проверить» в блоке OpenVPN ' +
'и тест задержки в дашборде (с ядром не из kit — ещё и роутер раз в ~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 (!f.ovpn_routes.value.trim())
errors.push('OpenVPN: укажи сети, которые идут через VPN');
f.ovpn_routes.value.split(/\s+/).filter(Boolean).forEach(function(n) {
if (!/^\d{1,3}(\.\d{1,3}){3}(\/\d{1,2})?$/.test(n))
errors.push('OpenVPN: сеть ' + n + ' — не IPv4-адрес или CIDR');
});
if (f.totp_secret.value.trim() && !/^[A-Za-z2-7=\s-]+$/.test(f.totp_secret.value))
errors.push('OpenVPN: TOTP-секрет — буквы A–Z и цифры 2–7 (base32)');
}
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|openvpn)$/;
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(), hostlist: e.hostlist.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 && !v.hostlist)
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)»)');
// the entry: a pool that exists and does not hold the server itself (a loop)
var en = e.entry.value, ep = poolData.filter(function(v) { return v.name.toUpperCase() == en; })[0];
if (en && !/^(FOREIGN|RU|DIRECT)$/.test(en) && !ep)
errors.push('Свой сервер ' + n + ': вход через пул ' + en + ', а такого пула нет');
else if (ep && ep.servers.split(';').map(function(x) { return x.trim(); }).indexOf(n) >= 0)
errors.push('Свой сервер ' + n + ': вход через пул ' + en + ', в который он сам входит — так нельзя');
srvLines.push(S.toLine(e.get()));
});
var nodeLines = [];
myNodes.forEach(function(n) {
var en = n.entry.value, ep = poolData.filter(function(v) { return v.name.toUpperCase() == en; })[0];
if (!en)
return;
if (!/^(FOREIGN|RU|DIRECT)$/.test(en) && !ep)
errors.push('Нода ' + n.name + ': вход через пул ' + en + ', а такого пула нет');
else if (ep && ep.subs.split(/\s+/).indexOf(n.provider) >= 0)
errors.push('Нода ' + n.name + ': вход через пул ' + en + ', который сам берёт ноды ' + n.provider + ' — так нельзя');
nodeLines.push(en + '|' + n.provider + '|' + n.name);
});
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, ''),
totp_clear: f.totp_clear.checked,
pass_format: f.pass_format.value,
ovpn_routes: f.ovpn_routes.value.trim(),
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'),
my_node_entries: nodeLines.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();
}, this));
}, this));
})
}, 'Сохранить и применить');
var put = L.bind(function(tab, children) {
dom.content(this.slots[tab].settings, section('Настройки', children));
}, this);
put('subs', [
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
]);
put('ovpn', [
field('Включить OpenVPN', f.openvpn, 'доступ к рабочей или учебной сети по файлу .ovpn, с одноразовыми кодами (TOTP) или без. ' +
'Через VPN идут только указанные сети, остальное — как обычно'),
ovpnBox
]);
put('csqtt', [
field('Включить CSQTT', f.csqtt, 'интерфейс csqtt0 от star-panel-csqtt (Службы → star-panel-csqtt). Группа UPLINK в дашборде: ' +
'DIRECT — как раньше, CSQTT — ноды подписок, BOOT и свои серверы подключаются через csqtt0 ' +
'(выход из белых списков), а MAIN/FOREIGN/MY работают поверх')
]);
put('ts', [
field('Включить Tailscale', f.tailscale, 'доступ к своей сети Tailscale (tailnet) со всех устройств за роутером'),
tsBox
]);
put('system', [
field('Облегчённый режим', f.lite, 'для роутеров с 256 МБ памяти: лимит памяти ядра (GOMEMLIMIT), ' +
'проверки нод раз в 10 минут и только при трафике, сниффер без QUIC, лог nikki — warning, без поиска процессов ' +
'(кроме CSQTT), перехват без TUN (TCP redirect, UDP tproxy). Что ещё ест память, kit напишет в журнале применения'),
field('Лимит памяти', f.lite_gomemlimit, 'GOMEMLIMIT для облегчённого режима, по умолчанию 64MiB; ' +
'слишком низкий — ядро постоянно чистит память и грузит процессор')
]);
put('phone', [
field('Конфиг для телефона', f.mobile, 'тот же обход в приложении на телефоне или компьютере (FlClash, Clash Mi и др.): ' +
'QR и ссылка появятся на этой вкладке после сохранения. Файл раздаёт роутер, только в своей сети')
]);
put('pools', [
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')
])
]);
put('rules', [
field('Торренты', f.torrent, 'через TORRENT-SEL (порты 20000-20199)'),
field('Обход для пушей', f.push, 'Apple APNs и Google FCM через группу PUSH (main/foreign — DIRECT, whitelist — MY): ' +
'уведомления не рвутся при смене ноды; выключено — пуши идут по общим правилам'),
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 и обратно. Только для этого роутера (не телефон, ' +
'при импорте не переносится)')
]);
put('servers', [
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('h4', 'Из подписок ([MY])'),
E('p', { 'class': 'cbi-value-description' }, 'Серверы, которые ты держишь в своей подписке с [MY] в имени: их настройки ' +
'приходят из подписки, но вход можно задать здесь — для каждого отдельно, как у своих серверов выше. ' +
'Нода ищется по точному имени: если в подписке её переименуют, вход перестанет действовать.'),
myNodeBox
]);
// one button for every tab: the settings are saved and applied together
dom.content(this.saveBox, E('div', { 'class': 'cbi-page-actions' }, [
E('span', { 'class': 'cbi-value-description', 'style': 'margin-right:1em' }, 'сохраняет настройки всех вкладок'), 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 = [];
// each tab: its live state and buttons (renderBody), then its settings (renderSettings)
this.slots = {};
var tabList = [ [ 'overview', 'Обзор' ], [ 'subs', 'Подписки' ], [ 'rules', 'Правила' ], [ 'servers', 'Свои серверы' ],
[ 'pools', 'Пулы и сервисы' ], [ 'ovpn', 'OpenVPN' ], [ 'ts', 'Tailscale' ], [ 'csqtt', 'CSQTT' ],
[ 'phone', 'Телефон' ], [ 'system', 'Система' ] ].map(function(t) {
var slot = this.slots[t[0]] = { status: E('div'), settings: E('div') };
return [ t[0], t[1], E('div', [ slot.status, slot.settings ]) ];
}, this);
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.saveBox = E('div');
this.renderSettingsBox();
this.renderBody(data[0]);
this.showJob(data[1]);
if (data[1].running)
this.follow();
return E([], [ E('h2', 'mihomo-kit'), tabs(tabList, 'mihomo-kit-tab'), this.saveBox, this.jobBox ]);
}
});