Author SHA1 Message Date
BobbyandClaude Opus 5.5 85cc7961b8 task: add history and spot probes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 15:15:57 -05:00
BobbyandClaude Opus 5.5 06c7091bb3 task: set User-Agent on claim (Cloudflare 1010), show error bodies
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 15:06:40 -05:00
BobbyandClaude Opus 5.5 76ee576a02 task: SimpleFIN coverage probe for #66
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:47:39 -05:00
BobbyandClaude Opus 5.5 5e8e2b8c0a new: public edge gateway, certificates, and DNS (ADR-0010)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:39:14 -05:00
BobbyandClaude Opus 5.5 8519546269 new: Smart home scope line (Jobs only, HA owns house state)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:22:05 -05:00
BobbyandClaude Opus 5.5 3f9a4b880a new: Maintenance vocabulary (Asset, Task, Service, Reading)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:05:53 -05:00
BobbyandClaude Opus 5.5 ef87951061 new: Fitness vocabulary (Workout, Exercise, Set, Measurement)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:07:07 -05:00
3 changed files with 332 additions and 1 deletions

No files matched your search

+41 -1
View File
@@ -1,6 +1,6 @@
# hAPI
hAPI ("home API") is a personal, cloud-hosted API serving one household and its automations: finance, fitness, home maintenance, and smart home. Access is restricted to a small, known set of Principals.
hAPI ("home API") is a personal, cloud-hosted API serving one household and its automations: finance, fitness, maintenance, and smart home. Access is restricted to a small, known set of Principals.
## Language
@@ -62,6 +62,8 @@ _Avoid_: Author, owner, creator
### Smart home
Smart home is hAPI's side of the house: queuing Jobs for Home Assistant, which remains the source of truth for the house's state.
**Job**:
A request, queued in hAPI, for Home Assistant to carry out an action in the house. Jobs are Household data. Domain code, Persons, and Bots can all create them.
_Avoid_: Task, command, message
@@ -103,3 +105,41 @@ _Avoid_: Sinking fund, rollover, savings
**Payee mapping**:
An owner's remembered link from a payee to a Category, learned from manual categorization and applied to newly ingested Transactions.
_Avoid_: Rule, auto-categorization
### Maintenance
Maintenance is the upkeep of the Household's physical property: the home, its land, its equipment, and its vehicles.
**Asset**:
A physical thing the Household keeps up, such as the roof, the furnace, a fridge, or a car. It may have a meter whose Readings track its use.
_Avoid_: Equipment, item, entity (a Home Assistant term); in Finance, use another word
**Task**:
A recurring piece of upkeep, due either a fixed interval after it was last done or on a calendar rhythm, and optionally also after a set amount of use. Tasks always recur; one-off work is recorded only as a Service.
_Avoid_: Chore, reminder, to-do (and never a Job)
**Service**:
One piece of maintenance work done on a date. It may fulfill a Task, and may concern an Asset.
_Avoid_: Completion, repair, log entry
**Reading**:
An Asset's meter value (an odometer's distance or a runtime counter) taken on a date, used to decide when usage-based Tasks come due.
_Avoid_: Measurement (a Fitness term), metric
### Fitness
**Workout**:
One session of exercise by one Person: an ordered list of Exercises performed, with what was done in each. A run is a Workout with a single cardio Exercise.
_Avoid_: Session, activity, training
**Exercise**:
A named movement that Workouts record, of kind strength, bodyweight, timed, or cardio; the kind decides what is recorded for it. Household Exercises can be used by every Household member; Personal Exercises only by their Person.
_Avoid_: Movement, lift, activity
**Set**:
One bout of a strength, bodyweight, or timed Exercise within a Workout: reps and load, or a duration. A warmup Set doesn't count toward records.
_Avoid_: Rep, round
**Measurement**:
One reading of a Person's body (weight, body fat, or a circumference) at a point in time.
_Avoid_: Metric, stat, body stat
@@ -0,0 +1,37 @@
# Envoy Gateway at the edge, DNS-01 through a delegated challenge zone, CAA pinned to our account
Public traffic reaches hAPI on one hostname, **`hapi.bobbypalko.com`**, over IPv4 only. OpenTofu reserves the IPv4 address. A Linode NodeBalancer created by the CCM listens on that address in **TCP mode** and sends **Proxy Protocol v2** to an **Envoy Gateway**. Envoy Gateway terminates TLS and forwards plain HTTP to hAPI `:8000`; Cilium's WireGuard encrypts traffic between nodes. There's no CDN (ADR-0002), so the Gateway is the only shield and enforces the edge limits. Envoy Gateway was chosen over Cilium's built-in Gateway because Cilium's Gateway has none of the limits we need as typed policy. Certificates come from **cert-manager** and Let's Encrypt over DNS-01, because `:80` is closed. The DNS-01 credential can only edit a separate, delegated **`acme.bobbypalko.com`** zone, not `bobbypalko.com` itself. A **CAA record pinned to our ACME account** means that even a leaked DNS token can't get a certificate for us.
## Considered Options
- **Cilium's built-in Gateway** (it's already the CNI, ADR-0003). It has one component fewer, but as of v1.20 it offers only global switches (Proxy Protocol, ALPN, trusted XFF hops). It has no rate limiting, connection limits, body or header limits, client timeouts or minimum-TLS policy. The only workaround is hand-written CiliumEnvoyConfig, which doesn't cleanly patch the listeners Cilium generates. Rejected.
- **Traefik with built-in ACME.** It renews certificates just as cert-manager does, but Traefik OSS keeps ACME state in a local file, so it can't run more than one replica. It would also still need the same DNS credential. Rejected.
- **A DNS-01 token on the whole `bobbypalko.com` zone** (an IAM restricted user with `domain_admin` on it). Simpler, but a leaked token could repoint `git.` or any other record. Rejected under ADR-0008's narrow-token rule.
- **Moving DNS to Cloudflare** for per-zone tokens. Rejected: it moves the whole zone to buy a token scope we can get with a delegated subzone.
- **Self-hosted acme-dns.** It has the narrowest credential, but it means running a public DNS server. Kept as the fallback if the delegated-zone setup doesn't hold up (see Consequences).
- **TLS terminated at the NodeBalancer (HTTPS mode).** Rejected: cert-manager can't rotate a certificate uploaded to Linode, and traffic from the NodeBalancer to the nodes would cross the unencrypted VPC in plaintext.
- **A backup ACME CA (GTS, ZeroSSL).** Deferred: each needs EAB credentials, which is one more secret to manage, plus its own CAA entry.
## Consequences
- **Tofu owns the stable parts:** the reserved IPv4, the NodeBalancer's Cloud Firewall (inbound TCP 443 only), the `A` record, the `_acme-challenge.hapi` CNAME, the `acme.` delegation and the CAA record. The Gateway's Service references the IP and the firewall through the CCM's `reserved-ipv4` and `firewall-id` annotations. The CCM creates and recreates the NodeBalancer without changing the address. There's no external-dns.
- **No `AAAA`.** The NodeBalancer's IPv6 frontend address can't be reserved, so recreating the NodeBalancer would silently break the record.
- **NodeBalancer:** `default-protocol: tcp`, `default-proxy-protocol: v2`, `throttle: 20` (new connections per second per client IP; the Household shares one CGNAT IP), and VPC backends.
- **Envoy Gateway:** 2 Envoy replicas spread across both workers, with a PDB and memory requests tuned down from the chart's 512Mi. The Gateway accepts Proxy Protocol only.
- `ClientTrafficPolicy`: TLS 1.3 only; ALPN h2 and http/1.1 (no HTTP/3); headers up to 16 KiB; about 50 connections per IP; request timeout 30 s, idle 60 s; client IP taken from Proxy Protocol.
- `BackendTrafficPolicy`: per-IP local rate limit of about 20 req/s, burst 100 (per replica, no Redis), and bodies up to 1 MiB (413). The app caps `transactions/ingest` batches on its own.
- HSTS is set at the edge. There's no per-Principal rate limiting (ADR-0005).
- **uvicorn trusts `X-Forwarded-For` only from the Gateway's pod range.** That way, logs and limits see the real client.
- **Layout:** one `Gateway` in a `gateway` namespace with a single HTTPS listener for `hapi.bobbypalko.com` and `allowedRoutes` limited to the `hapi` namespace. One `HTTPRoute` sends traffic to `:8000`; `:8081` is never routed (ADR-0009). Any other SNI or Host gets no certificate and no route.
- **Certificates:**
- cert-manager uses an ACME ClusterIssuer for Let's Encrypt on the default profile, plus a staging issuer for bring-up. `renewBefore` stays at its default, which is a proportion of the lifetime, so lifetimes can shrink (64 days from Feb 2027, 45 from 2028) without changes on our side. The DNS-01 solver is `linode/cert-manager-webhook-linode` with `cnameStrategy: Follow`.
- The webhook's token belongs to a **restricted Linode user** with `domain_admin` on `acme.bobbypalko.com` only. It's delivered through SOPS (ADR-0008).
- **CAA on `hapi.bobbypalko.com`** (not the apex, so other hostnames are unaffected): `0 issue "letsencrypt.org; validationmethods=dns-01; accounturi=<our account>"`.
- **The ACME account key is generated offline and committed SOPS-encrypted.** A cluster rebuilt from code (ADR-0003) reuses the same account. Otherwise the CAA pin would block our own issuance.
- **Verify during the build:**
1. That a restricted user's token really is capped by the user's grants: it must fail to edit `bobbypalko.com`.
2. That Linode serves the delegated `acme.` subzone.
3. That the CCM copies Gateway `spec.infrastructure` / `EnvoyProxy` Service annotations onto the NodeBalancer.
If either of the first two fails, switch to acme-dns before going live.
- **Delivery (ADR-0007):** cert-manager with the webhook, and Envoy Gateway with the **Standard-channel** Gateway API CRDs, arrive as Flux `HelmRelease`s in `deploy/infrastructure`. Cilium runs with `gatewayAPI.enabled=false`, so two controllers never compete for the CRDs. Renovate opens PRs for these charts, but they aren't auto-merged.
- **Observability (ADR-0009):** Envoy writes JSON access logs to stdout (client IP, status, bytes, duration, rate-limit verdict), without `Authorization` or query strings. Vector ships them to VictoriaLogs with the standard 30-day retention. Kuma's TLS-expiry notification on the `/v1/health` monitor alerts at 14 days. A vmalert rule on `certmanager_certificate_expiration_timestamp_seconds` is the in-cluster backstop.
+254
View File
@@ -0,0 +1,254 @@
#!/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
# Cloudflare in front of SimpleFIN rejects Python-urllib's default UA (error 1010).
UA = "hapi-simplefin-probe/1"
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-<hex32>' or '<uuid>'."""
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 "<uuid>"
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": UA})
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)}): {e.read()[:200].decode(errors='replace')}")
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", "User-Agent": UA})
try:
with urllib.request.urlopen(req, timeout=60) as r:
url = r.read().decode().strip()
except urllib.error.HTTPError as e:
die(f"HTTP {e.code} from claim: {e.read()[:200].decode(errors='replace')}")
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")
def cmd_history() -> None:
"""Pull 40-day slices back 200 days: is there a per-response cap, and how deep is history? (5 requests)"""
url = access_url()
now = int(time.time())
print("slice (days ago) per account: count, posted range")
for lo in range(0, 200, 40):
resp = get_accounts(url, **{"start-date": str(now - (lo + 40) * DAY), "end-date": str(now - lo * DAY)})
conns = {c.get("conn_id"): c for c in resp.get("connections") or []}
for a in resp.get("accounts", []):
ps = [t["posted"] for t in a.get("transactions") or [] if t.get("posted")]
print(f" {lo:3d}..{lo + 40:3d} {org_of(a, conns)!r}: {len(ps):3d} {day(min(ps, default=None))} .. {day(max(ps, default=None))}")
def cmd_spot() -> None:
"""LOCAL ONLY, do not paste: last 10 days, raw dates + amounts to compare with the bank's website. (1 request)"""
url = access_url()
now = int(time.time())
resp = get_accounts(url, **{"start-date": str(now - 10 * DAY)})
conns = {c.get("conn_id"): c for c in resp.get("connections") or []}
fmt = lambda ts: datetime.fromtimestamp(ts, UTC).strftime("%Y-%m-%d %H:%M:%SZ") if ts else "-" # noqa: E731
print("!! Contains amounts and descriptions. Compare with the bank site; do NOT paste this output.\n")
for a in resp.get("accounts", []):
print(f"{org_of(a, conns)} {(a.get('name') or '')[:3]}…")
print(f" {'posted':21} {'transacted_at':21} {'amount':>10} description")
for t in sorted(a.get("transactions") or [], key=lambda t: t.get("posted") or 0, reverse=True)[:15]:
print(f" {fmt(t.get('posted')):21} {fmt(t.get('transacted_at')):21} {t.get('amount', ''):>10} {(t.get('description') or '')[:30]}")
if __name__ == "__main__":
{"claim": cmd_claim, "run": cmd_run, "recheck": cmd_recheck, "history": cmd_history, "spot": cmd_spot}.get(
sys.argv[1] if len(sys.argv) > 1 else "", lambda: die("usage: probe.py claim|run|recheck|history|spot"))()