Add configurable Deck GUI host allowlist with backup and restore
This commit is contained in:
1 parent
b5f161531e
commit
0966abf1b5
14 files changed
+237
-17
No files matched your search
@@ -0,0 +1,48 @@
|
||||
"""Explicit HTTP Host aliases; never URLs, wildcards, or client IP access rules."""
|
||||
import ipaddress
|
||||
import re
|
||||
|
||||
|
||||
def normalize_host(value):
|
||||
if not isinstance(value, str) or not value or len(value) > 300 or re.search(r'[\s/@?#\\]', value):
|
||||
raise ValueError('Hostnamen ohne Protokoll, Pfad oder Leerzeichen eingeben.')
|
||||
port = None
|
||||
if value.startswith('['):
|
||||
match = re.fullmatch(r'\[([^]]+)\](?::([0-9]+))?', value)
|
||||
if not match:
|
||||
raise ValueError('Ungültiger IPv6-Host.')
|
||||
host = '[' + str(ipaddress.IPv6Address(match[1])) + ']'
|
||||
port = match[2]
|
||||
else:
|
||||
parts = value.split(':')
|
||||
if len(parts) > 2:
|
||||
raise ValueError('IPv6-Adressen in eckigen Klammern eingeben.')
|
||||
if len(parts) == 2:
|
||||
port = parts[1]
|
||||
try:
|
||||
host = parts[0].encode('idna').decode('ascii').lower()
|
||||
except UnicodeError:
|
||||
raise ValueError('Ungültiger Hostname.') from None
|
||||
if len(host) > 253 or not all(re.fullmatch(r'[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?', label) for label in host.split('.')):
|
||||
raise ValueError('Ungültiger Hostname; Platzhalter sind nicht erlaubt.')
|
||||
if port is not None:
|
||||
if not port.isascii() or not port.isdigit() or not 1 <= int(port) <= 65535:
|
||||
raise ValueError('Ungültiger Port.')
|
||||
port = int(port)
|
||||
# Standard HTTP(S) ports identify the same browser-facing host.
|
||||
return host + (':' + str(port) if port not in (None, 80, 443) else '')
|
||||
|
||||
|
||||
def validate_hosts(values):
|
||||
if not isinstance(values, list) or len(values) > 64:
|
||||
raise ValueError('Höchstens 64 erlaubte Hostnamen als Liste eingeben.')
|
||||
return list(dict.fromkeys(normalize_host(value) for value in values))
|
||||
|
||||
|
||||
def host_allowed(value, expected, aliases):
|
||||
if value == expected:
|
||||
return True
|
||||
try:
|
||||
return normalize_host(value) in aliases
|
||||
except ValueError:
|
||||
return False
|
||||
@@ -12,7 +12,7 @@ import sys
|
||||
|
||||
NAME = 'athena-deck-network'
|
||||
BASE = Path('/opt/athena-deck')
|
||||
FILES = {'ltx_original_runtime.py','ltx_original_entry.py','video_original.py','ltx-original-ui.js','deploy/ltx-original-requirements.lock','backup.py','backup_codec.py','backup-ui.js','deploy/docker_backup.py','video_comfy.py','video_comfy_node.py','video_comfy_proxy.py','image_upload.py','prompt_enhancer.py','prompt_enhancer_worker.py','audio_policy.py','dashboard_data.py','dashboard_history.py','dashboard-ui.js','dashboard.css','themes.css','deploy/tts-requirements.lock','stt.py','stt-ui.js','api_compat.py','execution_setup.py','tts_runtime.py','tts_test.py','tts_worker.py','tts-ui.js','auto_test.py','auto-test-ui.js','chat_test.py','chat-test-ui.js','endpoint.py','inference.py','endpoint-ui.js','image_runtime.py','image_encoder_node.py','docker_support.py','docker-ui.js','deploy/image-requirements.lock','image_test.py','image-test-ui.js','profiles.py','profiles-ui.js','capacity.py','runtime.py', 'runtime-ui.js', 'video.py','video_proxy.py','video-ui.js','catalog.py','hub_auth.py', 'catalog-ui.js', 'studio.js', 'auth.py', 'access-ui.js', 'server.py', 'collect_hardware.py', 'index.html', 'app.js', 'style.css', 'network-ui.js', 'login.html', 'login.js', 'network/__init__.py', 'network/config.py', 'network/policy.py', 'network/rpc.py', 'network/agent.py', 'network/client.py', 'network/Dockerfile', '.dockerignore'}
|
||||
FILES = {'ltx_original_runtime.py','ltx_original_entry.py','video_original.py','ltx-original-ui.js','deploy/ltx-original-requirements.lock','backup.py','backup_codec.py','backup-ui.js','deploy/docker_backup.py','video_comfy.py','video_comfy_node.py','video_comfy_proxy.py','image_upload.py','prompt_enhancer.py','prompt_enhancer_worker.py','audio_policy.py','dashboard_data.py','dashboard_history.py','dashboard-ui.js','dashboard.css','themes.css','deploy/tts-requirements.lock','stt.py','stt-ui.js','api_compat.py','execution_setup.py','tts_runtime.py','tts_test.py','tts_worker.py','tts-ui.js','auto_test.py','auto-test-ui.js','chat_test.py','chat-test-ui.js','endpoint.py','inference.py','endpoint-ui.js','image_runtime.py','image_encoder_node.py','docker_support.py','docker-ui.js','deploy/image-requirements.lock','image_test.py','image-test-ui.js','profiles.py','profiles-ui.js','capacity.py','runtime.py', 'runtime-ui.js', 'video.py','video_proxy.py','video-ui.js','catalog.py','hub_auth.py', 'catalog-ui.js', 'studio.js', 'auth.py', 'access-ui.js', 'server.py', 'collect_hardware.py', 'index.html', 'app.js', 'style.css', 'network-ui.js', 'login.html', 'login.js', 'network/__init__.py', 'network/config.py','network/hosts.py', 'network/policy.py', 'network/rpc.py', 'network/agent.py', 'network/client.py', 'network/Dockerfile', '.dockerignore'}
|
||||
|
||||
def run(*args, **kwargs):
|
||||
return subprocess.run(args, capture_output=True, timeout=600, **kwargs)
|
||||
|
||||
+14
-5
@@ -19,6 +19,7 @@ import threading
|
||||
import time
|
||||
from network.config import parse_config, wireguard_text
|
||||
from network.policy import Policy
|
||||
from network.hosts import validate_hosts, host_allowed
|
||||
|
||||
INTERFACE='wgdeck0'
|
||||
TABLE='51826'
|
||||
@@ -40,6 +41,7 @@ class Manager:
|
||||
self.root=Path(state);self.root.mkdir(mode=0o700,exist_ok=True);self.settings=policy
|
||||
self.lock=threading.RLock();self.listeners=[];self.enabled=False;self.error=None
|
||||
self.policy=Policy(mode=self.read('mode.json','lan'),persist=lambda v:save(self.root/'mode.json',v))
|
||||
self.allowed_hosts=validate_hosts(self.read('allowed-hosts.json',[]))
|
||||
token=self.root/'proxy-token'
|
||||
if not token.exists():token.write_text(secrets.token_hex(32));token.chmod(0o600)
|
||||
self.token=token.read_text().strip()
|
||||
@@ -57,7 +59,7 @@ class Manager:
|
||||
return latest>0 and 0<=time.time()-latest<180,latest
|
||||
def status(self,ingress='management'):
|
||||
connected,latest=self.connected();c=self.config()
|
||||
return dict(installed=True,install_supported=False,backend='native-systemd',interface=INTERFACE,enabled=self.enabled,configured=bool(c),state='connected' if connected else 'connecting' if self.enabled else 'disabled',latest_handshake=latest,ingress=ingress,lan_url='http://'+self.settings['lan_address']+':'+str(self.settings['gui_port']),tunnel_url='http://'+c['address']+':'+str(self.settings['gui_port']) if c else None,warnings=c['warnings'] if c else [],error=self.error,**self.policy.status())
|
||||
return dict(installed=True,install_supported=False,backend='native-systemd',interface=INTERFACE,allowed_hosts=self.allowed_hosts[:],enabled=self.enabled,configured=bool(c),state='connected' if connected else 'connecting' if self.enabled else 'disabled',latest_handshake=latest,ingress=ingress,lan_url='http://'+self.settings['lan_address']+':'+str(self.settings['gui_port']),tunnel_url='http://'+c['address']+':'+str(self.settings['gui_port']) if c else None,warnings=c['warnings'] if c else [],error=self.error,**self.policy.status())
|
||||
def connect(self):
|
||||
if self.enabled:return
|
||||
c=self.config()
|
||||
@@ -117,7 +119,10 @@ class Manager:
|
||||
if secrets.compare_digest(str(data.get('proxy_token','')),self.token) and data.get('ingress') in ('lan','tunnel'):ingress=data['ingress']
|
||||
with self.lock:
|
||||
if action=='status':return self.status(ingress)
|
||||
if action=='import':
|
||||
if action=='hosts':
|
||||
hosts=validate_hosts(data.get('allowed_hosts'))
|
||||
save(self.root/'allowed-hosts.json',hosts);self.allowed_hosts=hosts
|
||||
elif action=='import':
|
||||
if self.enabled or self.policy.mode!='lan' or self.policy.pending:raise ValueError('Import nur bei deaktiviertem Tunnel im bestätigten lokalen Modus.')
|
||||
text=data.get('config');parse_config(text,native=True);save(self.root/'config.json',text)
|
||||
elif action=='connect':self.connect()
|
||||
@@ -128,14 +133,16 @@ class Manager:
|
||||
elif action=='delete':
|
||||
if self.enabled or self.policy.mode!='lan' or self.policy.pending:raise ValueError('Tunnel zuerst deaktivieren und lokalen Modus bestätigen.')
|
||||
(self.root/'config.json').unlink(missing_ok=True)
|
||||
elif action=='backup-export':return dict(config=self.read('config.json'),enabled=self.enabled,mode=self.policy.mode)
|
||||
elif action=='backup-export':return dict(config=self.read('config.json'),enabled=self.enabled,mode=self.policy.mode,allowed_hosts=self.allowed_hosts[:])
|
||||
elif action=='backup-restore':
|
||||
b=data.get('backup',{})
|
||||
if set(b)!={'config','enabled','mode'} or type(b['enabled']) is not bool or b['mode'] not in Policy.MODES:raise ValueError('Ungültiger Netzwerkstand.')
|
||||
if set(b)-{'config','enabled','mode','allowed_hosts'} or not {'config','enabled','mode'}<=set(b) or type(b['enabled']) is not bool or b['mode'] not in Policy.MODES:raise ValueError('Ungültiger Netzwerkstand.')
|
||||
hosts=validate_hosts(b.get('allowed_hosts',[]))
|
||||
if self.enabled or self.policy.mode!='lan':raise ValueError('Restore benötigt deaktivierten Tunnel im lokalen Modus.')
|
||||
if b['config']:parse_config(b['config'],native=True);save(self.root/'config.json',b['config'])
|
||||
if b['enabled']:self.connect()
|
||||
if b['mode']!='lan':self.policy.propose(b['mode'],self.connected()[0])
|
||||
save(self.root/'allowed-hosts.json',hosts);self.allowed_hosts=hosts
|
||||
else:raise ValueError('Unbekannte Netzwerkaktion.')
|
||||
return self.status(ingress)
|
||||
|
||||
@@ -177,7 +184,9 @@ class GUI(BaseHTTPRequestHandler):
|
||||
def forward(self):
|
||||
if not self.server.allowed():self.send_error(403,'Network access disabled');return
|
||||
expected=('['+self.server.bind_address+']' if ':' in self.server.bind_address else self.server.bind_address)+':'+str(self.server.port)
|
||||
if self.headers.get('Host')!=expected:self.send_error(403,'Host rejected');return
|
||||
with self.server.manager.lock:
|
||||
accepted=host_allowed(self.headers.get('Host'),expected,self.server.manager.allowed_hosts)
|
||||
if not accepted:self.send_error(403,'Host rejected');return
|
||||
try:
|
||||
if self.headers.get('Transfer-Encoding'):raise ValueError()
|
||||
length=int(self.headers.get('Content-Length','0'))
|
||||
|
||||
Reference in new issue
Block a user