diff --git a/docs/research/simplefin-66/probe.py b/docs/research/simplefin-66/probe.py new file mode 100644 index 0000000..8ead7d6 --- /dev/null +++ b/docs/research/simplefin-66/probe.py @@ -0,0 +1,221 @@ +#!/usr/bin/env python3 +"""SimpleFIN coverage probe for "Check whether SimpleFIN covers Capital One and Fulton with purchase dates". + +Run by the Owner on their own machine, stdlib only: + + python3 -I probe.py claim # exchange a Setup Token for an Access URL (one time) + python3 -I probe.py run # pull accounts and print a redacted summary + python3 -I probe.py recheck # a day or more later: did ids survive, did pending ids post? + +Secrets are read with getpass and are never printed or written. Output contains no +amounts, descriptions, payees, or raw ids: ids are HMAC-hashed with a per-machine salt. +A redacted snapshot (hashed ids + dates) is kept in ~/.local/state/hapi-simplefin-probe/ +(mode 0600) so `recheck` can compare. Delete that directory when the ticket closes. + +Each `run` makes 4 requests and `recheck` makes 2; SimpleFIN allows ~24 per day. +""" + +from __future__ import annotations + +import base64 +import getpass +import hashlib +import hmac +import json +import os +import re +import secrets +import statistics +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +from collections import Counter +from datetime import UTC, datetime +from pathlib import Path + +STATE = Path.home() / ".local/state/hapi-simplefin-probe" +DAY = 86400 + + +def die(msg: str) -> None: + print(f"error: {msg}", file=sys.stderr) + sys.exit(1) + + +def salt() -> bytes: + STATE.mkdir(parents=True, exist_ok=True, mode=0o700) + p = STATE / "salt" + if not p.exists(): + p.write_bytes(secrets.token_bytes(32)) + p.chmod(0o600) + return p.read_bytes() + + +def h(value: str) -> str: + return hmac.new(salt(), value.encode(), hashlib.sha256).hexdigest()[:16] + + +def id_shape(value: str) -> str: + """Describe an id's shape without revealing it, e.g. 'TRN-' or ''.""" + if re.fullmatch(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", value, re.I): + return "" + m = re.fullmatch(r"([A-Za-z]+[-_])(.*)", value) + prefix, rest = (m.group(1), m.group(2)) if m else ("", value) + if re.fullmatch(r"[0-9a-fA-F]+", rest): + kind = "hex" + elif rest.isdigit(): + kind = "digits" + else: + kind = "mixed" + return f"{prefix}<{kind}{len(rest)}>" + + +def day(ts: int | None) -> str: + return datetime.fromtimestamp(ts, UTC).date().isoformat() if ts else "-" + + +def access_url() -> str: + url = os.environ.get("SIMPLEFIN_ACCESS_URL") or getpass.getpass("Access URL (hidden): ") + if not url.startswith("https://"): + die("Access URL must start with https://") + return url.strip() + + +def get_accounts(url: str, **params: str) -> dict: + u = urllib.parse.urlsplit(url) + if not (u.username and u.password): + die("Access URL has no embedded credentials") + netloc = u.hostname + (f":{u.port}" if u.port else "") + base = urllib.parse.urlunsplit((u.scheme, netloc, u.path.rstrip("/") + "/accounts", "", "")) + full = base + ("?" + urllib.parse.urlencode(params) if params else "") + cred = base64.b64encode(f"{urllib.parse.unquote(u.username)}:{urllib.parse.unquote(u.password)}".encode()).decode() + req = urllib.request.Request(full, headers={"Authorization": f"Basic {cred}", "User-Agent": "simplefin-probe"}) + try: + with urllib.request.urlopen(req, timeout=120) as r: + return json.load(r) + except urllib.error.HTTPError as e: + die(f"HTTP {e.code} from /accounts (params {sorted(params)})") + return {} + + +def org_of(acct: dict, conns: dict) -> str: + org = acct.get("org") or conns.get(acct.get("conn_id"), {}) + return org.get("name") or org.get("domain") or "?" + + +def errors_of(resp: dict) -> list[str]: + errs = list(resp.get("errors") or []) + for e in resp.get("errlist") or []: + errs.append(e.get("msg") or e.get("code") or str(e)) + return errs + + +def summarize(label: str, resp: dict) -> dict[str, dict]: + conns = {c.get("conn_id"): c for c in resp.get("connections") or []} + out: dict[str, dict] = {} + print(f"\n== {label} ==") + for err in errors_of(resp): + print(f" server message: {err}") + for a in resp.get("accounts", []): + txns = a.get("transactions") or [] + posted = [t for t in txns if t.get("posted")] + with_ta = [t for t in posted if t.get("transacted_at")] + lags = [(t["posted"] - t["transacted_at"]) / DAY for t in with_ta] + keys = Counter(k for t in txns for k in t) + shapes = Counter(id_shape(str(t.get("id", ""))) for t in txns) + ids = [str(t.get("id")) for t in txns] + key = h(f"{a.get('id')}") + out[key] = { + "org": org_of(a, conns), + "ids": {h(f"{a.get('id')}:{t.get('id')}"): {"posted": t.get("posted"), "ta": t.get("transacted_at"), + "pending": bool(t.get("pending"))} for t in txns}, + } + print(f" account {key} org={org_of(a, conns)!r} name~{(a.get('name') or '')[:3]}… currency={a.get('currency')}") + print(f" transactions: {len(txns)} ({len(posted)} posted, {len(txns) - len(posted)} pending/unposted)") + print(f" posted range: {day(min((t['posted'] for t in posted), default=None))} .. {day(max((t['posted'] for t in posted), default=None))}") + print(f" transacted_at present: {len(with_ta)}/{len(posted)} posted" + + (f"; posted − transacted_at days: min {min(lags):.1f}, median {statistics.median(lags):.1f}, max {max(lags):.1f}" if lags else "")) + print(f" fields seen: {dict(sorted(keys.items()))}") + print(f" id shapes: {dict(shapes)}; unique within account: {len(set(ids)) == len(ids)}") + if a.get("extra"): + print(f" account extra keys: {sorted(a['extra'])}") + return out + + +def save(name: str, data: dict) -> None: + p = STATE / f"{name}.json" + p.write_text(json.dumps({"at": int(time.time()), "accounts": data})) + p.chmod(0o600) + + +def compare(a: dict, b: dict, what: str) -> None: + print(f"\n== id stability: {what} ==") + for acct, snap in a.items(): + other = b.get(acct) + if not other: + print(f" account {acct}: missing from second pull") + continue + overlap_window = [i for i, t in snap["ids"].items() + if t["posted"] and min(x["posted"] or 1e12 for x in other["ids"].values()) <= t["posted"]] + kept = sum(1 for i in overlap_window if i in other["ids"]) + print(f" account {acct} ({snap['org']}): {kept}/{len(overlap_window)} posted ids reappear in the overlapping window") + + +def cmd_claim() -> None: + token = getpass.getpass("Setup Token (hidden): ").strip() + claim = base64.b64decode(token).decode() + if not claim.startswith("https://"): + die("Setup Token did not decode to an https URL") + req = urllib.request.Request(claim, method="POST", data=b"", headers={"Content-Length": "0"}) + with urllib.request.urlopen(req, timeout=60) as r: + url = r.read().decode().strip() + print("\nAccess URL obtained (not printed). A Setup Token can be claimed only once,") + print("so save the Access URL to Vaultwarden now; `run` will prompt for it.") + if input("Show it once to copy into Vaultwarden? [y/N] ").lower() == "y": + print(url) + print("\n(Clear your terminal scrollback after saving it.)") + + +def cmd_run() -> None: + url = access_url() + now = int(time.time()) + default = get_accounts(url) + summarize("default request (no params: posted only, server's default window)", default) + w90 = get_accounts(url, **{"start-date": str(now - 89 * DAY)}) + s1 = summarize("start-date = 89 days ago", w90) + old = get_accounts(url, **{"start-date": str(now - 365 * DAY), "end-date": str(now - 276 * DAY)}) + summarize("history probe: 365..276 days ago (is older history available?)", old) + pend = get_accounts(url, **{"start-date": str(now - 14 * DAY), "pending": "1"}) + sp = summarize("last 14 days with pending=1", pend) + save("run", s1) + save("pending", sp) + print("\nSaved redacted snapshot for `recheck`. Run it again in ≥1 day.") + + +def cmd_recheck() -> None: + try: + first = json.loads((STATE / "run.json").read_text())["accounts"] + pend = json.loads((STATE / "pending.json").read_text())["accounts"] + except FileNotFoundError: + die("no snapshot: run `probe.py run` first") + url = access_url() + now = int(time.time()) + again = summarize("start-date = 89 days ago (recheck)", get_accounts(url, **{"start-date": str(now - 89 * DAY)})) + compare(first, again, "posted ids across pulls") + later = summarize("last 14 days with pending=1 (recheck)", get_accounts(url, **{"start-date": str(now - 14 * DAY), "pending": "1"})) + print("\n== pending → posted ==") + for acct, snap in pend.items(): + was_pending = [i for i, t in snap["ids"].items() if t["pending"] or not t["posted"]] + now_ids = later.get(acct, {}).get("ids", {}) + same_id_posted = sum(1 for i in was_pending if i in now_ids and now_ids[i]["posted"]) + still_pending = sum(1 for i in was_pending if i in now_ids and not now_ids[i]["posted"]) + vanished = sum(1 for i in was_pending if i not in now_ids) + print(f" account {acct} ({snap['org']}): {len(was_pending)} were pending → " + f"{same_id_posted} posted under the same id, {still_pending} still pending, {vanished} id gone") + + +if __name__ == "__main__": + {"claim": cmd_claim, "run": cmd_run, "recheck": cmd_recheck}.get( + sys.argv[1] if len(sys.argv) > 1 else "", lambda: die("usage: probe.py claim|run|recheck"))()