Files
homelab-infra/ansible/roles/core-net/remnawave/templates/bootstrap-panel.sh.j2
T
karpenokandCursor bcbb2564f1
ansible-core-net / deploy (push) Successful in 23s
fix(remnawave): показывать ноду как ger-nod-02
Подпись хоста в подписке была Yali. Дашборд берёт её из метрик xray-checker, флаг Германии остаётся.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 19:32:15 +07:00

509 lines
20 KiB
Django/Jinja
Raw 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.
#!/bin/bash
set -euo pipefail
API_BASE="https://${RW_PANEL_DOMAIN}/api"
# Admin JWT без X-Remnawave-Client-Type: browser → 403 на всех эндпоинтах (Remnawave ≥3).
CURL=(curl -sSk --resolve "${RW_PANEL_DOMAIN}:443:127.0.0.1" -H "X-Remnawave-Client-Type: browser")
AUTH_HDR=()
admin_created=0
token_updated=0
profile_created=0
node_created=0
node_address_updated=0
host_created=0
host_remark_updated=0
node_secret=""
active_token="${RW_API_TOKEN:-}"
# В stderr/CI никогда не светить privateKey, SECRET_KEY, JWT, API-токены.
# publicKey оставляем — он не секрет.
redact_json() {
jq 'walk(
if type == "object" then
with_entries(
if (.key | test("(?i)privateKey|privKey|secretKey|SECRET_KEY|accessToken|apiToken|password|^token$|vlessUuid|trojanPassword|ssPassword|shortUuid|subscriptionUrl|setupKey|setup_key|METRICS_PASS"))
then .value = "[REDACTED]"
else .
end
)
else . end
)' 2>/dev/null || echo '[body redacted]'
}
log_api_error() {
local method="$1" path="$2" code="$3" body="$4"
echo "API ${method} ${path} → HTTP ${code}" >&2
printf '%s\n' "${body}" | redact_json >&2 || true
echo >&2
}
api() {
local method="$1"; shift
local path="$1"; shift
local tmp code
tmp=$(mktemp)
if [ -n "${AUTH_HDR[*]:-}" ]; then
code=$("${CURL[@]}" -o "$tmp" -w '%{http_code}' -X "$method" "${AUTH_HDR[@]}" \
-H "Content-Type: application/json" "${API_BASE}${path}" "$@") || true
else
code=$("${CURL[@]}" -o "$tmp" -w '%{http_code}' -X "$method" \
-H "Content-Type: application/json" "${API_BASE}${path}" "$@") || true
fi
if [[ ! "${code}" =~ ^2 ]]; then
log_api_error "$method" "$path" "$code" "$(cat "$tmp" 2>/dev/null || true)"
rm -f "$tmp"
return 1
fi
cat "$tmp"
rm -f "$tmp"
}
status_json=$("${CURL[@]}" "${API_BASE}/auth/status")
is_register=$(printf '%s' "${status_json}" | jq -r '.response.isRegisterAllowed // .isRegisterAllowed // false')
# Весь bootstrap держим на admin JWT + browser. API-токен создаём отдельно
# и НЕ переключаем на него: иначе пустые/неверные scopes → 403 на /keygen/.
if [ "${is_register}" = "true" ]; then
reg_payload=$(jq -n --arg u "$RW_ADMIN_USER" --arg p "$RW_ADMIN_PASS" '{username: $u, password: $p}')
reg_resp=$(api POST /auth/register -d "${reg_payload}")
access=$(printf '%s' "${reg_resp}" | jq -r '.response.accessToken // .accessToken // empty')
if [ -z "${access}" ]; then
echo "Не удалось зарегистрировать админа Remnawave" >&2
printf \'%s
\' "${reg_resp}" | redact_json >&2
exit 1
fi
AUTH_HDR=(-H "Authorization: Bearer ${access}")
admin_created=1
else
login_payload=$(jq -n --arg u "$RW_ADMIN_USER" --arg p "$RW_ADMIN_PASS" '{username: $u, password: $p}')
login_resp=$(api POST /auth/login -d "${login_payload}")
access=$(printf '%s' "${login_resp}" | jq -r '.response.accessToken // .accessToken // empty')
if [ -z "${access}" ]; then
echo "Не удалось войти в панель Remnawave (REMNAWAVE_ADMIN_* из /services/remnawave)" >&2
printf \'%s
\' "${login_resp}" | redact_json >&2
exit 1
fi
AUTH_HDR=(-H "Authorization: Bearer ${access}")
fi
# Каждый прогон перевыпускает именованный API-токен и гасит предыдущие
# (в том числе утёкший). Само значение наружу не печатаем.
tokens_json=$(api GET /tokens/ || echo '{"response":[]}')
old_uuids=$(printf '%s' "${tokens_json}" | jq -r --arg n "$RW_TOKEN_NAME" '
(.response // .)
| if type=="array" then . elif .tokens then .tokens else [] end
| map(select(.name == $n or .tokenName == $n) | .uuid)
| .[]')
for old_uuid in ${old_uuids}; do
[ -n "${old_uuid}" ] || continue
api DELETE "/tokens/${old_uuid}" >/dev/null || true
done
active_token=""
scopes_json=$(api GET /tokens/scopes || echo '{"response":{"wildcard":"*"}}')
wildcard=$(printf '%s' "${scopes_json}" | jq -r '.response.wildcard // "*"')
token_payload=$(jq -n --arg n "$RW_TOKEN_NAME" --arg s "${wildcard:-*}" \
'{name: $n, expiresInDays: 3650, scopes: [$s]}')
if token_resp=$(api POST /tokens/ -d "${token_payload}"); then
created=$(printf '%s' "${token_resp}" | jq -r '
.response.token // .response.apiToken // .token // .apiToken // empty')
if [ -n "${created}" ]; then
active_token="${created}"
token_updated=1
echo "API-токен ${RW_TOKEN_NAME} перевыпущен" >&2
else
echo "WARN: POST /tokens/ без поля token" >&2
fi
else
echo "WARN: не удалось перевыпустить API-токен" >&2
fi
if [ -z "${active_token}" ]; then
echo "Нет нового API-токена — bootstrap остановлен, секрет в лог не пишем" >&2
exit 1
fi
# SECRET_KEY ноды — отдельный endpoint /api/keygen/ (не ответ create node)
if [ -n "${RW_NODE_SECRET:-}" ]; then
node_secret="${RW_NODE_SECRET}"
else
keygen_resp=$(api GET /keygen/)
node_secret=$(printf '%s' "${keygen_resp}" | jq -r '.response.secretKey // .secretKey // empty')
if [ -z "${node_secret}" ]; then
echo "Не удалось получить SECRET_KEY ноды из /api/keygen/" >&2
printf \'%s
\' "${keygen_resp}" | redact_json >&2
exit 1
fi
fi
profiles_json=$(api GET /config-profiles/)
profile_uuid=$(printf '%s' "${profiles_json}" | jq -r --arg n "$RW_PROFILE_NAME" '
(.response.configProfiles // .response // [])
| map(select(.name == $n)) | .[0].uuid // empty')
pub=""
if [ -z "${profile_uuid}" ]; then
key_resp=$(api GET /system/tools/x25519/generate 2>/dev/null || echo '{}')
# v3: {response:{keypairs:[{publicKey,privateKey},...]}}
priv=$(printf '%s' "${key_resp}" | jq -r '
.response.keypairs[0].privateKey
// .response.privateKey // .response.privKey // .privateKey // .privKey // empty')
pub=$(printf '%s' "${key_resp}" | jq -r '
.response.keypairs[0].publicKey
// .response.publicKey // .response.pubKey // .publicKey // .pubKey // empty')
if [ -z "${priv}" ] || [ -z "${pub}" ]; then
echo "Не удалось сгенерировать X25519 ключи Reality" >&2
printf \'%s
\' "${key_resp}" | redact_json >&2
exit 1
fi
short_id=$(openssl rand -hex 8)
profile_config=$(sed \
-e "s|__REALITY_PRIVATE_KEY__|${priv}|g" \
-e "s|__REALITY_SHORT_ID__|${short_id}|g" \
"$RW_PROFILE_FILE")
create_profile=$(jq -n --arg n "$RW_PROFILE_NAME" --argjson c "${profile_config}" '{name: $n, config: $c}')
profile_resp=$(api POST /config-profiles/ -d "${create_profile}")
profile_uuid=$(printf '%s' "${profile_resp}" | jq -r '.response.uuid // .uuid // empty')
if [ -z "${profile_uuid}" ]; then
echo "Не удалось создать config profile" >&2
printf \'%s
\' "${profile_resp}" | redact_json >&2
exit 1
fi
profile_created=1
fi
profile_full=$(api GET "/config-profiles/${profile_uuid}")
inbound_uuid=$(printf '%s' "${profile_full}" | jq -r --arg t "$RW_INBOUND_TAG" '
(.response.inbounds // .inbounds // [])
| map(select(.tag == $t)) | .[0].uuid // empty')
if [ -z "${inbound_uuid}" ]; then
inbounds_json=$(api GET "/config-profiles/${profile_uuid}/inbounds" 2>/dev/null || echo '{}')
inbound_uuid=$(printf '%s' "${inbounds_json}" | jq -r --arg t "$RW_INBOUND_TAG" '
(.response // .)
| if type=="array" then . else (.inbounds // []) end
| map(select(.tag == $t)) | .[0].uuid // empty')
fi
if [ -z "${inbound_uuid}" ]; then
echo "Не найден inbound ${RW_INBOUND_TAG} в профиле ${profile_uuid}" >&2
exit 1
fi
nodes_json=$(api GET /nodes/)
node_uuid=$(printf '%s' "${nodes_json}" | jq -r --arg n "$RW_NODE_NAME" '
(.response // []) | map(select(.name == $n)) | .[0].uuid // empty')
if [ -z "${node_uuid}" ]; then
node_payload=$(jq -n \
--arg name "$RW_NODE_NAME" \
--arg addr "$RW_NODE_ADDR" \
--argjson port "$RW_NODE_PORT" \
--arg cc "$RW_NODE_CC" \
--arg pu "$profile_uuid" \
--arg iu "$inbound_uuid" \
'{
name: $name,
address: $addr,
port: $port,
countryCode: $cc,
configProfile: {
activeConfigProfileUuid: $pu,
activeInbounds: [$iu]
}
}')
node_resp=$(api POST /nodes/ -d "${node_payload}")
node_uuid=$(printf '%s' "${node_resp}" | jq -r '.response.uuid // .uuid // empty')
if [ -z "${node_uuid}" ]; then
echo "Не удалось создать ноду" >&2
printf \'%s
\' "${node_resp}" | redact_json >&2
exit 1
fi
node_created=1
fi
current_addr=$(printf '%s' "${nodes_json}" | jq -r --arg n "$RW_NODE_NAME" '(.response // []) | map(select(.name == $n)) | .[0].address // empty')
if [ -n "${RW_NODE_ADDR}" ] && [ "${current_addr}" != "${RW_NODE_ADDR}" ]; then
node_address_updated=1
fi
node_update=$(jq -n \
--arg u "$node_uuid" \
--arg pu "$profile_uuid" \
--arg iu "$inbound_uuid" \
--arg addr "$RW_NODE_ADDR" \
--argjson port "$RW_NODE_PORT" \
'{
uuid: $u,
address: $addr,
port: $port,
configProfile: {
activeConfigProfileUuid: $pu,
activeInbounds: [$iu]
}
}')
if ! api PATCH /nodes/ -d "${node_update}" >/dev/null \
&& ! api PUT /nodes/ -d "${node_update}" >/dev/null; then
echo "WARN: не удалось обновить адрес ноды ${RW_NODE_NAME}" >&2
fi
hosts_json=$(api GET /hosts/)
host_uuid=$(printf '%s' "${hosts_json}" | jq -r --arg a "$RW_SELFSTEAL" '
(.response // []) | map(select(.address == $a)) | .[0].uuid // empty')
if [ -z "${host_uuid}" ]; then
host_payload=$(jq -n \
--arg remark "$RW_HOST_REMARK" \
--arg addr "$RW_SELFSTEAL" \
--arg path "$RW_XHTTP_PATH" \
--arg sni "$RW_SELFSTEAL" \
--arg host "$RW_SELFSTEAL" \
--arg pu "$profile_uuid" \
--arg iu "$inbound_uuid" \
--arg nu "$node_uuid" \
'{
remark: $remark,
address: $addr,
port: 443,
path: $path,
sni: $sni,
host: $host,
fingerprint: "chrome",
isDisabled: false,
securityLayer: "DEFAULT",
alpn: "h2",
xHttpExtraParams: {
xmux: {
maxConcurrency: "16-32",
hMaxRequestTimes: "600-900",
hMaxReusableSecs: "1800-3000"
},
noSSEHeader: true,
xPaddingBytes: "100-1000"
},
inbound: {
configProfileUuid: $pu,
configProfileInboundUuid: $iu
},
nodes: [$nu]
}')
host_resp=$(api POST /hosts/ -d "${host_payload}")
host_uuid=$(printf '%s' "${host_resp}" | jq -r '.response.uuid // .uuid // empty')
if [ -z "${host_uuid}" ]; then
echo "Не удалось создать host" >&2
printf \'%s
\' "${host_resp}" | redact_json >&2
exit 1
fi
host_created=1
fi
if [ "${host_created}" -eq 0 ]; then
current_remark=$(printf '%s' "${hosts_json}" | jq -r --arg u "${host_uuid}" '
(.response // []) | map(select(.uuid == $u)) | .[0].remark // empty')
if [ "${current_remark}" != "${RW_HOST_REMARK}" ]; then
host_remark=$(jq -n --arg u "${host_uuid}" --arg remark "${RW_HOST_REMARK}" '{uuid: $u, remark: $remark}')
if ! api PATCH /hosts/ -d "${host_remark}" >/dev/null; then
echo "WARN: не удалось обновить имя хоста ${RW_SELFSTEAL}" >&2
else
host_remark_updated=1
echo "Имя хоста ${RW_SELFSTEAL}: ${RW_HOST_REMARK}" >&2
fi
fi
fi
users_changed=0
# Клиентский Xray JSON. Имя Except-RU: весь tcp/udp в proxy, RU/private/торренты и
# проверки IP в direct. Блок remnawave панель снимает до выдачи клиенту и
# подставляет этот хост как outbound с тегом proxy.
if [ -n "${RW_XRAY_TEMPLATE_FILE:-}" ] && [ -f "${RW_XRAY_TEMPLATE_FILE}" ]; then
want_tpl=$(jq -c . "${RW_XRAY_TEMPLATE_FILE}")
tpl_list=$(api GET /subscription-templates/)
tpl_uuid=$(printf '%s' "${tpl_list}" | jq -r --arg n "${RW_XRAY_TEMPLATE_NAME}" '
.response.templates[]? | select(.name == $n and .templateType == "XRAY_JSON") | .uuid' | head -1)
if [ -z "${tpl_uuid}" ]; then
tpl_body=$(jq -n --arg n "${RW_XRAY_TEMPLATE_NAME}" --argjson j "${want_tpl}" \
'{name: $n, templateType: "XRAY_JSON", templateJson: $j}')
tpl_resp=$(api POST /subscription-templates/ -d "${tpl_body}")
tpl_uuid=$(printf '%s' "${tpl_resp}" | jq -r '.response.uuid // empty')
if [ -z "${tpl_uuid}" ]; then
echo "Не удалось создать шаблон ${RW_XRAY_TEMPLATE_NAME}" >&2
exit 1
fi
echo "Шаблон ${RW_XRAY_TEMPLATE_NAME} создан" >&2
users_changed=1
else
tpl_full=$(api GET "/subscription-templates/${tpl_uuid}")
current_tpl=$(printf '%s' "${tpl_full}" | jq -cS '.response.templateJson // {}')
wanted_tpl=$(jq -cS . "${RW_XRAY_TEMPLATE_FILE}")
if [ "${current_tpl}" != "${wanted_tpl}" ]; then
upd=$(jq -n --arg u "${tpl_uuid}" --argjson j "${want_tpl}" '{uuid: $u, templateJson: $j}')
api PATCH /subscription-templates/ -d "${upd}" >/dev/null
echo "Шаблон ${RW_XRAY_TEMPLATE_NAME} обновлён" >&2
users_changed=1
else
echo "Шаблон ${RW_XRAY_TEMPLATE_NAME} уже совпадает" >&2
fi
fi
bound=$(printf '%s' "${hosts_json}" | jq -r --arg u "${host_uuid}" '.response[]? | select(.uuid == $u) | .xrayJsonTemplateUuid // empty')
if [ "${bound}" != "${tpl_uuid}" ]; then
host_bind=$(jq -n --arg u "${host_uuid}" --arg t "${tpl_uuid}" '{uuid: $u, xrayJsonTemplateUuid: $t}')
api PATCH /hosts/ -d "${host_bind}" >/dev/null
echo "Хост ${RW_SELFSTEAL} привязан к шаблону ${RW_XRAY_TEMPLATE_NAME}" >&2
users_changed=1
fi
fi
squad_uuid=$(api GET /internal-squads/ | jq -r --arg n "Default-Squad" '
.response.internalSquads[]? | select(.name == $n) | .uuid' | head -1)
if [ -n "${squad_uuid}" ] && [ -n "${inbound_uuid}" ]; then
has_inbound=$(api GET /internal-squads/ | jq -r --arg s "${squad_uuid}" --arg i "${inbound_uuid}" '
.response.internalSquads[]? | select(.uuid == $s) | .inbounds[]?.uuid | select(. == $i)' | head -1)
if [ -z "${has_inbound}" ]; then
squad_body=$(jq -n --arg u "${squad_uuid}" --arg i "${inbound_uuid}" '{uuid: $u, inbounds: [$i]}')
api PATCH /internal-squads/ -d "${squad_body}" >/dev/null
users_changed=1
fi
fi
# Конфиг страницы подписки. В списке поле config часто null — смотрим по имени.
sub_cfgs=$(api GET /subscription-page-configs/ || echo '{"response":{"configs":[]}}')
if ! printf '%s' "${sub_cfgs}" | jq -e '.response.configs[]? | select(.name == "Homelab")' >/dev/null; then
api POST /subscription-page-configs/ -d '{"name":"Homelab"}' >/dev/null
echo "Конфиг страницы подписки Homelab создан" >&2
users_changed=1
else
echo "Конфиг страницы подписки Homelab уже есть" >&2
fi
# Браузер: Accept и User-Agent без учёта регистра, правило BROWSER первым.
settings=$(api GET /subscription-settings/ || echo '')
if [ -n "${settings}" ]; then
patched=$(printf '%s' "${settings}" | jq '
.response
| .serveJsonAtBaseSubscription = true
| .responseRules.rules = (
[
{
name: "Browser",
enabled: true,
operator: "OR",
description: "IaC: HTML-страница подписки",
responseType: "BROWSER",
conditions: [
{headerName: "accept", operator: "CONTAINS", value: "text/html", caseSensitive: false},
{headerName: "user-agent", operator: "CONTAINS", value: "Mozilla", caseSensitive: false}
]
}
] + [
.responseRules.rules[]?
| select(.name != "Browser" and .name != "Browser Subscription" and .responseType != "BROWSER")
]
)')
api PATCH /subscription-settings/ -d "${patched}" >/dev/null \
|| api PUT /subscription-settings/ -d "${patched}" >/dev/null \
|| echo "WARN: не удалось обновить SRR" >&2
fi
if [ -n "${RW_USERS_FILE:-}" ] && [ -f "${RW_USERS_FILE}" ]; then
existing=$(api GET "/users/?size=500" || api GET /users/)
desired_names=$(jq -r '.users[].username' "${RW_USERS_FILE}")
while IFS= read -r username; do
[ -n "${username}" ] || continue
want=$(jq -c --arg u "${username}" '.users[] | select(.username == $u)' "${RW_USERS_FILE}")
squad_name=$(printf '%s' "${want}" | jq -r '.squad // "Default-Squad"')
sid=$(api GET /internal-squads/ | jq -r --arg n "${squad_name}" '.response.internalSquads[]? | select(.name == $n) | .uuid' | head -1)
uuid=$(printf '%s' "${existing}" | jq -r --arg u "${username}" '.response.users[]? | select(.username == $u) | .uuid' | head -1)
body=$(printf '%s' "${want}" | jq -c --arg sid "${sid}" '{
username,
status: (.status // "ACTIVE"),
expireAt: .expire_at,
description: (.description // ""),
trafficLimitBytes: (.traffic_limit_bytes // 0),
trafficLimitStrategy: (.traffic_limit_strategy // "NO_RESET"),
activeInternalSquads: (if $sid == "" then [] else [$sid] end)
}')
if [ -z "${uuid}" ]; then
api POST /users/ -d "${body}" >/dev/null
users_changed=1
else
api PATCH /users/ -d "$(printf '%s' "${body}" | jq -c --arg id "${uuid}" '. + {uuid: $id}')" >/dev/null
users_changed=1
fi
done <<< "${desired_names}"
while IFS= read -r row; do
[ -n "${row}" ] || continue
uname=${row%% *}
uuuid=${row#* }
if ! printf '%s\n' "${desired_names}" | grep -qx "${uname}"; then
api DELETE "/users/${uuuid}" >/dev/null
users_changed=1
fi
done < <(printf '%s' "${existing}" | jq -r '.response.users[]? | "\(.username)\t\(.uuid)"')
fi
xray_url=""
xray_user="${RW_XRAY_USER:-homelab}"
if [ -n "${xray_user}" ]; then
users_now=$(api GET "/users/?size=500" || api GET /users/ || echo '{}')
xray_url=$(printf '%s' "${users_now}" | jq -r --arg u "${xray_user}" '
.response.users[]? | select(.username == $u) | .subscriptionUrl // empty' | head -1)
if [ -z "${xray_url}" ]; then
short=$(printf '%s' "${users_now}" | jq -r --arg u "${xray_user}" '
.response.users[]? | select(.username == $u) | .shortUuid // empty' | head -1)
if [ -n "${short}" ] && [ -n "${RW_SUB_DOMAIN:-}" ]; then
xray_url="https://${RW_SUB_DOMAIN}/${short}"
fi
fi
fi
xray_saved=0
if [ -n "${xray_url}" ]; then
xray_saved=1
fi
# Секреты только в файл 0600. В stdout — статус без значений ключей.
secrets_file="${RW_SECRETS_FILE:-/opt/remnawave/.bootstrap-secrets.json}"
umask 077
jq -n \
--arg api_token "${active_token}" \
--arg node_secret "${node_secret}" \
--arg xray_url "${xray_url}" \
'{api_token: $api_token, node_secret: $node_secret, xray_checker_subscription_url: $xray_url}' > "${secrets_file}"
chmod 600 "${secrets_file}"
jq -n \
--arg profile_uuid "${profile_uuid}" \
--arg node_uuid "${node_uuid}" \
--arg host_uuid "${host_uuid}" \
--arg reality_pub "${pub}" \
--arg node_address "${RW_NODE_ADDR}" \
--argjson admin_created "${admin_created}" \
--argjson token_updated "${token_updated}" \
--argjson profile_created "${profile_created}" \
--argjson node_created "${node_created}" \
--argjson node_address_updated "${node_address_updated}" \
--argjson host_created "${host_created}" \
--argjson host_remark_updated "${host_remark_updated}" \
--argjson users_changed "${users_changed}" \
--argjson xray_saved "${xray_saved}" \
'{
profile_uuid: $profile_uuid,
node_uuid: $node_uuid,
host_uuid: $host_uuid,
node_address: $node_address,
reality_public_key: $reality_pub,
admin_created: ($admin_created == 1),
token_updated: ($token_updated == 1),
profile_created: ($profile_created == 1),
node_created: ($node_created == 1),
node_address_updated: ($node_address_updated == 1),
host_created: ($host_created == 1),
host_remark_updated: ($host_remark_updated == 1),
users_changed: ($users_changed == 1),
xray_checker_url_saved: ($xray_saved == 1),
changed: (($admin_created + $token_updated + $profile_created + $node_created + $node_address_updated + $host_created + $host_remark_updated + $users_changed + $xray_saved) > 0)
}'