mihomo-kit/luci/servers.js

1716 lines
55 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

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.

// Own servers of the kit (LuCI "Свои серверы"): share links, YAML, WireGuard / AmneziaWG
// .conf and AmneziaVPN keys (vpn://) -> mihomo proxy objects, and one stored line per
// server (/etc/nikki/my-servers, see mihomo-kit.sh).
// parseLinks is a port of mihomo's common/convert (ConvertsV2Ray) so a link gives the
// same proxy as in a subscription; tools/test.sh checks it against the Go converter.
// Browser: a global "mkServers" (loaded like qrcode.js); node: module.exports.
(function (root, factory) {
var api = factory();
if (typeof module === 'object' && module.exports)
module.exports = api;
else
root.mkServers = api;
})(this, function () {
'use strict';
// mihomo puts a random browser User-Agent into ws headers; a fixed one here
var USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36';
// --- base64 as Go's encoding/base64 (strict alphabets, \r \n skipped) -------------
var STD = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var URLSAFE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
// -> byte array or null; padded: '=' required to a multiple of 4, else forbidden
function b64(s, alphabet, padded) {
s = String(s).replace(/[\r\n]/g, '');
var body = s;
if (padded) {
if (s.length % 4)
return null;
var p = s.indexOf('=');
if (p >= 0) {
if (!/^={1,2}$/.test(s.slice(p)) || s.length - p > 2)
return null;
body = s.slice(0, p);
if ((body.length + (s.length - p)) % 4)
return null;
}
} else if (s.indexOf('=') >= 0) {
return null;
}
if (body.length % 4 == 1)
return null;
var out = [], bits = 0, acc = 0;
for (var i = 0; i < body.length; i++) {
var v = alphabet.indexOf(body.charAt(i));
if (v < 0)
return null;
acc = (acc << 6) | v;
bits += 6;
if (bits >= 8) {
bits -= 8;
out.push((acc >> bits) & 0xff);
}
}
// Go rejects non-zero trailing bits
if (bits && (acc & ((1 << bits) - 1)))
return null;
return out;
}
function utf8(bytes) {
var s = '';
for (var i = 0; i < bytes.length; i++)
s += '%' + ('0' + bytes[i].toString(16)).slice(-2);
try {
return decodeURIComponent(s);
} catch (e) {
// invalid UTF-8: one char per byte (Go keeps the bytes, a string can't)
return bytes.map(function (b) { return String.fromCharCode(b); }).join('');
}
}
// tryDecodeBase64: RawStdEncoding, then StdEncoding
function tryDecodeBase64(s) {
var r = b64(s, STD, false);
if (r === null)
r = b64(s, STD, true);
return r === null ? null : utf8(r);
}
function decodeBase64(s) {
var r = tryDecodeBase64(s);
return r === null ? s : r;
}
// TryDecodeBase64 (util.go): by length, std then url-safe
function tryDecodeBase64Str(s) {
var r = s.length % 4 == 0 ? (b64(s, STD, true) || b64(s, URLSAFE, true))
: (b64(s, STD, false) || b64(s, URLSAFE, false));
return r === null ? null : utf8(r);
}
function decodeUrlSafe(s) {
var r = b64(s, URLSAFE, false);
return r === null ? '' : utf8(r);
}
function urlSafe(s) {
return s.replace(/\+/g, '-').replace(/\//g, '_');
}
// --- net/url as in Go ------------------------------------------------------------
// unescape: '+' -> ' ' only in query mode; a bad %-escape -> null
function unescape(s, query) {
if (/%(?![0-9A-Fa-f]{2})/.test(s))
return null;
if (query)
s = s.replace(/\+/g, ' ');
try {
return decodeURIComponent(s);
} catch (e) {
// valid escapes but not UTF-8: per byte
return s.replace(/%([0-9A-Fa-f]{2})/g, function (_, h) { return String.fromCharCode(parseInt(h, 16)); });
}
}
// escaping of userinfo as Go's url.User(...).String() (encodeUserPassword): letters,
// digits, - _ . ~ and $ & + , ; = stay, the rest is %XX of the UTF-8 bytes
function escapeUser(s) {
return encodeURIComponent(s)
.replace(/%(24|26|2B|2C|3B|3D)/g, function (_, h) { return String.fromCharCode(parseInt(h, 16)); })
.replace(/[!'()*]/g, function (c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase(); });
}
// ParseQuery: '&'-separated; pairs with ';' or a bad escape are dropped (Go errors
// on them and url.Query() ignores the error)
function parseQuery(raw) {
var q = {};
String(raw || '').split('&').forEach(function (kv) {
if (!kv || kv.indexOf(';') >= 0)
return;
var i = kv.indexOf('='), k = i < 0 ? kv : kv.slice(0, i), v = i < 0 ? '' : kv.slice(i + 1);
k = unescape(k, true);
v = unescape(v, true);
if (k === null || v === null)
return;
(q[k] = q[k] || []).push(v);
});
return {
get: function (k) { return q[k] ? q[k][0] : ''; },
all: function (k) { return q[k] || []; },
has: function (k) { return !!q[k]; }
};
}
// url.Parse for scheme://[userinfo@]host[:port][/path][?query][#fragment]; null on error
function parseURL(s) {
var u = { fragment: '', rawQuery: '', path: '', user: null, host: '' };
// Go: "invalid control character in URL"
if (/[\x00-\x1f\x7f]/.test(s))
return null;
var h = s.indexOf('#');
if (h >= 0) {
u.fragment = unescape(s.slice(h + 1), false);
if (u.fragment === null)
return null;
s = s.slice(0, h);
}
var q = s.indexOf('?');
if (q >= 0) {
u.rawQuery = s.slice(q + 1);
s = s.slice(0, q);
}
var m = s.match(/^([A-Za-z][A-Za-z0-9+.-]*):\/\/(.*)$/);
if (!m)
return null;
u.scheme = m[1].toLowerCase();
var rest = m[2], slash = rest.indexOf('/');
var auth = slash < 0 ? rest : rest.slice(0, slash);
u.path = slash < 0 ? '' : rest.slice(slash);
var at = auth.lastIndexOf('@');
if (at >= 0) {
var ui = auth.slice(0, at), c = ui.indexOf(':');
// Go's validUserinfo
if (!/^[A-Za-z0-9\-._:~!$&'()*+,;=%@]*$/.test(ui))
return null;
var name = unescape(c < 0 ? ui : ui.slice(0, c), false);
var pass = c < 0 ? null : unescape(ui.slice(c + 1), false);
if (name === null || (c >= 0 && pass === null))
return null;
u.user = { username: name, password: pass };
auth = auth.slice(at + 1);
}
// Go's host check: ASCII only letters, digits and -_.~!$&'()*+,;=:[]<>"%
if (/[\x00-\x7f]/.test(auth) && !/^(?:[A-Za-z0-9\-_.~!$&'()*+,;=:\[\]<>"%]|[^\x00-\x7f])*$/.test(auth))
return null;
// host[:port] or [v6][:port]; the port must be digits
var hm = auth.match(/^(\[[^\]]*\]|[^:]*)(?::(.*))?$/);
if (!hm || (hm[2] !== undefined && !/^[0-9]*$/.test(hm[2])))
return null;
if (auth.indexOf(':') >= 0 && auth.charAt(0) != '[' && auth.indexOf(':') != auth.lastIndexOf(':'))
return null;
u.host = unescape(auth, false);
if (u.host === null)
return null;
u.hostname = hm[1].replace(/^\[|\]$/g, '');
u.port = hm[2] || '';
u.query = parseQuery(u.rawQuery);
u.userString = function () {
if (!u.user)
return '';
return escapeUser(u.user.username) + (u.user.password === null ? '' : ':' + escapeUser(u.user.password));
};
return u;
}
// strconv.ParseBool, error -> false
function parseBool(s) {
return /^(1|t|T|TRUE|true|True)$/.test(s);
}
function splitList(s) {
return s.split(',');
}
// shadowsocks methods mihomo accepts (stand-in for VerifyMethod)
var SS_METHODS = /^(none|plain|dummy|rc4-md5|aes-(128|192|256)-(gcm|cfb|ctr)|chacha20(-ietf)?(-poly1305)?|xchacha20(-ietf-poly1305)?|aes-(128|256)-ccm|2022-blake3-(aes-128-gcm|aes-256-gcm|chacha20-poly1305)|aegis-(128l|256)|lea-(128|192|256)-gcm|rabbit128-poly1305)$/;
function uniqueName(names, name) {
if (Object.prototype.hasOwnProperty.call(names, name)) {
names[name]++;
var i = names[name];
return name + '-' + (i < 10 ? '0' + i : i);
}
names[name] = 0;
return name;
}
function handleVShareLink(names, url, scheme, proxy) {
var query = url.query;
proxy.name = uniqueName(names, url.fragment);
if (url.hostname === '')
return 'url.Hostname() is empty';
if (url.port === '')
return 'url.Port() is empty';
proxy.type = scheme;
proxy.server = url.hostname;
proxy.port = url.port;
proxy.uuid = url.user ? url.user.username : '';
proxy.udp = true;
var tls = query.get('security').toLowerCase();
if (/tls$/.test(tls) || tls == 'reality') {
proxy.tls = true;
proxy['client-fingerprint'] = query.get('fp') || 'chrome';
if (query.get('alpn'))
proxy.alpn = splitList(query.get('alpn'));
if (query.get('pcs'))
proxy.fingerprint = query.get('pcs');
}
if (query.get('sni'))
proxy.servername = query.get('sni');
if (query.get('pbk')) {
var reality = { 'public-key': query.get('pbk'), 'short-id': query.get('sid') };
var ml = query.get('support-x25519mlkem768');
if (ml && /^(1|t|T|TRUE|true|True|0|f|F|FALSE|false|False)$/.test(ml))
reality['support-x25519mlkem768'] = parseBool(ml);
proxy['reality-opts'] = reality;
}
switch (query.get('packetEncoding')) {
case 'none':
break;
case 'packet':
proxy['packet-addr'] = true;
break;
default:
proxy.xudp = true;
}
var network = query.get('type').toLowerCase() || 'tcp';
var fakeType = query.get('headerType').toLowerCase();
if (network == 'tcp' && fakeType == 'http')
network = 'http';
else if (network == 'http')
network = 'h2';
proxy.network = network;
switch (network) {
case 'http':
var headers = {}, httpOpts = { path: [ '/' ] };
if (query.get('host'))
headers.Host = [ query.get('host') ];
if (query.get('method'))
httpOpts.method = query.get('method');
if (query.get('path'))
httpOpts.path = [ query.get('path') ];
httpOpts.headers = headers;
proxy['http-opts'] = httpOpts;
break;
case 'h2':
var h2 = { path: query.get('path') || '/' };
if (query.get('host'))
h2.host = [ query.get('host') ];
proxy['h2-opts'] = h2;
break;
case 'ws':
case 'httpupgrade':
var ws = { path: query.get('path'), headers: { 'User-Agent': USER_AGENT, Host: query.get('host') } };
if (network == 'httpupgrade') {
proxy.network = 'ws';
ws['v2ray-http-upgrade'] = true;
}
if (query.get('ed')) {
if (!/^[+-]?[0-9]+$/.test(query.get('ed')))
return 'bad WebSocket max early data size';
if (network == 'ws') {
ws['max-early-data'] = parseInt(query.get('ed'), 10);
ws['early-data-header-name'] = 'Sec-WebSocket-Protocol';
} else {
ws['v2ray-http-upgrade-fast-open'] = true;
}
}
if (query.get('eh'))
ws['early-data-header-name'] = query.get('eh');
proxy['ws-opts'] = ws;
break;
case 'grpc':
proxy['grpc-opts'] = { 'grpc-service-name': query.get('serviceName') };
break;
case 'xhttp':
var x = {};
if (query.get('path'))
x.path = query.get('path');
if (query.get('host'))
x.host = query.get('host');
if (query.get('mode'))
x.mode = query.get('mode');
if (query.get('extra')) {
var extra = null;
try { extra = JSON.parse(query.get('extra')); } catch (e) {}
if (extra && typeof extra == 'object' && !Array.isArray(extra))
parseXHTTPExtra(extra, x);
}
proxy['xhttp-opts'] = x;
break;
}
return null;
}
var isStr = function (v) { return typeof v == 'string'; };
var isNum = function (v) { return typeof v == 'number'; };
var isObj = function (v) { return v && typeof v == 'object' && !Array.isArray(v); };
var trunc = function (v) { return v < 0 ? Math.ceil(v) : Math.floor(v); };
function parseXHTTPExtra(extra, opts) {
var xmuxToReuse = function (xmux) {
var reuse = {};
var set = function (src, dst) {
var v = xmux[src];
if (isStr(v) && v !== '')
reuse[dst] = v;
else if (isNum(v))
reuse[dst] = String(trunc(v));
};
set('maxConnections', 'max-connections');
set('maxConcurrency', 'max-concurrency');
set('cMaxReuseTimes', 'c-max-reuse-times');
set('hMaxRequestTimes', 'h-max-request-times');
set('hMaxReusableSecs', 'h-max-reusable-secs');
if (isNum(xmux.hKeepAlivePeriod))
reuse['h-keep-alive-period'] = trunc(xmux.hKeepAlivePeriod);
return reuse;
};
var str = function (src, dst) {
if (isStr(extra[src]) && extra[src] !== '') {
opts[dst] = extra[src];
return true;
}
return false;
};
var int = function (src, dst) {
if (isNum(extra[src]))
opts[dst] = trunc(extra[src]);
};
if (isObj(extra.headers) && Object.keys(extra.headers).length)
opts.headers = extra.headers;
if (extra.noGRPCHeader === true)
opts['no-grpc-header'] = true;
str('xPaddingBytes', 'x-padding-bytes');
if (typeof extra.xPaddingObfsMode == 'boolean')
opts['x-padding-obfs-mode'] = extra.xPaddingObfsMode;
str('xPaddingKey', 'x-padding-key');
str('xPaddingHeader', 'x-padding-header');
str('xPaddingPlacement', 'x-padding-placement');
str('xPaddingMethod', 'x-padding-method');
str('uplinkHTTPMethod', 'uplink-http-method');
str('sessionIDPlacement', 'session-placement') || str('sessionPlacement', 'session-placement');
str('sessionIDKey', 'session-key') || str('sessionKey', 'session-key');
str('sessionIDTable', 'session-table');
if (!str('sessionIDLength', 'session-length') && isNum(extra.sessionIDLength))
opts['session-length'] = String(trunc(extra.sessionIDLength));
str('seqPlacement', 'seq-placement');
str('seqKey', 'seq-key');
str('uplinkDataPlacement', 'uplink-data-placement');
str('uplinkDataKey', 'uplink-data-key');
int('uplinkChunkSize', 'uplink-chunk-size');
int('scMaxEachPostBytes', 'sc-max-each-post-bytes');
int('scMinPostsIntervalMs', 'sc-min-posts-interval-ms');
if (isObj(extra.xmux) && Object.keys(extra.xmux).length) {
var reuse = xmuxToReuse(extra.xmux);
if (Object.keys(reuse).length)
opts['reuse-settings'] = reuse;
}
if (isObj(extra.downloadSettings)) {
var dsAny = extra.downloadSettings, ds = {};
if (isStr(dsAny.address) && dsAny.address !== '')
ds.server = dsAny.address;
if (isNum(dsAny.port))
ds.port = trunc(dsAny.port);
var sec = isStr(dsAny.security) ? dsAny.security.toLowerCase() : '';
if (sec == 'tls' || sec == 'reality') {
ds.tls = true;
var t = dsAny.tlsSettings;
if (isObj(t)) {
if (isStr(t.serverName) && t.serverName !== '')
ds.servername = t.serverName;
if (isStr(t.fingerprint) && t.fingerprint !== '')
ds['client-fingerprint'] = t.fingerprint;
if (Array.isArray(t.alpn) && t.alpn.length) {
var alpn = t.alpn.filter(isStr);
if (alpn.length)
ds.alpn = alpn;
}
if (t.allowInsecure === true)
ds['skip-cert-verify'] = true;
}
if (sec == 'reality' && isObj(dsAny.realitySettings)) {
var r = dsAny.realitySettings, ro = {};
if (isStr(r.publicKey) && r.publicKey !== '')
ro['public-key'] = r.publicKey;
if (isStr(r.shortId) && r.shortId !== '')
ro['short-id'] = r.shortId;
if (Object.keys(ro).length)
ds['reality-opts'] = ro;
}
}
var xs = dsAny.xhttpSettings;
if (isObj(xs)) {
if (isStr(xs.path) && xs.path !== '')
ds.path = xs.path;
if (isStr(xs.host) && xs.host !== '')
ds.host = xs.host;
if (isObj(xs.headers) && Object.keys(xs.headers).length)
ds.headers = xs.headers;
if (isObj(xs.extra) && isObj(xs.extra.xmux) && Object.keys(xs.extra.xmux).length) {
var dr = xmuxToReuse(xs.extra.xmux);
if (Object.keys(dr).length)
ds['reuse-settings'] = dr;
}
}
if (Object.keys(ds).length)
opts['download-settings'] = ds;
}
}
function buildRealmOpts(serverURL, token, realmID, stun) {
var o = { enable: true, 'server-url': serverURL };
if (token)
o.token = token;
if (realmID)
o['realm-id'] = realmID;
if (stun.length)
o['stun-servers'] = stun;
return o;
}
function splitHysteria2Ports(line) {
var i = line.indexOf('://');
if (i < 0)
return [ line, '' ];
var head = line.slice(0, i + 3), rest = line.slice(i + 3), auth = rest, tail = '';
var j = rest.search(/[\/?#]/);
if (j >= 0) {
auth = rest.slice(0, j);
tail = rest.slice(j);
}
var userinfo = '', at = auth.lastIndexOf('@');
if (at >= 0) {
userinfo = auth.slice(0, at + 1);
auth = auth.slice(at + 1);
}
if (auth.indexOf(']') >= 0)
return [ line, '' ];
var colon = auth.lastIndexOf(':');
if (colon < 0)
return [ line, '' ];
var host = auth.slice(0, colon), ports = auth.slice(colon + 1);
if (!/[,-]/.test(ports))
return [ line, '' ];
var first = ports.slice(0, ports.search(/[,-]/));
if (first === '')
return [ line, '' ];
return [ head + userinfo + host + ':' + first + tail, ports ];
}
// ConvertsV2Ray: share links (or a base64 subscription of them) -> proxy objects
function parseLinks(text) {
var data = decodeBase64(String(text));
var proxies = [], names = {};
data.split('\n').forEach(function (raw) {
var line = raw.replace(/[ \r]+$/, '');
if (!line)
return;
var cut = line.indexOf('://');
if (cut < 0)
return;
var scheme = line.slice(0, cut).toLowerCase(), body = line.slice(cut + 3);
var u, q, p;
switch (scheme) {
case 'hysteria':
if (!(u = parseURL(line)))
return;
q = u.query;
p = { name: uniqueName(names, u.fragment), type: scheme, server: u.hostname, port: u.port,
sni: q.get('peer'), obfs: q.get('obfs') };
if (q.get('alpn'))
p.alpn = splitList(q.get('alpn'));
p.auth_str = q.get('auth');
p.protocol = q.get('protocol');
p.down = q.get('down') || q.get('downmbps');
p.up = q.get('up') || q.get('upmbps');
p['skip-cert-verify'] = parseBool(q.get('insecure'));
proxies.push(p);
return;
case 'hysteria2':
case 'hy2':
case 'hysteria2+realm':
case 'hy2+realm':
var realm = /\+realm$/.test(scheme), hop = splitHysteria2Ports(line);
if (!(u = parseURL(hop[0])))
return;
q = u.query;
p = { name: uniqueName(names, u.fragment), type: 'hysteria2', server: u.hostname, port: u.port || '443' };
if (hop[1])
p.ports = hop[1];
p.obfs = q.get('obfs');
p['obfs-password'] = q.get('obfs-password');
p.sni = q.get('sni');
p['skip-cert-verify'] = parseBool(q.get('insecure'));
if (q.get('alpn'))
p.alpn = splitList(q.get('alpn'));
p.fingerprint = q.get('pinSHA256');
p.down = q.get('down');
p.up = q.get('up');
if (realm) {
var token = unescape(u.userString(), false) || '';
var realmID = unescape(u.path.replace(/^\//, ''), false) || '';
p['realm-opts'] = buildRealmOpts('https://' + u.host, token, realmID, q.all('stun'));
if (q.get('auth'))
p.password = q.get('auth');
} else if (u.userString()) {
p.password = u.userString();
}
proxies.push(p);
return;
case 'tuic':
if (!(u = parseURL(line)))
return;
q = u.query;
p = { name: uniqueName(names, u.fragment), type: scheme, server: u.hostname, port: u.port, udp: true };
if (u.user && u.user.password !== null) {
p.uuid = u.user.username;
p.password = u.user.password;
} else {
p.token = u.user ? u.user.username : '';
}
if (q.get('congestion_control'))
p['congestion-controller'] = q.get('congestion_control');
if (q.get('alpn'))
p.alpn = splitList(q.get('alpn'));
if (q.get('sni'))
p.sni = q.get('sni');
if (q.get('disable_sni') == '1')
p['disable-sni'] = true;
if (q.get('udp_relay_mode'))
p['udp-relay-mode'] = q.get('udp_relay_mode');
proxies.push(p);
return;
case 'trojan':
if (!(u = parseURL(line)))
return;
q = u.query;
p = { name: uniqueName(names, u.fragment), type: scheme, server: u.hostname, port: u.port,
password: u.user ? u.user.username : '', udp: true,
'skip-cert-verify': parseBool(q.get('allowInsecure')) };
if (q.get('sni'))
p.sni = q.get('sni');
if (q.get('alpn'))
p.alpn = splitList(q.get('alpn'));
var net = q.get('type').toLowerCase();
if (net)
p.network = net;
if (net == 'ws' || net == 'httpupgrade') {
p['ws-opts'] = { path: q.get('path'), headers: { 'User-Agent': USER_AGENT } };
if (net == 'httpupgrade') {
p.network = 'ws';
p['ws-opts']['v2ray-http-upgrade'] = true;
}
}
else if (net == 'grpc')
p['grpc-opts'] = { 'grpc-service-name': q.get('serviceName') };
p['client-fingerprint'] = q.get('fp') || 'chrome';
if (q.get('pcs'))
p.fingerprint = q.get('pcs');
proxies.push(p);
return;
case 'vless':
if (!(u = parseURL(line)))
return;
var dh = tryDecodeBase64(u.host);
if (dh !== null) {
// Go re-reads hostname/port from the decoded host
u.host = dh;
var dm = dh.match(/^(\[[^\]]*\]|[^:]*)(?::(.*))?$/);
u.hostname = dm ? dm[1].replace(/^\[|\]$/g, '') : dh;
u.port = dm && dm[2] && /^[0-9]+$/.test(dm[2]) ? dm[2] : '';
}
p = {};
if (handleVShareLink(names, u, scheme, p))
return;
if (u.query.get('flow'))
p.flow = u.query.get('flow').toLowerCase();
if (u.query.get('encryption'))
p.encryption = u.query.get('encryption');
proxies.push(p);
return;
case 'vmess':
var dc = tryDecodeBase64(body);
if (dc === null) {
// Xray VMessAEAD share link
if (!(u = parseURL(line)))
return;
p = {};
if (handleVShareLink(names, u, scheme, p))
return;
p.alterId = 0;
p.cipher = u.query.get('encryption') || 'auto';
proxies.push(p);
return;
}
var v;
try { v = JSON.parse(dc); } catch (e) { return; }
if (!isObj(v) || !isStr(v.ps))
return;
p = { name: uniqueName(names, v.ps), type: scheme, server: v.add, port: v.port, uuid: v.id,
alterId: 'aid' in v ? v.aid : 0, udp: true, xudp: true, tls: false, 'skip-cert-verify': false,
cipher: isStr(v.scy) && v.scy !== '' ? v.scy : 'auto' };
if (isStr(v.sni) && v.sni !== '')
p.servername = v.sni;
var network = '';
if (isStr(v.net)) {
network = v.net.toLowerCase();
if (v.type === 'http')
network = 'http';
else if (network == 'http')
network = 'h2';
p.network = network;
}
if (isStr(v.tls)) {
if (/tls$/.test(v.tls.toLowerCase()))
p.tls = true;
if (isStr(v.alpn))
p.alpn = splitList(v.alpn);
}
var host = isStr(v.host) && v.host !== '' ? v.host : '';
var path = isStr(v.path) && v.path !== '' ? v.path : '';
switch (network) {
case 'http':
p['http-opts'] = { path: [ path || '/' ], headers: host ? { Host: [ host ] } : {} };
break;
case 'h2':
p['h2-opts'] = { path: path || '/' };
if (host)
p['h2-opts'].host = [ host ];
break;
case 'ws':
case 'httpupgrade':
var wo = { path: '/' }, hd = {};
if (network == 'httpupgrade') {
p.network = 'ws';
wo['v2ray-http-upgrade'] = true;
}
if (host)
hd.Host = host;
if (path) {
var pu = parseURL('x://h' + (path.charAt(0) == '/' ? '' : '/') + path);
var pq = pu && pu.rawQuery !== '' ? pu.query : null;
if (pu && pq && pq.get('ed') && /^[+-]?[0-9]+$/.test(pq.get('ed'))) {
if (network == 'ws') {
wo['max-early-data'] = parseInt(pq.get('ed'), 10);
wo['early-data-header-name'] = 'Sec-WebSocket-Protocol';
} else {
wo['v2ray-http-upgrade-fast-open'] = true;
}
path = vmessPathWithoutEd(path);
}
if (pu && pq && pq.get('eh'))
wo['early-data-header-name'] = pq.get('eh');
wo.path = path;
}
wo.headers = hd;
p['ws-opts'] = wo;
break;
case 'grpc':
p['grpc-opts'] = { 'grpc-service-name': v.path };
break;
}
proxies.push(p);
return;
case 'ss':
if (!(u = parseURL(line)))
return;
var ssName = uniqueName(names, u.fragment);
if (u.port === '') {
var hb = b64(u.host, STD, false);
if (hb === null || !(u = parseURL('ss://' + utf8(hb))))
return;
}
var cipherRaw = u.user ? u.user.username : '', cipher = cipherRaw, password;
if (u.user && u.user.password !== null) {
password = u.user.password;
} else {
var bb = b64(cipherRaw, URLSAFE, false) || b64(cipherRaw, STD, true) || [];
var cp = utf8(bb), ci = cp.indexOf(':');
if (ci < 0)
return;
cipher = cp.slice(0, ci);
password = cp.slice(ci + 1);
if (!SS_METHODS.test(cipher)) {
cp = utf8(b64(cipherRaw, STD, false) || []);
ci = cp.indexOf(':');
cipher = ci < 0 ? cp : cp.slice(0, ci);
password = ci < 0 ? '' : cp.slice(ci + 1);
}
}
q = u.query;
p = { name: ssName, type: scheme, server: u.hostname, port: u.port, cipher: cipher, password: password, udp: true };
if (q.get('udp-over-tcp') == 'true' || q.get('uot') == '1')
p['udp-over-tcp'] = true;
var plugin = q.get('plugin');
if (plugin.indexOf(';') >= 0) {
var pi = parseQuery('pluginName=' + plugin.replace(/;/g, '&'));
var pn = pi.get('pluginName');
if (pn.indexOf('obfs') >= 0) {
p.plugin = 'obfs';
p['plugin-opts'] = { mode: pi.get('obfs'), host: pi.get('obfs-host') };
} else if (pn.indexOf('v2ray-plugin') >= 0) {
p.plugin = 'v2ray-plugin';
p['plugin-opts'] = { mode: pi.get('mode') || pi.get('obfs'), host: pi.get('host') || pi.get('obfs-host'),
path: pi.get('path'), tls: plugin.indexOf('tls') >= 0 };
}
}
proxies.push(p);
return;
case 'ssr':
var sd = tryDecodeBase64Str(body);
if (sd === null)
return;
var qi = sd.indexOf('/?');
if (qi < 0)
return;
var before = sd.slice(0, qi).split(':');
if (before.length != 6)
return;
var sq = parseQuery(urlSafe(sd.slice(qi + 2)));
p = { name: uniqueName(names, decodeUrlSafe(sq.get('remarks'))), type: scheme, server: before[0],
port: before[1], cipher: before[3], password: decodeUrlSafe(urlSafe(before[5])),
obfs: before[4], protocol: before[2], udp: true };
if (decodeUrlSafe(sq.get('obfsparam')))
p['obfs-param'] = decodeUrlSafe(sq.get('obfsparam'));
if (decodeUrlSafe(sq.get('protoparam')))
p['protocol-param'] = decodeUrlSafe(sq.get('protoparam'));
proxies.push(p);
return;
case 'socks':
case 'socks5':
case 'socks5h':
case 'http':
case 'https':
if (!(u = parseURL(line)) || !u.hostname || !u.port)
return;
var user = '', pw = '', enc = u.userString();
if (enc) {
var parts = decodeBase64(enc).split(':');
user = parts[0];
if (parts.length == 2)
pw = parts[1];
}
p = { name: uniqueName(names, u.fragment || u.hostname + ':' + u.port),
type: /^socks/.test(scheme) ? 'socks5' : 'http', server: u.hostname, port: u.port,
username: user, password: pw, 'skip-cert-verify': true };
if (scheme == 'https')
p.tls = true;
proxies.push(p);
return;
case 'anytls':
if (!(u = parseURL(line)) || !u.hostname || !u.port)
return;
var au = u.user ? u.user.username : '';
var ap = u.user && u.user.password !== null ? u.user.password : au;
q = u.query;
proxies.push({ name: uniqueName(names, u.fragment || u.hostname + ':' + u.port), type: 'anytls',
server: u.hostname, port: u.port, username: au, password: ap, sni: q.get('sni'),
fingerprint: q.get('hpkp'), 'skip-cert-verify': q.get('insecure') == '1', udp: true });
return;
case 'mierus':
if (!(u = parseURL(line)) || !u.hostname)
return;
q = u.query;
var base = u.fragment || q.get('profile') || u.hostname;
var ports = q.all('port'), protos = q.all('protocol');
if (!ports.length || ports.length != protos.length)
return;
ports.forEach(function (port, i) {
var m = { name: uniqueName(names, base + ':' + port + '/' + protos[i]), type: 'mieru',
server: u.hostname, transport: protos[i], udp: true,
username: u.user ? u.user.username : '', password: u.user && u.user.password !== null ? u.user.password : '' };
if (port.indexOf('-') >= 0)
m['port-range'] = port;
else if (/^[+-]?[0-9]+$/.test(port))
m.port = parseInt(port, 10);
else
return;
if (q.get('multiplexing'))
m.multiplexing = q.get('multiplexing');
if (q.get('handshake-mode'))
m['handshake-mode'] = q.get('handshake-mode');
if (q.get('traffic-pattern'))
m['traffic-pattern'] = q.get('traffic-pattern');
proxies.push(m);
});
return;
}
});
return proxies;
}
// vmess ws path: the "ed" parameter dropped, the rest re-encoded like Go's
// query.Encode() (keys sorted)
function vmessPathWithoutEd(path) {
var qi = path.indexOf('?');
var base = path.slice(0, qi), raw = path.slice(qi + 1), h = raw.indexOf('#'), frag = '';
if (h >= 0) {
frag = raw.slice(h);
raw = raw.slice(0, h);
}
var pairs = [];
raw.split('&').forEach(function (kv) {
if (!kv || kv.indexOf(';') >= 0)
return;
var i = kv.indexOf('='), k = unescape(i < 0 ? kv : kv.slice(0, i), true), v = unescape(i < 0 ? '' : kv.slice(i + 1), true);
if (k !== null && v !== null && k != 'ed')
pairs.push([ k, v ]);
});
var esc = function (s) {
return encodeURIComponent(s).replace(/%20/g, '+').replace(/[!'()*]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase();
});
};
pairs.sort(function (a, b) { return a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0; });
var enc = pairs.map(function (kv) { return esc(kv[0]) + '=' + esc(kv[1]); }).join('&');
return base + (enc ? '?' + enc : '') + frag;
}
// --- YAML: the subset proxy configs use ----------------------------------------
// Block mappings and sequences, flow {..} and [..] (also over several lines),
// plain / 'single' / "double" scalars, comments, | and > blocks. Scalars resolve as
// go-yaml v3 does for the common cases (bool, null, int, float, else string).
// No anchors, aliases, tags or multiple documents.
function yamlError(msg, line) {
var e = new Error((line ? 'строка ' + line + ': ' : '') + msg);
e.yaml = true;
return e;
}
function resolvePlain(s) {
if (/^(null|Null|NULL|~|)$/.test(s))
return null;
if (/^(true|True|TRUE)$/.test(s))
return true;
if (/^(false|False|FALSE)$/.test(s))
return false;
if (/^[-+]?[0-9]+$/.test(s) && Math.abs(Number(s)) <= Number.MAX_SAFE_INTEGER)
return parseInt(s, 10);
if (/^0x[0-9a-fA-F]+$/.test(s))
return parseInt(s.slice(2), 16);
if (/^0o[0-7]+$/.test(s))
return parseInt(s.slice(2), 8);
if (/^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$/.test(s))
return parseFloat(s);
if (/^[-+]?\.(inf|Inf|INF)$/.test(s))
return s.charAt(0) == '-' ? -Infinity : Infinity;
if (/^\.(nan|NaN|NAN)$/.test(s))
return NaN;
return s;
}
var DQ_ESC = { '0': '\0', 'a': '\x07', 'b': '\b', 't': '\t', '\t': '\t', 'n': '\n', 'v': '\x0b', 'f': '\f',
'r': '\r', 'e': '\x1b', ' ': ' ', '"': '"', '/': '/', '\\': '\\', 'N': '\x85', '_': '\xa0',
'L': '\u2028', 'P': '\u2029' };
// a scanner over one (possibly joined) text: quoted scalars and flow collections
function Scanner(text, line) {
this.s = text;
this.i = 0;
this.line = line;
}
Scanner.prototype = {
ws: function () {
while (this.i < this.s.length && /[ \t\n]/.test(this.s.charAt(this.i)))
this.i++;
// a comment runs to the end of its line
if (this.s.charAt(this.i) == '#' && (this.i == 0 || /[ \t\n]/.test(this.s.charAt(this.i - 1)))) {
while (this.i < this.s.length && this.s.charAt(this.i) != '\n')
this.i++;
this.ws();
}
},
peek: function () { return this.s.charAt(this.i); },
fail: function (msg) { throw yamlError(msg, this.line); },
quoted: function () {
// escapes go in as placeholders: line folding applies to the source breaks only
var q = this.s.charAt(this.i++), out = '', esc = [];
var put = function (c) {
out += String.fromCharCode(0xe000 + esc.length);
esc.push(c);
};
var done = function () {
return foldQuoted(out).replace(/[\ue000-\uf8ff]/g, function (c) { return esc[c.charCodeAt(0) - 0xe000]; });
};
for (;;) {
if (this.i >= this.s.length)
this.fail('незакрытая кавычка');
var c = this.s.charAt(this.i++);
if (q == "'") {
if (c == "'") {
if (this.s.charAt(this.i) == "'") {
put("'");
this.i++;
continue;
}
return done();
}
out += c;
continue;
}
if (c == '"')
return done();
if (c != '\\') {
out += c;
continue;
}
var e = this.s.charAt(this.i++), n;
if (e == '\n') {
// escaped line break: joined without a space
while (/[ \t]/.test(this.s.charAt(this.i)))
this.i++;
out += '\u0001';
continue;
}
if (DQ_ESC.hasOwnProperty(e)) {
put(DQ_ESC[e]);
continue;
}
n = { x: 2, u: 4, U: 8 }[e];
if (!n || !/^[0-9a-fA-F]+$/.test(this.s.substr(this.i, n)) || this.s.substr(this.i, n).length != n)
this.fail('неверное экранирование \\' + e);
put(String.fromCodePoint(parseInt(this.s.substr(this.i, n), 16)));
this.i += n;
}
},
// a plain scalar in flow context: up to , ] } or ": "
plain: function () {
var start = this.i;
while (this.i < this.s.length) {
var c = this.s.charAt(this.i);
if (c == ',' || c == ']' || c == '}' || c == '\n')
break;
// ":" ends a key (and a value) only before a space, , ] } or the end
if (c == ':' && (this.i + 1 == this.s.length || /[ ,\]}\n]/.test(this.s.charAt(this.i + 1))))
break;
if (c == '#' && /[ \t]/.test(this.s.charAt(this.i - 1)))
break;
this.i++;
}
return this.s.slice(start, this.i).trim();
},
node: function () {
this.ws();
var c = this.peek();
if (c == '{')
return this.map();
if (c == '[')
return this.seq();
if (c == '"' || c == "'")
return this.quoted();
if (c == '&' || c == '*' || c == '!')
this.fail('якоря, ссылки и теги не поддерживаются');
return resolvePlain(this.plain());
},
key: function () {
this.ws();
var c = this.peek();
if (c == '"' || c == "'")
return this.quoted();
return this.plain();
},
map: function () {
var o = {};
this.i++;
for (;;) {
this.ws();
if (this.peek() == '}') {
this.i++;
return o;
}
var k = this.key();
this.ws();
var v = null;
if (this.peek() == ':') {
this.i++;
this.ws();
if (this.peek() != ',' && this.peek() != '}')
v = this.node();
}
o[String(k)] = v;
this.ws();
if (this.peek() == ',')
this.i++;
else if (this.peek() != '}')
this.fail('ожидалась , или }');
}
},
seq: function () {
var a = [];
this.i++;
for (;;) {
this.ws();
if (this.peek() == ']') {
this.i++;
return a;
}
a.push(this.node());
this.ws();
if (this.peek() == ',')
this.i++;
else if (this.peek() != ']')
this.fail('ожидалась , или ]');
}
}
};
// line folding of a quoted scalar over several lines: a break -> space, empty lines -> \n
function foldQuoted(s) {
if (s.indexOf('\n') < 0)
return s.replace(/\u0001/g, '');
var parts = s.split('\n'), out = parts[0].replace(/[ \t]+$/, '');
for (var i = 1; i < parts.length; i++) {
var p = parts[i].replace(/^[ \t]+/, '');
if (i < parts.length - 1)
p = p.replace(/[ \t]+$/, '');
if (p === '' && i < parts.length - 1)
out += '\n';
else
out += (/\n$/.test(out) || /\u0001$/.test(out) ? '' : ' ') + p;
}
return out.replace(/\u0001/g, '');
}
function yamlLoad(text) {
var src = String(text).replace(/\r\n?/g, '\n').replace(/^\ufeff/, '').split('\n');
var lines = [];
src.forEach(function (raw, n) {
if (/^\t/.test(raw))
throw yamlError('табуляция в отступе', n + 1);
var t = raw.replace(/^ +/, '');
if (t === '' || t.charAt(0) == '#' || /^(---|\.\.\.)(\s|$)/.test(t))
return lines.push({ indent: -1, text: '', n: n + 1, raw: raw });
lines.push({ indent: raw.length - t.length, text: t.replace(/[ \t]+$/, ''), n: n + 1, raw: raw });
});
var pos = 0;
var skip = function () {
while (pos < lines.length && lines[pos].indent < 0)
pos++;
};
var cur = function () {
skip();
return pos < lines.length ? lines[pos] : null;
};
// "key: rest" of a block mapping line -> [key, rest] or null
var splitKey = function (t, n) {
var key, rest;
if (t.charAt(0) == '"' || t.charAt(0) == "'") {
var sc = new Scanner(t, n);
key = sc.quoted();
rest = t.slice(sc.i);
if (!/^:( |$)/.test(rest))
return null;
return [ key, rest.slice(1).replace(/^ +/, '') ];
}
if (/^[\[{&*!|>%@`]/.test(t))
return null;
var m = t.match(/^([^#]*?)\s*:(?: +(.*)|$)/);
if (!m || / #/.test(m[1]))
return null;
return [ m[1], m[2] === undefined ? '' : m[2] ];
};
// an inline value (after "key: " or "- "): flow, quoted, block scalar or plain;
// a flow / quoted value may continue on the following lines
var inline = function (rest, line, parentIndent) {
var c = rest.charAt(0);
if (c == '|' || c == '>') {
var m = rest.match(/^([|>])([+-]?)\s*(#.*)?$/);
if (!m)
throw yamlError('неподдерживаемый блочный скаляр', line.n);
return blockScalar(m[1], m[2], parentIndent);
}
if (c == '{' || c == '[' || c == '"' || c == "'") {
var text = rest, sc;
for (;;) {
sc = new Scanner(text, line.n);
try {
var v = sc.node();
sc.ws();
if (sc.i < sc.s.length)
throw yamlError('лишнее после значения: ' + sc.s.slice(sc.i, sc.i + 20), line.n);
return v;
} catch (e) {
// unbalanced: take the next line in
var nx = pos < lines.length ? lines[pos] : null;
if (!nx || !/незакрыт|ожидалась/.test(e.message) || sc.i < sc.s.length)
throw e;
text += '\n' + (nx.indent < 0 ? '' : nx.raw);
pos++;
}
}
}
if (c == '&' || c == '*' || c == '!')
throw yamlError('якоря, ссылки и теги не поддерживаются', line.n);
var plain = rest.replace(/\s+#.*$/, '');
// a plain scalar may continue on more indented lines
for (;;) {
var nl = cur();
if (!nl || nl.indent <= parentIndent || /^- |^-$/.test(nl.text) || splitKey(nl.text, nl.n))
break;
plain += ' ' + nl.text.replace(/\s+#.*$/, '');
pos++;
}
return resolvePlain(plain);
};
var blockScalar = function (style, chomp, parentIndent) {
var body = [], ind = -1;
while (pos < lines.length) {
var l = lines[pos], lead = l.raw.length - l.raw.replace(/^ +/, '').length;
if (l.raw.trim() !== '' && lead <= parentIndent)
break;
if (l.raw.trim() !== '' && ind < 0)
ind = lead;
body.push(l.raw);
pos++;
}
body = body.map(function (r) { return ind < 0 ? '' : r.slice(ind); });
var trail = 0;
while (body.length && body[body.length - 1].trim() === '') {
body.pop();
trail++;
}
var s;
if (style == '|')
s = body.join('\n');
else {
// folding: a break between two plain lines -> space, n empty lines -> n
// breaks; around more indented lines the breaks stay
s = '';
var empty = 0, prev = null;
body.forEach(function (r) {
if (r === '') {
empty++;
return;
}
if (prev !== null) {
var keep = /^\s/.test(r) || /^\s/.test(prev);
s += empty ? new Array(empty + (keep ? 2 : 1)).join('\n') : keep ? '\n' : ' ';
}
s += r;
prev = r;
empty = 0;
});
}
if (chomp == '-' || !body.length)
return s;
return s + (chomp == '+' ? new Array(trail + 2).join('\n') : '\n');
};
var node = function (indent) {
var l = cur();
if (!l || l.indent < indent)
return null;
if (/^-( |$)/.test(l.text))
return seq(l.indent);
if (splitKey(l.text, l.n))
return map(l.indent);
pos++;
return inline(l.text, l, l.indent - 1);
};
var seq = function (indent) {
var a = [];
for (;;) {
var l = cur();
if (!l || l.indent != indent || !/^-( |$)/.test(l.text))
return a;
var rest = l.text.replace(/^- */, '');
if (rest === '') {
pos++;
var nx = cur();
a.push(nx && nx.indent > indent ? node(nx.indent) : null);
continue;
}
// "- key: v" / "- - x": the rest is a node at the column after "- "
var col = indent + (l.text.length - rest.length);
if (/^-( |$)/.test(rest) || splitKey(rest, l.n)) {
lines[pos] = { indent: col, text: rest, n: l.n, raw: new Array(col + 1).join(' ') + rest };
a.push(node(col));
continue;
}
pos++;
a.push(inline(rest, l, indent));
}
};
var map = function (indent) {
var o = {};
for (;;) {
var l = cur();
if (!l || l.indent != indent)
return o;
var kv = splitKey(l.text, l.n);
if (!kv)
throw yamlError('ожидалось «ключ: значение»: ' + l.text.slice(0, 30), l.n);
pos++;
var v;
if (kv[1] === '' || /^#/.test(kv[1])) {
var nx = cur();
if (nx && nx.indent > indent)
v = node(nx.indent);
else if (nx && nx.indent == indent && /^-( |$)/.test(nx.text))
v = seq(indent);
else
v = null;
} else {
v = inline(kv[1], l, indent);
}
o[String(kv[0])] = v;
}
};
var l0 = cur();
if (!l0)
return null;
var doc = node(l0.indent);
var extra = cur();
if (extra)
throw yamlError('не разобрано: ' + extra.text.slice(0, 30), extra.n);
return doc;
}
// block YAML of a proxy (for editing); strings quoted only where needed
function yamlDump(v, indent) {
indent = indent || '';
var scalar = function (x) {
if (x === null || x === undefined)
return 'null';
if (typeof x == 'boolean' || typeof x == 'number')
return String(x);
x = String(x);
if (x === '' || resolvePlain(x) !== x || /^[\s\-?:,\[\]{}#&*!|>'"%@`]|[\s:]$|: | #|[\x00-\x1f"\\]/.test(x))
return JSON.stringify(x);
return x;
};
if (Array.isArray(v)) {
if (!v.length)
return '[]';
return v.map(function (x) {
if (isObj(x) && Object.keys(x).length)
return indent + '- ' + yamlDump(x, indent + ' ').replace(/^\s+/, '');
return indent + '- ' + (Array.isArray(x) || isObj(x) ? yamlDump(x, indent + ' ').trim() : scalar(x));
}).join('\n');
}
if (isObj(v)) {
var keys = Object.keys(v);
if (!keys.length)
return '{}';
return keys.map(function (k) {
var x = v[k], kk = scalar(k);
if ((Array.isArray(x) && x.length) || (isObj(x) && Object.keys(x).length))
return indent + kk + ':\n' + yamlDump(x, indent + ' ');
return indent + kk + ': ' + (Array.isArray(x) ? '[]' : isObj(x) ? '{}' : scalar(x));
}).join('\n');
}
return indent + scalar(v);
}
// --- WireGuard / AmneziaWG: .conf files and AmneziaVPN keys (vpn://) -------------
// zlib inflate (RFC 1950/1951) as zlib's puff.c: byte array -> byte array, throws
var LBASE = [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115,
131, 163, 195, 227, 258 ];
var LEXT = [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 ];
var DBASE = [ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 ];
var DEXT = [ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 ];
var CLORDER = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
// canonical Huffman code of the code lengths: count of codes per length, symbols in order
function huffman(lengths) {
var count = [], offs = [ 0, 0 ], sym = [], i;
for (i = 0; i < 16; i++)
count[i] = 0;
lengths.forEach(function (l) { count[l]++; });
for (i = 1; i < 15; i++)
offs[i + 1] = offs[i] + count[i];
lengths.forEach(function (l, s) {
if (l)
sym[offs[l]++] = s;
});
return { count: count, sym: sym };
}
function inflate(data) {
if (data.length < 2 || (data[0] & 0x0f) != 8 || ((data[0] << 8) | data[1]) % 31)
throw new Error('not zlib');
var pos = 2, bitbuf = 0, bitcnt = 0, out = [], fixed = null, i;
var bits = function (n) {
var v = bitbuf;
while (bitcnt < n) {
if (pos >= data.length)
throw new Error('truncated');
v |= data[pos++] << bitcnt;
bitcnt += 8;
}
bitbuf = v >>> n;
bitcnt -= n;
return v & ((1 << n) - 1);
};
var decode = function (h) {
for (var len = 1, code = 0, first = 0, index = 0; len < 16; len++) {
code |= bits(1);
if (code - h.count[len] < first)
return h.sym[index + code - first];
index += h.count[len];
first = (first + h.count[len]) << 1;
code <<= 1;
}
throw new Error('bad code');
};
var codes = function (lit, dist) {
for (;;) {
var s = decode(lit);
if (s < 256) {
out.push(s);
continue;
}
if (s == 256)
return;
if ((s -= 257) >= 29)
throw new Error('bad length');
var len = LBASE[s] + bits(LEXT[s]);
if ((s = decode(dist)) >= 30)
throw new Error('bad distance');
var d = DBASE[s] + bits(DEXT[s]);
if (d > out.length)
throw new Error('distance too far');
while (len--)
out.push(out[out.length - d]);
}
};
for (var last = 0; !last;) {
last = bits(1);
var type = bits(2);
if (type == 0) {
bitbuf = bitcnt = 0;
var n = data[pos] | data[pos + 1] << 8;
if (pos + 4 + n > data.length || (n ^ (data[pos + 2] | data[pos + 3] << 8)) != 0xffff)
throw new Error('bad stored block');
for (pos += 4; n--;)
out.push(data[pos++]);
} else if (type == 1) {
if (!fixed) {
var l = [];
for (i = 0; i < 288; i++)
l[i] = i < 144 ? 8 : i < 256 ? 9 : i < 280 ? 7 : 8;
fixed = [ huffman(l), huffman(l.slice(0, 30).map(function () { return 5; })) ];
}
codes(fixed[0], fixed[1]);
} else if (type == 2) {
var nlen = bits(5) + 257, ndist = bits(5) + 1, ncode = bits(4) + 4, lengths = [];
for (i = 0; i < 19; i++)
lengths[i] = 0;
for (i = 0; i < ncode; i++)
lengths[CLORDER[i]] = bits(3);
var lencode = huffman(lengths);
for (lengths = []; lengths.length < nlen + ndist;) {
var sym = decode(lencode), rep, prev = 0;
if (sym < 16) {
lengths.push(sym);
continue;
}
if (sym == 16) {
if (!lengths.length)
throw new Error('repeat with no length');
prev = lengths[lengths.length - 1];
rep = 3 + bits(2);
} else {
rep = sym == 17 ? 3 + bits(3) : 11 + bits(7);
}
while (rep--)
lengths.push(prev);
}
if (lengths.length > nlen + ndist)
throw new Error('too many lengths');
codes(huffman(lengths.slice(0, nlen)), huffman(lengths.slice(nlen)));
} else {
throw new Error('bad block type');
}
}
return out;
}
// AmneziaWG keys of [Interface] (lower case) -> amnezia-wg-option of mihomo
var AWG = { jc: 'jc', jmin: 'jmin', jmax: 'jmax', s1: 's1', s2: 's2', s3: 's3', s4: 's4',
h1: 'h1', h2: 'h2', h3: 'h3', h4: 'h4', i1: 'i1', i2: 'i2', i3: 'i3', i4: 'i4', i5: 'i5',
j1: 'j1', j2: 'j2', j3: 'j3', itime: 'itime' };
// AmneziaWG 3: mihomo needs "version: 3" with them
var AWG3 = { headerprotectionkey: 'header-protection-key', contentpaddingaddition: 'content-padding-addition',
rekeyaftertime: 'rekey-after-time', rekeytimeout: 'rekey-timeout', rejectaftertime: 'reject-after-time',
keepalivetimeout: 'keepalive-timeout', maxhandshakeattempts: 'max-handshake-attempts',
randomtrailers: 'random-trailers', disablecookies: 'disable-cookies' };
// [Interface] and the first [Peer] (keys in lower case) -> a wireguard proxy in the
// simplified syntax (one peer; AllowedIPs and DNS dropped: routing and DNS are the kit's)
function wgProxy(iface, peer, name) {
var need = function (v, what) {
if (!v)
throw new Error('нет ' + what);
return v;
};
var ep = need(peer.endpoint, 'Endpoint в [Peer]');
var m = /^\[([^\]]+)\]:([0-9]+)$/.exec(ep) || /^([^:\[\]]+):([0-9]+)$/.exec(ep);
if (!m)
throw new Error('Endpoint ' + ep + ': нужно адрес:порт');
var p = { name: name || m[1], type: 'wireguard', server: m[1], port: +m[2] };
need(iface.address, 'Address в [Interface]').split(',').forEach(function (a) {
a = a.trim();
var v6 = a.indexOf(':') >= 0, k = v6 ? 'ipv6' : 'ip';
if (a && !p[k])
p[k] = a.replace(v6 ? /\/128$/ : /\/32$/, '');
});
p['private-key'] = need(iface.privatekey, 'PrivateKey в [Interface]');
p['public-key'] = need(peer.publickey, 'PublicKey в [Peer]');
if (peer.presharedkey)
p['pre-shared-key'] = peer.presharedkey;
if (/^[0-9]+$/.test(iface.mtu || ''))
p.mtu = +iface.mtu;
// AmneziaWG 3 gives a range ("25-35"): mihomo takes one number
m = /^([0-9]+)(-[0-9]+)?$/.exec(peer.persistentkeepalive || '');
if (m && +m[1])
p['persistent-keepalive'] = +m[1];
p.udp = true;
var awg = {}, keys = Object.keys(iface).filter(function (k) { return (AWG[k] || AWG3[k]) && iface[k] !== ''; });
if (keys.some(function (k) { return AWG3[k]; }))
awg.version = 3;
keys.forEach(function (k) {
var v = iface[k];
if (k == 'randomtrailers' || k == 'disablecookies')
v = /^(1|true|on|yes)$/i.test(v);
else if (/^[0-9]+$/.test(v))
v = +v;
awg[AWG[k] || AWG3[k]] = v;
});
if (keys.length)
p['amnezia-wg-option'] = awg;
return p;
}
// a wg-quick / AmneziaWG .conf -> proxy (name: default name), throws
function parseConf(text, name) {
var iface = null, peers = [], sec = null;
String(text).split(/\r?\n/).forEach(function (l) {
l = l.replace(/#.*/, '').trim();
var m = /^\[\s*(\w+)\s*\]$/.exec(l), i = l.indexOf('=');
if (m) {
m = m[1].toLowerCase();
sec = m == 'interface' ? (iface = iface || {}) : m == 'peer' ? (peers[peers.length] = {}) : null;
} else if (sec && i > 0) {
sec[l.slice(0, i).trim().toLowerCase()] = l.slice(i + 1).trim();
}
});
if (!iface || !peers.length)
throw new Error('нужны секции [Interface] и [Peer]');
if (peers.length > 1)
throw new Error('несколько [Peer]: поддерживается один');
return wgProxy(iface, peers[0], name);
}
// an AmneziaVPN key: "vpn://" + base64url of qCompress(JSON) (4-byte length + zlib) or
// of the JSON itself; its AmneziaWG / WireGuard containers -> { servers, errors }
function parseAmnezia(line) {
var r = { servers: [], errors: [] }, o = null;
var raw = b64(urlSafe(line.trim().replace(/^vpn:\/\//i, '').replace(/[\s=]/g, '')), URLSAFE, false);
if (raw) {
try {
o = JSON.parse(utf8(inflate(raw.slice(4))));
} catch (e) {
try {
o = JSON.parse(utf8(raw));
} catch (e2) {}
}
}
if (!isObj(o)) {
r.errors.push('vpn://: не похоже на ключ AmneziaVPN');
return r;
}
if (o.api_key || o.auth_data) {
r.errors.push('vpn://: ключ Amnezia Free / Premium — в нём доступ к их API, а не сервер. ' +
'Нужен ключ своего сервера (AmneziaWG) или его .conf');
return r;
}
var other = [];
(Array.isArray(o.containers) ? o.containers : []).forEach(function (c) {
var proto = isObj(c) && (c.awg || c.wireguard), last = null;
if (!isObj(proto)) {
other.push(isObj(c) && c.container || '?');
return;
}
try {
last = JSON.parse(proto.last_config);
} catch (e) {}
if (!isObj(last)) {
r.errors.push('vpn://: ' + c.container + ' без настроек клиента (last_config)');
return;
}
var name = o.description || o.hostName;
try {
var p;
if (last.config) {
p = parseConf(last.config, name);
} else {
// no wg config text: the same from the fields (AWG ones are named as in it)
var iface = { address: last.client_ip, privatekey: last.client_priv_key };
Object.keys(last).forEach(function (k) {
if (AWG[k.toLowerCase()] || AWG3[k.toLowerCase()])
iface[k.toLowerCase()] = String(last[k]);
});
p = wgProxy(iface, { endpoint: (last.hostName || o.hostName) + ':' + (last.port || proto.port),
publickey: last.server_pub_key, presharedkey: last.psk_key,
persistentkeepalive: String(last.persistent_keep_alive || '') }, name);
}
// the client sets MTU from the key, not from the config text
if (!p.mtu && /^[0-9]+$/.test(String(last.mtu || '')))
p.mtu = +last.mtu;
r.servers.push(p);
} catch (e) {
r.errors.push('vpn://: ' + c.container + ': ' + e.message);
}
});
if (!r.servers.length && !r.errors.length)
r.errors.push('vpn://: нет AmneziaWG / WireGuard' + (other.length ? ' (есть: ' + other.join(', ') +
'; для Xray возьми vless://-ссылку)' : ''));
return r;
}
// --- servers of the form ---------------------------------------------------------
var LINK = /^\s*[A-Za-z][A-Za-z0-9+.-]*:\/\//;
var VPN = /^\s*vpn:\/\//i;
var CONF = /^\s*\[\s*Interface\s*\]\s*$/im;
// pasted text: share links, AmneziaVPN keys (vpn://) and/or mihomo YAML (a "proxies:"
// list, a list, one proxy) or WireGuard / AmneziaWG .conf; name: default name of a
// .conf (the file name) -> { servers: [...], errors: [...] }
function parseText(text, name) {
var links = [], keys = [], rest = [], errors = [];
String(text).split(/\r?\n/).forEach(function (l) {
(VPN.test(l) ? keys : LINK.test(l) ? links : rest).push(l);
});
var servers = links.length ? parseLinks(links.join('\n')) : [];
if (links.length && servers.length < links.length)
errors.push('не разобрано ссылок: ' + (links.length - servers.length) + ' из ' + links.length);
keys.forEach(function (l) {
var r = parseAmnezia(l);
servers = servers.concat(r.servers);
errors = errors.concat(r.errors);
});
var y = rest.join('\n');
if (CONF.test(y)) {
// .conf: one per [Interface] (several files pasted one after another)
y.split(/^(?=\s*\[\s*Interface\s*\]\s*$)/im).forEach(function (c) {
if (!CONF.test(c))
return;
try {
servers.push(parseConf(c, name));
} catch (e) {
errors.push('.conf: ' + e.message);
}
});
} else if (y.trim()) {
var doc = null, list = [];
try {
doc = yamlLoad(y);
} catch (e) {
// one base64 subscription blob
var fromB64 = /^[A-Za-z0-9+\/=_\-\s]+$/.test(y.trim()) ? parseLinks(y.trim()) : [];
if (fromB64.length)
servers = servers.concat(fromB64);
else
errors.push('YAML: ' + (e.message || e).split('\n')[0]);
}
if (Array.isArray(doc))
list = doc;
else if (isObj(doc) && Array.isArray(doc.proxies))
list = doc.proxies;
else if (isObj(doc) && doc.type)
list = [ doc ];
else if (doc !== null && doc !== undefined)
errors.push('YAML: нет списка proxies и не похоже на один сервер');
list.forEach(function (p) {
if (isObj(p) && isStr(p.type) && p.server !== undefined)
servers.push(p);
else
errors.push('YAML: пропущен элемент без type/server');
});
}
return { servers: servers, errors: errors };
}
// one stored line: JSON with "name" first (mihomo-kit.sh reads it with sed), a
// dialer-proxy only as the server's own entry (LuCI "Вход"; otherwise the kit sets
// it per profile), "$" as \u0024 (no ${...} for the template engine; JSON and YAML
// both read \u escapes)
function toLine(p) {
var o = { name: String(p.name) };
Object.keys(p).forEach(function (k) {
if (k != 'name' && (k != 'dialer-proxy' || p[k]))
o[k] = p[k];
});
return JSON.stringify(o).replace(/\$/g, '\\u0024');
}
function fromLines(text) {
var out = [];
String(text || '').split('\n').forEach(function (l) {
if (!l.trim())
return;
try {
var o = JSON.parse(l);
if (isObj(o))
out.push(o);
} catch (e) {}
});
return out;
}
// "vless · host:port"
function summary(p) {
var host = p.server === undefined ? '?' : String(p.server);
if (host.indexOf(':') >= 0)
host = '[' + host + ']';
return (p.type || '?') + ' · ' + host + (p.port !== undefined ? ':' + p.port : p['port-range'] ? ':' + p['port-range'] : '');
}
// a name not in "taken" (an object): "de", "de-2", "de-3", ...
function freeName(name, taken) {
name = String(name || '').trim() || 'server';
if (!taken[name])
return name;
for (var i = 2; ; i++)
if (!taken[name + '-' + i])
return name + '-' + i;
}
return {
parseLinks: parseLinks,
parseText: parseText,
parseConf: parseConf,
parseAmnezia: parseAmnezia,
yamlLoad: yamlLoad,
yamlDump: yamlDump,
toLine: toLine,
fromLines: fromLines,
summary: summary,
freeName: freeName,
USER_AGENT: USER_AGENT
};
});