import dbus,json,sys,time,pathlib
bus=dbus.SessionBus(); name='org.freedesktop.secrets'
service=dbus.Interface(bus.get_object(name,'/org/freedesktop/secrets'),'org.freedesktop.Secret.Service')
_,session=service.OpenSession('plain',dbus.String('',variant_level=1))
attrs={'server':'Chrome Keys','user':'Chrome Safe Storage','type':'plaintext','xdg:schema':'org.qt.keychain'}
collection=service.ReadAlias('default')
col=dbus.Interface(bus.get_object(name,collection),'org.freedesktop.Secret.Collection')
def props(p):return dbus.Interface(bus.get_object(name,p),'org.freedesktop.DBus.Properties').GetAll('org.freedesktop.Secret.Item')
def secret(p):return bytes(dbus.Interface(bus.get_object(name,p),'org.freedesktop.Secret.Item').GetSecret(session)[2])
def setsecret(p,value):return dbus.Interface(bus.get_object(name,p),'org.freedesktop.Secret.Item').SetSecret((session,dbus.ByteArray(b''),dbus.ByteArray(value),'text/plain'))
def create(label,value):
 return col.CreateItem({'org.freedesktop.Secret.Item.Label':dbus.String(label,variant_level=1),'org.freedesktop.Secret.Item.Attributes':dbus.Dictionary(attrs,signature='ss',variant_level=1)},(session,dbus.ByteArray(b''),dbus.ByteArray(value),'text/plain'),False)[0]
mode=sys.argv[1]; out=pathlib.Path(sys.argv[2]); out.mkdir(parents=True,exist_ok=True)
items=list(service.SearchItems({'server':'Chrome Keys','user':'Chrome Safe Storage'})[0])
current=next(secret(p) for p in items if secret(p)!=b'synthetic-stale-key')
if mode=='adversarial-newer':
 first,second=items
 setsecret(second,current)
 time.sleep(2)
 setsecret(first,b'synthetic-stale-key')
if mode=='tie-stale-first':
 first,second=items
 setsecret(first,b'synthetic-stale-key')
 setsecret(second,current)
if mode=='duplicate-newer-stale':
 assert len(items)==1
 original=items[0]
 create('Chrome Keys/Current migration copy',current)
 time.sleep(2)
 setsecret(original,b'synthetic-stale-key')
if mode=='tied':
 old=items
 # New items and both SetSecret calls use one clock second; report actual timestamps below.
 a=create('Chrome Keys/Stale tied copy',b'synthetic-stale-key')
 b=create('Chrome Keys/Current tied copy',current)
 for p in old:dbus.Interface(bus.get_object(name,p),'org.freedesktop.Secret.Item').Delete()
items=list(service.SearchItems({'server':'Chrome Keys','user':'Chrome Safe Storage'})[0])
result=[]
for p in items:
 x=props(p)
 result.append({'path':str(p),'label':str(x['Label']),'attributes':dict(x['Attributes']),'created':int(x['Created']),'modified':int(x['Modified']),'candidate':'stale' if secret(p)==b'synthetic-stale-key' else 'current'})
manifest={'provider':'native ksecretd 6.30.0','case':mode,'searchOrder':result,'applicationChromeMatches':len(service.SearchItems({'application':'chrome'})[0])}
(out/'wallet-state.json').write_text(json.dumps(manifest,indent=2))
print(json.dumps(manifest,indent=2))
