Net core: accept Amnezia keys that carry a plain AmneziaWG .conf
Newer Amnezia apps share vpn:// keys whose payload (same base64url + length + zlib wrapping) is an AmneziaWG .conf ([Interface]/[Peer], AWG 3 fields) instead of the JSON containers; the parser failed with «Expecting value: line 1 column 2». decode_key() handles both; --check and the provider build use it. Tested with mihomo -t. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+36
-10
@@ -68,12 +68,43 @@ def mid(v, default):
|
|||||||
return (int(m.group(1)) + int(m.group(2))) // 2 if m else int(v)
|
return (int(m.group(1)) + int(m.group(2))) // 2 if m else int(v)
|
||||||
|
|
||||||
|
|
||||||
def amnezia(path, name):
|
def decode_key(path):
|
||||||
|
"""vpn:// → (payload, description). Two formats are shared by Amnezia:
|
||||||
|
the JSON one (containers → awg → last_config) and, from newer apps, a plain AmneziaWG
|
||||||
|
.conf ([Interface] / [Peer]) under the same base64url + 4-byte length + zlib wrapping."""
|
||||||
key = open(path).read().strip()[len("vpn://"):]
|
key = open(path).read().strip()[len("vpn://"):]
|
||||||
key += "=" * (-len(key) % 4)
|
key += "=" * (-len(key) % 4)
|
||||||
j = json.loads(zlib.decompress(base64.urlsafe_b64decode(key)[4:]))
|
text = zlib.decompress(base64.urlsafe_b64decode(key)[4:]).decode("utf-8")
|
||||||
awg = j["containers"][0]["awg"]
|
if text.lstrip().startswith("["):
|
||||||
|
return conf_to_last_config(text), ""
|
||||||
|
j = json.loads(text)
|
||||||
|
cont = j["containers"][0]
|
||||||
|
if "awg" not in cont:
|
||||||
|
raise ValueError("это не AmneziaWG (контейнер %s) — пока поддерживается только AmneziaWG"
|
||||||
|
% cont.get("container"))
|
||||||
|
awg = cont["awg"]
|
||||||
c = awg["last_config"] if isinstance(awg["last_config"], dict) else json.loads(awg["last_config"])
|
c = awg["last_config"] if isinstance(awg["last_config"], dict) else json.loads(awg["last_config"])
|
||||||
|
return c, j.get("description") or ""
|
||||||
|
|
||||||
|
|
||||||
|
def conf_to_last_config(text):
|
||||||
|
"""An AmneziaWG .conf → the same field names the JSON key uses."""
|
||||||
|
p = configparser.ConfigParser()
|
||||||
|
p.optionxform = str
|
||||||
|
p.read_string(text)
|
||||||
|
i, peer = p["Interface"], p["Peer"]
|
||||||
|
host, port = peer["Endpoint"].rsplit(":", 1)
|
||||||
|
c = {k: v for k, v in i.items() if k not in ("Address", "PrivateKey", "DNS", "MTU")}
|
||||||
|
c.update({"hostName": host.strip("[]"), "port": port,
|
||||||
|
"client_ip": i["Address"].split(",")[0].split("/")[0].strip(),
|
||||||
|
"client_priv_key": i["PrivateKey"], "server_pub_key": peer["PublicKey"],
|
||||||
|
"psk_key": peer.get("PresharedKey", ""), "mtu": i.get("MTU", "1376"),
|
||||||
|
"persistent_keep_alive": peer.get("PersistentKeepalive", "25")})
|
||||||
|
return c
|
||||||
|
|
||||||
|
|
||||||
|
def amnezia(path, name):
|
||||||
|
c, _ = decode_key(path)
|
||||||
ver = 3 if c.get("HeaderProtectionKey") else 2
|
ver = 3 if c.get("HeaderProtectionKey") else 2
|
||||||
opt = {"version": ver, "jc": int(c["Jc"]), "jmin": int(c["Jmin"]), "jmax": int(c["Jmax"]),
|
opt = {"version": ver, "jc": int(c["Jc"]), "jmin": int(c["Jmin"]), "jmax": int(c["Jmax"]),
|
||||||
"s1": int(c["S1"]), "s2": int(c["S2"])}
|
"s1": int(c["S1"]), "s2": int(c["S2"])}
|
||||||
@@ -271,14 +302,9 @@ def check(path):
|
|||||||
raw = open(path).read().strip()
|
raw = open(path).read().strip()
|
||||||
if not raw.startswith("vpn://"):
|
if not raw.startswith("vpn://"):
|
||||||
raise ValueError("ключ должен начинаться с vpn://")
|
raise ValueError("ключ должен начинаться с vpn://")
|
||||||
key = raw[len("vpn://"):]
|
_, description = decode_key(path)
|
||||||
key += "=" * (-len(key) % 4)
|
|
||||||
j = json.loads(zlib.decompress(base64.urlsafe_b64decode(key)[4:]))
|
|
||||||
cont = j["containers"][0]
|
|
||||||
if "awg" not in cont:
|
|
||||||
raise ValueError("это не AmneziaWG (контейнер %s) — пока поддерживается только AmneziaWG" % cont.get("container"))
|
|
||||||
p = amnezia(path, "check")
|
p = amnezia(path, "check")
|
||||||
print(json.dumps({"ok": True, "name": j.get("description") or p["server"], "server": p["server"],
|
print(json.dumps({"ok": True, "name": description or p["server"], "server": p["server"],
|
||||||
"port": p["port"], "version": p["amnezia-wg-option"]["version"]}, ensure_ascii=False))
|
"port": p["port"], "version": p["amnezia-wg-option"]["version"]}, ensure_ascii=False))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(json.dumps({"ok": False, "error": str(e) or e.__class__.__name__}, ensure_ascii=False))
|
print(json.dumps({"ok": False, "error": str(e) or e.__class__.__name__}, ensure_ascii=False))
|
||||||
|
|||||||
Reference in New Issue
Block a user