Compare commits

..

37 Commits

Author SHA1 Message Date
inecs ca1011954f Embed QR PNGs as data URLs for file:// downloads
Chrome blocks fetch/canvas for sibling file:// images (CORS/tainted).
Inline base64 in HTML so lightbox and .png chips download offline.
2026-07-23 10:54:19 +03:00
inecs 6932496bfc Fix lightbox QR download: sync canvas.toDataURL
Async fetch/toBlob lost the user-gesture so Safari/Chrome opened
the PNG instead of downloading. Use a button and sync data-URL save.
2026-07-23 10:34:13 +03:00
inecs 396682459c docs: восстановить README salamander и пункт про скачивание файлов 2026-07-23 10:30:16 +03:00
inecs 7f644b693b docs: скачивание .url/.txt/.png/.qr.txt в «Последние обновления» 2026-07-23 10:29:56 +03:00
inecs c1b26ff35b Force download for .url/.txt/.png/.qr.txt chips
Browser often opens these files instead of downloading; use blob
downloads with embedded text fallbacks and canvas for PNG on file://.
2026-07-23 10:28:14 +03:00
inecs e486e1df86 Принудительное скачивание QR из lightbox как server-user.png
Кнопка больше не открывает PNG во вкладке: blob/canvas download
с именем <сервер>-<пользователь>.png.
2026-07-23 10:23:16 +03:00
inecs 78f4d05ceb docs: раздел «Последние обновления» за 2026-07-23 2026-07-23 09:42:47 +03:00
inecs 0ea10c40fc make index и install/update: единый стиль страниц серверов и каталога
Пересборка HTML серверов из server-info.yml; сетка карточек и вид
как у главной. Тот же pipeline после install/update/export.
2026-07-23 09:35:47 +03:00
inecs 94be253768 Убрать подсказку закрытия из lightbox 2026-07-23 09:31:20 +03:00
inecs 651ec2daee Сетка карточек на странице сервера и крупный QR в lightbox
Карточки как в глобальном индексе; QR заполняет доступную
площадь модального окна через container queries.
2026-07-23 09:25:22 +03:00
inecs ac85a43c11 docs: упомянуть вкладки и статистику в make index 2026-07-23 09:21:24 +03:00
inecs ade2ea0f9a Вкладки серверов и страница статистики в output/index.html
По умолчанию — Статистика: доступность TCP, IP, пользователи,
матрица присутствия. Серверы открываются отдельными вкладками.
2026-07-23 09:21:04 +03:00
inecs 28df4f4a04 Сделать lightbox на всю высоту экрана с небольшими отступами
Панель занимает 100dvh минус 1rem сверху/снизу; QR растягивается
в оставшееся пространство.
2026-07-23 09:16:45 +03:00
inecs 912938e6cf Увеличить QR в lightbox на 30% (до ~728px) 2026-07-23 09:13:58 +03:00
inecs a39e5b7d16 Ограничить lightbox QR высотой экрана с отступами сверху/снизу 2026-07-23 09:13:00 +03:00
inecs 212e891409 Увеличить QR в lightbox до ~560px 2026-07-23 09:11:14 +03:00
inecs c3b3bbb8a0 Добавить кнопку скачивания QR в lightbox
Файл сохраняется как <сервер>-<пользователь>.png.
2026-07-23 09:09:12 +03:00
inecs 2ea3dadc7b Добавить lightbox для QR-кодов в HTML-каталогах
Клик по QR открывает крупный просмотр с подписью; закрытие по Esc,
кнопке и клику на фон. В global и server index.
2026-07-23 09:07:23 +03:00
inecs 345326d844 Обновить bundled install_server.sh с официального get.hy2.sh
Синхронизация локальной копии после проверки SHA256.
2026-07-23 09:02:06 +03:00
inecs 9bfbd07251 Добавить make index: пересборка output/index.html из локальных экспортов
Отдельный playbook на localhost читает server-info.yml, обновляет
общий каталог и открывает его в браузере без обращения к VPS.
2026-07-23 08:56:04 +03:00
inecs dc35bec4fb fix: корректный make status при inactive и без -o
systemctl is-active с rc≠0 больше не дублирует inactive;
убран deprecated флаг -o.
2026-07-23 08:46:17 +03:00
inecs e11ccd3040 Улучшить вывод make status: кратко и без логов journal
Одна строка на хост (active/not installed, since, PID, RAM);
хост без установки больше не валит весь make.
2026-07-23 08:32:08 +03:00
inecs 2210a55782 fix: пропускать sync install_server.sh при сетевой ошибке
Если get.hy2.sh недоступен (таймаут без VPN), используется локальная
копия в roles/hysteria2/files/; падение только если её нет.
2026-07-01 14:06:46 +03:00
inecs 1452086c98 docs: LIMIT при добавлении сервера и force_export в README
Описано, что make install LIMIT не трогает старые VPS и как принудительно
перевыпустить URL/QR через hysteria2_force_export.
2026-07-01 13:37:53 +03:00
inecs 9600e18f65 fix: пересборка output/index.html при uninstall с LIMIT
Второй play перенесён на hysteria2_servers с run_once на localhost,
чтобы LIMIT не пропускал пересборку. Пустой index.html удаляется.
2026-07-01 13:31:28 +03:00
inecs 2331a5c04e Полная очистка при uninstall: VPS и output/<server>/
Скрипт --remove снимает только бинарник и systemd; Ansible дочищает конфиг,
пользователя, ufw, пакеты и всегда удаляет локальную папку экспорта.
2026-07-01 13:28:59 +03:00
inecs da66d4e045 fix: run only uninstall tasks, not full role on make uninstall
Tagging the whole role with uninstall caused install/configure/update/export to run first. Use include_role tasks_from uninstall.yml; add safe defaults for uninstall variables.
2026-07-01 13:20:17 +03:00
inecs 90db85aaf0 docs: update README for Salamander branch features
Mirror main documentation: install script sync, incremental update/export, uninstall, vault wiring, Makefile and role structure.
2026-07-01 13:16:38 +03:00
inecs ca22c0f39d feat: incremental user passwords and export on update
Preserve passwords from server-info.yml and vault; generate only for new users; remove deleted users from output; re-export URL/QR only when password, domain, port, obfs or files changed.
2026-07-01 13:06:33 +03:00
inecs fc5efccd91 feat: complete uninstall cleanup on server and local output
Remove binary, config, masq, system user, ufw rules, and apt packages from VPS; delete output/<server>/ by default and rebuild global index.html via localhost play.
2026-07-01 12:56:20 +03:00
inecs f3bd4313df feat: bundle and sync official Hysteria2 install script locally
Store install_server.sh in role files, compare SHA256 with get.hy2.sh on the control node before install/update, refresh the bundled copy when upstream changes, then copy and run it on VPS.
2026-07-01 12:00:37 +03:00
inecs a821dabf18 fix: disable become on localhost play and drop deprecated facts
Use now() for export timestamps and ansible_facts['system'] for browser detection. Set become: false on the localhost play to avoid sudo on local fact gathering.
2026-07-01 11:56:18 +03:00
inecs 69eccce8eb fix: generate VPN passwords without pwgen, set EDITOR=nano
Use Ansible password lookup on the control node so install works before packages are installed on VPS and without pwgen on macOS. Export EDITOR=nano in Makefile for vault-edit.
2026-07-01 11:43:34 +03:00
inecs d4f968d799 fix: replace removed yaml callback with default + result_format
community.general.yaml was removed in collection 12.0; use ansible.builtin.default with result_format=yaml for Ansible 2.13+.
2026-07-01 11:09:08 +03:00
inecs 5ed370013b Align README with main branch: branches comparison, ACME renewal, switching.
Unified documentation structure across main and salamander branches.
2026-07-01 02:22:28 +03:00
inecs c9b283eca6 Add Salamander obfs branch: replace masquerade with packet obfuscation.
- ACME TLS challenge on 443 (no port 80 or nginx decoy)
- Auto-generate and persist obfs password per server
- Update client export, HTML catalog, and vault examples
- Document Salamander vs main and ACME auto-renewal in README
2026-07-01 02:17:22 +03:00
inecs df19816039 Initial commit: Ansible role for Hysteria2 VPN server deployment.
Includes install/update/uninstall playbooks, Makefile, vault-based SSH credentials, per-server and global HTML export with QR codes.
2026-07-01 02:02:58 +03:00
30 changed files with 2108 additions and 435 deletions
+24 -6
View File
@@ -32,7 +32,7 @@ BOLD := \033[1m
NC := \033[0m
.PHONY: help init check ping status \
install update export uninstall \
install update export index uninstall \
vault-init vault-encrypt vault-edit vault-view
help: ## Показать справку
@@ -48,7 +48,8 @@ help: ## Показать справку
@echo " make install"
@echo " make install LIMIT=vps-de"
@echo " make update LIMIT=vps-nl"
@echo " make uninstall LIMIT=vps-de EXTRA_VARS='hysteria2_uninstall_remove_local_output=true'"
@echo " make index"
@echo " make uninstall LIMIT=vps-de"
@echo ""
init: ## Создать inventory, group_vars и .vault_pass из примеров
@@ -67,14 +68,27 @@ init: ## Создать inventory, group_vars и .vault_pass из примеро
check: ## Проверить синтаксис playbook
$(ANSIBLE) playbook.yml --syntax-check $(VAULT_ARGS)
$(ANSIBLE) playbook-uninstall.yml --syntax-check $(VAULT_ARGS)
$(ANSIBLE) playbook-index.yml --syntax-check $(VAULT_ARGS)
ping: ## Проверить SSH-доступ ко всем VPS
$(ANSIBLE_ADHOC) hysteria2_servers -m ping $(ANSIBLE_OPTS)
status: ## Статус hysteria-server на VPS
status: ## Краткий статус hysteria-server на VPS
@ANSIBLE_DEPRECATION_WARNINGS=False ANSIBLE_STDOUT_CALLBACK=minimal \
$(ANSIBLE_ADHOC) hysteria2_servers -m shell \
-a "systemctl status hysteria-server --no-pager || systemctl status hysteria2 --no-pager" \
-b $(VAULT_ARGS) $(if $(LIMIT),--limit $(LIMIT),)
-a 'UNIT=""; \
if systemctl cat hysteria-server.service >/dev/null 2>&1; then UNIT=hysteria-server; \
elif systemctl cat hysteria2.service >/dev/null 2>&1; then UNIT=hysteria2; fi; \
if [ -z "$$UNIT" ]; then echo "not installed"; exit 0; fi; \
STATE=$$(systemctl is-active "$$UNIT" 2>/dev/null || true); \
[ -n "$$STATE" ] || STATE=inactive; \
SINCE=$$(systemctl show -p ActiveEnterTimestamp --value "$$UNIT" 2>/dev/null); \
PID=$$(systemctl show -p MainPID --value "$$UNIT" 2>/dev/null); \
MEM=$$(systemctl show -p MemoryCurrent --value "$$UNIT" 2>/dev/null); \
case "$$MEM" in ""|"[not set]"|"0"|"n/a") MEM="-";; *) MEM="$$((MEM/1024/1024))M";; esac; \
echo "$$UNIT: $$STATE | since $$SINCE | PID $$PID | RAM $$MEM"; \
[ "$$STATE" = "active" ]' \
-b $(ANSIBLE_OPTS)
install: check ## Установить Hysteria2 на VPS (+ URL и QR локально)
$(ANSIBLE) playbook.yml --tags install $(ANSIBLE_OPTS)
@@ -85,7 +99,11 @@ update: check ## Обновить бинарник, перекатить кон
export: check ## Только перевыпустить URL и QR (без изменений на сервере)
$(ANSIBLE) playbook.yml --tags export $(ANSIBLE_OPTS)
uninstall: ## Удалить Hysteria2 с VPS
index: check ## Пересобрать HTML серверов + output/index.html и открыть в браузере
$(ANSIBLE) playbook-index.yml $(VAULT_ARGS) \
$(if $(EXTRA_VARS),--extra-vars "$(EXTRA_VARS)",)
uninstall: ## Полностью удалить Hysteria2 с VPS (только uninstall, без install/update)
@echo "$(YELLOW)Будет выполнено удаление Hysteria2$(NC) $(if $(LIMIT),на $(LIMIT),на всех серверах)"
@read -p "Продолжить? [y/N] " c; [[ "$$c" =~ ^[Yy]$$ ]] || exit 1
$(ANSIBLE) playbook-uninstall.yml --tags uninstall $(ANSIBLE_OPTS)
+242 -79
View File
@@ -1,16 +1,30 @@
# Hysteria2 Ansible — ветка **main**
# Hysteria2 Ansible — ветка **Salamander**
> **Ветка:** `main`
> **Режим:** **masquerade** — маскировка под HTTPS-сайт nginx
> **Альтернатива:** [`salamander`](https://git.antropoff.ru/DevOpsTools/hysteria2/src/branch/salamander) — обфускация Salamander для агрессивного DPI
> **Ветка:** `salamander`
> **Режим:** **Salamander obfs** — запутывание пакетов для обхода DPI
> **Основная ветка:** [`main`](https://git.antropoff.ru/DevOpsTools/hysteria2/src/branch/main) — masquerade под HTTPS-сайт nginx
Ansible-роль для установки [Hysteria 2](https://v2.hysteria.network/) на Debian/Ubuntu VPS: Let's Encrypt, masquerade под nginx, несколько пользователей, экспорт URL/QR и HTML-каталог.
Ansible-роль для установки [Hysteria 2](https://v2.hysteria.network/) на Debian/Ubuntu VPS с **Salamander obfs** — когда masquerade под «обычный сайт» недостаточен.
---
## Последние обновления
### 2026-07-23
- **`make status`** — краткий статус по хостам (active / not installed, PID, RAM), без длинных логов journal.
- **`make index`** — пересборка HTML всех серверов и общего `output/index.html` из локальных `server-info.yml` (без SSH), открытие в браузере.
- **Каталог `output/index.html`** — вкладки «Статистика» (по умолчанию) и серверы (`vps-db`, `vps-kz`, …): IP, доступность TCP, пользователи, матрица присутствия.
- **Страницы серверов** — сетка карточек и визуальный стиль как у главной; ссылка «← Общий каталог».
- **Lightbox QR** — крупный просмотр на высоту экрана, кнопка скачивания `<сервер>-<пользователь>.png`.
- **Скачивание файлов** — ссылки `.url` / `.txt` / `.png` / `.qr.txt` принудительно скачивают файл как `<сервер>-<пользователь>.ext`, а не открывают его во вкладке браузера.
- **`make install` / `make update` / `make export`** — в конце тот же pipeline HTML, что и у `make index`.
---
## Выбор ветки: `main` или `salamander`
| | **`main` (эта ветка)** | **`salamander`** |
| | **`main`** | **`salamander` (эта ветка)** |
|---|---|---|
| Маскировка | HTTPS-сайт nginx + Let's Encrypt | **Salamander obfs** — пакеты выглядят как шум |
| Порт 80/tcp | **Нужен** (ACME HTTP + masquerade) | **Не нужен** |
@@ -20,19 +34,18 @@ Ansible-роль для установки [Hysteria 2](https://v2.hysteria.netw
| URI клиента | `hysteria2://user:pass@domain:443` | + `obfs=salamander&obfs-password=...` |
| Лучше когда | Нужен «легитимный» сайт в браузере | Агрессивный DPI, блокировка QUIC fingerprint |
### Когда выбирать `main`
- нужен **нормальный HTTPS-сайт** при открытии домена в браузере;
- достаточно маскировки под nginx;
- хотите **минимум параметров** в URI клиента;
- провайдер не «палит» Hysteria/QUIC внутри TLS.
### Когда выбирать `salamander`
- masquerade из `main` **блокируют** или распознают по fingerprint;
- не нужен фейковый сайт;
- не нужен фейковый сайт в браузере;
- готовы хранить **дополнительный** obfs-пароль.
### Когда выбирать `main`
- нужен **нормальный HTTPS-сайт** при открытии домена;
- достаточно маскировки под nginx;
- хотите **минимум параметров** в URI клиента.
---
## Быстрый старт
@@ -40,16 +53,25 @@ Ansible-роль для установки [Hysteria 2](https://v2.hysteria.netw
```bash
git clone https://git.antropoff.ru/DevOpsTools/hysteria2.git
cd hysteria2
git checkout main
git checkout salamander
# macOS: установить Ansible (если ещё нет)
brew install ansible
make init
# отредактировать inventory/hosts.yml, group_vars/all.yml, vault
# отредактировать:
# inventory/hosts.yml
# group_vars/all.yml
# group_vars/hysteria2_servers/vault.yml
# group_vars/hysteria2_servers/vars.yml (проброс vault → роль)
make vault-encrypt
make ping
make install # → output/index.html откроется в браузере
```
После `make init` создаются локальные файлы из `.example` (не коммитятся). Пароль vault хранится в `.vault_pass`.
---
## Makefile
@@ -57,25 +79,35 @@ make install # → output/index.html откроется в браузере
| Команда | Описание |
|---|---|
| `make help` | Справка |
| `make init` | Создать конфиги из `.example` |
| `make init` | Создать конфиги из `.example` и `.vault_pass` |
| `make check` | Проверить синтаксис playbook |
| `make ping` | Проверить SSH к VPS |
| `make status` | `systemctl status hysteria-server` |
| `make install` | Установка masquerade + экспорт URL/QR/HTML |
| `make update` | Обновить бинарник, конфиг, перевыпустить экспорт |
| `make export` | Только экспорт (URL, QR, HTML) |
| `make uninstall` | Удалить Hysteria2 с VPS |
| `make vault-encrypt` | Зашифровать vault |
| `make vault-edit` | Редактировать vault |
| `make status` | Краткий статус: active / not installed, uptime, PID, RAM |
| `make install` | Установка Salamander + экспорт URL/QR/HTML |
| `make update` | Обновить бинарник и конфиг; экспорт только для новых/изменённых пользователей |
| `make export` | Только экспорт (URL, QR, HTML) без изменений на сервере |
| `make index` | Пересобрать HTML всех серверов + общий `output/index.html` и открыть в браузере |
| `make uninstall` | Полное удаление с VPS + `output/<server>/` + пересборка `output/index.html` |
| `make vault-init` | Создать `.vault_pass`, включить `vault_password_file` в `ansible.cfg` |
| `make vault-encrypt` | Зашифровать `vault.yml` |
| `make vault-edit` | Редактировать vault (редактор **nano**, см. `EDITOR` в Makefile) |
| `make vault-view` | Показать расшифрованный vault |
```bash
make install LIMIT=vps-de
make install LIMIT=vps-nl # только новый сервер — старые не трогаются
make update LIMIT=vps-nl
make export
make uninstall LIMIT=vps-de EXTRA_VARS='hysteria2_uninstall_remove_local_output=true'
make index # только пересобрать общий каталог из output/
make uninstall LIMIT=vps-de
make update EXTRA_VARS='hysteria2_force_export=true' # перевыпустить URL/QR для всех
make install EXTRA_VARS='hysteria2_force_export=true' # то же при install
make install EXTRA_VARS='hysteria2_open_browser=false'
make update EXTRA_VARS='hysteria2_wait_for_acme=false'
```
`LIMIT` — имя хоста из `inventory/hosts.yml` (например `vps-de`).
---
## Inventory
@@ -90,7 +122,7 @@ all:
ansible_port: 2222 # SSH-порт (если не 22)
ansible_user: root
ansible_password: "{{ vault_ssh_passwords['vps-de'] }}"
hysteria2_domain: vpn-de.example.com
hysteria2_domain: vpn-de.example.com # для TLS/SNI и ACME
hysteria2_users:
- my
- friend
@@ -126,7 +158,7 @@ vault_ssh_passwords:
---
## Как работает masquerade в этом проекте
## Как работает Salamander в этом проекте
### Сервер (`/etc/hysteria/config.yaml`)
@@ -134,7 +166,7 @@ vault_ssh_passwords:
listen: 0.0.0.0:443
acme:
type: http
type: tls # сертификат без порта 80
domains:
- vpn-de.example.com
email: admin@example.com
@@ -145,38 +177,36 @@ auth:
my: "..."
friend: "..."
masquerade:
type: file
file:
dir: /var/www/masq
listenHTTP: :80
listenHTTPS: :443
forceHTTPS: true
obfs:
type: salamander
salamander:
password: "общий_obfs_пароль_сервера"
```
### Сайт-заглушка
В `/var/www/masq/index.html` — официальная страница **Welcome to nginx!**
При открытии домена в браузере — валидный HTTPS-сайт с Let's Encrypt.
### Клиент (генерируется автоматически)
```yaml
server: vpn-de.example.com:443
auth: my:password
obfs:
type: salamander
salamander:
password: общий_obfs_пароль_сервера
```
### URI (пример)
```
hysteria2://my:password@vpn-de.example.com:443#my
hysteria2://my:password@vpn-de.example.com:443?obfs=salamander&obfs-password=OBFS_PASS#my
```
Роль вызывает `hysteria share` — URI и QR формируются автоматически.
Роль вызывает `hysteria share` — URI и QR уже содержат параметры Salamander.
---
## Пароли VPN-пользователей
## Пароли
### VPN-пользователи (`userpass`)
1. **Vault (рекомендуется):**
@@ -189,6 +219,7 @@ vault_hysteria2_user_passwords:
Подключается через `group_vars/hysteria2_servers/vars.yml`:
```yaml
hysteria2_user_passwords: "{{ vault_hysteria2_user_passwords[inventory_hostname] | default({}) }}"
```
2. **Per-host в inventory:**
@@ -198,9 +229,108 @@ hysteria2_user_passwords:
friend: "custom-password"
```
3. **Автогенерация** — Ansible `password` lookup (длина `hysteria2_password_length`), если пароль не задан.
3. **Автогенерация** — Ansible `password` lookup, если пароль не задан ни в inventory/vault, ни в `output/<server>/server-info.yml`.
При `make update` пароли подтягиваются из `output/<server>/server-info.yml`, если не указаны в vault/inventory.
При `make update` / `make export`:
- **существующие** пользователи сохраняют пароли из `server-info.yml` (и URL/QR, если домен/порт/obfs не менялись);
- **новые** получают автогенерацию и полный экспорт;
- **удалённые** из inventory убираются из конфига Hysteria2 и из `output/<server>/`.
### Salamander obfs (один на сервер)
1. **Vault (рекомендуется):**
```yaml
vault_hysteria2_obfs_passwords:
vps-de: "cry_me_a_r1ver_salamander_obfs"
```
Подключается через `group_vars/hysteria2_servers/vars.yml`:
```yaml
hysteria2_obfs_password: "{{ vault_hysteria2_obfs_passwords[inventory_hostname] | default('') }}"
```
2. **Авто:** Ansible `password` lookup (`hysteria2_obfs_password_length`) при первой установке
3. **При update/export:** загружается из `output/<server>/server-info.yml` (как VPN-пароли)
> **Важно:** obfs-пароль на сервере и клиенте должен **совпадать**. При `make update` без vault пароль сохраняется из предыдущего экспорта.
Принудительно перевыпустить URL/QR для всех VPN-пользователей: `hysteria2_force_export: true`.
```bash
make install EXTRA_VARS='hysteria2_force_export=true'
make update LIMIT=vps-de EXTRA_VARS='hysteria2_force_export=true'
```
### Добавить второй VPS
После `make install` на первом сервере можно добавить ещё один хост в `inventory/hosts.yml`.
**Без `LIMIT`** `make install` пройдёт по **всем** серверам из inventory. На уже установленном пароли и файлы URL/QR **не перегенерируются** (берутся из `output/<server>/server-info.yml`), если вы не меняли его `hysteria2_users`, домен или порт.
Чтобы **не трогать** уже работающий VPS и экспорт:
```bash
make install LIMIT=новый-сервер
```
`LIMIT` — имя нового хоста из inventory (например `vps-nl`).
### Добавить / удалить пользователя
1. Отредактируйте `hysteria2_users` в `inventory/hosts.yml`.
2. Запустите `make update LIMIT=<хост>`.
Пароли и obfs существующих клиентов **не меняются** (из `server-info.yml`).
Новому пользователю генерируется пароль и создаются URL/QR с параметрами Salamander.
Удалённый пользователь пропадает из конфига и из `output/<server>/`.
---
## Установка бинарника Hysteria2
Официальный скрипт `install_server.sh` хранится в `roles/hysteria2/files/`.
Перед `make install` / `make update` на **control node**:
1. Скачивается копия с https://get.hy2.sh/
2. Сравнивается SHA256 с локальным файлом в роли
3. При отличии — локальная копия обновляется
4. Скрипт копируется на VPS и запускается оттуда
---
## `make update` — что меняется
| Компонент | Поведение |
|---|---|
| Бинарник `hysteria` | Обновляется (`install_server.sh --force`) |
| `/etc/hysteria/config.yaml` | Перекатывается (auth + obfs) |
| Пароли VPN / obfs | Сохраняются для существующей конфигурации |
| URL / QR | Только для новых, изменённых или при `hysteria2_force_export=true` |
| `apt upgrade` | **Не** выполняется |
| Ожидание ACME | **Не** выполняется |
---
## `make uninstall` — полная очистка
На **VPS** (официальный `install_server.sh --remove` + дочистка Ansible):
- бинарник `/usr/local/bin/hysteria` и unit-файлы systemd;
- `/etc/hysteria/` (конфиг и ACME);
- `/var/lib/hysteria` и пользователь `hysteria`;
- symlink'и `multi-user.target.wants/hysteria-server*`;
- временные `/tmp/hysteria-client-*.yaml`;
- правила ufw: `443/tcp`, `443/udp` (порт из `hysteria2_listen_port`);
- пакеты `curl`, `micro`, `qrencode`.
На **control node**:
- удаляется `output/<имя_сервера>/`;
- пересобирается общий `output/index.html` (сервер убирается из списка; при `LIMIT=...` тоже);
- если серверов не осталось — `output/index.html` удаляется.
---
@@ -210,11 +340,11 @@ hysteria2_user_passwords:
При блоке `acme:` в конфиге встроенный ACME-клиент Hysteria2 сам получает и **продлевает** сертификат Let's Encrypt (срок ~90 дней). Повторный `make install` или certbot для продления **не нужны** — процесс `hysteria-server` делает это сам.
**Условия для авто-продления (ветка `main`):**
**Условия для авто-продления (ветка `salamander`):**
- сервер **запущен** и доступен из интернета;
- домен указывает на IP VPS;
- порты **80/tcp** и **443/tcp** открыты (ACME HTTP challenge + masquerade);
- порт **443/tcp** открыт (ACME TLS-ALPN challenge);
- конфиг `acme` не удалён.
Проверка логов: `journalctl -u hysteria-server -f`
@@ -223,11 +353,12 @@ hysteria2_user_passwords:
## Firewall
По умолчанию открываются:
По умолчанию открываются только порты Hysteria2:
- **80/tcp** — ACME HTTP + masquerade HTTP
- **443/tcp** — HTTPS masquerade
- **443/udp** — Hysteria2
- **443/tcp**
- **443/udp**
**Порт 80 не используется** — в отличие от ветки `main`.
---
@@ -237,23 +368,26 @@ hysteria2_user_passwords:
output/
├── index.html ← все серверы (открывается в браузере)
├── vps-de/
│ ├── index.html ← страница сервера
│ ├── my.url
│ ├── index.html ← страница сервера + obfs-пароль
│ ├── my.url ← URI с obfs=salamander
│ ├── my.png ← QR PNG
│ ├── my.qr.txt ← QR ASCII
│ ├── my.txt
│ └── server-info.yml
│ └── server-info.yml ← mode, obfs_password, users
└── vps-nl/
└── ...
```
HTML-страницы показывают:
- пароль и URL каждого пользователя с **кнопкой копирования**;
- режим **Salamander** и **obfs-password** с кнопкой копирования;
- пароль и URL каждого пользователя;
- QR-коды;
- ссылки на файлы и страницы серверов.
После `make install`, `make update` и `make export` **`output/index.html` автоматически открывается в браузере** (macOS: `open`, Linux: `xdg-open`).
После `make install`, `make update`, `make export` и `make index` **`output/index.html` автоматически открывается в браузере** (macOS: `open`, Linux: `xdg-open`).
`make index` не ходит на VPS: только читает `output/*/server-info.yml` и пересобирает общий каталог.
Отключить: `hysteria2_open_browser: false` в `group_vars/all.yml` или `EXTRA_VARS`.
@@ -275,33 +409,48 @@ ASCII QR — `hysteria share --qr` → `user.qr.txt`.
| Переменная | Где | Описание |
|---|---|---|
| `hysteria2_domain` | host | Домен с A-записью на IP |
| `hysteria2_users` | host | Список имён VPN-пользователей |
| `hysteria2_acme_email` | group | Email для Let's Encrypt |
| `hysteria2_user_passwords` | host/vault | Свои пароли VPN |
| `hysteria2_output_dir` | group | Папка экспорта (по умолчанию `./output`) |
| `hysteria2_output_name` | host | Имя подпапки (по умолчанию `inventory_hostname`) |
| `hysteria2_listen_port` | group | Порт Hysteria2 (443) |
| `hysteria2_mode` | defaults | `salamander` (информативно) |
| `hysteria2_domain` | host | Домен для TLS/SNI/ACME |
| `hysteria2_users` | host | VPN-пользователи |
| `hysteria2_acme_email` | group | Email Let's Encrypt |
| `hysteria2_user_passwords` | host/vault | Фиксированные пароли VPN |
| `hysteria2_password_length` | group | Длина автопароля VPN (40) |
| `hysteria2_force_export` | group | Перегенерировать URL/QR для всех (`false`) |
| `hysteria2_obfs_password` | host/vault | Пароль Salamander (или авто) |
| `hysteria2_obfs_password_length` | group | Длина автопароля obfs (32) |
| `hysteria2_output_dir` | group | Папка экспорта (`./output`) |
| `hysteria2_listen_port` | group | Порт (443) |
| `hysteria2_upgrade_system` | group | `apt upgrade` перед install |
| `hysteria2_configure_firewall` | group | Открыть порты в ufw |
| `hysteria2_generate_qr_png` | group | PNG QR через `qrencode` |
| `hysteria2_wait_for_acme` | group | Пауза при первом ACME |
| `hysteria2_open_browser` | group | Открыть `output/index.html` после экспорта |
| `hysteria2_uninstall_remove_local_output` | extra-vars | Удалить `output/<server>/` при uninstall |
| `hysteria2_uninstall_rebuild_global_index` | group | Пересобрать `output/index.html` после uninstall (`true`) |
| `vault_ssh_passwords` | vault | SSH-пароли root |
| `vault_hysteria2_user_passwords` | vault | VPN-пароли по серверам |
| `vault_hysteria2_obfs_passwords` | vault | obfs-пароли по серверам |
Полный список: `roles/hysteria2/defaults/main.yml`, `defaults/uninstall.yml`.
---
## Безопасность
- `output/` содержит пароли и URL — **не коммитить**`.gitignore`)
- `output/` содержит пароли, obfs-ключи и URL — **не коммитить**`.gitignore`)
- `inventory/hosts.yml`, `vault.yml`, `.vault_pass` — не коммитить
- После `make init` выполните `make vault-encrypt`
- Salamander **не делает** вас невидимым: IP VPS и UDP-поток всё ещё можно анализировать
---
## Требования
- Ansible 2.14+
- Debian/Ubuntu VPS с sudo
- Домен с A-записью на IP сервера
- Для авто-открытия браузера: macOS или Linux с `xdg-open`
- **Control node:** macOS или Linux с Ansible **2.14+** (`brew install ansible` на Mac)
- **VPS:** Debian/Ubuntu с sudo
- Домен с A-записью на IP (для ACME TLS)
- Порт **443/tcp+udp** доступен с интернета
- Клиент Hysteria2 с поддержкой Salamander (Shadowrocket, NekoBox, Hiddify и др.)
- Для авто-открытия браузера: macOS (`open`) или Linux (`xdg-open`)
---
@@ -309,16 +458,30 @@ ASCII QR — `hysteria share --qr` → `user.qr.txt`.
```
roles/hysteria2/
├── defaults/
│ ├── main.yml
│ └── uninstall.yml
├── files/
│ └── install_server.sh
├── tasks/
│ ├── install.yml ← пакеты, hysteria, qrencode
│ ├── configure.yml ← masquerade + ACME + firewall
│ ├── export.yml ← URL, QR, HTML сервера
── export_global.yml ← общий output/index.html
│ ├── main.yml
│ ├── validate.yml
│ ├── users.yml
── obfs.yml ← пароль Salamander obfs
│ ├── sync_install_script.yml
│ ├── install.yml
│ ├── configure.yml ← Salamander, без masquerade
│ ├── update.yml
│ ├── export_prepare.yml
│ ├── export.yml
│ ├── export_global.yml
│ ├── share_user.yml
│ ├── reuse_export_user.yml
│ └── uninstall.yml
└── templates/
├── config.yaml.j2 ← acme http + masquerade file
├── config.yaml.j2 ← acme tls + obfs salamander
├── client.yaml.j2
── masq/index.html.j2
└── export/ ← HTML-каталоги
── export/
```
---
@@ -327,15 +490,15 @@ roles/hysteria2/
```bash
git fetch origin
git checkout main # masquerade + nginx (эта ветка)
git checkout salamander # Salamander obfs
git checkout main # masquerade + nginx
git checkout salamander # Salamander obfs (эта ветка)
```
Конфиги на **уже установленном** сервере **не меняются** при переключении ветки в git.
Чтобы применить другой режим на VPS:
```bash
git checkout salamander # или main
git checkout main # или salamander
make install # перекатит конфиг сервера
# или
make update
+5 -2
View File
@@ -17,8 +17,11 @@ hysteria2_output_dir: "{{ playbook_dir }}/output"
# Открывать output/index.html в браузере после install/update/export
# hysteria2_open_browser: true
# Порт Hysteria2
# Порт Hysteria2 (Salamander — достаточно открыть только его, 80/tcp не нужен)
hysteria2_listen_port: 443
# Открывать порты в ufw (80/tcp, 443/tcp, 443/udp)
# Открывать порты в ufw ({{ hysteria2_listen_port }}/tcp и /udp)
hysteria2_configure_firewall: true
# Длина пароля Salamander obfs
# hysteria2_obfs_password_length: 32
@@ -3,3 +3,7 @@
# Файл group_vars/hysteria2_servers/vault.yml должен быть зашифрован (make vault-encrypt).
# Проброс VPN-паролей из vault в переменные роли (опционально)
hysteria2_user_passwords: "{{ vault_hysteria2_user_passwords[inventory_hostname] | default({}) }}"
# Опционально: фиксированный пароль Salamander obfs для сервера
# hysteria2_obfs_password: "{{ vault_hysteria2_obfs_passwords[inventory_hostname] | default('') }}"
@@ -14,5 +14,8 @@ vault_ssh_passwords:
# vault_hysteria2_user_passwords:
# vps-de:
# friend: "Aingae0Okit1eek4eeZahFohVei4akee"
# vps-nl:
# alice: "CustomAlicePassword40chars................"
# Опционально: пароль Salamander obfs (один на сервер)
# vault_hysteria2_obfs_passwords:
# vps-de: "cry_me_a_r1ver_salamander_obfs_pass"
# vps-nl: "another_obfs_password_32chars!!"
+11
View File
@@ -0,0 +1,11 @@
---
- name: Rebuild HTML catalogs from local exports
hosts: localhost
connection: local
gather_facts: true
become: false
tasks:
- name: Regenerate server pages and global index.html
ansible.builtin.include_role:
name: hysteria2
tasks_from: export_rebuild_local.yml
+24 -3
View File
@@ -2,6 +2,27 @@
- name: Uninstall Hysteria2 servers
hosts: hysteria2_servers
gather_facts: false
roles:
- role: hysteria2
tags: [uninstall]
tags: [uninstall]
tasks:
- name: Run Hysteria2 uninstall tasks only
ansible.builtin.include_role:
name: hysteria2
tasks_from: uninstall.yml
- name: Rebuild global output index after uninstall
hosts: hysteria2_servers
gather_facts: false
tags: [uninstall]
tasks:
- name: Regenerate output/index.html without removed server
block:
- name: Run global export tasks
ansible.builtin.include_role:
name: hysteria2
tasks_from: export_global.yml
vars:
hysteria2_open_browser: false
run_once: true
delegate_to: localhost
become: false
when: hysteria2_uninstall_rebuild_global_index | default(true) | bool
+3 -3
View File
@@ -5,14 +5,14 @@
roles:
- hysteria2
- name: Build global output index
- name: Build HTML catalogs from local exports
hosts: localhost
connection: local
gather_facts: true
become: false
tags: [install, update, export]
tasks:
- name: Generate global index.html and open in browser
- name: Regenerate server pages and global index.html
ansible.builtin.include_role:
name: hysteria2
tasks_from: export_global.yml
tasks_from: export_rebuild_local.yml
+19 -12
View File
@@ -1,5 +1,8 @@
---
# Домен сервера (A-запись → IP VPS). Задаётся per-host в inventory.
# Режим развёртывания (ветка salamander)
hysteria2_mode: salamander
# Домен сервера (A-запись → IP VPS). Используется для TLS/SNI и ACME.
hysteria2_domain: ""
# Email для ACME / Let's Encrypt
@@ -9,14 +12,17 @@ hysteria2_acme_email: ""
hysteria2_users: []
# Опционально: фиксированные пароли { username: password }
# Пустое значение или отсутствие ключа — автогенерация на control node (Ansible password lookup)
# Пароль обфускации Salamander (общий для сервера).
# Пусто — автогенерация на control node (Ansible password lookup) или загрузка из output/<server>/server-info.yml
hysteria2_obfs_password: ""
hysteria2_password_length: 40
hysteria2_obfs_password_length: 32
hysteria2_listen_port: 443
hysteria2_upgrade_system: true
hysteria2_configure_firewall: true
hysteria2_masq_dir: /var/www/masq
hysteria2_config_path: /etc/hysteria/config.yaml
hysteria2_service_name: hysteria-server
@@ -26,23 +32,24 @@ hysteria2_install_script_name: install_server.sh
hysteria2_install_script_staging_dir: "{{ playbook_dir }}/.cache/hysteria2"
hysteria2_install_script_remote_path: /tmp/hysteria2-install_server.sh
# Локальный каталог для экспорта URL и QR (на control node)
hysteria2_output_dir: "{{ playbook_dir }}/output"
hysteria2_output_name: "{{ inventory_hostname }}"
# Генерировать PNG QR-коды через qrencode (apt на VPS, fetch на control node)
hysteria2_generate_qr_png: true
hysteria2_qr_png_size: 6
hysteria2_qr_png_margin: 2
hysteria2_qr_png_error_correction: M
# Ждать ACME при первом запуске (отключите при update: make update)
hysteria2_wait_for_acme: true
# Открыть output/index.html в браузере после install/update/export
hysteria2_open_browser: true
# --- uninstall ---
hysteria2_uninstall_remove_config: true
hysteria2_uninstall_remove_masq: true
hysteria2_uninstall_remove_local_output: false
# Перегенерировать URL/QR для всех пользователей (иначе — только новые/изменённые)
hysteria2_force_export: false
# --- uninstall (см. также defaults/uninstall.yml) ---
hysteria2_system_user: hysteria
hysteria2_uninstall_remove_masq: false
hysteria2_uninstall_rebuild_global_index: true
hysteria2_uninstall_ufw_rules:
- "{{ hysteria2_listen_port }}/tcp"
- "{{ hysteria2_listen_port }}/udp"
+11
View File
@@ -0,0 +1,11 @@
---
# Системный пользователь Hysteria (создаётся install_server.sh)
hysteria2_system_user: hysteria
# --- uninstall (Salamander: без masq, порты listen_port/tcp+udp) ---
# install_server.sh --remove: бинарник + systemd; остальное — задачи uninstall.yml
hysteria2_uninstall_remove_masq: false
hysteria2_uninstall_rebuild_global_index: true
hysteria2_uninstall_ufw_rules:
- "{{ hysteria2_listen_port }}/tcp"
- "{{ hysteria2_listen_port }}/udp"
+4 -4
View File
@@ -38,7 +38,7 @@ HY2_API_BASE_URL="https://api.hy2.io/v1"
# curl command line flags.
# To using a proxy, please specify ALL_PROXY in the environ variable, such like:
# export ALL_PROXY=socks5h://192.0.2.1:1080
CURL_FLAGS=(-L -f -q --retry 5 --retry-delay 10 --retry-max-time 60)
CURL_FLAGS=(-q -L -f --retry 5 --retry-delay 10 --retry-max-time 60)
###
@@ -1027,10 +1027,10 @@ perform_install_hysteria_home_legacy() {
}
perform_install() {
local _is_frash_install
local _is_fresh_install
local _is_upgrade_from_hysteria1
if ! is_hysteria_installed; then
_is_frash_install=1
_is_fresh_install=1
elif is_hysteria1_version "$(get_installed_version)"; then
_is_upgrade_from_hysteria1=1
fi
@@ -1067,7 +1067,7 @@ perform_install() {
echo
echo "$(tgreen)Installed version is up-to-date, there is nothing to do.$(treset)"
echo
elif [[ -n "$_is_frash_install" ]]; then
elif [[ -n "$_is_fresh_install" ]]; then
echo
echo -e "$(tbold)Congratulation! Hysteria 2 has been successfully installed on your server.$(treset)"
echo
+1 -1
View File
@@ -2,7 +2,7 @@
galaxy_info:
role_name: hysteria2
author: inecs
description: Install Hysteria2 VPN server with masquerade site and export client URLs with QR codes
description: Install Hysteria2 VPN server with Salamander obfs and export client URLs with QR codes
license: MIT
min_ansible_version: "2.14"
platforms:
+6 -20
View File
@@ -1,24 +1,11 @@
---
- name: Create masquerade web directory
ansible.builtin.file:
path: "{{ hysteria2_masq_dir }}"
state: directory
mode: "0755"
- name: Deploy masquerade index.html
ansible.builtin.template:
src: masq/index.html.j2
dest: "{{ hysteria2_masq_dir }}/index.html"
mode: "0644"
notify: Restart hysteria-server
- name: Remove default Hysteria config if present
ansible.builtin.file:
path: "{{ hysteria2_config_path }}"
state: absent
when: not ansible_check_mode
- name: Deploy Hysteria2 server config
- name: Deploy Hysteria2 Salamander server config
ansible.builtin.template:
src: config.yaml.j2
dest: "{{ hysteria2_config_path }}"
@@ -42,12 +29,11 @@
failed_when: false
when: hysteria2_configure_firewall | bool
- name: Allow HTTP and HTTPS in ufw
- name: Allow Hysteria2 port in ufw (Salamander — только {{ hysteria2_listen_port }})
ansible.builtin.command: "ufw allow {{ item }}"
loop:
- 80/tcp
- 443/tcp
- 443/udp
- "{{ hysteria2_listen_port }}/tcp"
- "{{ hysteria2_listen_port }}/udp"
register: _hysteria2_ufw_allow
changed_when: "'Skipping' not in (_hysteria2_ufw_allow.stdout | default(''))"
failed_when: false
@@ -55,10 +41,10 @@
- hysteria2_configure_firewall | bool
- "'active' in (_hysteria2_ufw_status.stdout | default(''))"
- name: Wait for ACME certificate (first start may take several minutes)
- name: Wait for ACME TLS certificate (first start may take several minutes)
ansible.builtin.pause:
seconds: 30
prompt: "Ожидание получения ACME-сертификата для {{ hysteria2_domain }}..."
prompt: "Ожидание получения ACME TLS-сертификата для {{ hysteria2_domain }}..."
when: hysteria2_wait_for_acme | default(true) | bool
- name: Verify hysteria-server is running
+23 -5
View File
@@ -11,16 +11,28 @@
ansible.builtin.set_fact:
hysteria2_export_users: []
- name: Prepare incremental export (remove deleted users, split new vs existing)
ansible.builtin.import_tasks: export_prepare.yml
- name: Install qrencode on server for PNG QR export
ansible.builtin.apt:
name: qrencode
state: present
update_cache: false
when: hysteria2_generate_qr_png | bool
when:
- hysteria2_generate_qr_png | bool
- hysteria2_users_for_export | default([]) | length > 0
- name: Build client share data for each user
- name: Reuse existing export data for unchanged users
ansible.builtin.include_tasks: reuse_export_user.yml
loop: "{{ hysteria2_users_for_reuse | default([]) }}"
loop_control:
loop_var: hysteria2_reuse_user
label: "{{ hysteria2_reuse_user.name }}"
- name: Build client share data for new or changed users
ansible.builtin.include_tasks: share_user.yml
loop: "{{ hysteria2_resolved_users }}"
loop: "{{ hysteria2_users_for_export | default([]) }}"
loop_control:
loop_var: hysteria2_current_user
label: "{{ hysteria2_current_user.name }}"
@@ -31,8 +43,11 @@
mode: "0600"
content: |
server: {{ hysteria2_output_name }}
mode: salamander
domain: {{ hysteria2_domain }}
port: {{ hysteria2_listen_port }}
host_ip: "{{ ansible_host | default('') }}"
obfs_password: "{{ hysteria2_obfs_password }}"
users:
{% for user in hysteria2_export_users %}
- name: {{ user.name }}
@@ -53,11 +68,14 @@
mode: "0644"
vars:
generated_at: "{{ now(utc=false, fmt='%Y-%m-%d %H:%M:%S') }}"
hysteria2_obfs_password: "{{ hysteria2_obfs_password }}"
delegate_to: localhost
become: false
- name: Show export location
ansible.builtin.debug:
msg: >-
Клиентские URL, QR и index.html сохранены в
{{ hysteria2_output_dir }}/{{ hysteria2_output_name }}/
Экспорт: {{ hysteria2_users_for_export | default([]) | length }} пользователь(ей) обновлено,
{{ hysteria2_users_for_reuse | default([]) | length }} без изменений,
{{ _hysteria2_removed_users | default([]) | length }} удалено.
Каталог: {{ hysteria2_output_dir }}/{{ hysteria2_output_name }}/
+77 -2
View File
@@ -29,10 +29,18 @@
when: not item.skipped | default(false)
vars:
_info: "{{ item.content | b64decode | from_yaml }}"
_server_name: "{{ _info.server }}"
_entry:
name: "{{ _info.server }}"
name: "{{ _server_name }}"
domain: "{{ _info.domain }}"
port: "{{ _info.port }}"
mode: "{{ _info.mode | default('salamander') }}"
host_ip: >-
{{
_info.host_ip
| default(hostvars[_server_name].ansible_host | default(''), true)
}}
obfs_password: "{{ _info.obfs_password | default('') }}"
dir: "{{ item.item.path | dirname | basename }}"
users: "{{ _info.users }}"
become: false
@@ -43,6 +51,64 @@
when: hysteria2_global_servers | default([]) | length > 0
become: false
- name: Probe TCP reachability of exported servers
ansible.builtin.wait_for:
host: "{{ item.host_ip if (item.host_ip | default('') | length > 0) else item.domain }}"
port: "{{ item.port | int }}"
timeout: 3
state: started
loop: "{{ hysteria2_global_servers | default([]) }}"
loop_control:
label: "{{ item.name }}"
register: _hysteria2_probe
failed_when: false
changed_when: false
become: false
when: hysteria2_global_servers | default([]) | length > 0
- name: Merge probe result for each server
ansible.builtin.set_fact:
hysteria2_global_servers_enriched: >-
{{
(hysteria2_global_servers_enriched | default([]))
+ [
hysteria2_global_servers[item] | combine({
'reachable': not ((_hysteria2_probe.results | default([]))[item].failed | default(true)),
'probe_seconds': (_hysteria2_probe.results | default([]))[item].elapsed | default(none)
})
]
}}
loop: "{{ range(0, hysteria2_global_servers | length) | list }}"
when: hysteria2_global_servers | default([]) | length > 0
become: false
- name: Replace servers list with enriched data
ansible.builtin.set_fact:
hysteria2_global_servers: "{{ hysteria2_global_servers_enriched }}"
when: hysteria2_global_servers_enriched is defined
become: false
- name: Compute unique users across servers
ansible.builtin.set_fact:
hysteria2_unique_users: >-
{{
hysteria2_global_servers
| map(attribute='users')
| map('map', attribute='name')
| flatten
| unique
| sort
}}
hysteria2_reachable_count: >-
{{
hysteria2_global_servers
| selectattr('reachable')
| list
| length
}}
when: hysteria2_global_servers | default([]) | length > 0
become: false
- name: Generate global HTML index
ansible.builtin.template:
src: export/global-index.html.j2
@@ -51,9 +117,18 @@
vars:
generated_at: "{{ now(utc=false, fmt='%Y-%m-%d %H:%M:%S') }}"
total_users: "{{ hysteria2_global_servers | map(attribute='users') | map('length') | sum }}"
unique_users: "{{ hysteria2_unique_users | default([]) }}"
reachable_count: "{{ hysteria2_reachable_count | default(0) }}"
when: hysteria2_global_servers | default([]) | length > 0
become: false
- name: Remove global HTML index when no servers remain
ansible.builtin.file:
path: "{{ hysteria2_output_dir }}/index.html"
state: absent
when: hysteria2_global_servers | default([]) | length == 0
become: false
- name: Open global index in default browser (macOS)
ansible.builtin.command:
cmd: open "{{ hysteria2_output_dir }}/index.html"
@@ -85,6 +160,6 @@
- name: Skip global index when no servers exported
ansible.builtin.debug:
msg: "Глобальный index.html не создан — нет server-info.yml в {{ hysteria2_output_dir }}/"
msg: "Глобальный {{ hysteria2_output_dir }}/index.html удалён — нет server-info.yml в output/"
when: hysteria2_global_servers | default([]) | length == 0
become: false
+84
View File
@@ -0,0 +1,84 @@
---
- name: Determine removed users from previous export
ansible.builtin.set_fact:
_hysteria2_removed_users: >-
{{
(_hysteria2_saved_server_info.users | default([]) | map(attribute='name') | list)
| difference(hysteria2_resolved_users | map(attribute='name') | list)
}}
delegate_to: localhost
become: false
- name: Build list of export files to remove for deleted users
ansible.builtin.set_fact:
_hysteria2_removed_user_files: >-
{{
_hysteria2_removed_user_files | default([]) + [
hysteria2_output_dir ~ '/' ~ hysteria2_output_name ~ '/' ~ item.0 ~ item.1
]
}}
loop: "{{ _hysteria2_removed_users | default([]) | product(_hysteria2_user_export_suffixes) | list }}"
vars:
_hysteria2_user_export_suffixes:
- ".url"
- ".txt"
- ".qr.txt"
- ".png"
when: _hysteria2_removed_users | default([]) | length > 0
delegate_to: localhost
become: false
- name: Remove export files for deleted users
ansible.builtin.file:
path: "{{ item }}"
state: absent
loop: "{{ _hysteria2_removed_user_files | default([]) }}"
delegate_to: localhost
become: false
when: _hysteria2_removed_user_files | default([]) | length > 0
- name: Check local URL files for resolved users
ansible.builtin.stat:
path: "{{ hysteria2_output_dir }}/{{ hysteria2_output_name }}/{{ item.name }}.url"
loop: "{{ hysteria2_resolved_users }}"
register: _hysteria2_url_file_stats
delegate_to: localhost
become: false
- name: Split users into full export and reuse existing export data
ansible.builtin.set_fact:
hysteria2_users_for_export: "{{ hysteria2_users_for_export | default([]) + ([item] if _needs_export else []) }}"
hysteria2_users_for_reuse: "{{ hysteria2_users_for_reuse | default([]) + ([_reuse_entry] if not _needs_export else []) }}"
loop: "{{ hysteria2_resolved_users }}"
loop_control:
label: "{{ item.name }}"
vars:
_saved_user: >-
{{
(_hysteria2_saved_server_info.users | default([])
| selectattr('name', 'equalto', item.name)
| list | first) | default({}, true)
}}
_url_stat: >-
{{
((_hysteria2_url_file_stats.results
| selectattr('item.name', 'equalto', item.name)
| list | first).stat) | default({}, true)
}}
_needs_export: >-
{{
hysteria2_force_export | bool
or (_saved_user | length == 0)
or (item.password != (_saved_user.password | default('')))
or (hysteria2_domain != (_hysteria2_saved_server_info.domain | default('')))
or ((hysteria2_listen_port | string) != (_hysteria2_saved_server_info.port | default('') | string))
or ((hysteria2_obfs_password | default('')) != (_hysteria2_saved_server_info.obfs_password | default('')))
or not (_url_stat.exists | default(false))
}}
_reuse_entry:
name: "{{ item.name }}"
password: "{{ item.password }}"
url: "{{ _saved_user.url }}"
has_png: "{{ _saved_user.has_png | default(false) | bool }}"
delegate_to: localhost
become: false
@@ -0,0 +1,41 @@
---
# Пересборка HTML-страниц серверов и общего index из локальных server-info.yml (без SSH)
- name: Find server-info.yml in output directories
ansible.builtin.find:
paths: "{{ hysteria2_output_dir }}"
patterns: server-info.yml
recurse: true
register: _hysteria2_local_server_info_files
become: false
- name: Load local server-info.yml files
ansible.builtin.slurp:
src: "{{ item.path }}"
loop: "{{ _hysteria2_local_server_info_files.files | default([]) }}"
register: _hysteria2_local_server_info_raw
when: _hysteria2_local_server_info_files.matched | default(0) | int > 0
become: false
- name: Rebuild per-server index.html from local export data
ansible.builtin.template:
src: export/index.html.j2
dest: "{{ _server_dir }}/index.html"
mode: "0644"
loop: "{{ _hysteria2_local_server_info_raw.results | default([]) }}"
when: not item.skipped | default(false)
loop_control:
label: "{{ _info.server | default('unknown') }}"
vars:
_info: "{{ item.content | b64decode | from_yaml }}"
_server_dir: "{{ item.item.path | dirname }}"
hysteria2_output_name: "{{ _info.server }}"
hysteria2_domain: "{{ _info.domain }}"
hysteria2_listen_port: "{{ _info.port }}"
hysteria2_export_users: "{{ _info.users }}"
hysteria2_obfs_password: "{{ _info.obfs_password | default('') }}"
hysteria2_mode: "{{ _info.mode | default('') }}"
generated_at: "{{ now(utc=false, fmt='%Y-%m-%d %H:%M:%S') }}"
become: false
- name: Rebuild global output index
ansible.builtin.import_tasks: export_global.yml
+4
View File
@@ -7,6 +7,10 @@
ansible.builtin.import_tasks: users.yml
tags: [install, update, export]
- name: Resolve Salamander obfs password
ansible.builtin.import_tasks: obfs.yml
tags: [install, update, export]
- name: Install packages and Hysteria2 binary
ansible.builtin.import_tasks: install.yml
tags: [install]
+58
View File
@@ -0,0 +1,58 @@
---
- name: Check for saved Salamander password from previous install
ansible.builtin.stat:
path: "{{ hysteria2_output_dir }}/{{ hysteria2_output_name }}/server-info.yml"
register: _hysteria2_saved_info
delegate_to: localhost
become: false
tags:
- install
- update
- export
- name: Load saved Salamander obfs password
when: _hysteria2_saved_info.stat.exists
block:
- name: Read server-info.yml for obfs password
ansible.builtin.slurp:
path: "{{ hysteria2_output_dir }}/{{ hysteria2_output_name }}/server-info.yml"
register: _hysteria2_saved_info_raw
delegate_to: localhost
become: false
- name: Parse saved obfs password
ansible.builtin.set_fact:
_hysteria2_saved_obfs_password: "{{ (_hysteria2_saved_info_raw.content | b64decode | from_yaml).obfs_password | default('') }}"
delegate_to: localhost
become: false
tags:
- install
- update
- export
- name: Resolve Salamander obfs password
ansible.builtin.set_fact:
hysteria2_obfs_password: >-
{{
hysteria2_obfs_password
| default(_hysteria2_saved_obfs_password | default(''), true)
}}
tags:
- install
- update
- export
- name: Generate Salamander obfs password
ansible.builtin.set_fact:
hysteria2_obfs_password: >-
{{
lookup(
'password',
'/dev/null chars=ascii_letters,digits length=' ~ (hysteria2_obfs_password_length | string)
)
}}
when: hysteria2_obfs_password | length == 0
tags:
- install
- update
- export
@@ -0,0 +1,4 @@
---
- name: Register reused export data for HTML page
ansible.builtin.set_fact:
hysteria2_export_users: "{{ hysteria2_export_users | default([]) + [hysteria2_reuse_user] }}"
+2
View File
@@ -34,6 +34,8 @@
Domain: {{ hysteria2_domain }}:{{ hysteria2_listen_port }}
User: {{ hysteria2_current_user.name }}
Password: {{ hysteria2_current_user.password }}
Mode: salamander
Obfs password: {{ hysteria2_obfs_password }}
URL:
{{ _hysteria2_client_url }}
+56 -11
View File
@@ -14,10 +14,19 @@
dest: "{{ hysteria2_install_script_staging_dir }}/{{ hysteria2_install_script_name }}.remote"
mode: "0644"
force: true
timeout: 30
delegate_to: localhost
become: false
run_once: true
register: _hysteria2_remote_script
failed_when: false
- name: Record install script fetch result
ansible.builtin.set_fact:
_hysteria2_script_fetch_ok: "{{ not (_hysteria2_remote_script.failed | default(false)) }}"
delegate_to: localhost
become: false
run_once: true
- name: Stat local install script in role files
ansible.builtin.stat:
@@ -36,6 +45,7 @@
become: false
run_once: true
register: _hysteria2_remote_script_stat
when: _hysteria2_script_fetch_ok | bool
- name: Update bundled install script when official version is newer
ansible.builtin.copy:
@@ -45,20 +55,55 @@
delegate_to: localhost
become: false
run_once: true
when: >-
not _hysteria2_local_script.stat.exists
or _hysteria2_local_script.stat.checksum
!= _hysteria2_remote_script_stat.stat.checksum
when:
- _hysteria2_script_fetch_ok | bool
- >-
not _hysteria2_local_script.stat.exists
or _hysteria2_local_script.stat.checksum
!= _hysteria2_remote_script_stat.stat.checksum
register: _hysteria2_script_updated
- name: Report install script sync result
ansible.builtin.debug:
- name: Fail when bundled install script is missing and official fetch failed
ansible.builtin.fail:
msg: >-
{{
'Официальный install_server.sh обновлён в roles/hysteria2/files/'
if (_hysteria2_script_updated.changed | default(false))
else 'Локальный install_server.sh актуален (совпадает с ' ~ hysteria2_install_script_url ~ ')'
}}
Не удалось скачать {{ hysteria2_install_script_url }}
({{ _hysteria2_remote_script.msg | default('сеть недоступна') }})
и локальный roles/hysteria2/files/{{ hysteria2_install_script_name }} отсутствует.
delegate_to: localhost
become: false
run_once: true
when:
- not _hysteria2_script_fetch_ok | bool
- not _hysteria2_local_script.stat.exists
- name: Report install script sync skipped due to network error
ansible.builtin.debug:
msg: >-
Пропуск синхронизации с {{ hysteria2_install_script_url }}:
{{ _hysteria2_remote_script.msg | default('сеть недоступна') }}.
Используется локальный roles/hysteria2/files/{{ hysteria2_install_script_name }}.
delegate_to: localhost
become: false
run_once: true
when: not _hysteria2_script_fetch_ok | bool
- name: Report install script updated from official server
ansible.builtin.debug:
msg: Официальный install_server.sh обновлён в roles/hysteria2/files/
delegate_to: localhost
become: false
run_once: true
when:
- _hysteria2_script_fetch_ok | bool
- _hysteria2_script_updated.changed | default(false)
- name: Report install script already up to date
ansible.builtin.debug:
msg: >-
Локальный install_server.sh актуален (совпадает с {{ hysteria2_install_script_url }}).
delegate_to: localhost
become: false
run_once: true
when:
- _hysteria2_script_fetch_ok | bool
- not (_hysteria2_script_updated.changed | default(false))
+108 -23
View File
@@ -1,46 +1,131 @@
---
- name: Stop and disable hysteria-server
- name: Stop and disable hysteria-server before removal
ansible.builtin.systemd:
name: "{{ hysteria2_service_name }}"
enabled: false
state: stopped
failed_when: false
- name: Remove Hysteria2 via official script
ansible.builtin.shell:
cmd: bash <(curl -fsSL https://get.hy2.sh/) --remove
executable: /bin/bash
- name: Copy Hysteria2 install script to server
ansible.builtin.copy:
src: "{{ hysteria2_install_script_name }}"
dest: "{{ hysteria2_install_script_remote_path }}"
mode: "0755"
- name: Remove Hysteria2 binary and systemd units via official script
ansible.builtin.command:
cmd: "{{ hysteria2_install_script_remote_path }} --remove"
register: _hysteria2_remove
changed_when: _hysteria2_remove.rc == 0
failed_when: false
- name: Remove Hysteria2 configuration directory
ansible.builtin.file:
path: "{{ hysteria2_config_path | dirname }}"
state: absent
when: hysteria2_uninstall_remove_config | bool
- name: Show official script removal output
ansible.builtin.debug:
msg: "{{ _hysteria2_remove.stdout_lines | default(['install_server.sh --remove: no output']) }}"
when: _hysteria2_remove.stdout_lines is defined
- name: Remove masquerade web directory
- name: Remove Hysteria2 configuration and ACME data
ansible.builtin.file:
path: "{{ hysteria2_masq_dir }}"
path: "{{ item }}"
state: absent
loop:
- "{{ hysteria2_config_path | dirname }}"
- "/var/lib/{{ hysteria2_system_user | default('hysteria') }}"
- name: Remove enabled hysteria-server systemd symlink
ansible.builtin.file:
path: /etc/systemd/system/multi-user.target.wants/hysteria-server.service
state: absent
failed_when: false
- name: Find enabled hysteria-server@ systemd symlinks
ansible.builtin.find:
paths: /etc/systemd/system/multi-user.target.wants
patterns: hysteria-server@*.service
file_type: file
register: _hysteria2_systemd_instance_wants
failed_when: false
- name: Remove enabled hysteria-server@ systemd symlinks
ansible.builtin.file:
path: "{{ item.path }}"
state: absent
loop: "{{ _hysteria2_systemd_instance_wants.files | default([]) }}"
failed_when: false
- name: Remove Hysteria system user and home directory
ansible.builtin.user:
name: "{{ hysteria2_system_user | default('hysteria') }}"
state: absent
remove: true
failed_when: false
- name: Find temporary Hysteria client configs on server
ansible.builtin.find:
paths: /tmp
patterns: hysteria-client-*.yaml
file_type: file
register: _hysteria2_tmp_client_configs
failed_when: false
- name: Remove temporary Hysteria client configs on server
ansible.builtin.file:
path: "{{ item.path }}"
state: absent
loop: "{{ _hysteria2_tmp_client_configs.files | default([]) }}"
failed_when: false
- name: Check if ufw is available and active
ansible.builtin.command: ufw status
register: _hysteria2_ufw_status
changed_when: false
failed_when: false
- name: Remove firewall rules added during install
ansible.builtin.command: "ufw delete allow {{ item }}"
loop: "{{ hysteria2_uninstall_ufw_rules }}"
register: _hysteria2_ufw_delete
changed_when: >-
_hysteria2_ufw_delete.rc == 0
and 'Could not delete' not in (_hysteria2_ufw_delete.stdout | default(''))
and 'Could not find' not in (_hysteria2_ufw_delete.stderr | default(''))
failed_when: false
when: "'active' in (_hysteria2_ufw_status.stdout | default(''))"
- name: Remove packages installed for Hysteria2
ansible.builtin.apt:
name: "{{ _hysteria2_apt_packages }}"
state: absent
purge: true
autoremove: true
vars:
_hysteria2_apt_packages: >-
{{
['curl', 'micro']
+ (['qrencode'] if hysteria2_generate_qr_png | default(true) | bool else [])
}}
- name: Remove copied install script from server
ansible.builtin.file:
path: "{{ hysteria2_install_script_remote_path }}"
state: absent
when: hysteria2_uninstall_remove_masq | bool
- name: Reload systemd after uninstall
ansible.builtin.systemd:
daemon_reload: true
- name: Show uninstall result
ansible.builtin.debug:
msg: >-
Hysteria2 удалён с {{ inventory_hostname }}.
{% if not hysteria2_uninstall_remove_local_output | bool %}
Локальные URL/QR в {{ hysteria2_output_dir }}/{{ hysteria2_output_name }}/ сохранены.
{% endif %}
- name: Remove local exported client files
- name: Remove local output directory for this server
ansible.builtin.file:
path: "{{ hysteria2_output_dir }}/{{ hysteria2_output_name }}"
state: absent
delegate_to: localhost
become: false
when: hysteria2_uninstall_remove_local_output | bool
- name: Show uninstall result
ansible.builtin.debug:
msg: >-
Hysteria2 (Salamander) полностью удалён с {{ inventory_hostname }}.
Локальная папка {{ hysteria2_output_dir }}/{{ hysteria2_output_name }}/ удалена.
{% if hysteria2_uninstall_rebuild_global_index | default(true) | bool %}
{{ hysteria2_output_dir }}/index.html будет пересобран без этого сервера.
{% endif %}
+35 -4
View File
@@ -10,6 +10,16 @@
- update
- export
- name: Initialize empty saved export metadata
ansible.builtin.set_fact:
_hysteria2_saved_passwords: {}
_hysteria2_saved_server_info: {}
when: not _hysteria2_saved_info.stat.exists
tags:
- install
- update
- export
- name: Load saved user passwords from local export
when: _hysteria2_saved_info.stat.exists
block:
@@ -20,8 +30,9 @@
delegate_to: localhost
become: false
- name: Parse saved passwords into lookup dict
- name: Parse saved export metadata
ansible.builtin.set_fact:
_hysteria2_saved_server_info: "{{ _hysteria2_saved_info_raw.content | b64decode | from_yaml }}"
_hysteria2_saved_passwords: >-
{{
dict(
@@ -33,12 +44,14 @@
)
)
}}
delegate_to: localhost
become: false
tags:
- install
- update
- export
- name: Resolve user list with optional fixed passwords
- name: Resolve user list with passwords from inventory, vault and previous export
ansible.builtin.set_fact:
hysteria2_resolved_users: "{{ hysteria2_resolved_users | default([]) + [ _entry ] }}"
vars:
@@ -46,8 +59,26 @@
_password: >-
{{
(
item.password if item is mapping
) | default('', true)
item.password
if item is mapping and (item.password | default('') | length > 0)
else none
)
| default(
hysteria2_user_passwords[_username]
if (
hysteria2_user_passwords is defined
and (hysteria2_user_passwords[_username] | default('') | length > 0)
)
else none,
true
)
| default(
_hysteria2_saved_passwords[_username]
if (_hysteria2_saved_passwords[_username] | default('') | length > 0)
else none,
true
)
| default('', true)
}}
_entry:
name: "{{ _username }}"
+1 -1
View File
@@ -7,7 +7,7 @@
- hysteria2_users | length > 0
fail_msg: |
Задайте для каждого хоста:
hysteria2_domain — домен с A-записью на IP сервера
hysteria2_domain — домен с A-записью на IP сервера (используется для TLS/SNI)
hysteria2_users — список имён пользователей, например [my, friend]
И в group_vars/all.yml:
hysteria2_acme_email — email для Let's Encrypt
+5
View File
@@ -1,3 +1,8 @@
server: {{ hysteria2_domain }}:{{ hysteria2_listen_port }}
auth: {{ hysteria2_current_user.name }}:{{ hysteria2_current_user.password }}
obfs:
type: salamander
salamander:
password: {{ hysteria2_obfs_password }}
+5 -8
View File
@@ -1,7 +1,7 @@
listen: 0.0.0.0:{{ hysteria2_listen_port }}
acme:
type: http
type: tls
domains:
- {{ hysteria2_domain }}
email: {{ hysteria2_acme_email }}
@@ -13,10 +13,7 @@ auth:
{{ user.name }}: "{{ user.password }}"
{% endfor %}
masquerade:
type: file
file:
dir: {{ hysteria2_masq_dir }}
listenHTTP: :80
listenHTTPS: :{{ hysteria2_listen_port }}
forceHTTPS: true
obfs:
type: salamander
salamander:
password: "{{ hysteria2_obfs_password }}"
@@ -15,11 +15,14 @@
--text: #e6edf3;
--muted: #8b949e;
--accent: #58a6ff;
--accent-2: #a371f7;
--accent-2: #3fb950;
--accent-soft: rgba(88, 166, 255, 0.12);
--accent-soft-2: rgba(163, 113, 247, 0.12);
--success: #3fb950;
--success-soft: rgba(63, 185, 80, 0.15);
--danger: #f85149;
--danger-soft: rgba(248, 81, 73, 0.15);
--warn: #d29922;
--warn-soft: rgba(210, 153, 34, 0.15);
--radius: 14px;
--shadow: 0 12px 40px rgba(0, 0, 0, 0.35);
}
@@ -33,96 +36,241 @@
--text: #1f2328;
--muted: #656d76;
--accent: #0969da;
--accent-2: #8250df;
--accent-2: #1a7f37;
--accent-soft: rgba(9, 105, 218, 0.08);
--accent-soft-2: rgba(130, 80, 223, 0.08);
--success: #1a7f37;
--success-soft: rgba(26, 127, 55, 0.1);
--danger: #cf222e;
--danger-soft: rgba(207, 34, 46, 0.1);
--warn: #9a6700;
--warn-soft: rgba(154, 103, 0, 0.1);
--shadow: 0 10px 30px rgba(31, 35, 40, 0.08);
}
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
background: var(--bg);
font-family: "Segoe UI", "SF Pro Display", "Helvetica Neue", Arial, sans-serif;
background:
radial-gradient(ellipse 80% 50% at 20% -10%, var(--accent-soft), transparent),
radial-gradient(ellipse 60% 40% at 100% 0%, rgba(63, 185, 80, 0.08), transparent),
var(--bg);
color: var(--text);
line-height: 1.5;
min-height: 100vh;
}
.hero {
background:
radial-gradient(ellipse 80% 60% at 50% -10%, var(--accent-soft), transparent),
radial-gradient(ellipse 60% 40% at 90% 10%, var(--accent-soft-2), transparent),
var(--bg-soft);
border-bottom: 1px solid var(--border);
padding: 2.5rem 1.5rem 2rem;
padding: 2rem 1.5rem 1.25rem;
text-align: center;
}
.hero h1 {
font-size: clamp(1.75rem, 4vw, 2.25rem);
font-weight: 800;
letter-spacing: -0.03em;
margin-bottom: 0.5rem;
background: linear-gradient(135deg, var(--accent), var(--accent-2));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
margin-bottom: 0.35rem;
color: var(--accent);
}
.hero p { color: var(--muted); font-size: 0.95rem; }
.stats {
display: flex;
justify-content: center;
gap: 1rem;
flex-wrap: wrap;
margin-top: 1.25rem;
}
.stat {
padding: 0.5rem 1rem;
border: 1px solid var(--border);
border-radius: 999px;
background: var(--bg-card);
font-size: 0.85rem;
font-weight: 600;
}
.stat span { color: var(--accent); }
.nav {
.tabs {
position: sticky;
top: 0;
z-index: 50;
display: flex;
gap: 0.5rem;
gap: 0.45rem;
flex-wrap: wrap;
justify-content: center;
padding: 0.85rem 1rem;
background: color-mix(in srgb, var(--bg-soft) 88%, transparent);
backdrop-filter: blur(10px);
padding: 0.75rem 1rem;
background: color-mix(in srgb, var(--bg-soft) 90%, transparent);
backdrop-filter: blur(12px);
border-bottom: 1px solid var(--border);
}
.nav a {
padding: 0.4rem 0.85rem;
border-radius: 999px;
.tab {
appearance: none;
border: 1px solid var(--border);
background: var(--bg-card);
color: var(--text);
text-decoration: none;
font-size: 0.82rem;
font-weight: 600;
transition: border-color 0.15s, background 0.15s, color 0.15s;
padding: 0.5rem 0.95rem;
border-radius: 999px;
font-size: 0.85rem;
font-weight: 650;
cursor: pointer;
transition: border-color 0.15s, background 0.15s, color 0.15s, box-shadow 0.15s;
}
.nav a:hover {
.tab:hover {
border-color: var(--accent);
color: var(--accent);
background: var(--accent-soft);
}
.tab.active {
border-color: var(--accent);
background: var(--accent-soft);
color: var(--accent);
box-shadow: 0 0 0 3px var(--accent-soft);
}
.tab .dot {
display: inline-block;
width: 7px;
height: 7px;
border-radius: 50%;
margin-right: 0.35rem;
vertical-align: middle;
background: var(--muted);
}
.tab .dot.up { background: var(--success); box-shadow: 0 0 8px var(--success); }
.tab .dot.down { background: var(--danger); }
.container {
max-width: 980px;
max-width: 1080px;
margin: 0 auto;
padding: 1.5rem 1rem 3rem;
}
.server-section {
scroll-margin-top: 4.5rem;
margin-bottom: 2.5rem;
.tab-panel { display: none; animation: fadeIn 0.2s ease; }
.tab-panel.active { display: block; }
@keyframes fadeIn {
from { opacity: 0; transform: translateY(6px); }
to { opacity: 1; transform: translateY(0); }
}
.metrics {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
gap: 0.85rem;
margin-bottom: 1.5rem;
}
.metric {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 1.1rem 1.2rem;
box-shadow: var(--shadow);
}
.metric .label {
font-size: 0.72rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--muted);
margin-bottom: 0.35rem;
}
.metric .value {
font-size: 1.75rem;
font-weight: 800;
letter-spacing: -0.03em;
color: var(--accent);
}
.metric .sub {
margin-top: 0.2rem;
font-size: 0.78rem;
color: var(--muted);
}
.section-title {
font-size: 1.05rem;
font-weight: 700;
margin: 0 0 0.85rem;
}
.server-stats {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1rem;
margin-bottom: 1.75rem;
}
.server-stat-card {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 1.15rem 1.25rem;
box-shadow: var(--shadow);
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.server-stat-card header {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 0.75rem;
}
.server-stat-card h3 {
font-size: 1.1rem;
font-weight: 750;
}
.badge {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.25rem 0.65rem;
border-radius: 999px;
font-size: 0.72rem;
font-weight: 700;
white-space: nowrap;
}
.badge.up {
background: var(--success-soft);
color: var(--success);
border: 1px solid color-mix(in srgb, var(--success) 35%, transparent);
}
.badge.down {
background: var(--danger-soft);
color: var(--danger);
border: 1px solid color-mix(in srgb, var(--danger) 35%, transparent);
}
.meta-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.55rem 0.85rem;
}
.meta-item label {
display: block;
font-size: 0.68rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--muted);
}
.meta-item span,
.meta-item code {
font-size: 0.88rem;
font-weight: 600;
word-break: break-all;
}
.meta-item code {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.8rem;
}
.matrix-wrap {
overflow-x: auto;
border: 1px solid var(--border);
border-radius: var(--radius);
background: var(--bg-card);
box-shadow: var(--shadow);
}
table.matrix {
width: 100%;
border-collapse: collapse;
min-width: 480px;
}
table.matrix th,
table.matrix td {
padding: 0.65rem 0.85rem;
border-bottom: 1px solid var(--border);
text-align: center;
font-size: 0.85rem;
}
table.matrix th {
background: var(--bg-soft);
font-weight: 700;
position: sticky;
top: 0;
}
table.matrix th:first-child,
table.matrix td:first-child {
text-align: left;
font-weight: 650;
white-space: nowrap;
}
table.matrix tr:last-child td { border-bottom: none; }
.cell-yes {
color: var(--success);
font-weight: 800;
}
.cell-no { color: var(--muted); opacity: 0.45; }
.server-header {
display: flex;
flex-wrap: wrap;
@@ -137,15 +285,8 @@
box-shadow: var(--shadow);
border-left: 4px solid var(--accent);
}
.server-header h2 {
font-size: 1.35rem;
font-weight: 700;
}
.server-header .domain {
color: var(--muted);
font-size: 0.9rem;
margin-top: 0.15rem;
}
.server-header h2 { font-size: 1.35rem; font-weight: 700; }
.server-header .domain { color: var(--muted); font-size: 0.9rem; margin-top: 0.15rem; }
.server-link {
display: inline-flex;
align-items: center;
@@ -236,6 +377,13 @@
width: 160px;
height: 160px;
image-rendering: pixelated;
cursor: zoom-in;
border-radius: 4px;
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.qr-block img:hover {
transform: scale(1.03);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);
}
.files {
display: flex;
@@ -282,31 +430,265 @@
z-index: 100;
}
.toast.show { transform: translateX(-50%) translateY(0); opacity: 1; }
.lightbox {
position: fixed;
inset: 0;
z-index: 200;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
box-sizing: border-box;
background: rgba(8, 12, 18, 0.72);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
opacity: 0;
visibility: hidden;
pointer-events: none;
transition: opacity 0.22s ease, visibility 0.22s ease;
}
.lightbox.open {
opacity: 1;
visibility: visible;
pointer-events: auto;
}
.lightbox-panel {
position: relative;
display: flex;
flex-direction: column;
width: min(96vw, calc(100dvh - 2rem));
height: calc(100dvh - 2rem);
max-height: calc(100dvh - 2rem);
padding: 2.5rem 1rem 0.85rem;
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 18px;
box-shadow: 0 24px 64px rgba(0, 0, 0, 0.45);
text-align: center;
overflow: hidden;
box-sizing: border-box;
transform: translateY(12px) scale(0.96);
transition: transform 0.22s ease;
}
.lightbox.open .lightbox-panel { transform: translateY(0) scale(1); }
.lightbox-media {
flex: 1 1 auto;
min-height: 0;
width: 100%;
container-type: size;
display: grid;
place-items: center;
}
.lightbox-panel img {
display: block;
width: min(100cqi, 100cqb);
height: min(100cqi, 100cqb);
max-width: 100%;
max-height: 100%;
aspect-ratio: 1;
object-fit: contain;
background: #fff;
border-radius: 12px;
padding: 0.75rem;
box-sizing: border-box;
image-rendering: pixelated;
}
.lightbox-caption {
flex-shrink: 0;
margin-top: 0.55rem;
font-size: 0.95rem;
font-weight: 650;
color: var(--text);
}
.lightbox-actions {
flex-shrink: 0;
margin-top: 0.65rem;
display: flex;
justify-content: center;
}
.lightbox-download {
display: inline-flex;
align-items: center;
gap: 0.45rem;
padding: 0.55rem 1rem;
border-radius: 999px;
border: 1px solid var(--border);
background: var(--bg-input);
color: var(--accent);
text-decoration: none;
font: inherit;
font-size: 0.85rem;
font-weight: 650;
cursor: pointer;
transition: color 0.15s, border-color 0.15s, background 0.15s;
}
.lightbox-download:hover {
border-color: var(--accent);
background: var(--accent-soft);
}
.lightbox-download svg { width: 16px; height: 16px; flex-shrink: 0; }
.lightbox-close {
position: absolute;
top: 0.65rem;
right: 0.65rem;
width: 36px;
height: 36px;
border: 1px solid var(--border);
border-radius: 999px;
background: var(--bg-input);
color: var(--muted);
cursor: pointer;
font-size: 1.25rem;
line-height: 1;
display: flex;
align-items: center;
justify-content: center;
transition: color 0.15s, border-color 0.15s, background 0.15s;
}
.lightbox-close:hover {
color: var(--accent);
border-color: var(--accent);
background: var(--accent-soft);
}
body.lightbox-open { overflow: hidden; }
.probe-note {
margin-top: 1rem;
font-size: 0.78rem;
color: var(--muted);
}
</style>
</head>
<body>
<header class="hero">
<h1>Hysteria2</h1>
<p>Общий каталог VPN-подключений</p>
<div class="stats">
<div class="stat"><span>{{ hysteria2_global_servers | length }}</span> серверов</div>
<div class="stat"><span>{{ total_users }}</span> пользователей</div>
</div>
<p>Каталог VPN и сводная статистика</p>
</header>
<nav class="nav" aria-label="Серверы">
<nav class="tabs" role="tablist" aria-label="Разделы">
<button type="button" class="tab active" role="tab" aria-selected="true" data-tab="stats" id="tab-btn-stats">Статистика</button>
{% for server in hysteria2_global_servers %}
<a href="#server-{{ server.dir | e }}">{{ server.name | e }}</a>
<button type="button" class="tab" role="tab" aria-selected="false" data-tab="server-{{ server.dir | e }}" id="tab-btn-{{ server.dir | e }}">
<span class="dot {{ 'up' if server.reachable | default(false) else 'down' }}" aria-hidden="true"></span>{{ server.name | e }}
</button>
{% endfor %}
</nav>
<main class="container">
<section class="tab-panel active" id="tab-stats" role="tabpanel" aria-labelledby="tab-btn-stats">
<div class="metrics">
<div class="metric">
<div class="label">Серверы</div>
<div class="value">{{ hysteria2_global_servers | length }}</div>
<div class="sub">в локальном экспорте</div>
</div>
<div class="metric">
<div class="label">Доступность</div>
<div class="value">{{ reachable_count }}/{{ hysteria2_global_servers | length }}</div>
<div class="sub">TCP :порт отвечает</div>
</div>
<div class="metric">
<div class="label">Учётки</div>
<div class="value">{{ total_users }}</div>
<div class="sub">сумма по серверам</div>
</div>
<div class="metric">
<div class="label">Уникальные</div>
<div class="value">{{ unique_users | length }}</div>
<div class="sub">разных пользователей</div>
</div>
</div>
<h2 class="section-title">Серверы</h2>
<div class="server-stats">
{% for server in hysteria2_global_servers %}
<section class="server-section" id="server-{{ server.dir | e }}">
<article class="server-stat-card">
<header>
<div>
<h3>{{ server.name | e }}</h3>
</div>
{% if server.reachable | default(false) %}
<span class="badge up">● online</span>
{% else %}
<span class="badge down">● offline</span>
{% endif %}
</header>
<div class="meta-grid">
<div class="meta-item">
<label>Домен</label>
<span>{{ server.domain | e }}</span>
</div>
<div class="meta-item">
<label>Порт</label>
<span>{{ server.port }}</span>
</div>
<div class="meta-item">
<label>IP</label>
<code>{{ server.host_ip | default('—') | e }}</code>
</div>
<div class="meta-item">
<label>Режим</label>
<span>{{ server.mode | default('masquerade') | e }}</span>
</div>
<div class="meta-item">
<label>Пользователи</label>
<span>{{ server.users | length }}</span>
</div>
<div class="meta-item">
<label>QR-коды</label>
<span>{{ server.users | selectattr('has_png') | list | length }}</span>
</div>
</div>
<div style="display:flex; gap:0.5rem; flex-wrap:wrap; margin-top:0.25rem;">
<button type="button" class="tab" data-tab="server-{{ server.dir | e }}" style="margin:0;">Открыть вкладку</button>
<a class="server-link" href="{{ server.dir | e }}/index.html">Страница сервера →</a>
</div>
</article>
{% endfor %}
</div>
<h2 class="section-title">Пользователи × серверы</h2>
<div class="matrix-wrap">
<table class="matrix">
<thead>
<tr>
<th>Пользователь</th>
{% for server in hysteria2_global_servers %}
<th>{{ server.name | e }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for uname in unique_users %}
<tr>
<td>{{ uname | e }}</td>
{% for server in hysteria2_global_servers %}
{% set names = server.users | map(attribute='name') | list %}
<td class="{{ 'cell-yes' if uname in names else 'cell-no' }}">{{ '✓' if uname in names else '—' }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
<p class="probe-note">Доступность проверена с control node при генерации ({{ generated_at | default('') }}): TCP connect к IP/домену и порту Hysteria.</p>
</section>
{% for server in hysteria2_global_servers %}
<section class="tab-panel" id="tab-server-{{ server.dir | e }}" role="tabpanel" aria-labelledby="tab-btn-{{ server.dir | e }}" hidden>
<div class="server-header">
<div>
<h2>{{ server.name | e }}</h2>
<p class="domain">{{ server.domain | e }}:{{ server.port }}</p>
<p class="domain">
{{ server.domain | e }}:{{ server.port }}
{% if server.host_ip | default('') | length > 0 %}
· <code>{{ server.host_ip | e }}</code>
{% endif %}
{% if server.reachable | default(false) %}
· <span style="color:var(--success);font-weight:700;">online</span>
{% else %}
· <span style="color:var(--danger);font-weight:700;">offline</span>
{% endif %}
</p>
</div>
<a class="server-link" href="{{ server.dir | e }}/index.html">Страница сервера →</a>
</div>
@@ -336,19 +718,33 @@
</div>
</div>
{% set _png = namespace(b64='', data='') %}
{% if user.has_png | default(false) %}
{% set _png.b64 = lookup('pipe', 'base64 < ' ~ ((hysteria2_output_dir ~ '/' ~ server.dir ~ '/' ~ user.name ~ '.png') | quote)) | regex_replace('\\s+', '') %}
{% set _png.data = 'data:image/png;base64,' ~ _png.b64 %}
<div class="qr-block">
<img src="{{ server.dir | e }}/{{ user.name | e }}.png" alt="QR {{ user.name | e }}" width="160" height="160">
<img
src="{{ _png.data }}"
alt="QR {{ user.name | e }}"
width="160"
height="160"
role="button"
tabindex="0"
data-lightbox-src="{{ _png.data }}"
data-lightbox-caption="{{ server.name | e }} · {{ user.name | e }}"
data-lightbox-download="{{ server.name | e }}-{{ user.name | e }}.png"
aria-label="Открыть QR-код {{ user.name | e }}"
>
</div>
{% endif %}
<nav class="files" aria-label="Файлы">
<a href="{{ server.dir | e }}/{{ user.name | e }}.url" download>.url</a>
<a href="{{ server.dir | e }}/{{ user.name | e }}.txt" download>.txt</a>
{% if user.has_png | default(false) %}
<a href="{{ server.dir | e }}/{{ user.name | e }}.png" download>.png</a>
<a class="file-download" href="{{ server.dir | e }}/{{ user.name | e }}.url" download="{{ server.name | e }}-{{ user.name | e }}.url" data-filename="{{ server.name | e }}-{{ user.name | e }}.url" data-text="{{ (user.url ~ '\n') | e }}">.url</a>
<a class="file-download" href="{{ server.dir | e }}/{{ user.name | e }}.txt" download="{{ server.name | e }}-{{ user.name | e }}.txt" data-filename="{{ server.name | e }}-{{ user.name | e }}.txt" data-text="{{ ('Server: ' ~ server.name ~ '\nDomain: ' ~ server.domain ~ ':' ~ server.port ~ '\nUser: ' ~ user.name ~ '\nPassword: ' ~ user.password ~ '\n\nURL:\n' ~ user.url ~ '\n') | e }}">.txt</a>
{% if user.has_png | default(false) and _png.b64 %}
<a class="file-download" href="{{ server.dir | e }}/{{ user.name | e }}.png" download="{{ server.name | e }}-{{ user.name | e }}.png" data-filename="{{ server.name | e }}-{{ user.name | e }}.png" data-png-b64="{{ _png.b64 }}">.png</a>
{% endif %}
<a href="{{ server.dir | e }}/{{ user.name | e }}.qr.txt" download>.qr.txt</a>
<a class="file-download" href="{{ server.dir | e }}/{{ user.name | e }}.qr.txt" download="{{ server.name | e }}-{{ user.name | e }}.qr.txt" data-filename="{{ server.name | e }}-{{ user.name | e }}.qr.txt" data-text="{{ lookup('file', hysteria2_output_dir ~ '/' ~ server.dir ~ '/' ~ user.name ~ '.qr.txt', errors='ignore') | default('URL: ' ~ user.url ~ '\n', true) | e }}">.qr.txt</a>
</nav>
</article>
{% endfor %}
@@ -360,6 +756,22 @@
<footer>Сгенерировано Ansible · {{ generated_at | default('') }}</footer>
<div class="toast" id="toast">Скопировано!</div>
<div class="lightbox" id="lightbox" role="dialog" aria-modal="true" aria-hidden="true" aria-labelledby="lightbox-caption">
<div class="lightbox-panel" role="document">
<button type="button" class="lightbox-close" id="lightbox-close" aria-label="Закрыть">&times;</button>
<div class="lightbox-media">
<img id="lightbox-img" src="" alt="">
</div>
<p class="lightbox-caption" id="lightbox-caption"></p>
<div class="lightbox-actions">
<button type="button" class="lightbox-download" id="lightbox-download">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
Скачать QR
</button>
</div>
</div>
</div>
<script>
function copyField(id, btn) {
var el = document.getElementById(id);
@@ -384,6 +796,230 @@
t.classList.add('show');
setTimeout(function() { t.classList.remove('show'); }, 1800);
}
(function () {
function activateTab(id) {
document.querySelectorAll('.tab[data-tab]').forEach(function (btn) {
var on = btn.getAttribute('data-tab') === id;
btn.classList.toggle('active', on);
btn.setAttribute('aria-selected', on ? 'true' : 'false');
});
document.querySelectorAll('.tab-panel').forEach(function (panel) {
var on = panel.id === 'tab-' + id;
panel.classList.toggle('active', on);
if (on) panel.removeAttribute('hidden');
else panel.setAttribute('hidden', '');
});
try { history.replaceState(null, '', '#' + id); } catch (e) {}
}
document.querySelectorAll('.tab[data-tab]').forEach(function (btn) {
btn.addEventListener('click', function () {
activateTab(btn.getAttribute('data-tab'));
});
});
var hash = (location.hash || '#stats').replace(/^#/, '');
if (!document.getElementById('tab-' + hash)) hash = 'stats';
activateTab(hash);
})();
(function () {
var box = document.getElementById('lightbox');
var img = document.getElementById('lightbox-img');
var caption = document.getElementById('lightbox-caption');
var closeBtn = document.getElementById('lightbox-close');
var downloadBtn = document.getElementById('lightbox-download');
var downloadSrc = '';
function triggerDataUrlDownload(dataUrl, filename) {
var a = document.createElement('a');
a.href = dataUrl;
a.download = filename;
a.rel = 'noopener';
document.body.appendChild(a);
a.click();
a.remove();
}
function triggerFileDownload(blob, filename) {
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = filename;
a.rel = 'noopener';
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(function () { URL.revokeObjectURL(url); }, 1500);
}
function downloadQrFromCanvas(filename) {
if (!img.complete || !img.naturalWidth) return false;
try {
var canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
canvas.getContext('2d').drawImage(img, 0, 0);
// toDataURL sync — download stays in the user-gesture (Safari/Chrome)
triggerDataUrlDownload(canvas.toDataURL('image/png'), filename);
return true;
} catch (err) {
return false;
}
}
function downloadQrImage(e) {
e.preventDefault();
e.stopPropagation();
var filename = downloadBtn.getAttribute('data-filename') || 'qr.png';
var src = downloadSrc || img.currentSrc || img.src;
// Embedded data: URLs work on file:// (no CORS / tainted canvas)
if (src && src.indexOf('data:') === 0) {
triggerDataUrlDownload(src, filename);
return;
}
if (downloadQrFromCanvas(filename)) return;
if (!src || location.protocol === 'file:') return;
fetch(src)
.then(function (res) {
if (!res.ok) throw new Error('fetch failed');
return res.blob();
})
.then(function (blob) { triggerFileDownload(blob, filename); })
.catch(function () { /* avoid navigating to the image URL */ });
}
function openLightbox(src, text, alt, filename) {
var safeName = filename || 'qr.png';
img.src = src;
img.alt = alt || text || 'QR';
caption.textContent = text || '';
downloadSrc = src;
downloadBtn.setAttribute('data-filename', safeName);
downloadBtn.setAttribute('aria-label', 'Скачать ' + safeName);
box.classList.add('open');
box.setAttribute('aria-hidden', 'false');
document.body.classList.add('lightbox-open');
closeBtn.focus();
}
function closeLightbox() {
box.classList.remove('open');
box.setAttribute('aria-hidden', 'true');
document.body.classList.remove('lightbox-open');
img.removeAttribute('src');
downloadSrc = '';
downloadBtn.removeAttribute('data-filename');
}
document.querySelectorAll('[data-lightbox-src]').forEach(function (el) {
function openFromEl() {
openLightbox(
el.getAttribute('data-lightbox-src'),
el.getAttribute('data-lightbox-caption'),
el.getAttribute('alt'),
el.getAttribute('data-lightbox-download')
);
}
el.addEventListener('click', openFromEl);
el.addEventListener('keydown', function (e) {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
openFromEl();
}
});
});
downloadBtn.addEventListener('click', downloadQrImage);
closeBtn.addEventListener('click', closeLightbox);
box.addEventListener('click', function (e) {
if (e.target === box) closeLightbox();
});
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && box.classList.contains('open')) closeLightbox();
});
})();
(function () {
function triggerDataUrlDownload(dataUrl, filename) {
var a = document.createElement('a');
a.href = dataUrl;
a.download = filename;
a.rel = 'noopener';
document.body.appendChild(a);
a.click();
a.remove();
}
function triggerFileDownload(blob, filename) {
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = filename;
a.rel = 'noopener';
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(function () { URL.revokeObjectURL(url); }, 1500);
}
function pngFromCard(link, filename) {
var card = link.closest('.user-card');
var qrImg = card && card.querySelector('img[data-lightbox-src], .qr-block img');
if (!qrImg) return false;
var src = qrImg.currentSrc || qrImg.src || '';
if (src.indexOf('data:image/') === 0) {
triggerDataUrlDownload(src, filename);
return true;
}
if (!qrImg.complete || !qrImg.naturalWidth) return false;
try {
var canvas = document.createElement('canvas');
canvas.width = qrImg.naturalWidth;
canvas.height = qrImg.naturalHeight;
canvas.getContext('2d').drawImage(qrImg, 0, 0);
triggerDataUrlDownload(canvas.toDataURL('image/png'), filename);
return true;
} catch (err) {
return false;
}
}
document.querySelectorAll('a.file-download').forEach(function (link) {
link.addEventListener('click', function (e) {
e.preventDefault();
e.stopPropagation();
var filename = link.getAttribute('data-filename') || link.getAttribute('download') || 'download';
var href = link.getAttribute('href');
var fallbackText = link.getAttribute('data-text');
var pngB64 = link.getAttribute('data-png-b64');
var isPng = /\.png$/i.test(filename);
// Sync paths first — file:// blocks fetch (CORS) and taints canvas
if (pngB64) {
triggerDataUrlDownload('data:image/png;base64,' + pngB64, filename);
return;
}
if (isPng && pngFromCard(link, filename)) return;
if (fallbackText !== null) {
triggerFileDownload(new Blob([fallbackText], { type: 'text/plain;charset=utf-8' }), filename);
return;
}
if (!href || location.protocol === 'file:') return;
fetch(href)
.then(function (res) {
if (!res.ok) throw new Error('fetch failed');
return res.blob();
})
.then(function (blob) { triggerFileDownload(blob, filename); })
.catch(function () { /* do not navigate to the file URL */ });
});
});
})();
</script>
</body>
</html>
+536 -148
View File
@@ -7,133 +7,171 @@
<style>
:root {
color-scheme: light dark;
--bg: #0f1419;
--bg-card: #1a2332;
--bg: #0b0f14;
--bg-soft: #121820;
--bg-card: #161d27;
--bg-input: #0d1117;
--border: #2d3a4f;
--border: #2a3544;
--text: #e6edf3;
--muted: #8b949e;
--accent: #58a6ff;
--accent-soft: rgba(88, 166, 255, 0.15);
--accent-soft: rgba(88, 166, 255, 0.12);
--success: #3fb950;
--success-soft: rgba(63, 185, 80, 0.15);
--radius: 12px;
--shadow: 0 8px 32px rgba(0, 0, 0, 0.35);
--radius: 14px;
--shadow: 0 12px 40px rgba(0, 0, 0, 0.35);
}
@media (prefers-color-scheme: light) {
:root {
--bg: #f0f4f8;
--bg: #eef2f7;
--bg-soft: #f6f8fb;
--bg-card: #ffffff;
--bg-input: #f6f8fa;
--border: #d0d7de;
--border: #d8dee4;
--text: #1f2328;
--muted: #656d76;
--accent: #0969da;
--accent-soft: rgba(9, 105, 218, 0.1);
--accent-soft: rgba(9, 105, 218, 0.08);
--success: #1a7f37;
--success-soft: rgba(26, 127, 55, 0.1);
--shadow: 0 8px 24px rgba(31, 35, 40, 0.08);
--shadow: 0 10px 30px rgba(31, 35, 40, 0.08);
}
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
background: var(--bg);
font-family: "Segoe UI", "SF Pro Display", "Helvetica Neue", Arial, sans-serif;
background:
radial-gradient(ellipse 80% 50% at 20% -10%, var(--accent-soft), transparent),
radial-gradient(ellipse 60% 40% at 100% 0%, rgba(63, 185, 80, 0.08), transparent),
var(--bg);
color: var(--text);
line-height: 1.5;
min-height: 100vh;
padding: 2rem 1rem 3rem;
}
.container { max-width: 720px; margin: 0 auto; }
header {
.hero {
padding: 2rem 1.5rem 1.25rem;
text-align: center;
margin-bottom: 2.5rem;
padding: 2rem 1.5rem;
background: linear-gradient(135deg, var(--accent-soft), transparent);
border: 1px solid var(--border);
border-radius: var(--radius);
box-shadow: var(--shadow);
}
header h1 {
font-size: 1.75rem;
font-weight: 700;
letter-spacing: -0.02em;
margin-bottom: 0.5rem;
.hero h1 {
font-size: clamp(1.75rem, 4vw, 2.25rem);
font-weight: 800;
letter-spacing: -0.03em;
margin-bottom: 0.35rem;
color: var(--accent);
}
header .meta {
color: var(--muted);
font-size: 0.9rem;
.hero p { color: var(--muted); font-size: 0.95rem; }
.hero .meta strong { color: var(--text); font-weight: 650; }
.badges {
display: flex;
flex-wrap: wrap;
gap: 0.45rem;
justify-content: center;
margin-top: 1rem;
}
header .meta strong { color: var(--text); font-weight: 600; }
.badge {
display: inline-block;
margin-top: 1rem;
padding: 0.25rem 0.75rem;
background: var(--accent-soft);
color: var(--accent);
border: 1px solid color-mix(in srgb, var(--accent) 30%, transparent);
border-radius: 999px;
font-size: 0.8rem;
font-weight: 600;
font-weight: 650;
}
.badge-salamander {
background: rgba(63, 185, 80, 0.12);
color: var(--success);
border-color: color-mix(in srgb, var(--success) 35%, transparent);
}
.top-nav {
display: flex;
justify-content: center;
gap: 0.5rem;
flex-wrap: wrap;
padding: 0 1rem 1rem;
}
.nav-link {
display: inline-flex;
align-items: center;
padding: 0.45rem 0.9rem;
border-radius: 999px;
border: 1px solid var(--border);
background: var(--bg-card);
color: var(--accent);
text-decoration: none;
font-size: 0.82rem;
font-weight: 650;
}
.nav-link:hover { background: var(--accent-soft); border-color: var(--accent); }
.container {
max-width: 1080px;
margin: 0 auto;
padding: 0 1rem 3rem;
}
.server-obfs {
max-width: 640px;
margin: 0 auto 1.25rem;
padding: 1rem 1.15rem;
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius);
box-shadow: var(--shadow);
text-align: left;
}
.users-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 1rem;
}
.user-card {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 1.25rem;
box-shadow: var(--shadow);
padding: 1.5rem;
margin-bottom: 1.25rem;
display: flex;
flex-direction: column;
gap: 0.85rem;
}
.user-card h2 {
font-size: 1.25rem;
margin-bottom: 1rem;
font-size: 1.05rem;
display: flex;
align-items: center;
gap: 0.5rem;
}
.user-card h2::before {
content: "";
width: 8px;
height: 8px;
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--success);
box-shadow: 0 0 8px var(--success);
}
.field { margin-bottom: 1rem; }
.field label {
display: block;
font-size: 0.75rem;
font-weight: 600;
font-size: 0.7rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
letter-spacing: 0.06em;
color: var(--muted);
margin-bottom: 0.4rem;
}
.input-row {
display: flex;
gap: 0.5rem;
align-items: stretch;
margin-bottom: 0.35rem;
}
.input-row { display: flex; gap: 0.45rem; }
.input-row input {
flex: 1;
min-width: 0;
padding: 0.65rem 0.85rem;
padding: 0.55rem 0.75rem;
background: var(--bg-input);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text);
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
font-size: 0.8rem;
}
.input-row input:focus {
outline: none;
border-color: var(--accent);
box-shadow: 0 0 0 3px var(--accent-soft);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.72rem;
}
.btn-copy {
display: flex;
align-items: center;
justify-content: center;
width: 42px;
width: 38px;
flex-shrink: 0;
background: var(--bg-input);
border: 1px solid var(--border);
@@ -142,65 +180,53 @@
cursor: pointer;
transition: color 0.15s, border-color 0.15s, background 0.15s;
}
.btn-copy:hover {
color: var(--accent);
border-color: var(--accent);
background: var(--accent-soft);
}
.btn-copy.copied {
color: var(--success);
border-color: var(--success);
background: var(--success-soft);
}
.btn-copy svg { width: 18px; height: 18px; }
.btn-copy:hover { color: var(--accent); border-color: var(--accent); background: var(--accent-soft); }
.btn-copy.copied { color: var(--success); border-color: var(--success); background: var(--success-soft); }
.btn-copy svg { width: 16px; height: 16px; }
.qr-block {
text-align: center;
margin: 1.25rem 0;
padding: 1rem;
padding: 0.75rem;
background: #fff;
border-radius: 8px;
border: 1px solid var(--border);
}
@media (prefers-color-scheme: dark) {
.qr-block { background: #fff; }
}
.qr-block img {
max-width: 220px;
width: 100%;
height: auto;
width: 160px;
height: 160px;
image-rendering: pixelated;
cursor: zoom-in;
border-radius: 4px;
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.qr-block img:hover {
transform: scale(1.03);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);
}
.files {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
margin-top: 1rem;
padding-top: 1rem;
gap: 0.4rem;
margin-top: auto;
padding-top: 0.75rem;
border-top: 1px solid var(--border);
}
.files a {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.35rem 0.75rem;
background: var(--bg-input);
border: 1px solid var(--border);
padding: 0.3rem 0.6rem;
border-radius: 6px;
border: 1px solid var(--border);
background: var(--bg-input);
color: var(--accent);
text-decoration: none;
font-size: 0.8rem;
font-weight: 500;
transition: background 0.15s, border-color 0.15s;
}
.files a:hover {
background: var(--accent-soft);
border-color: var(--accent);
font-size: 0.72rem;
font-weight: 600;
}
.files a:hover { background: var(--accent-soft); border-color: var(--accent); }
footer {
text-align: center;
margin-top: 2rem;
padding: 1.5rem;
color: var(--muted);
font-size: 0.8rem;
border-top: 1px solid var(--border);
}
.toast {
position: fixed;
@@ -220,71 +246,236 @@
pointer-events: none;
z-index: 100;
}
.toast.show {
transform: translateX(-50%) translateY(0);
opacity: 1;
.toast.show { transform: translateX(-50%) translateY(0); opacity: 1; }
.lightbox {
position: fixed;
inset: 0;
z-index: 200;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
box-sizing: border-box;
background: rgba(8, 12, 18, 0.72);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
opacity: 0;
visibility: hidden;
pointer-events: none;
transition: opacity 0.22s ease, visibility 0.22s ease;
}
.lightbox.open {
opacity: 1;
visibility: visible;
pointer-events: auto;
}
.lightbox-panel {
position: relative;
display: flex;
flex-direction: column;
width: min(96vw, calc(100dvh - 2rem));
height: calc(100dvh - 2rem);
max-height: calc(100dvh - 2rem);
padding: 2.5rem 1rem 0.85rem;
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 18px;
box-shadow: 0 24px 64px rgba(0, 0, 0, 0.45);
text-align: center;
overflow: hidden;
box-sizing: border-box;
transform: translateY(12px) scale(0.96);
transition: transform 0.22s ease;
}
.lightbox.open .lightbox-panel { transform: translateY(0) scale(1); }
.lightbox-media {
flex: 1 1 auto;
min-height: 0;
width: 100%;
container-type: size;
display: grid;
place-items: center;
}
.lightbox-panel img {
display: block;
width: min(100cqi, 100cqb);
height: min(100cqi, 100cqb);
max-width: 100%;
max-height: 100%;
aspect-ratio: 1;
object-fit: contain;
background: #fff;
border-radius: 12px;
padding: 0.75rem;
box-sizing: border-box;
image-rendering: pixelated;
}
.lightbox-caption {
flex-shrink: 0;
margin-top: 0.55rem;
font-size: 0.95rem;
font-weight: 650;
color: var(--text);
}
.lightbox-actions {
flex-shrink: 0;
margin-top: 0.65rem;
display: flex;
justify-content: center;
}
.lightbox-download {
display: inline-flex;
align-items: center;
gap: 0.45rem;
padding: 0.55rem 1rem;
border-radius: 999px;
border: 1px solid var(--border);
background: var(--bg-input);
color: var(--accent);
text-decoration: none;
font: inherit;
font-size: 0.85rem;
font-weight: 650;
cursor: pointer;
}
.lightbox-download:hover {
border-color: var(--accent);
background: var(--accent-soft);
}
.lightbox-download svg { width: 16px; height: 16px; flex-shrink: 0; }
.lightbox-close {
position: absolute;
top: 0.65rem;
right: 0.65rem;
width: 36px;
height: 36px;
border: 1px solid var(--border);
border-radius: 999px;
background: var(--bg-input);
color: var(--muted);
cursor: pointer;
font-size: 1.25rem;
line-height: 1;
display: flex;
align-items: center;
justify-content: center;
}
.lightbox-close:hover {
color: var(--accent);
border-color: var(--accent);
background: var(--accent-soft);
}
body.lightbox-open { overflow: hidden; }
</style>
</head>
<body>
<div class="container">
<header>
<h1>Hysteria2</h1>
<p class="meta">
Сервер: <strong>{{ hysteria2_output_name }}</strong><br>
Домен: <strong>{{ hysteria2_domain }}:{{ hysteria2_listen_port }}</strong>
</p>
<header class="hero">
<h1>{{ hysteria2_output_name | e }}</h1>
<p class="meta">
<strong>{{ hysteria2_domain | e }}:{{ hysteria2_listen_port }}</strong>
</p>
<div class="badges">
<span class="badge">{{ hysteria2_export_users | length }} {{ 'пользователь' if hysteria2_export_users | length == 1 else 'пользователей' }}</span>
</header>
{% for user in hysteria2_export_users %}
<article class="user-card">
<h2>{{ user.name }}</h2>
<div class="field">
<label for="pwd-{{ loop.index }}">Пароль</label>
<div class="input-row">
<input type="text" id="pwd-{{ loop.index }}" value="{{ user.password | e }}" readonly>
<button type="button" class="btn-copy" onclick="copyField('pwd-{{ loop.index }}', this)" title="Копировать пароль" aria-label="Копировать пароль">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
</button>
</div>
</div>
<div class="field">
<label for="url-{{ loop.index }}">Ссылка подключения</label>
<div class="input-row">
<input type="text" id="url-{{ loop.index }}" value="{{ user.url | e }}" readonly>
<button type="button" class="btn-copy" onclick="copyField('url-{{ loop.index }}', this)" title="Копировать ссылку" aria-label="Копировать ссылку">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
</button>
</div>
</div>
{% if user.has_png %}
<div class="qr-block">
<img src="{{ user.name | e }}.png" alt="QR-код {{ user.name | e }}" width="220" height="220">
</div>
{% if (hysteria2_mode | default('')) == 'salamander' or (hysteria2_obfs_password | default('') | length > 0) %}
<span class="badge badge-salamander">Salamander</span>
{% endif %}
</div>
</header>
<nav class="files" aria-label="Файлы">
<a href="{{ user.name | e }}.url" download>{{ user.name | e }}.url</a>
<a href="{{ user.name | e }}.txt" download>{{ user.name | e }}.txt</a>
{% if user.has_png %}
<a href="{{ user.name | e }}.png" download>{{ user.name | e }}.png</a>
{% endif %}
<a href="{{ user.name | e }}.qr.txt" download>{{ user.name | e }}.qr.txt</a>
</nav>
</article>
{% endfor %}
<footer>
Сгенерировано Ansible · {{ generated_at | default('') }}
</footer>
<div class="top-nav">
<a class="nav-link" href="../index.html">← Общий каталог</a>
</div>
<main class="container">
{% if hysteria2_obfs_password | default('') | length > 0 %}
<div class="field server-obfs">
<label for="obfs-server">Пароль обфускации (Salamander)</label>
<div class="input-row">
<input type="text" id="obfs-server" value="{{ hysteria2_obfs_password | e }}" readonly>
<button type="button" class="btn-copy" onclick="copyField('obfs-server', this)" title="Копировать obfs-password" aria-label="Копировать obfs-password">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
</button>
</div>
</div>
{% endif %}
<div class="users-grid">
{% for user in hysteria2_export_users %}
<article class="user-card">
<h2>{{ user.name | e }}</h2>
<div class="field">
<label for="pwd-{{ loop.index }}">Пароль</label>
<div class="input-row">
<input type="text" id="pwd-{{ loop.index }}" value="{{ user.password | e }}" readonly>
<button type="button" class="btn-copy" onclick="copyField('pwd-{{ loop.index }}', this)" title="Копировать пароль" aria-label="Копировать пароль">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
</button>
</div>
</div>
<div class="field">
<label for="url-{{ loop.index }}">Ссылка</label>
<div class="input-row">
<input type="text" id="url-{{ loop.index }}" value="{{ user.url | e }}" readonly>
<button type="button" class="btn-copy" onclick="copyField('url-{{ loop.index }}', this)" title="Копировать ссылку" aria-label="Копировать ссылку">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2 2v1"/></svg>
</button>
</div>
</div>
{% set _png = namespace(b64='', data='') %}
{% if user.has_png | default(false) %}
{% set _png.b64 = lookup('pipe', 'base64 < ' ~ ((hysteria2_output_dir ~ '/' ~ hysteria2_output_name ~ '/' ~ user.name ~ '.png') | quote)) | regex_replace('\\s+', '') %}
{% set _png.data = 'data:image/png;base64,' ~ _png.b64 %}
<div class="qr-block">
<img
src="{{ _png.data }}"
alt="QR {{ user.name | e }}"
width="160"
height="160"
role="button"
tabindex="0"
data-lightbox-src="{{ _png.data }}"
data-lightbox-caption="{{ hysteria2_output_name | e }} · {{ user.name | e }}"
data-lightbox-download="{{ hysteria2_output_name | e }}-{{ user.name | e }}.png"
aria-label="Открыть QR-код {{ user.name | e }}"
>
</div>
{% endif %}
<nav class="files" aria-label="Файлы">
<a class="file-download" href="{{ user.name | e }}.url" download="{{ hysteria2_output_name | e }}-{{ user.name | e }}.url" data-filename="{{ hysteria2_output_name | e }}-{{ user.name | e }}.url" data-text="{{ (user.url ~ '\n') | e }}">.url</a>
<a class="file-download" href="{{ user.name | e }}.txt" download="{{ hysteria2_output_name | e }}-{{ user.name | e }}.txt" data-filename="{{ hysteria2_output_name | e }}-{{ user.name | e }}.txt" data-text="{{ ('Server: ' ~ hysteria2_output_name ~ '\nDomain: ' ~ hysteria2_domain ~ ':' ~ hysteria2_listen_port ~ '\nUser: ' ~ user.name ~ '\nPassword: ' ~ user.password ~ '\n\nURL:\n' ~ user.url ~ '\n') | e }}">.txt</a>
{% if user.has_png | default(false) and _png.b64 %}
<a class="file-download" href="{{ user.name | e }}.png" download="{{ hysteria2_output_name | e }}-{{ user.name | e }}.png" data-filename="{{ hysteria2_output_name | e }}-{{ user.name | e }}.png" data-png-b64="{{ _png.b64 }}">.png</a>
{% endif %}
<a class="file-download" href="{{ user.name | e }}.qr.txt" download="{{ hysteria2_output_name | e }}-{{ user.name | e }}.qr.txt" data-filename="{{ hysteria2_output_name | e }}-{{ user.name | e }}.qr.txt" data-text="{{ lookup('file', hysteria2_output_dir ~ '/' ~ hysteria2_output_name ~ '/' ~ user.name ~ '.qr.txt', errors='ignore') | default('URL: ' ~ user.url ~ '\n', true) | e }}">.qr.txt</a>
</nav>
</article>
{% endfor %}
</div>
</main>
<footer>Сгенерировано Ansible · {{ generated_at | default('') }}</footer>
<div class="toast" id="toast">Скопировано!</div>
<div class="lightbox" id="lightbox" role="dialog" aria-modal="true" aria-hidden="true" aria-labelledby="lightbox-caption">
<div class="lightbox-panel" role="document">
<button type="button" class="lightbox-close" id="lightbox-close" aria-label="Закрыть">&times;</button>
<div class="lightbox-media">
<img id="lightbox-img" src="" alt="">
</div>
<p class="lightbox-caption" id="lightbox-caption"></p>
<div class="lightbox-actions">
<button type="button" class="lightbox-download" id="lightbox-download">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
Скачать QR
</button>
</div>
</div>
</div>
<script>
function copyField(id, btn) {
var el = document.getElementById(id);
@@ -309,6 +500,203 @@
t.classList.add('show');
setTimeout(function() { t.classList.remove('show'); }, 1800);
}
(function () {
var box = document.getElementById('lightbox');
var img = document.getElementById('lightbox-img');
var caption = document.getElementById('lightbox-caption');
var closeBtn = document.getElementById('lightbox-close');
var downloadBtn = document.getElementById('lightbox-download');
var downloadSrc = '';
function triggerDataUrlDownload(dataUrl, filename) {
var a = document.createElement('a');
a.href = dataUrl;
a.download = filename;
a.rel = 'noopener';
document.body.appendChild(a);
a.click();
a.remove();
}
function triggerFileDownload(blob, filename) {
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = filename;
a.rel = 'noopener';
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(function () { URL.revokeObjectURL(url); }, 1500);
}
function downloadQrFromCanvas(filename) {
if (!img.complete || !img.naturalWidth) return false;
try {
var canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
canvas.getContext('2d').drawImage(img, 0, 0);
// toDataURL sync — download stays in the user-gesture (Safari/Chrome)
triggerDataUrlDownload(canvas.toDataURL('image/png'), filename);
return true;
} catch (err) {
return false;
}
}
function downloadQrImage(e) {
e.preventDefault();
e.stopPropagation();
var filename = downloadBtn.getAttribute('data-filename') || 'qr.png';
var src = downloadSrc || img.currentSrc || img.src;
// Embedded data: URLs work on file:// (no CORS / tainted canvas)
if (src && src.indexOf('data:') === 0) {
triggerDataUrlDownload(src, filename);
return;
}
if (downloadQrFromCanvas(filename)) return;
if (!src || location.protocol === 'file:') return;
fetch(src)
.then(function (res) {
if (!res.ok) throw new Error('fetch failed');
return res.blob();
})
.then(function (blob) { triggerFileDownload(blob, filename); })
.catch(function () { /* avoid navigating to the image URL */ });
}
function openLightbox(src, text, alt, filename) {
var safeName = filename || 'qr.png';
img.src = src;
img.alt = alt || text || 'QR';
caption.textContent = text || '';
downloadSrc = src;
downloadBtn.setAttribute('data-filename', safeName);
downloadBtn.setAttribute('aria-label', 'Скачать ' + safeName);
box.classList.add('open');
box.setAttribute('aria-hidden', 'false');
document.body.classList.add('lightbox-open');
closeBtn.focus();
}
function closeLightbox() {
box.classList.remove('open');
box.setAttribute('aria-hidden', 'true');
document.body.classList.remove('lightbox-open');
img.removeAttribute('src');
downloadSrc = '';
downloadBtn.removeAttribute('data-filename');
}
document.querySelectorAll('[data-lightbox-src]').forEach(function (el) {
function openFromEl() {
openLightbox(
el.getAttribute('data-lightbox-src'),
el.getAttribute('data-lightbox-caption'),
el.getAttribute('alt'),
el.getAttribute('data-lightbox-download')
);
}
el.addEventListener('click', openFromEl);
el.addEventListener('keydown', function (e) {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
openFromEl();
}
});
});
downloadBtn.addEventListener('click', downloadQrImage);
closeBtn.addEventListener('click', closeLightbox);
box.addEventListener('click', function (e) {
if (e.target === box) closeLightbox();
});
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && box.classList.contains('open')) closeLightbox();
});
})();
(function () {
function triggerDataUrlDownload(dataUrl, filename) {
var a = document.createElement('a');
a.href = dataUrl;
a.download = filename;
a.rel = 'noopener';
document.body.appendChild(a);
a.click();
a.remove();
}
function triggerFileDownload(blob, filename) {
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = filename;
a.rel = 'noopener';
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(function () { URL.revokeObjectURL(url); }, 1500);
}
function pngFromCard(link, filename) {
var card = link.closest('.user-card');
var qrImg = card && card.querySelector('img[data-lightbox-src], .qr-block img');
if (!qrImg) return false;
var src = qrImg.currentSrc || qrImg.src || '';
if (src.indexOf('data:image/') === 0) {
triggerDataUrlDownload(src, filename);
return true;
}
if (!qrImg.complete || !qrImg.naturalWidth) return false;
try {
var canvas = document.createElement('canvas');
canvas.width = qrImg.naturalWidth;
canvas.height = qrImg.naturalHeight;
canvas.getContext('2d').drawImage(qrImg, 0, 0);
triggerDataUrlDownload(canvas.toDataURL('image/png'), filename);
return true;
} catch (err) {
return false;
}
}
document.querySelectorAll('a.file-download').forEach(function (link) {
link.addEventListener('click', function (e) {
e.preventDefault();
e.stopPropagation();
var filename = link.getAttribute('data-filename') || link.getAttribute('download') || 'download';
var href = link.getAttribute('href');
var fallbackText = link.getAttribute('data-text');
var pngB64 = link.getAttribute('data-png-b64');
var isPng = /\.png$/i.test(filename);
// Sync paths first — file:// blocks fetch (CORS) and taints canvas
if (pngB64) {
triggerDataUrlDownload('data:image/png;base64,' + pngB64, filename);
return;
}
if (isPng && pngFromCard(link, filename)) return;
if (fallbackText !== null) {
triggerFileDownload(new Blob([fallbackText], { type: 'text/plain;charset=utf-8' }), filename);
return;
}
if (!href || location.protocol === 'file:') return;
fetch(href)
.then(function (res) {
if (!res.ok) throw new Error('fetch failed');
return res.blob();
})
.then(function (blob) { triggerFileDownload(blob, filename); })
.catch(function () { /* do not navigate to the file URL */ });
});
});
})();
</script>
</body>
</html>
@@ -1,27 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, nginx is successfully installed and working.
Further configuration is required for the web server, reverse proxy,
API gateway, load balancer, content cache, or other features.</p>
<p>For online documentation and support please refer to
<a href="https://nginx.org/">nginx.org</a>.<br/>
To engage with the community please visit
<a href="https://community.nginx.org/">community.nginx.org</a>.<br/>
For enterprise grade support, professional services, additional
security features and capabilities please refer to
<a href="https://f5.com/nginx">f5.com/nginx</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>