Improved hysteria import

This commit is contained in:
Sam Latsin 2026-10-10 12:36:49 +03:00
parent ee65368976
commit e60ea55b25

View File

@ -49,6 +49,93 @@ function field(title, el, 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;
});
}
function readFile(input) {
var f = input.files && input.files[0];
if (!f)
@ -269,6 +356,47 @@ return view.extend({
};
(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),
@ -381,7 +509,13 @@ return view.extend({
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({}); } }, 'Добавить сервер'),
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 ])
]);
},