Compare commits
4 Commits
6e05a366c9
...
v1.4.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74849a8e2c | ||
|
|
693f9513f1 | ||
|
|
2faa91de9b | ||
|
|
75345ebc03 |
4
09. История и грабли.md
Normal file
4
09. История и грабли.md
Normal file
@@ -0,0 +1,4 @@
|
||||
# 09. История и грабли
|
||||
|
||||
- [09.1 Версия 1.3.0 — протоколы с сайта, каскад, домен, тема](<09.1 Версия 1.3.0 — протоколы с сайта, каскад, домен, тема.md>) — 23.10.2026
|
||||
- 04.10.2026 — проект переехал в папку-группу; код не менялся.
|
||||
@@ -0,0 +1,13 @@
|
||||
# 09.1 Версия 1.3.0 — протоколы с сайта, каскад, домен, тема (23.10.2026)
|
||||
|
||||
СИМПТОМ: (а) клиент AWG 1.x из панели — рукопожатие есть, интернета нет; (б) после обновления переключение инстанса создавало клиента не в том контейнере; (в) проверка занятого порта ничего не ловила.
|
||||
ПРИЧИНА: (а) выгрузка .conf подставляла «умолчательные» S3/S4/I1, которых нет на сервере 1.x; (б) install.sh клал контейнеры панели в AWG_PROFILES, env-копия затеняла управляемый инстанс; (в) `ss` запускался внутри контейнера панели.
|
||||
КАК ПРОВЕРИТЬ ЗА МИНУТУ:
|
||||
curl -s http://IP:8080/health # version 1.3.0
|
||||
в .conf клиента 1.x не должно быть строк S3/S4; GET /api/protocols — id управляемых = amnezia-<вариант>-<порт>
|
||||
ИСПРАВЛЕНИЕ: v1.3.0 (тег v1.3.0). Параметры обфускации берутся с сервера (awgObfuscationLines); getProfiles отдаёт приоритет управляемым; порт — через docker ps. Добавлено: AWG 3.0/3.1 (образы по дайджесту, патч awg-quick на userspace), домен в /data/settings.json, каскад POST /api/cascade/upstream (конфиг другого сервера → интерфейс warp), светлая тема.
|
||||
Проверено на школе (friends = сервер, it-kruzhok = клиент/выход): Legacy, 1.x, 2.0, 3.0, 3.1 — рукопожатие + интернет; каскад — трафик прошёл через второй сервер, переживает рестарт; домен; обновление поверх контейнера приложения amnezia-awg; чистая установка с GitHub. Тестовое удалено.
|
||||
ПРОФИЛАКТИКА: перед релизом гонять клиентов всех вариантов со второй машины (скрипт-клиент в контейнере amneziawg-go 3.1). Xray/VLESS в открытую панель не вошёл — есть в закрытом amnezia_web-PRO_test.
|
||||
Не сделано: Gitea (.153:3030 недоступна из сети мини 23.10) — допушить `git push gitea main --tags`.
|
||||
|
||||
- 23.10.2026: новость о 1.3.0 опубликована в @PCAdministration (сообщение 877). Gitea не отправлено: Proxmox 192.168.88.5 и ВМ .153 не в сети — после включения `git push gitea main --tags`.
|
||||
@@ -7,11 +7,11 @@
|
||||
|
||||
| Что | Где |
|
||||
|---|---|
|
||||
| Папка проекта | `/Volumes/ssd/Мои проекты/amnezia_web-PRO/` |
|
||||
| Папка проекта | `/Volumes/ssd/Мои проекты/Открытые проекты/amnezia_web-PRO/` |
|
||||
| Заметки | Apple Notes → `МОИ ПРОЕКТЫ` → папка `amnezia_web-PRO` |
|
||||
| GitHub (публичный) | https://github.com/andrey271192/amnezia_web-PRO |
|
||||
| Ветка прода | `main` |
|
||||
| Тестовая копия рядом | `/Volumes/ssd/Мои проекты/amnezia_web-PRO_test/` |
|
||||
| Тестовая копия рядом | `/Volumes/ssd/Мои проекты/Закрытые продукты/amnezia_web-PRO_test/` |
|
||||
|
||||
Путь `/Volumes/andrey/Мои проекты/...` из старого промпта синхронизации **не существует** —
|
||||
актуальная копия только на `/Volumes/ssd`.
|
||||
@@ -65,4 +65,4 @@ curl -fsSL https://raw.githubusercontent.com/andrey271192/amnezia_web-PRO/main/s
|
||||
|
||||
## Состояние
|
||||
|
||||
- HEAD `7b92bfb` (08.09.2026), совпадает с `origin/main`.
|
||||
- v1.3.0 (23.10.2026), тег и релиз на GitHub. Gitea — допушить (была недоступна).
|
||||
|
||||
27
README.md
27
README.md
@@ -1,10 +1,29 @@
|
||||
# amnezia_web-PRO
|
||||
|
||||
## Public PRO panel
|
||||
Полностью открытая веб-панель для сервера Amnezia: все функции бесплатны, без платных или закрытых редакций. Один репозиторий, один установщик.
|
||||
|
||||
**amnezia_web-PRO** — public full Amnezia Web panel. One repository, one installer, no private download flow and no separate deploy repository.
|
||||
## Что нового в 1.4.0
|
||||
|
||||
Base project **[amnezia_web](https://github.com/andrey271192/amnezia_web)** remains a lighter open panel. This repository contains the full PRO feature set by default.
|
||||
- **Xray VLESS‑Reality** — раздел «Xray VLESS‑Reality»: установка с выбором TCP‑порта и сайта‑маскировки, клиенты (создать, выключить/включить, удалить), ссылка `vless://` для Amnezia VPN, v2rayNG, Hiddify, Streisand, Happ. Файлы в `/opt/amnezia/xray` в том же формате, что у приложения Amnezia.
|
||||
- **Всё открыто:** убрана редакция «community / только просмотр» и переменные `AMNEZIA_EDITION`, `COMMUNITY_UPGRADE_*` — все функции доступны всем.
|
||||
|
||||
## Что нового в 1.3.0
|
||||
|
||||
- **Установка протоколов прямо с сайта** (раздел «Протоколы / инстансы»), несколько версий рядом на разных портах:
|
||||
| Вариант | Для кого |
|
||||
|---|---|
|
||||
| AmneziaWG 3.1 | новейший: защита заголовков, случайные хвосты; свежее приложение Amnezia |
|
||||
| AmneziaWG 3.0 | HeaderProtectionKey, паддинг |
|
||||
| AmneziaWG 2.0 | рекомендуемый по умолчанию (S3/S4) |
|
||||
| AmneziaWG 1.x | роутеры Keenetic/OpenWrt и старые приложения (без S3/S4) |
|
||||
| WireGuard (Legacy) | любой WG-клиент, без обфускации |
|
||||
- **Исправлено:** конфиг клиента для AWG 1.x получал лишние S3/S4/I1 — рукопожатие было, интернета нет. Теперь в .conf попадают только параметры, которые есть на сервере.
|
||||
- **Исправлено:** при обновлении установщик записывал контейнеры панели в `AWG_PROFILES`, и переключение инстанса создавало клиента не там.
|
||||
- **Исправлено:** проверка занятого UDP-порта смотрела внутрь контейнера панели и ничего не находила.
|
||||
- **Домен сервера** — поле «Домен или IP сервера в конфигах клиентов»: подставляется в Endpoint всех выгрузок, домен проверяется на резолв.
|
||||
- **Настоящий каскад** — в разделе «Cloudflare WARP / каскад» вставьте клиентский .conf другого сервера: отмеченные клиенты выходят в интернет через него (переживает перезапуск контейнера).
|
||||
- **Светлая / тёмная тема** — кнопка «◐ Тема» в шапке (по умолчанию как в системе).
|
||||
- Старые установки не затрагиваются: контейнеры, поставленные приложением Amnezia, остаются как были.
|
||||
|
||||
## Что открывается по какому порту
|
||||
|
||||
@@ -243,7 +262,7 @@ UI_HIDE_SECTIONS=warp,cascade curl -fsSL https://raw.githubusercontent.com/andre
|
||||
|
||||
Что нужно человеку, который ставит связку:
|
||||
|
||||
1. На **этом** (основном) VPS — обычный AmneziaWG и панель PRO; здесь блок **«Новый клиент под каскад»** **создаёт peer и ключи** и выдаёт скачанный **`.conf`**, в котором **Endpoint** уже указывает на промежуточную машину.
|
||||
1. На **этом** (основном) VPS — обычный AmneziaWG и эта панель; здесь блок **«Новый клиент под каскад»** **создаёт peer и ключи** и выдаёт скачанный **`.conf`**, в котором **Endpoint** уже указывает на промежуточную машину.
|
||||
2. На **промежуточном** сервере нужен **проброс порта DNAT до основного VPS** на тот же **ListenPort**, что слушает туннель здесь (либо свой внешний порт → тогда его указывают в форме как «Порт Endpoint»).
|
||||
|
||||
Готовая панель для правил проброса (iptables DNAT NAT «под ключ»): репозиторий **[andrey271192/kaskad_web_vpn](https://github.com/andrey271192/kaskad_web_vpn)** — установка `curl … install.sh | sudo bash`, затем вход в браузере на промежуточный VPS по порту из README (например `8088/setup`) и настройка правила «вход → IP основного VPS:порт WG». Подробные шаги и переменные среды см. там же в README.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "amnezia-admin",
|
||||
"version": "1.2.39",
|
||||
"version": "1.4.0",
|
||||
"private": false,
|
||||
"description": "amnezia_web-PRO — веб-панель AmneziaWG: несколько инстансов, WARP, каскад/Endpoint, экспорт .conf (Docker)",
|
||||
"license": "MIT",
|
||||
|
||||
258
public/app.js
258
public/app.js
@@ -74,77 +74,6 @@ let warpSshPendingCmd = null;
|
||||
/** Какие панели скрыты настройкой сервера (`UI_HIDE_SECTIONS`). */
|
||||
let uiHidden = { users: false, warp: false, cascade: false, mtproto: false };
|
||||
|
||||
const editionBanner = document.querySelector("#edition-banner");
|
||||
const DEFAULT_HEADER_SUB = document.querySelector(".top .sub")?.textContent?.trim() || "";
|
||||
|
||||
/** Состояние редакции панели (community = только просмотр клиентов). */
|
||||
let editionState = {
|
||||
tier: "pro",
|
||||
readOnlyClients: false,
|
||||
upgradeUrl: null,
|
||||
upgradePitch: null,
|
||||
showDebugWg: true,
|
||||
};
|
||||
|
||||
function applyEditionPayload(data) {
|
||||
const ed = data?.edition;
|
||||
if (!ed || typeof ed !== "object") return;
|
||||
editionState = {
|
||||
tier: ed.tier === "community" ? "community" : "pro",
|
||||
readOnlyClients: Boolean(ed.readOnlyClients),
|
||||
upgradeUrl: typeof ed.upgradeUrl === "string" ? ed.upgradeUrl : null,
|
||||
upgradePitch: typeof ed.upgradePitch === "string" ? ed.upgradePitch : null,
|
||||
showDebugWg: ed.showDebugWg !== false,
|
||||
};
|
||||
const titleEl = document.querySelector(".top h1");
|
||||
if (titleEl) {
|
||||
titleEl.textContent =
|
||||
editionState.tier === "community"
|
||||
? "Пользователи AmneziaWG FREE"
|
||||
: "Пользователи AmneziaWG PRO";
|
||||
}
|
||||
const subEl = document.querySelector(".top .sub");
|
||||
if (subEl) {
|
||||
if (editionState.tier === "community") {
|
||||
subEl.textContent =
|
||||
"Базовая панель amnezia_web: только просмотр клиентов AmneziaWG и статусов. Управление туннелем, экспорт .conf, каскад, Cloudflare WARP, MTProto‑прокси Telegram и синхронизация времени хоста — в версии PRO.";
|
||||
} else {
|
||||
subEl.textContent = DEFAULT_HEADER_SUB;
|
||||
}
|
||||
}
|
||||
if (editionBanner) {
|
||||
if (editionState.tier === "community") {
|
||||
editionBanner.classList.remove("hidden");
|
||||
editionBanner.innerHTML = "";
|
||||
const wrap = document.createElement("div");
|
||||
wrap.className = "edition-banner-inner";
|
||||
const textCol = document.createElement("div");
|
||||
textCol.className = "edition-banner-text";
|
||||
const strong = document.createElement("strong");
|
||||
strong.textContent = "Базовая версия · только просмотр";
|
||||
const pitch = document.createElement("p");
|
||||
pitch.className = "edition-banner-pitch muted";
|
||||
pitch.textContent = editionState.upgradePitch || "";
|
||||
textCol.append(strong, pitch);
|
||||
const cta = document.createElement("a");
|
||||
cta.className = "btn small primary edition-banner-cta";
|
||||
cta.rel = "noopener noreferrer";
|
||||
cta.target = "_blank";
|
||||
cta.href =
|
||||
editionState.upgradeUrl ||
|
||||
"https://github.com/andrey271192/amnezia_web-PRO";
|
||||
cta.textContent = "Открыть PRO на GitHub";
|
||||
wrap.append(textCol, cta);
|
||||
editionBanner.appendChild(wrap);
|
||||
} else {
|
||||
editionBanner.classList.add("hidden");
|
||||
editionBanner.innerHTML = "";
|
||||
}
|
||||
}
|
||||
document.querySelector(".clock-host-sync")?.classList.toggle("hidden", editionState.readOnlyClients);
|
||||
if (wgRawDetails) wgRawDetails.hidden = uiHidden.users || !editionState.showDebugWg;
|
||||
}
|
||||
|
||||
/** @param {string} [tgLink] */
|
||||
function setMtprotoLinkCard(tgLink) {
|
||||
const t = typeof tgLink === "string" ? tgLink.trim() : "";
|
||||
@@ -350,7 +279,7 @@ function applyUiHiddenFromPayload(data) {
|
||||
};
|
||||
}
|
||||
if (usersPanel) usersPanel.hidden = uiHidden.users;
|
||||
if (wgRawDetails) wgRawDetails.hidden = uiHidden.users || !editionState.showDebugWg;
|
||||
if (wgRawDetails) wgRawDetails.hidden = uiHidden.users;
|
||||
if (cascadePanel) cascadePanel.hidden = uiHidden.cascade;
|
||||
if (warpPanel) warpPanel.hidden = uiHidden.warp;
|
||||
if (mtprotoPanel) mtprotoPanel.hidden = uiHidden.mtproto;
|
||||
@@ -586,7 +515,6 @@ async function checkSession() {
|
||||
async function loadProtocols() {
|
||||
try {
|
||||
const data = await api("/api/protocols");
|
||||
applyEditionPayload(data);
|
||||
protoLabel.textContent = `Протокол: ${data.currentLabel || "AmneziaWG"}`;
|
||||
if (profileHintEl) {
|
||||
if (data.singleProfile && typeof data.profilesPersistHint === "string" && data.profilesPersistHint) {
|
||||
@@ -629,6 +557,8 @@ loginForm.addEventListener("submit", async (ev) => {
|
||||
await loadTimeSyncCaps();
|
||||
await loadClients();
|
||||
await loadInstances();
|
||||
await loadSettings();
|
||||
await loadXray();
|
||||
} catch (e) {
|
||||
loginError.textContent = String(e.message || e);
|
||||
}
|
||||
@@ -647,6 +577,8 @@ logoutBtn.addEventListener("click", async () => {
|
||||
refreshBtn.addEventListener("click", () => {
|
||||
loadClients();
|
||||
loadInstances();
|
||||
loadSettings();
|
||||
loadXray();
|
||||
});
|
||||
|
||||
const cascadeForm = document.querySelector("#cascade-form");
|
||||
@@ -836,14 +768,6 @@ async function loadTimeSyncCaps() {
|
||||
const btn = document.querySelector("#sync-host-time");
|
||||
try {
|
||||
const c = await api("/api/time-sync-capabilities");
|
||||
if (editionState.readOnlyClients || c.communityBlocked) {
|
||||
if (hint) {
|
||||
hint.textContent =
|
||||
"В базовой версии синхронизация времени хоста по SSH недоступна — это функция PRO.";
|
||||
}
|
||||
if (btn) btn.disabled = true;
|
||||
return;
|
||||
}
|
||||
if (hint) {
|
||||
hint.textContent = c.hostTimeSync
|
||||
? `Записывается UTC-момент с этого устройства на хост по SSH (root@${c.sshHost}). Пояс строки «Сервер»: ${c.serverClockTimeZone}. Пароль не сохраняется.`
|
||||
@@ -936,7 +860,6 @@ function renderRows(clients) {
|
||||
nameWrap.className = "name-cell";
|
||||
const strong = document.createElement("strong");
|
||||
strong.textContent = c.name;
|
||||
if (!editionState.readOnlyClients) {
|
||||
const renameWrap = document.createElement("div");
|
||||
renameWrap.className = "rename-inline";
|
||||
renameWrap.appendChild(
|
||||
@@ -959,16 +882,6 @@ function renderRows(clients) {
|
||||
hintFold.appendChild(exHint);
|
||||
nameWrap.appendChild(hintFold);
|
||||
}
|
||||
} else {
|
||||
nameWrap.appendChild(strong);
|
||||
const roHint = document.createElement("p");
|
||||
roHint.className = "muted hint-mini";
|
||||
roHint.style.margin = "0.35rem 0 0";
|
||||
roHint.textContent = c.exportAvailable
|
||||
? "На сервере есть данные для .conf — скачивание доступно в PRO."
|
||||
: "Нет last_config на сервере — полный конфиг в приложении Amnezia.";
|
||||
nameWrap.appendChild(roHint);
|
||||
}
|
||||
nameTd.appendChild(nameWrap);
|
||||
|
||||
const ipTd = document.createElement("td");
|
||||
@@ -989,24 +902,16 @@ function renderRows(clients) {
|
||||
const dateLine = document.createElement("div");
|
||||
dateLine.textContent = formatLastDisconnect(c);
|
||||
offTd.appendChild(dateLine);
|
||||
if (!editionState.readOnlyClients) {
|
||||
const dtWrap = document.createElement("div");
|
||||
dtWrap.className = "rename-inline";
|
||||
dtWrap.appendChild(
|
||||
btn("Задать дату", "btn small ghost", () => openEditDisconnectDialog(c))
|
||||
);
|
||||
offTd.appendChild(dtWrap);
|
||||
}
|
||||
|
||||
const actTd = document.createElement("td");
|
||||
actTd.className = "actions";
|
||||
|
||||
if (editionState.readOnlyClients) {
|
||||
const lock = document.createElement("span");
|
||||
lock.className = "muted";
|
||||
lock.textContent = "Только PRO";
|
||||
actTd.appendChild(lock);
|
||||
} else {
|
||||
if (c.activeInConf) {
|
||||
actTd.appendChild(iconBtn("⏻", "Выключить", "btn small ghost icon", () => openDisableDialog(c)));
|
||||
} else {
|
||||
@@ -1033,7 +938,6 @@ function renderRows(clients) {
|
||||
);
|
||||
}
|
||||
actTd.appendChild(iconBtn("🗑", "Удалить", "btn small warn icon", () => confirmDelete(c.name, c.clientId)));
|
||||
}
|
||||
|
||||
tr.append(nameTd, ipTd, stTd, offTd, actTd);
|
||||
rowsEl.appendChild(tr);
|
||||
@@ -1649,7 +1553,6 @@ async function loadClients() {
|
||||
try {
|
||||
setStatus("Загрузка…", false);
|
||||
const data = await api(`/api/clients${currentProfileQueryString()}`);
|
||||
applyEditionPayload(data);
|
||||
applyUiHiddenFromPayload(data);
|
||||
const pref = data.profileLabel ? `${data.profileLabel} · ` : "";
|
||||
if (uiHidden.users) {
|
||||
@@ -1659,10 +1562,7 @@ async function loadClients() {
|
||||
} else {
|
||||
if (syncPeersBtn) {
|
||||
syncPeersBtn.hidden = false;
|
||||
syncPeersBtn.disabled = editionState.readOnlyClients;
|
||||
syncPeersBtn.title = editionState.readOnlyClients
|
||||
? "Доступно в PRO"
|
||||
: "Создать недостающие строки clientsTable из активных [Peer] текущего инстанса";
|
||||
syncPeersBtn.title = "Создать недостающие строки clientsTable из активных [Peer] текущего инстанса";
|
||||
}
|
||||
peerCountEl.textContent = `${pref}${data.clients.length} в таблице · ${data.peerCount} peer`;
|
||||
wgShowEl.textContent = data.wgShow || "";
|
||||
@@ -1730,6 +1630,8 @@ async function boot() {
|
||||
await loadTimeSyncCaps();
|
||||
await loadClients();
|
||||
await loadInstances();
|
||||
await loadSettings();
|
||||
await loadXray();
|
||||
} else {
|
||||
showLogin();
|
||||
loginPassword.focus();
|
||||
@@ -1738,3 +1640,147 @@ async function boot() {
|
||||
|
||||
initMtprotoLinkCopy();
|
||||
boot();
|
||||
|
||||
// ── Тема, адрес сервера, вышестоящий сервер каскада ──
|
||||
document.querySelector("#theme-toggle")?.addEventListener("click", () => {
|
||||
const next = document.documentElement.dataset.theme === "light" ? "dark" : "light";
|
||||
document.documentElement.dataset.theme = next;
|
||||
try { localStorage.setItem("theme", next); } catch { /* private mode */ }
|
||||
});
|
||||
|
||||
async function loadSettings() {
|
||||
const input = document.querySelector("#settings-endpoint");
|
||||
const hint = document.querySelector("#settings-hint");
|
||||
if (!input) return;
|
||||
try {
|
||||
const st = await api("/api/settings");
|
||||
input.value = st.endpointHost || "";
|
||||
if (hint) hint.textContent = `Сейчас в конфигах клиентов: ${st.effectiveEndpoint || "адрес из браузера"}. Новый адрес действует на все выгрузки .conf, в том числе старых клиентов.`;
|
||||
} catch { /* старый сервер без /api/settings */ }
|
||||
}
|
||||
|
||||
document.querySelector("#settings-form")?.addEventListener("submit", async (ev) => {
|
||||
ev.preventDefault();
|
||||
const endpointHost = document.querySelector("#settings-endpoint")?.value.trim() || "";
|
||||
try {
|
||||
const r = await api("/api/settings", { method: "POST", body: JSON.stringify({ endpointHost }) });
|
||||
setStatus(r.resolved ? `Адрес сохранён: ${endpointHost} → ${r.resolved.join(", ")}` : "Адрес сохранён.", false);
|
||||
await loadSettings();
|
||||
} catch (e) {
|
||||
setStatus(String(e.message || e), true);
|
||||
}
|
||||
});
|
||||
|
||||
document.querySelector("#upstream-form")?.addEventListener("submit", async (ev) => {
|
||||
ev.preventDefault();
|
||||
const configText = document.querySelector("#upstream-conf")?.value || "";
|
||||
const b = ev.target.querySelector("button[type=submit]");
|
||||
if (b) b.disabled = true;
|
||||
try {
|
||||
setStatus("Подключаю вышестоящий сервер…", false);
|
||||
const r = await api("/api/cascade/upstream", { method: "POST", body: JSON.stringify({ configText }) });
|
||||
setStatus(r.handshake ? "Каскад подключён: рукопожатие есть. Отметьте клиентов ниже и нажмите «Применить»." : "Туннель поднят, но рукопожатия пока нет — проверьте Endpoint и UDP-порт вышестоящего сервера.", !r.handshake);
|
||||
await loadClients();
|
||||
} catch (e) {
|
||||
setStatus(String(e.message || e), true);
|
||||
} finally {
|
||||
if (b) b.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
async function loadXray() {
|
||||
const line = document.querySelector("#xray-status-line");
|
||||
try {
|
||||
const x = await api("/api/xray/status");
|
||||
document.querySelector("#xray-install-form").style.display = x.installed ? "none" : "";
|
||||
document.querySelector("#xray-manage").style.display = x.installed ? "" : "none";
|
||||
if (line) {
|
||||
line.textContent = !x.installed
|
||||
? "не установлен"
|
||||
: x.running
|
||||
? `порт ${x.port} · ${x.sni} · клиентов: ${x.clients.length}`
|
||||
: "контейнер остановлен";
|
||||
}
|
||||
if (x.error) setStatus(x.error, true);
|
||||
const rows = document.querySelector("#xray-rows");
|
||||
rows.innerHTML = "";
|
||||
for (const c of x.clients) {
|
||||
const tr = document.createElement("tr");
|
||||
const nameTd = document.createElement("td");
|
||||
nameTd.innerHTML = `<strong>${escapeHtml(c.name)}</strong>`;
|
||||
const stTd = document.createElement("td");
|
||||
stTd.innerHTML = `<span class="badge ${c.enabled ? "on" : "off"}">${c.enabled ? "Включён" : "Выключен"}</span>`;
|
||||
const actTd = document.createElement("td");
|
||||
actTd.className = "actions";
|
||||
const act = (action) => async () => {
|
||||
if (action === "delete" && !confirm(`Удалить клиента ${c.name}?`)) return;
|
||||
try {
|
||||
await api("/api/xray/clients/update", { method: "POST", body: JSON.stringify({ id: c.id, action }) });
|
||||
await loadXray();
|
||||
} catch (e) {
|
||||
setStatus(String(e.message || e), true);
|
||||
}
|
||||
};
|
||||
actTd.append(
|
||||
iconBtn("⧉", "Копировать ссылку vless://", "btn small ghost icon", async () => {
|
||||
const ok = await copyTextToClipboard(c.link);
|
||||
setStatus(ok ? `Ссылка ${c.name} скопирована.` : "Не удалось скопировать.", !ok);
|
||||
}),
|
||||
c.enabled
|
||||
? iconBtn("⏻", "Выключить", "btn small ghost icon", act("disable"))
|
||||
: iconBtn("▶", "Включить", "btn small primary icon", act("enable")),
|
||||
iconBtn("🗑", "Удалить", "btn small warn icon", act("delete")),
|
||||
);
|
||||
tr.append(nameTd, stTd, actTd);
|
||||
rows.appendChild(tr);
|
||||
}
|
||||
} catch (e) {
|
||||
if (line) line.textContent = String(e.message || e);
|
||||
}
|
||||
}
|
||||
|
||||
document.querySelector("#xray-install-form")?.addEventListener("submit", async (ev) => {
|
||||
ev.preventDefault();
|
||||
const b = ev.target.querySelector("button[type=submit]");
|
||||
if (b) b.disabled = true;
|
||||
try {
|
||||
setStatus("Ставлю Xray (сборка образа ~1 мин)…", false);
|
||||
await api("/api/xray/install", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
port: document.querySelector("#xray-port").value,
|
||||
sni: document.querySelector("#xray-sni").value,
|
||||
}),
|
||||
});
|
||||
setStatus("Xray установлен. Создайте клиента.", false);
|
||||
await loadXray();
|
||||
} catch (e) {
|
||||
setStatus(String(e.message || e), true);
|
||||
} finally {
|
||||
if (b) b.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
document.querySelector("#xray-client-form")?.addEventListener("submit", async (ev) => {
|
||||
ev.preventDefault();
|
||||
const input = document.querySelector("#xray-client-name");
|
||||
try {
|
||||
const r = await api("/api/xray/clients/create", { method: "POST", body: JSON.stringify({ name: input.value }) });
|
||||
input.value = "";
|
||||
const ok = await copyTextToClipboard(r.link);
|
||||
setStatus(ok ? "Клиент создан, ссылка скопирована." : "Клиент создан.", false);
|
||||
await loadXray();
|
||||
} catch (e) {
|
||||
setStatus(String(e.message || e), true);
|
||||
}
|
||||
});
|
||||
|
||||
document.querySelector("#xray-remove")?.addEventListener("click", async () => {
|
||||
if (!confirm("Удалить контейнер Xray? Клиенты Xray перестанут работать.")) return;
|
||||
try {
|
||||
await api("/api/xray/remove", { method: "POST", body: "{}" });
|
||||
await loadXray();
|
||||
} catch (e) {
|
||||
setStatus(String(e.message || e), true);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -7,14 +7,15 @@
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;600;700&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="/styles.css?v=1.2.28">
|
||||
<script>try{var t=localStorage.getItem("theme")||(matchMedia("(prefers-color-scheme: light)").matches?"light":"dark");document.documentElement.dataset.theme=t}catch(e){}</script>
|
||||
<link rel="stylesheet" href="/styles.css?v=1.4.0">
|
||||
</head>
|
||||
<body class="page">
|
||||
<aside class="panel-promo-strip" role="complementary" aria-label="Поддержка и донат">
|
||||
<div class="panel-promo-strip-inner">
|
||||
<p class="panel-promo-subtitle muted">Поддержите проект через Boosty, Ozon СБП и Telegram — ниже те же ссылки в подвале.</p>
|
||||
<div class="panel-promo-links">
|
||||
<a class="panel-promo-a" href="https://github.com/andrey271192/amnezia_web-PRO" target="_blank" rel="noopener noreferrer">⭐ GitHub · PRO</a>
|
||||
<a class="panel-promo-a" href="https://github.com/andrey271192/amnezia_web-PRO" target="_blank" rel="noopener noreferrer">⭐ GitHub</a>
|
||||
<span class="panel-promo-sep" aria-hidden="true">·</span>
|
||||
<a class="panel-promo-a" href="https://boosty.to/andrey27/donate" target="_blank" rel="noopener noreferrer">💖 Boosty</a>
|
||||
<span class="panel-promo-sep" aria-hidden="true">·</span>
|
||||
@@ -38,7 +39,7 @@
|
||||
</form>
|
||||
<nav class="gate-donate muted" aria-label="Поддержка и донат">
|
||||
Поддержка веб‑панелей (вне этого сервера):<br/>
|
||||
<a href="https://github.com/andrey271192/amnezia_web-PRO" target="_blank" rel="noopener noreferrer">GitHub · PRO</a>
|
||||
<a href="https://github.com/andrey271192/amnezia_web-PRO" target="_blank" rel="noopener noreferrer">GitHub</a>
|
||||
<span class="gate-donate-dot" aria-hidden="true">·</span>
|
||||
<a href="https://boosty.to/andrey27/donate" target="_blank" rel="noopener noreferrer">Boosty</a>
|
||||
<span class="gate-donate-dot" aria-hidden="true">·</span>
|
||||
@@ -58,6 +59,7 @@
|
||||
</div>
|
||||
<div class="token-box">
|
||||
<div class="session-actions">
|
||||
<button type="button" id="theme-toggle" class="btn ghost full" title="Светлая / тёмная тема">◐ Тема</button>
|
||||
<button type="button" id="logout" class="btn ghost full">Выйти</button>
|
||||
</div>
|
||||
<details class="pw-change">
|
||||
@@ -76,7 +78,6 @@
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div id="edition-banner" class="edition-banner hidden" role="region" aria-label="Редакция панели"></div>
|
||||
|
||||
<section class="toolbar">
|
||||
<div class="pill proto-pill"><span class="dot ok"></span><span id="proto-label">Протокол: AmneziaWG</span></div>
|
||||
@@ -121,7 +122,7 @@
|
||||
<summary class="fold-summary">
|
||||
<span class="fold-arrow" aria-hidden="true"></span>
|
||||
<span class="fold-titles">
|
||||
<span class="fold-h">Cloudflare WARP</span>
|
||||
<span class="fold-h">Cloudflare WARP / каскад</span>
|
||||
<span class="muted fold-meta" id="warp-status-line"></span>
|
||||
</span>
|
||||
</summary>
|
||||
@@ -132,6 +133,11 @@
|
||||
Один раз на хосте VPS под root: в каталоге с репозиторием выполните <code class="inline">bash scripts/warp-amnezia.sh install</code>.
|
||||
Затем отметьте клиентов ниже и нажмите «Применить» (контейнер AWG перезапустится). Установить или удалить WARP с хоста можно кнопками ниже (пароль root по SSH — как при синхронизации времени). Убрать вручную: <code class="inline">bash scripts/warp-amnezia.sh uninstall</code> — см. README.
|
||||
</p>
|
||||
<form id="upstream-form" class="cascade-form">
|
||||
<label for="upstream-conf"><strong>Каскад через другой сервер</strong> — вставьте клиентский .conf (AmneziaWG или WireGuard) другого сервера. Он станет выходом вместо WARP: отмеченные ниже клиенты пойдут в интернет через тот сервер.</label>
|
||||
<textarea id="upstream-conf" rows="6" placeholder="[Interface] PrivateKey = … [Peer] Endpoint = …" autocomplete="off"></textarea>
|
||||
<button type="submit" class="btn primary">Подключить вышестоящий сервер</button>
|
||||
</form>
|
||||
<div id="warp-actions" class="warp-actions"></div>
|
||||
<div id="warp-client-list" class="warp-client-list"></div>
|
||||
<details class="raw warp-raw">
|
||||
@@ -183,6 +189,44 @@
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="panel-fold" id="xray-panel">
|
||||
<summary class="fold-summary">
|
||||
<span class="fold-arrow" aria-hidden="true"></span>
|
||||
<span class="fold-titles">
|
||||
<span class="fold-h">Xray VLESS‑Reality</span>
|
||||
<span class="muted fold-meta" id="xray-status-line"></span>
|
||||
</span>
|
||||
</summary>
|
||||
<div class="panel-fold-body">
|
||||
<p class="muted warp-intro">
|
||||
Протокол для мест, где блокируют AmneziaWG: трафик выглядит как обычный HTTPS к сайту‑маскировке.
|
||||
Ссылку <code class="inline">vless://</code> вставьте в Amnezia VPN, v2rayNG, Hiddify, Streisand или Happ. Нужен открытый TCP‑порт.
|
||||
</p>
|
||||
<form id="xray-install-form" class="instance-form">
|
||||
<div class="instance-form-row">
|
||||
<label for="xray-port">Порт (TCP)</label>
|
||||
<input id="xray-port" type="number" min="1" max="65535" value="443">
|
||||
</div>
|
||||
<div class="instance-form-row">
|
||||
<label for="xray-sni">Сайт‑маскировка</label>
|
||||
<input id="xray-sni" type="text" value="www.google.com" autocomplete="off">
|
||||
</div>
|
||||
<button type="submit" class="btn primary">+ Установить Xray</button>
|
||||
</form>
|
||||
<div id="xray-manage" style="display:none">
|
||||
<form id="xray-client-form" class="instance-form">
|
||||
<div class="instance-form-row">
|
||||
<label for="xray-client-name">Новый клиент</label>
|
||||
<input id="xray-client-name" type="text" maxlength="64" placeholder="Имя" autocomplete="off">
|
||||
</div>
|
||||
<button type="submit" class="btn primary">+ Создать</button>
|
||||
<button type="button" id="xray-remove" class="btn small warn">Удалить Xray</button>
|
||||
</form>
|
||||
<table class="clients-table"><tbody id="xray-rows"></tbody></table>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="panel-fold" id="instances-panel" open>
|
||||
<summary class="fold-summary">
|
||||
<span class="fold-arrow" aria-hidden="true"></span>
|
||||
@@ -198,8 +242,10 @@
|
||||
<label for="instance-variant">Протокол</label>
|
||||
<select id="instance-variant" class="form-select">
|
||||
<option value="awg2">AmneziaWG 2.0 (рекомендуется)</option>
|
||||
<option value="awg">AmneziaWG</option>
|
||||
<option value="legacy">AmneziaWG Legacy</option>
|
||||
<option value="awg31">AmneziaWG 3.1 — новейший, свежее приложение Amnezia</option>
|
||||
<option value="awg3">AmneziaWG 3.0</option>
|
||||
<option value="awg">AmneziaWG 1.x — роутеры Keenetic/OpenWrt, старые приложения</option>
|
||||
<option value="legacy">WireGuard (Legacy) — любой WG-клиент, без обфускации</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="instance-form-row">
|
||||
@@ -208,7 +254,15 @@
|
||||
</div>
|
||||
<button type="submit" class="btn primary">+ Развернуть инстанс</button>
|
||||
</form>
|
||||
<p class="muted instance-hint">Создаёт серверный контейнер AmneziaWG из публичного образа, генерирует ключи и NAT. Затем в «Пользователях» выберите инстанс и создавайте клиентов.</p>
|
||||
<p class="muted instance-hint">Создаёт серверный контейнер AmneziaWG из публичного образа, генерирует ключи и NAT. Затем в «Пользователях» выберите инстанс и создавайте клиентов. Можно держать несколько версий рядом на разных портах: 3.1/2.0 — для телефонов и ПК, 1.x или WireGuard — для роутеров. Не забудьте открыть UDP-порт в фаерволе хостинга.</p>
|
||||
<form id="settings-form" class="instance-form">
|
||||
<div class="instance-form-row">
|
||||
<label for="settings-endpoint">Домен или IP сервера в конфигах клиентов</label>
|
||||
<input id="settings-endpoint" type="text" placeholder="vpn.example.com — пусто: IP из установки" autocomplete="off">
|
||||
</div>
|
||||
<button type="submit" class="btn primary">Сохранить адрес</button>
|
||||
</form>
|
||||
<p id="settings-hint" class="muted instance-hint"></p>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
@@ -406,6 +460,6 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<script src="/app.js?v=1.2.28" type="module"></script>
|
||||
<script src="/app.js?v=1.4.0" type="module"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -8,6 +8,10 @@
|
||||
--danger: #fb7185;
|
||||
--ok: #4ade80;
|
||||
--shadow: 0 24px 80px rgba(0, 0, 0, 0.45);
|
||||
--field: #0a0f16;
|
||||
--text-soft: #cbd5f5;
|
||||
--overlay: rgba(10, 15, 22, 0.92);
|
||||
color-scheme: dark;
|
||||
font-family: "DM Sans", system-ui, sans-serif;
|
||||
}
|
||||
|
||||
@@ -15,6 +19,28 @@
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
/* Светлая тема: те же переменные, переключатель в шапке (localStorage "theme"). */
|
||||
html[data-theme="light"] {
|
||||
--bg: #f4f6fb;
|
||||
--card: #ffffff;
|
||||
--line: rgba(15, 23, 42, 0.12);
|
||||
--text: #0f172a;
|
||||
--muted: #526077;
|
||||
--accent: #0369a1;
|
||||
--danger: #be123c;
|
||||
--ok: #15803d;
|
||||
--shadow: 0 12px 40px rgba(15, 23, 42, 0.12);
|
||||
--field: #ffffff;
|
||||
--text-soft: #1e293b;
|
||||
--overlay: rgba(255, 255, 255, 0.94);
|
||||
color-scheme: light;
|
||||
}
|
||||
html[data-theme="light"] .panel-promo-strip {
|
||||
background: linear-gradient(90deg, #e0f2fe, #eef2ff);
|
||||
border-bottom-color: rgba(3, 105, 161, 0.25);
|
||||
}
|
||||
html[data-theme="light"] .panel-promo-a { color: #92400e; }
|
||||
|
||||
body.page {
|
||||
margin: 0;
|
||||
background: radial-gradient(circle at 20% 20%, rgba(125, 211, 252, 0.08), transparent 35%),
|
||||
@@ -123,7 +149,7 @@ h1 {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 14px;
|
||||
padding: 1rem;
|
||||
background: #0c121b;
|
||||
background: var(--field);
|
||||
}
|
||||
|
||||
.token-box label {
|
||||
@@ -191,7 +217,7 @@ h1 {
|
||||
padding: 0.65rem 0.75rem;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--line);
|
||||
background: #0a0f16;
|
||||
background: var(--field);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
margin-bottom: 0.75rem;
|
||||
@@ -255,7 +281,7 @@ h1 {
|
||||
padding: 0.55rem 0.65rem;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--line);
|
||||
background: #0a0f16;
|
||||
background: var(--field);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
}
|
||||
@@ -265,7 +291,7 @@ h1 {
|
||||
padding: 0.65rem 0.75rem;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--line);
|
||||
background: #0a0f16;
|
||||
background: var(--field);
|
||||
color: var(--text);
|
||||
font-family: "JetBrains Mono", ui-monospace, monospace;
|
||||
font-size: 0.85rem;
|
||||
@@ -294,7 +320,7 @@ h1 {
|
||||
padding: 0.45rem 0.55rem;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--line);
|
||||
background: #0a0f16;
|
||||
background: var(--field);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
font-size: 0.85rem;
|
||||
@@ -407,7 +433,7 @@ h1 {
|
||||
padding: 0.45rem 0.55rem;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--line);
|
||||
background: #0a0f16;
|
||||
background: var(--field);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
font-size: 0.85rem;
|
||||
@@ -715,7 +741,7 @@ tr:last-child td {
|
||||
.ip {
|
||||
font-family: "JetBrains Mono", ui-monospace, monospace;
|
||||
font-size: 0.85rem;
|
||||
color: #dbeafe;
|
||||
color: var(--text-soft);
|
||||
}
|
||||
|
||||
.badge {
|
||||
@@ -736,7 +762,7 @@ tr:last-child td {
|
||||
|
||||
.badge.off {
|
||||
border-color: rgba(148, 163, 184, 0.35);
|
||||
color: #e2e8f0;
|
||||
color: var(--text-soft);
|
||||
background: rgba(148, 163, 184, 0.06);
|
||||
}
|
||||
|
||||
@@ -833,11 +859,11 @@ tr:last-child td {
|
||||
.cascade-snippet {
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
background: #0a0f16;
|
||||
background: var(--field);
|
||||
border: 1px solid var(--line);
|
||||
padding: 0.75rem 0.95rem;
|
||||
border-radius: 12px;
|
||||
color: #cbd5f5;
|
||||
color: var(--text-soft);
|
||||
font-size: 0.78rem;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
margin: 0.5rem 0 0.85rem;
|
||||
@@ -884,11 +910,11 @@ tr:last-child td {
|
||||
.raw pre {
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
background: #0a0f16;
|
||||
background: var(--field);
|
||||
border: 1px solid var(--line);
|
||||
padding: 0.75rem;
|
||||
border-radius: 12px;
|
||||
color: #cbd5f5;
|
||||
color: var(--text-soft);
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
||||
@@ -927,7 +953,7 @@ tr:last-child td {
|
||||
padding: 0.55rem 0.65rem;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--line);
|
||||
background: #0a0f16;
|
||||
background: var(--field);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
}
|
||||
@@ -975,7 +1001,7 @@ tr:last-child td {
|
||||
margin-top: auto;
|
||||
padding: 1.25rem clamp(1rem, 3vw, 1.5rem) 1.5rem;
|
||||
border-top: 1px solid var(--line);
|
||||
background: rgba(10, 15, 22, 0.92);
|
||||
background: var(--overlay);
|
||||
}
|
||||
|
||||
.support-line {
|
||||
@@ -1071,36 +1097,6 @@ tr:last-child td {
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.edition-banner {
|
||||
margin: 0 0 1rem;
|
||||
padding: 0.85rem 1rem;
|
||||
border-radius: 14px;
|
||||
border: 1px solid rgba(125, 211, 252, 0.35);
|
||||
background: linear-gradient(135deg, rgba(125, 211, 252, 0.12), rgba(94, 234, 212, 0.06));
|
||||
}
|
||||
|
||||
.edition-banner.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.edition-banner-inner {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem 1rem;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.edition-banner-text {
|
||||
flex: 1 1 280px;
|
||||
}
|
||||
|
||||
.edition-banner-pitch {
|
||||
margin: 0.35rem 0 0;
|
||||
font-size: 0.88rem;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
/* --- Telegram MTProto --- */
|
||||
.mtproto-link-card {
|
||||
margin: 0.65rem 0 0.85rem;
|
||||
@@ -1227,3 +1223,12 @@ tr:last-child td {
|
||||
.instance-empty { padding: 12px; }
|
||||
|
||||
.inst-src { font-size: 0.6rem; color: var(--muted); border: 1px solid var(--line); border-radius: 999px; padding: 2px 7px; vertical-align: middle; }
|
||||
|
||||
/* Светлая тема: пастельные надписи тёмной темы на белом не читаются */
|
||||
html[data-theme="light"] .clock-zone-diff--accent,
|
||||
html[data-theme="light"] .cascade-guide a,
|
||||
html[data-theme="light"] .cascade-guide a:hover { color: #0369a1; }
|
||||
html[data-theme="light"] .btn.warn { color: #9f1239; }
|
||||
html[data-theme="light"] .status.err { color: #b91c1c; }
|
||||
html[data-theme="light"] .badge.on { color: #166534; }
|
||||
html[data-theme="light"] body.page { background: var(--bg); }
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
# Deploy / remove an AmneziaWG server instance from public images — no Amnezia app.
|
||||
# Variants: awg2 (AmneziaWG 2.0, awg-go 2.0.0), awg (classic, awg-go 0.2.18),
|
||||
# legacy (kernel WireGuard, amnezia-wg).
|
||||
# Variants: awg31 (AmneziaWG 3.1), awg3 (3.0), awg2 (2.0, awg-go 2.0.0),
|
||||
# awg (1.x for routers/old apps, awg-go 0.2.18), legacy (plain WireGuard, amnezia-wg).
|
||||
# Usage:
|
||||
# awg-instance.sh create <variant> <port> [name]
|
||||
# awg-instance.sh remove <name>
|
||||
@@ -12,6 +12,9 @@ INSTANCES_DIR="${INSTANCES_DIR:-/opt/amnezia-instances}"
|
||||
IMG_AWG2="${IMG_AWG2:-amneziavpn/amneziawg-go:2.0.0}"
|
||||
IMG_AWG="${IMG_AWG:-amneziavpn/amneziawg-go:0.2.18}"
|
||||
IMG_LEGACY="${IMG_LEGACY:-amneziavpn/amnezia-wg:latest}"
|
||||
# 3.x pinned by digest: tags on Docker Hub get rewritten (tools inside differ from the tag name)
|
||||
IMG_AWG3="${IMG_AWG3:-amneziavpn/amneziawg-go:3.0.20260805@sha256:8447c91637c37536dd99b8bbd4420c819ac9f330f047804197291625bfb0ea8a}"
|
||||
IMG_AWG31="${IMG_AWG31:-amneziavpn/amneziawg-go:3.1.20260828@sha256:cbafc02b8373a83f428272db6d8001b37bc02e6211cbd8c0cb4e2e3759b12b72}"
|
||||
|
||||
err() { echo "ERROR: $*" >&2; exit 1; }
|
||||
|
||||
@@ -28,10 +31,12 @@ rand_magic() { # single large uint32 (AmneziaWG H header), NOT a range
|
||||
|
||||
image_for() {
|
||||
case "$1" in
|
||||
awg31) echo "$IMG_AWG31" ;;
|
||||
awg3) echo "$IMG_AWG3" ;;
|
||||
awg2) echo "$IMG_AWG2" ;;
|
||||
awg) echo "$IMG_AWG" ;;
|
||||
legacy) echo "$IMG_LEGACY" ;;
|
||||
*) err "unknown variant: $1 (awg2|awg|legacy)" ;;
|
||||
*) err "unknown variant: $1 (awg31|awg3|awg2|awg|legacy)" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
@@ -63,7 +68,8 @@ cmd_create() {
|
||||
[[ -n "$name" ]] || err "bad name"
|
||||
docker inspect "$name" >/dev/null 2>&1 && err "container $name already exists"
|
||||
# port free?
|
||||
if ss -lun 2>/dev/null | grep -qE "[:.]${port}\b"; then err "udp port $port busy"; fi
|
||||
# this script runs inside the panel container: its own `ss` does not see host ports, docker does
|
||||
if docker ps --format '{{.Ports}}' | tr ',' '\n' | grep -qE ":${port}->[0-9]+/udp"; then err "udp port $port busy (другой контейнер)"; fi
|
||||
|
||||
echo "→ pulling $img"
|
||||
docker pull -q "$img" >/dev/null
|
||||
@@ -87,22 +93,37 @@ cmd_create() {
|
||||
{
|
||||
echo "[Interface]"
|
||||
echo "PrivateKey = $priv"
|
||||
echo "Address = ${net}.0/24"
|
||||
echo "Address = ${net}.1/24"
|
||||
echo "ListenPort = $port"
|
||||
if [[ "$variant" != "legacy" ]]; then
|
||||
# 3.x header protection rejects junk sizes <= 12
|
||||
local smin=15
|
||||
echo "Jc = $(rand_range 3 10)"
|
||||
echo "Jmin = 10"
|
||||
echo "Jmax = 50"
|
||||
echo "S1 = $(rand_range 15 60)"
|
||||
echo "S2 = $(rand_range 15 60)"
|
||||
if [[ "$variant" == "awg2" ]]; then
|
||||
echo "S3 = $(rand_range 5 40)"
|
||||
echo "S4 = $(rand_range 1 40)"
|
||||
echo "S1 = $(rand_range $smin 60)"
|
||||
echo "S2 = $(rand_range $smin 60)"
|
||||
if [[ "$variant" != "awg" ]]; then
|
||||
echo "S3 = $(rand_range $smin 40)"
|
||||
echo "S4 = $(rand_range $smin 40)"
|
||||
fi
|
||||
echo "H1 = $(rand_magic)"
|
||||
echo "H2 = $(rand_magic)"
|
||||
echo "H3 = $(rand_magic)"
|
||||
echo "H4 = $(rand_magic)"
|
||||
if [[ "$variant" == awg3* ]]; then
|
||||
echo "HeaderProtectionKey = $(docker run --rm "$img" awg genkey | tr -d '\r\n')"
|
||||
echo "ContentPaddingAddition = 10-100"
|
||||
echo "RekeyAfterTime = 100-120"
|
||||
echo "RekeyTimeout = 3-7"
|
||||
echo "RejectAfterTime = 150-180"
|
||||
echo "KeepaliveTimeout = 5-15"
|
||||
echo "MaxHandshakeAttempts = 15-20"
|
||||
fi
|
||||
if [[ "$variant" == "awg31" ]]; then
|
||||
echo "RandomTrailers = on"
|
||||
echo "DisableCookies = on"
|
||||
fi
|
||||
fi
|
||||
} > "$conf"
|
||||
|
||||
@@ -114,6 +135,13 @@ cmd_create() {
|
||||
# start script run inside container
|
||||
local usimpl=""
|
||||
if [[ "$variant" != "legacy" ]]; then usimpl="export WG_QUICK_USERSPACE_IMPLEMENTATION=amneziawg-go"; fi
|
||||
# 3.x is userspace-only: a loaded amneziawg kernel module (2.0 on the same host) does not know 3.x keys
|
||||
if [[ "$variant" == awg3* ]]; then
|
||||
usimpl="$usimpl"$'\n'"$(cat <<'PATCH'
|
||||
sed -i -e 's/if ! cmd ip link add "$INTERFACE" type amneziawg; then/if true; then/' -e 's|^\([[:space:]]*\)\[\[ -e /sys/module/amneziawg \]\].*|\1:|' /usr/bin/awg-quick
|
||||
PATCH
|
||||
)"
|
||||
fi
|
||||
cat > "$dir/start.sh" <<EOF
|
||||
#!/bin/sh
|
||||
set +e
|
||||
@@ -156,7 +184,7 @@ cmd_remove() {
|
||||
}
|
||||
|
||||
cmd_list() {
|
||||
docker ps --format '{{.Names}} {{.Ports}}' | grep -E '^amnezia-(awg2|awg|legacy)-|^amnezia-' || true
|
||||
docker ps --format '{{.Names}} {{.Ports}}' | grep -E '^amnezia-' || true
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
|
||||
@@ -161,7 +161,8 @@ if [[ -z "${AWG_PROFILES:-}" ]] && [[ -f "${AWG_PROFILE_SNAPSHOT}" ]]; then
|
||||
fi
|
||||
fi
|
||||
|
||||
__awg_names="$(docker ps --format '{{.Names}}' 2>/dev/null | awk '/^amnezia-awg/ { print }' | sort || true)"
|
||||
# Контейнеры, развёрнутые самой панелью (/opt/amnezia-instances/<имя>), панель знает сама — в AWG_PROFILES их не кладём.
|
||||
__awg_names="$(docker ps --format '{{.Names}}' 2>/dev/null | awk '/^amnezia-awg/ { print }' | while read -r __n; do [[ -d "/opt/amnezia-instances/${__n}" ]] || echo "${__n}"; done | sort || true)"
|
||||
__awg_multi_count="$(printf '%s\n' "${__awg_names}" | sed '/^$/d' | wc -l | tr -d '[:space:]')"
|
||||
__profile_container_count=0
|
||||
if [[ -n "${AWG_PROFILES:-}" ]]; then
|
||||
@@ -282,20 +283,6 @@ if [[ -n "${BOOT_PW}" ]]; then
|
||||
RUN_ENV+=( -e "ADMIN_PASSWORD=${BOOT_PW}" )
|
||||
fi
|
||||
|
||||
if [[ -n "${AMNEZIA_EDITION:-}" ]]; then
|
||||
RUN_ENV+=( -e "AMNEZIA_EDITION=${AMNEZIA_EDITION}" )
|
||||
elif [[ -f "${INSTALL_DIR}/.amnezia-panel-edition" ]]; then
|
||||
__PE="$(tr -d '\r\n' <"${INSTALL_DIR}/.amnezia-panel-edition" | head -c 48)"
|
||||
if [[ -n "${__PE}" ]]; then
|
||||
RUN_ENV+=( -e "AMNEZIA_EDITION=${__PE}" )
|
||||
echo "→ AMNEZIA_EDITION из ${INSTALL_DIR}/.amnezia-panel-edition: ${__PE}"
|
||||
fi
|
||||
fi
|
||||
for __ce_var in COMMUNITY_UPGRADE_URL COMMUNITY_UPGRADE_PITCH; do
|
||||
if [[ -n "${!__ce_var:-}" ]]; then
|
||||
RUN_ENV+=( -e "${__ce_var}=${!__ce_var}" )
|
||||
fi
|
||||
done
|
||||
|
||||
IP="$(hostname -I 2>/dev/null | awk '{print $1}' || true)"
|
||||
|
||||
|
||||
598
server.js
598
server.js
@@ -3,6 +3,7 @@ import { spawn, spawnSync } from "child_process";
|
||||
import crypto from "crypto";
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import dns from "dns";
|
||||
import { fileURLToPath } from "url";
|
||||
import { healClientsMeta, readClientsMeta, writeClientsMeta } from "./scripts/clients-meta.mjs";
|
||||
|
||||
@@ -50,36 +51,6 @@ function resolveUiHidden() {
|
||||
|
||||
const UI_HIDDEN = resolveUiHidden();
|
||||
|
||||
const AMNEZIA_EDITION = (process.env.AMNEZIA_EDITION || "pro").trim().toLowerCase();
|
||||
const IS_COMMUNITY = AMNEZIA_EDITION === "community";
|
||||
const COMMUNITY_UPGRADE_URL =
|
||||
process.env.COMMUNITY_UPGRADE_URL?.trim() ||
|
||||
"https://github.com/andrey271192/amnezia_web-PRO";
|
||||
const COMMUNITY_UPGRADE_PITCH =
|
||||
process.env.COMMUNITY_UPGRADE_PITCH?.trim() ||
|
||||
"В PRO: вкл/выкл клиентов, даты и расписание отключений, переименование, удаление, экспорт .conf, каскад, Cloudflare WARP, синхронизация времени хоста. Полная сборка открыта в публичном репозитории amnezia_web-PRO.";
|
||||
|
||||
function editionPayload() {
|
||||
return {
|
||||
tier: IS_COMMUNITY ? "community" : "pro",
|
||||
readOnlyClients: IS_COMMUNITY,
|
||||
upgradeUrl: IS_COMMUNITY ? COMMUNITY_UPGRADE_URL : null,
|
||||
upgradePitch: IS_COMMUNITY ? COMMUNITY_UPGRADE_PITCH : null,
|
||||
showDebugWg: !IS_COMMUNITY,
|
||||
};
|
||||
}
|
||||
|
||||
function effectiveUiHidden() {
|
||||
if (!IS_COMMUNITY) return { ...UI_HIDDEN };
|
||||
return {
|
||||
users: UI_HIDDEN.users,
|
||||
warp: true,
|
||||
cascade: true,
|
||||
mtproto: UI_HIDDEN.mtproto,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
function parseProfilesFromEnv() {
|
||||
const raw = process.env.AWG_PROFILES?.trim();
|
||||
const fallback = () => {
|
||||
@@ -87,6 +58,7 @@ function parseProfilesFromEnv() {
|
||||
return [
|
||||
{
|
||||
id: "awg",
|
||||
isDefault: true,
|
||||
label: process.env.AWG_PROFILE_LABEL || "AmneziaWG",
|
||||
container: process.env.AWG_CONTAINER || "amnezia-awg",
|
||||
confPath: process.env.AWG_CONF_PATH || "/opt/amnezia/awg/awg0.conf",
|
||||
@@ -137,25 +109,36 @@ function parseProfilesFromEnv() {
|
||||
}
|
||||
|
||||
const ENV_PROFILES = parseProfilesFromEnv();
|
||||
let defaultProfileMissing = false; // set by createRuntime when the default profile resolves to nothing
|
||||
|
||||
const INSTANCES_DIR = process.env.INSTANCES_DIR || "/opt/amnezia-instances";
|
||||
const INSTANCES_FILE = `${process.env.DATA_DIR || "/data"}/instances.json`;
|
||||
const INSTANCE_SCRIPT = `${process.env.APP_DIR || "/app"}/scripts/awg-instance.sh`;
|
||||
|
||||
const INSTANCE_VARIANTS = {
|
||||
awg31: {
|
||||
label: "AmneziaWG 3.1",
|
||||
desc: "Новейшая версия: защита заголовков, случайные хвосты пакетов. Нужно свежее приложение Amnezia.",
|
||||
iface: "awg0", binary: "awg",
|
||||
},
|
||||
awg3: {
|
||||
label: "AmneziaWG 3.0",
|
||||
desc: "Защита заголовков (HeaderProtectionKey), паддинг. Приложение Amnezia 4.8.x и новее.",
|
||||
iface: "awg0", binary: "awg",
|
||||
},
|
||||
awg2: {
|
||||
label: "AmneziaWG 2.0",
|
||||
desc: "Новая версия протокола на основе awg-go. Расширенная обфускация (S3, S4).",
|
||||
iface: "awg0", binary: "awg",
|
||||
},
|
||||
awg: {
|
||||
label: "AmneziaWG",
|
||||
desc: "Версия протокола на основе awg-go. Обфускация S1, S2.",
|
||||
label: "AmneziaWG 1.x (роутеры)",
|
||||
desc: "Обфускация Jc/S1/S2/H1–H4 без S3/S4 — для Keenetic, OpenWrt и старых приложений.",
|
||||
iface: "awg0", binary: "awg",
|
||||
},
|
||||
legacy: {
|
||||
label: "AmneziaWG Legacy",
|
||||
desc: "Оригинальная версия на ядре WireGuard. Совместима с клиентами старых версий.",
|
||||
label: "WireGuard (Legacy)",
|
||||
desc: "Чистый WireGuard без обфускации — любой WG-клиент и любые роутеры. Легко блокируется DPI.",
|
||||
iface: "wg0", binary: "wg",
|
||||
},
|
||||
};
|
||||
@@ -219,10 +202,16 @@ function profileIdentityKey(p) {
|
||||
// Effective profile set = env profiles + managed instances (deduped by id and target files).
|
||||
function getProfiles() {
|
||||
const managed = loadManagedProfiles();
|
||||
const managedContainers = new Set(managed.map((m) => m.container));
|
||||
const seenIds = new Set();
|
||||
const seenTargets = new Set();
|
||||
const out = [];
|
||||
for (const p of [...ENV_PROFILES, ...managed]) {
|
||||
// install.sh used to put panel-managed containers into AWG_PROFILES too: the env copy then
|
||||
// shadowed the managed one (wrong id, no variant). Managed instance wins.
|
||||
const envProfiles = ENV_PROFILES.filter((p) => !managedContainers.has(p.container));
|
||||
// Default profile (no AWG_PROFILES) that found no container: hide it once the panel has its own instances.
|
||||
const env = managed.length && defaultProfileMissing ? envProfiles.filter((p) => !p.isDefault) : envProfiles;
|
||||
for (const p of [...env, ...managed]) {
|
||||
const id = String(p.id || "").trim();
|
||||
const target = profileIdentityKey(p);
|
||||
if ((id && seenIds.has(id)) || (target !== "|||" && seenTargets.has(target))) continue;
|
||||
@@ -438,23 +427,6 @@ function requireAuthOrExportToken(req, res, next) {
|
||||
requireAuth(req, res, next);
|
||||
}
|
||||
|
||||
function rejectCommunityProOnly(res) {
|
||||
res.status(403).json({
|
||||
error:
|
||||
"Доступно в версии PRO: управление клиентами, экспорт .conf, каскад, Cloudflare WARP и синхронизация времени хоста.",
|
||||
upgradeRequired: true,
|
||||
upgradeUrl: COMMUNITY_UPGRADE_URL,
|
||||
});
|
||||
}
|
||||
|
||||
function requireProTier(_req, res, next) {
|
||||
if (!IS_COMMUNITY) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
rejectCommunityProOnly(res);
|
||||
}
|
||||
|
||||
function runtimeFromExportRequest(req) {
|
||||
const qPid = typeof req.query.profileId === "string" ? req.query.profileId.trim() : "";
|
||||
const bodyPid =
|
||||
@@ -546,6 +518,30 @@ async function dockerRestartContainer(container) {
|
||||
throw new Error("Контейнер не ответил после restart");
|
||||
}
|
||||
|
||||
// awg-quick brings up both AmneziaWG and plain WireGuard configs; old images only have wg-quick.
|
||||
const QUICK_SH = "$(command -v awg-quick || echo wg-quick)";
|
||||
|
||||
/**
|
||||
* Upstream for a real cascade: a client .conf of ANOTHER server (AWG or WG) becomes the "warp"
|
||||
* interface of this instance. Routing of selected clients reuses the WARP machinery.
|
||||
*/
|
||||
function buildUpstreamConf(text) {
|
||||
const sections = parseWireGuardSections(text);
|
||||
const iface = sections.interface || {};
|
||||
const peer = sections.peer || {};
|
||||
if (!iface.PrivateKey || !peer.PublicKey || !peer.Endpoint) {
|
||||
throw new Error("Нужен клиентский конфиг другого сервера: [Interface] с PrivateKey и [Peer] с PublicKey и Endpoint.");
|
||||
}
|
||||
const lines = ["[Interface]", `PrivateKey = ${iface.PrivateKey}`];
|
||||
if (iface.Address) lines.push(`Address = ${String(iface.Address).split(",")[0].trim()}`);
|
||||
for (const k of AWG_OBF_KEYS) if (iface[k]) lines.push(`${k} = ${iface[k]}`);
|
||||
lines.push(`MTU = ${iface.MTU || 1280}`, "Table = off", "", "[Peer]", `PublicKey = ${peer.PublicKey}`);
|
||||
if (peer.PresharedKey) lines.push(`PresharedKey = ${peer.PresharedKey}`);
|
||||
lines.push("AllowedIPs = 0.0.0.0/0", `Endpoint = ${peer.Endpoint}`, "PersistentKeepalive = 25", "");
|
||||
for (const l of lines) if (/['`$\\]/.test(l)) throw new Error("Недопустимые символы в конфиге.");
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
async function warpFileExists(rt, remotePath) {
|
||||
try {
|
||||
await execDocker(["exec", await rt.resolveContainer(), "test", "-f", remotePath]);
|
||||
@@ -637,7 +633,7 @@ function buildWarpBootBlock(warpConf, ips) {
|
||||
return (
|
||||
"# --- WARP-MANAGER BEGIN ---\n\n" +
|
||||
`if [ -f '${warpConf}' ]; then\n` +
|
||||
` wg-quick up '${warpConf}' || true\n` +
|
||||
` ${QUICK_SH} up '${warpConf}' || true\n` +
|
||||
` sleep 3\n` +
|
||||
`fi\n\n` +
|
||||
routing +
|
||||
@@ -745,7 +741,7 @@ async function warpSummaryForRt(rt) {
|
||||
let wgShowWarp = "";
|
||||
if (installed && running) {
|
||||
try {
|
||||
wgShowWarp = await rt.dockerExec("wg show warp 2>/dev/null || true");
|
||||
wgShowWarp = await rt.dockerExec("awg show warp 2>/dev/null || wg show warp 2>/dev/null || true");
|
||||
} catch {
|
||||
wgShowWarp = "";
|
||||
}
|
||||
@@ -800,7 +796,8 @@ async function containerHasFile(name, filePath) {
|
||||
// Lets the panel work even if AWG_CONTAINER points at the wrong name
|
||||
// (e.g. configured "amnezia-awg" but Amnezia created "amnezia-awg2").
|
||||
async function discoverAwgContainer(confPath, preferredName) {
|
||||
const names = await listRunningContainerNames();
|
||||
const managed = new Set(loadManagedProfiles().map((m) => m.container));
|
||||
const names = (await listRunningContainerNames()).filter((n) => n === preferredName || !managed.has(n));
|
||||
const score = (n) => {
|
||||
if (preferredName && n === preferredName) return 0;
|
||||
if (/^amnezia-?awg/i.test(n)) return 1;
|
||||
@@ -852,6 +849,7 @@ function createRuntime(profile) {
|
||||
if (profile.container) {
|
||||
for (const candidate of confCandidates) {
|
||||
if (await containerHasFile(profile.container, candidate)) {
|
||||
if (profile.isDefault) defaultProfileMissing = false;
|
||||
resolvedContainer = profile.container;
|
||||
return resolvedContainer;
|
||||
}
|
||||
@@ -862,6 +860,7 @@ function createRuntime(profile) {
|
||||
found = await discoverAwgContainer(candidate, profile.container);
|
||||
if (found) break;
|
||||
}
|
||||
if (profile.isDefault) defaultProfileMissing = !found;
|
||||
if (found) {
|
||||
resolvedContainer = found;
|
||||
if (found !== profile.container) {
|
||||
@@ -996,7 +995,7 @@ function createRuntime(profile) {
|
||||
const activeIface = ifaceFromConfPath(activeConfPath, iface);
|
||||
const activeBinary = await resolveWgBinary();
|
||||
await dockerExec(
|
||||
`wg-quick strip '${activeConfPath}' > /tmp/wg-admin-strip.conf && ${activeBinary} syncconf ${activeIface} /tmp/wg-admin-strip.conf`
|
||||
`(awg-quick strip '${activeConfPath}' 2>/dev/null || wg-quick strip '${activeConfPath}') > /tmp/wg-admin-strip.conf && ${activeBinary} syncconf ${activeIface} /tmp/wg-admin-strip.conf`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1186,26 +1185,45 @@ function defaultPeerClientName(peer) {
|
||||
return ip ? `Клиент ${ip}` : `Peer ${String(peer?.publicKey || "").slice(0, 10)}…`;
|
||||
}
|
||||
|
||||
/** Совпадает с defaults Amnezia Desktop (protocolConstants awg, desktop MTU). */
|
||||
const AWG_EXPORT_DEFAULTS = {
|
||||
Jc: "3",
|
||||
Jmin: "10",
|
||||
Jmax: "30",
|
||||
S1: "15",
|
||||
S2: "18",
|
||||
S3: "20",
|
||||
S4: "23",
|
||||
H1: "1020325451",
|
||||
H2: "3288052141",
|
||||
H3: "1766607858",
|
||||
H4: "2528465083",
|
||||
I1: "<r 2><b 0x858000010001000000000669636c6f756403636f6d0000010001c00c000100010000105a00044d583737>",
|
||||
I2: "",
|
||||
I3: "",
|
||||
I4: "",
|
||||
I5: "",
|
||||
|
||||
// Client-side obfuscation keys, in the order Amnezia writes them. 3.x keys must match the server.
|
||||
const AWG_OBF_KEYS = [
|
||||
"Jc", "Jmin", "Jmax", "S1", "S2", "S3", "S4", "H1", "H2", "H3", "H4", "I1", "I2", "I3", "I4", "I5",
|
||||
"HeaderProtectionKey", "ContentPaddingAddition", "RekeyAfterTime", "RekeyTimeout", "RejectAfterTime",
|
||||
"KeepaliveTimeout", "MaxHandshakeAttempts", "RandomTrailers", "DisableCookies",
|
||||
];
|
||||
const AWG_OBF_ALIASES = {
|
||||
Jc: ["junk_packet_count", "junkPacketCount"], Jmin: ["junk_packet_min_size", "junkPacketMinSize"],
|
||||
Jmax: ["junk_packet_max_size", "junkPacketMaxSize"], S1: ["init_packet_junk_size", "initPacketJunkSize"],
|
||||
S2: ["response_packet_junk_size", "responsePacketJunkSize"], S3: ["cookie_reply_packet_junk_size", "cookieReplyPacketJunkSize"],
|
||||
S4: ["transport_packet_junk_size", "transportPacketJunkSize"], H1: ["init_packet_magic_header", "initPacketMagicHeader"],
|
||||
H2: ["response_packet_magic_header", "responsePacketMagicHeader"], H3: ["underload_packet_magic_header", "underloadPacketMagicHeader"],
|
||||
H4: ["transport_packet_magic_header", "transportPacketMagicHeader"],
|
||||
I1: ["special_junk_1", "specialJunk1"], I2: ["special_junk_2", "specialJunk2"], I3: ["special_junk_3", "specialJunk3"],
|
||||
I4: ["special_junk_4", "specialJunk4"], I5: ["special_junk_5", "specialJunk5"],
|
||||
HeaderProtectionKey: ["header_protection_key"],
|
||||
};
|
||||
|
||||
/**
|
||||
* Obfuscation lines for a client .conf. The server [Interface] is the source of truth: a key the
|
||||
* server does not have (e.g. S3/S4 on AWG 1.x) must not appear in the client, otherwise the
|
||||
* handshake passes but data packets are dropped. Keys only in last_config (I1..I5 written by the
|
||||
* Amnezia app) are kept. Returns "" for plain WireGuard servers.
|
||||
*/
|
||||
function awgObfuscationLines(lc, ifaceMap) {
|
||||
if (!ifaceMap.Jc && !pickLc(lc, "Jc", "junk_packet_count", "junkPacketCount")) return "";
|
||||
const lines = [];
|
||||
for (const k of AWG_OBF_KEYS) {
|
||||
const isServerKey = !/^I\d$/.test(k);
|
||||
let v = isServerKey ? ifaceMap[k] : undefined;
|
||||
if (v == null || String(v).trim() === "") v = pickLc(lc, k, ...(AWG_OBF_ALIASES[k] || []));
|
||||
if (!isServerKey && (v == null || String(v).trim() === "")) v = ifaceMap[k];
|
||||
if (isServerKey && ifaceMap.Jc && (ifaceMap[k] == null || ifaceMap[k] === "")) v = undefined;
|
||||
if (v != null && String(v).trim() !== "") lines.push(`${k} = ${String(v).trim()}`);
|
||||
}
|
||||
return lines.length ? `${lines.join("\n")}\n` : "";
|
||||
}
|
||||
|
||||
function parseLastConfigFromClientRow(row) {
|
||||
const ud = row?.userData;
|
||||
if (!ud || typeof ud !== "object") return null;
|
||||
@@ -1490,8 +1508,28 @@ function tunnelClientIpv4(peer, lc, row) {
|
||||
);
|
||||
}
|
||||
|
||||
// Panel settings editable from the UI (domain for client Endpoint etc.).
|
||||
const SETTINGS_FILE = path.join(process.env.DATA_DIR || "/data", "settings.json");
|
||||
function loadPanelSettings() {
|
||||
try {
|
||||
const o = JSON.parse(fs.readFileSync(SETTINGS_FILE, "utf-8"));
|
||||
return o && typeof o === "object" ? o : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
function savePanelSettings(next) {
|
||||
fs.mkdirSync(path.dirname(SETTINGS_FILE), { recursive: true });
|
||||
fs.writeFileSync(SETTINGS_FILE, JSON.stringify(next, null, 2));
|
||||
}
|
||||
/** Domain/IP set in the UI wins over CLIENT_CONFIG_ENDPOINT (installer puts the raw IP there). */
|
||||
function configuredEndpointHost() {
|
||||
const ui = String(loadPanelSettings().endpointHost || "").trim();
|
||||
return ui || process.env.CLIENT_CONFIG_ENDPOINT?.trim() || "";
|
||||
}
|
||||
|
||||
function resolveExportEndpointHost(lc, req) {
|
||||
const env = process.env.CLIENT_CONFIG_ENDPOINT?.trim();
|
||||
const env = configuredEndpointHost();
|
||||
if (env) return env;
|
||||
const hn = pickLc(lc, "hostName", "hostname", "host");
|
||||
if (hn && String(hn).trim()) return String(hn).trim();
|
||||
@@ -1546,70 +1584,11 @@ async function buildClientConfExport(rt, lc, ifaceMap, req, row, conf) {
|
||||
const mtuVal = pickLc(lc, "mtu", "MTU");
|
||||
const mtuLine = mtuVal ? `MTU = ${String(mtuVal).trim()}\n` : "";
|
||||
|
||||
if (activeBinary === "awg") {
|
||||
const Jc = String(pickLc(lc, "Jc", "junk_packet_count", "junkPacketCount") ?? AWG_EXPORT_DEFAULTS.Jc);
|
||||
const Jmin = String(pickLc(lc, "Jmin", "junk_packet_min_size", "junkPacketMinSize") ?? AWG_EXPORT_DEFAULTS.Jmin);
|
||||
const Jmax = String(pickLc(lc, "Jmax", "junk_packet_max_size", "junkPacketMaxSize") ?? AWG_EXPORT_DEFAULTS.Jmax);
|
||||
const S1 = String(pickLc(lc, "S1", "init_packet_junk_size", "initPacketJunkSize") ?? AWG_EXPORT_DEFAULTS.S1);
|
||||
const S2 = String(pickLc(lc, "S2", "response_packet_junk_size", "responsePacketJunkSize") ?? AWG_EXPORT_DEFAULTS.S2);
|
||||
const S3 = String(
|
||||
pickLc(lc, "S3", "cookie_reply_packet_junk_size", "cookieReplyPacketJunkSize") ?? AWG_EXPORT_DEFAULTS.S3,
|
||||
);
|
||||
const S4 = String(
|
||||
pickLc(lc, "S4", "transport_packet_junk_size", "transportPacketJunkSize") ?? AWG_EXPORT_DEFAULTS.S4,
|
||||
);
|
||||
const H1 = String(pickLc(lc, "H1", "init_packet_magic_header", "initPacketMagicHeader") ?? AWG_EXPORT_DEFAULTS.H1);
|
||||
const H2 = String(
|
||||
pickLc(lc, "H2", "response_packet_magic_header", "responsePacketMagicHeader") ?? AWG_EXPORT_DEFAULTS.H2,
|
||||
);
|
||||
const H3 = String(
|
||||
pickLc(lc, "H3", "underload_packet_magic_header", "underloadPacketMagicHeader") ?? AWG_EXPORT_DEFAULTS.H3,
|
||||
);
|
||||
const H4 = String(
|
||||
pickLc(lc, "H4", "transport_packet_magic_header", "transportPacketMagicHeader") ?? AWG_EXPORT_DEFAULTS.H4,
|
||||
);
|
||||
const I1 = String(pickLc(lc, "I1", "special_junk_1", "specialJunk1") ?? AWG_EXPORT_DEFAULTS.I1);
|
||||
const I2 = String(pickLc(lc, "I2", "special_junk_2", "specialJunk2") ?? AWG_EXPORT_DEFAULTS.I2);
|
||||
const I3 = String(pickLc(lc, "I3", "special_junk_3", "specialJunk3") ?? AWG_EXPORT_DEFAULTS.I3);
|
||||
const I4 = String(pickLc(lc, "I4", "special_junk_4", "specialJunk4") ?? AWG_EXPORT_DEFAULTS.I4);
|
||||
const I5 = String(pickLc(lc, "I5", "special_junk_5", "specialJunk5") ?? AWG_EXPORT_DEFAULTS.I5);
|
||||
const iLines = [
|
||||
["I1", I1], ["I2", I2], ["I3", I3], ["I4", I4], ["I5", I5],
|
||||
]
|
||||
.filter(([, v]) => String(v ?? "").trim() !== "")
|
||||
.map(([k, v]) => `${k} = ${v}`)
|
||||
.join("\n");
|
||||
const iBlock = iLines ? `${iLines}\n` : "";
|
||||
|
||||
return `[Interface]
|
||||
Address = ${tunnelIp}/32
|
||||
DNS = ${dns1}, ${dns2}
|
||||
PrivateKey = ${priv.trim()}
|
||||
Jc = ${Jc}
|
||||
Jmin = ${Jmin}
|
||||
Jmax = ${Jmax}
|
||||
S1 = ${S1}
|
||||
S2 = ${S2}
|
||||
S3 = ${S3}
|
||||
S4 = ${S4}
|
||||
H1 = ${H1}
|
||||
H2 = ${H2}
|
||||
H3 = ${H3}
|
||||
H4 = ${H4}
|
||||
${iBlock}${mtuLine}[Peer]
|
||||
PublicKey = ${String(serverPub).trim()}
|
||||
PresharedKey = ${String(psk).trim()}
|
||||
AllowedIPs = ${peerAllowed}
|
||||
Endpoint = ${endpointHost}:${port}
|
||||
PersistentKeepalive = ${keepAlive}
|
||||
`;
|
||||
}
|
||||
|
||||
return `[Interface]
|
||||
Address = ${tunnelIp}/32
|
||||
DNS = ${dns1}, ${dns2}
|
||||
PrivateKey = ${priv.trim()}
|
||||
${mtuLine}[Peer]
|
||||
${awgObfuscationLines(lc, ifaceMap)}${mtuLine}[Peer]
|
||||
PublicKey = ${String(serverPub).trim()}
|
||||
PresharedKey = ${String(psk).trim()}
|
||||
AllowedIPs = ${peerAllowed}
|
||||
@@ -1652,7 +1631,7 @@ async function awgGenKeypair(rt) {
|
||||
}
|
||||
|
||||
function obfuscationFieldsFromServerHead(ifaceMap) {
|
||||
const keys = ["Jc", "Jmin", "Jmax", "S1", "S2", "S3", "S4", "H1", "H2", "H3", "H4", "I1", "I2", "I3", "I4", "I5"];
|
||||
const keys = AWG_OBF_KEYS;
|
||||
const out = {};
|
||||
for (const k of keys) {
|
||||
const v = ifaceMap[k];
|
||||
@@ -2080,9 +2059,6 @@ if (UI_HIDDEN.users || UI_HIDDEN.warp || UI_HIDDEN.cascade || UI_HIDDEN.mtproto)
|
||||
`UI_HIDDEN: users=${UI_HIDDEN.users} warp=${UI_HIDDEN.warp} cascade=${UI_HIDDEN.cascade} mtproto=${UI_HIDDEN.mtproto}`,
|
||||
);
|
||||
}
|
||||
if (IS_COMMUNITY) {
|
||||
console.warn(`Редакция community (только просмотр клиентов). PRO: ${COMMUNITY_UPGRADE_URL}`);
|
||||
}
|
||||
app.use(express.json({ limit: "2mb" }));
|
||||
|
||||
app.get("/health", (_req, res) => {
|
||||
@@ -2128,15 +2104,6 @@ app.get("/api/server-time", requireAuth, (req, res) => {
|
||||
});
|
||||
|
||||
app.get("/api/time-sync-capabilities", requireAuth, (_req, res) => {
|
||||
if (IS_COMMUNITY) {
|
||||
res.json({
|
||||
hostTimeSync: false,
|
||||
sshHost: process.env.TIME_SYNC_SSH_HOST?.trim() || "172.17.0.1",
|
||||
serverClockTimeZone: resolveServerClockTimeZone(),
|
||||
communityBlocked: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.json({
|
||||
hostTimeSync: hostTimeSyncConfigured(),
|
||||
sshHost: process.env.TIME_SYNC_SSH_HOST?.trim() || "172.17.0.1",
|
||||
@@ -2154,7 +2121,7 @@ function mtprotoLogsTailPayload(req) {
|
||||
}
|
||||
|
||||
app.get("/api/mtproto/status", requireAuth, (req, res) => {
|
||||
if (effectiveUiHidden().mtproto) {
|
||||
if (UI_HIDDEN.mtproto) {
|
||||
return res.status(403).json({ error: MSG_UI_MTProto_OFF });
|
||||
}
|
||||
const snap = mtprotoSnapshot(hostFromRequest(req));
|
||||
@@ -2170,21 +2137,21 @@ app.get("/api/mtproto/status", requireAuth, (req, res) => {
|
||||
});
|
||||
|
||||
app.get("/api/mtproto/logs", requireAuth, (req, res) => {
|
||||
if (effectiveUiHidden().mtproto) {
|
||||
if (UI_HIDDEN.mtproto) {
|
||||
return res.status(403).json({ error: MSG_UI_MTProto_OFF });
|
||||
}
|
||||
res.json(mtprotoLogsTailPayload(req));
|
||||
});
|
||||
|
||||
app.get("/api/mtproto/tail", requireAuth, (req, res) => {
|
||||
if (effectiveUiHidden().mtproto) {
|
||||
if (UI_HIDDEN.mtproto) {
|
||||
return res.status(403).json({ error: MSG_UI_MTProto_OFF });
|
||||
}
|
||||
res.json(mtprotoLogsTailPayload(req));
|
||||
});
|
||||
|
||||
app.post("/api/mtproto/install", requireAuth, (req, res) => {
|
||||
if (effectiveUiHidden().mtproto) {
|
||||
if (UI_HIDDEN.mtproto) {
|
||||
return res.status(403).json({ error: MSG_UI_MTProto_OFF });
|
||||
}
|
||||
if (!/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(MTPRO_CONTAINER)) {
|
||||
@@ -2280,7 +2247,7 @@ app.post("/api/mtproto/install", requireAuth, (req, res) => {
|
||||
});
|
||||
|
||||
app.post("/api/mtproto/remove", requireAuth, (_req, res) => {
|
||||
if (effectiveUiHidden().mtproto) {
|
||||
if (UI_HIDDEN.mtproto) {
|
||||
return res.status(403).json({ error: MSG_UI_MTProto_OFF });
|
||||
}
|
||||
const r = dockerSpawnSync(["rm", "-f", MTPRO_CONTAINER], 120_000);
|
||||
@@ -2294,7 +2261,7 @@ app.post("/api/mtproto/remove", requireAuth, (_req, res) => {
|
||||
});
|
||||
|
||||
app.post("/api/mtproto/restart", requireAuth, (_req, res) => {
|
||||
if (effectiveUiHidden().mtproto) {
|
||||
if (UI_HIDDEN.mtproto) {
|
||||
return res.status(403).json({ error: MSG_UI_MTProto_OFF });
|
||||
}
|
||||
const snap = mtprotoSnapshot();
|
||||
@@ -2309,7 +2276,7 @@ app.post("/api/mtproto/restart", requireAuth, (_req, res) => {
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.post("/api/sync-host-time", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/sync-host-time", requireAuth, async (req, res) => {
|
||||
if (!hostTimeSyncConfigured()) {
|
||||
return res.status(503).json({
|
||||
error:
|
||||
@@ -2341,7 +2308,7 @@ app.post("/api/sync-host-time", requireAuth, requireProTier, async (req, res) =>
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/warp/host-setup", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/warp/host-setup", requireAuth, async (req, res) => {
|
||||
if (UI_HIDDEN.warp) {
|
||||
return res.status(403).json({ error: MSG_UI_WARP_OFF });
|
||||
}
|
||||
@@ -2385,6 +2352,202 @@ app.post("/api/warp/host-setup", requireAuth, requireProTier, async (req, res) =
|
||||
}
|
||||
});
|
||||
|
||||
// ---------- Xray VLESS-Reality ----------
|
||||
// Layout matches the official Amnezia client (xray_*.key + clientsTable), so the app sees the same server.
|
||||
const XRAY_CONTAINER = "amnezia-xray";
|
||||
const XRAY_IMAGE = "amnezia-xray";
|
||||
const XRAY_DIR = "/opt/amnezia/xray";
|
||||
const XRAY_VERSION = "v26.3.27";
|
||||
const XRAY_DOCKERFILE = `FROM alpine:3.20
|
||||
RUN apk add --no-cache curl unzip bash openssl dumb-init && \\
|
||||
curl -fsSL -o /root/xray.zip https://github.com/XTLS/Xray-core/releases/download/${XRAY_VERSION}/Xray-linux-64.zip && \\
|
||||
unzip /root/xray.zip xray -d /usr/bin/ && chmod +x /usr/bin/xray && rm /root/xray.zip && mkdir -p ${XRAY_DIR}
|
||||
ENTRYPOINT ["dumb-init", "/usr/bin/xray", "-config", "${XRAY_DIR}/server.json"]
|
||||
`;
|
||||
|
||||
function xrayExec(script) {
|
||||
return dockerExecStdin(XRAY_CONTAINER, script);
|
||||
}
|
||||
function xrayShellQuote(s) {
|
||||
return `'${String(s).replace(/'/g, `'\\''`)}'`;
|
||||
}
|
||||
async function xrayReadFile(name) {
|
||||
try {
|
||||
return (await xrayExec(`cat ${XRAY_DIR}/${name} 2>/dev/null`)).stdout;
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
async function xrayWriteFile(name, text) {
|
||||
await execDocker(["exec", "-i", XRAY_CONTAINER, "sh", "-c", `cat > ${XRAY_DIR}/${name}`], text);
|
||||
}
|
||||
function xrayInspect() {
|
||||
const r = dockerSpawnSync(["inspect", "--format", "{{.State.Running}}", XRAY_CONTAINER], 15_000);
|
||||
return { installed: r.code === 0, running: r.stdout.trim() === "true" };
|
||||
}
|
||||
async function xrayState() {
|
||||
const server = JSON.parse((await xrayReadFile("server.json")) || "{}");
|
||||
const ib = (server.inbounds || []).find((i) => i.protocol === "vless");
|
||||
if (!ib) throw new Error("В server.json нет VLESS-входа.");
|
||||
let table = [];
|
||||
try {
|
||||
table = JSON.parse((await xrayReadFile("clientsTable")) || "[]");
|
||||
} catch {}
|
||||
if (!Array.isArray(table)) table = [];
|
||||
return {
|
||||
server,
|
||||
ib,
|
||||
table,
|
||||
pub: (await xrayReadFile("xray_public.key")).trim(),
|
||||
shortId: (await xrayReadFile("xray_short_id.key")).trim() || ib.streamSettings?.realitySettings?.shortIds?.[0] || "",
|
||||
};
|
||||
}
|
||||
async function xraySave(st) {
|
||||
// Enabled = present in server.json; disabled clients live only in clientsTable.
|
||||
st.ib.settings.clients = st.table
|
||||
.filter((r) => !r.userData?.disabled)
|
||||
.map((r) => ({ id: r.clientId, flow: "xtls-rprx-vision" }));
|
||||
await xrayWriteFile("server.json", JSON.stringify(st.server, null, 2));
|
||||
await xrayWriteFile("clientsTable", JSON.stringify(st.table, null, 2));
|
||||
await execDocker(["restart", XRAY_CONTAINER]);
|
||||
}
|
||||
function xrayLink(st, row, host) {
|
||||
const rs = st.ib.streamSettings.realitySettings;
|
||||
const q = new URLSearchParams({
|
||||
type: "tcp",
|
||||
security: "reality",
|
||||
pbk: st.pub,
|
||||
fp: "chrome",
|
||||
sni: rs.serverNames[0],
|
||||
sid: st.shortId,
|
||||
spx: "/",
|
||||
flow: "xtls-rprx-vision",
|
||||
encryption: "none",
|
||||
});
|
||||
const name = encodeURIComponent(row.userData?.clientName || "client");
|
||||
return `vless://${row.clientId}@${host}:${st.ib.port}?${q}#${name}`;
|
||||
}
|
||||
function xrayHost(req) {
|
||||
return configuredEndpointHost() || hostFromRequest(req) || "SERVER_IP";
|
||||
}
|
||||
|
||||
app.get("/api/xray/status", requireAuth, async (req, res) => {
|
||||
const s = xrayInspect();
|
||||
if (!s.running) return res.json({ ...s, clients: [] });
|
||||
try {
|
||||
const st = await xrayState();
|
||||
const host = xrayHost(req);
|
||||
res.json({
|
||||
...s,
|
||||
port: st.ib.port,
|
||||
sni: st.ib.streamSettings?.realitySettings?.serverNames?.[0] || "",
|
||||
clients: st.table.map((r) => ({
|
||||
id: r.clientId,
|
||||
name: r.userData?.clientName || r.clientId,
|
||||
enabled: !r.userData?.disabled,
|
||||
created: r.userData?.creationDate || "",
|
||||
link: xrayLink(st, r, host),
|
||||
})),
|
||||
});
|
||||
} catch (e) {
|
||||
res.json({ ...s, clients: [], error: String(e.message || e) });
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/xray/install", requireAuth, async (req, res) => {
|
||||
const port = Number.parseInt(String(req.body?.port || "443"), 10);
|
||||
const sni = String(req.body?.sni || "www.google.com").trim();
|
||||
if (!(port > 0 && port < 65536)) return res.status(400).json({ error: "Неверный порт." });
|
||||
if (!/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(sni)) return res.status(400).json({ error: "Неверный сайт-маскировка (SNI)." });
|
||||
if (xrayInspect().installed) return res.status(409).json({ error: "Xray уже установлен. Сначала удалите его." });
|
||||
const busy = dockerSpawnSync(["ps", "--format", "{{.Names}} {{.Ports}}"], 15_000).stdout
|
||||
.split("\n")
|
||||
.find((l) => new RegExp(`:${port}->\\d+/tcp`).test(l));
|
||||
if (busy) return res.status(409).json({ error: `TCP-порт ${port} занят: ${busy.split(" ")[0]}` });
|
||||
try {
|
||||
await execDocker(["build", "-t", XRAY_IMAGE, "-"], XRAY_DOCKERFILE);
|
||||
const kp = (await execDocker(["run", "--rm", "--entrypoint", "/usr/bin/xray", XRAY_IMAGE, "x25519"])).stdout;
|
||||
const priv = (kp.match(/Private\s*key:\s*(\S+)/i) || kp.match(/PrivateKey:\s*(\S+)/i) || [])[1];
|
||||
const pub = (kp.match(/(?:Public\s*key|Password)[^:\n]*:\s*(\S+)/i) || [])[1];
|
||||
if (!priv || !pub) throw new Error(`Не удалось получить ключи x25519: ${kp}`);
|
||||
const shortId = crypto.randomBytes(8).toString("hex");
|
||||
const server = {
|
||||
log: { loglevel: "error" },
|
||||
inbounds: [
|
||||
{
|
||||
port,
|
||||
protocol: "vless",
|
||||
settings: { clients: [], decryption: "none" },
|
||||
streamSettings: {
|
||||
network: "tcp",
|
||||
security: "reality",
|
||||
realitySettings: { dest: `${sni}:443`, serverNames: [sni], privateKey: priv, shortIds: [shortId] },
|
||||
},
|
||||
},
|
||||
],
|
||||
outbounds: [{ protocol: "freedom" }],
|
||||
};
|
||||
const files = {
|
||||
"server.json": JSON.stringify(server, null, 2),
|
||||
"xray_private.key": `${priv}\n`,
|
||||
"xray_public.key": `${pub}\n`,
|
||||
"xray_short_id.key": `${shortId}\n`,
|
||||
"xray_uuid.key": "\n",
|
||||
clientsTable: "[]",
|
||||
};
|
||||
const script = ["set -e", `mkdir -p /x`]
|
||||
.concat(Object.entries(files).map(([n, t]) => `printf '%s' ${xrayShellQuote(t)} > /x/${n}`))
|
||||
.join("\n");
|
||||
await execDocker(["run", "--rm", "-i", "-v", `${XRAY_DIR}:/x`, "--entrypoint", "sh", XRAY_IMAGE, "-s"], script);
|
||||
await execDocker([
|
||||
"run", "-d", "--restart", "always", "--name", XRAY_CONTAINER,
|
||||
"-p", `${port}:${port}/tcp`, "-v", `${XRAY_DIR}:${XRAY_DIR}`, XRAY_IMAGE,
|
||||
]);
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
res.status(500).json({ error: String(e.message || e) });
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/xray/remove", requireAuth, async (_req, res) => {
|
||||
dockerSpawnSync(["rm", "-f", XRAY_CONTAINER], 60_000);
|
||||
// ponytail: keys and clientsTable stay in /opt/amnezia/xray on the host; a reinstall regenerates them.
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.post("/api/xray/clients/create", requireAuth, async (req, res) => {
|
||||
const name = String(req.body?.name || "").trim().slice(0, 64);
|
||||
if (!name) return res.status(400).json({ error: "Укажите имя клиента." });
|
||||
try {
|
||||
const st = await xrayState();
|
||||
const row = { clientId: crypto.randomUUID(), userData: { clientName: name, creationDate: new Date().toString() } };
|
||||
st.table.push(row);
|
||||
await xraySave(st);
|
||||
res.json({ ok: true, link: xrayLink(st, row, xrayHost(req)) });
|
||||
} catch (e) {
|
||||
res.status(500).json({ error: String(e.message || e) });
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/xray/clients/update", requireAuth, async (req, res) => {
|
||||
const id = String(req.body?.id || "");
|
||||
const action = String(req.body?.action || "");
|
||||
try {
|
||||
const st = await xrayState();
|
||||
const row = st.table.find((r) => r.clientId === id);
|
||||
if (!row) return res.status(404).json({ error: "Клиент не найден." });
|
||||
if (action === "delete") st.table = st.table.filter((r) => r !== row);
|
||||
else if (action === "enable" || action === "disable") {
|
||||
row.userData = { ...row.userData, disabled: action === "disable" };
|
||||
if (!row.userData.disabled) delete row.userData.disabled;
|
||||
} else return res.status(400).json({ error: "Неизвестное действие." });
|
||||
await xraySave(st);
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
res.status(500).json({ error: String(e.message || e) });
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/login", (req, res) => {
|
||||
const pw = req.body?.password;
|
||||
if (typeof pw !== "string" || !pw) {
|
||||
@@ -2427,13 +2590,45 @@ app.post("/api/change-password", requireAuth, (req, res) => {
|
||||
res.json({ ok: true, message: "Пароль изменён. Войдите снова." });
|
||||
});
|
||||
|
||||
app.get("/api/settings", requireAuth, (_req, res) => {
|
||||
const st = loadPanelSettings();
|
||||
res.json({
|
||||
endpointHost: st.endpointHost || "",
|
||||
envEndpoint: process.env.CLIENT_CONFIG_ENDPOINT?.trim() || "",
|
||||
effectiveEndpoint: configuredEndpointHost(),
|
||||
});
|
||||
});
|
||||
|
||||
app.post("/api/settings", requireAuth, async (req, res) => {
|
||||
const raw = String(req.body?.endpointHost ?? "").trim();
|
||||
let host = "";
|
||||
if (raw) {
|
||||
try {
|
||||
host = assertCascadeEndpointHost(raw);
|
||||
} catch (e) {
|
||||
return res.status(400).json({ error: String(e.message || e) });
|
||||
}
|
||||
if (!/^[A-Za-z0-9.-]+$/.test(host) && !/^[0-9a-fA-F:]+$/.test(host)) {
|
||||
return res.status(400).json({ error: "Домен или IP: только латиница, цифры, точки и дефисы." });
|
||||
}
|
||||
}
|
||||
let resolved = null;
|
||||
if (host && !/^[\d.]+$/.test(host) && host.includes(".")) {
|
||||
try {
|
||||
resolved = (await dns.promises.lookup(host, { all: true })).map((a) => a.address);
|
||||
} catch {
|
||||
return res.status(400).json({ error: `Домен ${host} не резолвится. Создайте A-запись на IP этого сервера и повторите.` });
|
||||
}
|
||||
}
|
||||
savePanelSettings({ ...loadPanelSettings(), endpointHost: host });
|
||||
res.json({ ok: true, endpointHost: host, resolved });
|
||||
});
|
||||
|
||||
app.get("/api/protocols", requireAuth, (req, res) => {
|
||||
const rt = runtimeForRequest(req);
|
||||
const hintSingle =
|
||||
getProfiles().length < 2
|
||||
? IS_COMMUNITY
|
||||
? "Один инстанс в интерфейсе. Несколько контейнеров и профиль AWG_PROFILES — в полной панели PRO."
|
||||
: "Сейчас один инстанс: при установке не передали AWG_PROFILES или не восстановился снимок. Задайте JSON профилей и запустите install.sh — он сохранится в /root/amnezia-admin.awg-profiles.json."
|
||||
? "Сейчас один инстанс: при установке не передали AWG_PROFILES или не восстановился снимок. Задайте JSON профилей и запустите install.sh — он сохранится в /root/amnezia-admin.awg-profiles.json."
|
||||
: "";
|
||||
res.json({
|
||||
currentId: rt.profile.id,
|
||||
@@ -2445,7 +2640,6 @@ app.get("/api/protocols", requireAuth, (req, res) => {
|
||||
})),
|
||||
singleProfile: getProfiles().length < 2,
|
||||
profilesPersistHint: hintSingle,
|
||||
edition: editionPayload(),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2555,8 +2749,7 @@ app.get("/api/clients", requireAuth, async (req, res) => {
|
||||
clients: rows,
|
||||
wgShow,
|
||||
warp: warpOut,
|
||||
uiHidden: { ...effectiveUiHidden() },
|
||||
edition: editionPayload(),
|
||||
uiHidden: { ...UI_HIDDEN },
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
@@ -2564,7 +2757,7 @@ app.get("/api/clients", requireAuth, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/clients/sync-peers", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/clients/sync-peers", requireAuth, async (req, res) => {
|
||||
const rt = runtimeFromExportRequest(req);
|
||||
try {
|
||||
await rt.backupRemoteFiles();
|
||||
@@ -2658,14 +2851,6 @@ app.get("/api/clients/source-report", requireAuth, async (req, res) => {
|
||||
});
|
||||
|
||||
async function serveClientConfigExport(req, res) {
|
||||
if (IS_COMMUNITY) {
|
||||
res.status(403).json({
|
||||
error: "Экспорт .conf доступен в версии PRO.",
|
||||
upgradeRequired: true,
|
||||
upgradeUrl: COMMUNITY_UPGRADE_URL,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const tokenOk =
|
||||
req.method === "GET" &&
|
||||
verifyExportQueryToken(typeof req.query.token === "string" ? req.query.token : "");
|
||||
@@ -2745,7 +2930,7 @@ app.post("/api/clients/export-config", requireAuth, (req, res) => {
|
||||
* Новый клиент для каскада: генерирует ключи, добавляет peer на сервер, сохраняет last_config,
|
||||
* отдаёт .conf с Endpoint = endpointHost:endpointPort (ваш промежуточный узел).
|
||||
*/
|
||||
app.post("/api/clients/create", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/clients/create", requireAuth, async (req, res) => {
|
||||
const rt = runtimeFromExportRequest(req);
|
||||
try {
|
||||
await rt.backupRemoteFiles();
|
||||
@@ -2757,7 +2942,7 @@ app.post("/api/clients/create", requireAuth, requireProTier, async (req, res) =>
|
||||
}
|
||||
const tunnelIp = normalizeCascadeTunnelIp(conf, ifaceMap, req.body?.tunnelIp);
|
||||
const listenPort = ifaceMap.ListenPort ? Number(ifaceMap.ListenPort) : NaN;
|
||||
const envHost = process.env.CLIENT_CONFIG_ENDPOINT?.trim();
|
||||
const envHost = configuredEndpointHost();
|
||||
const hdrHost =
|
||||
typeof req.headers.host === "string" ? req.headers.host.split(":")[0].trim() : "";
|
||||
const endpointHost = envHost || (hdrHost && hdrHost !== "localhost" ? hdrHost : "");
|
||||
@@ -2838,7 +3023,7 @@ AllowedIPs = ${tunnelIp}/32
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/clients/create-cascade", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/clients/create-cascade", requireAuth, async (req, res) => {
|
||||
if (UI_HIDDEN.cascade) {
|
||||
return res.status(403).json({ error: MSG_UI_CASCADE_OFF });
|
||||
}
|
||||
@@ -2954,7 +3139,7 @@ AllowedIPs = ${tunnelIp}/32
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/clients/import-config", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/clients/import-config", requireAuth, async (req, res) => {
|
||||
const rt = runtimeFromExportRequest(req);
|
||||
try {
|
||||
const raw = req.body?.configText ?? req.body?.backupText ?? req.body?.text ?? "";
|
||||
@@ -2980,7 +3165,7 @@ app.post("/api/clients/import-config", requireAuth, requireProTier, async (req,
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/warp/start", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/warp/start", requireAuth, async (req, res) => {
|
||||
if (UI_HIDDEN.warp) {
|
||||
return res.status(403).json({ error: MSG_UI_WARP_OFF });
|
||||
}
|
||||
@@ -2992,8 +3177,8 @@ app.post("/api/warp/start", requireAuth, requireProTier, async (req, res) => {
|
||||
});
|
||||
}
|
||||
try {
|
||||
await rt.dockerExec(`wg-quick down '${rt.profile.warpConf}' 2>/dev/null || true`);
|
||||
await rt.dockerExec(`wg-quick up '${rt.profile.warpConf}'`);
|
||||
await rt.dockerExec(`${QUICK_SH} down '${rt.profile.warpConf}' 2>/dev/null || true`);
|
||||
await rt.dockerExec(`${QUICK_SH} up '${rt.profile.warpConf}'`);
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
@@ -3001,7 +3186,32 @@ app.post("/api/warp/start", requireAuth, requireProTier, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/warp/stop", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/cascade/upstream", requireAuth, async (req, res) => {
|
||||
if (UI_HIDDEN.warp || UI_HIDDEN.cascade) {
|
||||
return res.status(403).json({ error: MSG_UI_CASCADE_OFF });
|
||||
}
|
||||
const rt = runtimeForRequest(req);
|
||||
try {
|
||||
const conf = buildUpstreamConf(String(req.body?.configText || ""));
|
||||
await rt.backupRemoteFiles();
|
||||
await rt.dockerExec(`mkdir -p '${rt.profile.warpDir}'`);
|
||||
await rt.dockerExec(`${QUICK_SH} down '${rt.profile.warpConf}' 2>/dev/null || true`);
|
||||
await rt.dockerWriteFile(rt.profile.warpConf, conf);
|
||||
await rt.dockerExec(`chmod 600 '${rt.profile.warpConf}'`);
|
||||
const up = await rt.dockerExec(`${QUICK_SH} up '${rt.profile.warpConf}' 2>&1`);
|
||||
const selected = await warpLoadSelectedIps(rt);
|
||||
await warpApplyRouting(rt, selected);
|
||||
await warpPatchStartSh(rt, selected);
|
||||
await new Promise((r) => setTimeout(r, 3000));
|
||||
const show = await rt.dockerExec("awg show warp 2>/dev/null || wg show warp 2>/dev/null || true");
|
||||
res.json({ ok: true, handshake: /latest handshake/.test(show), show: show.slice(0, 2000), output: up.slice(-1500) });
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
res.status(400).json({ error: String(e.message || e).slice(0, 1500) });
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/warp/stop", requireAuth, async (req, res) => {
|
||||
if (UI_HIDDEN.warp) {
|
||||
return res.status(403).json({ error: MSG_UI_WARP_OFF });
|
||||
}
|
||||
@@ -3010,7 +3220,7 @@ app.post("/api/warp/stop", requireAuth, requireProTier, async (req, res) => {
|
||||
return res.status(400).json({ error: "WARP не установлен." });
|
||||
}
|
||||
try {
|
||||
await rt.dockerExec(`wg-quick down '${rt.profile.warpConf}' 2>/dev/null || true`);
|
||||
await rt.dockerExec(`${QUICK_SH} down '${rt.profile.warpConf}' 2>/dev/null || true`);
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
@@ -3018,7 +3228,7 @@ app.post("/api/warp/stop", requireAuth, requireProTier, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/warp/routing", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/warp/routing", requireAuth, async (req, res) => {
|
||||
if (UI_HIDDEN.warp) {
|
||||
return res.status(403).json({ error: MSG_UI_WARP_OFF });
|
||||
}
|
||||
@@ -3057,7 +3267,7 @@ app.post("/api/warp/routing", requireAuth, requireProTier, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/clients/disable", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/clients/disable", requireAuth, async (req, res) => {
|
||||
const rt = runtimeFromExportRequest(req);
|
||||
const clientId = req.body?.clientId;
|
||||
if (!clientId) return res.status(400).json({ error: "clientId required" });
|
||||
@@ -3080,7 +3290,7 @@ app.post("/api/clients/disable", requireAuth, requireProTier, async (req, res) =
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/clients/enable", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/clients/enable", requireAuth, async (req, res) => {
|
||||
const rt = runtimeFromExportRequest(req);
|
||||
const clientId = req.body?.clientId;
|
||||
if (!clientId) return res.status(400).json({ error: "clientId required" });
|
||||
@@ -3130,7 +3340,7 @@ AllowedIPs = ${ips}`;
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/clients/disconnect-date", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/clients/disconnect-date", requireAuth, async (req, res) => {
|
||||
const rt = runtimeFromExportRequest(req);
|
||||
const clientId = req.body?.clientId;
|
||||
if (!clientId) return res.status(400).json({ error: "clientId required" });
|
||||
@@ -3174,7 +3384,7 @@ app.post("/api/clients/disconnect-date", requireAuth, requireProTier, async (req
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/clients/rename", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/clients/rename", requireAuth, async (req, res) => {
|
||||
const rt = runtimeFromExportRequest(req);
|
||||
const clientId = req.body?.clientId;
|
||||
const rawName = req.body?.name ?? req.body?.clientName;
|
||||
@@ -3206,7 +3416,7 @@ app.post("/api/clients/rename", requireAuth, requireProTier, async (req, res) =>
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/clients/delete", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/clients/delete", requireAuth, async (req, res) => {
|
||||
const rt = runtimeFromExportRequest(req);
|
||||
const clientId = req.body?.clientId;
|
||||
if (!clientId) return res.status(400).json({ error: "clientId required" });
|
||||
@@ -3261,6 +3471,8 @@ function runInstanceScript(args) {
|
||||
}
|
||||
|
||||
function detectVariantFromHead(head, iface) {
|
||||
if (/^RandomTrailers\s*=/m.test(head)) return "awg31";
|
||||
if (/^HeaderProtectionKey\s*=/m.test(head)) return "awg3";
|
||||
if (iface === "wg0" || !/^S1\s*=/m.test(head)) return "legacy";
|
||||
if (/^S3\s*=/m.test(head) || /^S4\s*=/m.test(head)) return "awg2";
|
||||
return "awg";
|
||||
@@ -3269,6 +3481,8 @@ function detectVariantFromHead(head, iface) {
|
||||
function inferVariantFromProfile(prof) {
|
||||
const raw = `${prof.variant || ""} ${prof.id || ""} ${prof.container || ""} ${prof.label || ""}`.toLowerCase();
|
||||
if (raw.includes("legacy") || prof.iface === "wg0") return "legacy";
|
||||
if (raw.includes("awg31") || raw.includes("3.1")) return "awg31";
|
||||
if (raw.includes("awg3") || raw.includes("3.0")) return "awg3";
|
||||
if (raw.includes("awg2") || raw.includes("2.0")) return "awg2";
|
||||
return "awg";
|
||||
}
|
||||
@@ -3318,7 +3532,7 @@ app.get("/api/instances", requireAuth, async (_req, res) => {
|
||||
res.json({ instances: items, variants: INSTANCE_VARIANTS });
|
||||
});
|
||||
|
||||
app.post("/api/instances/create", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/instances/create", requireAuth, async (req, res) => {
|
||||
const variant = String(req.body?.variant || "").trim();
|
||||
const port = Number(req.body?.port);
|
||||
if (!INSTANCE_VARIANTS[variant]) return res.status(400).json({ error: "Неизвестный вариант протокола." });
|
||||
@@ -3348,7 +3562,7 @@ app.post("/api/instances/create", requireAuth, requireProTier, async (req, res)
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/api/instances/delete", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/instances/delete", requireAuth, async (req, res) => {
|
||||
const id = String(req.body?.id || "").trim();
|
||||
const list = loadManagedProfiles();
|
||||
const found = list.find((p) => p.id === id);
|
||||
@@ -3369,7 +3583,7 @@ async function resolveProfileContainer(id) {
|
||||
catch { return prof.container || null; }
|
||||
}
|
||||
|
||||
app.post("/api/instances/stop", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/instances/stop", requireAuth, async (req, res) => {
|
||||
const id = String(req.body?.id || "").trim();
|
||||
const container = await resolveProfileContainer(id);
|
||||
if (!container) return res.status(404).json({ error: "Инстанс не найден." });
|
||||
@@ -3377,7 +3591,7 @@ app.post("/api/instances/stop", requireAuth, requireProTier, async (req, res) =>
|
||||
catch (e) { res.status(500).json({ error: String(e.message || e) }); }
|
||||
});
|
||||
|
||||
app.post("/api/instances/start", requireAuth, requireProTier, async (req, res) => {
|
||||
app.post("/api/instances/start", requireAuth, async (req, res) => {
|
||||
const id = String(req.body?.id || "").trim();
|
||||
const container = await resolveProfileContainer(id);
|
||||
if (!container) return res.status(404).json({ error: "Инстанс не найден." });
|
||||
@@ -3404,13 +3618,9 @@ app.listen(PORT, "0.0.0.0", () => {
|
||||
});
|
||||
|
||||
setInterval(() => {
|
||||
if (!IS_COMMUNITY) {
|
||||
processAllScheduledDisconnects().catch((e) => console.error("scheduleDisconnect:", e));
|
||||
}
|
||||
}, SCHEDULER_MS);
|
||||
|
||||
setTimeout(() => {
|
||||
if (!IS_COMMUNITY) {
|
||||
processAllScheduledDisconnects().catch((e) => console.error("scheduleDisconnect:", e));
|
||||
}
|
||||
}, 4000);
|
||||
|
||||
Reference in New Issue
Block a user