Files
clash-rules/config-sub-converter/scripts/convert-awg-to-clash.js

97 lines
2.4 KiB
JavaScript

function parseIniWG(text) {
const lines = text
.replace(/\r\n/g, "\n")
.split("\n")
.map(l => l.trim())
.filter(l => l && !l.startsWith("#") && !l.startsWith(";"));
let section = null;
const data = { Interface: {}, Peer: {} };
for (const line of lines) {
const sec = line.match(/^\[(.+?)\]$/);
if (sec) {
section = sec[1];
continue;
}
const kv = line.match(/^([^=]+?)\s*=\s*(.+)$/);
if (!kv || !section) continue;
const key = kv[1].trim();
const val = kv[2].trim();
if (section === "Interface") data.Interface[key] = val;
if (section === "Peer") data.Peer[key] = val;
}
return data;
}
function splitList(v) {
return String(v || "")
.split(",")
.map(x => x.trim())
.filter(Boolean);
}
function parseEndpoint(ep) {
const m = String(ep || "").match(/^(.+?):(\d+)$/);
if (!m) return { host: "", port: 0 };
return { host: m[1], port: Number(m[2]) };
}
function scalar(v) {
if (typeof v === "number") return String(v);
if (typeof v === "boolean") return v ? "true" : "false";
return `"${String(v).replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
}
function arrayInline(arr) {
return `[${arr.map(scalar).join(", ")}]`;
}
function main() {
const input = $content; // Sub Store magic variable
const wg = parseIniWG(input);
const i = wg.Interface;
const p = wg.Peer;
const dns = splitList(i.DNS);
const allowed = splitList(p.AllowedIPs);
const ep = parseEndpoint(p.Endpoint);
const amz = {};
["Jc","Jmin","Jmax","S1","S2","H1","H2","H3","H4"].forEach(k => {
if (i[k] !== undefined) amz[k.toLowerCase()] = Number(i[k]);
});
let out = "";
out += "proxies:\n";
out += " - name: \"amz-wg\"\n";
out += " type: wireguard\n";
out += ` ip: ${scalar(i.Address)}\n`;
out += ` private-key: ${scalar(i.PrivateKey)}\n`;
out += " peers:\n";
out += ` - server: ${scalar(ep.host)}\n`;
out += ` port: ${ep.port}\n`;
out += ` public-key: ${scalar(p.PublicKey)}\n`;
if (p.PresharedKey)
out += ` pre-shared-key: ${scalar(p.PresharedKey)}\n`;
out += ` allowed-ips: ${arrayInline(allowed)}\n`;
out += " udp: true\n";
out += " remote-dns-resolve: true\n";
if (dns.length) out += ` dns: ${arrayInline(dns)}\n`;
if (Object.keys(amz).length) {
out += " amnezia-wg-option:\n";
for (const k in amz) {
out += ` ${k}: ${amz[k]}\n`;
}
}
return out;
}
main();