#!/usr/bin/env python3
"""kept-delete.py APP — delete ONE kept-data item on scratch guest 9202 through the product's own page (the ending
"kept data of a removed app is deleted"). It reads /kept-data, finds the one row whose path ends in /appdata/APP, and
posts /kept-data/delete with the typed confirmation, as the household does. It refuses when it finds 0 or 2+ rows.
EVIDENCE, NOT PRODUCT. Environment: SC, EV, TARGET=9202."""
import html, json, os, re, sys, time
sys.path.insert(0, "/mnt/5_hdd/felhom.eu/git/app-catalog-felhom.eu/scripts")
import box_walk as w
app = sys.argv[1]
w.login()
pg = w.page("/kept-data")
forms = re.findall(r'
', pg, re.S)
rows = []
for f in forms:
p = re.search(r'name="path"\s+value="([^"]+)"', f)
if p:
rows.append((html.unescape(p.group(1)), f))
w.say(f"kept rows on the page: {[r[0] for r in rows]}")
mine = [r for r in rows if r[0].rstrip("/").endswith("/appdata/" + app)]
if len(mine) != 1:
sys.exit(f"REFUSED: {len(mine)} rows match /appdata/{app}")
path, form = mine[0]
m = re.search(r'', form) # the page's own prompt: "... type: "
if not m:
sys.exit("REFUSED: no typed-confirmation prompt found in the form")
names = [html.unescape(m.group(1)).strip()]
w.say(f"the page asks to type: {names[0]!r}")
sess = open(f"{w.SC}/sess{os.getpid()}.txt").read().strip()
csrf = open(f"{w.SC}/csrf{os.getpid()}.txt").read().strip()
r = w.sh(["curl", "-sk", "-D", "-", "-o", "/dev/null", "-H", w.HOSTHDR, "-H", f"Cookie: {sess}", "-X", "POST",
"--data-urlencode", f"_csrf={csrf}", "--data-urlencode", f"path={path}",
"--data-urlencode", f"confirm={names[0]}", f"{w.BASE}/kept-data/delete"])
head = (r.stdout or "").split("\n")[0].strip()
loc = [l.strip() for l in (r.stdout or "").split("\n") if l.lower().startswith("location:")]
w.say(f"POST /kept-data/delete path={path} -> {head} {loc[:1]}")
time.sleep(3)
left = [x for x in re.findall(r'name="path"\s+value="([^"]+)"', w.page("/kept-data"))]
w.say(f"kept rows after: {sorted(set(html.unescape(x) for x in left))}")
json.dump({"path": path, "http": head, "location": loc, "rows_before": [r[0] for r in rows], "log": w.LOG},
open(os.path.join(os.environ["EV"], f"kept-delete-{app}-{int(time.time())}.json"), "w"), indent=1)