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,226 @@
|
|
|
1
|
+
"""Find rows that survive in a SQLite file after they were deleted or replaced.
|
|
2
|
+
|
|
3
|
+
SQLite does not overwrite deleted rows by default (secure_delete is off): the bytes stay in page
|
|
4
|
+
free blocks, in unallocated page space and on free pages until a VACUUM rewrites the file, and an
|
|
5
|
+
update leaves the previous version the same way. `sqlite_pages` parses the file into live cells and
|
|
6
|
+
the regions no live cell covers. Text in those regions is residue unless the live cells explain it:
|
|
7
|
+
a compacted or split page keeps copies of rows that are still live, and those are not reported.
|
|
8
|
+
The check is structural, so it reports a deleted name or street address as readily as an email.
|
|
9
|
+
Pattern matches (email, phone, card, SSN, API key) only annotate what was found.
|
|
10
|
+
|
|
11
|
+
secure_delete is a per-connection setting whose default is compiled into the library. Debian and
|
|
12
|
+
Ubuntu build their system SQLite with SQLITE_SECURE_DELETE, so an application using that library
|
|
13
|
+
zeroes rows as it deletes them and leaves little behind; python.org, Homebrew, conda and uv-managed
|
|
14
|
+
Pythons bundle a SQLite with the ordinary default. Whatever a file does keep is reported the same way.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import re
|
|
20
|
+
import sqlite3
|
|
21
|
+
from collections.abc import Iterator
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
from . import sqlite_pages
|
|
25
|
+
from .pii import LivePii, find_pii, pii_set, redact, summarize
|
|
26
|
+
from .report import Finding
|
|
27
|
+
|
|
28
|
+
SQLITE_MAGIC = sqlite_pages.MAGIC
|
|
29
|
+
|
|
30
|
+
# Printable ASCII or well-formed UTF-8, eight characters or more: shorter runs are mostly headers.
|
|
31
|
+
_RUN = re.compile(rb"(?:[\x20-\x7e]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf4][\x80-\xbf]{3}){8,}")
|
|
32
|
+
# A sqlite_master row as it lies in a page (type, name, tbl_name, then the statement, with at most one header
|
|
33
|
+
# byte in front) or the statement on its own: the schema a dropped or altered table had. Not a record; VACUUM
|
|
34
|
+
# removes it with everything else. Text that merely begins with a word like "index" does not match.
|
|
35
|
+
_SCHEMA = re.compile(rb"^.?(?:CREATE\s+(?:UNIQUE\s+|VIRTUAL\s+|TEMP\s+|TEMPORARY\s+)?(?:TABLE|INDEX|VIEW|TRIGGER)\b"
|
|
36
|
+
rb"|(?:table|index|view|trigger)([A-Za-z_][\w$]*)(?:\1|[\w$]*CREATE\s))", re.I)
|
|
37
|
+
MAX_SAMPLES = 5
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def is_sqlite(path: Path) -> bool:
|
|
41
|
+
try:
|
|
42
|
+
with path.open("rb") as f:
|
|
43
|
+
return f.read(16) == SQLITE_MAGIC
|
|
44
|
+
except OSError:
|
|
45
|
+
return False
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _is_wal(path: Path) -> bool:
|
|
49
|
+
with path.open("rb") as f:
|
|
50
|
+
header = f.read(20)
|
|
51
|
+
return len(header) == 20 and header[18] == 2 # file format write version 2 = WAL
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def connect_ro(path: Path) -> sqlite3.Connection:
|
|
55
|
+
"""Open read-only so scanning never changes the evidence.
|
|
56
|
+
|
|
57
|
+
Opening a WAL database even read-only creates -wal and -shm files. When no -wal file
|
|
58
|
+
exists there is nothing to replay, so open it as immutable and touch nothing.
|
|
59
|
+
"""
|
|
60
|
+
if _is_wal(path) and not path.with_name(path.name + "-wal").exists():
|
|
61
|
+
return sqlite3.connect(f"{path.as_uri()}?immutable=1", uri=True)
|
|
62
|
+
try:
|
|
63
|
+
conn = sqlite3.connect(f"{path.as_uri()}?mode=ro", uri=True)
|
|
64
|
+
conn.execute("select count(*) from sqlite_master").fetchone()
|
|
65
|
+
return conn
|
|
66
|
+
except sqlite3.OperationalError:
|
|
67
|
+
# Read-only directory with a WAL database: fall back to an immutable view.
|
|
68
|
+
return sqlite3.connect(f"{path.as_uri()}?immutable=1", uri=True)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _live_values(conn: sqlite3.Connection) -> Iterator[bytes]:
|
|
72
|
+
tables = [r[0] for r in conn.execute("select name from sqlite_master where type='table'")]
|
|
73
|
+
for (sql,) in conn.execute("select sql from sqlite_master where sql is not null"):
|
|
74
|
+
yield sql.encode()
|
|
75
|
+
for table in tables:
|
|
76
|
+
quoted = '"' + table.replace('"', '""') + '"'
|
|
77
|
+
try:
|
|
78
|
+
rows = conn.execute(f"select * from {quoted}")
|
|
79
|
+
except sqlite3.Error:
|
|
80
|
+
continue # e.g. a virtual table whose module isn't loaded
|
|
81
|
+
for row in rows:
|
|
82
|
+
for value in row:
|
|
83
|
+
if isinstance(value, str):
|
|
84
|
+
yield value.encode()
|
|
85
|
+
elif isinstance(value, bytes):
|
|
86
|
+
yield value
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def live_pii(path: Path) -> LivePii:
|
|
90
|
+
"""Pattern matches reachable through SQL in this SQLite file, for the checks that still compare
|
|
91
|
+
raw bytes against live content by pattern (Chroma's leaked index memory)."""
|
|
92
|
+
conn = connect_ro(path)
|
|
93
|
+
try:
|
|
94
|
+
return LivePii(pii_set(_live_values(conn)))
|
|
95
|
+
finally:
|
|
96
|
+
conn.close()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def text_runs(data: bytes) -> list[str]:
|
|
100
|
+
return [m.group(0).decode("utf-8", "replace") for m in _RUN.finditer(data)]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class _Grams:
|
|
104
|
+
"""Every window of the live cells' text, in a Bloom filter: 16 MB whatever the file's size, no false
|
|
105
|
+
negatives, and a false positive rate far below one in a thousand for any store that fits in memory,
|
|
106
|
+
which no run of text could pass at every one of its windows by chance."""
|
|
107
|
+
|
|
108
|
+
def __init__(self, width: int, bits: int = 1 << 27):
|
|
109
|
+
self.width = width
|
|
110
|
+
self.mask = bits - 1
|
|
111
|
+
self.bits = bytearray(bits >> 3)
|
|
112
|
+
|
|
113
|
+
def add(self, s: bytes) -> None:
|
|
114
|
+
bits, mask, w = self.bits, self.mask, self.width
|
|
115
|
+
for i in range(len(s) - w + 1):
|
|
116
|
+
h = hash(s[i:i + w])
|
|
117
|
+
a, b = h & mask, (h >> 29) & mask
|
|
118
|
+
bits[a >> 3] |= 1 << (a & 7)
|
|
119
|
+
bits[b >> 3] |= 1 << (b & 7)
|
|
120
|
+
|
|
121
|
+
def has(self, gram: bytes) -> bool:
|
|
122
|
+
h = hash(gram)
|
|
123
|
+
a, b = h & self.mask, (h >> 29) & self.mask
|
|
124
|
+
return bool(self.bits[a >> 3] & (1 << (a & 7))) and bool(self.bits[b >> 3] & (1 << (b & 7)))
|
|
125
|
+
|
|
126
|
+
def explains(self, s: bytes, tail: int = 2) -> bool:
|
|
127
|
+
"""True if every window of `s` that ends before its last `tail` bytes is one a live cell has.
|
|
128
|
+
A run too short for one such window is judged on its first window alone."""
|
|
129
|
+
n, w = len(s), self.width
|
|
130
|
+
last = n - tail - w
|
|
131
|
+
if last < 0:
|
|
132
|
+
return n < w or self.has(s[:w])
|
|
133
|
+
return all(self.has(s[i:i + w]) for i in range(last + 1))
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
WINDOW, SHORT_WINDOW = 16, 8
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _roots(path: Path) -> list[int]:
|
|
140
|
+
conn = connect_ro(path)
|
|
141
|
+
try:
|
|
142
|
+
return [r[0] for r in conn.execute("select rootpage from sqlite_master where rootpage > 0")]
|
|
143
|
+
except sqlite3.Error:
|
|
144
|
+
return []
|
|
145
|
+
finally:
|
|
146
|
+
conn.close()
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def residue_text(path: Path) -> list[str]:
|
|
150
|
+
"""Text in the file's free space, its -wal and its -journal that no live cell explains.
|
|
151
|
+
|
|
152
|
+
A compacted or split page keeps byte-for-byte copies of rows that are still live, so a run of text
|
|
153
|
+
in free space is explained when every 16-byte window of it (8-byte, for a short run) occurs in a
|
|
154
|
+
live cell, header bytes included. A copy's run may end with the first two bytes of the next cell's
|
|
155
|
+
header, which are in no one live cell, so windows that reach into the last two bytes are not
|
|
156
|
+
required. The cost is small and stated: a deleted row is not reported when every 16-byte
|
|
157
|
+
stretch of its text also occurs in live rows, or when it differs from a live row only in its last
|
|
158
|
+
two characters. Name the value as a canary to check for it. The schema a dropped or altered table
|
|
159
|
+
had is left out too: a replaced CREATE statement is not a record.
|
|
160
|
+
"""
|
|
161
|
+
layout = sqlite_pages.layout(path, _roots(path))
|
|
162
|
+
long, short = _Grams(WINDOW), _Grams(SHORT_WINDOW)
|
|
163
|
+
for cell in layout.live:
|
|
164
|
+
for m in _RUN.finditer(cell):
|
|
165
|
+
long.add(m.group(0))
|
|
166
|
+
short.add(m.group(0))
|
|
167
|
+
found: dict[str, None] = {}
|
|
168
|
+
for where, region in layout.slack:
|
|
169
|
+
if where.endswith(", schema)") or not region or region.count(0) == len(region):
|
|
170
|
+
continue
|
|
171
|
+
for m in _RUN.finditer(region):
|
|
172
|
+
run = m.group(0)
|
|
173
|
+
if _SCHEMA.search(run):
|
|
174
|
+
continue
|
|
175
|
+
if not (long if len(run) - 2 >= WINDOW else short).explains(run):
|
|
176
|
+
found[run.decode("utf-8", "replace")] = None
|
|
177
|
+
return list(found)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _sample(run: str, show: bool) -> str:
|
|
181
|
+
return f"text: {run[:80]}" if show else f"text: {redact('text', run.encode())}"
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def slack_finding(path: Path, location: str, show: bool = False) -> Finding | None:
|
|
185
|
+
"""The `sqlite.slack` finding for one SQLite file, or None if its free space holds no text that
|
|
186
|
+
is not also live."""
|
|
187
|
+
runs = residue_text(path)
|
|
188
|
+
if not runs:
|
|
189
|
+
return None
|
|
190
|
+
pii, _ = summarize((kv for r in runs for kv in find_pii(r.encode())), show)
|
|
191
|
+
readable = sorted(runs, key=lambda r: -sum(c.isalpha() for c in r))
|
|
192
|
+
return Finding(
|
|
193
|
+
check="sqlite.slack",
|
|
194
|
+
title="Deleted or replaced rows still readable in the SQLite file's free space",
|
|
195
|
+
location=location,
|
|
196
|
+
records=len(runs),
|
|
197
|
+
unit="text fragments",
|
|
198
|
+
why="SQLite leaves a deleted or replaced row's bytes in free space until VACUUM; any file reader can carve them out",
|
|
199
|
+
pii=pii,
|
|
200
|
+
samples=[_sample(r, show) for r in readable[:MAX_SAMPLES]],
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def table_columns(conn: sqlite3.Connection) -> dict[str, list[str]]:
|
|
205
|
+
"""table -> its column names, for every ordinary table."""
|
|
206
|
+
out = {}
|
|
207
|
+
for (table,) in conn.execute("select name from sqlite_master where type='table' and name not like 'sqlite_%'"):
|
|
208
|
+
quoted = '"' + table.replace('"', '""') + '"'
|
|
209
|
+
try:
|
|
210
|
+
out[table] = [r[1] for r in conn.execute(f"pragma table_info({quoted})")]
|
|
211
|
+
except sqlite3.Error:
|
|
212
|
+
continue
|
|
213
|
+
return out
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def vacuum(path: Path) -> None:
|
|
217
|
+
conn = sqlite3.connect(path)
|
|
218
|
+
try:
|
|
219
|
+
conn.execute("pragma secure_delete=on")
|
|
220
|
+
if conn.execute("pragma journal_mode").fetchone()[0].lower() == "wal":
|
|
221
|
+
conn.execute("pragma wal_checkpoint(TRUNCATE)")
|
|
222
|
+
conn.execute("VACUUM")
|
|
223
|
+
if conn.execute("pragma journal_mode").fetchone()[0].lower() == "wal":
|
|
224
|
+
conn.execute("pragma wal_checkpoint(TRUNCATE)")
|
|
225
|
+
finally:
|
|
226
|
+
conn.close()
|
forgetproof/subject.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""A subject is the set of exact values that identify what a person wants forgotten.
|
|
2
|
+
|
|
3
|
+
For an operator (0.1) a subject was one value, typically an email. The owner of a personal agent
|
|
4
|
+
thinks in entities: *Alice* is a name, two emails and a phone number; *that key I pasted* is one
|
|
5
|
+
string; *my old address* is a street line. forgetproof treats an entity as the list of its exact
|
|
6
|
+
values and nothing more — it never guesses related values, because a guess that erases the wrong
|
|
7
|
+
live record is worse than a value the person has to add by hand.
|
|
8
|
+
|
|
9
|
+
The one expansion it does is mechanical: the same phone number written with different punctuation
|
|
10
|
+
is the same value, so a phone number is matched in its common spellings. Email addresses and
|
|
11
|
+
names are already matched case-insensitively by the byte scanner.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from collections.abc import Iterable
|
|
19
|
+
|
|
20
|
+
_PHONE_DIGITS = re.compile(r"^\+?[\d\s().-]{7,20}$")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def phone_spellings(value: str) -> set[str]:
|
|
24
|
+
"""Common spellings of one phone number, or an empty set if `value` isn't shaped like one.
|
|
25
|
+
|
|
26
|
+
A ten-digit North American number `4155550100` comes back as `415-555-0100`, `415.555.0100`,
|
|
27
|
+
`415 555 0100`, `(415) 555-0100`, `4155550100`, and each with a leading `+1`/`1`; an eleven-digit
|
|
28
|
+
number starting with 1 is treated as the same number with its country code. Anything else keeps
|
|
29
|
+
only its digits and its original spelling, so an international number still matches itself.
|
|
30
|
+
"""
|
|
31
|
+
if not _PHONE_DIGITS.match(value.strip()):
|
|
32
|
+
return set()
|
|
33
|
+
digits = re.sub(r"\D", "", value)
|
|
34
|
+
if len(digits) < 7:
|
|
35
|
+
return set()
|
|
36
|
+
out = {value.strip(), digits}
|
|
37
|
+
national = digits[1:] if len(digits) == 11 and digits[0] == "1" else digits
|
|
38
|
+
if len(national) == 10:
|
|
39
|
+
a, b, c = national[:3], national[3:6], national[6:]
|
|
40
|
+
for sep in ("-", ".", " "):
|
|
41
|
+
out.add(f"{a}{sep}{b}{sep}{c}")
|
|
42
|
+
out.add(f"({a}) {b}-{c}")
|
|
43
|
+
out.add(f"({a}){b}-{c}")
|
|
44
|
+
out |= {f"+1{national}", f"1{national}", f"+1 {a}-{b}-{c}", f"+1 ({a}) {b}-{c}", f"1-{a}-{b}-{c}"}
|
|
45
|
+
return out
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class Subject:
|
|
50
|
+
"""The exact values to look for and erase. `values` is what the person gave; `needles` is what
|
|
51
|
+
the scanner matches, after mechanical expansion. Neither is ever written to a receipt or a log:
|
|
52
|
+
receipts carry `len(values)` only."""
|
|
53
|
+
|
|
54
|
+
values: tuple[str, ...]
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def needles(self) -> list[str]:
|
|
58
|
+
seen: list[str] = []
|
|
59
|
+
for v in self.values:
|
|
60
|
+
for n in [v, *sorted(phone_spellings(v))]:
|
|
61
|
+
if n and n not in seen:
|
|
62
|
+
seen.append(n)
|
|
63
|
+
return seen
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def count(self) -> int:
|
|
67
|
+
return len(self.values)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def subject(values: Iterable[str] | str) -> Subject:
|
|
71
|
+
"""Build a Subject from one value or many, dropping blanks and duplicates, keeping order."""
|
|
72
|
+
if isinstance(values, str):
|
|
73
|
+
values = [values]
|
|
74
|
+
cleaned: list[str] = []
|
|
75
|
+
for v in values:
|
|
76
|
+
v = (v or "").strip()
|
|
77
|
+
if v and v not in cleaned:
|
|
78
|
+
cleaned.append(v)
|
|
79
|
+
if not cleaned:
|
|
80
|
+
raise ValueError("a subject needs at least one non-empty value")
|
|
81
|
+
return Subject(tuple(cleaned))
|