# Session

## Session object

class proton.session.Session(appversion: str = 'Other', user_agent: str = 'None')
  __init__(appversion: str = 'Other', user_agent: str = 'None')

    Get a session towards the Proton API.

    Parameters:

      - appversion (str, optional) – version for the new Session object, defaults to `"Other"`

      - user_agent (str, optional) –

        user agent to use, defaults to `"None"`. It should be of the following syntax:

        - Linux based -> `ClientName/client.version (Linux; Distro/distro_version)`

        - Non-linux based -> `ClientName/client.version (OS)`

  async async_api_request(endpoint, jsondata=None, data=None, additional_headers=None, method=None, params=None, no_condition_check=False, return_raw=False)

    Do an API request.

    This call can return any of the exceptions defined in `proton.session.exceptions`.

    Parameters:

      - endpoint (str) – API endpoint

      - jsondata (dict) – JSON serializable dict to send as request data

      - data (FormData) – data to be sent as either multipart/form-data or application/x-www-form-urlencoded. multipart/form-data is used when required, for example if data includes fields with a file-like value (i.e. is an instance of io.IOBase).

      - additional_headers (dict) – additional headers to send

      - method (str) – HTTP method (get|post|put|delete|patch)

      - params (str, dict or iterable) – URL parameters to append to the URL. If a dictionary or list of tuples `[(key, value)]` is provided, form-encoding will take place.

      - no_condition_check (bool, optional) – Internal flag to disable locking, defaults to False

      - return_raw (bool, optional) – If set to true, the function will return a `RawResponse` object instead of a dict, this class contains the header and status information along with the json response.

    Returns:

      Deserialized JSON reply or a RawResponse object if return_raw is True

    Return type:

      dict | RawResponse

  async async_authenticate(username: str, password: str, client_secret: str = None, no_condition_check: bool = False, additional_headers=None) → bool

    Authenticate against Proton API

    Parameters:

      - username (str) – Proton account username

      - password (str) – Proton account password

      - client_secret (str, optional) – Client Secret for SRP

      - no_condition_check (bool, optional) – Internal flag to disable locking, defaults to False

      - additional_headers (dict) – additional headers to send

    Returns:

      True if authentication succeeded, False otherwise.

    Return type:

      bool

  async async_provide_2fa(code: str, no_condition_check=False, additional_headers=None) → bool

    Provide Two Factor Authentication Code to the API.

    Parameters:

      - code (str) – 2FA code

      - no_condition_check (bool, optional) – Internal flag to disable locking, defaults to False

    Returns:

      True if 2FA succeeded, False otherwise.

    Return type:

      bool

    Raises:

      ProtonAPIAuthenticationNeeded – if 2FA failed, and the session was reset by the API backend (this is normally the case)

  async async_refresh(only_when_refresh_revision_is=None, no_condition_check=False, additional_headers=None)

    Refresh tokens.

    Refresh AccessToken with a valid RefreshToken. If the RefreshToken is invalid then the user will have to re-authenticate.

    Returns:

      True if refresh succeeded, False otherwise (doesn’t throw an exception)

    Return type:

      bool

  async async_logout(no_condition_check=False, additional_headers=None)

    Logout from API.

    Returns:

      True if logout was successful (or nothing was done)

    Return type:

      bool

  async async_lock(no_condition_check=False, additional_headers=None)

    Lock the current user (remove PASSWORD and LOCKED scopes)

  async async_human_verif_request_code(address=None, phone=None, additional_headers=None)

    Request a verification code. Either address (email address) or phone (phone number) should be specified.

  async async_human_verif_provide_token(method, token)
  async async_fork(child_client_id: str, payload: str = None, independent: int = 0, user_code: int = None, no_condition_check=False) → str

    Try to fork the current session with parameters and return the fork selector if successful.

    Parameters:

      - child_client_id (str) – The clientID that the client creating the child session will use.

      - payload (str, optional) – Will be downloaded by the child client, and can contain encrypted sensitive information.

      - independent (int, optional) – set to 1 if the newly forked session has to be independent, else 0.

      - user_code (int, optional) – If provided, the selector will not be randomly chosen, but rather the one already returned will be used.

      - no_condition_check (bool, optional) – Internal flag to disable locking, defaults to False

    Return selector:

      Fork selector to be used by method async_import_fork()

    Return type:

      str

  async async_import_fork(selector: str, no_condition_check=False) → str

    Try to import the session fork specified by the selector.

    Parameters:

      - selector (str) – Obtained via a successful call to async_fork()

      - no_condition_check (bool, optional) – Internal flag to disable locking, defaults to False

    Return payload:

      The payload sent by the parent session when initiating the fork.

    Return type:

      str

  api_request(**kw)

    Synchronous wrapper for `async_api_request()`

  authenticate(**kw)

    Synchronous wrapper for `async_authenticate()`

  provide_2fa(**kw)

    Synchronous wrapper for `async_provide_2fa()`

  logout(**kw)

    Synchronous wrapper for `async_logout()`

  refresh(**kw)

    Synchronous wrapper for `async_refresh()`

  lock(**kw)

    Synchronous wrapper for `async_lock()`

  human_verif_request_code(**kw)

    Synchronous wrapper for `async_human_verif_request_code()`

  human_verif_provide_token(**kw)

    Synchronous wrapper for `async_human_verif_provide_token()`

  fork(**kw)

    Synchronous wrapper for `async_fork()`

  import_fork(**kw)

    Synchronous wrapper for `async_import_fork()`

  register_persistence_observer(observer: object)

    Register an observer that will be notified of any persistent state change of the session

    Parameters:

      observer (object) –

      Observer to register. It has to provide the following interface (see `proton.sso.ProtonSSO` for an actual implementation):

      - `_acquire_session_lock(account_name : str, session_data : dict)`

      - `_release_session_lock(account_name : str, new_session_data : dict)`

  property transport_factory

    Set/read the factory used for transports (i.e. how to reach the API).

    If the property is set to a class, it will be wrapped in a factory.

    If the property is set to None, then the default `transport` will be obtained from `Loader`.

  property appversion: str
    Returns:

      The appversion defined at construction (used for creating requests by transports)

    Return type:

      str

  property user_agent: str
    Returns:

      The user_agent defined at construction (used for creating requests by transports)

    Return type:

      str

  property authenticated: bool
    Returns:

      True if session is authenticated, False otherwise.

    Return type:

      bool

  property UID: str | None
    Returns:

      the session UID, None if not authenticated

    Return type:

      str, optional

  property Scopes: list[str] | None
    Returns:

      list of scopes of the current session, None if unknown or not defined.

    Return type:

      list[str], optional

  property AccountName: str
    Returns:

      session account name (mostly used for SSO)

    Return type:

      str

  property AccessToken: str
    Returns:

      return the access token for API calls (used by transports)

    Return type:

      str

  property needs_twofa: bool
    Returns:

      True if a 2FA authentication is needed, False otherwise.

    Return type:

      bool

  property environment

    Get/set the environment in use for that session. It can be only set once at the beginning of the session’s object lifetime, as changing the environment can lead to security hole.

    If the new value is:

    - None: do nothing

    - a string: will use `Loader.get("environment", newvalue)()` to get the actual class.

    - an environment: use it

## Exceptions

Copyright (c) 2023 Proton AG

This file is part of Proton.

Proton is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

Proton is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with ProtonVPN. If not, see <https://www.gnu.org/licenses/>.

exception proton.session.exceptions.ProtonError(message, additional_context=None)

  Base class for Proton API specific exceptions

  add_note(object, /)

    Exception.add_note(note) – add a note to the exception

  with_traceback(object, /)

    Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception proton.session.exceptions.ProtonCryptoError(message, additional_context=None)

  Exception thrown when something is wrong on the crypto side. In general this has to be handled as being fatal, as something is super-wrong.

  add_note(object, /)

    Exception.add_note(note) – add a note to the exception

  with_traceback(object, /)

    Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception proton.session.exceptions.ProtonUnsupportedAuthVersionError(message, additional_context=None)

  When the auth_version returned by the API is lower then what is currently supported. This is usually fixed with a login via the webclient.

  add_note(object, /)

    Exception.add_note(note) – add a note to the exception

  with_traceback(object, /)

    Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception proton.session.exceptions.ProtonAPIError(http_code, http_headers, json_data)

  Exception that is raised whenever the API call didn’t return a 1000/1001 code. Logic for handling these depend on the call (see API doc)

  property http_code: int
    Returns:

      HTTP error code (401, 403, 422…)

    Return type:

      int

  property http_headers: dict
    Returns:

      Dictionary of HTTP headers of the error reply

    Return type:

      dict

  property json_data: dict
    Returns:

      JSON data of the error reply

    Return type:

      dict

  property body_code: int
    Returns:

      Body error code (“Code” in JSON)

    Return type:

      int

  property error: str
    Returns:

      Body error message (“Error” in JSON)

    Return type:

      str

  classmethod from_proton_api_error(e: ProtonAPIError)

    Construct an instance of this class, based on a ProtonAPIError (this allows to downcast to a more specific exception)

    Parameters:

      e (ProtonAPIError) – Initial API exception

    Returns:

      An instance of the current class

    Return type:

      Any

  add_note(object, /)

    Exception.add_note(note) – add a note to the exception

  with_traceback(object, /)

    Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception proton.session.exceptions.ProtonAPINotReachable(message, additional_context=None)

  Exception thrown when the transport couldn’t reach the API.

  One may try using a different transport, or later if the error is transient.

  add_note(object, /)

    Exception.add_note(note) – add a note to the exception

  with_traceback(object, /)

    Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception proton.session.exceptions.ProtonAPINotAvailable(message, additional_context=None)

  Exception thrown when the API is reachable (i.e. at the TLS level), but doesn’t work.

  This is definitive for that transport, it will not work by retrying in the same conditions.

  add_note(object, /)

    Exception.add_note(note) – add a note to the exception

  with_traceback(object, /)

    Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception proton.session.exceptions.ProtonAPIUnexpectedError(message, additional_context=None)

  Something went wrong, but we don’t know how to handle it. Good luck :-)

  add_note(object, /)

    Exception.add_note(note) – add a note to the exception

  with_traceback(object, /)

    Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception proton.session.exceptions.ProtonAPIAuthenticationNeeded(http_code, http_headers, json_data)

  We tried to call a route that requires authentication, but we don’t have it.

  This should be solved by calling session.authenticate() with valid credentials

  add_note(object, /)

    Exception.add_note(note) – add a note to the exception

  property body_code: int
    Returns:

      Body error code (“Code” in JSON)

    Return type:

      int

  property error: str
    Returns:

      Body error message (“Error” in JSON)

    Return type:

      str

  classmethod from_proton_api_error(e: ProtonAPIError)

    Construct an instance of this class, based on a ProtonAPIError (this allows to downcast to a more specific exception)

    Parameters:

      e (ProtonAPIError) – Initial API exception

    Returns:

      An instance of the current class

    Return type:

      Any

  property http_code: int
    Returns:

      HTTP error code (401, 403, 422…)

    Return type:

      int

  property http_headers: dict
    Returns:

      Dictionary of HTTP headers of the error reply

    Return type:

      dict

  property json_data: dict
    Returns:

      JSON data of the error reply

    Return type:

      dict

  with_traceback(object, /)

    Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception proton.session.exceptions.ProtonAPI2FANeeded(http_code, http_headers, json_data)

  We need 2FA authentication, but it’s not done yet.

  This should be solved by calling session.provide_2fa() with valid 2FA

  add_note(object, /)

    Exception.add_note(note) – add a note to the exception

  property body_code: int
    Returns:

      Body error code (“Code” in JSON)

    Return type:

      int

  property error: str
    Returns:

      Body error message (“Error” in JSON)

    Return type:

      str

  classmethod from_proton_api_error(e: ProtonAPIError)

    Construct an instance of this class, based on a ProtonAPIError (this allows to downcast to a more specific exception)

    Parameters:

      e (ProtonAPIError) – Initial API exception

    Returns:

      An instance of the current class

    Return type:

      Any

  property http_code: int
    Returns:

      HTTP error code (401, 403, 422…)

    Return type:

      int

  property http_headers: dict
    Returns:

      Dictionary of HTTP headers of the error reply

    Return type:

      dict

  property json_data: dict
    Returns:

      JSON data of the error reply

    Return type:

      dict

  with_traceback(object, /)

    Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception proton.session.exceptions.ProtonAPIMissingScopeError(http_code, http_headers, json_data)

  We don’t have a required scope.

  This might be because of user rights, but also might require a call to unlock.

  add_note(object, /)

    Exception.add_note(note) – add a note to the exception

  property body_code: int
    Returns:

      Body error code (“Code” in JSON)

    Return type:

      int

  property error: str
    Returns:

      Body error message (“Error” in JSON)

    Return type:

      str

  classmethod from_proton_api_error(e: ProtonAPIError)

    Construct an instance of this class, based on a ProtonAPIError (this allows to downcast to a more specific exception)

    Parameters:

      e (ProtonAPIError) – Initial API exception

    Returns:

      An instance of the current class

    Return type:

      Any

  property http_code: int
    Returns:

      HTTP error code (401, 403, 422…)

    Return type:

      int

  property http_headers: dict
    Returns:

      Dictionary of HTTP headers of the error reply

    Return type:

      dict

  property json_data: dict
    Returns:

      JSON data of the error reply

    Return type:

      dict

  with_traceback(object, /)

    Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception proton.session.exceptions.ProtonAPIHumanVerificationNeeded(http_code, http_headers, json_data)

  Human verification is needed for this API call to succeed.

  property HumanVerificationToken: str | None

    Get the Token for human verification

  property HumanVerificationMethods: list[str]

    Return a list of allowed human verification methods.

    Returns:

      human verification methods

    Return type:

      list[str]

  add_note(object, /)

    Exception.add_note(note) – add a note to the exception

  property body_code: int
    Returns:

      Body error code (“Code” in JSON)

    Return type:

      int

  property error: str
    Returns:

      Body error message (“Error” in JSON)

    Return type:

      str

  classmethod from_proton_api_error(e: ProtonAPIError)

    Construct an instance of this class, based on a ProtonAPIError (this allows to downcast to a more specific exception)

    Parameters:

      e (ProtonAPIError) – Initial API exception

    Returns:

      An instance of the current class

    Return type:

      Any

  property http_code: int
    Returns:

      HTTP error code (401, 403, 422…)

    Return type:

      int

  property http_headers: dict
    Returns:

      Dictionary of HTTP headers of the error reply

    Return type:

      dict

  property json_data: dict
    Returns:

      JSON data of the error reply

    Return type:

      dict

  with_traceback(object, /)

    Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.