diff --git a/.gitignore b/.gitignore index dba52881..04b5e93e 100644 --- a/.gitignore +++ b/.gitignore @@ -14,4 +14,13 @@ identifier.sqlite obfuscated.sb3 .pytest_cache .ruff_cache + +.coverage +certfile.pem +coverage.xml +keyfile.pem +.test/test.py +.test/teststststs.py +.test/ws_client_test.py +tests/test_tw_cloud_debug_compliance.py .vscode diff --git a/.test/server.py b/.test/server.py new file mode 100644 index 00000000..6d7f8d3d --- /dev/null +++ b/.test/server.py @@ -0,0 +1,57 @@ +import scratchattach as sa + +from rich.traceback import install + +from scratchattach.cloud.cloud import CustomCloud + +install(show_locals=True) + +server_ip = '127.0.0.1' +ws_server_port = 8080 +wss_server_port = 8765 +project_id=["108566337"] + +ws_server = sa.init_cloud_server(server_ip, + ws_server_port, + length_limit=65536, + allow_non_numeric=True, + whitelisted_projects=project_id, + allow_nonscratch_names=True, + blocked_ips=None, + sync_players=True, + log_var_sets=True +) + +wss_server = sa.init_ssl_cloud_server(server_ip, + wss_server_port, + length_limit=65536, + allow_non_numeric=True, + whitelisted_projects=project_id, + allow_nonscratch_names=True, + blocked_ips=None, + sync_players=True, + log_var_sets=True, + certfile="certfile.pem", + keyfile="keyfile.pem" +) + + + +ws_server.start() + +wss_server.start() + +cloud = CustomCloud(project_id=project_id[0], + cloud_host=f"wss://{server_ip}:{wss_server_port}", + username = "Boss_1s", + length_limit = None, + allow_non_numeric = True, + _session = None, + header = None, + cookie = None, + origin = None, + print_connect_messages = True) + +events = cloud.events() + +events.start() diff --git a/scratchattach/__init__.py b/scratchattach/__init__.py index a2329989..acdcc8ec 100644 --- a/scratchattach/__init__.py +++ b/scratchattach/__init__.py @@ -1,15 +1,33 @@ -from .cloud.cloud import CustomCloud, ScratchCloud, TwCloud, get_cloud, get_scratch_cloud, get_tw_cloud +from .cloud.cloud import ( + CustomCloud, + ScratchCloud, + TwCloud, + get_cloud, + get_scratch_cloud, + get_tw_cloud, +) from .cloud._base import BaseCloud, AnyCloud -from .eventhandlers.cloud_server import init_cloud_server -from .eventhandlers._base import BaseEventHandler +from .eventhandlers.cloud_server import ( + init_cloud_server, + init_ssl_cloud_server, + TwCloudSocket, + TwCloudServer, + TwSSLCloudServer, +) +from .eventhandlers._base import BaseEventHandler, BaseCloudServer from .eventhandlers.filterbot import Filterbot, HardFilter, SoftFilter, SpamFilter from .eventhandlers.cloud_storage import Database from .eventhandlers.combine import MultiEventHandler from .other.other_apis import * - -# from .other.project_json_capabilities import ProjectBody, get_empty_project_pb, get_pb_from_dict, read_sb3_file, download_asset +# from .other.project_json_capabilities import ( +# ProjectBody, +# get_empty_project_pb, +# get_pb_from_dict, +# read_sb3_file, +# download_asset, +# ) from .utils.encoder import Encoding from .utils.enums import Languages, TTSVoices from .utils.exceptions import ( @@ -27,11 +45,29 @@ from .site.cloud_activity import CloudActivity from .site.forum import ForumPost, ForumTopic, get_topic, get_topic_list, youtube_link_to_scratch from .site.project import Project, get_project, search_projects, explore_projects -from .site.session import Session, login, login_by_id, login_by_session_string, login_by_io, login_by_file, login_from_browser +from .site.session import ( + Session, + login, + login_by_id, + login_by_session_string, + login_by_io, + login_by_file, + login_from_browser, +) from .site.studio import Studio, get_studio, search_studios, explore_studios from .site.classroom import Classroom, get_classroom from .site.user import User, get_user, Rank from .site._base import BaseSiteComponent -from .site.browser_cookies import Browser, ANY, FIREFOX, CHROME, CHROMIUM, VIVALDI, EDGE, EDGE_DEV, SAFARI +from .site.browser_cookies import ( + Browser, + ANY, + FIREFOX, + CHROME, + CHROMIUM, + VIVALDI, + EDGE, + EDGE_DEV, + SAFARI, +) from . import editor diff --git a/scratchattach/cloud/_base.py b/scratchattach/cloud/_base.py index 112d7535..37b77f4f 100644 --- a/scratchattach/cloud/_base.py +++ b/scratchattach/cloud/_base.py @@ -9,6 +9,7 @@ from abc import ABC, abstractmethod, ABCMeta from threading import Lock from collections.abc import Iterator +from rich import print from scratchattach.cloud import cloud as cloud_module @@ -199,7 +200,7 @@ def __init__(self, cloud: BaseCloud): except exceptions.CloudConnectionError: warnings.warn("Initial cloud connection attempt failed, retrying...", exceptions.UnexpectedWebsocketEventWarning) self.packets_left = [] - + def wait_before_reconnect(self): if time.time() - self.most_recent_reconnection_time > self.RECENT_RECONNECT_TIME_DELTA: self.recent_reconnect_count = 0 @@ -254,10 +255,12 @@ def read(self, amount: int = -1) -> Iterator[dict[str, Any]]: i += 1 yield json.loads(self.packets_left.pop(0)) done = True - except json.JSONDecodeError as e: + except json.JSONDecodeError: # this could happen e.g. when the scratchattach server sends the message # "This server uses @TimMcCool's scratchattach 2.0.0" - warnings.warn(f"Invalid JSON sent from server: {e}") + # print(f"[yellow]Warning: Cloud events handler received invalid JSON.[/]") + # print(f" [b]Data received:[/] \"{self.packets_left}\"") + warnings.warn(f"Cloud events handler received invalid JSON. Data received: {self.packets_left}") except (websocket.WebSocketConnectionClosedException, ssl.SSLWantReadError): self.wait_before_reconnect() self.source_cloud.reconnect() diff --git a/scratchattach/eventhandlers/_base.py b/scratchattach/eventhandlers/_base.py index 4e4236ac..81f9b30e 100644 --- a/scratchattach/eventhandlers/_base.py +++ b/scratchattach/eventhandlers/_base.py @@ -1,14 +1,21 @@ from __future__ import annotations +import json +import time +import ssl from abc import ABC, abstractmethod -from typing import Optional +from typing import Optional, Any from collections import defaultdict from threading import Thread, Event from collections.abc import Callable import traceback +from SimpleWebSocketServer import WebSocket +from rich import print + from scratchattach.utils.requests import requests from scratchattach.utils import exceptions + class BaseEventHandler(ABC): _events: defaultdict[str, list[Callable]] _threaded_events: defaultdict[str, list[Callable]] @@ -41,8 +48,8 @@ def start(self, *, thread=True, ignore_exceptions=True): else: self._thread = None self._updater() - - def call_event(self, event_name, args : list = []): + + def call_event(self, event_name, args: list = []): try: # print(f"Calling for {event_name}...") if event_name in self._threaded_events: @@ -56,20 +63,18 @@ def call_event(self, event_name, args : list = []): func(*args) except Exception as e: if self.ignore_exceptions: - print( - f"Warning: Caught error in event '{event_name}' - Full error below" - ) + print(f"Warning: Caught error in event '{event_name}' - Full error below") try: traceback.print_exc() except Exception: print(e) else: - raise(e) + raise (e) @abstractmethod def _updater(self): pass - + def __del__(self): self.stop() @@ -108,6 +113,7 @@ def event(self, function=None, *, thread=False): """ Decorator function. Adds an event. """ + def inner(function): # called directly if the decorator provides arguments if thread is True: @@ -120,4 +126,240 @@ def inner(function): return inner else: # => the decorator doesn't provide arguments - inner(function) \ No newline at end of file + inner(function) + + +class BaseCloudServer(BaseEventHandler): + """ + Base class for all sa cloud servers. + + If you are developing a custom cloud server with sa, please inherit from this class + and change up the methods as needed. + """ + + hostname: str + "IP address or domain name of the host to bind the server to." + port: int + "Port to bind the server to." + tw_clients: dict[tuple[str, int], dict[str, Any]] + "Dictionary containing client information." + tw_variables: dict[str, dict[str, Any]] + "Dictionary containing existing cloud variables." + allow_non_numeric: bool + "Whether or not non-numeric characters are allowed in cloud variable values." + whitelisted_projects: set[str] | None + "Optional list of whitelisted projects." + length_limit: int | None + "Optional limit on the length of cloud variable values." + allow_nonscratch_names: bool + "Whether or not usernames that do not exist on scratch are allowed." + blocked_ips: list[str] + "List of blocked IP addresses." + sync_players: bool + log_var_sets: bool + + def __init__( + self, + hostname: str, + *, + port: int, + length_limit: int | None = None, + allow_non_numeric: bool = True, + whitelisted_projects: list[Any] | None = None, + allow_nonscratch_names: bool = True, + blocked_ips: list[str] | None = None, + sync_players: bool = True, + log_var_sets: bool = True, + ): + + if blocked_ips is None: + blocked_ips = [] + + BaseEventHandler.__init__(self) + + self.tw_clients = {} # saves connected clients + self.tw_variables = {} # holds cloud variable states + + self.hostname = hostname + self.port = port + + # server config + self.allow_non_numeric = allow_non_numeric + self.whitelisted_projects = ( + {str(i) for i in whitelisted_projects} if whitelisted_projects else None + ) + self.length_limit = length_limit + self.allow_nonscratch_names = allow_nonscratch_names + self.blocked_ips = blocked_ips + self.sync_players = sync_players + self.log_var_sets = log_var_sets + + def check_for_ip_ban(self, client): + if ( + client.address[0] in self.blocked_ips + or client.address[0] + ":" + str(client.address[1]) in self.blocked_ips + or client.address in self.blocked_ips + ): + client.sendMessage("You have been banned from this server") + client.close(4002) + print(f"[yellow]Client {client.address[0]}:{client.address[1]} was forced disconnected "+ + "due to IP ban. [b]If this dosen't look right, remove them from the list.[/][/]") + return True + return False + + def active_projects(self): + only_active = {} + for project_id in self.tw_variables: + if self.active_user_ips(project_id) != []: + only_active[project_id] = self.tw_variables[project_id] + return only_active + + def active_user_names(self, project_id): + return [self.tw_clients[user]["username"] for user in self.active_user_ips(project_id)] + + def active_user_ips(self, project_id: Any): + project_id = str(project_id) + return [ + user + for user in self.tw_clients + if str(self.tw_clients[user]["project_id"]) == project_id + ] + + def get_global_vars(self): + return self.tw_variables + + def get_project_vars(self, project_id: Any): + project_id = str(project_id) + return self.tw_variables.get(project_id, {}) + + def get_var(self, project_id: Any, var_name: str, *, no_prefix: bool = False): + project_id = str(project_id) + if not no_prefix: + var_name = "☁ " + var_name.removeprefix("☁ ") + if project_id in self.tw_variables: + if var_name in self.tw_variables[project_id]: + return self.tw_variables[project_id][var_name] + else: + print(f"[yellow]Warning: Could not find variable {var_name} in project {project_id}![/]") + return None + else: + print(f"[yellow]Warning: Could not find project {project_id}! Are you sure it exists from the server's perspective? Is it whitelisted?[/]") + return None + + def set_global_vars( + self, + data: dict[str, dict[str, Any]], + no_prefix: bool = False, + ): + try: + for project_id, project_data in data.items(): + self.set_project_vars(project_id, project_data, no_prefix=no_prefix) + except Exception as e: # TODO: determine which exception we want to catch specifically + print(f"[red]Internal Error in BaseCloudServer.set_global_vars:[/]", traceback.format_exc()) + + def set_project_vars( + self, + project_id: Any, + data: dict[str, Any], + *, + user: str = "@server", + no_prefix: bool = False, + ): + project_id = str(project_id) + if not no_prefix: + data = {"☁ " + key.removeprefix("☁ "): value for key, value in data.items()} + self.tw_variables[project_id].update(data) + for client in (self.tw_clients[ip]["client"] for ip in self.active_user_ips(project_id)): + try: + client.sendMessage( + "\n".join( + [ + json.dumps( + { + "method": "set", + "project_id": project_id, + "name": varname, + "value": data[varname], + "server": "scratchattach/3", + "timestamp": time.time() * 1000, + "user": user, + } + ) + for varname in data + ] + ) + ) + except Exception as e: # TODO: determine which exceptions we want to catch specifically + print(f"[red]Internal Error in BaseCloudServer.set_project_vars:[/]", traceback.format_exc()) + + def set_var( + self, + project_id: Any, + var_name: str, + value: Any, + *, + user: str = "@server", + skip_forward=None, + no_prefix: bool = False, + ): + if not no_prefix: + var_name = "☁ " + var_name.removeprefix("☁ ") + project_id = str(project_id) + if project_id not in self.tw_variables: + self.tw_variables[project_id] = {} + self.tw_variables[project_id][var_name] = value + + if self.sync_players is True: + for client in ( + self.tw_clients[ip]["client"] for ip in self.active_user_ips(project_id) + ): + if client == skip_forward: + continue + try: + client.sendMessage( + json.dumps( + { + "method": "set", + "project_id": project_id, + "name": var_name, + "value": value, + "timestamp": time.time() * 1000, + "user": user, + } + ) + ) + except Exception as e: # TODO: determine which exceptions we want to catch specifically + print(f"[red]Internal Error in BaseCloudServer.set_var:[/]", traceback.format_exc()) + + def _check_value(self, value): + # Checks if a received cloud value satisfies the server's constraints + if self.length_limit is not None: + if len(str(value)) > self.length_limit: + return False + if self.allow_non_numeric is False: + x = value.replace(".", "") + x = x.replace("-", "") + if not (x.isnumeric() or x == ""): + return False + return True + + def _updater(self): + try: + # Function called when .start() is executed (.start is inherited from BaseEventHandler) + print(f"Serving websocket server: ws://{self.hostname}:{self.port}") + self.serveforever() + except Exception as e: + raise exceptions.WebsocketServerError(str(e)) + + def pause(self): + self.running = False + + def resume(self): + self.running = True + + def stop(self, wait_call_threads: bool = True): + try: + BaseEventHandler.stop(self, wait_call_threads) + self.close() + except Exception as e: + print(f"[red]Error while stopping cloud server: [/]", traceback.format_exc()) diff --git a/scratchattach/eventhandlers/cloud_server.py b/scratchattach/eventhandlers/cloud_server.py index 0bda1f84..58f58555 100644 --- a/scratchattach/eventhandlers/cloud_server.py +++ b/scratchattach/eventhandlers/cloud_server.py @@ -1,14 +1,21 @@ from __future__ import annotations -from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket -from threading import Thread -from scratchattach.utils import exceptions +from scratchattach.site.typed_dicts import CloudActivityDict + import json import time +import ssl +import traceback +from typing import Any +import warnings + +from SimpleWebSocketServer import SimpleSSLWebSocketServer, SimpleWebSocketServer, WebSocket +from rich import print + +from scratchattach.utils import exceptions from scratchattach.site import cloud_activity from scratchattach.site.user import User -from ._base import BaseEventHandler -import traceback +from ._base import BaseCloudServer class TwCloudSocket(WebSocket): @@ -17,89 +24,106 @@ class TwCloudSocket(WebSocket): def handle_set(self, data: dict): # cloud variable set received # check if project_id is in whitelisted projects (if there's a list of whitelisted projects) - if self.server.whitelisted_projects is not None: - if data["project_id"] not in self.server.whitelisted_projects: - self.close(4002) - if self.server.log_var_sets: - print( - self.address[0] + ":" + str(self.address[1]), - "tried to set a var on non-whitelisted project and was disconnected, project:", - data["project_id"], - "user:", - data["user"], - ) - return + if (self.server.whitelisted_projects is not None and + str(data["project_id"]) not in self.server.whitelisted_projects): + self.close(4002) + if self.server.log_var_sets: + print("[red]Error: "+ + self.address[0] + ":" + str(self.address[1])+ + " with username "+ + data["user"]+ + " tried to set a var on non-whitelisted project ID "+ + data["project_id"]+ + " and was disconnected.[/]" + ) + return # check if value is valid if not self.server._check_value(data["value"]): if self.server.log_var_sets: - print(self.address[0] + ":" + str(self.address[1]), "sent an invalid var value") + print("[yellow]Warning: "+ + self.address[0] + ":" + str(self.address[1])+ + " sent an invalid variable value.[/]\n"+ + f" Value: {data["value"]}") return # perform cloud var and forward to other players if self.server.log_var_sets: print( - self.address[0] + ":" + str(self.address[1]), - f"set {data['name']} to {data['value']}, project:", - str(data["project_id"]), - "user:", - data["user"], + self.address[0] + ":" + str(self.address[1])+ + f" with username {data['user']}"+ + f" sucessfully set {data['name']} to {data['value']} in project "+ + f"{str(data['project_id'])}." ) - self.server.set_var(data["project_id"], data["name"], data["value"], user=data["user"], skip_forward=self) - send_to_clients = { + self.server.set_var( + data["project_id"], + data["name"], + data["value"], + user=data["user"], + skip_forward=self, + no_prefix=True, + ) + send_to_clients: CloudActivityDict = { "method": "set", "user": data["user"], "project_id": data["project_id"], "name": data["name"], "value": data["value"], "timestamp": round(time.time() * 1000), - "server": "scratchattach/2.0.0", + "server": "scratchattach/3", } + # TODO: Add a cloud to the activity dict (possibly some kind of adapter) # raise event _a = cloud_activity.CloudActivity(timestamp=time.time() * 1000) - data["name"] = data["name"].replace("☁ ", "") _a._update_from_dict(send_to_clients) self.server.call_event("on_set", [_a, self]) def handle_handshake(self, data: dict): # check if handshake is valid - if not "user" in data: - print(self.address[0] + ":" + str(self.address[1]), "tried to handshake without providing a username") + if not data["user"]: + print("[red]Error: "+ + str(self.address[0]) + ":" + str(self.address[1])+ + " tried to handshake without providing a username.[/]") self.close(4002) return - if not "project_id" in data: - print(self.address[0] + ":" + str(self.address[1]), "tried to handshake without providing a project_id") + if not data["project_id"]: + print("[red]Error: "+ + str(self.address[0]) + ":" + str(self.address[1])+ + " tried to handshake without providing a project_id.[/]") self.close(4002) return + # check if project_id is in username is allowed - if self.server.allow_nonscratch_names is False: - if not User(username=data["user"]).does_exist(): - print( - self.address[0] + ":" + str(self.address[1]), - "tried to handshake using a username not existing on Scratch, project:", - data["project_id"], - "user:", - data["user"], - ) - self.close(4002) - return + if not self.server.allow_nonscratch_names and not User(username=data["user"]).does_exist(): + print("[red]Error: "+ + str(self.address[0]) + ":" + str(self.address[1])+ + " tried to handshake with non-existent Scratch username "+ + data["user"]+ + ".[/]" + ) + self.close(4002) + return + # check if project_id is in whitelisted projects (if there's a list of whitelisted projects) - if self.server.whitelisted_projects is not None: - if str(data["project_id"]) not in self.server.whitelisted_projects: - self.close(4002) - print( - self.address[0] + ":" + str(self.address[1]), - "tried to handshake on a non-whitelisted project:", - data["project_id"], - "user:", - data["user"], - ) - return + if (self.server.whitelisted_projects is not None + and str(data["project_id"]) not in self.server.whitelisted_projects): + self.close(4002) + print("[red]Error: "+ + str(self.address[0]) + ":" + str(self.address[1])+ + " with username "+ + data["user"]+ + " tried to handshake on a non-whitelisted project with ID "+ + data["project_id"]+ + ".[/]" + ) + return # register handshake in users list (save username and project_id) - print( - self.address[0] + ":" + str(self.address[1]), - "handshaked, project:", - data["project_id"], - "user:", - data["user"], + print("[green b]Handshake successful![/]\n"+ + "[green] Address "+ + str(self.address[0]) + ":" + str(self.address[1])+ + " under username [b]"+ + data["user"]+ + "[/] and project ID [b]"+ + data["project_id"]+ + " sucessfully handshaked with the server.[/green]" ) self.server.tw_clients[self.address]["username"] = data["user"] self.server.tw_clients[self.address]["project_id"] = data["project_id"] @@ -113,7 +137,7 @@ def handle_handshake(self, data: dict): "project_id": data["project_id"], "name": "☁ " + varname, "value": self.server.tw_variables[str(data["project_id"])][varname], - "server": "scratchattach/2.0.0", + "server": "scratchattach/3", } ) for varname in self.server.get_project_vars(str(data["project_id"])) @@ -131,22 +155,44 @@ def handleMessage(self): if self.server.check_for_ip_ban(self): return - data = json.loads(self.data) - # print(data) + try: + data = json.loads(self.data) + except json.decoder.JSONDecodeError: + print(f"[yellow]Warning: Client {str(self.address[0]) + ':' + str(self.address[1])} sent"+ + " invalid JSON to the server. The client may be unsafe, please stay alert.[/]\n"+ + f" [b]Data received:[/] {self.data}") + return - if data["method"] == "set": - self.handle_set(data) - elif data["method"] == "handshake": - self.handle_handshake(data) + if data == {}: + print( + "[yellow]Warning: "+ + str(self.address[0]) + ":" + str(self.address[1])+ + " sent a blank JSON message. [b]If this seems suspicious, ban the IP.[/][/]", + ) + return + if 'method' in data: + if data["method"] == "set": + self.handle_set(data) + elif data["method"] == "handshake": + self.handle_handshake(data) + else: + print( + "[yellow]Warning: "+ + str(self.address[0]) + ":" + str(self.address[1]), + " sent a message without providing a valid method (either [b]set[/b] or [b]handshake[/b]),"+ + f"but provided method '{list(data.values())[0]}' instead.[/]\n", + f" [b]Data received:[/] {self.data}" + ) else: print( - "Error:", - self.address[0] + ":" + str(self.address[1]), - "sent a message without providing a valid method (set, handshake)", + "[yellow]Warning: "+ + str(self.address[0]) + ":" + str(self.address[1])+ + " sent a message without providing a valid [b]'method'[/b] key,"+ + f" but provided key '{list(data.keys())[0]}' instead.[/]\n", + f" [b]Data received:[/] {self.data}" ) - except Exception as e: - print("Internal error in handleMessage:", e, traceback.format_exc()) + print(f"[red]Internal error in handleMessage: {e}[/]\n", traceback.format_exc()) def handleConnected(self): if not self.server.running: @@ -155,19 +201,22 @@ def handleConnected(self): if self.server.check_for_ip_ban(self): return - print(self.address[0] + ":" + str(self.address[1]), "connected") - self.server.tw_clients[self.address] = {"client": self, "username": None, "project_id": None} - # raise event + print("[green]New client " + str(self.address[0]) + ":" + str(self.address[1]) + " connected![/]") + self.server.tw_clients[self.address] = {"client": self, + "username": None, + "project_id": None,} + # raise connect event self.server.call_event("on_connect", [self]) except Exception as e: - print("Internal error in handleConntected:", e) + print(f"[red]Internal error in handleConnected: {e} [/]\n", traceback.format_exc()) def handleClose(self): if not self.server.running: return + try: if self.address in self.server.tw_clients: - # raise event + # raise disconnect event self.server.call_event( "on_disconnect", [ @@ -176,189 +225,108 @@ def handleClose(self): self, ], ) - print(self.address[0] + ":" + str(self.address[1]), "disconnected") + print(f"[blue]Client {self.address[0]}:{self.address[1]} disconnected from server sucessfully.[/]") except Exception as e: - print("Internal error in handleClose:", e) + print(f"[red]Internal error in handleClose: {e} [/]\n", traceback.format_exc()) -class TwCloudServer(SimpleWebSocketServer, BaseEventHandler): +class TwCloudServer(BaseCloudServer, SimpleWebSocketServer): def __init__( self, - hostname, + hostname: str, *, - port, - websocketclass, - length_limit=None, - allow_non_numeric=True, - whitelisted_projects=None, - allow_nonscratch_names=True, - blocked_ips=None, - sync_players=True, - log_var_sets=True, + port: int, + websocketclass: type[WebSocket], + length_limit: int | None = None, + allow_non_numeric: bool = True, + whitelisted_projects: list[Any] | None = None, + allow_nonscratch_names: bool = True, + blocked_ips: list[str] | None = None, + sync_players: bool = True, + log_var_sets: bool = True, ): if blocked_ips is None: blocked_ips = [] SimpleWebSocketServer.__init__(self, hostname, port=port, websocketclass=websocketclass) - BaseEventHandler.__init__(self) - - self.running = False - self._events = {} # saves event functions called on cloud updates - - self.tw_clients = {} # saves connected clients - self.tw_variables = {} # holds cloud variable states - - self.hostname = hostname - self.port = port - - # server config - self.allow_non_numeric = allow_non_numeric - self.whitelisted_projects = whitelisted_projects - self.length_limit = length_limit - self.allow_nonscratch_names = allow_nonscratch_names - self.blocked_ips = blocked_ips - self.sync_players = sync_players - self.log_var_sets = log_var_sets - - def check_for_ip_ban(self, client): - if ( - client.address[0] in self.blocked_ips - or client.address[0] + ":" + str(client.address[1]) in self.blocked_ips - or client.address in self.blocked_ips - ): - client.sendMessage("You have been banned from this server") - client.close(4002) - print(client.address[0] + ":" + str(client.address[1]), "(IP-banned) was disconnected") - return True - return False - - def active_projects(self): - only_active = {} - for project_id in self.tw_variables: - if self.active_user_ips(project_id) != []: - only_active[project_id] = self.tw_variables[project_id] - return only_active - - def active_user_names(self, project_id): - return [self.tw_clients[user]["username"] for user in self.active_user_ips(project_id)] - - def active_user_ips(self, project_id): - return list(filter(lambda user: str(self.tw_clients[user]["project_id"]) == str(project_id), self.tw_clients)) - - def get_global_vars(self): - return self.tw_variables - - def get_project_vars(self, project_id): - project_id = str(project_id) - if project_id in self.tw_variables: - return self.tw_variables[project_id] - else: - return {} - - def get_var(self, project_id, var_name): - project_id = str(project_id) - var_name = var_name.replace("☁ ", "") - if project_id in self.tw_variables: - if var_name in self.tw_variables[project_id]: - return self.tw_variables[project_id][var_name] - else: - return None - else: - return None - - def set_global_vars(self, data): - for project_id in data: - self.set_project_vars(project_id, data[project_id]) - - def set_project_vars(self, project_id, data, *, user="@server"): - project_id = str(project_id) - self.tw_variables[project_id] = data - for client in [self.tw_clients[ip]["client"] for ip in self.active_user_ips(project_id)]: - client.sendMessage( - "\n".join( - [ - json.dumps( - { - "method": "set", - "project_id": project_id, - "name": "☁ " + varname, - "value": data[varname], - "server": "scratchattach/2.0.0", - "timestamp": time.time() * 1000, - "user": user, - } - ) - for varname in data - ] - ) - ) - def set_var(self, project_id, var_name, value, *, user="@server", skip_forward=None): - var_name = var_name.replace("☁ ", "") - project_id = str(project_id) - if project_id not in self.tw_variables: - self.tw_variables[project_id] = {} - self.tw_variables[project_id][var_name] = value - - if self.sync_players is True: - for client in [self.tw_clients[ip]["client"] for ip in self.active_user_ips(project_id)]: - if client == skip_forward: - continue - client.sendMessage( - json.dumps( - { - "method": "set", - "project_id": project_id, - "name": "☁ " + var_name, - "value": value, - "timestamp": time.time() * 1000, - "user": user, - } - ) - ) + BaseCloudServer.__init__( + self, + hostname=hostname, + port=port, + length_limit=length_limit, + allow_non_numeric=allow_non_numeric, + whitelisted_projects=whitelisted_projects, + allow_nonscratch_names=allow_nonscratch_names, + blocked_ips=blocked_ips, + sync_players=sync_players, + log_var_sets=log_var_sets, + ) - def _check_value(self, value): - # Checks if a received cloud value satisfies the server's constraints - if self.length_limit is not None: - if len(str(value)) > self.length_limit: - return False - if self.allow_non_numeric is False: - x = value.replace(".", "") - x = x.replace("-", "") - if not (x.isnumeric() or x == ""): - return False - return True + +class TwSSLCloudServer(BaseCloudServer, SimpleSSLWebSocketServer): + def __init__( + self, + hostname: str, + *, + certfile: str | None = None, + keyfile: str | None = None, + ssl_version: int = ssl.PROTOCOL_TLSv1_2, + ssl_context: ssl.SSLContext | None = None, + port: int, + websocketclass: type[WebSocket], + length_limit: int | None = None, + allow_non_numeric: bool = True, + whitelisted_projects: list[Any] | None = None, + allow_nonscratch_names: bool = True, + blocked_ips: list[str] | None = None, + sync_players: bool = True, + log_var_sets: bool = True, + ): + SimpleSSLWebSocketServer.__init__( + self, + hostname, + port=port, + websocketclass=websocketclass, + certfile=certfile, + keyfile=keyfile, + version=ssl_version, + ssl_context=ssl_context, + ) + + BaseCloudServer.__init__( + self, + hostname=hostname, + port=port, + length_limit=length_limit, + allow_non_numeric=allow_non_numeric, + whitelisted_projects=whitelisted_projects, + allow_nonscratch_names=allow_nonscratch_names, + blocked_ips=blocked_ips, + sync_players=sync_players, + log_var_sets=log_var_sets, + ) def _updater(self): try: # Function called when .start() is executed (.start is inherited from BaseEventHandler) - print(f"Serving websocket server: ws://{self.hostname}:{self.port}") + print(f"Serving websocket server: wss://{self.hostname}:{self.port}") self.serveforever() except Exception as e: raise exceptions.WebsocketServerError(str(e)) - def pause(self): - self.running = False - - def resume(self): - self.running = True - - def stop(self, wait_call_threads: bool = True): - BaseEventHandler.stop(self, wait_call_threads) - self.close() - def init_cloud_server( - hostname="127.0.0.1", - port=8080, + hostname: str = "127.0.0.1", + port: int = 8080, *, - length_limit=None, - allow_non_numeric=True, - whitelisted_projects=None, - allow_nonscratch_names=True, - blocked_ips=None, - sync_players=True, - log_var_sets=True, + length_limit: int | None = None, + allow_non_numeric: bool = True, + whitelisted_projects: list[Any] | None = None, + allow_nonscratch_names: bool = True, + blocked_ips: list[str] | None = None, + sync_players: bool = True, + log_var_sets: bool = True, ): """ Inits a websocket server which can be used with TurboWarp's ?cloud_host URL parameter. @@ -380,3 +348,48 @@ def init_cloud_server( sync_players=sync_players, log_var_sets=log_var_sets, ) + + +def init_ssl_cloud_server( + hostname: str = "127.0.0.1", + port: int = 8080, + *, + certfile: str | None = None, + keyfile: str | None = None, + ssl_version: int = ssl.PROTOCOL_TLSv1_2, + ssl_context: ssl.SSLContext | None = None, + length_limit: int | None = None, + allow_non_numeric: bool = True, + whitelisted_projects: list[Any] | None = None, + allow_nonscratch_names: bool = True, + blocked_ips: list[str] | None = None, + sync_players: bool = True, + log_var_sets: bool = True, +) -> TwSSLCloudServer: + """ + Inits a websocket server which can be used with TurboWarp's ?cloud_host URL parameter. + + Prints out the websocket address in the console. + """ + if (certfile is None or keyfile is None) and ssl_context is None: + warnings.warn( + "To init a ssl cloud server, you need provide `certfile` and " + + "`keyfile` or `ssl_context`." + ) + + return TwSSLCloudServer( + hostname, + port=port, + websocketclass=TwCloudSocket, + certfile=certfile, + keyfile=keyfile, + ssl_version=ssl_version, + ssl_context=ssl_context, + length_limit=length_limit, + allow_non_numeric=allow_non_numeric, + whitelisted_projects=whitelisted_projects, + allow_nonscratch_names=allow_nonscratch_names, + blocked_ips=blocked_ips, + sync_players=sync_players, + log_var_sets=log_var_sets, + )