458 lines
19 KiB
JavaScript
458 lines
19 KiB
JavaScript
'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: { '': {} } });
|
||
var callOvpnStatus = rpc.declare({ object: 'mihomo-kit', method: 'ovpn_status', expect: { '': {} } });
|
||
var callJob = rpc.declare({ object: 'mihomo-kit', method: 'job', expect: { '': {} } });
|
||
var callRun = rpc.declare({ object: 'mihomo-kit', method: 'run', params: [ 'cmd', 'arg' ], expect: { '': {} } });
|
||
var callConfigGet = rpc.declare({ object: 'mihomo-kit', method: 'config_get', expect: { '': {} } });
|
||
var callConfigSet = rpc.declare({ object: 'mihomo-kit', method: 'config_set', params: [ 'data' ], expect: { '': {} } });
|
||
|
||
function wait(ms) {
|
||
return new Promise(function(resolve) { window.setTimeout(resolve, ms); });
|
||
}
|
||
|
||
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));
|
||
}
|
||
|
||
// 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) ] : []))
|
||
]);
|
||
}
|
||
|
||
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 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('Версия kit', st.kit_version || 'неизвестна (появится после «Обновить kit»)'),
|
||
row('Профиль', [ select, ' ',
|
||
this.button('Включить', 'apply', 'use', function() { return select.value; }) ])
|
||
])
|
||
]));
|
||
|
||
if (st.openvpn) {
|
||
var ovpnState = E('em', 'проверяю…');
|
||
var otp = E('span', '—');
|
||
callOvpnStatus().then(function(o) {
|
||
dom.content(ovpnState, {
|
||
up: E('strong', { 'style': 'color:green' }, 'туннель работает'),
|
||
down: E('strong', { 'style': 'color:#c00' }, 'туннель не отвечает'),
|
||
off: 'выключен'
|
||
}[o.state] || o.state);
|
||
dom.content(otp, o.otp ? o.otp + ' (ещё ' + o.otp_left + ' с)' : '—');
|
||
}).catch(function(e) { dom.content(ovpnState, String(e)); });
|
||
sections.push(section('OpenVPN', [
|
||
E('table', { 'class': 'table' }, [
|
||
row('Состояние', ovpnState),
|
||
row('OTP сейчас', otp)
|
||
]),
|
||
E('div', { 'class': 'cbi-page-actions' }, [
|
||
this.button('Включить', 'positive', 'ovpn-on'), ' ',
|
||
this.button('Выключить', 'negative', 'ovpn-off', null,
|
||
'Закрыть туннель? Сессия на сервере освободится в течение ~5 минут.'), ' ',
|
||
this.button('Переподключить', 'action', 'ovpn-refresh')
|
||
])
|
||
]));
|
||
}
|
||
|
||
if (st.tailscale)
|
||
sections.push(section('Tailscale', [
|
||
E('table', { 'class': 'table' }, [
|
||
row('Нода', st.ts_logged_in ? 'вошла в аккаунт' : E('strong', 'не вошла'))
|
||
]),
|
||
E('div', { 'class': 'cbi-page-actions' }, st.ts_logged_in
|
||
? [ this.button('Войти заново', 'negative', 'ts-relogin', null,
|
||
'Удалить ключ ноды и войти заново? Нода получит новый адрес 100.x.') ]
|
||
: [ this.button('Получить ссылку для входа', 'positive', 'ts-login') ])
|
||
]));
|
||
|
||
sections.push(section('Обслуживание', [
|
||
E('table', { 'class': 'table' }, [
|
||
row(this.button('Пересобрать профили', 'action', 'build'),
|
||
'profiles.d/*.env → profiles/*.yaml (применится после «Включить» профиль)'),
|
||
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 callConfigGet().then(L.bind(this.renderSettings, this));
|
||
dom.content(this.settingsBox, [ E('h3', 'Настройка'), E('button', {
|
||
'class': 'btn cbi-button cbi-button-action',
|
||
'click': ui.createHandlerFn(this, function() { return this.renderSettingsBox(true); })
|
||
}, 'Изменить настройки') ]);
|
||
return Promise.resolve();
|
||
},
|
||
|
||
renderSettings: function(cfg) {
|
||
var subList = E('div'), subs = [];
|
||
var hwidBox = E('div'), ovpnBox = E('div'), tsBox = E('div');
|
||
|
||
var f = {
|
||
boot: text(cfg.boot_link, 'vless://…'),
|
||
hwid_ua: text(cfg.hwid_ua), hwid_os: text(cfg.hwid_os), hwid_os_ver: text(cfg.hwid_os_ver),
|
||
hwid_model: text(cfg.hwid_model), hwid_id: text(cfg.hwid_id),
|
||
torrent: check(cfg.torrent),
|
||
ru_ips: text(cfg.ru_ips, '1.2.3.4/32 5.6.0.0/16'),
|
||
openvpn: check(cfg.openvpn),
|
||
ovpn: E('input', { 'type': 'file', 'accept': '.ovpn,.conf' }),
|
||
vpn_username: text(cfg.vpn_username),
|
||
vpn_password: text('', cfg.has_vpn_password ? 'сохранён — пусто, чтобы не менять' : '', 'password'),
|
||
totp_secret: text('', cfg.has_totp ? 'сохранён — пусто, чтобы не менять' : 'base32 из QR', 'password'),
|
||
tailscale: check(cfg.tailscale),
|
||
ts_hostname: text(cfg.ts_hostname),
|
||
ts_domains: text(cfg.ts_domains, 'corp.example.com')
|
||
};
|
||
|
||
var update = function() {
|
||
hwidBox.style.display = subs.some(function(s) { return s.hwid.checked; }) ? '' : 'none';
|
||
ovpnBox.style.display = f.openvpn.checked ? '' : 'none';
|
||
tsBox.style.display = f.tailscale.checked ? '' : 'none';
|
||
};
|
||
|
||
var addSub = function(s) {
|
||
var vias = [ 'BOOT', 'DIRECT' ];
|
||
if (s.via && vias.indexOf(s.via) < 0)
|
||
vias.push(s.via);
|
||
var entry = {
|
||
url: E('input', { 'type': 'text', 'class': 'cbi-input-text', 'style': 'flex:1;min-width:16em',
|
||
'value': s.url || '', 'placeholder': 'https://…' }),
|
||
via: E('select', { 'class': 'cbi-input-select' }, vias.map(function(v) { return E('option', { 'value': v }, v); })),
|
||
hwid: check(s.hwid)
|
||
};
|
||
entry.via.value = s.via || 'BOOT';
|
||
entry.hwid.addEventListener('change', update);
|
||
var el = E('div', { 'style': 'display:flex;gap:.5em;align-items:center;flex-wrap:wrap;margin-bottom:.4em' }, [
|
||
entry.url, E('code', { 'title': 'имя провайдера' }, s.id || 'новая'), 'через', entry.via,
|
||
E('label', [ entry.hwid, ' HWID' ]),
|
||
E('button', { 'class': 'btn cbi-button cbi-button-remove', 'click': function() {
|
||
subList.removeChild(el);
|
||
subs.splice(subs.indexOf(entry), 1);
|
||
update();
|
||
} }, '✕')
|
||
]);
|
||
subs.push(entry);
|
||
subList.appendChild(el);
|
||
};
|
||
(cfg.subs && cfg.subs.length ? cfg.subs : [ {} ]).forEach(addSub);
|
||
|
||
// own hysteria2 servers: one block of fields each
|
||
var hy2List = E('div'), hy2 = [];
|
||
var addHy2 = function(h) {
|
||
var e = {
|
||
name: text(h.name, 'nl-1'),
|
||
server: text(h.server, 'vpn.example.com'),
|
||
port: text(h.port || '443'),
|
||
password: text(h.password, '', 'password'),
|
||
obfs_password: text(h.obfs_password, 'пусто — без obfs', 'password'),
|
||
sni: text(h.sni, 'пусто — как server'),
|
||
insecure: check(h.insecure == '1'),
|
||
up: text(h.up, '50 mbps'),
|
||
down: text(h.down, '100 mbps')
|
||
};
|
||
var el = E('div', { 'style': 'border:1px solid #8884;border-radius:4px;padding:.5em;margin-bottom:.5em' }, [
|
||
field('Имя', e.name, 'буквы, цифры, _ - ; так сервер виден в дашборде'),
|
||
field('Сервер', e.server),
|
||
field('Порт', e.port),
|
||
field('Пароль', e.password, 'auth.password на сервере'),
|
||
field('Obfs-пароль', e.obfs_password, 'salamander; пусто — без obfs'),
|
||
field('SNI', e.sni),
|
||
field('Не проверять сертификат', e.insecure, 'для самоподписанного сертификата (SNI чужого сайта)'),
|
||
field('Up / Down', [ e.up, e.down ], 'реальный потолок канала клиента; пусто — без ограничения'),
|
||
E('button', { 'class': 'btn cbi-button cbi-button-remove', 'click': function() {
|
||
hy2List.removeChild(el);
|
||
hy2.splice(hy2.indexOf(e), 1);
|
||
} }, 'Удалить сервер')
|
||
]);
|
||
hy2.push(e);
|
||
hy2List.appendChild(el);
|
||
};
|
||
(cfg.hy2 || []).forEach(addHy2);
|
||
|
||
dom.content(hwidBox, [
|
||
E('h4', 'HWID (общий для подписок с галкой HWID)'),
|
||
field('User-Agent', f.hwid_ua),
|
||
field('x-device-os', f.hwid_os),
|
||
field('x-ver-os', f.hwid_os_ver),
|
||
field('x-device-model', f.hwid_model),
|
||
field('x-hwid', f.hwid_id, 'если провайдер уже знает устройство — оставь тот же')
|
||
]);
|
||
dom.content(ovpnBox, [
|
||
field('Файл .ovpn', f.ovpn, cfg.ovpn_file ? 'загружен; выбери файл, только чтобы заменить' : 'ещё не загружен'),
|
||
field('Логин', f.vpn_username),
|
||
field('Пароль (без OTP)', f.vpn_password),
|
||
field('TOTP-секрет', f.totp_secret)
|
||
]);
|
||
dom.content(tsBox, [
|
||
field('Имя ноды', f.ts_hostname),
|
||
field('Split-DNS домены', f.ts_domains, 'домены тейлнета кроме *.ts.net, через пробел')
|
||
]);
|
||
f.openvpn.addEventListener('change', update);
|
||
f.tailscale.addEventListener('change', update);
|
||
update();
|
||
|
||
var save = E('button', {
|
||
'class': 'btn cbi-button cbi-button-save',
|
||
'click': ui.createHandlerFn(this, function() {
|
||
var list = subs.map(function(s) {
|
||
return { url: s.url.value.trim(), via: s.via.value, hwid: s.hwid.checked };
|
||
}).filter(function(s) { return s.url; });
|
||
var errors = [];
|
||
if (!list.length)
|
||
errors.push('нужна хотя бы одна подписка');
|
||
if (f.boot.value.trim() && !/^vless:\/\//.test(f.boot.value.trim()))
|
||
errors.push('BOOT: нужна ссылка vless://');
|
||
if (f.openvpn.checked) {
|
||
if (!cfg.ovpn_file && !f.ovpn.files.length)
|
||
errors.push('OpenVPN: выбери файл .ovpn');
|
||
if (!f.vpn_username.value.trim())
|
||
errors.push('OpenVPN: нужен логин');
|
||
if (!cfg.has_vpn_password && !f.vpn_password.value)
|
||
errors.push('OpenVPN: нужен пароль');
|
||
if (!cfg.has_totp && !f.totp_secret.value.trim())
|
||
errors.push('OpenVPN: нужен TOTP-секрет');
|
||
}
|
||
var names = {};
|
||
var hy2Data = hy2.map(function(e) {
|
||
var d = {};
|
||
Object.keys(e).forEach(function(k) {
|
||
d[k] = k == 'insecure' ? e[k].checked : (k == 'password' || k == 'obfs_password' ? e[k].value : e[k].value.trim());
|
||
});
|
||
if (!/^[A-Za-z0-9_-]+$/.test(d.name))
|
||
errors.push('Свой сервер: имя «' + d.name + '» — только буквы, цифры, _ -');
|
||
else if (names[d.name.toUpperCase().replace(/-/g, '_')])
|
||
errors.push('Свой сервер: имя ' + d.name + ' повторяется');
|
||
names[d.name.toUpperCase().replace(/-/g, '_')] = true;
|
||
if (!d.server || !/^[0-9]+$/.test(d.port) || !d.password)
|
||
errors.push('Свой сервер ' + (d.name || '?') + ': нужны сервер, порт и пароль');
|
||
return d;
|
||
});
|
||
if (errors.length) {
|
||
ui.addNotification(null, errors.map(function(e) { return E('p', e); }), 'danger');
|
||
return;
|
||
}
|
||
return readFile(f.ovpn).then(L.bind(function(ovpn) {
|
||
return callConfigSet({
|
||
boot_link: f.boot.value.trim(),
|
||
subs: list,
|
||
hwid_ua: f.hwid_ua.value, hwid_os: f.hwid_os.value, hwid_os_ver: f.hwid_os_ver.value,
|
||
hwid_model: f.hwid_model.value, hwid_id: f.hwid_id.value,
|
||
torrent: f.torrent.checked,
|
||
ru_ips: f.ru_ips.value.trim(),
|
||
openvpn: f.openvpn.checked,
|
||
ovpn: ovpn,
|
||
vpn_username: f.vpn_username.value.trim(),
|
||
vpn_password: f.vpn_password.value,
|
||
totp_secret: f.totp_secret.value.replace(/\s+/g, ''),
|
||
tailscale: f.tailscale.checked,
|
||
ts_hostname: f.ts_hostname.value.trim(),
|
||
ts_domains: f.ts_domains.value.trim(),
|
||
hy2: hy2Data
|
||
});
|
||
}, this)).then(L.bind(function(r) {
|
||
if (r.error) {
|
||
ui.addNotification(null, E('p', r.error), 'danger');
|
||
return;
|
||
}
|
||
return this.follow().then(L.bind(function(j) {
|
||
if (j && j.rc === 0)
|
||
return this.renderSettingsBox(false);
|
||
}, this));
|
||
}, this));
|
||
})
|
||
}, 'Сохранить и применить');
|
||
|
||
dom.content(this.settingsBox, [
|
||
E('h3', 'Настройка'),
|
||
field('BOOT', f.boot, 'vless-ссылка seed-ноды, через неё качаются подписки; пусто — без BOOT'),
|
||
field('Подписки', [ subList, E('button', {
|
||
'class': 'btn cbi-button cbi-button-add',
|
||
'click': function() { addSub({}); update(); }
|
||
}, 'Добавить подписку') ], 'Имя провайдера берётся из домена (sub.kittyvpn.com → kittyvpn), ' +
|
||
'настройки привязаны к нему; задать своё: имя=https://…. HWID — для подписок с лимитом устройств.'),
|
||
hwidBox,
|
||
field('Торренты', f.torrent, 'через TORRENT-SEL (порты 20000-20199)'),
|
||
field('Доп. IP через RU', f.ru_ips, 'CIDR через пробел'),
|
||
field('OpenVPN BMSTU', f.openvpn),
|
||
ovpnBox,
|
||
field('Tailscale', f.tailscale),
|
||
tsBox,
|
||
E('h4', 'Свои серверы (hysteria2)'),
|
||
E('p', { 'class': 'cbi-value-description' }, 'Появляются в группе MAIN рядом с FOREIGN (и в TS-EXIT) — ' +
|
||
'выбираются вручную в дашборде, в автовыборе не участвуют. На профиле street идут через FOREIGN-ноду, на home — напрямую.'),
|
||
hy2List,
|
||
E('button', { 'class': 'btn cbi-button cbi-button-add', 'click': function() { addHy2({}); } }, 'Добавить сервер'),
|
||
E('div', { 'class': 'cbi-page-actions' }, [ save ])
|
||
]);
|
||
},
|
||
|
||
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 ]);
|
||
}
|
||
});
|