"""Pim's side of the cross-provider path: the recipients Pim shared a memory with, and how it asks them. When John moved, Pim had already given his old address to others: Bay Parcel, the courier, which is the reference Company (its own process, its own origin, its own key; see company/README.md), and two recipients this demo simulates inside Pim's own process and labels as such: Harbor Pharmacy, which only acknowledges a deletion through a plain API and issues no evidence, and Oakland Utilities, which is offline when first asked and, when reached, publishes no ForgetMe endpoint at all. Pim talks to the Company as a Poppy 1.0 Personal Agent (`poppy_agent.py` signs; this module speaks): - **discovery** (spec 3, 3.2): `/.well-known/poppy.json`, checked against the host that served it and the protocol version Pim implements; the protected resource metadata, then the issuer's metadata, checked against each other; the `stellarminds.ai/forget-me` entry with its endpoint and scope names; whether the Company lists the Operations extension, version 3; the ForgetMe index with the issuer's keys; - **account access** (spec 4): a refresh token for John's account (the demo's labelled fixture stands in for the sign-in a fictional user cannot do), exchanged at the token endpoint with a client assertion for an access token, refreshed when it expires or is refused; - **one Session per scenario and Company** (spec 5): a random `sid` and User ID, the same `Poppy-Version` and `Poppy-Extensions` on every request, a fresh Session JWT per request, no Session header on the discovery documents or the token endpoint; - **approval** (Operations, version 3): at preview time Pim asks the Company what a withdrawal would perform and receives the operation with its exact terms; those terms are what the person sees and approves in the button; at execution Pim sends the same request with the person's approval, and the Company performs it once. Pim never approves on its own, and an unavailable extension never lets any other flow stand in. For each recipient the person chose to ask, Pim previews with the recipient-specific opaque reference it got when it shared the record (never an email, never the address as a locator), submits with one idempotency key per (operation, recipient), polls, fetches the recipient's evidence, verifies every portable receipt against the keys the recipient publishes, and shows one row per holder of the recipient. An unreachable recipient ends `queued` and is retried on later status reads under the same operation id. A recipient without ForgetMe is Pim's observation, never a receipt. Nothing here is reachable without a Company configured: `FORGETME_COMPANY_URL` turns the cross-provider level on; without it Pim is the local-only host of phase 1. """ from __future__ import annotations import os import secrets import time from datetime import datetime, timezone from pathlib import Path from urllib.parse import urlsplit import httpx from forgetproof import forgetme, receipt if __package__: from . import poppy_agent else: # pragma: no cover - `python demo/forgetme.py` import poppy_agent # type: ignore MAX_ATTEMPTS = 10 OPERATIONS = ("operations", "3") DECLARES = {forgetme.NAMESPACE: forgetme.VERSION, "operations": "3"} # what Pim speaks; declared only when the Company lists it def company_url() -> str | None: """The Company's origin, read when asked (so a test or the recorder can set it after import).""" return (os.environ.get("FORGETME_COMPANY_URL") or "").rstrip("/") or None def pim_origin() -> str: """Pim's own public origin: the Company fetches Pim's client metadata document there (spec 4.1).""" env = os.environ.get("PIM_ORIGIN") if env: return env.rstrip("/") dom = os.environ.get("RAILWAY_PUBLIC_DOMAIN") if dom: return f"https://{dom}" return f"http://127.0.0.1:{os.environ.get('PORT', '8080')}" def timeout() -> float: return float(os.environ.get("FORGETME_RECIPIENT_TIMEOUT", "8")) def poll_seconds() -> float: """How long one ask waits for the recipient to finish before leaving the row pending.""" return float(os.environ.get("FORGETME_RECIPIENT_POLL", "20")) def retry_after() -> float: """How long before an unreachable recipient is tried again, on a status read.""" return float(os.environ.get("FORGETME_RECIPIENT_RETRY", "3")) COMPANY_ID = "bay-parcel" SIMULATED = { "harbor-pharmacy": {"party": "Harbor Pharmacy (simulated)", "kind": "api-only", "what": "a pharmacy that takes deletion requests through a plain API and acknowledges them; it keeps no ForgetMe endpoint, so nothing it holds can be inspected from here"}, "oakland-utilities": {"party": "Oakland Utilities (simulated)", "kind": "offline", "what": "a utility that is unreachable when first asked; when reached, it publishes no ForgetMe endpoint, so Pim can only observe that"}, } _agent: poppy_agent.Agent | None = None def agent() -> poppy_agent.Agent: """Pim's Poppy identity: one P-256 key beside the site's receipt key (FORGETPROOF_HOME), created on first use.""" global _agent if _agent is None: _agent = poppy_agent.Agent.from_file(Path(receipt.key_path()).parent / "pim-poppy-es256.pem") return _agent def reset_agent() -> None: # tests that change FORGETPROOF_HOME global _agent _agent = None def now() -> str: return datetime.now(timezone.utc).isoformat(timespec="seconds") def enabled() -> bool: return company_url() is not None def new_share() -> str: return "fms_" + secrets.token_urlsafe(12) def _client() -> httpx.Client: return httpx.Client(timeout=timeout(), follow_redirects=False, headers={"accept": "application/json", "user-agent": "forgetproof-demo-pim/0.2 (Poppy 1.0 personal agent; ForgetMe v1 client)"}) class Unreachable(Exception): pass # --- discovery (spec 3, 3.2, 3.3) -------------------------------------------------------------------------------- def _domain_of(origin: str) -> str: p = urlsplit(origin) host = (p.hostname or "").lower() if p.port and not (p.scheme == "https" and p.port == 443) and not (p.scheme == "http" and p.port == 80): return f"{host}:{p.port}" return host def _compatible(version) -> bool: try: major, _minor = str(version).split(".") return int(major) == 1 except (ValueError, AttributeError): return False def discover(origin: str) -> dict: """poppy.json, the two OAuth metadata documents, the ForgetMe entry, the index. Raises Unreachable on a network failure; returns status 'no-forget-me' when the Company publishes no v1 entry, and 'no-poppy' when its documents fail the checks of spec 3 (then nothing is sent: a document that does not speak for its host authorizes nothing). No Session header on any of these (spec 5.2).""" try: with _client() as c: r = c.get(origin + "/.well-known/poppy.json") if r.status_code != 200: return {"status": "no-forget-me", "why": f"no poppy.json (HTTP {r.status_code})"} doc = r.json() if not isinstance(doc, dict) or not _compatible(doc.get("protocol_version")): return {"status": "no-poppy", "why": f"poppy.json names protocol_version {doc.get('protocol_version')!r}, not compatible with 1.0 (spec 3.4)"} org = doc.get("organization") if isinstance(doc.get("organization"), dict) else {} if str(org.get("domain", "")).lower() != _domain_of(origin): return {"status": "no-poppy", "why": f"organization.domain {org.get('domain')!r} is not the host that served the document (spec 3.1)"} endpoint = forgetme.endpoint_from_poppy(doc, origin) if not endpoint: return {"status": "no-forget-me", "why": "poppy.json lists no stellarminds.ai/forget-me entry for version 1"} entry = next((e for e in doc["extensions"][forgetme.NAMESPACE] if e.get("version") == forgetme.VERSION), {}) scope_names = entry.get("scopes") if isinstance(entry.get("scopes"), dict) else {} ops = doc.get("extensions", {}).get("operations") has_operations = isinstance(ops, list) and any(isinstance(e, dict) and e.get("version") == "3" for e in ops) # the issuer: from the domain's protected resource metadata, confirmed by the issuer's own metadata (spec 3.2) prm = c.get(origin + "/.well-known/oauth-protected-resource") if prm.status_code != 200: return {"status": "no-poppy", "why": f"no protected resource metadata (HTTP {prm.status_code}); this Company offers no account access, so nothing can be withdrawn"} prm_doc = prm.json() if str(prm_doc.get("resource", "")).rstrip("/").lower() != origin.lower(): return {"status": "no-poppy", "why": "the protected resource metadata's resource is not this origin (RFC 9728 section 3.3)"} servers = prm_doc.get("authorization_servers") or [] issuer = doc.get("auth", {}).get("issuer") if isinstance(doc.get("auth"), dict) else None if not servers: return {"status": "no-poppy", "why": "the Company has no issuer: signed-out only, nothing to withdraw with"} if issuer is None and len(servers) == 1: issuer = servers[0] if issuer not in servers: return {"status": "no-poppy", "why": "auth.issuer is not one of the authorization servers the resource metadata lists (spec 3.2)"} asm = c.get(issuer.rstrip("/") + "/.well-known/oauth-authorization-server") if asm.status_code != 200: return {"status": "no-poppy", "why": f"the issuer publishes no metadata (HTTP {asm.status_code})"} meta = asm.json() if meta.get("issuer") != issuer: return {"status": "no-poppy", "why": "the issuer's metadata names another issuer (spec 3.2, compared character for character)"} if origin.lower() not in [str(x).rstrip("/").lower() for x in meta.get("protected_resources", [])]: return {"status": "no-poppy", "why": "the issuer does not list this domain in protected_resources (spec 3.2)"} if "refresh_token" not in meta.get("grant_types_supported", []): return {"status": "no-poppy", "why": "the issuer offers no refresh_token grant (spec 3.2)"} idx = c.get(endpoint) if idx.status_code != 200: raise Unreachable(f"the index answered HTTP {idx.status_code}") index = idx.json() except (httpx.HTTPError, ValueError) as e: raise Unreachable(f"{type(e).__name__}: {e}") from None keys = forgetme.keys_of(index) if not keys or index.get("namespace") != forgetme.NAMESPACE or index.get("version") != forgetme.VERSION: return {"status": "no-forget-me", "why": "the index is not a ForgetMe v1 index with keys"} declares = {k: v for k, v in DECLARES.items() if k == forgetme.NAMESPACE or (k == "operations" and has_operations)} return {"status": "ready", "endpoint": endpoint, "issuer": index.get("issuer", "?"), "keys": keys, "poll_interval_ms": int(index.get("limits", {}).get("poll_interval_ms", 1000)), "identifier": issuer, "token_endpoint": meta["token_endpoint"], "revocation_endpoint": meta.get("revocation_endpoint"), "scope_names": {"item": scope_names.get("item", "forget-me:item"), "account": scope_names.get("account", "forget-me:account")}, "operations": has_operations, "declares": declares, "organization": org.get("name")} # --- the demo's Company account (a labelled fixture) and the Session that uses it ----------------------------------- def open_account(origin: str, name: str, scenario: str, address: dict) -> dict: """Create John's synthetic account at the Company with the old address already shared (a delivery months ago), the way a real account would already exist, and take the refresh token the fixture mints for Pim's client_id: the labelled stand-in for a sign-in. Then the first token exchange. Returns the recipient record (tokens inside: private).""" disc = discover(origin) if disc["status"] != "ready": return {"id": COMPANY_ID, "party": "Bay Parcel", "kind": "forget-me", "simulated": False, "origin": origin, **disc, "shares": {}} me = pim_origin() with _client() as c: try: r = c.post(origin + "/fixture/accounts", json={"name": name, "scenario": scenario, "scopes": ["item", "account", "addresses"], "addresses": [{"label": address["label"], "line": address["line"]}], "deliveries": 1, "client_id": agent().client_id(me)}) except httpx.HTTPError as e: raise Unreachable(f"fixture account: {type(e).__name__}") from None if r.status_code != 201: raise Unreachable(f"fixture account: HTTP {r.status_code} {r.text[:200]}") acct = r.json() rec = {"id": COMPANY_ID, "party": "Bay Parcel", "kind": "forget-me", "simulated": False, "origin": origin, **disc, "account": acct["account"], "refresh_token": acct["grant"]["refresh_token"], "scope": acct["grant"]["scope"], "user_id": "usr_" + poppy_agent.new_id(), "sid": poppy_agent.new_id(), "client_id": agent().client_id(me), "pim_origin": me, "access_token": None, "token_expires_at": 0, "account_share": new_share(), "offers": {}, "shares": {address["record"]: acct["addresses"][0]["reference"]}} Link(rec).token() return rec class Link: """Pim's Session with one Company for one scenario (spec 5): signs a Session JWT per request with the declaration headers the Company and Pim share, carries the access token, refreshes it with a client assertion when it expires or the Company refuses it (section 7: `invalid_token` means refresh, once), and never sends any of it to a URL the Company did not list for it.""" def __init__(self, rec: dict): self.rec = rec self.session = agent().session(rec.get("pim_origin") or pim_origin(), rec["identifier"], rec["user_id"], sid=rec["sid"], extensions=rec.get("declares") or {}) def token(self, *, force: bool = False) -> str: rec = self.rec if rec.get("access_token") and not force and rec.get("token_expires_at", 0) - time.time() > 30: return rec["access_token"] with _client() as c: try: r = c.post(rec["token_endpoint"], data={"grant_type": "refresh_token", "refresh_token": rec["refresh_token"], "client_assertion_type": poppy_agent.CLIENT_ASSERTION_TYPE, "client_assertion": agent().client_assertion(rec.get("pim_origin") or pim_origin(), rec["identifier"])}) except httpx.HTTPError as e: raise Unreachable(f"token endpoint: {type(e).__name__}") from None if r.status_code != 200: err = r.json().get("error", r.status_code) if r.headers.get("content-type", "").startswith("application/json") else r.status_code raise Unreachable(f"the token endpoint refused the refresh ({err})") body = r.json() rec["access_token"] = body["access_token"] rec["token_expires_at"] = time.time() + int(body.get("expires_in", 300)) rec["scope"] = body.get("scope", rec.get("scope")) return rec["access_token"] def request(self, c: httpx.Client, method: str, url: str, *, json=None, approval: dict | None = None, _retry: bool = True) -> httpx.Response: token = self.token() headers = self.session.headers(method, url, token, approval=approval) r = c.request(method, url, json=json, headers=headers) if r.status_code == 401 and _retry and 'error="invalid_token"' in r.headers.get("www-authenticate", ""): self.token(force=True) return self.request(c, method, url, json=json, approval=approval, _retry=False) return r def share_address(rec: dict, record_id: str, line: str, label: str) -> str | None: """Pim shares an address with the Company (a booking) and gets a reference back. None when the Company can't be reached.""" if rec.get("status") != "ready" or not rec.get("refresh_token"): return None try: link = Link(rec) with _client() as c: a = link.request(c, "POST", rec["origin"] + "/api/addresses", json={"label": label, "line": line}) if a.status_code != 201: return None link.request(c, "POST", rec["origin"] + "/api/deliveries", json={"address": a.json()["id"], "parcel": f"BP-{secrets.randbelow(9000) + 1000}"}) ref = a.json()["reference"] except (httpx.HTTPError, Unreachable, ValueError): return None rec["shares"][record_id] = ref return ref def lookup(rec: dict) -> dict | None: """Where the Company would deliver now, from its own records.""" if rec.get("status") != "ready" or not rec.get("refresh_token"): return None try: with _client() as c: r = Link(rec).request(c, "GET", rec["origin"] + "/api/lookup") return r.json().get("found") if r.status_code == 200 else None except (httpx.HTTPError, Unreachable, ValueError): return None # --- the approval exchange: what the Company would perform, shown before anyone confirms -------------------------------- def _body_for(remote: dict, preview: dict, key: str) -> dict: return {**preview["terms"], "idempotency_key": key} def offer(rec: dict, remote: dict) -> dict | None: """At preview time: ask the Company for its own preview of the withdrawal, then send the submit it would get, without an approval. The Company performs nothing and answers 403 approval_required with the operation: its id, revision, summary, exact terms and expiry (Operations 4). That is what the person approves. Returns {"operation", "body", "preview", "at"} or None when the Company can't say right now (it is then asked at execution and, lacking an approval of terms the person saw, nothing is performed).""" if rec.get("status") != "ready" or not rec.get("refresh_token") or not rec.get("operations"): return None try: link = Link(rec) ep = rec["endpoint"] with _client() as c: body = {"scope": "account"} if remote["scope"] == "account" else {"scope": "item", "reference": remote["reference"]} pv = link.request(c, "POST", ep + "/preview", json=body) if pv.status_code != 200: return None preview = pv.json() # one key per offer: the body the person approves is sent again, as is, at execution (Operations 6: the same # request), and a later attempt after an error gets a fresh key with its fresh offer submit_body = _body_for(remote, preview, f"{remote['share']}:{poppy_agent.new_id(12)}") r = link.request(c, "POST", ep + "/submit", json=submit_body) if r.status_code == 403 and r.json().get("error") == "approval_required" and isinstance(r.json().get("operation"), dict): op = r.json()["operation"] if not all(isinstance(op.get(k), str) for k in ("operation_id", "revision", "expires_at")) or not isinstance(op.get("terms"), dict): return None found = {"operation": op, "body": submit_body, "preview": preview, "at": now()} rec.setdefault("offers", {})[remote["share"]] = [found, *rec.get("offers", {}).get(remote["share"], [])][:5] return found return None # anything else (double_submit, a refusal): no terms to show; execution reports what happened except (httpx.HTTPError, Unreachable, ValueError): return None def offered(rec: dict, share: str, operation_id: str, revision: str) -> dict | None: """The offer Pim showed for this share with exactly this operation_id and revision, if still valid.""" for o in rec.get("offers", {}).get(share, []): op = o["operation"] if op["operation_id"] == operation_id and op["revision"] == revision: try: if datetime.fromisoformat(op["expires_at"]) <= datetime.now(timezone.utc): return None except ValueError: return None return o return None # --- asking ------------------------------------------------------------------------------------------------------- def ask_company(rec: dict, remote: dict, say) -> dict: """Drive one recipient through the public contract, over Poppy. `remote` is Pim's durable record of this ask (reference or scope, idempotency key, the body the person saw and the approval they gave, the recipient's operation id once known, attempts). Returns {"rows": [...], "receipts": [...], "pending": bool, "observation": None}. Raises Unreachable.""" remote["attempts"] = remote.get("attempts", 0) + 1 remote["last_attempt_at"] = now() party = rec["party"] try: link = Link(rec) with _client() as c: ep = rec["endpoint"] if not remote.get("remote_operation"): body = remote.get("body") if body is None: # nothing was shown at preview time: ask now, and expect to be refused without an approval req = {"scope": "account"} if remote["scope"] == "account" else {"scope": "item", "reference": remote["reference"]} pv = link.request(c, "POST", ep + "/preview", json=req) err = pv.json() if pv.status_code != 200 and pv.headers.get("content-type", "").startswith("application/json") else {} if pv.status_code != 200 and err.get("error") == "double_submit" and err.get("operation"): remote["remote_operation"] = err["operation"] # it already has an operation (a retry after a restart): follow it elif pv.status_code != 200: return _failed(rec, remote, f"{party} refused the preview: {err.get('error', pv.status_code)}") else: body = _body_for(remote, pv.json(), remote["idempotency_key"]) if not remote.get("remote_operation"): approval = remote.get("approval") sub = link.request(c, "POST", ep + "/submit", json=body, approval=approval) if sub.status_code in (200, 202): remote["remote_operation"] = sub.json()["operation"] say(party, f"Approval {approval['reference'] if approval else '(none)'} checked against operation {approval['operation_id'] if approval else '?'} " f"revision {approval['revision'] if approval else '?'}: performed once. Stopped returning the record at {sub.json().get('retrieval_stopped_at')}.") else: err = sub.json() if sub.headers.get("content-type", "").startswith("application/json") else {} code = err.get("error", sub.status_code) if code == "double_submit" and err.get("operation"): remote["remote_operation"] = err["operation"] elif code == "approval_required": op = err.get("operation", {}) if approval: why = (f"{party}'s terms changed since you approved them (operation {op.get('operation_id')}, new revision {op.get('revision')}); " "nothing was done there. Open the preview again to see and approve the new terms.") else: why = f"{party} asks for your approval of terms you have not seen; nothing was done there. Open the preview again to see and approve them." say("Pim", why + " I never approve on your behalf.") return _failed(rec, remote, why, action="not performed: new approval needed") elif code == "approval_declined": why = f"{party} declined the approval: {err.get('reason', 'no reason given')}" return _failed(rec, remote, why, action="not performed: declined") elif code == "extension_required": why = f"{party} performs withdrawals only through the {err.get('extension')} extension, which this agent and it do not share; nothing was done there" return _failed(rec, remote, why, action="not performed: extension not shared") else: return _failed(rec, remote, f"{party} refused the request: {code}") # poll deadline = datetime.now(timezone.utc).timestamp() + poll_seconds() interval = max(0.3, rec.get("poll_interval_ms", 1000) / 1000) st = None while True: r = link.request(c, "GET", f"{ep}/operations/{remote['remote_operation']}") if r.status_code != 200: raise Unreachable(f"{party} answered HTTP {r.status_code} on the status read") st = r.json() if st["state"] in ("done", "error") or datetime.now(timezone.utc).timestamp() > deadline: break time.sleep(interval) if st["state"] not in ("done", "error"): remote["pending"] = True return {"rows": [_row(rec, {"holder": "operation", "title": f"{party}", "kind": "recipient", "outcome": "queued", "detail": f"{party} is still working on it", "action": "asked; in progress", "unresolved": "waiting for the recipient", "at": now()})], "receipts": [], "pending": True, "observation": None} ev = link.request(c, "GET", f"{ep}/operations/{remote['remote_operation']}/evidence") evidence = ev.json() if ev.status_code == 200 else {"receipts": []} except (httpx.HTTPError, ValueError) as e: raise Unreachable(f"{type(e).__name__}: {e}") from None rows, receipts = [], [] verified = 0 for r in evidence.get("receipts", []): rec_json = r.get("receipt", {}) try: forgetme.verify(rec_json, rec["keys"]) forgetme.check_portable(rec_json) ok = True verified += 1 except ValueError as e: ok = False say("Pim", f"{party}'s receipt for {r.get('holder')} did not verify against the keys it publishes: {e}. Kept, marked unverified.") receipts.append({"receipt_id": f"{rec['id']}.{r.get('holder', 'holder')}", "holder": f"{rec['id']}-{r.get('holder', 'holder')}", "party": party, "issuer": r.get("issuer", rec["issuer"]), "issuer_key_url": r.get("issuer_key_url", rec["endpoint"]), "fingerprint": r.get("fingerprint", ""), "verified_by_host": ok, "receipt": rec_json}) for h in (st.get("outcome") or {}).get("holders", []): rows.append(_row(rec, h)) outstanding = (st.get("outcome") or {}).get("outstanding", 0) remote["pending"] = bool(outstanding) say("Pim", f"{party} answered: {(st.get('outcome') or {}).get('sentence', st['state'])} {verified} receipt{'s' if verified != 1 else ''} verified against the keys it publishes.") return {"rows": rows, "receipts": receipts, "pending": bool(outstanding), "observation": None} def _failed(rec: dict, remote: dict, why: str, action: str = "asked; refused") -> dict: remote["pending"] = False return {"rows": [_row(rec, {"holder": "operation", "title": rec["party"], "kind": "recipient", "outcome": "error", "detail": why, "action": action, "unresolved": why, "at": now()})], "receipts": [], "pending": False, "observation": None} def _row(rec: dict, h: dict) -> dict: holder = f"{rec['id']}-{h.get('holder', 'holder')}" title = h.get("title", h.get("holder", "")) row = {"holder": holder, "title": (title if title.startswith(rec["party"]) else f"{rec['party']} ยท {title}") if h.get("holder") != "operation" else rec["party"], "kind": h.get("kind", "recipient"), "outcome": h.get("outcome", "unsupported"), "detail": h.get("detail", ""), "party": rec["party"], "action": h.get("action", "asked"), "evidence": f"{rec['id']}.{h['holder']}" if h.get("receipt_id") else None, "unresolved": h.get("unresolved"), "at": h.get("at") or now(), "retained_until": h.get("retained_until")} if h.get("receipt_id"): row["receipt_id"] = f"{rec['id']}.{h['holder']}" return row def ask_simulated(rec: dict, remote: dict, say, sign) -> dict: """The two recipients simulated inside Pim. `sign(holder, kind, outcome, actions, coverage)` issues a Pim-signed portable receipt for an acknowledgment; an observation gets none.""" remote["attempts"] = remote.get("attempts", 0) + 1 remote["last_attempt_at"] = now() party = rec["party"] if rec["kind"] == "api-only": say(party, "Deletion request received through our API: acknowledged. We keep no ForgetMe endpoint.") receipt_ = sign(rec["id"], "api", "unsupported", ["deletion requested through the holder's API and acknowledged", "nothing done: the holder could not be inspected from here"], {"inspected": False, "checks": [], "limits": ["the recipient does not speak ForgetMe; its acknowledgment is all there is"]}) remote["pending"] = False row = {"holder": rec["id"], "title": party, "kind": "api", "outcome": "unsupported", "party": party, "detail": "acknowledged the deletion through its API; nothing can be inspected from here, so this is not evidence of erasure", "action": "asked through its API; acknowledged", "evidence": f"{rec['id']}.acknowledgment", "receipt_id": f"{rec['id']}.acknowledgment", "unresolved": "unverifiable: an acknowledgment, not an inspection", "at": now()} return {"rows": [row], "receipts": [{"receipt_id": f"{rec['id']}.acknowledgment", "holder": rec["id"], "party": party, "fingerprint": "", "receipt": receipt_}], "pending": False, "observation": None} # offline: unreachable the first time; reached later, it has no ForgetMe endpoint if remote["attempts"] < 2: raise Unreachable("connection refused (simulated: the recipient is offline)") remote["pending"] = False say("Pim", f"{party} is reachable again, but its poppy.json lists no ForgetMe entry. I asked by email; nothing can be verified.") obs = {"holder": rec["id"], "party": party, "outcome": "unsupported", "observed_by": "Pim (this demo)", "text": "publishes no ForgetMe endpoint; asked by email, nothing can be verified", "at": now()} row = {"holder": rec["id"], "title": party, "kind": "recipient", "outcome": "unsupported", "party": party, "detail": "reached on retry; publishes no ForgetMe endpoint, so Pim asked by email and can verify nothing", "action": "asked by email", "evidence": None, "unresolved": "unverifiable: no ForgetMe at this recipient", "at": now()} return {"rows": [row], "receipts": [], "pending": False, "observation": obs} def unreachable_row(rec: dict, remote: dict, why: str) -> dict: final = remote.get("attempts", 0) >= MAX_ATTEMPTS return {"holder": rec["id"], "title": rec["party"], "kind": rec.get("kind", "recipient"), "outcome": "error" if final else "queued", "party": rec["party"], "detail": f"not reachable ({why}); " + ("given up after ten attempts" if final else "Pim retries and this row updates under the same operation id"), "action": "asked; no answer", "evidence": None, "unresolved": "the recipient has not answered", "at": now()} def kept_row(rec: dict) -> dict: return {"holder": rec["id"], "title": rec["party"], "kind": rec.get("kind", "recipient"), "outcome": "intentionally-retained", "party": rec["party"], "detail": f"left with {rec['party']}, as you chose; it was not asked", "action": "not asked, as you chose", "evidence": None, "unresolved": f"{rec['party']} still holds it", "at": now()}