842 lines
40 KiB
JavaScript
842 lines
40 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: { '': {} } });
|
||
// 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 callJob = rpc.declare({ object: 'mihomo-kit', method: 'job', expect: { '': {} } });
|
||
var callRun = rpc.declare({ object: 'mihomo-kit', method: 'run', params: [ 'cmd', 'arg' ], 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));
|
||
}
|
||
|
||
// 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) ] : []))
|
||
]);
|
||
}
|
||
|
||
// hysteria2 servers from pasted text: mihomo proxy YAML (block or {flow} items,
|
||
// with or without "proxies:") and/or hysteria2:// links -> form values.
|
||
// dialer-proxy and other keys are ignored: the kit sets them itself.
|
||
function parseHy2(text) {
|
||
var unquote = function(v) {
|
||
v = v.trim();
|
||
var m = v.match(/^"((?:[^"\\]|\\.)*)"/);
|
||
if (m)
|
||
return m[1].replace(/\\(.)/g, '$1');
|
||
m = v.match(/^'((?:[^']|'')*)'/);
|
||
if (m)
|
||
return m[1].replace(/''/g, "'");
|
||
return v.replace(/\s+#.*$/, '').trim();
|
||
};
|
||
var fromMap = function(o) {
|
||
if (o.type && !/^(hysteria2|hy2)$/i.test(o.type))
|
||
return null;
|
||
if (!o.server || !o.password)
|
||
return null;
|
||
return {
|
||
name: o.name || '', server: o.server, port: o.port || '443', password: o.password,
|
||
obfs_password: o['obfs-password'] || '', sni: o.sni || '',
|
||
insecure: /^(true|1|yes)$/i.test(o['skip-cert-verify'] || '') ? '1' : '0',
|
||
up: o.up || '', down: o.down || ''
|
||
};
|
||
};
|
||
var out = [], cur = null;
|
||
var flush = function() {
|
||
var h = cur && fromMap(cur);
|
||
if (h)
|
||
out.push(h);
|
||
cur = null;
|
||
};
|
||
|
||
String(text).split(/\r?\n/).forEach(function(line) {
|
||
var t = line.trim(), m;
|
||
if (!t || t.charAt(0) == '#')
|
||
return;
|
||
|
||
// hysteria2://password@host:port/?sni=..&obfs=salamander&obfs-password=..&insecure=1#name
|
||
if ((m = t.match(/^(?:hysteria2|hy2):\/\/([^@]*)@([^:\/?#]+|\[[^\]]+\]):?(\d*)[^?#]*(?:\?([^#]*))?(?:#(.*))?$/i))) {
|
||
flush();
|
||
var q = {};
|
||
(m[4] || '').split('&').forEach(function(kv) {
|
||
var i = kv.indexOf('=');
|
||
if (i > 0)
|
||
q[decodeURIComponent(kv.slice(0, i))] = decodeURIComponent(kv.slice(i + 1));
|
||
});
|
||
var h = fromMap({ name: decodeURIComponent(m[5] || ''), server: m[2].replace(/^\[|\]$/g, ''),
|
||
port: m[3], password: decodeURIComponent(m[1]), 'obfs-password': q['obfs-password'] || '',
|
||
sni: q.sni || q.peer || '', 'skip-cert-verify': q.insecure || '' });
|
||
if (h)
|
||
out.push(h);
|
||
return;
|
||
}
|
||
|
||
// - {name: a, type: hysteria2, ...}
|
||
if ((m = t.match(/^-?\s*\{(.*)\}$/))) {
|
||
flush();
|
||
cur = {};
|
||
m[1].split(',').forEach(function(kv) {
|
||
var i = kv.indexOf(':');
|
||
if (i > 0)
|
||
cur[kv.slice(0, i).trim()] = unquote(kv.slice(i + 1));
|
||
});
|
||
flush();
|
||
return;
|
||
}
|
||
|
||
// "- key: value" starts a new item, "key: value" continues it
|
||
if ((m = t.match(/^(-\s+)?([A-Za-z0-9_-]+)\s*:\s*(.*)$/))) {
|
||
if (m[1] || !cur) {
|
||
flush();
|
||
cur = {};
|
||
}
|
||
if (m[3] !== '')
|
||
cur[m[2]] = unquote(m[3]);
|
||
}
|
||
});
|
||
flush();
|
||
|
||
return out.map(function(h) {
|
||
h.name = (h.name || h.server.split('.')[0]).replace(/[^A-Za-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '') || 'hy2';
|
||
return h;
|
||
});
|
||
}
|
||
|
||
// qrcode-generator (luci/qrcode.js, installed with the page): a global "qrcode"
|
||
function loadQr() {
|
||
if (window.qrcode)
|
||
return Promise.resolve(window.qrcode);
|
||
return new Promise(function(resolve, reject) {
|
||
var s = document.createElement('script');
|
||
s.src = L.resource('mihomo-kit/qrcode.js');
|
||
s.onload = function() { resolve(window.qrcode); };
|
||
s.onerror = function() { reject(new Error('qrcode.js not loaded')); };
|
||
document.head.appendChild(s);
|
||
});
|
||
}
|
||
|
||
// one hysteria2 server from the form -> mihomo proxy YAML (parseHy2 reads it back)
|
||
function hy2Yaml(d) {
|
||
var q = function(v) { return '"' + String(v).replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"'; };
|
||
var y = [ '- name: ' + d.name, ' type: hysteria2', ' server: ' + d.server, ' port: ' + d.port,
|
||
' password: ' + q(d.password) ];
|
||
if (d.obfs_password)
|
||
y.push(' obfs: salamander', ' obfs-password: ' + q(d.obfs_password));
|
||
if (d.sni)
|
||
y.push(' sni: ' + d.sni);
|
||
if (d.insecure)
|
||
y.push(' skip-cert-verify: true');
|
||
if (d.up)
|
||
y.push(' up: ' + q(d.up));
|
||
if (d.down)
|
||
y.push(' down: ' + q(d.down));
|
||
return y.join('\n') + '\n';
|
||
}
|
||
|
||
// 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('Версия kit', [ st.kit_version || 'неизвестна (появится после «Обновить kit»)', ' ', updState ]),
|
||
row('Профиль', [ select, ' ',
|
||
this.button('Включить', 'apply', 'use', function() { return select.value; }) ])
|
||
])
|
||
]));
|
||
|
||
if (st.openvpn) {
|
||
var ovpnState = E('span', '—');
|
||
var otp = E('span', '—');
|
||
var schedInfo = E('span', '—');
|
||
var schedOn = E('input', { 'type': 'checkbox' });
|
||
var schedStart = E('input', { 'type': 'time', 'value': '09:00' });
|
||
var schedEnd = E('input', { 'type': 'time', 'value': '17:00' });
|
||
var schedFilled = false;
|
||
var ovpnCheck = function() {
|
||
dom.content(ovpnState, E('em', 'проверяю…'));
|
||
return callOvpnStatus().then(function(o) {
|
||
dom.content(ovpnState, {
|
||
up: E('strong', { 'style': 'color:green' }, 'туннель работает, ' + o.delay + ' мс'),
|
||
down: [ E('strong', { 'style': 'color:#c00' }, 'туннель не отвечает'), ' ' + (o.message || '') ],
|
||
off: 'выключен'
|
||
}[o.state] || o.state);
|
||
if (o.url)
|
||
ovpnState.appendChild(E('span', { 'class': 'cbi-value-description' }, [ ' — ', o.url ]));
|
||
dom.content(otp, o.otp ? o.otp + ' (ещё ' + o.otp_left + ' с)' : '—');
|
||
var bits = [ o.sched ? 'расписание ' + o.sched_start + '–' + o.sched_end + ' MSK' : 'расписание выключено' ];
|
||
if (o.until) bits.push('таймер ещё ' + Math.max(1, Math.round((o.until * 1000 - Date.now()) / 60000)) + ' мин');
|
||
dom.content(schedInfo, bits.join(', '));
|
||
if (!schedFilled) {
|
||
schedOn.checked = !!o.sched;
|
||
if (o.sched_start) schedStart.value = o.sched_start;
|
||
if (o.sched_end) schedEnd.value = o.sched_end;
|
||
schedFilled = true;
|
||
}
|
||
}).catch(function(e) { dom.content(ovpnState, String(e)); });
|
||
};
|
||
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('OTP сейчас', otp),
|
||
row('Режим', schedInfo)
|
||
]),
|
||
E('div', { 'class': 'cbi-page-actions' }, [
|
||
this.button('Включить', 'positive', 'ovpn-on'), ' ',
|
||
this.button('Включить на 1 ч', 'action', 'ovpn-for', '60'), ' ',
|
||
this.button('Выключить', 'negative', 'ovpn-off', null,
|
||
'Закрыть туннель? Сессия на сервере освободится в течение ~5 минут.'), ' ',
|
||
this.button('Переподключить', 'action', 'ovpn-refresh')
|
||
]),
|
||
field('Расписание (MSK)', [ schedOn, ' ', schedStart, ' – ', schedEnd, ' ',
|
||
this.button('Сохранить', 'action', 'ovpn-sched', function() {
|
||
return schedOn.checked ? schedStart.value + ' ' + schedEnd.value : 'off';
|
||
}) ],
|
||
'Туннель работает только в эти часы (±10 мин разброс). Ручное «Выключить» держится поверх расписания до «Включить». «на 1 ч» поднимает вне окна.')
|
||
]));
|
||
}
|
||
|
||
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;
|
||
var qrBox = E('div', { 'style': 'width:220px;max-width:100%;background:#fff;padding:8px;border-radius:4px' }, E('em', 'QR…'));
|
||
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)); });
|
||
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', 'FlClash → Профили → + → по ссылке (или QR) — профиль из тех же подписок и BOOT, ' +
|
||
'без OpenVPN, Tailscale и торрентов; свои серверы — через MY-EXIT.'),
|
||
E('p', [ E('a', { 'href': mobUrl, 'target': '_blank', 'rel': 'noreferrer' }, mobUrl) ]),
|
||
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 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: 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'),
|
||
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'),
|
||
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)
|
||
};
|
||
|
||
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);
|
||
|
||
// 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('div', [
|
||
E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': function() {
|
||
var yaml = hy2Yaml({ name: e.name.value.trim(), server: e.server.value.trim(), port: e.port.value.trim(),
|
||
password: e.password.value, obfs_password: e.obfs_password.value, sni: e.sni.value.trim(),
|
||
insecure: e.insecure.checked, up: e.up.value.trim(), down: e.down.value.trim() });
|
||
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', 'click': function() {
|
||
hy2List.removeChild(el);
|
||
hy2.splice(hy2.indexOf(e), 1);
|
||
} }, 'Удалить сервер')
|
||
])
|
||
]);
|
||
hy2.push(e);
|
||
hy2List.appendChild(el);
|
||
};
|
||
(cfg.hy2 || []).forEach(addHy2);
|
||
|
||
// import: paste YAML / hysteria2:// links (or load a file) -> fields
|
||
var importText = E('textarea', { 'class': 'cbi-input-textarea', 'rows': 10, 'style': 'width:100%;font-family:monospace',
|
||
'placeholder': '- name: nl-1\n type: hysteria2\n server: vpn.example.com\n port: 443\n password: ...\n\nили hysteria2://пароль@host:443/?sni=...#nl-1' });
|
||
var importFile = E('input', { 'type': 'file', 'accept': '.yaml,.yml,.txt,.conf' });
|
||
importFile.addEventListener('change', function() {
|
||
readFile(importFile).then(function(t) { importText.value = t; });
|
||
});
|
||
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 found = parseHy2(importText.value);
|
||
if (!found.length) {
|
||
ui.addNotification(null, E('p', 'Не нашёл серверов hysteria2: нужны хотя бы server и password'), 'warning');
|
||
return;
|
||
}
|
||
var added = 0, updated = 0;
|
||
found.forEach(function(h) {
|
||
var e = hy2.filter(function(x) { return x.name.value.trim() == h.name; })[0];
|
||
if (!e) {
|
||
addHy2(h);
|
||
added++;
|
||
return;
|
||
}
|
||
Object.keys(h).forEach(function(k) {
|
||
if (k == 'insecure')
|
||
e[k].checked = h[k] == '1';
|
||
else
|
||
e[k].value = h[k];
|
||
});
|
||
updated++;
|
||
});
|
||
importText.value = '';
|
||
importBox.style.display = 'none';
|
||
ui.addNotification(null, E('p', 'Импорт: добавлено ' + added + ', обновлено ' + updated +
|
||
'. Проверь поля и нажми «Сохранить и применить».'), 'info');
|
||
} }, 'Разобрать')
|
||
])
|
||
]);
|
||
|
||
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, 'что открывает проверка туннеля в дашборде (группа BMSTU); лучше внутренний ресурс')
|
||
]);
|
||
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 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_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(),
|
||
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(),
|
||
ovpn_check_url: f.ovpn_check_url.value.trim(),
|
||
ts_check_url: f.ts_check_url.value.trim(),
|
||
mobile: f.mobile.checked,
|
||
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 берёт первую живую, ' +
|
||
'через неё качаются подписки; пусто — без 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('Доп. IP через RU', f.ru_ips, 'CIDR через пробел; на main (свой белый IP) идут напрямую'),
|
||
field('OpenVPN BMSTU', f.openvpn),
|
||
ovpnBox,
|
||
field('Tailscale', f.tailscale),
|
||
tsBox,
|
||
field('Конфиг для телефона', f.mobile, 'FlClash: QR и ссылка появятся на этой странице после сохранения ' +
|
||
'(файл раздаётся роутером внутри LAN по ссылке со случайным токеном)'),
|
||
E('h4', 'Свои серверы (hysteria2)'),
|
||
E('p', { 'class': 'cbi-value-description' }, 'Собираются в группу MY (автовыбор самого быстрого, в дашборде можно закрепить один). MY — пункт в MAIN ' +
|
||
'рядом с FOREIGN. К самим серверам на whitelist — через MY-EXIT, на main — напрямую.'),
|
||
hy2List,
|
||
importBox,
|
||
E('div', [
|
||
E('button', { 'class': 'btn cbi-button cbi-button-add', 'click': function() { addHy2({}); } }, 'Добавить сервер'), ' ',
|
||
E('button', { 'class': 'btn cbi-button cbi-button-action', 'click': function() {
|
||
importBox.style.display = importBox.style.display == 'none' ? '' : 'none';
|
||
} }, 'Импорт из YAML / ссылки')
|
||
]),
|
||
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 ]);
|
||
}
|
||
});
|