Add reCAPTCHA v3 and bump panel to v110

This commit is contained in:
kzolotarev95 committed 2026-10-07 15:05:31 +04:00
1 parent 5414eb6c4f
commit 9aa6b9daf9
10 files changed
+966 -53

No files matched your search

+2 -2
View File
@@ -314,7 +314,7 @@ render_page() {
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="owrt-remote-ui-version" content="$OWRT_REMOTE_UI_VERSION">
<title>OpenWrt Remote Hub v109</title>
<title>OpenWrt Remote Hub v110</title>
<style>
:root{color-scheme:dark;--bg:#07040f;--panel:rgba(19,14,32,.88);--text:#f7f2ff;--muted:#b9adc9;--line:rgba(169,126,255,.24);--blue:#7c3aed;--green:#22c55e;--red:#fb7185;--amber:#f59e0b;--teal:#a855f7;--grid:rgba(168,85,247,.16)}
*{box-sizing:border-box}body{position:relative;min-height:100vh;margin:0;overflow-x:hidden;background-color:var(--bg);background-image:radial-gradient(circle at 12% 8%,rgba(168,85,247,.46),transparent 31%),radial-gradient(circle at 82% 12%,rgba(79,70,229,.38),transparent 30%),radial-gradient(circle at 50% 105%,rgba(236,72,153,.26),transparent 35%),linear-gradient(145deg,#07040f,#120a24 48%,#05030a),repeating-linear-gradient(0deg,transparent 0 30px,var(--grid) 31px),repeating-linear-gradient(90deg,transparent 0 30px,var(--grid) 31px);background-size:130% 130%,140% 140%,135% 135%,100% 100%,31px 31px,31px 31px;background-attachment:fixed;color:var(--text);font:14px/1.45 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;animation:bgFlow 22s ease-in-out infinite alternate}
@@ -344,7 +344,7 @@ form{margin:0}.formgrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr
<div class="brand">
<div class="brandPanel">
<div class="titleRow">
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v109</span></span></h1>
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v110</span></span></h1>
</div>
<div class="links">
<a class="uiPill" href="https://t.me/kzolotarev95" target="_blank" rel="noopener noreferrer">Telegram</a>
@@ -14,7 +14,7 @@ return view.extend({
if (!key) {
return E('div', { 'class': 'cbi-map' }, [
E('h2', {}, _('OpenWrt Remote Hub v109')),
E('h2', {}, _('OpenWrt Remote Hub v110')),
E('div', { 'class': 'alert-message warning' }, [
_('Web key not found. Reinstall the module or create /etc/owrt-remote/web.key.')
])
@@ -34,7 +34,7 @@ return view.extend({
}, 100);
return E('div', { 'class': 'cbi-map' }, [
E('h2', {}, _('OpenWrt Remote Hub v109')),
E('h2', {}, _('OpenWrt Remote Hub v110')),
E('p', {}, _('Opening remote access panel...')),
E('p', {}, [
E('a', { 'class': 'btn cbi-button cbi-button-apply', 'href': url }, _('Open panel'))
+82
View File
@@ -0,0 +1,82 @@
# reCAPTCHA v3 в OpenWrt Remote Hub v110
В меню владельца, в блоке «Капча на экране входа», доступны цифры,
Google reCAPTCHA v2 Checkbox и Google reCAPTCHA v3. Установка обновления
сохраняет текущий режим и ключи. Для включения v3 выберите этот режим,
введите Site Key и Secret Key для **v3** и домена панели, затем сохраните
настройки с текущим паролем Hub.
При смене режима поля ключей очищаются. Для цифровой капчи они скрыты,
а после сохранения ключи удаляются из настроек на сервере. Для v2/v3
нужно ввести ключи выбранной версии; сервер не подставляет ключи другой
версии и отклоняет сохранение Google reCAPTCHA с пустыми ключами.
Удалённый текст полей больше не восстанавливается из-за обработки пустых
значений формы. Простое обновление формы сохраняет несохранённый ввод.
Порог оценки по умолчанию — 0.5, его можно изменить от 0 до 1.
Сервер отклоняет ответ с недостаточной оценкой, неверным доменом,
действием, отличным от `login`, отсутствующим или некорректным score.
Пароль и настроенная 2FA проверяются после капчи. При недоступности
Google вход по паролю показывает ошибку; другие способы входа остаются
доступны. Secret Key не попадает на публичную страницу входа.
Токен получается при отправке формы, а не при загрузке страницы.
Повторная попытка получает новый токен; повторный клик во время запроса
не отправляет второй вход. При ошибке или недоступности Google кнопка
снова становится доступной. На загрузку/ответ Google в браузере отведено
12 секунд, затем на запрос входа — 20 секунд.
Интеграция следует [документации Google v3](https://developers.google.com/recaptcha/docs/v3)
и [проверке токенов](https://developers.google.com/recaptcha/docs/verify).
Ключи v3 регистрируются в [консоли reCAPTCHA](https://www.google.com/recaptcha/admin/create).
Стандартный Google badge не скрывается.
## Проверки
```powershell
python -m unittest discover -s tests -v
python tests/test_recaptcha.py --export-js .test-output/recaptcha
node --check .test-output/recaptcha/login.js
node --check .test-output/recaptcha/dashboard.js
node tests/test_recaptcha_login.cjs .test-output/recaptcha/login.js
```
Python проверяет настройки, проверки ответа Google, совместимость v2/цифр,
отсутствие Secret Key в странице входа и настоящий HTTP `/login`
с разрешением/отказом до создания сессии. Ответы Google подменены;
настоящие ключи не нужны. Node проверяет получение свежего токена,
повторный вход, ошибки, timeout, двойной клик и сохранение настроек.
Реальную выдачу токена Google нужно проверить на домене VPS с ключами v3.
## Установка локальных изменений и откат
Из PowerShell Windows 11, находясь в корне репозитория:
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-recaptcha-v3.ps1" -Vps "root@YOUR_VPS_IP" -Action Install
```
Скрипт загружает локальный Python файл и тесты, проверяет их до замены
рабочего файла, сохраняет резервную копию, перезапускает `owrt-remote`
и проверяет health. База роутеров не заменяется. Установка не меняет
режим капчи: после неё v3 включается через настройки панели.
Откат при необходимости:
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-recaptcha-v3.ps1" -Vps "root@YOUR_VPS_IP" -Action Rollback
```
Откат восстанавливает Python файл и **только настройки капчи**, сохраняя
актуальный пароль, пользователей и другие параметры авторизации.
Это позволяет вернуть v2 вместе с прежними ключами после тестирования v3.
При неудачном запуске после установки/отката возвращается состояние
непосредственно перед попыткой. Резервные копии при повторном запуске
не перезаписываются:
* `/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v110`
* `/opt/owrt-remote/captcha-before-recaptcha-v3-v110.json` (режим 0600).
Скрипт рассчитан на стандартные пути установленного Hub:
`/opt/owrt-remote/owrt-remote-hub.py`, `/var/lib/owrt-remote/hub-auth.json`
и health на `http://127.0.0.1:8088/health`.
+3 -3
View File
@@ -1,6 +1,6 @@
# Аудит ресурсов OpenWrt Remote Hub v109
# Аудит ресурсов OpenWrt Remote Hub v110
Исправления внесены поверх `7f809fd`. Версия панели остаётся v109.
Исправления внесены поверх `7f809fd`. Версия панели остаётся v110.
## SQLite
@@ -115,7 +115,7 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-resource-fix
Установщик загружает локальный файл без Git, запускает изолированные тесты,
сохраняет исходный серверный файл:
`/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v109`,
`/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v110`,
атомарно заменяет Python файл, перезапускает `owrt-remote` и проверяет health.
Существующая резервная копия не перезаписывается. При ошибке установки
восстанавливается файл, работавший непосредственно перед текущей попыткой.
+278
View File
@@ -0,0 +1,278 @@
"""Login/settings regression tests. Google responses are mocked; no real keys.
Run: python -m unittest discover -s tests -v
The deployment helper can load a staged hub via OWRT_RECAPTCHA_HUB_SOURCE.
"""
import importlib.util
import json
import os
from pathlib import Path
import re
import sys
import tempfile
import threading
import unittest
import urllib.error
import urllib.request
from unittest import mock
SOURCE = Path(os.environ.get("OWRT_RECAPTCHA_HUB_SOURCE", Path(__file__).resolve().parents[1] / "vps" / "owrt-remote-hub.py"))
STATE = tempfile.TemporaryDirectory(prefix="owrt-recaptcha-tests-")
spec = importlib.util.spec_from_file_location("recaptcha_test_hub", SOURCE)
hub = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = hub
with mock.patch.dict(os.environ, {"OWRT_REMOTE_STATE_DIR": STATE.name}):
spec.loader.exec_module(hub)
def configured_auth(mode=hub.CAPTCHA_MODE_RECAPTCHA_V3, score=0.5):
return hub.normalize_auth_state({
"username": "test-owner",
"captcha": {"mode": mode, "site_key": "test-site", "secret_key": "test-secret", "min_score": score},
})
class RecaptchaTests(unittest.TestCase):
def verify(self, result, **kwargs):
with mock.patch.object(hub, "oauth_fetch_json", return_value=result) as google:
answer = hub.verify_recaptcha_token("test-secret", "test-token", expected_hostname="hub.example", expected_action="login", **kwargs)
return answer, google
def test_modes_and_old_v2_settings_are_preserved(self):
self.assertEqual(hub.sanitize_captcha_mode("recaptcha"), hub.CAPTCHA_MODE_RECAPTCHA)
self.assertEqual(hub.sanitize_captcha_mode("recaptcha_v3"), hub.CAPTCHA_MODE_RECAPTCHA_V3)
self.assertEqual(hub.sanitize_captcha_mode("unknown"), hub.CAPTCHA_MODE_DIGITS)
old = hub.sanitize_captcha_state({"mode": "recaptcha", "site_key": "old-site", "secret_key": "old-secret"})
self.assertEqual(old["mode"], "recaptcha")
self.assertEqual(old["min_score"], 0.5)
self.assertEqual(hub.effective_captcha_state({"captcha": {"mode": "recaptcha_v3"}})["effective_mode"], "digits")
def test_invalid_thresholds_are_rejected(self):
for value in (True, None, "", "nan", "inf", -0.1, 1.1):
with self.subTest(value=value), self.assertRaises(ValueError):
hub.parse_recaptcha_score(value)
self.assertEqual(hub.parse_recaptcha_score("0"), 0)
self.assertEqual(hub.parse_recaptcha_score("1"), 1)
self.assertEqual(hub.sanitize_captcha_state({"min_score": "nan"})["min_score"], 0.5)
def test_v3_checks_success_action_hostname_and_score(self):
good = {"success": True, "hostname": "hub.example", "action": "login", "score": 0.5}
self.assertTrue(self.verify(good)[0][0])
for patch in ({"score": 0.49}, {"score": None}, {"score": True}, {"score": "0.9"}, {"score": float("nan")},
{"score": 1.1}, {"action": "other"}, {"action": ""}, {"hostname": "other.example"},
{"hostname": ""}, {"success": False}, {"success": "true"}):
with self.subTest(patch=patch):
self.assertFalse(self.verify({**good, **patch})[0][0])
self.assertFalse(self.verify({k: v for k, v in good.items() if k != "score"})[0][0])
self.assertFalse(self.verify(good, min_score=0.6)[0][0])
self.assertFalse(self.verify([])[0][0])
def test_v2_does_not_require_v3_fields(self):
with mock.patch.object(hub, "oauth_fetch_json", return_value={"success": True, "hostname": "hub.example"}):
self.assertTrue(hub.verify_recaptcha_token("secret", "token", expected_hostname="hub.example")[0])
def test_empty_expired_and_network_error_fail_closed(self):
with mock.patch.object(hub, "oauth_fetch_json") as google:
self.assertFalse(hub.verify_recaptcha_token("secret", "")[0])
google.assert_not_called()
self.assertFalse(self.verify({"success": False, "error-codes": ["timeout-or-duplicate"]})[0][0])
with mock.patch.object(hub, "oauth_fetch_json", side_effect=TimeoutError("unavailable")):
self.assertFalse(hub.verify_recaptcha_token("secret", "token")[0])
def test_google_receives_secret_token_and_optional_ip(self):
with mock.patch.object(hub, "oauth_fetch_json", return_value={"success": True}) as google:
hub.verify_recaptcha_token("secret", "token", remote_ip="192.0.2.1")
google.assert_called_once_with(hub.RECAPTCHA_VERIFY_URL, method="POST", data={"secret": "secret", "response": "token", "remoteip": "192.0.2.1"})
def test_handler_uses_server_action_and_threshold(self):
handler = object.__new__(hub.Handler)
handler.client_ip = lambda: "192.0.2.1"
handler.request_host_name = lambda: "hub.example"
with mock.patch.object(hub, "verify_recaptcha_token", return_value=(True, "")) as verify:
self.assertTrue(handler.verify_login_captcha({"g-recaptcha-response": "token", "action": "evil", "score": 1}, configured_auth(score=0.7))[0])
self.assertEqual(verify.call_args.kwargs["expected_action"], "login")
self.assertEqual(verify.call_args.kwargs["min_score"], 0.7)
def test_digits_still_work(self):
handler = object.__new__(hub.Handler)
with mock.patch.object(hub, "verify_captcha", return_value=True) as verify:
self.assertTrue(handler.verify_login_captcha({"captcha_token": "token", "captcha_answer": "12345"}, configured_auth("digits"))[0])
verify.assert_called_once_with("token", "12345")
def test_login_pages_and_public_meta_hide_secret(self):
auth = configured_auth()
self.assertNotIn("secret_key", hub.public_auth_meta(auth)["captcha"])
self.assertEqual(hub.admin_auth_meta(auth)["captcha"]["min_score"], 0.5)
with mock.patch.object(hub, "load_auth", return_value=auth):
page = hub.login_html()
self.assertIn("api.js?render=test-site", page)
self.assertIn('data-recaptcha-action="login"', page)
self.assertIn('name="g-recaptcha-response"', page)
self.assertNotIn('name="captcha_answer"', page)
self.assertNotIn('class="g-recaptcha"', page)
self.assertNotIn("test-secret", page)
self.assertNotIn("test-secret", hub.modern_login_captcha_html(auth))
for mode in ("digits", "recaptcha"):
with mock.patch.object(hub, "load_auth", return_value=configured_auth(mode)):
page = hub.login_html()
if mode == "digits":
self.assertIn('name="captcha_answer"', page)
self.assertNotIn('src="https://www.google.com/recaptcha', page)
else:
self.assertIn('class="g-recaptcha"', page)
self.assertNotIn("api.js?render=", page)
def test_untrusted_site_key_is_escaped_in_markup_and_url(self):
auth = configured_auth()
auth["captcha"]["site_key"] = '"><script>bad</script>'
self.assertNotIn('"><script>bad', hub.modern_login_captcha_html(auth))
self.assertIn("%3Cscript%3E", hub.login_recaptcha_script(auth))
def test_settings_validate_and_preserve_other_auth(self):
handler = object.__new__(hub.Handler)
handler.send_text = mock.Mock()
auth = configured_auth("recaptcha")
payload = {"current_password": "fake-password", "captcha_mode": "recaptcha_v3", "captcha_min_score": "0.7", "captcha_site_key": "new-site", "captcha_secret_key": "new-secret"}
handler.read_payload = lambda **kwargs: payload
with mock.patch.object(hub, "load_auth", return_value=auth), mock.patch.object(hub, "verify_login", return_value=True), mock.patch.object(hub, "save_auth_state") as save:
handler.update_auth()
self.assertEqual(handler.send_text.call_args.args[0], 200)
self.assertEqual(save.call_args.args[0]["captcha"]["mode"], "recaptcha_v3")
self.assertEqual(save.call_args.args[0]["captcha"]["min_score"], 0.7)
for bad in ("nan", "", "2"):
save.reset_mock()
payload["captcha_min_score"] = bad
handler.update_auth()
self.assertEqual(handler.send_text.call_args.args[0], 400)
save.assert_not_called()
payload.update(captcha_min_score="0.5", captcha_site_key="")
handler.update_auth()
self.assertEqual(handler.send_text.call_args.args[0], 400)
save.assert_not_called()
payload = {"current_password": "fake-password", "username": "renamed"}
handler.read_payload = lambda **kwargs: payload
handler.update_auth()
self.assertEqual(save.call_args.args[0]["captcha"]["mode"], "recaptcha")
with mock.patch.object(hub, "load_auth", return_value=auth), mock.patch.object(hub, "verify_login", return_value=False), mock.patch.object(hub, "save_auth_state") as save:
handler.update_auth()
self.assertEqual(handler.send_text.call_args.args[0], 403)
save.assert_not_called()
def test_digits_remove_keys_even_if_old_browser_sends_them(self):
handler = object.__new__(hub.Handler)
handler.send_text = mock.Mock()
payload = {"current_password": "fake-password", "captcha_mode": "digits", "captcha_site_key": "old-site", "captcha_secret_key": "old-secret"}
handler.read_payload = lambda **kwargs: payload
with mock.patch.object(hub, "load_auth", return_value=configured_auth()), mock.patch.object(hub, "verify_login", return_value=True), mock.patch.object(hub, "save_auth_state") as save:
handler.update_auth()
self.assertEqual(handler.send_text.call_args.args[0], 200)
captcha = save.call_args.args[0]["captcha"]
self.assertEqual(captcha["mode"], "digits")
self.assertEqual(captcha["site_key"], "")
self.assertEqual(captcha["secret_key"], "")
def test_switching_versions_cannot_reuse_old_keys(self):
handler = object.__new__(hub.Handler)
handler.send_text = mock.Mock()
for before, after in (("recaptcha_v3", "recaptcha"), ("recaptcha", "recaptcha_v3")):
with self.subTest(before=before, after=after):
handler.read_payload = lambda **kwargs: {"current_password": "fake-password", "captcha_mode": after}
with mock.patch.object(hub, "load_auth", return_value=configured_auth(before)), mock.patch.object(hub, "verify_login", return_value=True), mock.patch.object(hub, "save_auth_state") as save:
handler.update_auth()
self.assertEqual(handler.send_text.call_args.args[0], 400)
save.assert_not_called()
def test_empty_form_fields_are_not_restored_from_old_keys(self):
handler = object.__new__(hub.Handler)
handler.send_text = mock.Mock()
handler.headers = {"Content-Type": "application/x-www-form-urlencoded"}
handler.read_body = lambda: b"current_password=fake-password&captcha_mode=recaptcha&captcha_site_key=&captcha_secret_key="
self.assertEqual(handler.read_payload(keep_blank_values=True)["captcha_site_key"], "")
with mock.patch.object(hub, "load_auth", return_value=configured_auth("recaptcha")), mock.patch.object(hub, "verify_login", return_value=True), mock.patch.object(hub, "save_auth_state") as save:
handler.update_auth()
self.assertEqual(handler.send_text.call_args.args[0], 400)
save.assert_not_called()
def test_digits_key_removal_persists_after_auth_reload(self):
with tempfile.TemporaryDirectory(prefix="owrt-key-reset-") as temp, mock.patch.object(hub, "AUTH_FILE", Path(temp) / "hub-auth.json"):
hub.save_auth_state(configured_auth())
handler = object.__new__(hub.Handler)
handler.send_text = mock.Mock()
handler.headers = {"Content-Type": "application/x-www-form-urlencoded"}
handler.read_body = lambda: b"current_password=fake-password&captcha_mode=digits&captcha_site_key=&captcha_secret_key="
with mock.patch.object(hub, "verify_login", return_value=True):
handler.update_auth()
self.assertEqual(handler.send_text.call_args.args[0], 200)
reloaded = hub.load_auth()["captcha"]
self.assertEqual(reloaded["mode"], "digits")
self.assertEqual(reloaded["site_key"], "")
self.assertEqual(reloaded["secret_key"], "")
meta = hub.admin_auth_meta(hub.load_auth())["captcha"]
self.assertFalse(meta["configured"])
self.assertEqual(meta["site_key"], "")
self.assertEqual(meta["secret_key"], "")
class QuietHandler(hub.Handler):
def log_message(self, *args):
pass
class LoginHttpTests(unittest.TestCase):
def test_real_login_http_checks_v3_before_creating_cookie(self):
auth = configured_auth()
with mock.patch.object(hub, "load_auth", return_value=auth):
server = hub.HubHTTPServer(("127.0.0.1", 0), QuietHandler)
server.app = hub.App(Path(STATE.name) / "hub.db", "fake-session", "fake-agent", "")
server.is_tls = False
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
base = f"http://127.0.0.1:{server.server_port}"
try:
result = {"success": True, "action": "login", "score": 0.9, "hostname": "127.0.0.1"}
payload = {"username": "test-owner", "password": "fake-password", "g-recaptcha-response": "token"}
request = urllib.request.Request(base + "/login", data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"})
# Use an opener that exposes 302 and its Set-Cookie header.
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args):
return None
opener = urllib.request.build_opener(NoRedirect())
with mock.patch.object(hub, "oauth_fetch_json", return_value=result), mock.patch.object(hub, "verify_password_login", return_value=(True, "", auth, "password")) as password, mock.patch.object(hub.Handler, "create_login_session", return_value=("new-session", {})) as session:
with self.assertRaises(urllib.error.HTTPError) as caught:
opener.open(request, timeout=5)
with caught.exception as response:
self.assertEqual(response.code, 302)
self.assertIn("new-session", response.headers["Set-Cookie"])
password.assert_called_once()
session.assert_called_once()
result["score"] = 0.1
password.reset_mock()
session.reset_mock()
with self.assertRaises(urllib.error.HTTPError) as caught:
opener.open(request, timeout=5)
with caught.exception as response:
self.assertEqual(response.code, 401)
password.assert_not_called()
session.assert_not_called()
finally:
server.shutdown()
server.server_close()
thread.join(timeout=5)
if __name__ == "__main__":
if len(sys.argv) == 3 and sys.argv[1] == "--export-js":
output = Path(sys.argv[2])
output.mkdir(parents=True, exist_ok=True)
auth = configured_auth()
with mock.patch.object(hub, "load_auth", return_value=auth):
pages = {
"login": hub.login_html(),
"dashboard": hub.dashboard_html([], "test-owner", auth_bootstrap={**hub.admin_auth_meta(auth), "is_owner": True}),
}
for name, page in pages.items():
(output / f"{name}.js").write_text("\n".join(re.findall(r"<script>(.*?)</script>", page, re.S)), encoding="utf-8")
print(f"JavaScript exported to {output}")
else:
unittest.main()
+187
View File
@@ -0,0 +1,187 @@
// Run after: python tests/test_recaptcha.py --export-js .test-output/recaptcha
// Then: node tests/test_recaptcha_login.cjs .test-output/recaptcha/login.js
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const source = fs.readFileSync(process.argv[2], 'utf8').replace(/\r\n/g, '\n');
const prepareStart = source.indexOf('async function prepareLoginRecaptcha()');
const prepareEnd = source.indexOf('\nfunction setActiveAuthTab', prepareStart);
const submitStart = source.indexOf("if (passwordLoginForm) {\n passwordLoginForm.addEventListener('submit'");
const submitEnd = source.indexOf('\nasync function loadLoginMeta', submitStart);
assert(prepareStart >= 0 && prepareEnd > prepareStart && submitStart >= 0 && submitEnd > submitStart);
function fixture(kind = 'v3') {
const tokenField = {value: 'stale-token', dataset: {recaptchaV3SiteKey: 'test-site', recaptchaAction: 'login'}};
const button = {disabled: false};
const posts = [], status = [], timers = new Map();
let submitted, timerId = 0, generation = 0, resetCount = 0;
const form = {
action: '/login',
querySelector() { return kind === 'v3' ? tokenField : null; },
reportValidity() { return true; },
addEventListener(event, callback) { submitted = callback; },
submit() { posts.push({native: true, token: tokenField.value}); },
};
const google = {
ready(callback) { callback(); },
async execute(site, options) {
assert.equal(site, 'test-site');
assert.equal(options.action, 'login');
return 'fresh-token-' + ++generation;
},
reset() { resetCount++; },
};
const window = {
grecaptcha: google, FormData: true, fetch: true, AbortController: true,
setTimeout(callback, delay) { const id = ++timerId; timers.set(id, {callback, delay}); return id; },
clearTimeout(id) { timers.delete(id); },
location: {assign() { throw new Error('Unexpected redirect in rejection test'); }},
};
const context = {
window, passwordLoginForm: form, passwordLoginSubmitBtn: button,
loginSubmitInFlight: false, loginAuthMeta: {}, hubOtp: null,
setLoginRuntimeStatus(text) { status.push(text); },
FormData: class { constructor() { this.token = tokenField.value; } },
AbortController: class { constructor() { this.signal = {}; } abort() {} },
extractLoginError() { return 'Incorrect password'; },
async fetch(url, options) {
posts.push({url, token: options.body.token});
return {ok: false, status: 401, async text() { return 'Incorrect password'; }};
},
};
vm.createContext(context);
vm.runInContext(source.slice(prepareStart, prepareEnd) + '\n' + source.slice(submitStart, submitEnd), context);
return {
context, window, google, tokenField, button, posts, status, timers,
submit: () => submitted({preventDefault() {}}),
resetCount: () => resetCount,
};
}
(async () => {
const retry = fixture();
assert.equal(retry.posts.length, 0, 'v3 must run on submission, not page load');
await retry.submit();
await retry.submit();
assert.deepEqual(retry.posts.map(p => p.token), ['fresh-token-1', 'fresh-token-2']);
assert.equal(retry.tokenField.value, '');
assert.equal(retry.button.disabled, false);
assert.equal(retry.context.loginSubmitInFlight, false);
assert.equal(retry.timers.size, 0);
const failure = fixture();
failure.google.execute = async () => { throw new Error('blocked'); };
await failure.submit();
assert.equal(failure.posts.length, 0, 'a failed CAPTCHA must not send login');
assert.equal(failure.button.disabled, false);
assert.equal(failure.tokenField.value, '');
const blocked = fixture();
delete blocked.window.grecaptcha;
const pending = blocked.submit();
const timeout = [...blocked.timers.values()].find(timer => timer.delay === 12000);
assert(timeout, 'missing Google script needs a finite timeout');
timeout.callback();
await pending;
assert.equal(blocked.posts.length, 0);
assert.equal(blocked.timers.size, 0);
assert.equal(blocked.button.disabled, false);
const doubleClick = fixture();
let release;
doubleClick.google.execute = () => new Promise(resolve => { release = resolve; });
const first = doubleClick.submit();
await doubleClick.submit();
release('only-once');
await first;
assert.equal(doubleClick.posts.length, 1, 'double click must not duplicate login');
const native = fixture();
native.window.fetch = false;
await native.submit();
assert.deepEqual(native.posts, [{native: true, token: 'fresh-token-1'}]);
for (const kind of ['v2', 'digits']) {
const previous = fixture(kind);
await previous.submit();
assert.equal(previous.posts.length, 1);
assert.equal(previous.button.disabled, false);
assert.equal(previous.resetCount(), 1);
}
console.log('RECAPTCHA_LOGIN_JS_OK: fresh tokens, retry, failure, timeout, double click, native POST and old modes');
const dashboard = fs.readFileSync(path.join(path.dirname(process.argv[2]), 'dashboard.js'), 'utf8');
const start = dashboard.indexOf('function updateCaptchaSettingsMode(');
const end = dashboard.indexOf('\nfunction authB64urlToBytes', start);
const scoreLabel = {hidden: true};
const settings = {
authCaptchaModeField: {value: 'recaptcha_v3'}, authCaptchaMinScoreField: {},
authCaptchaSiteKeyField: {value: 'v3-site'}, authCaptchaSecretKeyField: {value: 'v3-secret'},
authCaptchaDraftDirty: false,
authForm: {querySelector() { return scoreLabel; }},
};
vm.createContext(settings);
vm.runInContext(dashboard.slice(start, end), settings);
settings.updateCaptchaSettingsMode();
assert.equal(scoreLabel.hidden, false);
assert.equal(settings.authCaptchaMinScoreField.disabled, false);
assert.equal(settings.authCaptchaSiteKeyField.placeholder, 'reCAPTCHA v3 Site Key');
assert.equal(settings.authCaptchaSiteKeyField.value, 'v3-site', 'rendering must preserve keys of the saved mode');
settings.authCaptchaModeField.value = 'recaptcha';
settings.updateCaptchaSettingsMode(true);
assert.equal(scoreLabel.hidden, true);
assert.equal(settings.authCaptchaMinScoreField.disabled, true);
assert.equal(settings.authCaptchaSiteKeyField.value, '');
assert.equal(settings.authCaptchaSecretKeyField.value, '');
assert.equal(settings.authCaptchaSiteKeyField.required, true);
assert.equal(settings.authCaptchaDraftDirty, true);
settings.authCaptchaSiteKeyField.value = 'v2-site';
settings.authCaptchaSecretKeyField.value = 'v2-secret';
settings.updateCaptchaSettingsMode();
assert.equal(settings.authCaptchaSiteKeyField.value, 'v2-site');
settings.authCaptchaModeField.value = 'digits';
settings.updateCaptchaSettingsMode(true);
assert.equal(settings.authCaptchaSiteKeyField.value, '');
assert.equal(settings.authCaptchaSecretKeyField.value, '');
assert.equal(settings.authCaptchaSiteKeyField.hidden, true);
assert.equal(settings.authCaptchaSiteKeyField.disabled, true);
assert.equal(settings.authCaptchaSiteKeyField.required, false);
settings.authCaptchaModeField.value = 'recaptcha_v3';
settings.updateCaptchaSettingsMode(true);
assert.equal(settings.authCaptchaSiteKeyField.value, '');
assert.equal(settings.authCaptchaSecretKeyField.value, '');
assert.equal(settings.authCaptchaSiteKeyField.hidden, false);
assert.equal(settings.authCaptchaSiteKeyField.disabled, false);
console.log('RECAPTCHA_SETTINGS_JS_OK: v2/v3/digits switching clears incompatible keys and keeps edited drafts');
const saveStart = dashboard.indexOf("authForm.addEventListener('submit', async (ev) => {");
const saveEnd = dashboard.indexOf('\nif (delegatedUserReset)', saveStart);
assert(saveStart >= 0 && saveEnd > saveStart);
let saveCallback, posted, reloaded = false;
const savedForm = {
password: {value: ''}, password_confirm: {value: ''}, current_password: {value: 'fake-password'},
addEventListener(type, fn) { saveCallback = fn; },
};
const saving = {
authForm: savedForm, authUsernameDraftDirty: true, authCaptchaDraftDirty: true,
setAuthMessage() {}, ownerPasswordRememberEnabled() { return false; }, restoreOwnerPasswordInput() {},
FormData: class {
constructor(form) { assert.equal(form, savedForm); }
*[Symbol.iterator]() { yield ['captcha_mode', 'recaptcha_v3']; yield ['captcha_min_score', '0.7']; }
},
URLSearchParams,
async fetch(url, options) { posted = options.body.toString(); return {ok: true, async text() { return 'Saved'; }}; },
async loadAuthMeta() { reloaded = true; },
};
vm.createContext(saving);
vm.runInContext(dashboard.slice(saveStart, saveEnd), saving);
const event = {currentTarget: savedForm, preventDefault() {}, stopImmediatePropagation() {}};
const saved = saveCallback(event);
event.currentTarget = null; // Browsers clear currentTarget after dispatch.
await saved;
assert.equal(posted, 'captcha_mode=recaptcha_v3&captcha_min_score=0.7');
assert.equal(saving.authCaptchaDraftDirty, false);
assert.equal(reloaded, true);
console.log('RECAPTCHA_SETTINGS_SAVE_JS_OK: v3 persisted and currentTarget expiry handled');
})().catch(error => { console.error(error); process.exitCode = 1; });
+1 -1
View File
@@ -131,7 +131,7 @@ class HubFixture:
assert "groups" in json.loads(self.request("/api/router-groups"))
assert "notifications" in json.loads(self.request("/api/notifications"))
assert self.request("/access/test-router/") == b"router proxy fixture"
assert b"v109" in self.request("/")
assert b"v110" in self.request("/")
self.app.snapshot_router_states()
def __exit__(self, *args):
+205
View File
@@ -0,0 +1,205 @@
param(
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Vps,
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$RemoteTarget = $Vps
$UploadName = 'owrt-recaptcha-v3-' + [guid]::NewGuid().ToString('N')
$Utf8 = [System.Text.UTF8Encoding]::new($false)
$UploadFiles = @()
if ($Action -eq 'Install') {
$RemoteScript = @'
#!/bin/bash
set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v110
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v110.json
candidate=$target.new-__UPLOAD_NAME__
changed=0
cleanup() {
code=$?
trap - EXIT
if [ "$code" -ne 0 ] && [ "$changed" = 1 ]; then
echo 'Installation failed; restoring the file from this attempt.' >&2
systemctl --no-pager -l status owrt-remote >&2 || true
journalctl -u owrt-remote -n 60 --no-pager >&2 || true
cp -a "$stage/previous.py" "$candidate"
mv -f "$candidate" "$target"
systemctl restart owrt-remote || true
fi
rm -f "$candidate"
rm -rf -- "$stage"
exit "$code"
}
trap cleanup EXIT
test -s "$target"
test -s "$stage/hub.py"
python_bin=/opt/owrt-remote/venv/bin/python
if [ ! -x "$python_bin" ]; then python_bin=python3; fi
"$python_bin" - "$stage/hub.py" <<'PY'
import ast, pathlib, sys
source = pathlib.Path(sys.argv[1]).read_text(encoding='utf-8')
tree = ast.parse(source)
assert 'v110' in source
assert 'v108' not in source
assert 'CAPTCHA_MODE_RECAPTCHA_V3' in source
assert 'prepareLoginRecaptcha' in source
PY
# The Linux regression suite uses its own temporary DB and loopback ports.
# It also exercises a real PTY and verifies child reaping.
OWRT_RESOURCE_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/resources.py" -v
OWRT_RECAPTCHA_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/recaptcha.py" -v
if [ ! -e "$backup" ]; then cp -a "$target" "$backup"; fi
test -s "$backup"
if [ ! -e "$captcha_backup" ]; then
"$python_bin" - "$captcha_backup" <<'PY'
import json, os, pathlib, sys
auth = pathlib.Path('/var/lib/owrt-remote/hub-auth.json')
state = json.loads(auth.read_text(encoding='utf-8')) if auth.exists() else {}
with open(os.open(sys.argv[1], os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), 'w', encoding='utf-8') as output:
json.dump(state.get('captcha', {'mode': 'digits', 'site_key': '', 'secret_key': ''}), output)
PY
fi
test -s "$captcha_backup"
printf 'Backup: %s\n' "$backup"
cp -a "$target" "$stage/previous.py"
install -m 0755 "$stage/hub.py" "$candidate"
changed=1
mv -f "$candidate" "$target"
systemctl restart owrt-remote
healthy=0
for attempt in {1..10}; do
if systemctl is-active --quiet owrt-remote && curl -fsS --max-time 5 http://127.0.0.1:8088/health; then
healthy=1
break
fi
sleep 2
done
test "$healthy" = 1
cmp -s "$target" "$stage/hub.py"
printf '\n'
pid=$(systemctl show owrt-remote -p MainPID --value)
test "$pid" -gt 0
printf 'PID=%s FD=%s\n' "$pid" "$(find /proc/$pid/fd -maxdepth 1 -type l | wc -l)"
systemctl --no-pager --full status owrt-remote | sed -n '1,16p'
echo RECAPTCHA_V3_V110_OK
'@
} elseif ($Action -eq 'Rollback') {
$RemoteScript = @'
#!/bin/bash
set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v110
captcha_backup=/opt/owrt-remote/captcha-before-recaptcha-v3-v110.json
candidate=$target.rollback-__UPLOAD_NAME__
changed=0
restore_captcha() {
python3 - "$1" <<'PY'
import json, os, pathlib, sys, tempfile
auth = pathlib.Path('/var/lib/owrt-remote/hub-auth.json')
state = json.loads(auth.read_text(encoding='utf-8'))
state['captcha'] = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding='utf-8'))
fd, name = tempfile.mkstemp(prefix='.hub-auth-rollback-', dir=auth.parent)
try:
with os.fdopen(fd, 'w', encoding='utf-8') as output:
json.dump(state, output, ensure_ascii=False, indent=2)
output.write('\n')
os.replace(name, auth)
finally:
pathlib.Path(name).unlink(missing_ok=True)
PY
}
cleanup() {
code=$?
trap - EXIT
if [ "$code" -ne 0 ] && [ "$changed" = 1 ]; then
echo 'Rollback failed; restoring the file from this attempt.' >&2
cp -a "$stage/current.py" "$candidate"
mv -f "$candidate" "$target"
restore_captcha "$stage/current-captcha.json"
systemctl restart owrt-remote || true
fi
rm -f "$candidate"
rm -rf -- "$stage"
exit "$code"
}
trap cleanup EXIT
test -s "$target"
test -s "$backup"
test -s "$captcha_backup"
python3 - "$backup" <<'PY'
import ast, pathlib, sys
ast.parse(pathlib.Path(sys.argv[1]).read_text(encoding='utf-8'))
PY
cp -a "$target" "$stage/current.py"
python3 - "$stage/current-captcha.json" <<'PY'
import json, os, pathlib, sys
auth = pathlib.Path('/var/lib/owrt-remote/hub-auth.json')
state = json.loads(auth.read_text(encoding='utf-8'))
with open(os.open(sys.argv[1], os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), 'w', encoding='utf-8') as output:
json.dump(state.get('captcha', {}), output)
PY
cp -a "$backup" "$candidate"
changed=1
mv -f "$candidate" "$target"
systemctl stop owrt-remote
restore_captcha "$captcha_backup"
systemctl restart owrt-remote
healthy=0
for attempt in {1..10}; do
if systemctl is-active --quiet owrt-remote && curl -fsS --max-time 5 http://127.0.0.1:8088/health; then
healthy=1
break
fi
sleep 2
done
test "$healthy" = 1
printf '\n'
echo RECAPTCHA_V3_ROLLBACK_OK
'@
}
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName)
try {
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
$UploadFiles += $StageRoot
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'run.sh'), $RemoteScript.Replace("`r`n", "`n") + "`n", $Utf8)
if ($Action -eq 'Install') {
$Payloads = @{
'hub.py' = Join-Path $RepoRoot 'vps\owrt-remote-hub.py'
'resources.py' = Join-Path $RepoRoot 'tests\test_resource_lifecycle.py'
'recaptcha.py' = Join-Path $RepoRoot 'tests\test_recaptcha.py'
}
foreach ($Item in $Payloads.GetEnumerator()) {
$FileText = [System.IO.File]::ReadAllText($Item.Value)
[System.IO.File]::WriteAllText((Join-Path $StageRoot $Item.Key), $FileText.Replace("`r`n", "`n"), $Utf8)
}
}
if ($PrepareOnly) {
Write-Host "Prepared only: $StageRoot"
$UploadFiles = @()
return
}
& scp -r -- $StageRoot "${RemoteTarget}:/tmp/"
if ($LASTEXITCODE -ne 0) { throw 'Upload failed; installation has not started.' }
& ssh $RemoteTarget "bash /tmp/$UploadName/run.sh"
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
Write-Host "$Action finished successfully."
} finally {
foreach ($UploadFile in $UploadFiles) {
$Resolved = [System.IO.Path]::GetFullPath($UploadFile)
$Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName))
if ($Resolved -ne $Expected -or (Split-Path -Leaf $Resolved) -ne $UploadName) {
throw 'Unsafe staging cleanup path.'
}
if (Test-Path -LiteralPath $Resolved) { Remove-Item -LiteralPath $Resolved -Recurse -Force }
}
}
+4 -4
View File
@@ -18,7 +18,7 @@ if ($Action -eq 'Install') {
set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v109
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v110
candidate=$target.new-__UPLOAD_NAME__
changed=0
cleanup() {
@@ -45,7 +45,7 @@ if [ ! -x "$python_bin" ]; then python_bin=python3; fi
import ast, pathlib, sys
source = pathlib.Path(sys.argv[1]).read_text(encoding='utf-8')
tree = ast.parse(source)
assert 'v109' in source
assert 'v110' in source
assert 'v108' not in source
factory = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == 'connect')
assert any(isinstance(item, ast.Name) and item.id == 'contextmanager' for item in factory.decorator_list)
@@ -78,7 +78,7 @@ pid=$(systemctl show owrt-remote -p MainPID --value)
test "$pid" -gt 0
printf 'PID=%s FD=%s\n' "$pid" "$(find /proc/$pid/fd -maxdepth 1 -type l | wc -l)"
systemctl --no-pager --full status owrt-remote | sed -n '1,16p'
echo RESOURCE_FIX_V109_OK
echo RESOURCE_FIX_V110_OK
'@
} elseif ($Action -eq 'Rollback') {
$RemoteScript = @'
@@ -86,7 +86,7 @@ echo RESOURCE_FIX_V109_OK
set -Eeuo pipefail
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v109
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v110
candidate=$target.rollback-__UPLOAD_NAME__
changed=0
cleanup() {
+202 -41
View File
@@ -13,6 +13,7 @@ import hashlib
import html
import http.client
import json
import math
import os
import re
import secrets
@@ -110,6 +111,10 @@ SESSION_TTL_SECONDS = int(os.environ.get("OWRT_REMOTE_SESSION_TTL", str(30 * 24
CAPTCHA_TTL_SECONDS = 600
CAPTCHA_MODE_DIGITS = "digits"
CAPTCHA_MODE_RECAPTCHA = "recaptcha"
CAPTCHA_MODE_RECAPTCHA_V3 = "recaptcha_v3"
CAPTCHA_RECAPTCHA_MODES = (CAPTCHA_MODE_RECAPTCHA, CAPTCHA_MODE_RECAPTCHA_V3)
RECAPTCHA_V3_ACTION = "login"
RECAPTCHA_V3_MIN_SCORE = 0.5
ROUTER_ACCESS_FLAGS = ("A", "B", "G")
ROUTER_ACCESS_LABELS = {
"A": "Web only",
@@ -605,12 +610,25 @@ def default_captcha_state():
"mode": CAPTCHA_MODE_DIGITS,
"site_key": "",
"secret_key": "",
"min_score": RECAPTCHA_V3_MIN_SCORE,
}
def sanitize_captcha_mode(value):
value = str(value or "").strip().lower()
return CAPTCHA_MODE_RECAPTCHA if value == CAPTCHA_MODE_RECAPTCHA else CAPTCHA_MODE_DIGITS
return value if value in CAPTCHA_RECAPTCHA_MODES else CAPTCHA_MODE_DIGITS
def parse_recaptcha_score(value):
try:
if isinstance(value, bool):
raise ValueError
score = float(value)
if not math.isfinite(score) or not 0 <= score <= 1:
raise ValueError
return score
except (TypeError, ValueError, OverflowError):
raise ValueError("Порог reCAPTCHA v3 должен быть числом от 0 до 1") from None
def sanitize_captcha_state(item):
@@ -619,6 +637,10 @@ def sanitize_captcha_state(item):
clean["mode"] = sanitize_captcha_mode(item.get("mode"))
clean["site_key"] = str(item.get("site_key") or "").strip()[:240]
clean["secret_key"] = str(item.get("secret_key") or "").strip()[:512]
try:
clean["min_score"] = parse_recaptcha_score(item.get("min_score", RECAPTCHA_V3_MIN_SCORE))
except ValueError:
clean["min_score"] = RECAPTCHA_V3_MIN_SCORE
return clean
@@ -626,7 +648,7 @@ def effective_captcha_state(auth=None):
auth = normalize_auth_state(auth or load_auth())
state = sanitize_captcha_state(auth.get("captcha"))
configured = bool(state.get("site_key") and state.get("secret_key"))
effective_mode = CAPTCHA_MODE_RECAPTCHA if state.get("mode") == CAPTCHA_MODE_RECAPTCHA and configured else CAPTCHA_MODE_DIGITS
effective_mode = state["mode"] if state["mode"] in CAPTCHA_RECAPTCHA_MODES and configured else CAPTCHA_MODE_DIGITS
state["configured"] = configured
state["effective_mode"] = effective_mode
return state
@@ -996,6 +1018,7 @@ def admin_auth_meta(auth=None):
"configured": bool(captcha.get("configured")),
"site_key": auth.get("captcha", {}).get("site_key", ""),
"secret_key": auth.get("captcha", {}).get("secret_key", ""),
"min_score": captcha["min_score"],
},
"passkeys": [
{
@@ -2767,7 +2790,7 @@ def verify_captcha(token, answer):
return False
def verify_recaptcha_token(secret_key, response_token, remote_ip="", expected_hostname=""):
def verify_recaptcha_token(secret_key, response_token, remote_ip="", expected_hostname="", expected_action="", min_score=RECAPTCHA_V3_MIN_SCORE):
secret_key = str(secret_key or "").strip()
response_token = str(response_token or "").strip()
if not secret_key or not response_token:
@@ -2782,7 +2805,9 @@ def verify_recaptcha_token(secret_key, response_token, remote_ip="", expected_ho
result = oauth_fetch_json(RECAPTCHA_VERIFY_URL, method="POST", data=payload)
except Exception as exc:
return False, f"Не удалось проверить Google reCAPTCHA: {exc}"
if not result.get("success"):
if not isinstance(result, dict):
return False, "Google reCAPTCHA вернула некорректный ответ"
if result.get("success") is not True:
errors = result.get("error-codes", [])
detail = ", ".join(str(item) for item in errors if str(item).strip())
if "timeout-or-duplicate" in errors:
@@ -2790,20 +2815,46 @@ def verify_recaptcha_token(secret_key, response_token, remote_ip="", expected_ho
return False, f"Google reCAPTCHA отклонена{': ' + detail if detail else ''}"
actual_hostname = str(result.get("hostname") or "").strip().lower()
expected_hostname = str(expected_hostname or "").strip().lower()
if expected_hostname and actual_hostname and actual_hostname != expected_hostname:
if expected_hostname and actual_hostname != expected_hostname:
return False, f"Google reCAPTCHA выдана для другого хоста: {actual_hostname}"
if expected_action:
if str(result.get("action") or "") != expected_action:
return False, "Google reCAPTCHA v3 выдана для другого действия"
try:
if not isinstance(result.get("score"), (int, float)):
raise ValueError
score = parse_recaptcha_score(result["score"])
threshold = parse_recaptcha_score(min_score)
except ValueError:
return False, "Google reCAPTCHA v3 вернула некорректную оценку"
if score < threshold:
return False, "Google reCAPTCHA v3 отклонила вход. Попробуй ещё раз или используй другой способ входа."
return True, ""
def login_recaptcha_script(auth=None):
state = effective_captcha_state(auth)
if state.get("effective_mode") != CAPTCHA_MODE_RECAPTCHA:
if state.get("effective_mode") not in CAPTCHA_RECAPTCHA_MODES:
return ""
if state["effective_mode"] == CAPTCHA_MODE_RECAPTCHA_V3:
site_key = urllib.parse.quote(state["site_key"], safe="")
return f'<script src="https://www.google.com/recaptcha/api.js?render={site_key}" async defer></script>'
return '<script src="https://www.google.com/recaptcha/api.js" async defer></script>'
def recaptcha_v3_captcha_html(auth=None):
state = effective_captcha_state(auth)
site_key = html.escape(state["site_key"], quote=True)
return f'''<div class="captchaSection captchaSectionRecaptcha">
<div class="captchaHeading">Защита Google reCAPTCHA v3</div>
<input type="hidden" name="g-recaptcha-response" value="" data-recaptcha-v3-site-key="{site_key}" data-recaptcha-action="{RECAPTCHA_V3_ACTION}">
</div>'''
def legacy_login_captcha_html(auth=None):
state = effective_captcha_state(auth)
if state["effective_mode"] == CAPTCHA_MODE_RECAPTCHA_V3:
return recaptcha_v3_captcha_html(auth)
if state.get("effective_mode") == CAPTCHA_MODE_RECAPTCHA:
safe_site_key = html.escape(state.get("site_key", ""), quote=True)
return f"""
@@ -2823,6 +2874,8 @@ def legacy_login_captcha_html(auth=None):
def modern_login_captcha_html(auth=None):
state = effective_captcha_state(auth)
if state["effective_mode"] == CAPTCHA_MODE_RECAPTCHA_V3:
return recaptcha_v3_captcha_html(auth)
if state.get("effective_mode") == CAPTCHA_MODE_RECAPTCHA:
safe_site_key = html.escape(state.get("site_key", ""), quote=True)
return f"""
@@ -4608,7 +4661,7 @@ input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding
<div class="brand">
<div class="desktopHeader">
<div class="desktopHeaderTop">
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v109</span></span></h1>
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v110</span></span></h1>
<div class="routerSearchDock" id="routerSearchDock">
<button class="routerSearchToggle" id="routerSearchToggle" type="button" aria-expanded="false" aria-controls="routerSearchPanel" data-active="false">
<span>Поиск роутеров</span>
@@ -4960,7 +5013,7 @@ systemctl restart owrt-remote-xray</pre>
</div>
</div>
<div class="mobileSearchDock" id="mobileRouterSearchDock">
<span class="mobileSearchVersion">v109</span>
<span class="mobileSearchVersion">v110</span>
<button class="routerSearchToggle mobilePanelToggle primary" id="mobileRouterSearchToggle" type="button" aria-expanded="false" aria-controls="mobileRouterSearchPanel" data-active="false">
<span>Поиск роутеров</span>
</button>
@@ -8872,6 +8925,8 @@ const authUsernameField = authForm && authForm.elements ? authForm.elements.name
let authCaptchaModeField = null;
let authCaptchaSiteKeyField = null;
let authCaptchaSecretKeyField = null;
let authCaptchaMinScoreField = null;
let authCaptchaDraftDirty = false;
const authMsg = document.getElementById('authMsg');
const authSummary = document.getElementById('authSummary');
const totpState = document.getElementById('totpState');
@@ -9499,16 +9554,22 @@ function ensureCaptchaSettingsFields() {{
const wrap = document.createElement('div');
wrap.className = 'wide';
wrap.dataset.captchaConfig = 'true';
wrap.addEventListener('input', () => {{ authCaptchaDraftDirty = true; }});
wrap.addEventListener('change', () => {{ authCaptchaDraftDirty = true; }});
wrap.innerHTML = `
<div style="display:grid;gap:8px;padding:10px 12px;border:1px solid rgba(148,163,184,.18);border-radius:8px;background:rgba(255,255,255,.03)">
<strong style="font-size:13px">Капча на экране входа</strong>
<span style="color:var(--muted);font-size:12px;line-height:1.45">Можно оставить цифровую капчу или переключить вход на Google reCAPTCHA v2 Checkbox. Ключ должен быть выпущен для текущего домена.</span>
<span style="color:var(--muted);font-size:12px;line-height:1.45">Цифры, Google reCAPTCHA v2 Checkbox или v3 без галочки. Используй ключи выбранной версии, выпущенные для домена панели.</span>
<select class="wide" name="captcha_mode">
<option value="{CAPTCHA_MODE_DIGITS}">Капча: цифры</option>
<option value="{CAPTCHA_MODE_RECAPTCHA}">Капча: Google reCAPTCHA v2 Checkbox</option>
<option value="{CAPTCHA_MODE_RECAPTCHA_V3}">Капча: Google reCAPTCHA v3</option>
</select>
<input class="wide" name="captcha_site_key" placeholder="reCAPTCHA v2 Site Key">
<input class="wide" name="captcha_secret_key" placeholder="reCAPTCHA v2 Secret Key">
<input class="wide" name="captcha_site_key" placeholder="reCAPTCHA Site Key" aria-label="reCAPTCHA Site Key">
<input class="wide" name="captcha_secret_key" placeholder="reCAPTCHA Secret Key" aria-label="reCAPTCHA Secret Key">
<label class="wide" data-captcha-score hidden>Минимальная оценка v3 (0–1)
<input class="wide" name="captcha_min_score" type="number" min="0" max="1" step="0.01" value="{RECAPTCHA_V3_MIN_SCORE}">
</label>
</div>
`;
const saveBtn = authForm.querySelector('button');
@@ -9517,6 +9578,32 @@ function ensureCaptchaSettingsFields() {{
authCaptchaModeField = authForm.elements ? authForm.elements.namedItem('captcha_mode') : null;
authCaptchaSiteKeyField = authForm.elements ? authForm.elements.namedItem('captcha_site_key') : null;
authCaptchaSecretKeyField = authForm.elements ? authForm.elements.namedItem('captcha_secret_key') : null;
authCaptchaMinScoreField = authForm.elements ? authForm.elements.namedItem('captcha_min_score') : null;
if (authCaptchaModeField && !authCaptchaModeField.dataset.captchaBound) {{
authCaptchaModeField.dataset.captchaBound = 'true';
authCaptchaModeField.addEventListener('change', () => updateCaptchaSettingsMode(true));
}}
}}
function updateCaptchaSettingsMode(clearKeys = false) {{
if (!authCaptchaModeField) return;
const isGoogle = ['{CAPTCHA_MODE_RECAPTCHA}', '{CAPTCHA_MODE_RECAPTCHA_V3}'].includes(authCaptchaModeField.value);
const isV3 = authCaptchaModeField.value === '{CAPTCHA_MODE_RECAPTCHA_V3}';
const version = isV3 ? 'v3' : 'v2';
const scoreLabel = authForm.querySelector('[data-captcha-score]');
if (scoreLabel) scoreLabel.hidden = !isV3;
if (authCaptchaMinScoreField) authCaptchaMinScoreField.disabled = !isV3;
if (clearKeys) authCaptchaDraftDirty = true;
[authCaptchaSiteKeyField, authCaptchaSecretKeyField].forEach((field) => {{
if (!field) return;
field.hidden = !isGoogle;
field.disabled = !isGoogle;
field.required = isGoogle;
if (clearKeys || !isGoogle) field.value = '';
}});
if ((clearKeys || !isGoogle) && authCaptchaMinScoreField) authCaptchaMinScoreField.value = {RECAPTCHA_V3_MIN_SCORE};
if (authCaptchaSiteKeyField) authCaptchaSiteKeyField.placeholder = `reCAPTCHA ${{version}} Site Key`;
if (authCaptchaSecretKeyField) authCaptchaSecretKeyField.placeholder = `reCAPTCHA ${{version}} Secret Key`;
}}
function authB64urlToBytes(value) {{
@@ -9729,23 +9816,29 @@ function renderAuthMeta() {{
const captchaMeta = meta.captcha && typeof meta.captcha === 'object' ? meta.captcha : {{}};
const captchaMode = String(captchaMeta.mode || '{CAPTCHA_MODE_DIGITS}');
const captchaConfigured = !!captchaMeta.configured;
const captchaPillText = captchaMode === '{CAPTCHA_MODE_RECAPTCHA}'
? (captchaConfigured ? 'Google reCAPTCHA v2' : 'reCAPTCHA v2 без ключей')
const captchaIsGoogle = ['{CAPTCHA_MODE_RECAPTCHA}', '{CAPTCHA_MODE_RECAPTCHA_V3}'].includes(captchaMode);
const captchaVersion = captchaMode === '{CAPTCHA_MODE_RECAPTCHA_V3}' ? 'v3' : 'v2';
const captchaPillText = captchaIsGoogle
? (captchaConfigured ? `Google reCAPTCHA ${{captchaVersion}}` : `reCAPTCHA ${{captchaVersion}} без ключей`)
: 'Капча: цифры';
const socialEntries = Object.entries(meta.social || {{}})
.filter(([, item]) => Number(item && item.linked_count || 0) > 0)
.map(([provider, item]) => `<span class="authPill">${{escapeHtml((item && item.label) || socialProviderUi[provider]?.label || 'OAuth')}}: ${{Number(item && item.linked_count || 0)}}</span>`);
authSummary.innerHTML = [
'<span class="authPill">Пароль</span>',
`<span class="authPill ${{captchaMode === '{CAPTCHA_MODE_RECAPTCHA}' && !captchaConfigured ? 'off' : ''}}">${{captchaPillText}}</span>`,
`<span class="authPill ${{captchaIsGoogle && !captchaConfigured ? 'off' : ''}}">${{captchaPillText}}</span>`,
`<span class="authPill ${{totpEnabled ? '' : 'off'}}">${{totpEnabled ? '2FA включена' : '2FA выключена'}}</span>`,
`<span class="authPill ${{passkeyCount ? '' : 'off'}}">Passkey: ${{passkeyCount}}</span>`,
`<span class="authPill ${{sshCount ? '' : 'off'}}">ED25519: ${{sshCount}}</span>`,
...socialEntries
].join('');
if (authCaptchaModeField) authCaptchaModeField.value = captchaMode === '{CAPTCHA_MODE_RECAPTCHA}' ? '{CAPTCHA_MODE_RECAPTCHA}' : '{CAPTCHA_MODE_DIGITS}';
if (authCaptchaSiteKeyField && document.activeElement !== authCaptchaSiteKeyField) authCaptchaSiteKeyField.value = captchaMeta.site_key || '';
if (authCaptchaSecretKeyField && document.activeElement !== authCaptchaSecretKeyField) authCaptchaSecretKeyField.value = captchaMeta.secret_key || '';
if (!authCaptchaDraftDirty) {{
if (authCaptchaModeField && document.activeElement !== authCaptchaModeField) authCaptchaModeField.value = captchaIsGoogle ? captchaMode : '{CAPTCHA_MODE_DIGITS}';
if (authCaptchaSiteKeyField && document.activeElement !== authCaptchaSiteKeyField) authCaptchaSiteKeyField.value = captchaMeta.site_key || '';
if (authCaptchaSecretKeyField && document.activeElement !== authCaptchaSecretKeyField) authCaptchaSecretKeyField.value = captchaMeta.secret_key || '';
if (authCaptchaMinScoreField && document.activeElement !== authCaptchaMinScoreField) authCaptchaMinScoreField.value = captchaMeta.min_score ?? {RECAPTCHA_V3_MIN_SCORE};
}}
updateCaptchaSettingsMode();
totpState.textContent = totpEnabled ? '2FA включена' : '2FA выключена';
totpState.className = 'authSectionState' + (totpEnabled ? '' : ' off');
passkeySummary.textContent = passkeyCount ? `Passkey: ${{passkeyCount}}` : '0 ключей';
@@ -11004,18 +11097,20 @@ authMenu.addEventListener('click', async (ev) => {{
authForm.addEventListener('submit', async (ev) => {{
ev.preventDefault();
ev.stopImmediatePropagation();
const form = ev.currentTarget;
setAuthMessage('');
const body = new URLSearchParams(new FormData(ev.currentTarget));
const body = new URLSearchParams(new FormData(form));
const res = await fetch('/api/auth', {{method: 'POST', body}});
const text = await res.text();
if (res.ok) {{
const nextCurrentPassword = ev.currentTarget.password.value ? String(ev.currentTarget.password.value || '') : String(ev.currentTarget.current_password.value || '');
const nextCurrentPassword = form.password.value ? String(form.password.value || '') : String(form.current_password.value || '');
if (ownerPasswordRememberEnabled()) setOwnerPasswordRememberEnabled(true, nextCurrentPassword);
setAuthMessage(text || 'Доступ обновлен');
restoreOwnerPasswordInput(ev.currentTarget.current_password, nextCurrentPassword);
ev.currentTarget.password.value = '';
ev.currentTarget.password_confirm.value = '';
restoreOwnerPasswordInput(form.current_password, nextCurrentPassword);
form.password.value = '';
form.password_confirm.value = '';
authUsernameDraftDirty = false;
authCaptchaDraftDirty = false;
await loadAuthMeta({{silent: true, forceUsername: true}}).catch(() => {{}});
}} else {{
setAuthMessage(text || 'Не удалось сохранить', true);
@@ -12310,7 +12405,7 @@ button:hover{{filter:brightness(1.06)}}
<form class="login" method="post" action="/login">
{error_html}
<span class="brand">
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v109</span></span></h1>
<h1 class="appBanner"><span>OpenWrt Remote Hub <span class="appBannerVersion">v110</span></span></h1>
</span>
<label for="hubUsername">Логин</label>
<input id="hubUsername" name="username" autocomplete="off" autofocus required>
@@ -12782,7 +12877,7 @@ body::after{{content:"";position:fixed;inset:0;pointer-events:none;background:li
<circle cx="65" cy="59" r="3" fill="#E5F2FF"/>
</svg>
</div>
<h2 class="brandTitle">OpenWrt Remote Hub <span class="brandVersion">v109</span></h2>
<h2 class="brandTitle">OpenWrt Remote Hub <span class="brandVersion">v110</span></h2>
</div>
</div>
<div class="brandBottom">
@@ -13074,6 +13169,48 @@ let loginAuthMeta = {initial_login_meta_json};
let sshTicket = '';
let loginSubmitInFlight = false;
async function prepareLoginRecaptcha() {{
const tokenField = passwordLoginForm.querySelector('[data-recaptcha-v3-site-key]');
if (!tokenField) return;
tokenField.value = '';
setLoginRuntimeStatus('Проверяю Google reCAPTCHA v3...', 'info');
const token = await new Promise((resolve, reject) => {{
let finished = false;
let pollId = null;
const finish = (error, value) => {{
if (finished) return;
finished = true;
window.clearTimeout(timeoutId);
window.clearTimeout(pollId);
if (error) reject(error); else resolve(value);
}};
const timeoutId = window.setTimeout(() => finish(new Error('Google reCAPTCHA v3 не ответила. Проверь доступ к Google и попробуй ещё раз.')), 12000);
const execute = () => {{
if (finished) return;
if (!window.grecaptcha || typeof window.grecaptcha.ready !== 'function' || typeof window.grecaptcha.execute !== 'function') {{
pollId = window.setTimeout(execute, 100);
return;
}}
try {{
window.grecaptcha.ready(() => {{
if (finished) return;
try {{
Promise.resolve(window.grecaptcha.execute(tokenField.dataset.recaptchaV3SiteKey, {{action: tokenField.dataset.recaptchaAction}}))
.then((value) => value ? finish(null, value) : finish(new Error('Google reCAPTCHA v3 не выдала токен. Попробуй ещё раз.')))
.catch(() => finish(new Error('Не удалось пройти Google reCAPTCHA v3. Проверь ключи и попробуй ещё раз.')));
}} catch (err) {{
finish(new Error('Не удалось запустить Google reCAPTCHA v3. Проверь ключи и попробуй ещё раз.'));
}}
}});
}} catch (err) {{
finish(new Error('Не удалось загрузить Google reCAPTCHA v3. Попробуй ещё раз.'));
}}
}};
execute();
}});
tokenField.value = token;
}}
function setActiveAuthTab(name) {{
const activeTab = name === 'quick' ? 'quick' : 'password';
authTabButtons.forEach((button) => {{
@@ -13289,16 +13426,18 @@ if (passwordLoginForm) {{
hubOtp.setCustomValidity('');
}}
if (passwordLoginForm.reportValidity && !passwordLoginForm.reportValidity()) return;
if (!window.FormData || !window.fetch || !window.AbortController) {{
passwordLoginForm.submit();
return;
}}
loginSubmitInFlight = true;
if (passwordLoginSubmitBtn) passwordLoginSubmitBtn.disabled = true;
setLoginRuntimeStatus('Проверяю вход и сохраняю сессию...', 'info');
const controller = new AbortController();
const timeoutId = window.setTimeout(() => controller.abort(), 20000);
let timeoutId = null;
try {{
await prepareLoginRecaptcha();
if (!window.FormData || !window.fetch || !window.AbortController) {{
passwordLoginForm.submit();
return;
}}
setLoginRuntimeStatus('Проверяю вход и сохраняю сессию...', 'info');
const controller = new AbortController();
timeoutId = window.setTimeout(() => controller.abort(), 20000);
const response = await fetch(passwordLoginForm.action || '/login', {{
method: 'POST',
body: new FormData(passwordLoginForm),
@@ -13342,6 +13481,11 @@ if (passwordLoginForm) {{
setLoginRuntimeStatus(message, 'bad');
}} finally {{
window.clearTimeout(timeoutId);
const tokenField = passwordLoginForm.querySelector('[data-recaptcha-v3-site-key]');
if (tokenField) tokenField.value = '';
if (!tokenField && window.grecaptcha && typeof window.grecaptcha.reset === 'function') {{
try {{ window.grecaptcha.reset(); }} catch (err) {{ /* Widget may still be loading. */ }}
}}
loginSubmitInFlight = false;
if (passwordLoginSubmitBtn) passwordLoginSubmitBtn.disabled = false;
}}
@@ -13646,7 +13790,7 @@ def login_html(error=""):
auth = normalize_auth_state(load_auth())
page = _base_login_html(error)
state = effective_captcha_state(auth)
if state.get("effective_mode") != CAPTCHA_MODE_RECAPTCHA:
if state.get("effective_mode") not in CAPTCHA_RECAPTCHA_MODES:
return page
replacement = modern_login_captcha_html(auth)
page, count = re.subn(
@@ -13996,7 +14140,7 @@ class Handler(BaseHTTPRequestHandler):
raise ValueError("incomplete request body")
return body
def read_payload(self):
def read_payload(self, *, keep_blank_values=False):
body = self.read_body()
ctype = self.headers.get("Content-Type", "")
if "application/json" in ctype:
@@ -14027,7 +14171,7 @@ class Handler(BaseHTTPRequestHandler):
continue
payload[name] = raw.decode(part.get_content_charset() or "utf-8", errors="replace")
return payload
parsed = urllib.parse.parse_qs(body.decode("utf-8"))
parsed = urllib.parse.parse_qs(body.decode("utf-8"), keep_blank_values=keep_blank_values)
return {k: v[-1] for k, v in parsed.items()}
def session_cookie(self, token):
@@ -14096,7 +14240,7 @@ class Handler(BaseHTTPRequestHandler):
def verify_login_captcha(self, payload, auth=None):
auth = normalize_auth_state(auth or load_auth())
state = effective_captcha_state(auth)
if state.get("effective_mode") == CAPTCHA_MODE_RECAPTCHA:
if state.get("effective_mode") in CAPTCHA_RECAPTCHA_MODES:
token = (
(payload or {}).get("g-recaptcha-response")
or (payload or {}).get("recaptcha_token")
@@ -14107,6 +14251,8 @@ class Handler(BaseHTTPRequestHandler):
token,
remote_ip=self.client_ip(),
expected_hostname=self.request_host_name(),
expected_action=RECAPTCHA_V3_ACTION if state["effective_mode"] == CAPTCHA_MODE_RECAPTCHA_V3 else "",
min_score=state["min_score"],
)
captcha_token = (payload or {}).get("captcha_token", "")
captcha_answer = (payload or {}).get("captcha_answer", "")
@@ -14464,7 +14610,7 @@ a{{display:inline-flex;margin-top:18px;color:#93c5fd}}
self.send_text(200, "Доступ к Hub обновлен")
def update_auth(self):
payload = self.read_payload()
payload = self.read_payload(keep_blank_values=True)
auth = normalize_auth_state(load_auth())
current_password = payload.get("current_password", "")
if not verify_login(auth.get("username", ""), current_password):
@@ -14473,9 +14619,22 @@ a{{display:inline-flex;margin-top:18px;color:#93c5fd}}
username = payload.get("username", auth.get("username", "admin"))
new_password = payload.get("password", "")
confirm = payload.get("password_confirm", "")
captcha_mode = sanitize_captcha_mode(payload.get("captcha_mode"))
captcha_site_key = str(payload.get("captcha_site_key") or "").strip()
captcha_secret_key = str(payload.get("captcha_secret_key") or "").strip()
previous_captcha = sanitize_captcha_state(auth.get("captcha"))
captcha_mode = sanitize_captcha_mode(payload.get("captcha_mode", previous_captcha["mode"]))
same_captcha_mode = captcha_mode == previous_captcha["mode"]
captcha_site_key = str(payload.get("captcha_site_key", previous_captcha["site_key"] if same_captcha_mode else "") or "").strip()
captcha_secret_key = str(payload.get("captcha_secret_key", previous_captcha["secret_key"] if same_captcha_mode else "") or "").strip()
captcha_min_score = previous_captcha["min_score"] if same_captcha_mode else RECAPTCHA_V3_MIN_SCORE
if captcha_mode == CAPTCHA_MODE_DIGITS:
captcha_site_key = ""
captcha_secret_key = ""
captcha_min_score = RECAPTCHA_V3_MIN_SCORE
if captcha_mode == CAPTCHA_MODE_RECAPTCHA_V3:
try:
captcha_min_score = parse_recaptcha_score(payload.get("captcha_min_score", captcha_min_score))
except ValueError as exc:
self.send_text(400, str(exc))
return
if new_password:
if new_password != confirm:
self.send_text(400, "Новый пароль и повтор не совпадают")
@@ -14483,8 +14642,9 @@ a{{display:inline-flex;margin-top:18px;color:#93c5fd}}
if len(new_password) < MIN_PASSWORD_LENGTH:
self.send_text(400, f"Новый пароль должен быть минимум {MIN_PASSWORD_LENGTH} символа")
return
if captcha_mode == CAPTCHA_MODE_RECAPTCHA and not (captcha_site_key and captcha_secret_key):
self.send_text(400, "Для Google reCAPTCHA v2 Checkbox нужны Site Key и Secret Key")
if captcha_mode in CAPTCHA_RECAPTCHA_MODES and not (captcha_site_key and captcha_secret_key):
version = "v3" if captcha_mode == CAPTCHA_MODE_RECAPTCHA_V3 else "v2 Checkbox"
self.send_text(400, f"Для Google reCAPTCHA {version} нужны Site Key и Secret Key")
return
auth["username"] = clean_username(username)
if new_password:
@@ -14494,6 +14654,7 @@ a{{display:inline-flex;margin-top:18px;color:#93c5fd}}
"mode": captcha_mode,
"site_key": captcha_site_key,
"secret_key": captcha_secret_key,
"min_score": captcha_min_score,
}
)
auth["updated_at"] = now_ts()