forgetproof 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """Detect and erase deleted records left on disk by the stores AI agents keep: Chroma, mem0, Qdrant local, LanceDB, SQLite, Postgres/pgvector and text files."""
2
+
3
+ __version__ = "0.2.0"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,197 @@
1
+ """Chroma operations that need the chromadb client. Run in a child process by the fixer:
2
+
3
+ rebuild PATH rebuild every collection from its live records
4
+ migrations print the schema migrations this chromadb applies to a new store, as JSON
5
+
6
+ A separate process means Chroma's file handles and caches are fully released before
7
+ the fixer touches the files directly.
8
+
9
+ Each swap is journaled in PATH/.forgetproof-rebuild.json before it starts, so a crash
10
+ at any point is repaired by `recover` on the next run, and no live record is ever lost:
11
+ until the original is deleted it is untouched, and after that the full copy exists
12
+ under its temporary name.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import shutil
20
+ import sqlite3
21
+ import sys
22
+ import tempfile
23
+ import uuid
24
+ from pathlib import Path
25
+
26
+ BATCH = 1000
27
+ JOURNAL = ".forgetproof-rebuild.json"
28
+ TMP_PREFIX = "fp-rebuild-"
29
+
30
+
31
+ def _crash_point(name: str) -> None:
32
+ """Test hook: simulate the process dying at a named step."""
33
+ if os.environ.get("FORGETPROOF_TEST_CRASH") == name:
34
+ os._exit(70)
35
+
36
+
37
+ def _flood_point(name: str, client) -> None:
38
+ """Test hook: at a named step, push FORGETPROOF_TEST_FLOOD=N throwaway collections through Chroma's in-memory
39
+ index pool, evicting every index that was in it (see rebuild_collection)."""
40
+ if os.environ.pop("FORGETPROOF_TEST_FLOOD_AT", None) == name:
41
+ for i in range(int(os.environ["FORGETPROOF_TEST_FLOOD"])):
42
+ client.create_collection(f"flood{i:04d}", embedding_function=None).add(ids=["x"], embeddings=[[0.0, 1.0]])
43
+
44
+
45
+ def _test_file_limit() -> None:
46
+ """Test hook: FORGETPROOF_TEST_NOFILE=N caps this process's open files at N before chromadb loads. chromadb sizes
47
+ its index pool from that limit, so a test can give Linux the ~100-index pool Windows always has."""
48
+ if os.environ.get("FORGETPROOF_TEST_NOFILE") and os.name == "posix":
49
+ import resource
50
+
51
+ soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
52
+ want = int(os.environ["FORGETPROOF_TEST_NOFILE"])
53
+ resource.setrlimit(resource.RLIMIT_NOFILE, (min(want, hard if hard != resource.RLIM_INFINITY else want), hard))
54
+
55
+
56
+ def _names(client) -> set[str]:
57
+ return {c if isinstance(c, str) else c.name for c in client.list_collections()}
58
+
59
+
60
+ def _write_journal(path: Path, entries: dict[str, str]) -> None:
61
+ journal = path / JOURNAL
62
+ if not entries:
63
+ journal.unlink(missing_ok=True)
64
+ return
65
+ tmp = journal.with_suffix(".tmp")
66
+ tmp.write_text(json.dumps(entries))
67
+ os.replace(tmp, journal)
68
+
69
+
70
+ def recover(client, path: Path) -> list[str]:
71
+ """Finish or undo swaps left by an interrupted rebuild."""
72
+ journal = path / JOURNAL
73
+ if not journal.exists():
74
+ return []
75
+ entries: dict[str, str] = json.loads(journal.read_text())
76
+ notes = []
77
+ for tmp_name, orig in entries.items():
78
+ names = _names(client)
79
+ if tmp_name not in names:
80
+ continue
81
+ if orig in names:
82
+ client.delete_collection(tmp_name) # crashed before the swap: original is intact
83
+ notes.append(f"recovered {orig}: discarded an unfinished copy")
84
+ else:
85
+ client.get_collection(tmp_name, embedding_function=None).modify(name=orig)
86
+ notes.append(f"recovered {orig}: completed an interrupted swap")
87
+ journal.unlink()
88
+ return notes
89
+
90
+
91
+ def _create_like(client, name, src):
92
+ try:
93
+ return client.create_collection(name, metadata=src.metadata, configuration=src.configuration, embedding_function=None)
94
+ except Exception:
95
+ # Older/newer configuration shapes: keep only the index settings.
96
+ conf = {k: v for k, v in (src.configuration or {}).items() if k in ("hnsw", "spann") and v}
97
+ return client.create_collection(name, metadata=src.metadata, configuration=conf or None, embedding_function=None)
98
+
99
+
100
+ def _column(batch, key):
101
+ values = batch.get(key)
102
+ if values is None or all(v is None for v in values):
103
+ return None
104
+ return values
105
+
106
+
107
+ def rebuild_collection(client, path: Path, name: str) -> int:
108
+ src = client.get_collection(name, embedding_function=None)
109
+ ids = src.get(include=[])["ids"]
110
+ # Every live record is read before the copy exists, and held in memory (one copy of the live data, as on disk).
111
+ # Chroma 1.x keeps each collection's vector index in a bounded in-memory pool and, for a persistent store, flushes
112
+ # it to disk only every sync_threshold (1000) writes: the newest records live in the write log alone. The pool is
113
+ # filled from the log once per process; an index evicted from it is reloaded from the stale disk copy and never
114
+ # filled again, so reading those records' embeddings then fails ("Error finding id"). The pool holds about 100
115
+ # indexes on Windows (sized from the C runtime's 512-handle limit), and inserting the copy's index can evict this
116
+ # one. Nothing enters the pool while the source is read, so the reads below cannot hit an evicted index.
117
+ batches = [
118
+ src.get(ids=ids[start:start + BATCH], include=["embeddings", "documents", "metadatas", "uris"])
119
+ for start in range(0, len(ids), BATCH)
120
+ ]
121
+ tmp_name = f"{TMP_PREFIX}{uuid.uuid4().hex[:12]}"
122
+ _write_journal(path, {tmp_name: name})
123
+ tmp = _create_like(client, tmp_name, src)
124
+ for batch in batches:
125
+ tmp.add(
126
+ ids=batch["ids"],
127
+ embeddings=batch["embeddings"],
128
+ documents=_column(batch, "documents"),
129
+ metadatas=_column(batch, "metadatas"),
130
+ uris=_column(batch, "uris"),
131
+ )
132
+ _crash_point("copy")
133
+ _flood_point("copy", client)
134
+ if tmp.count() != len(ids):
135
+ client.delete_collection(tmp_name)
136
+ _write_journal(path, {})
137
+ raise RuntimeError(f"rebuild of {name!r} copied {tmp.count()} of {len(ids)} records; original left untouched")
138
+ client.delete_collection(name)
139
+ _crash_point("swap")
140
+ tmp.modify(name=name)
141
+ _write_journal(path, {})
142
+ return len(ids)
143
+
144
+
145
+ def rebuild(path: Path) -> None:
146
+ _test_file_limit()
147
+ import chromadb
148
+
149
+ client = chromadb.PersistentClient(path=str(path))
150
+ for note in recover(client, path):
151
+ print(note, file=sys.stderr)
152
+ for name in sorted(_names(client)):
153
+ n = rebuild_collection(client, path, name)
154
+ print(f"rebuilt {name}: {n} records", file=sys.stderr)
155
+
156
+
157
+ def delete_containing(path: Path) -> None:
158
+ """Delete, in every collection, the live records whose document contains one of the values read
159
+ as a JSON list from stdin. Chroma's `where_document` matches documents only, so a value that is
160
+ only in a record's metadata is left; the caller's scan still reports it."""
161
+ import chromadb
162
+
163
+ values = json.loads(sys.stdin.read())
164
+ client = chromadb.PersistentClient(path=str(path))
165
+ for name in sorted(_names(client)):
166
+ col = client.get_collection(name, embedding_function=None)
167
+ before = col.count()
168
+ for v in values:
169
+ ids = col.get(where_document={"$contains": v}, include=[])["ids"]
170
+ if ids:
171
+ col.delete(ids=ids)
172
+ gone = before - col.count()
173
+ if gone:
174
+ print(f"deleted {gone} live record(s) from collection {name}", file=sys.stderr)
175
+
176
+
177
+ def migrations() -> None:
178
+ import chromadb
179
+
180
+ scratch = tempfile.mkdtemp(prefix="forgetproof-")
181
+ try:
182
+ client = chromadb.PersistentClient(path=scratch)
183
+ client.heartbeat()
184
+ conn = sqlite3.connect(Path(scratch) / "chroma.sqlite3")
185
+ rows = conn.execute("select dir, version from migrations").fetchall()
186
+ conn.close()
187
+ del client
188
+ finally:
189
+ shutil.rmtree(scratch, ignore_errors=True)
190
+ print(json.dumps({"chromadb": chromadb.__version__, "migrations": sorted(rows)}))
191
+
192
+
193
+ if __name__ == "__main__":
194
+ if sys.argv[1] == "rebuild":
195
+ rebuild(Path(sys.argv[2]))
196
+ else:
197
+ migrations()
forgetproof/agent.py ADDED
@@ -0,0 +1,342 @@
1
+ """The forget-me extension for hosted personal agents, as a provider embeds it.
2
+
3
+ Instinct, Hello Haven, Wajo, Muse and every other hosted personal agent keep a person's memory in
4
+ their own cloud, where the person can't run forgetproof. What the person can do is use a provider
5
+ that embeds it. `Provider` is that embedding: it wraps the provider's stores, erases a signed-in
6
+ user's values on request, signs receipts with the provider's key, and serves the small HTTP surface
7
+ the extension defines (docs/extension.md), so a user, their agent on another host, or a page in
8
+ their browser can check the receipt against the key the provider publishes.
9
+
10
+ The one rule the SDK enforces itself: *the subject comes from the provider's session, never from
11
+ the request.* `forget()` takes the values; the ASGI app gets them from a `subject_of(scope)`
12
+ callback the provider writes — typically "the signed-in user's email and phone" — and ignores
13
+ anything a request body says about who to forget. An agent or a browser can ask that the current
14
+ user be forgotten; it cannot name someone else.
15
+
16
+ Stores the provider can only delete through an API (a managed vector database with no disk access)
17
+ are declared `api_only`, with a callback that does the deletion. Their receipts carry the verdict
18
+ UNVERIFIABLE, never CLEAN: the deletion was requested and acknowledged, and nothing more can be
19
+ said about the bytes.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import re
26
+ from collections.abc import Awaitable, Callable, Iterable
27
+ from dataclasses import dataclass, field
28
+ from datetime import datetime, timezone
29
+ from pathlib import Path
30
+ from typing import Any
31
+
32
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
33
+
34
+ from . import __version__, forget as forget_mod, postgres, receipt, safety
35
+ from .erase_live import LiveEraseError
36
+ from .fixer import FixError
37
+ from .report import Report
38
+ from .scanner import UnsupportedStore, detect
39
+ from .subject import Subject, subject as make_subject
40
+
41
+ EXTENSION = "0.2"
42
+ STORE_NAME = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
43
+ RECEIPT_ID = re.compile(r"^([A-Za-z0-9_-]{1,64})\.(\d{8}T\d{12}Z)$")
44
+ _EXPECTED = (UnsupportedStore, FixError, LiveEraseError, postgres.PostgresError, ValueError, OSError)
45
+
46
+ ApiDelete = Callable[[str, Subject], list[str]] # (store name, subject) -> what was done, as plain sentences
47
+ SubjectOf = Callable[[dict], Awaitable[list[str] | None]] # ASGI scope -> the signed-in user's values, or None
48
+
49
+
50
+ @dataclass
51
+ class StoreResult:
52
+ store: str
53
+ status: str # "clean" | "residue_remains" | "unverifiable" | "queued" | "error"
54
+ receipt_id: str | None = None
55
+ queued_at: str | None = None
56
+ why: str | None = None
57
+ actions: list[str] = field(default_factory=list)
58
+
59
+ def to_dict(self) -> dict:
60
+ d = {"store": self.store, "status": self.status}
61
+ if self.receipt_id:
62
+ d["receipt_id"] = self.receipt_id
63
+ if self.queued_at:
64
+ d["queued_at"] = self.queued_at
65
+ if self.why:
66
+ d["why"] = self.why
67
+ if self.actions:
68
+ d["actions"] = self.actions
69
+ return d
70
+
71
+
72
+ @dataclass
73
+ class ForgetResult:
74
+ stores: list[StoreResult]
75
+ subject_values: int
76
+ correlation_id: str | None
77
+
78
+ @property
79
+ def status(self) -> str:
80
+ s = {r.status for r in self.stores}
81
+ for worst in ("error", "residue_remains", "queued", "unverifiable"):
82
+ if worst in s:
83
+ return worst
84
+ return "clean"
85
+
86
+ def to_dict(self) -> dict:
87
+ return {"status": self.status, "subject_values": self.subject_values, "correlation_id": self.correlation_id,
88
+ "stores": [r.to_dict() for r in self.stores]}
89
+
90
+
91
+ class Provider:
92
+ """A hosted personal agent's forgetproof. See the module docstring."""
93
+
94
+ def __init__(self, issuer: str, stores: dict[str, Path | str], *, receipts_dir: Path | str,
95
+ key_path: Path | str | None = None, queue_dir: Path | str | None = None,
96
+ api_only: dict[str, ApiDelete] | None = None, live_delete: bool = False,
97
+ statement: str | None = None, base_path: str = "/forgetproof"):
98
+ if not issuer.strip():
99
+ raise ValueError("issuer must name the provider")
100
+ self.issuer = issuer
101
+ self.stores: dict[str, Path | str] = {}
102
+ for name, target in stores.items():
103
+ if not STORE_NAME.match(name):
104
+ raise ValueError(f"store name {name!r}: letters, digits, - and _ only")
105
+ self.stores[name] = target if postgres.is_postgres(target) else Path(target).resolve()
106
+ self.api_only = dict(api_only or {})
107
+ for name in self.api_only:
108
+ if not STORE_NAME.match(name) or name in self.stores:
109
+ raise ValueError(f"api_only store {name!r} must have a valid name not used by a file store")
110
+ self.receipts_dir = Path(receipts_dir)
111
+ self.receipts_dir.mkdir(parents=True, exist_ok=True)
112
+ self.queue_dir = Path(queue_dir) if queue_dir else self.receipts_dir.parent / "queue"
113
+ self.key: Ed25519PrivateKey = receipt.load_or_create_key(Path(key_path) if key_path else None)
114
+ self.live_delete = live_delete
115
+ self.statement = statement
116
+ self.base_path = base_path.rstrip("/") or "/forgetproof"
117
+
118
+ # -- identity ------------------------------------------------------------------------------------
119
+
120
+ @property
121
+ def public_key(self) -> str:
122
+ return receipt.public_key_b64(self.key)
123
+
124
+ @property
125
+ def fingerprint(self) -> str:
126
+ return receipt.fingerprint(self.public_key)
127
+
128
+ def _kind(self, name: str) -> str:
129
+ if name in self.api_only:
130
+ return "api"
131
+ target = self.stores[name]
132
+ if postgres.is_postgres(target):
133
+ return "postgres"
134
+ try:
135
+ return detect(Path(target))
136
+ except UnsupportedStore:
137
+ return "files"
138
+
139
+ def well_known(self) -> dict:
140
+ """The document served at /.well-known/forgetproof.json (schemas/well-known.schema.json)."""
141
+ doc = {
142
+ "forgetproof": EXTENSION,
143
+ "issuer": self.issuer,
144
+ "public_key": self.public_key,
145
+ "key_fingerprint": self.fingerprint,
146
+ "keys": [{"public_key": self.public_key, "key_fingerprint": self.fingerprint}],
147
+ "stores": [{"name": n, "kind": self._kind(n)} for n in [*self.stores, *self.api_only]],
148
+ "endpoints": {
149
+ "forget": f"{self.base_path}/forget",
150
+ "status": f"{self.base_path}/status",
151
+ "receipts": f"{self.base_path}/receipts/{{id}}",
152
+ },
153
+ "capabilities": {
154
+ "erase": bool(self.stores),
155
+ "verify_on_disk": bool(self.stores),
156
+ "queue": True,
157
+ "live_delete": self.live_delete,
158
+ },
159
+ "tool": f"forgetproof {__version__}",
160
+ }
161
+ if self.statement:
162
+ doc["statement"] = self.statement
163
+ return doc
164
+
165
+ # -- receipts ------------------------------------------------------------------------------------
166
+
167
+ def _write(self, store: str, rec: dict) -> str:
168
+ receipt_id = f"{store}.{datetime.now(timezone.utc):%Y%m%dT%H%M%S%fZ}"
169
+ (self.receipts_dir / f"{receipt_id}.json").write_text(json.dumps(rec, indent=2) + "\n")
170
+ return receipt_id
171
+
172
+ def receipt(self, receipt_id: str) -> dict | None:
173
+ if not RECEIPT_ID.match(receipt_id):
174
+ return None
175
+ path = self.receipts_dir / f"{receipt_id}.json"
176
+ return json.loads(path.read_text()) if path.is_file() else None
177
+
178
+ def receipts(self, limit: int = 50) -> list[dict]:
179
+ out = []
180
+ for p in sorted(self.receipts_dir.glob("*.json"), reverse=True)[:limit]:
181
+ rec = json.loads(p.read_text())
182
+ out.append({"receipt_id": p.stem, "store": p.stem.split(".")[0], "issued_at": rec["issued_at"],
183
+ "verdict": rec["verdict"], "correlation_id": rec.get("correlation_id")})
184
+ return out
185
+
186
+ def _api_receipt(self, name: str, actions: list[str], subj: Subject, correlation_id: str | None) -> dict:
187
+ summary = Report(target=name, store="api").summary()
188
+ summary["incomplete"] = "deleted through the store's API; the bytes on its disks can't be checked from here"
189
+ summary["clean"] = False
190
+ return receipt.issue(name, summary, summary, actions, [], label=name, correlation_id=correlation_id,
191
+ issuer=self.issuer, subject_values=subj.count, copies=[], verdict="UNVERIFIABLE",
192
+ files={}, key=self.key)
193
+
194
+ # -- the operations ------------------------------------------------------------------------------
195
+
196
+ def forget(self, values: str | Iterable[str] | Subject, *, correlation_id: str | None = None,
197
+ also_live: bool = False, stores: Iterable[str] | None = None) -> ForgetResult:
198
+ """Erase the subject from every store (or the named ones). One receipt per store; a store that
199
+ is open elsewhere is queued and finished by `run_queued()`."""
200
+ subj = values if isinstance(values, Subject) else make_subject(values)
201
+ if also_live and not self.live_delete:
202
+ raise ValueError("this provider doesn't offer live deletion (Provider(live_delete=True))")
203
+ names = list(stores) if stores is not None else [*self.stores, *self.api_only]
204
+ results: list[StoreResult] = []
205
+ for name in names:
206
+ if name in self.api_only:
207
+ try:
208
+ actions = list(self.api_only[name](name, subj))
209
+ rec = self._api_receipt(name, actions, subj, correlation_id)
210
+ results.append(StoreResult(name, "unverifiable", self._write(name, rec), actions=actions))
211
+ except Exception as e: # a provider callback can fail any way it likes
212
+ results.append(StoreResult(name, "error", why=str(e)))
213
+ continue
214
+ if name not in self.stores:
215
+ results.append(StoreResult(name, "error", why="unknown store"))
216
+ continue
217
+ try:
218
+ r = forget_mod.forget(self.stores[name], subj, also_live=also_live, queue_dir=self.queue_dir,
219
+ correlation_id=correlation_id, issuer=self.issuer)
220
+ except _EXPECTED as e:
221
+ results.append(StoreResult(name, "error", why=str(e)))
222
+ continue
223
+ if isinstance(r, forget_mod.Queued):
224
+ results.append(StoreResult(name, "queued", queued_at=r.queued_at,
225
+ why="the store is open in another process; finishes at its next start"))
226
+ continue
227
+ rec = self._resign(r)
228
+ results.append(StoreResult(name, rec["verdict"].lower(), self._write(name, rec), actions=rec["actions"]))
229
+ return ForgetResult(results, subj.count, correlation_id)
230
+
231
+ def _resign(self, rec: dict) -> dict:
232
+ """forget() signs with the machine key; a provider signs with its own. Re-sign the same body."""
233
+ if rec["public_key"] == self.public_key:
234
+ return rec
235
+ body = {k: v for k, v in rec.items() if k != "signature"}
236
+ body["public_key"] = self.public_key
237
+ body["signature"] = receipt._b64(self.key.sign(receipt.canonical(body)))
238
+ return body
239
+
240
+ def run_queued(self) -> list[StoreResult]:
241
+ """Finish queued erasures for every store; call at the agent's start, before it opens its stores."""
242
+ out = []
243
+ for name, target in self.stores.items():
244
+ try:
245
+ for rec in forget_mod.run_queued(target, queue_dir=self.queue_dir, issuer=self.issuer):
246
+ rec = self._resign(rec)
247
+ out.append(StoreResult(name, rec["verdict"].lower(), self._write(name, rec), actions=rec["actions"]))
248
+ except _EXPECTED as e:
249
+ out.append(StoreResult(name, "error", why=str(e)))
250
+ return out
251
+
252
+ def status(self) -> dict:
253
+ stores = []
254
+ for name, target in self.stores.items():
255
+ is_db = postgres.is_postgres(target)
256
+ is_open = False if is_db or self._kind(name) == "files" else bool(safety.open_by_other_processes(Path(target)))
257
+ stores.append({"name": name, "kind": self._kind(name), "open": is_open,
258
+ "queued": forget_mod.pending(target, queue_dir=self.queue_dir),
259
+ "parked": forget_mod.stale_entries(target, queue_dir=self.queue_dir)})
260
+ for name in self.api_only:
261
+ stores.append({"name": name, "kind": "api", "open": False, "queued": 0, "parked": 0})
262
+ return {"issuer": self.issuer, "key_fingerprint": self.fingerprint, "stores": stores,
263
+ "receipts": len(list(self.receipts_dir.glob("*.json"))), "tool": f"forgetproof {__version__}"}
264
+
265
+ # -- the HTTP surface ----------------------------------------------------------------------------
266
+
267
+ def asgi(self, subject_of: SubjectOf | None):
268
+ """An ASGI app for the extension's endpoints. Mount it anywhere; it routes on the path's tail:
269
+
270
+ GET /.well-known/forgetproof.json (serve well_known() yourself if you mount under a prefix)
271
+ GET <base>/status
272
+ POST <base>/forget body: {"correlation_id"?: str, "also_live"?: bool}
273
+ GET <base>/receipts
274
+ GET <base>/receipts/{id}
275
+
276
+ `subject_of(scope)` returns the signed-in user's exact values from the provider's own session
277
+ (cookie, bearer token, whatever the provider uses), or None when nobody is signed in, which
278
+ makes POST /forget answer 401. The request body is never consulted for who to forget. Without a
279
+ `subject_of`, POST /forget always answers 401.
280
+ """
281
+ provider = self
282
+
283
+ async def app(scope, receive, send):
284
+ if scope["type"] != "http":
285
+ raise RuntimeError("forgetproof.agent serves HTTP only")
286
+ path = scope.get("path", "/")
287
+ root = scope.get("root_path", "")
288
+ if root and path.startswith(root):
289
+ path = path[len(root):] or "/"
290
+ tail = path[len(provider.base_path):] if path.startswith(provider.base_path + "/") else path
291
+ method = scope["method"]
292
+
293
+ async def reply(status: int, body: Any) -> None:
294
+ data = json.dumps(body, indent=2).encode()
295
+ await send({"type": "http.response.start", "status": status, "headers": [
296
+ (b"content-type", b"application/json; charset=utf-8"),
297
+ (b"content-length", str(len(data)).encode()),
298
+ (b"cache-control", b"no-store"),
299
+ ]})
300
+ await send({"type": "http.response.body", "body": data})
301
+
302
+ async def read_json() -> dict:
303
+ chunks, more = [], True
304
+ while more:
305
+ msg = await receive()
306
+ chunks.append(msg.get("body", b""))
307
+ more = msg.get("more_body", False)
308
+ raw = b"".join(chunks)
309
+ if not raw.strip():
310
+ return {}
311
+ try:
312
+ body = json.loads(raw)
313
+ except ValueError:
314
+ raise ValueError("the body isn't JSON") from None
315
+ return body if isinstance(body, dict) else {}
316
+
317
+ if tail in ("/.well-known/forgetproof.json", "/well-known") and method == "GET":
318
+ return await reply(200, provider.well_known())
319
+ if tail == "/status" and method == "GET":
320
+ return await reply(200, provider.status())
321
+ if tail == "/receipts" and method == "GET":
322
+ return await reply(200, {"receipts": provider.receipts()})
323
+ if tail.startswith("/receipts/") and method == "GET":
324
+ rec = provider.receipt(tail[len("/receipts/"):])
325
+ return await reply(200, rec) if rec else await reply(404, {"error": "no such receipt"})
326
+ if tail == "/forget" and method == "POST":
327
+ values = await subject_of(scope) if subject_of else None
328
+ if not values:
329
+ return await reply(401, {"error": "no signed-in user to forget; the request can't name one"})
330
+ try:
331
+ body = await read_json()
332
+ correlation = body.get("correlation_id")
333
+ if correlation is not None and (not isinstance(correlation, str) or len(correlation) > 200):
334
+ return await reply(400, {"error": "correlation_id must be a short string"})
335
+ also_live = bool(body.get("also_live", False))
336
+ result = provider.forget(values, correlation_id=correlation, also_live=also_live)
337
+ except ValueError as e:
338
+ return await reply(400, {"error": str(e)})
339
+ return await reply(200, result.to_dict())
340
+ return await reply(404 if method in ("GET", "POST") else 405, {"error": "not an extension endpoint"})
341
+
342
+ return app