From 10e115cba3b6fb4c6b8988a5952ba21443d3c07d Mon Sep 17 00:00:00 2001 From: 0x3d Date: Wed, 7 Feb 2024 00:19:55 +0100 Subject: [PATCH 01/14] Accomodate for Stellantis' Jan 23 OAuth changes (still one manual step involved during setup but at least the error 500 is gone) --- psa_car_controller/psa/constants.py | 2 +- psa_car_controller/psa/oauth.py | 26 +++++++++++++++++-- psa_car_controller/psa/setup/app_decoder.py | 2 +- .../psacc/application/psa_client.py | 4 +-- 4 files changed, 28 insertions(+), 6 deletions(-) diff --git a/psa_car_controller/psa/constants.py b/psa_car_controller/psa/constants.py index e10fbd4..9c7e848 100644 --- a/psa_car_controller/psa/constants.py +++ b/psa_car_controller/psa/constants.py @@ -28,7 +28,7 @@ DEFAULT_PRECONDITIONING_PROGRAM = { "program3": {"day": [0, 0, 0, 0, 0, 0, 0], "hour": 34, "minute": 7, "on": 0}, "program4": {"day": [0, 0, 0, 0, 0, 0, 0], "hour": 34, "minute": 7, "on": 0} } -AUTHORIZE_SERVICE = "https://api.mpsa.com/api/connectedcar/v2/oauth/authorize" +AUTHORIZE_SERVICE = "https://idpcvs.opel.com/am/oauth2/authorize" REMOTE_URL = "https://api.groupe-psa.com/connectedcar/v4/virtualkey/remoteaccess/token?client_id=" BRAND = {"com.psa.mym.myopel": {"realm": "clientsB2COpel", "brand_code": "OP", "app_name": "MyOpel"}, "com.psa.mym.mypeugeot": {"realm": "clientsB2CPeugeot", "brand_code": "AP", "app_name": "MyPeugeot"}, diff --git a/psa_car_controller/psa/oauth.py b/psa_car_controller/psa/oauth.py index 26a4590..e4aad02 100644 --- a/psa_car_controller/psa/oauth.py +++ b/psa_car_controller/psa/oauth.py @@ -1,4 +1,9 @@ import logging +import hashlib +import secrets +import base64 +from typing import Tuple + from http import HTTPStatus from typing import Optional @@ -22,8 +27,25 @@ class OpenIdCredentialManager(CredentialManager): return {"grant_type": 'password', "username": login, "scope": ' '.join(self.service_information.scopes), "password": password, "realm": realm} - def init_with_user_credentials_realm(self, login: str, password: str, realm: str): - self._token_request(self._grant_password_request_realm(login, password, realm), True) + def generate_sha256_pkce(self, length: int) -> Tuple[str, str]: + if not (43 <= length <= 128): + raise Exception("Invalid length: " % str(length)) + verifier = secrets.token_urlsafe(length) + encoded = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode('ascii')).digest()) + challenge = encoded.decode('ascii')[:-1] + return verifier, challenge + + def init_with_user_credentials_realm(self, country_code: str, realm: str): + redir_uri = "mymop://oauth2redirect/" + country_code.lower() + code_verifier, code_challenge = self.generate_sha256_pkce(64) + url = self.generate_authorize_url(redir_uri, secrets.token_urlsafe(16), code_challenge=code_challenge, code_challenge_method="S256") + + ret = "" + while len(ret) != 36: + logger.info("Now login to this URL in a browser: " + url) + ret = input("\nCopy+paste the resulting mymop-code (in F12 > Network when you hit the final OK button, 36 chars, UUID format): ") + + self._token_request(dict(grant_type='authorization_code', code=ret, redirect_uri=redir_uri, code_verifier=code_verifier), False) @staticmethod def _is_token_expired(response: Response) -> bool: diff --git a/psa_car_controller/psa/setup/app_decoder.py b/psa_car_controller/psa/setup/app_decoder.py index c6f4128..3694fd9 100755 --- a/psa_car_controller/psa/setup/app_decoder.py +++ b/psa_car_controller/psa/setup/app_decoder.py @@ -92,7 +92,7 @@ def firstLaunchConfig(package_name, client_email, client_password, country_code, psacc = PSAClient(None, apk_parser.client_id, apk_parser.client_secret, None, customer_id, BRAND[package_name]["realm"], country_code) - psacc.connect(client_email, client_password) + psacc.connect(country_code) psacc.save_config(name=config_prefix + "config.json") res = psacc.get_vehicles() diff --git a/psa_car_controller/psacc/application/psa_client.py b/psa_car_controller/psacc/application/psa_client.py index 8df313f..dbd47b1 100644 --- a/psa_car_controller/psacc/application/psa_client.py +++ b/psa_car_controller/psacc/application/psa_client.py @@ -31,8 +31,8 @@ logger = CustomLogger.getLogger(__name__) class PSAClient: - def connect(self, user, password): - self.manager.init_with_user_credentials_realm(user, password, self.realm) + def connect(self, country_code): + self.manager.init_with_user_credentials_realm(country_code, self.realm) # pylint: disable=too-many-arguments def __init__(self, refresh_token, client_id, client_secret, remote_refresh_token, customer_id, realm, country_code, From cdf7f85bf997257ad4307028f1e41c5698b70ec8 Mon Sep 17 00:00:00 2001 From: 0x3d Date: Wed, 7 Feb 2024 00:19:55 +0100 Subject: [PATCH 02/14] Accomodate for Stellantis' Jan 23 OAuth changes (still one manual step involved during setup but at least the error 500 is gone) --- psa_car_controller/psa/constants.py | 2 +- psa_car_controller/psa/oauth.py | 28 +++++++++++++++++-- psa_car_controller/psa/setup/app_decoder.py | 2 +- .../psacc/application/psa_client.py | 4 +-- 4 files changed, 30 insertions(+), 6 deletions(-) diff --git a/psa_car_controller/psa/constants.py b/psa_car_controller/psa/constants.py index e10fbd4..9c7e848 100644 --- a/psa_car_controller/psa/constants.py +++ b/psa_car_controller/psa/constants.py @@ -28,7 +28,7 @@ DEFAULT_PRECONDITIONING_PROGRAM = { "program3": {"day": [0, 0, 0, 0, 0, 0, 0], "hour": 34, "minute": 7, "on": 0}, "program4": {"day": [0, 0, 0, 0, 0, 0, 0], "hour": 34, "minute": 7, "on": 0} } -AUTHORIZE_SERVICE = "https://api.mpsa.com/api/connectedcar/v2/oauth/authorize" +AUTHORIZE_SERVICE = "https://idpcvs.opel.com/am/oauth2/authorize" REMOTE_URL = "https://api.groupe-psa.com/connectedcar/v4/virtualkey/remoteaccess/token?client_id=" BRAND = {"com.psa.mym.myopel": {"realm": "clientsB2COpel", "brand_code": "OP", "app_name": "MyOpel"}, "com.psa.mym.mypeugeot": {"realm": "clientsB2CPeugeot", "brand_code": "AP", "app_name": "MyPeugeot"}, diff --git a/psa_car_controller/psa/oauth.py b/psa_car_controller/psa/oauth.py index 26a4590..4ad5098 100644 --- a/psa_car_controller/psa/oauth.py +++ b/psa_car_controller/psa/oauth.py @@ -1,4 +1,9 @@ import logging +import hashlib +import secrets +import base64 +from typing import Tuple + from http import HTTPStatus from typing import Optional @@ -22,8 +27,27 @@ class OpenIdCredentialManager(CredentialManager): return {"grant_type": 'password', "username": login, "scope": ' '.join(self.service_information.scopes), "password": password, "realm": realm} - def init_with_user_credentials_realm(self, login: str, password: str, realm: str): - self._token_request(self._grant_password_request_realm(login, password, realm), True) + def generate_sha256_pkce(self, length: int) -> Tuple[str, str]: + if not (43 <= length <= 128): + raise ValueError("Invalid length: " % str(length)) + verifier = secrets.token_urlsafe(length) + encoded = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode('ascii')).digest()) + challenge = encoded.decode('ascii')[:-1] + return verifier, challenge + + def init_with_user_credentials_realm(self, country_code: str): + redir_uri = "mymop://oauth2redirect/" + country_code.lower() + code_verifier, code_challenge = self.generate_sha256_pkce(64) + url = self.generate_authorize_url(redir_uri, secrets.token_urlsafe(16), + code_challenge=code_challenge, code_challenge_method="S256") + + ret = "" + while len(ret) != 36: + logger.info("Now login to this URL in a browser: " + url) + ret = input("\nCopy+paste the resulting mymop-code (in F12 > Network when you hit the final OK button, 36 chars, UUID format): ") + + self._token_request({ "grant_type": 'authorization_code', "code": ret, + "redirect_uri": redir_uri, "code_verifier": code_verifier), False) @staticmethod def _is_token_expired(response: Response) -> bool: diff --git a/psa_car_controller/psa/setup/app_decoder.py b/psa_car_controller/psa/setup/app_decoder.py index c6f4128..3694fd9 100755 --- a/psa_car_controller/psa/setup/app_decoder.py +++ b/psa_car_controller/psa/setup/app_decoder.py @@ -92,7 +92,7 @@ def firstLaunchConfig(package_name, client_email, client_password, country_code, psacc = PSAClient(None, apk_parser.client_id, apk_parser.client_secret, None, customer_id, BRAND[package_name]["realm"], country_code) - psacc.connect(client_email, client_password) + psacc.connect(country_code) psacc.save_config(name=config_prefix + "config.json") res = psacc.get_vehicles() diff --git a/psa_car_controller/psacc/application/psa_client.py b/psa_car_controller/psacc/application/psa_client.py index 8df313f..dbd47b1 100644 --- a/psa_car_controller/psacc/application/psa_client.py +++ b/psa_car_controller/psacc/application/psa_client.py @@ -31,8 +31,8 @@ logger = CustomLogger.getLogger(__name__) class PSAClient: - def connect(self, user, password): - self.manager.init_with_user_credentials_realm(user, password, self.realm) + def connect(self, country_code): + self.manager.init_with_user_credentials_realm(country_code, self.realm) # pylint: disable=too-many-arguments def __init__(self, refresh_token, client_id, client_secret, remote_refresh_token, customer_id, realm, country_code, From be3238f85bd9031fd894b6cb747b0c125084e753 Mon Sep 17 00:00:00 2001 From: 0x3d Date: Wed, 7 Feb 2024 00:38:16 +0100 Subject: [PATCH 03/14] Happy linter --- psa_car_controller/psa/oauth.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/psa_car_controller/psa/oauth.py b/psa_car_controller/psa/oauth.py index 4ad5098..ae56125 100644 --- a/psa_car_controller/psa/oauth.py +++ b/psa_car_controller/psa/oauth.py @@ -44,10 +44,11 @@ class OpenIdCredentialManager(CredentialManager): ret = "" while len(ret) != 36: logger.info("Now login to this URL in a browser: " + url) - ret = input("\nCopy+paste the resulting mymop-code (in F12 > Network when you hit the final OK button, 36 chars, UUID format): ") + ret = input("\nCopy+paste the resulting mymop-code (in F12 > Network" \ + "when you hit the final OK button, 36 chars, UUID format): ") self._token_request({ "grant_type": 'authorization_code', "code": ret, - "redirect_uri": redir_uri, "code_verifier": code_verifier), False) + "redirect_uri": redir_uri, "code_verifier": code_verifier}, False) @staticmethod def _is_token_expired(response: Response) -> bool: From 034ce5d3cc847549ea1158d050deee88664d43cd Mon Sep 17 00:00:00 2001 From: 0x3d Date: Wed, 7 Feb 2024 00:42:36 +0100 Subject: [PATCH 04/14] more linitng issues --- psa_car_controller/psa/oauth.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/psa_car_controller/psa/oauth.py b/psa_car_controller/psa/oauth.py index ae56125..d0e9b43 100644 --- a/psa_car_controller/psa/oauth.py +++ b/psa_car_controller/psa/oauth.py @@ -29,7 +29,7 @@ class OpenIdCredentialManager(CredentialManager): def generate_sha256_pkce(self, length: int) -> Tuple[str, str]: if not (43 <= length <= 128): - raise ValueError("Invalid length: " % str(length)) + raise ValueError("Invalid length: %s", str(length)) verifier = secrets.token_urlsafe(length) encoded = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode('ascii')).digest()) challenge = encoded.decode('ascii')[:-1] @@ -43,7 +43,7 @@ class OpenIdCredentialManager(CredentialManager): ret = "" while len(ret) != 36: - logger.info("Now login to this URL in a browser: " + url) + logger.info("Now login to this URL in a browser: %s", url) ret = input("\nCopy+paste the resulting mymop-code (in F12 > Network" \ "when you hit the final OK button, 36 chars, UUID format): ") From 82a3df1febd4403d2d4059d91e1ac3e778be2c93 Mon Sep 17 00:00:00 2001 From: 0x3d Date: Wed, 7 Feb 2024 00:47:09 +0100 Subject: [PATCH 05/14] Derp. Starting to think 2 days of OAuth deep-diving was the easy part :-D --- psa_car_controller/psa/oauth.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/psa_car_controller/psa/oauth.py b/psa_car_controller/psa/oauth.py index d0e9b43..07eee23 100644 --- a/psa_car_controller/psa/oauth.py +++ b/psa_car_controller/psa/oauth.py @@ -29,7 +29,7 @@ class OpenIdCredentialManager(CredentialManager): def generate_sha256_pkce(self, length: int) -> Tuple[str, str]: if not (43 <= length <= 128): - raise ValueError("Invalid length: %s", str(length)) + raise ValueError("Invalid length: %d" % length) verifier = secrets.token_urlsafe(length) encoded = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode('ascii')).digest()) challenge = encoded.decode('ascii')[:-1] From 9bcf2aeaf582dc8ea16edc009e570e4c31dd5eae Mon Sep 17 00:00:00 2001 From: 0x3d Date: Wed, 7 Feb 2024 01:17:44 +0100 Subject: [PATCH 06/14] Linters don't code --- psa_car_controller/psa/oauth.py | 5 +++-- psa_car_controller/psacc/application/psa_client.py | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/psa_car_controller/psa/oauth.py b/psa_car_controller/psa/oauth.py index 07eee23..900636d 100644 --- a/psa_car_controller/psa/oauth.py +++ b/psa_car_controller/psa/oauth.py @@ -41,10 +41,11 @@ class OpenIdCredentialManager(CredentialManager): url = self.generate_authorize_url(redir_uri, secrets.token_urlsafe(16), code_challenge=code_challenge, code_challenge_method="S256") + logger.info("Now login to this URL in a browser: %s", url) + ret = "" while len(ret) != 36: - logger.info("Now login to this URL in a browser: %s", url) - ret = input("\nCopy+paste the resulting mymop-code (in F12 > Network" \ + ret = input("\nCopy+paste the resulting mymop-code (in F12 > Network, " \ "when you hit the final OK button, 36 chars, UUID format): ") self._token_request({ "grant_type": 'authorization_code', "code": ret, diff --git a/psa_car_controller/psacc/application/psa_client.py b/psa_car_controller/psacc/application/psa_client.py index dbd47b1..e9a9ef2 100644 --- a/psa_car_controller/psacc/application/psa_client.py +++ b/psa_car_controller/psacc/application/psa_client.py @@ -32,7 +32,7 @@ logger = CustomLogger.getLogger(__name__) class PSAClient: def connect(self, country_code): - self.manager.init_with_user_credentials_realm(country_code, self.realm) + self.manager.init_with_user_credentials_realm(country_code) # pylint: disable=too-many-arguments def __init__(self, refresh_token, client_id, client_secret, remote_refresh_token, customer_id, realm, country_code, From 2721ac6a85f33691f3f022df8a964ec33475113e Mon Sep 17 00:00:00 2001 From: 0x3d Date: Wed, 7 Feb 2024 11:00:42 +0100 Subject: [PATCH 07/14] Use a different AUTHORIZE_SERVICE per brand/realm --- psa_car_controller/psa/connected_car_api/configuration.py | 2 +- psa_car_controller/psa/constants.py | 7 ++++++- psa_car_controller/psacc/application/psa_client.py | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/psa_car_controller/psa/connected_car_api/configuration.py b/psa_car_controller/psa/connected_car_api/configuration.py index 8f1a4a4..4b2fe62 100644 --- a/psa_car_controller/psa/connected_car_api/configuration.py +++ b/psa_car_controller/psa/connected_car_api/configuration.py @@ -72,7 +72,7 @@ class Configuration(object): # Debug file location self.logger_file = None # Debug switch - self.debug = False + self.debug = True # SSL/TLS verification # Set this to false to skip verifying SSL certificate when calling API diff --git a/psa_car_controller/psa/constants.py b/psa_car_controller/psa/constants.py index 9c7e848..a41a858 100644 --- a/psa_car_controller/psa/constants.py +++ b/psa_car_controller/psa/constants.py @@ -28,7 +28,12 @@ DEFAULT_PRECONDITIONING_PROGRAM = { "program3": {"day": [0, 0, 0, 0, 0, 0, 0], "hour": 34, "minute": 7, "on": 0}, "program4": {"day": [0, 0, 0, 0, 0, 0, 0], "hour": 34, "minute": 7, "on": 0} } -AUTHORIZE_SERVICE = "https://idpcvs.opel.com/am/oauth2/authorize" +AUTHORIZE_SERVICE = {"clientsB2COpel": "https://idpcvs.opel.com/am/oauth2/authorize", + "clientsB2CPeugeot": "https://idpcvs.peugeot.com/am/oauth2/authorize", + "clientsB2CCitroen": "https://idpcvs.citroen.com/am/oauth2/authorize", + "clientsB2CDS": "https://idpcvs.driveds.com/am/oauth2/authorize", + "clientsB2CVauxhall": "https://idpcvs.vauxhall.co.uk/am/oauth2/authorize" + } REMOTE_URL = "https://api.groupe-psa.com/connectedcar/v4/virtualkey/remoteaccess/token?client_id=" BRAND = {"com.psa.mym.myopel": {"realm": "clientsB2COpel", "brand_code": "OP", "app_name": "MyOpel"}, "com.psa.mym.mypeugeot": {"realm": "clientsB2CPeugeot", "brand_code": "AP", "app_name": "MyPeugeot"}, diff --git a/psa_car_controller/psacc/application/psa_client.py b/psa_car_controller/psacc/application/psa_client.py index e9a9ef2..b510fec 100644 --- a/psa_car_controller/psacc/application/psa_client.py +++ b/psa_car_controller/psacc/application/psa_client.py @@ -38,7 +38,7 @@ class PSAClient: def __init__(self, refresh_token, client_id, client_secret, remote_refresh_token, customer_id, realm, country_code, proxies=None, weather_api=None, abrp=None, co2_signal_api=None): self.realm = realm - self.service_information = ServiceInformation(AUTHORIZE_SERVICE, + self.service_information = ServiceInformation(AUTHORIZE_SERVICE[self.realm], realm_info[self.realm]['oauth_url'], client_id, client_secret, From 66c188f18cee5270da90c0dfbf42bc6567128a48 Mon Sep 17 00:00:00 2001 From: 0x3d Date: Wed, 7 Feb 2024 11:05:01 +0100 Subject: [PATCH 08/14] Proper labelling --- psa_car_controller/psa/oauth.py | 2 +- psa_car_controller/psacc/application/psa_client.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/psa_car_controller/psa/oauth.py b/psa_car_controller/psa/oauth.py index 900636d..bd15f96 100644 --- a/psa_car_controller/psa/oauth.py +++ b/psa_car_controller/psa/oauth.py @@ -35,7 +35,7 @@ class OpenIdCredentialManager(CredentialManager): challenge = encoded.decode('ascii')[:-1] return verifier, challenge - def init_with_user_credentials_realm(self, country_code: str): + def init_with_country_code(self, country_code: str): redir_uri = "mymop://oauth2redirect/" + country_code.lower() code_verifier, code_challenge = self.generate_sha256_pkce(64) url = self.generate_authorize_url(redir_uri, secrets.token_urlsafe(16), diff --git a/psa_car_controller/psacc/application/psa_client.py b/psa_car_controller/psacc/application/psa_client.py index b510fec..4fefd3f 100644 --- a/psa_car_controller/psacc/application/psa_client.py +++ b/psa_car_controller/psacc/application/psa_client.py @@ -32,7 +32,7 @@ logger = CustomLogger.getLogger(__name__) class PSAClient: def connect(self, country_code): - self.manager.init_with_user_credentials_realm(country_code) + self.manager.init_with_country_code(country_code) # pylint: disable=too-many-arguments def __init__(self, refresh_token, client_id, client_secret, remote_refresh_token, customer_id, realm, country_code, From bd46b52f3b90d579cae217df3bc005a9b6c54d78 Mon Sep 17 00:00:00 2001 From: 0x3d Date: Wed, 7 Feb 2024 12:36:22 +0100 Subject: [PATCH 09/14] =?UTF-8?q?The=20"op"=20in=20"mym**op**"=20stands=20?= =?UTF-8?q?for=20Opel=20=F0=9F=98=85=20=F0=9F=A4=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- psa_car_controller/psa/oauth.py | 4 ++-- psa_car_controller/psa/setup/app_decoder.py | 4 ++-- psa_car_controller/psacc/application/psa_client.py | 7 ++++--- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/psa_car_controller/psa/oauth.py b/psa_car_controller/psa/oauth.py index bd15f96..6577f0a 100644 --- a/psa_car_controller/psa/oauth.py +++ b/psa_car_controller/psa/oauth.py @@ -35,8 +35,8 @@ class OpenIdCredentialManager(CredentialManager): challenge = encoded.decode('ascii')[:-1] return verifier, challenge - def init_with_country_code(self, country_code: str): - redir_uri = "mymop://oauth2redirect/" + country_code.lower() + def init_with_brand_country_code(self, brand: str, country_code: str): + redir_uri = "mym" + brand.lower() + "://oauth2redirect/" + country_code.lower() code_verifier, code_challenge = self.generate_sha256_pkce(64) url = self.generate_authorize_url(redir_uri, secrets.token_urlsafe(16), code_challenge=code_challenge, code_challenge_method="S256") diff --git a/psa_car_controller/psa/setup/app_decoder.py b/psa_car_controller/psa/setup/app_decoder.py index 3694fd9..cd475ec 100755 --- a/psa_car_controller/psa/setup/app_decoder.py +++ b/psa_car_controller/psa/setup/app_decoder.py @@ -91,8 +91,8 @@ def firstLaunchConfig(package_name, client_email, client_password, country_code, # Psacc psacc = PSAClient(None, apk_parser.client_id, apk_parser.client_secret, None, customer_id, BRAND[package_name]["realm"], - country_code) - psacc.connect(country_code) + country_code, BRAND[package_name]["brand_code"]) + psacc.connect() psacc.save_config(name=config_prefix + "config.json") res = psacc.get_vehicles() diff --git a/psa_car_controller/psacc/application/psa_client.py b/psa_car_controller/psacc/application/psa_client.py index 4fefd3f..67c3c62 100644 --- a/psa_car_controller/psacc/application/psa_client.py +++ b/psa_car_controller/psacc/application/psa_client.py @@ -31,12 +31,12 @@ logger = CustomLogger.getLogger(__name__) class PSAClient: - def connect(self, country_code): - self.manager.init_with_country_code(country_code) + def connect(self): + self.manager.init_with_brand_country_code(self.brand, self.country_code) # pylint: disable=too-many-arguments def __init__(self, refresh_token, client_id, client_secret, remote_refresh_token, customer_id, realm, country_code, - proxies=None, weather_api=None, abrp=None, co2_signal_api=None): + brand=None, proxies=None, weather_api=None, abrp=None, co2_signal_api=None): self.realm = realm self.service_information = ServiceInformation(AUTHORIZE_SERVICE[self.realm], realm_info[self.realm]['oauth_url'], @@ -60,6 +60,7 @@ class PSAClient: self._record_enabled = False self.weather_api = weather_api self.country_code = country_code + self.brand = brand self.info_callback = [] self.info_refresh_rate = 120 if abrp is None: From 073fb1828ed01b81c5bb6e54494471c79057cf37 Mon Sep 17 00:00:00 2001 From: 0x3d Date: Wed, 7 Feb 2024 12:46:20 +0100 Subject: [PATCH 10/14] mymop -> mymXX --- psa_car_controller/psa/oauth.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/psa_car_controller/psa/oauth.py b/psa_car_controller/psa/oauth.py index 6577f0a..607c0d2 100644 --- a/psa_car_controller/psa/oauth.py +++ b/psa_car_controller/psa/oauth.py @@ -45,7 +45,7 @@ class OpenIdCredentialManager(CredentialManager): ret = "" while len(ret) != 36: - ret = input("\nCopy+paste the resulting mymop-code (in F12 > Network, " \ + ret = input("\nCopy+paste the resulting mymXX-code (in F12 > Network, " \ "when you hit the final OK button, 36 chars, UUID format): ") self._token_request({ "grant_type": 'authorization_code', "code": ret, From 0fc116fbb524effbd954713087f1fdbb7b7d4a96 Mon Sep 17 00:00:00 2001 From: Gernot Hillier Date: Thu, 15 Feb 2024 21:48:47 +0100 Subject: [PATCH 11/14] fix: stay with paho-mqtt 1.x due to breaking change in 2.0 This fixes psacc crashing with: TypeError: Client.__init__() missing 1 required positional argument: 'callback_api_version' paho-mqtt 2.0, released on Feb, 10th, requires additional arguments to mqtt.Client(), see https://github.com/eclipse/paho.mqtt.python/blob/v2.0.0/docs/migrations.rst. So stay with 1.x for now. --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 19d4c5f..831291d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,7 +12,7 @@ include = [ [tool.poetry.dependencies] python = ">=3.7.2, <4.0.0" -paho-mqtt = ">=1.5.0" +paho-mqtt = ">=1.5.0, <2.0.0" dash = ">=2.9.0, <3.0.0" dash-daq = "^0.5.0" plotly = ">=5" From c67286ac4af442dbd819762e8affdc598519e126 Mon Sep 17 00:00:00 2001 From: Florian Bezannier Date: Sat, 27 Jan 2024 13:28:32 +0100 Subject: [PATCH 12/14] fix: object is not subscriptable #744 --- psa_car_controller/psacc/utils/utils.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/psa_car_controller/psacc/utils/utils.py b/psa_car_controller/psacc/utils/utils.py index 5dc3ce3..be4ecc1 100644 --- a/psa_car_controller/psacc/utils/utils.py +++ b/psa_car_controller/psacc/utils/utils.py @@ -9,7 +9,7 @@ TIMEOUT_IN_S = 10 def get_temp(latitude: str, longitude: str, api_key: str) -> float: try: - if not (latitude is None or longitude is None or api_key is None): + if latitude and longitude and api_key: weather_rep = requests.get("https://api.openweathermap.org/data/2.5/onecall", params={"lat": latitude, "lon": longitude, "exclude": "minutely,hourly,daily,alerts", @@ -17,7 +17,7 @@ def get_temp(latitude: str, longitude: str, api_key: str) -> float: "units": "metric"}, timeout=TIMEOUT_IN_S) weather_res_json = weather_rep.json() - temp = weather_res_json.get("current", weather_res_json.get("main"))["temp"] + temp = weather_res_json.get("current", weather_res_json["main"])["temp"] logger.debug("Temperature :%fc", temp) return temp except ConnectionError: From ce3c7a4ae4a02d2b7d8c3e9b5eb8195c5f48fff3 Mon Sep 17 00:00:00 2001 From: Florian Bezannier Date: Sat, 24 Feb 2024 11:36:32 +0100 Subject: [PATCH 13/14] feat: retrieve redirect scheme from constant and allow retry auth Signed-off-by: Florian Bezannier --- psa_car_controller/psa/constants.py | 18 +++++++--- psa_car_controller/psa/oauth.py | 35 +++++++++++-------- .../psacc/application/psa_client.py | 2 +- 3 files changed, 35 insertions(+), 20 deletions(-) diff --git a/psa_car_controller/psa/constants.py b/psa_car_controller/psa/constants.py index a41a858..9e86ba7 100644 --- a/psa_car_controller/psa/constants.py +++ b/psa_car_controller/psa/constants.py @@ -3,12 +3,20 @@ IMMEDIATE_CHARGE = "immediate" PSA_CORRELATION_DATE_FORMAT = "%Y%m%d%H%M%S%f" PSA_DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ" realm_info = { - "clientsB2CPeugeot": {"oauth_url": "https://idpcvs.peugeot.com/am/oauth2/access_token", "app_name": "MyPeugeot"}, - "clientsB2CCitroen": {"oauth_url": "https://idpcvs.citroen.com/am/oauth2/access_token", "app_name": "MyCitroen"}, - "clientsB2CDS": {"oauth_url": "https://idpcvs.driveds.com/am/oauth2/access_token", "app_name": "MyDS"}, - "clientsB2COpel": {"oauth_url": "https://idpcvs.opel.com/am/oauth2/access_token", "app_name": "MyOpel"}, + "clientsB2CPeugeot": {"oauth_url": "https://idpcvs.peugeot.com/am/oauth2/access_token", "app_name": "MyPeugeot", + "scheme": "mymap"}, + "clientsB2CCitroen": {"oauth_url": "https://idpcvs.citroen.com/am/oauth2/access_token", "app_name": "MyCitroen", + "scheme": "mymacsdk"}, + "clientsB2CDS": {"oauth_url": "https://idpcvs.driveds.com/am/oauth2/access_token", "app_name": "MyDS", + "scheme": "mymdssdk"}, + + "clientsB2COpel": {"oauth_url": "https://idpcvs.opel.com/am/oauth2/access_token", "app_name": "MyOpel", + "scheme": "mymopsdk"}, + "clientsB2CVauxhall": {"oauth_url": "https://idpcvs.vauxhall.co.uk/am/oauth2/access_token", - "app_name": "MyVauxhall"} + "app_name": "MyVauxhall", + "scheme": "mymvxsdk", + } } MQTT_BRANDCODE = {"AP": "AP", "AC": "AC", diff --git a/psa_car_controller/psa/oauth.py b/psa_car_controller/psa/oauth.py index 607c0d2..079fea4 100644 --- a/psa_car_controller/psa/oauth.py +++ b/psa_car_controller/psa/oauth.py @@ -7,7 +7,7 @@ from typing import Tuple from http import HTTPStatus from typing import Optional -from oauth2_client.credentials_manager import CredentialManager, ServiceInformation +from oauth2_client.credentials_manager import CredentialManager, ServiceInformation, OAuthError from requests import Response, RequestException from psa_car_controller.common.utils import rate_limit @@ -35,21 +35,28 @@ class OpenIdCredentialManager(CredentialManager): challenge = encoded.decode('ascii')[:-1] return verifier, challenge - def init_with_brand_country_code(self, brand: str, country_code: str): - redir_uri = "mym" + brand.lower() + "://oauth2redirect/" + country_code.lower() - code_verifier, code_challenge = self.generate_sha256_pkce(64) - url = self.generate_authorize_url(redir_uri, secrets.token_urlsafe(16), - code_challenge=code_challenge, code_challenge_method="S256") - - logger.info("Now login to this URL in a browser: %s", url) - + def init_with_oauth2_redirect(self, scheme: str, country_code: str): ret = "" - while len(ret) != 36: - ret = input("\nCopy+paste the resulting mymXX-code (in F12 > Network, " \ - "when you hit the final OK button, 36 chars, UUID format): ") + while True: + redir_uri = scheme + "://oauth2redirect/" + country_code.lower() + code_verifier, code_challenge = self.generate_sha256_pkce(64) + url = self.generate_authorize_url(redir_uri, secrets.token_urlsafe(16), + code_challenge=code_challenge, code_challenge_method="S256") - self._token_request({ "grant_type": 'authorization_code', "code": ret, - "redirect_uri": redir_uri, "code_verifier": code_verifier}, False) + logger.info("Now login to this URL in a browser: %s", url) + + try: + ret = input("\nCopy+paste the resulting mymXX-code (in F12 > Network, " + "when you hit the final OK button, 36 chars, UUID format): ") + logger.info("Try getting a token with code %s", ret) + assert len(ret) == 36, "Invalid code length" + self._token_request({"grant_type": 'authorization_code', "code": ret, + "redirect_uri": redir_uri, "code_verifier": code_verifier}, False) + except (OAuthError, AssertionError): + logger.exception("Failed to get a token") + if input("Retry ? yes/NO") == "yes": + continue + break @staticmethod def _is_token_expired(response: Response) -> bool: diff --git a/psa_car_controller/psacc/application/psa_client.py b/psa_car_controller/psacc/application/psa_client.py index 67c3c62..7b08ffa 100644 --- a/psa_car_controller/psacc/application/psa_client.py +++ b/psa_car_controller/psacc/application/psa_client.py @@ -32,7 +32,7 @@ logger = CustomLogger.getLogger(__name__) class PSAClient: def connect(self): - self.manager.init_with_brand_country_code(self.brand, self.country_code) + self.manager.init_with_oauth2_redirect(realm_info[self.realm]["scheme"], self.country_code) # pylint: disable=too-many-arguments def __init__(self, refresh_token, client_id, client_secret, remote_refresh_token, customer_id, realm, country_code, From 6ded92adaea7487112a07740614ac485f9dce506 Mon Sep 17 00:00:00 2001 From: Florian Bezannier Date: Sat, 24 Feb 2024 12:09:12 +0100 Subject: [PATCH 14/14] chore: add how-to auth with new method --- psa_car_controller/web/view/config_views.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/psa_car_controller/web/view/config_views.py b/psa_car_controller/web/view/config_views.py index c07fb7d..5634d58 100644 --- a/psa_car_controller/web/view/config_views.py +++ b/psa_car_controller/web/view/config_views.py @@ -61,10 +61,16 @@ login_config_layout = dbc.Row(dbc.Col(md=12, lg=2, className="m-3", children=[ color="secondary", )]), dbc.Row(dbc.Button("Submit", color="primary", id="submit-form")), - dbc.Row( - dbc.FormText( - "After submit be patient it can take some time...", - color="secondary")), + html.Div(html.P([ + "1. After submit switch back to the CLI and wait for the login URL to be shown", html.Br(), + "2. Open that URL in a browser", html.Br(), + "3. Complete the login procedure there too", html.Br(), + "4. Open your browser's DevTools (F12) and then the 'Network' tab", html.Br(), + "5. Hit the final 'OK' button, under 'LOGIN SUCCESSFUL'", html.Br(), + "6. Find xxxx://oauth2redirect....?code=&scope=openid... " + "in the DevTools and paste it into the command line interface", html.Br(), + "7. Switch back to the browser and do the OTP config", html.Br()] + )), dcc.Loading( id="loading-2", children=[html.Div([html.Div(id="form_result")])],