from curl_cffi import requests
from concurrent.futures import ThreadPoolExecutor,as_completed
from pathlib import Path
from urllib.parse import quote
import re,json
BASE='https://mein-portal.baloise.de/auth/rest/oauth2/authorization-servers/'
terms=set(Path('work/scratch/selector-candidates.txt').read_text().split())
terms |= set('''oauth oauth2 oidc openid openidconnect openid-connect authorization authorization-server auth authserver as iam airlock baloise basler easylogin easy-login external internal public private partner broker makler portal kunden web mobile api resource resources test dev prod production default main primary legacy new v1 v2 venta ao mo si sas va guidewire gw pc bc cc cm bsi crm bipro tgic employee customer user admin service technical techclient tech-client sso saml'''.split())
for a in list(terms):
 for pre in ('oauth2-','oauth2_','oidc-','oidc_','as-','as_','auth-','auth_'):
  if len(pre+a)<=30:terms.add(pre+a)
 for suf in ('-oauth2','_oauth2','-oidc','_oidc','-as','_as'):
  if len(a+suf)<=30:terms.add(a+suf)
apps=sorted(x for x in terms if 1<=len(x)<=30 and x==x.lower() and re.fullmatch(r'[a-z0-9_-]+',x))
known=set('''baloise easylogin easy-login easy_login external guidewire_bc guidewire_cc guidewire_cm guidewire_pc portal_ao portal_mo portal_si sas_va venta default test antragsfreigabe bsi_crm'''.split())
apps=[x for x in apps if x not in known]
print('candidates',len(apps),flush=True)
Path('work/scratch/oauth-as-candidates.txt').write_text('\n'.join(apps))
def one(a):
 try:
  r=requests.get(BASE+quote(a,safe='')+'/.well-known/openid-configuration',headers={'X-Bug-Bounty':'dwbzn','Accept':'application/json'},verify=False,timeout=15,toadex_capture=False)
  if r.status_code!=404 or 'AUTHORIZATION_SERVER_NOT_FOUND' not in r.text:
   return (a,r.status_code,len(r.content),r.headers.get('Content-Type',''),r.text[:1000].replace('\n',' '))
 except Exception as e:return(a,0,0,'',repr(e))
h=[]
with ThreadPoolExecutor(max_workers=16) as ex:
 for f in as_completed([ex.submit(one,a) for a in apps]):
  x=f.result()
  if x: h.append(x);print('\t'.join(map(str,x)),flush=True)
Path('work/scratch/oauth-as-hits.json').write_text(json.dumps(h,indent=2))
print('done hits',len(h),flush=True)
