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.
- forgetproof/__init__.py +3 -0
- forgetproof/__main__.py +5 -0
- forgetproof/_chroma_rebuild.py +197 -0
- forgetproof/agent.py +342 -0
- forgetproof/cli.py +582 -0
- forgetproof/copies.py +155 -0
- forgetproof/desktop/__init__.py +1 -0
- forgetproof/desktop/__main__.py +26 -0
- forgetproof/desktop/api.py +549 -0
- forgetproof/desktop/app.py +59 -0
- forgetproof/desktop/schedule.py +161 -0
- forgetproof/desktop/ui/index.html +298 -0
- forgetproof/discovery.py +357 -0
- forgetproof/erase_live.py +180 -0
- forgetproof/files_store.py +69 -0
- forgetproof/fixer.py +274 -0
- forgetproof/forget.py +264 -0
- forgetproof/forgetme.py +270 -0
- forgetproof/hnsw.py +132 -0
- forgetproof/integrations/__init__.py +9 -0
- forgetproof/integrations/mem0.py +283 -0
- forgetproof/keystore.py +58 -0
- forgetproof/lance_store.py +191 -0
- forgetproof/mcp_server.py +541 -0
- forgetproof/mem0_store.py +189 -0
- forgetproof/pii.py +160 -0
- forgetproof/postgres.py +334 -0
- forgetproof/py.typed +0 -0
- forgetproof/qdrant_store.py +69 -0
- forgetproof/receipt.py +135 -0
- forgetproof/remembered.py +257 -0
- forgetproof/report.py +59 -0
- forgetproof/safety.py +105 -0
- forgetproof/scanner.py +288 -0
- forgetproof/sqlite_pages.py +245 -0
- forgetproof/sqlite_residue.py +226 -0
- forgetproof/subject.py +81 -0
- forgetproof-0.2.0.dist-info/METADATA +397 -0
- forgetproof-0.2.0.dist-info/RECORD +42 -0
- forgetproof-0.2.0.dist-info/WHEEL +4 -0
- forgetproof-0.2.0.dist-info/entry_points.txt +3 -0
- forgetproof-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,549 @@
|
|
|
1
|
+
"""The local API behind the Memory Hygiene desktop app.
|
|
2
|
+
|
|
3
|
+
A small JSON server on a loopback port with a per-launch token, the same core as the CLI underneath
|
|
4
|
+
it. The window (pywebview, or the default browser with --browser) loads `/?t=<token>` and sends the
|
|
5
|
+
token on every call; a page from any other origin can't reach it, and nothing leaves the machine.
|
|
6
|
+
|
|
7
|
+
Everything the app shows comes from these routes, so they are what the tests exercise — no window
|
|
8
|
+
needed. Long operations (a scan, a fix, a sweep) run in the request thread; per-store locks keep two
|
|
9
|
+
of them off the same store at once, as the MCP server does.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import secrets
|
|
16
|
+
import sqlite3
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
from datetime import datetime, timezone
|
|
20
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any
|
|
23
|
+
from urllib.parse import parse_qs, urlparse
|
|
24
|
+
|
|
25
|
+
from .. import __version__, copies as copies_mod, discovery, forget as forget_mod, postgres, receipt, remembered, safety
|
|
26
|
+
from ..erase_live import LiveEraseError
|
|
27
|
+
from ..fixer import FixError, Options, fix, plan
|
|
28
|
+
from ..scanner import KINDS, UnsupportedStore, scan
|
|
29
|
+
from ..subject import subject as make_subject
|
|
30
|
+
from . import schedule
|
|
31
|
+
|
|
32
|
+
UI_DIR = Path(__file__).parent / "ui"
|
|
33
|
+
_EXPECTED = (UnsupportedStore, FixError, LiveEraseError, postgres.PostgresError, ValueError, OSError, sqlite3.DatabaseError,
|
|
34
|
+
schedule.ScheduleError)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ApiError(Exception):
|
|
38
|
+
def __init__(self, status: int, message: str):
|
|
39
|
+
super().__init__(message)
|
|
40
|
+
self.status = status
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _now() -> str:
|
|
44
|
+
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Desktop:
|
|
48
|
+
"""The app's state and operations. One per process; the handler calls into it."""
|
|
49
|
+
|
|
50
|
+
def __init__(self, home: Path | None = None):
|
|
51
|
+
self.home = home or receipt.key_path().parent
|
|
52
|
+
self.home.mkdir(parents=True, exist_ok=True)
|
|
53
|
+
self.receipts_dir = self.home / "receipts"
|
|
54
|
+
self.receipts_dir.mkdir(exist_ok=True)
|
|
55
|
+
self.queue_dir = self.home / "queue"
|
|
56
|
+
self.state_path = self.home / "desktop-state.json"
|
|
57
|
+
self.state: dict[str, Any] = self._load_state()
|
|
58
|
+
self.locks: dict[str, threading.Lock] = {}
|
|
59
|
+
self._lock = threading.Lock()
|
|
60
|
+
|
|
61
|
+
# -- state -------------------------------------------------------------------------------------
|
|
62
|
+
|
|
63
|
+
def _load_state(self) -> dict:
|
|
64
|
+
try:
|
|
65
|
+
return json.loads(self.state_path.read_text())
|
|
66
|
+
except (OSError, ValueError):
|
|
67
|
+
return {"scans": {}, "last_sweep": None}
|
|
68
|
+
|
|
69
|
+
def _save_state(self) -> None:
|
|
70
|
+
self.state_path.write_text(json.dumps(self.state, indent=2))
|
|
71
|
+
|
|
72
|
+
def lock(self, name: str) -> threading.Lock:
|
|
73
|
+
with self._lock:
|
|
74
|
+
return self.locks.setdefault(name, threading.Lock())
|
|
75
|
+
|
|
76
|
+
def exclusive(self, name: str):
|
|
77
|
+
lock = self.lock(name)
|
|
78
|
+
if not lock.acquire(blocking=False):
|
|
79
|
+
raise ApiError(409, f"{name} is busy with another operation; try again when it finishes")
|
|
80
|
+
return lock
|
|
81
|
+
|
|
82
|
+
# -- stores ------------------------------------------------------------------------------------
|
|
83
|
+
|
|
84
|
+
def pinned(self) -> dict[str, discovery.Found]:
|
|
85
|
+
return discovery.load_home_config()
|
|
86
|
+
|
|
87
|
+
def target(self, name: str) -> Path | str:
|
|
88
|
+
found = self.pinned().get(name)
|
|
89
|
+
if found is None:
|
|
90
|
+
raise ApiError(404, f"no pinned store named {name!r}")
|
|
91
|
+
try:
|
|
92
|
+
return discovery.resolve(found, root=Path.home())
|
|
93
|
+
except ValueError as e:
|
|
94
|
+
raise ApiError(409, str(e)) from None
|
|
95
|
+
|
|
96
|
+
def _store_row(self, name: str, f: discovery.Found) -> dict:
|
|
97
|
+
row = {"name": name, "kind": f.kind, "kind_label": KINDS.get(f.kind, f.kind), "agent": f.agent, "where": f.where,
|
|
98
|
+
"ok": True, "open": False, "copies": 0, "last_scan": self.state["scans"].get(name)}
|
|
99
|
+
try:
|
|
100
|
+
target = discovery.resolve(f, root=Path.home())
|
|
101
|
+
except ValueError as e:
|
|
102
|
+
row["ok"] = False
|
|
103
|
+
row["problem"] = str(e)
|
|
104
|
+
return row
|
|
105
|
+
if not postgres.is_postgres(target) and f.kind != "files":
|
|
106
|
+
try:
|
|
107
|
+
row["open"] = bool(safety.open_by_other_processes(Path(target)))
|
|
108
|
+
except OSError:
|
|
109
|
+
pass
|
|
110
|
+
if not postgres.is_postgres(target):
|
|
111
|
+
row["copies"] = len([c for c in copies_mod.copies_of(target) if c.kind != "hint"])
|
|
112
|
+
return row
|
|
113
|
+
|
|
114
|
+
def overview(self) -> dict:
|
|
115
|
+
pinned = self.pinned()
|
|
116
|
+
found = [] if pinned else discovery.discover_home()
|
|
117
|
+
return {
|
|
118
|
+
"version": __version__,
|
|
119
|
+
"home": str(self.home),
|
|
120
|
+
"stores": [self._store_row(n, f) for n, f in pinned.items()],
|
|
121
|
+
"unpinned": [{"name": f.name, "kind": f.kind, "kind_label": KINDS.get(f.kind, f.kind), "agent": f.agent,
|
|
122
|
+
"where": f.where} for f in found if f.kind != "postgres"],
|
|
123
|
+
"last_sweep": self.state.get("last_sweep"),
|
|
124
|
+
"queue": self.queue_summary(),
|
|
125
|
+
"key": {"fingerprint": receipt.fingerprint(receipt.public_key_b64(receipt.load_or_create_key()))},
|
|
126
|
+
"schedule": schedule.status(),
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
def discover(self) -> dict:
|
|
130
|
+
found = [f for f in discovery.discover_home() if f.kind != "postgres"]
|
|
131
|
+
pinned = self.pinned()
|
|
132
|
+
new = [f for f in found if f.where not in {p.where for p in pinned.values()}]
|
|
133
|
+
return {"found": [f.__dict__ for f in found], "new": [f.__dict__ for f in new]}
|
|
134
|
+
|
|
135
|
+
def pin(self, entries: list[dict]) -> dict:
|
|
136
|
+
pinned = dict(self.pinned())
|
|
137
|
+
taken = set(pinned)
|
|
138
|
+
for e in entries:
|
|
139
|
+
where = Path(str(e.get("where", ""))).expanduser()
|
|
140
|
+
if not where.exists():
|
|
141
|
+
raise ApiError(400, f"{where} doesn't exist")
|
|
142
|
+
try:
|
|
143
|
+
where.resolve().relative_to(Path.home().resolve())
|
|
144
|
+
except ValueError:
|
|
145
|
+
raise ApiError(400, f"{where} is outside your home directory; the app only pins stores inside it") from None
|
|
146
|
+
kind = e.get("kind") or self._detect(where)
|
|
147
|
+
if kind not in discovery.KINDS or kind == "postgres":
|
|
148
|
+
raise ApiError(400, f"unsupported kind {kind!r}")
|
|
149
|
+
name = str(e.get("name") or where.stem or "store")
|
|
150
|
+
name = "".join(ch if ch.isalnum() or ch in "-_" else "-" for ch in name)[:64] or "store"
|
|
151
|
+
base, n = name, 2
|
|
152
|
+
while name in taken:
|
|
153
|
+
name, n = f"{base}-{n}", n + 1
|
|
154
|
+
taken.add(name)
|
|
155
|
+
pinned[name] = discovery.Found(name, kind, str(where.resolve()), str(e.get("agent", "")))
|
|
156
|
+
discovery.write_config(Path.home(), list(pinned.values()), path=discovery.home_config_path())
|
|
157
|
+
return {"pinned": len(pinned)}
|
|
158
|
+
|
|
159
|
+
def unpin(self, name: str) -> dict:
|
|
160
|
+
pinned = dict(self.pinned())
|
|
161
|
+
if name not in pinned:
|
|
162
|
+
raise ApiError(404, f"no pinned store named {name!r}")
|
|
163
|
+
del pinned[name]
|
|
164
|
+
self.state["scans"].pop(name, None)
|
|
165
|
+
self._save_state()
|
|
166
|
+
discovery.write_config(Path.home(), list(pinned.values()), path=discovery.home_config_path())
|
|
167
|
+
return {"pinned": len(pinned)}
|
|
168
|
+
|
|
169
|
+
def _detect(self, where: Path) -> str:
|
|
170
|
+
from ..scanner import detect
|
|
171
|
+
|
|
172
|
+
try:
|
|
173
|
+
return detect(where)
|
|
174
|
+
except UnsupportedStore as e:
|
|
175
|
+
raise ApiError(400, str(e)) from None
|
|
176
|
+
|
|
177
|
+
# -- operations --------------------------------------------------------------------------------
|
|
178
|
+
|
|
179
|
+
def scan_store(self, name: str) -> dict:
|
|
180
|
+
target = self.target(name)
|
|
181
|
+
lock = self.exclusive(name)
|
|
182
|
+
try:
|
|
183
|
+
r = scan(target)
|
|
184
|
+
summary = {"clean": r.clean, "findings": len(r.findings), "records": sum(f.records for f in r.findings),
|
|
185
|
+
"incomplete": r.incomplete, "scanned_at": _now()}
|
|
186
|
+
self.state["scans"][name] = summary
|
|
187
|
+
self._save_state()
|
|
188
|
+
d = r.to_dict()
|
|
189
|
+
d["plan"] = plan(r)
|
|
190
|
+
d["copies"] = [] if postgres.is_postgres(target) else [c.to_dict() for c in copies_mod.copies_of(target)]
|
|
191
|
+
d["summary"] = summary
|
|
192
|
+
return d
|
|
193
|
+
finally:
|
|
194
|
+
lock.release()
|
|
195
|
+
|
|
196
|
+
def remembered(self, values: list[str], show: bool, stores: list[str] | None) -> dict:
|
|
197
|
+
subj = make_subject(values)
|
|
198
|
+
out = []
|
|
199
|
+
for name, f in self.pinned().items():
|
|
200
|
+
if stores and name not in stores:
|
|
201
|
+
continue
|
|
202
|
+
try:
|
|
203
|
+
target = self.target(name)
|
|
204
|
+
except ApiError as e:
|
|
205
|
+
out.append({"store": name, "kind": f.kind, "agent": f.agent, "status": "error", "error": str(e)})
|
|
206
|
+
continue
|
|
207
|
+
if postgres.is_postgres(target):
|
|
208
|
+
continue
|
|
209
|
+
lock = self.exclusive(name)
|
|
210
|
+
try:
|
|
211
|
+
rem = remembered.where_is(target, subj, show=show)
|
|
212
|
+
d = rem.to_dict()
|
|
213
|
+
out.append({"store": name, "kind": f.kind, "agent": f.agent, "status": d["status"], "values": d["values"]})
|
|
214
|
+
except _EXPECTED as e:
|
|
215
|
+
out.append({"store": name, "kind": f.kind, "agent": f.agent, "status": "error", "error": str(e)})
|
|
216
|
+
finally:
|
|
217
|
+
lock.release()
|
|
218
|
+
overall = "live" if any(o["status"] == "live" for o in out) else \
|
|
219
|
+
"residue" if any(o["status"] == "residue" for o in out) else "absent"
|
|
220
|
+
return {"status": overall, "values": subj.count, "stores": out}
|
|
221
|
+
|
|
222
|
+
def _write_receipt(self, name: str, rec: dict) -> str:
|
|
223
|
+
receipt_id = f"{name}.{datetime.now(timezone.utc):%Y%m%dT%H%M%S%fZ}"
|
|
224
|
+
(self.receipts_dir / f"{receipt_id}.json").write_text(json.dumps(rec, indent=2) + "\n")
|
|
225
|
+
return receipt_id
|
|
226
|
+
|
|
227
|
+
def forget(self, values: list[str], also_live: bool, stores: list[str] | None, correlation_id: str | None) -> dict:
|
|
228
|
+
subj = make_subject(values)
|
|
229
|
+
out = []
|
|
230
|
+
for name, f in self.pinned().items():
|
|
231
|
+
if stores and name not in stores:
|
|
232
|
+
continue
|
|
233
|
+
try:
|
|
234
|
+
target = self.target(name)
|
|
235
|
+
except ApiError as e:
|
|
236
|
+
out.append({"store": name, "status": "error", "why": str(e)})
|
|
237
|
+
continue
|
|
238
|
+
if postgres.is_postgres(target):
|
|
239
|
+
continue
|
|
240
|
+
lock = self.exclusive(name)
|
|
241
|
+
try:
|
|
242
|
+
r = forget_mod.forget(target, subj, also_live=also_live, queue_dir=self.queue_dir, correlation_id=correlation_id)
|
|
243
|
+
if isinstance(r, forget_mod.Queued):
|
|
244
|
+
out.append({"store": name, "status": "queued", "queued_at": r.queued_at,
|
|
245
|
+
"why": "open in another program; finishes at its next start or the next run of queued erasures"})
|
|
246
|
+
continue
|
|
247
|
+
rid = self._write_receipt(name, r)
|
|
248
|
+
self.state["scans"][name] = {"clean": r["after"]["clean"], "findings": len(r["after"]["findings"]),
|
|
249
|
+
"records": sum(r["after"]["findings"].values()), "incomplete": r["after"]["incomplete"],
|
|
250
|
+
"scanned_at": _now()}
|
|
251
|
+
out.append({"store": name, "status": r["verdict"].lower(), "receipt_id": rid, "actions": r["actions"],
|
|
252
|
+
"canaries_found": r["after"]["canaries_found"],
|
|
253
|
+
"copies_not_reached": [c for c in r["copies"] if not c["scannable"]],
|
|
254
|
+
"copies_reachable": [c for c in r["copies"] if c["scannable"]]})
|
|
255
|
+
except _EXPECTED as e:
|
|
256
|
+
out.append({"store": name, "status": "error", "why": str(e)})
|
|
257
|
+
finally:
|
|
258
|
+
lock.release()
|
|
259
|
+
self._save_state()
|
|
260
|
+
return {"values": subj.count, "stores": out}
|
|
261
|
+
|
|
262
|
+
def sweep(self, dry_run: bool = False) -> dict:
|
|
263
|
+
out = []
|
|
264
|
+
for name, f in self.pinned().items():
|
|
265
|
+
try:
|
|
266
|
+
target = self.target(name)
|
|
267
|
+
except ApiError as e:
|
|
268
|
+
out.append({"store": name, "status": "error", "why": str(e)})
|
|
269
|
+
continue
|
|
270
|
+
if not postgres.is_postgres(target) and f.kind != "files" and safety.open_by_other_processes(Path(target)):
|
|
271
|
+
out.append({"store": name, "status": "skipped", "why": "open in another program"})
|
|
272
|
+
continue
|
|
273
|
+
lock = self.exclusive(name)
|
|
274
|
+
try:
|
|
275
|
+
before = scan(target)
|
|
276
|
+
if before.clean:
|
|
277
|
+
out.append({"store": name, "status": "clean"})
|
|
278
|
+
self.state["scans"][name] = {"clean": True, "findings": 0, "records": 0, "incomplete": None, "scanned_at": _now()}
|
|
279
|
+
continue
|
|
280
|
+
if dry_run:
|
|
281
|
+
out.append({"store": name, "status": "would_fix", "findings": len(before.findings), "plan": plan(before)})
|
|
282
|
+
continue
|
|
283
|
+
result = fix(target, [], Options())
|
|
284
|
+
rec = receipt.issue(target, result.before.summary(), result.after.summary(), result.actions, [],
|
|
285
|
+
label=result.before.target, copies=forget_mod._copies(target))
|
|
286
|
+
rid = self._write_receipt(name, rec)
|
|
287
|
+
self.state["scans"][name] = {"clean": result.after.clean, "findings": len(result.after.findings),
|
|
288
|
+
"records": sum(x.records for x in result.after.findings),
|
|
289
|
+
"incomplete": result.after.incomplete, "scanned_at": _now()}
|
|
290
|
+
out.append({"store": name, "status": rec["verdict"].lower(), "receipt_id": rid, "actions": result.actions})
|
|
291
|
+
except _EXPECTED as e:
|
|
292
|
+
out.append({"store": name, "status": "error", "why": str(e)})
|
|
293
|
+
finally:
|
|
294
|
+
lock.release()
|
|
295
|
+
if not dry_run:
|
|
296
|
+
self.state["last_sweep"] = _now()
|
|
297
|
+
self._save_state()
|
|
298
|
+
return {"stores": out, "dry_run": dry_run}
|
|
299
|
+
|
|
300
|
+
# -- queue -------------------------------------------------------------------------------------
|
|
301
|
+
|
|
302
|
+
def queue_summary(self) -> dict:
|
|
303
|
+
pending = parked = 0
|
|
304
|
+
per_store = {}
|
|
305
|
+
for name, f in self.pinned().items():
|
|
306
|
+
try:
|
|
307
|
+
target = discovery.resolve(f, root=Path.home())
|
|
308
|
+
except ValueError:
|
|
309
|
+
continue
|
|
310
|
+
p, s = forget_mod.pending(target, queue_dir=self.queue_dir), forget_mod.stale_entries(target, queue_dir=self.queue_dir)
|
|
311
|
+
if p or s:
|
|
312
|
+
per_store[name] = {"pending": p, "parked": s}
|
|
313
|
+
pending += p
|
|
314
|
+
parked += s
|
|
315
|
+
return {"pending": pending, "parked": parked, "stores": per_store}
|
|
316
|
+
|
|
317
|
+
def run_queued(self) -> dict:
|
|
318
|
+
out = []
|
|
319
|
+
for name, f in self.pinned().items():
|
|
320
|
+
try:
|
|
321
|
+
target = self.target(name)
|
|
322
|
+
except ApiError:
|
|
323
|
+
continue
|
|
324
|
+
if not forget_mod.pending(target, queue_dir=self.queue_dir):
|
|
325
|
+
continue
|
|
326
|
+
lock = self.exclusive(name)
|
|
327
|
+
try:
|
|
328
|
+
for rec in forget_mod.run_queued(target, queue_dir=self.queue_dir):
|
|
329
|
+
out.append({"store": name, "status": rec["verdict"].lower(), "receipt_id": self._write_receipt(name, rec)})
|
|
330
|
+
except _EXPECTED as e:
|
|
331
|
+
out.append({"store": name, "status": "error", "why": str(e)})
|
|
332
|
+
finally:
|
|
333
|
+
lock.release()
|
|
334
|
+
return {"drained": out, "queue": self.queue_summary()}
|
|
335
|
+
|
|
336
|
+
# -- receipts ----------------------------------------------------------------------------------
|
|
337
|
+
|
|
338
|
+
def receipts(self) -> dict:
|
|
339
|
+
rows = []
|
|
340
|
+
for p in sorted(self.receipts_dir.glob("*.json"), reverse=True):
|
|
341
|
+
try:
|
|
342
|
+
rec = json.loads(p.read_text())
|
|
343
|
+
except (OSError, ValueError):
|
|
344
|
+
continue
|
|
345
|
+
rows.append({"receipt_id": p.stem, "store": p.stem.split(".")[0], "issued_at": rec.get("issued_at"),
|
|
346
|
+
"verdict": rec.get("verdict"), "target": rec.get("target"), "subject_values": rec.get("subject_values", 0),
|
|
347
|
+
"correlation_id": rec.get("correlation_id"), "actions": len(rec.get("actions", []))})
|
|
348
|
+
key = receipt.load_or_create_key()
|
|
349
|
+
return {"receipts": rows, "public_key": receipt.public_key_b64(key),
|
|
350
|
+
"fingerprint": receipt.fingerprint(receipt.public_key_b64(key)), "key_path": str(receipt.key_path())}
|
|
351
|
+
|
|
352
|
+
def receipt(self, receipt_id: str) -> dict:
|
|
353
|
+
if "/" in receipt_id or "\\" in receipt_id or ".." in receipt_id:
|
|
354
|
+
raise ApiError(400, "not a receipt id")
|
|
355
|
+
path = self.receipts_dir / f"{receipt_id}.json"
|
|
356
|
+
if not path.is_file():
|
|
357
|
+
raise ApiError(404, "no such receipt")
|
|
358
|
+
return json.loads(path.read_text())
|
|
359
|
+
|
|
360
|
+
def verify(self, receipt_id: str) -> dict:
|
|
361
|
+
rec = self.receipt(receipt_id)
|
|
362
|
+
try:
|
|
363
|
+
receipt.verify_signature(rec)
|
|
364
|
+
except ValueError as e:
|
|
365
|
+
return {"signature_valid": False, "why": str(e)}
|
|
366
|
+
out = {"signature_valid": True, "signing_key": receipt.fingerprint(rec["public_key"]),
|
|
367
|
+
"ours": rec["public_key"] == receipt.public_key_b64(receipt.load_or_create_key()),
|
|
368
|
+
"verdict_at_issue": rec["verdict"]}
|
|
369
|
+
name = receipt_id.split(".")[0]
|
|
370
|
+
try:
|
|
371
|
+
target = self.target(name)
|
|
372
|
+
out["store_unchanged"] = receipt.file_hashes(target) == rec["files"]
|
|
373
|
+
out["clean_now"] = scan(target).clean
|
|
374
|
+
except (ApiError, *_EXPECTED):
|
|
375
|
+
out["store_unchanged"] = None
|
|
376
|
+
out["clean_now"] = None
|
|
377
|
+
return out
|
|
378
|
+
|
|
379
|
+
# -- schedule ----------------------------------------------------------------------------------
|
|
380
|
+
|
|
381
|
+
def schedule_status(self) -> dict:
|
|
382
|
+
return schedule.status()
|
|
383
|
+
|
|
384
|
+
def schedule_install(self, time: str) -> dict:
|
|
385
|
+
return schedule.install(time)
|
|
386
|
+
|
|
387
|
+
def schedule_uninstall(self) -> dict:
|
|
388
|
+
return schedule.uninstall()
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
# --- HTTP ----------------------------------------------------------------------------------------------
|
|
392
|
+
|
|
393
|
+
def make_handler(desktop: Desktop, token: str):
|
|
394
|
+
class Handler(BaseHTTPRequestHandler):
|
|
395
|
+
server_version = f"forgetproof-desktop/{__version__}"
|
|
396
|
+
|
|
397
|
+
def log_message(self, format, *args): # quiet
|
|
398
|
+
pass
|
|
399
|
+
|
|
400
|
+
def _send(self, status: int, body: Any, content_type: str = "application/json; charset=utf-8") -> None:
|
|
401
|
+
data = body if isinstance(body, bytes) else json.dumps(body, indent=2).encode()
|
|
402
|
+
self.send_response(status)
|
|
403
|
+
self.send_header("Content-Type", content_type)
|
|
404
|
+
self.send_header("Content-Length", str(len(data)))
|
|
405
|
+
self.send_header("Cache-Control", "no-store")
|
|
406
|
+
self.send_header("X-Content-Type-Options", "nosniff")
|
|
407
|
+
self.send_header("Referrer-Policy", "no-referrer")
|
|
408
|
+
self.send_header("Content-Security-Policy", "default-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data:")
|
|
409
|
+
self.end_headers()
|
|
410
|
+
self.wfile.write(data)
|
|
411
|
+
|
|
412
|
+
def _authorized(self, query: dict) -> bool:
|
|
413
|
+
given = self.headers.get("X-Forgetproof-Token") or (query.get("t") or [""])[0]
|
|
414
|
+
return bool(given) and secrets.compare_digest(given, token)
|
|
415
|
+
|
|
416
|
+
def _body(self) -> dict:
|
|
417
|
+
n = int(self.headers.get("Content-Length") or 0)
|
|
418
|
+
if n > 1 << 20:
|
|
419
|
+
raise ApiError(413, "body too large")
|
|
420
|
+
raw = self.rfile.read(n) if n else b""
|
|
421
|
+
if not raw.strip():
|
|
422
|
+
return {}
|
|
423
|
+
try:
|
|
424
|
+
body = json.loads(raw)
|
|
425
|
+
except ValueError:
|
|
426
|
+
raise ApiError(400, "the body isn't JSON") from None
|
|
427
|
+
return body if isinstance(body, dict) else {}
|
|
428
|
+
|
|
429
|
+
def do_GET(self):
|
|
430
|
+
url = urlparse(self.path)
|
|
431
|
+
query = parse_qs(url.query)
|
|
432
|
+
if url.path in ("/", "/index.html"):
|
|
433
|
+
if not self._authorized(query):
|
|
434
|
+
return self._send(403, b"forgetproof desktop: open this app from its own window", "text/plain")
|
|
435
|
+
return self._send(200, (UI_DIR / "index.html").read_bytes(), "text/html; charset=utf-8")
|
|
436
|
+
if url.path == "/health":
|
|
437
|
+
return self._send(200, {"ok": True, "version": __version__})
|
|
438
|
+
self._route("GET", url.path, query, {})
|
|
439
|
+
|
|
440
|
+
def do_POST(self):
|
|
441
|
+
url = urlparse(self.path)
|
|
442
|
+
self._route("POST", url.path, parse_qs(url.query), None)
|
|
443
|
+
|
|
444
|
+
def do_DELETE(self):
|
|
445
|
+
url = urlparse(self.path)
|
|
446
|
+
self._route("DELETE", url.path, parse_qs(url.query), {})
|
|
447
|
+
|
|
448
|
+
def _route(self, method: str, path: str, query: dict, body: dict | None) -> None:
|
|
449
|
+
if not self._authorized(query) and not (self.headers.get("X-Forgetproof-Token") and secrets.compare_digest(self.headers.get("X-Forgetproof-Token", ""), token)):
|
|
450
|
+
return self._send(401, {"error": "missing or wrong token"})
|
|
451
|
+
# Browsers send a same-origin check we can rely on: the token header is never set cross-origin
|
|
452
|
+
# without CORS, and we never answer CORS preflights, so no other page can call these.
|
|
453
|
+
try:
|
|
454
|
+
if body is None:
|
|
455
|
+
body = self._body()
|
|
456
|
+
result = self._dispatch(method, path, query, body)
|
|
457
|
+
except ApiError as e:
|
|
458
|
+
return self._send(e.status, {"error": str(e)})
|
|
459
|
+
except _EXPECTED as e:
|
|
460
|
+
return self._send(400, {"error": str(e)})
|
|
461
|
+
except Exception as e: # never a traceback to the page; it's logged to stderr by the server
|
|
462
|
+
import sys
|
|
463
|
+
import traceback
|
|
464
|
+
|
|
465
|
+
traceback.print_exc(file=sys.stderr)
|
|
466
|
+
return self._send(500, {"error": f"unexpected error: {type(e).__name__}"})
|
|
467
|
+
self._send(200, result)
|
|
468
|
+
|
|
469
|
+
def _dispatch(self, method: str, path: str, query: dict, body: dict) -> Any:
|
|
470
|
+
parts = [p for p in path.split("/") if p]
|
|
471
|
+
if not parts or parts[0] != "api":
|
|
472
|
+
raise ApiError(404, "not found")
|
|
473
|
+
parts = parts[1:]
|
|
474
|
+
d = desktop
|
|
475
|
+
match (method, parts):
|
|
476
|
+
case ("GET", ["overview"]):
|
|
477
|
+
return d.overview()
|
|
478
|
+
case ("POST", ["discover"]):
|
|
479
|
+
return d.discover()
|
|
480
|
+
case ("POST", ["stores"]):
|
|
481
|
+
return d.pin(body.get("stores") or [body])
|
|
482
|
+
case ("DELETE", ["stores", name]):
|
|
483
|
+
return d.unpin(name)
|
|
484
|
+
case ("POST", ["stores", name, "scan"]):
|
|
485
|
+
return d.scan_store(name)
|
|
486
|
+
case ("POST", ["remembered"]):
|
|
487
|
+
return d.remembered(body.get("values") or [], bool(body.get("show")), body.get("stores"))
|
|
488
|
+
case ("POST", ["forget"]):
|
|
489
|
+
corr = body.get("correlation_id")
|
|
490
|
+
if corr is not None and (not isinstance(corr, str) or len(corr) > 200):
|
|
491
|
+
raise ApiError(400, "correlation_id must be a short string")
|
|
492
|
+
return d.forget(body.get("values") or [], bool(body.get("also_live")), body.get("stores"), corr)
|
|
493
|
+
case ("POST", ["sweep"]):
|
|
494
|
+
return d.sweep(bool(body.get("dry_run")))
|
|
495
|
+
case ("GET", ["queue"]):
|
|
496
|
+
return d.queue_summary()
|
|
497
|
+
case ("POST", ["queue", "run"]):
|
|
498
|
+
return d.run_queued()
|
|
499
|
+
case ("GET", ["receipts"]):
|
|
500
|
+
return d.receipts()
|
|
501
|
+
case ("GET", ["receipts", rid]):
|
|
502
|
+
return d.receipt(rid)
|
|
503
|
+
case ("POST", ["receipts", rid, "verify"]):
|
|
504
|
+
return d.verify(rid)
|
|
505
|
+
case ("GET", ["schedule"]):
|
|
506
|
+
return d.schedule_status()
|
|
507
|
+
case ("POST", ["schedule"]):
|
|
508
|
+
return d.schedule_install(str(body.get("time") or "03:00"))
|
|
509
|
+
case ("DELETE", ["schedule"]):
|
|
510
|
+
return d.schedule_uninstall()
|
|
511
|
+
raise ApiError(404, "not found")
|
|
512
|
+
|
|
513
|
+
return Handler
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
class Server:
|
|
517
|
+
"""The loopback server: `start()` binds a free port and returns the URL with the token."""
|
|
518
|
+
|
|
519
|
+
def __init__(self, desktop: Desktop | None = None, port: int = 0):
|
|
520
|
+
self.desktop = desktop or Desktop()
|
|
521
|
+
self.token = secrets.token_urlsafe(24)
|
|
522
|
+
self.httpd = ThreadingHTTPServer(("127.0.0.1", port), make_handler(self.desktop, self.token))
|
|
523
|
+
self.httpd.daemon_threads = True
|
|
524
|
+
self.thread: threading.Thread | None = None
|
|
525
|
+
|
|
526
|
+
@property
|
|
527
|
+
def port(self) -> int:
|
|
528
|
+
return self.httpd.server_address[1]
|
|
529
|
+
|
|
530
|
+
@property
|
|
531
|
+
def url(self) -> str:
|
|
532
|
+
return f"http://127.0.0.1:{self.port}/?t={self.token}"
|
|
533
|
+
|
|
534
|
+
def start(self) -> str:
|
|
535
|
+
self.thread = threading.Thread(target=self.httpd.serve_forever, name="forgetproof-desktop", daemon=True)
|
|
536
|
+
self.thread.start()
|
|
537
|
+
import socket
|
|
538
|
+
|
|
539
|
+
for _ in range(50): # until the port accepts a connection
|
|
540
|
+
try:
|
|
541
|
+
with socket.create_connection(("127.0.0.1", self.port), timeout=1):
|
|
542
|
+
break
|
|
543
|
+
except OSError:
|
|
544
|
+
time.sleep(0.05)
|
|
545
|
+
return self.url
|
|
546
|
+
|
|
547
|
+
def stop(self) -> None:
|
|
548
|
+
self.httpd.shutdown()
|
|
549
|
+
self.httpd.server_close()
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Launch the Memory Hygiene window: a loopback server plus a system webview (or the browser)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
import webbrowser
|
|
8
|
+
|
|
9
|
+
from .api import Server
|
|
10
|
+
|
|
11
|
+
TITLE = "Memory Hygiene · forgetproof"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def main(argv: list[str] | None = None) -> int:
|
|
15
|
+
from .. import __version__
|
|
16
|
+
|
|
17
|
+
p = argparse.ArgumentParser(prog="forgetproof desktop", description="the Memory Hygiene desktop app")
|
|
18
|
+
p.add_argument("--version", action="version", version=f"Memory Hygiene (forgetproof {__version__})")
|
|
19
|
+
p.add_argument("--browser", action="store_true", help="open in the default browser instead of a window")
|
|
20
|
+
p.add_argument("--port", type=int, default=0, help="loopback port (default: any free port)")
|
|
21
|
+
p.add_argument("--no-open", action="store_true", help="start the server and print its URL; open nothing")
|
|
22
|
+
args = p.parse_args(argv)
|
|
23
|
+
|
|
24
|
+
server = Server(port=args.port)
|
|
25
|
+
url = server.start()
|
|
26
|
+
if args.no_open:
|
|
27
|
+
print(url, flush=True)
|
|
28
|
+
try:
|
|
29
|
+
server.thread.join()
|
|
30
|
+
except KeyboardInterrupt:
|
|
31
|
+
pass
|
|
32
|
+
finally:
|
|
33
|
+
server.stop()
|
|
34
|
+
return 0
|
|
35
|
+
|
|
36
|
+
webview = None
|
|
37
|
+
if not args.browser:
|
|
38
|
+
try:
|
|
39
|
+
import webview # type: ignore
|
|
40
|
+
except ImportError:
|
|
41
|
+
print("pywebview isn't installed (pip install 'forgetproof[desktop]'); opening in the browser instead",
|
|
42
|
+
file=sys.stderr)
|
|
43
|
+
if webview is None:
|
|
44
|
+
webbrowser.open(url)
|
|
45
|
+
print(f"Memory Hygiene is at {url} (Ctrl+C to stop)", flush=True)
|
|
46
|
+
try:
|
|
47
|
+
server.thread.join()
|
|
48
|
+
except KeyboardInterrupt:
|
|
49
|
+
pass
|
|
50
|
+
finally:
|
|
51
|
+
server.stop()
|
|
52
|
+
return 0
|
|
53
|
+
|
|
54
|
+
webview.create_window(TITLE, url, width=1120, height=780, min_size=(820, 560))
|
|
55
|
+
try:
|
|
56
|
+
webview.start()
|
|
57
|
+
finally:
|
|
58
|
+
server.stop()
|
|
59
|
+
return 0
|