feat(remnawave): persist Reality keys in Infisical and auto-sync OPNsense VLESS link
ansible-deploy / plan (push) Successful in 2s
ansible-lint / lint (push) Successful in 2s
ansible-deploy / deploy (core-net, ) (push) Successful in 13s
ansible-deploy / deploy (opnsense, ) (push) Successful in 8s

This commit is contained in:
karpenok committed 2026-11-19 11:25:15 +07:00
1 parent ef8179e96e
commit e623faff2b
6 files changed
+131 -4

No files matched your search

@@ -30,3 +30,4 @@ nodes:
country_code: DE
profile: DE-Yali
host_remark: "🇩🇪 ger-nod-02"
opnsense_secret: GERM_02
@@ -3,6 +3,7 @@
from __future__ import annotations
import base64
import copy
import json
import os
@@ -10,6 +11,7 @@ import re
import secrets
import subprocess
import sys
import urllib.parse
from typing import Any
@@ -167,6 +169,9 @@ class Sync:
self.refs: dict[str, dict[str, dict[str, Any]]] = {}
self.inbounds: dict[str, dict[str, Any]] = {}
self.xray_url = ""
self.reality_private_key = ""
self.reality_short_id = ""
self.opnsense_links: dict[str, str] = {}
def run(self) -> dict[str, Any]:
pending: list[tuple[dict[str, Any], list[dict[str, Any]], set[tuple[Any, ...]]]] = []
@@ -179,7 +184,9 @@ class Sync:
self._prune(step, remote, keep)
for step in later:
getattr(self, f"run_{step['run']}")()
self._collect_opnsense_links()
self._write_xray_url()
self._write_sync_secrets()
return {"changed": bool(self.changes), "changes": self.changes, "warnings": self.warnings}
def _list(self, step: dict[str, Any]) -> list[dict[str, Any]]:
@@ -311,7 +318,11 @@ class Sync:
if existing and not current and existing.get("uuid"):
_, data = self.api.request("GET", f"/config-profiles/{existing['uuid']}")
current = _as_obj(data).get("config")
private, short = _reality(current, item["inbound_tag"])
env_private = os.environ.get("RW_REALITY_PRIVATE_KEY", "").strip()
env_short = os.environ.get("RW_REALITY_SHORT_ID", "").strip()
cur_private, cur_short = _reality(current, item["inbound_tag"])
private = env_private or cur_private
short = env_short or cur_short
if not private:
_, data = self.api.request("GET", "/system/tools/x25519/generate")
body = _as_obj(data)
@@ -321,6 +332,10 @@ class Sync:
raise RuntimeError(f"Не удалось сгенерировать X25519 для профиля {item['name']}")
if not short:
short = secrets.token_hex(8)
if not self.reality_private_key:
self.reality_private_key = private
if not self.reality_short_id:
self.reality_short_id = short
raw = self.files[item["template"]]
rendered = (
raw.replace("__REALITY_PRIVATE_KEY__", private)
@@ -337,7 +352,9 @@ class Sync:
if current is None and existing.get("uuid"):
_, data = self.api.request("GET", f"/config-profiles/{existing['uuid']}")
current = _as_obj(data).get("config")
if _reality(current, prepared["inbound_tag"])[0] == "":
cur_priv, cur_short = _reality(current, prepared["inbound_tag"])
want_priv, want_short = _reality(prepared.get("config"), prepared["inbound_tag"])
if cur_priv == "" or (want_priv and cur_priv != want_priv) or (want_short and cur_short != want_short):
return True
return _canon_profile(current) != _canon_profile(prepared.get("config"))
@@ -522,6 +539,43 @@ class Sync:
if not self.xray_url and user.get("shortUuid") and self.cfg.get("sub_domain"):
self.xray_url = f"https://{self.cfg['sub_domain']}/{user['shortUuid']}"
def _collect_opnsense_links(self) -> None:
wanted: dict[str, str] = {}
for node in self.desired.get("nodes") or []:
secret_name = str(node.get("opnsense_secret") or "").strip()
if not secret_name:
continue
profile = self.refs.get("profile", {}).get(node.get("profile", "")) or {}
domain = str(profile.get("selfsteal_domain") or "").strip().lower()
if domain:
wanted[domain] = secret_name
if not wanted or not self.xray_url:
return
sub_domain = str(self.cfg.get("sub_domain") or "").strip()
cmd = ["curl", "-sSk", "--max-time", "15", "-H", "User-Agent: v2rayNG/1.8"]
if sub_domain:
cmd.extend(["--resolve", f"{sub_domain}:443:127.0.0.1"])
cmd.append(self.xray_url)
proc = subprocess.run(cmd, capture_output=True, check=False)
if proc.returncode != 0:
return
raw = proc.stdout.decode("utf-8", errors="replace").strip()
if not raw:
return
if not raw.startswith("vless://"):
try:
pad = "=" * ((4 - len(raw) % 4) % 4)
raw = base64.b64decode(raw + pad).decode("utf-8", errors="replace")
except Exception:
return
for line in raw.splitlines():
link = line.strip()
if not link.startswith("vless://"):
continue
host = (urllib.parse.urlsplit(link).hostname or "").strip().lower()
if host in wanted:
self.opnsense_links[wanted[host]] = link
def _write_xray_url(self) -> None:
path = os.environ.get("RW_XRAY_URL_FILE", "").strip()
if not path:
@@ -530,6 +584,19 @@ class Sync:
handle.write(self.xray_url)
os.chmod(path, 0o600)
def _write_sync_secrets(self) -> None:
path = os.environ.get("RW_SYNC_SECRETS_FILE", "").strip()
if not path:
return
payload = {
"reality_private_key": self.reality_private_key,
"reality_short_id": self.reality_short_id,
"opnsense_links": self.opnsense_links,
}
with open(path, "w", encoding="utf-8") as handle:
json.dump(payload, handle, ensure_ascii=False)
os.chmod(path, 0o600)
def main() -> int:
if len(sys.argv) == 2 and sys.argv[1] == "--selftest":