import json, io, sys, base64
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
HAR = r'E:\ios\vinfast\Untitled.har'
d = json.load(open(HAR, encoding='utf-8'))
entries = d['log']['entries']

def hmap(h):
    return {x['name'].lower(): x['value'] for x in h}

pad = lambda s: s + '=' * (-len(s) % 4)

# 1) Cac loai authorization xuat hien o host backend
print('== CÁC LOẠI AUTHORIZATION ở mobile.connected-car ==')
bearer_tok = None
basic_seen = set()
for e in entries:
    if 'mobile.connected-car' not in e['request']['url']: continue
    a = hmap(e['request']['headers']).get('authorization', '')
    if a.startswith('Basic '):
        raw = base64.b64decode(pad(a[6:])).decode('utf-8', 'replace')
        basic_seen.add(raw)
    elif a.startswith('Bearer ') and bearer_tok is None:
        bearer_tok = a[7:].strip()

for b in basic_seen:
    print('   BASIC credential (decoded):', b)
print('   Bearer JWT len:', len(bearer_tok or ''))

# 2) Decode JWT
if bearer_tok and bearer_tok.count('.') == 2:
    claims = json.loads(base64.urlsafe_b64decode(pad(bearer_tok.split('.')[1])))
    print('\n== JWT THẬT CỦA iOS APP (payload) ==')
    for k, v in claims.items():
        print(f'   {k}: {json.dumps(v, ensure_ascii=False)[:200]}')

# 3) Bang 44 request backend
print('\n== TOÀN BỘ REQ tới mobile.connected-car.vinfast.vn ==')
for e in entries:
    u = e['request']['url']
    if 'mobile.connected-car' not in u: continue
    rq = e['request']
    path = '/' + u.split('/', 3)[3] if u.count('/') >= 3 else u
    h = hmap(rq['headers'])
    sig = []
    for k in ('x-hash', 'x-hash-2', 'x-timestamp', 'x-service-name', 'x-app-version',
              'x-device-identifier', 'x-vin-code', 'x-player-identifier', 'content-type',
              'x-country', 'x-timezone', 'x-device-family', 'x-device-locale', 'x-os-version',
              'x-device-id', 'x-user-agent', 'authorization'):
        if k in h:
            v = h[k]
            if k == 'authorization':
                v = v.split(' ')[0] + ':' + v[-8:]
            sig.append(f'{k}={v[:46]}')
    print(f"[{e['response']['status']}] {rq['method']:4s} {path[:110]}")
    if sig:
        print('      ' + ' | '.join(sig))
