Config manager now ensures configs, as I transition away from connection_enable having all responsibility. Also updating locations now triggers respawn

This commit is contained in:
SimplifiedPrivacy 2026-11-08 15:20:21 -05:00
parent b11625f1e8
commit 37fae8a116
7 changed files with 163 additions and 23 deletions

View file

@ -26,21 +26,6 @@ PROTOCOL_CHOICES = {
ProfileType.SESSION: SESSION_CHOICES ProfileType.SESSION: SESSION_CHOICES
} }
CONFIG_NAME = {
ProtocolChoice.WIREGUARD: "wg.conf",
ProtocolChoice.TOR: "proxy.json",
ProtocolChoice.SOCK5_PROXY: "proxy.json",
ProtocolChoice.HYSTERIA2: "proxy.json",
ProtocolChoice.VLESS: "proxy.json"
}
SYSTEM_WIDE_BACKUP_CONFIG_NAME = {
ProtocolChoice.WIREGUARD: "wg.conf.bak",
ProtocolChoice.HYSTERIA2: "proxy.json.bak",
ProtocolChoice.VLESS: "proxy.json.bak"
}
@dataclass_json @dataclass_json
@dataclass @dataclass
class BaseProfile(ABC): class BaseProfile(ABC):

View file

@ -0,0 +1,13 @@
class ObserverStash:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(ObserverStash, cls).__new__(cls)
cls._instance.connection_observer = None
cls._instance.ticket_observer = None
cls._instance.profile_observer = None
return cls._instance

View file

@ -1,12 +1,44 @@
from core.services.config_tools.manage_sudo_configs import remove_sudo_config from core.services.WebServiceApiService import WebServiceApiService
from core.observers.ConnectionObserver import ConnectionObserver
from core.controllers.ConnectionController import ConnectionController
from core.models.enum_models import ProtocolChoice
from core.services.config_tools.wireguard_configs import register_wireguard_session
from core.services.profiles.model_manipulator import get_config_path from core.services.profiles.model_manipulator import get_config_path
from core.models.BaseProfile import BaseProfile as Profile from core.models.BaseProfile import BaseProfile as Profile
from core.models.BaseProfile import ProfileType, CONFIG_NAME, SYSTEM_WIDE_BACKUP_CONFIG_NAME from core.models.BaseProfile import ProfileType
from core.utils.run_commands import run_generic_command
from core.models.system.SystemProfile import SystemProfile
from core.utils.basic_operations.does_file_exist import does_file_exist
from core.models.Result import Result, ResultError from core.models.Result import Result, ResultError
from core.errors.logger import logger from core.errors.logger import logger
from typing import Optional
from pathlib import Path from pathlib import Path
NEEDS_SOCK5_PROXY_CONFIG = [ProtocolChoice.TOR, ProtocolChoice.SOCK5_PROXY]
CONFIG_NAME = {
ProtocolChoice.WIREGUARD: "wg.conf",
ProtocolChoice.TOR: "proxy.json",
ProtocolChoice.SOCK5_PROXY: "proxy.json",
ProtocolChoice.HYSTERIA2: "proxy.json",
ProtocolChoice.VLESS: "proxy.json"
}
SYSTEM_WIDE_BACKUP_CONFIG_NAME = {
ProtocolChoice.WIREGUARD: "wg.conf.bak",
ProtocolChoice.HYSTERIA2: "proxy.json.bak",
ProtocolChoice.VLESS: "proxy.json.bak"
}
def uses_proxy_configuration(profile: Profile) -> bool:
"""Does the profile use an unencrypted socks5 proxy?"""
if profile.protocol in NEEDS_SOCK5_PROXY_CONFIG:
return True
return profile.connection.masked
def delete_connection_configs(profile: Profile) -> Result: def delete_connection_configs(profile: Profile) -> Result:
"""Delete both connection configuration and backup connection config files for a given profile.""" """Delete both connection configuration and backup connection config files for a given profile."""
@ -31,4 +63,70 @@ def delete_connection_configs(profile: Profile) -> Result:
return removed.wrap("Unable to delete the systemwide configs behind sudo protection.") return removed.wrap("Unable to delete the systemwide configs behind sudo protection.")
logger.info("Deleted the previous connection configuration") logger.info("Deleted the previous connection configuration")
return Result(valid=True) return Result(valid=True)
def ensure_proxy_configured(
profile: Profile,
connection_observer: Optional[ConnectionObserver],
) -> Result:
"""Setup UNencrypted regular socks5 proxy config if needed."""
if profile.has_proxy_configuration():
return Result(valid=True)
logger.info("You need a new proxy configuration")
if not profile.has_subscription():
error_msg = "There is no subscription to request a Socks5 proxy config"
logger.error(error_msg)
return Result(valid=False, error_type=ResultError.SUBSCRIPTION, message=error_msg)
logger.info("Getting a proxy config from web service..")
proxy_config = ConnectionController.with_preferred_connection(
profile.subscription.billing_code,
task=WebServiceApiService.get_proxy_configuration,
connection_observer=connection_observer
)
if proxy_config is None:
return Result(valid=False, error_type=ResultError.SUBSCRIPTION, message="Failed to fetch the Socks5 proxy config, likely due to a invalid subscription")
profile.attach_proxy_configuration(proxy_config)
return Result(valid=True)
def ensure_wireguard_configured(
profile: Profile,
connection_observer: Optional[ConnectionObserver]
):
"""Setup WireGuard config if needed."""
# Already has one
if profile.has_wireguard_configuration():
return Result(valid=True)
logger.info("Profile does NOT have WG keys and it needs it. Registering a NEW wg session..")
registry_result = register_wireguard_session(profile, connection_observer=connection_observer)
logger.info(f"registry_result is {registry_result}")
if not registry_result.valid:
return registry_result.wrap("Unable to register WG session.")
return Result(valid=True)
def network_config_ready(profile: Profile, connection_observer: Optional[ConnectionObserver]) -> Result:
"""Confirms the network config is ready, and fetches one from the API if it's not."""
if profile.protocol == ProtocolChoice.WIREGUARD:
wireguard_result = ensure_wireguard_configured(profile, connection_observer)
if not wireguard_result.valid:
return wireguard_result.wrap("Unable to get WG config.")
if uses_proxy_configuration(profile):
proxy_result = ensure_proxy_configured(profile, connection_observer)
if not proxy_result.valid:
return proxy_result.wrap("Unable to get socks5 proxy config.")
return Result(valid=True)

View file

@ -1,3 +1,4 @@
from core.services.subscriptions.subscriptions import activate_subscription
from core.models.enum_models import ProtocolChoice, SINGBOX_PROTOCOLS from core.models.enum_models import ProtocolChoice, SINGBOX_PROTOCOLS
from core.services.networking.systemwide.encrypted_proxy.launch_proxy import launch_encrypted_proxy from core.services.networking.systemwide.encrypted_proxy.launch_proxy import launch_encrypted_proxy
# from core.services.networking.general_connection_tools.location_evaluation import check_if_location_is_up # from core.services.networking.general_connection_tools.location_evaluation import check_if_location_is_up

View file

@ -2,7 +2,7 @@ from core.errors.pydantic_errors import get_failed_validation_fields
from core.services.networking.tor_tools import ports from core.services.networking.tor_tools import ports
from core.services.networking.httpx import connect from core.services.networking.httpx import connect
from core.models.enum_models import ProtocolChoice from core.models.enum_models import ProtocolChoice
from core.models.BaseProfile import SYSTEM_WIDE_BACKUP_CONFIG_NAME from core.services.config_tools.config_manager import SYSTEM_WIDE_BACKUP_CONFIG_NAME
from core.services.networking.systemwide.encrypted_proxy.hysteria_config import build_hysteria_config from core.services.networking.systemwide.encrypted_proxy.hysteria_config import build_hysteria_config
from core.services.networking.systemwide.encrypted_proxy.vless_config import build_vless_config, parse_vless_link from core.services.networking.systemwide.encrypted_proxy.vless_config import build_vless_config, parse_vless_link
from core.utils.basic_operations.write_or_read_from_json import write_json_to_file from core.utils.basic_operations.write_or_read_from_json import write_json_to_file

View file

@ -1,3 +1,4 @@
from core.services.config_tools.config_manager import network_config_ready
from core.infrastructure.state_management.kill_processes import kill_all_associated_processes from core.infrastructure.state_management.kill_processes import kill_all_associated_processes
from core.models.enum_models import ProtocolChoice from core.models.enum_models import ProtocolChoice
from core.services.apps.launch_app import orchestrate_app_launch from core.services.apps.launch_app import orchestrate_app_launch
@ -103,11 +104,18 @@ def enable_session_profile(
if not application_version.is_installed(): if not application_version.is_installed():
ApplicationVersionController.install(application_version, application_version_observer=application_version_observer, connection_observer=connection_observer) ApplicationVersionController.install(application_version, application_version_observer=application_version_observer, connection_observer=connection_observer)
#-----------------------------------
# NETWORK CONFIG
#-----------------------------------
config_ready = network_config_ready(profile=profile, connection_observer=connection_observer)
if not config_ready.valid:
return config_ready.wrap("Unable to enable the profile, because it can't get a config.")
print("Got networking config.")
#----------------------------------- #-----------------------------------
# NETWORK CONNECTION # NETWORK CONNECTION
#----------------------------------- #-----------------------------------
try: try:
print("Starting session networking function")
network_result = start_session_networking(profile, ignore=ignore, connection_observer=connection_observer) network_result = start_session_networking(profile, ignore=ignore, connection_observer=connection_observer)
print(f"Completed start_session_networking function with this result: {network_result}") print(f"Completed start_session_networking function with this result: {network_result}")
except EndpointVerificationError: except EndpointVerificationError:

View file

@ -1,3 +1,4 @@
from core.observers.ObserverStash import ObserverStash
from core.errors.logger import logger from core.errors.logger import logger
from core.models.Result import Result, ResultError from core.models.Result import Result, ResultError
from core.services.config_tools.manage_sudo_configs import remove_sudo_config from core.services.config_tools.manage_sudo_configs import remove_sudo_config
@ -13,6 +14,7 @@ from core.models.orm_models.Location import Location
from core.models.orm_calls.application_version_calls import get_application_by_id from core.models.orm_calls.application_version_calls import get_application_by_id
from core.models.orm_calls.location_calls import get_profile_location_data_by_id from core.models.orm_calls.location_calls import get_profile_location_data_by_id
from core.services.profiles.create_objects import create_new_profile_object from core.services.profiles.create_objects import create_new_profile_object
from core.services.assassin.ticket_respawn import respawn_profile
from core.utils.dict_tools import get_sorted_keys from core.utils.dict_tools import get_sorted_keys
def finally_save_it(profile: Profile) -> Result: def finally_save_it(profile: Profile) -> Result:
@ -235,21 +237,54 @@ def change_protocol(profile: Profile, new_value: str) -> Result:
def change_location(profile: Profile, new_value: int) -> Result: def change_location(profile: Profile, new_value: int) -> Result:
""" """
Change a profile's location for the in memory object, and return it. Change a profile's location for the in memory object, and return it.
This does NOT save it to disk. Changes the connection configs and respawns the ticket. But this does NOT save the profile to disk.
""" """
new_location = get_profile_location_data_by_id(new_value)
####################################
# COMPATABILITY CHECKS
####################################
new_location = get_profile_location_data_by_id(new_value)
pre_existing_protocol = profile.protocol pre_existing_protocol = profile.protocol
if not new_location.supports_protocol(pre_existing_protocol): if not new_location.supports_protocol(pre_existing_protocol):
return Result(valid=False, message=f"The {new_location.name} location doesn't currently support the {str(pre_existing_protocol)} protocol", error_type=ResultError.WRONG_LOCATION) return Result(valid=False, message=f"The {new_location.name} location doesn't currently support the {str(pre_existing_protocol)} protocol", error_type=ResultError.WRONG_LOCATION)
####################################
# CONNECTION CONFIGS
####################################
if profile.type == ProfileType.SYSTEM:
removed = remove_sudo_config(profile)
if not removed.valid:
return removed.wrap("Unable to change location due to sudo permission configs.")
if pre_existing_protocol == ProtocolChoice.WIREGUARD: if pre_existing_protocol == ProtocolChoice.WIREGUARD:
profile.delete_wireguard_configuration() # for all polymorphic types. profile.delete_wireguard_configuration() # for all polymorphic types.
profile.location = new_location ####################################
# RESPAWN TICKET
####################################
which_ticket = profile.ticket
if which_ticket:
observer_stash = ObserverStash()
respawn_result = respawn_profile(
profile=profile,
ticket_observer=observer_stash.ticket_observer,
connection_observer=observer_stash.connection_observer
)
if which_ticket and not respawn_result.valid:
logger.error(f"Unable to respawn the ticket. {respawn_result.message} {respawn_result.error_type}")
####################################
# REGARDLESS OF TICKET, SUB & LOCATION
####################################
# Subscription gets wiped on a location change, and is outside location ORM # Subscription gets wiped on a location change, and is outside location ORM
profile.subscription = None profile.subscription = None
profile.ticket = None
# finally set location:
profile.location = new_location
return Result(valid=True, data=profile) return Result(valid=True, data=profile)