fix(remnawave): пользователи из файла, ротация API-токена без логов
ansible-core-net / deploy (push) Failing after 14s

users.yml — источник правды (homelab — первый). Именованный токен
перевыпускается каждый прогон и пишется в Infisical; stdout/stderr
секретов в CI закрыты no_log и redact.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
karpenokandCursor committed 2026-11-11 23:39:18 +07:00
1 parent 928c04ce9d
commit e4fc3fce69
4 files changed
+146 -41

No files matched your search

@@ -20,7 +20,7 @@ redact_json() {
jq 'walk(
if type == "object" then
with_entries(
if (.key | test("(?i)privateKey|privKey|secretKey|SECRET_KEY|accessToken|apiToken|password|^token$"))
if (.key | test("(?i)privateKey|privKey|secretKey|SECRET_KEY|accessToken|apiToken|password|^token$|vlessUuid|trojanPassword|ssPassword|shortUuid|subscriptionUrl"))
then .value = "[REDACTED]"
else .
end
@@ -87,36 +87,37 @@ else
AUTH_HDR=(-H "Authorization: Bearer ${access}")
fi
# Постоянный API-токен: scopes ["*"] (wildcard из GET /tokens/scopes).
# Если создать нельзя — не валим bootstrap; пользователь может положить токен вручную.
if [ -z "${active_token}" ] || [ "${admin_created}" -eq 1 ]; then
tokens_json=$(api GET /tokens/ || echo '{"response":[]}')
old_uuid=$(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))
| .[0].uuid // empty')
if [ -n "${old_uuid}" ]; then
api DELETE "/tokens/${old_uuid}" >/dev/null || true
fi
wildcard=$(api GET /tokens/scopes 2>/dev/null | 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
else
echo "WARN: POST /tokens/ без поля token — положите REMNAWAVE_API_TOKEN вручную" >&2
printf \'%s
\' "${token_resp}" | redact_json >&2
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=""
wildcard=$(api GET /tokens/scopes 2>/dev/null | 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
else
echo "WARN: не удалось создать API-токен автоматически — создайте в UI и положите в Infisical /services/remnawave как REMNAWAVE_API_TOKEN" >&2
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)
@@ -286,6 +287,92 @@ if [ -z "${host_uuid}" ]; then
host_created=1
fi
users_changed=0
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":[]}}')
ready=$(printf '%s' "${sub_cfgs}" | jq '[.response.configs[]? | select(.config != null)] | length')
if [ "${ready}" = "0" ]; then
api POST /subscription-page-configs/ -d '{"name":"Homelab"}' >/dev/null
users_changed=1
fi
# Браузер: Accept и User-Agent без учёта регистра, правило BROWSER первым.
settings=$(api GET /subscription-settings/ || echo '')
if [ -n "${settings}" ]; then
patched=$(printf '%s' "${settings}" | jq '
.response
| .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
jq -n \
--arg api_token "${active_token}" \
--arg node_secret "${node_secret}" \
@@ -298,6 +385,7 @@ jq -n \
--argjson profile_created "${profile_created}" \
--argjson node_created "${node_created}" \
--argjson host_created "${host_created}" \
--argjson users_changed "${users_changed}" \
'{
api_token: $api_token,
node_secret: $node_secret,
@@ -310,5 +398,6 @@ jq -n \
profile_created: ($profile_created == 1),
node_created: ($node_created == 1),
host_created: ($host_created == 1),
changed: (($admin_created + $token_updated + $profile_created + $node_created + $host_created) > 0)
users_changed: ($users_changed == 1),
changed: (($admin_created + $token_updated + $profile_created + $node_created + $host_created + $users_changed) > 0)
}'