From b988e782962e5128b7e308554b009c40f3dbaf03 Mon Sep 17 00:00:00 2001
From: Stefan Kraus <stefan.kraus@methodpark.de>
Date: Mon, 5 Apr 2021 13:48:16 +0200
Subject: [PATCH] Let reverse proxy handle SSL by default

---
 server/server.py | 27 ++++++++++++++++++++-------
 1 file changed, 20 insertions(+), 7 deletions(-)

diff --git a/server/server.py b/server/server.py
index 8846366..fa27f49 100755
--- a/server/server.py
+++ b/server/server.py
@@ -11,10 +11,16 @@ from enum import Enum, auto
 
 from aioconsole import ainput
 
-LOCAL = False
+# Port the websocket will listen on
 PORT = 8432
-PATH_CERTCHAIN = "/etc/letsencrypt/live/www.mpvsync.de/fullchain.pem"
-PATH_PRIVATE_KEY = "/etc/letsencrypt/live/www.mpvsync.de/privkey.pem"
+
+# Shall SSL be handled by the server itself?
+# Can be disabled if you use a reverse proxy who does ssl for you
+ENABLE_SSL = False
+# In case you set ENABLE_SSL = True, set paths to your certchain and private key
+PATH_CERTCHAIN = "/path/to/ssl/certchain.pem"
+PATH_PRIVATE_KEY = "/path/to/ssl/privatekey.pem"
+
 
 PLAY_REQUEST = {"command": "play"}
 PAUSE_REQUEST = {"command": "pause"}
@@ -219,15 +225,22 @@ async def handle(ws: websockets.WebSocketServerProtocol, path: str) -> None:
 
 
 def main():
-    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
-    ssl_context.load_cert_chain(PATH_CERTCHAIN, PATH_PRIVATE_KEY)
 
-    hostname = "127.0.0.1" if LOCAL else None
+    hostname = None # Listen 'publicly'
     port = PORT
 
     try:
         async def async_main():
-            await websockets.serve(handle, hostname, port, ssl=ssl_context)
+
+            if ENABLE_SSL:
+                ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+                ssl_context.load_cert_chain(PATH_CERTCHAIN, PATH_PRIVATE_KEY)
+                # wss connection, public one
+                await websockets.serve(handle, hostname, port, ssl=ssl_context)
+            else:
+                # ws connection without TLS, for development only!
+                await websockets.serve(handle, hostname, port)
+
             await console_input()
 
         asyncio.run(async_main())
-- 
GitLab