keepfold 0.6.4__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.
- keepfold/__init__.py +1 -0
- keepfold/_proc.py +102 -0
- keepfold/access.py +154 -0
- keepfold/agent_eval.py +162 -0
- keepfold/agent_text.py +56 -0
- keepfold/anki.py +285 -0
- keepfold/app/__init__.py +5 -0
- keepfold/app/actions.py +690 -0
- keepfold/app/desktop.py +677 -0
- keepfold/app/exports.py +254 -0
- keepfold/app/hello.py +79 -0
- keepfold/app/launch.py +114 -0
- keepfold/app/news.py +60 -0
- keepfold/app/server.py +3142 -0
- keepfold/app/status.py +811 -0
- keepfold/app/targets.py +1374 -0
- keepfold/app/winpath.py +54 -0
- keepfold/app/wizard.py +506 -0
- keepfold/ask.py +475 -0
- keepfold/askfile.py +322 -0
- keepfold/assets/LICENSE-d3.txt +13 -0
- keepfold/assets/agent_eval.json +235 -0
- keepfold/assets/app/app.css +611 -0
- keepfold/assets/app/app.js +2712 -0
- keepfold/assets/app/capture.html +16 -0
- keepfold/assets/app/capture.js +91 -0
- keepfold/assets/app/index.html +149 -0
- keepfold/assets/brain3d.js +3730 -0
- keepfold/assets/chat_eval.json +454 -0
- keepfold/assets/d3.v7.min.js +2 -0
- keepfold/assets/dashboard.css +774 -0
- keepfold/assets/dashboard.html.tmpl +170 -0
- keepfold/assets/dashboard.js +4262 -0
- keepfold/assets/help/GUIDE.md +544 -0
- keepfold/assets/help/help.md +83 -0
- keepfold/assets/keepfold.ico +0 -0
- keepfold/assets/whats_new.json +162 -0
- keepfold/backup.py +100 -0
- keepfold/brainmap.py +1382 -0
- keepfold/browse/__init__.py +10 -0
- keepfold/browse/build.py +1320 -0
- keepfold/browse/forget.py +510 -0
- keepfold/browse/legacy.py +95 -0
- keepfold/browse/lists.py +285 -0
- keepfold/browse/privacy.py +391 -0
- keepfold/browse/selftest.py +166 -0
- keepfold/browse/sites.py +1068 -0
- keepfold/browse/sources.py +329 -0
- keepfold/browse/store.py +991 -0
- keepfold/browse/takeout.py +312 -0
- keepfold/browse/titles.py +127 -0
- keepfold/browse/vectors.py +326 -0
- keepfold/browse_serve.py +332 -0
- keepfold/catalog.py +564 -0
- keepfold/chat.py +1464 -0
- keepfold/chat_archive.py +165 -0
- keepfold/chat_eval.py +583 -0
- keepfold/chat_facts.py +721 -0
- keepfold/chat_import.py +1045 -0
- keepfold/chat_pages.py +291 -0
- keepfold/chat_study.py +371 -0
- keepfold/chats.py +669 -0
- keepfold/claims.py +650 -0
- keepfold/cli.py +3254 -0
- keepfold/clients.py +96 -0
- keepfold/cloudllm.py +135 -0
- keepfold/contract.py +43 -0
- keepfold/corrections.py +134 -0
- keepfold/dashboard.py +959 -0
- keepfold/dates.py +202 -0
- keepfold/delta.py +146 -0
- keepfold/digest.py +72 -0
- keepfold/doctor.py +565 -0
- keepfold/duplicates.py +145 -0
- keepfold/egress.py +68 -0
- keepfold/eval_history.py +109 -0
- keepfold/events.py +554 -0
- keepfold/export_context.py +109 -0
- keepfold/fact_harvest.py +578 -0
- keepfold/forget.py +720 -0
- keepfold/harvest.py +334 -0
- keepfold/home.py +714 -0
- keepfold/importers.py +627 -0
- keepfold/index.py +733 -0
- keepfold/know.py +40 -0
- keepfold/learning_eval.py +261 -0
- keepfold/levels.py +595 -0
- keepfold/life_sources.py +747 -0
- keepfold/lint.py +241 -0
- keepfold/localllm.py +699 -0
- keepfold/loops.py +316 -0
- keepfold/mcp_server.py +4464 -0
- keepfold/migrate.py +552 -0
- keepfold/more_sources.py +709 -0
- keepfold/packs.py +148 -0
- keepfold/people.py +99 -0
- keepfold/planner.py +819 -0
- keepfold/prime.py +630 -0
- keepfold/prime_hook.py +265 -0
- keepfold/profiles.py +118 -0
- keepfold/quarantine.py +123 -0
- keepfold/recall_log.py +93 -0
- keepfold/redteam.py +393 -0
- keepfold/reflect.py +164 -0
- keepfold/relink.py +477 -0
- keepfold/render.py +406 -0
- keepfold/review.py +1181 -0
- keepfold/rollups.py +412 -0
- keepfold/safety_net.py +571 -0
- keepfold/sample.py +103 -0
- keepfold/sample_vault/areas/programming.algorithms.md +11 -0
- keepfold/sample_vault/areas/programming.basics.md +11 -0
- keepfold/sample_vault/concepts/big-o-notation.md +13 -0
- keepfold/sample_vault/concepts/functions.md +13 -0
- keepfold/sample_vault/concepts/loops.md +14 -0
- keepfold/sample_vault/concepts/recursion.md +13 -0
- keepfold/sample_vault/domains/programming.md +10 -0
- keepfold/sample_vault/journal/2026-01-12.md +9 -0
- keepfold/sample_vault/me/goals.md +17 -0
- keepfold/sample_vault/me/profile.md +19 -0
- keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
- keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
- keepfold/sample_vault/problems/fizzbuzz.md +12 -0
- keepfold/sample_vault/projects/text-adventure.md +15 -0
- keepfold/sample_vault/resources/python-tutorial.md +16 -0
- keepfold/semantic.py +1254 -0
- keepfold/session.py +764 -0
- keepfold/share.py +69 -0
- keepfold/sources.py +612 -0
- keepfold/sync_copies.py +83 -0
- keepfold/tags.py +230 -0
- keepfold/taint.py +301 -0
- keepfold/tonight.py +195 -0
- keepfold/topics.py +1072 -0
- keepfold/update.py +300 -0
- keepfold/vault.py +942 -0
- keepfold/vecstore.py +218 -0
- keepfold/voice.py +260 -0
- keepfold/voice_memos.py +280 -0
- keepfold/watch.py +303 -0
- keepfold/where.py +119 -0
- keepfold/xray.py +516 -0
- keepfold/zotero.py +303 -0
- keepfold-0.6.4.dist-info/METADATA +644 -0
- keepfold-0.6.4.dist-info/RECORD +148 -0
- keepfold-0.6.4.dist-info/WHEEL +4 -0
- keepfold-0.6.4.dist-info/entry_points.txt +6 -0
- keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
"""The browse privacy filter (docs/design/browse-brain.md §2), as pure functions.
|
|
2
|
+
|
|
3
|
+
It runs first, before anything is kept: a record it drops is never stored anywhere. Order:
|
|
4
|
+
hard drop (scheme, local hosts, sign-in, payment and bank pages, secret-carrying URLs), URL
|
|
5
|
+
scrubbing (no query or fragment but a search term or a YouTube `v=`), the user's lists, then
|
|
6
|
+
the sensitive categories (`browse.skip_categories` drops; one not in `browse.cloud_categories`
|
|
7
|
+
stays on the private pages; by default adult is skipped and every other category kept private).
|
|
8
|
+
`filter_record` is the whole filter.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import hashlib
|
|
14
|
+
import ipaddress
|
|
15
|
+
import re
|
|
16
|
+
import unicodedata
|
|
17
|
+
from dataclasses import dataclass, replace
|
|
18
|
+
from urllib.parse import parse_qsl, quote, unquote, urlsplit
|
|
19
|
+
|
|
20
|
+
from keepfold.browse import lists
|
|
21
|
+
from keepfold.vault import secret_pattern
|
|
22
|
+
|
|
23
|
+
HOST_RE = re.compile(r"^[a-z0-9.-]+$")
|
|
24
|
+
_WORD = re.compile(r"[a-z0-9]+")
|
|
25
|
+
_UWORD = re.compile(r"[^\W_]+") # any script, casefolded first; "_" splits like "-"
|
|
26
|
+
_HYPHENED = re.compile(r"[^\W_]+(?:-[^\W_]+)+")
|
|
27
|
+
_NOTIFY = re.compile(r"^\(\d+\+?\)\s*") # "(3) Title": an unread-count prefix
|
|
28
|
+
TITLE_MAX, TERM_MAX = 300, 200
|
|
29
|
+
ADULT = ("skip", "private")
|
|
30
|
+
SENSITIVE = ("private", "skip")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Settings:
|
|
35
|
+
"""`browse:` in ~/.keepfold/config.yaml. adult: skip|private (code default skip, spec §0);
|
|
36
|
+
sensitive: private|skip; deny/allow/private: domain lists (a domain covers subdomains);
|
|
37
|
+
visible_to_claude: write the public pages, journal lines and touches (code default False:
|
|
38
|
+
only private pages, so nothing from browsing reaches Claude)."""
|
|
39
|
+
adult: str = "skip"
|
|
40
|
+
sensitive: str = "private"
|
|
41
|
+
deny: tuple[str, ...] = ()
|
|
42
|
+
allow: tuple[str, ...] = ()
|
|
43
|
+
private: tuple[str, ...] = ()
|
|
44
|
+
visible_to_claude: bool = False
|
|
45
|
+
browsers: tuple[str, ...] = () # `browsers:` which browsers to read; empty = every one found
|
|
46
|
+
# categories (lists.CATEGORIES) kept only under browse/private/, never shown to Claude
|
|
47
|
+
hidden_from_claude: tuple[str, ...] = lists.CATEGORIES
|
|
48
|
+
# never saved at all; None: from the legacy adult/sensitive "skip" (adult by default)
|
|
49
|
+
skip_categories: tuple[str, ...] | None = None
|
|
50
|
+
private_mcp: bool = False # allow `keepfold mcp --private` (local models only)
|
|
51
|
+
cloud_processing: bool = False # a cloud model may process cloud-audience browsing
|
|
52
|
+
skip_profiles: tuple[str, ...] = () # source keys unticked in the app: no automatic import
|
|
53
|
+
|
|
54
|
+
def __post_init__(self):
|
|
55
|
+
if self.skip_categories is None:
|
|
56
|
+
object.__setattr__(self, "skip_categories", tuple(
|
|
57
|
+
c for c in lists.CATEGORIES
|
|
58
|
+
if (self.adult if c == "adult" else self.sensitive) == "skip"))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def load_settings(config: dict | None = None) -> Settings:
|
|
62
|
+
"""Settings from a config dict (default: ~/.keepfold/config.yaml); bad values fall back."""
|
|
63
|
+
if config is None:
|
|
64
|
+
from keepfold.taint import config as read
|
|
65
|
+
config = read()
|
|
66
|
+
b = config.get("browse") if isinstance(config, dict) else None
|
|
67
|
+
b = b if isinstance(b, dict) else {}
|
|
68
|
+
|
|
69
|
+
def domains(key):
|
|
70
|
+
v = b.get(key) or []
|
|
71
|
+
v = [v] if isinstance(v, str) else v if isinstance(v, list) else []
|
|
72
|
+
v = {str(d).strip().lower().lstrip(".") for d in v if str(d).strip()}
|
|
73
|
+
return tuple(sorted({_ascii_host(d) or d for d in v})) # hosts are stored as punycode
|
|
74
|
+
|
|
75
|
+
def cats(key, default):
|
|
76
|
+
v = b.get(key)
|
|
77
|
+
v = [v] if isinstance(v, str) else v if isinstance(v, list) else None
|
|
78
|
+
return default if v is None else tuple(c for c in lists.CATEGORIES if c in {
|
|
79
|
+
str(x).strip().lower() for x in v})
|
|
80
|
+
|
|
81
|
+
# C9: the cloud allowlist is stored, so a category added later is local; a config from
|
|
82
|
+
# before it (hidden_from_claude) counts every category it could not know of as hidden
|
|
83
|
+
cloud = cats("cloud_categories", None)
|
|
84
|
+
legacy = cats("hidden_from_claude", None)
|
|
85
|
+
hidden = (tuple(c for c in lists.CATEGORIES if c not in cloud) if cloud is not None
|
|
86
|
+
else lists.CATEGORIES if legacy is None
|
|
87
|
+
else tuple(c for c in lists.CATEGORIES
|
|
88
|
+
if c in legacy or c not in lists.CATEGORIES_V1))
|
|
89
|
+
return Settings(adult=b.get("adult") if b.get("adult") in ADULT else "skip",
|
|
90
|
+
hidden_from_claude=hidden,
|
|
91
|
+
skip_categories=cats("skip_categories", None),
|
|
92
|
+
private_mcp=b.get("private_mcp") is True,
|
|
93
|
+
cloud_processing=b.get("cloud_processing") is True,
|
|
94
|
+
sensitive=b.get("sensitive") if b.get("sensitive") in SENSITIVE
|
|
95
|
+
else "private",
|
|
96
|
+
deny=domains("deny_domains"), allow=domains("allow_domains"),
|
|
97
|
+
private=domains("private_domains"),
|
|
98
|
+
visible_to_claude=b.get("visible_to_claude") is True,
|
|
99
|
+
skip_profiles=tuple(sorted({x for x in b["skip_profiles"]
|
|
100
|
+
if isinstance(x, str)}))
|
|
101
|
+
if isinstance(b.get("skip_profiles"), list) else (),
|
|
102
|
+
browsers=tuple(sorted({str(x).strip().lower() for x in (
|
|
103
|
+
[b["browsers"]] if isinstance(b.get("browsers"), str)
|
|
104
|
+
else b.get("browsers") if isinstance(b.get("browsers"), list) else [])
|
|
105
|
+
if str(x).strip()})))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@dataclass(frozen=True)
|
|
109
|
+
class Kept:
|
|
110
|
+
"""A record that passed the filter. `url` is scrubbed; `title` is still untrusted text
|
|
111
|
+
(escape it when rendering); `category` is one of lists.CATEGORIES or None;
|
|
112
|
+
`maybe` marks a category from a soft word only; it is private all the same."""
|
|
113
|
+
url: str
|
|
114
|
+
title: str
|
|
115
|
+
host: str
|
|
116
|
+
category: str | None = None
|
|
117
|
+
private: bool = False
|
|
118
|
+
search: str | None = None # the kept search term
|
|
119
|
+
engine: str | None = None
|
|
120
|
+
video: str | None = None # a YouTube video id
|
|
121
|
+
maybe: bool = False
|
|
122
|
+
# C1: kept local because its text has no local-model verdict yet (a local model is set up)
|
|
123
|
+
local: bool = False
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def in_domains(host: str, domains) -> bool:
|
|
127
|
+
return any(host == d or host.endswith("." + d) for d in domains)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _local(host: str) -> bool:
|
|
131
|
+
if host == "localhost" or host.endswith((".localhost", ".local", ".internal", ".lan")):
|
|
132
|
+
return True
|
|
133
|
+
try:
|
|
134
|
+
ip = ipaddress.ip_address(host.strip("[]"))
|
|
135
|
+
except ValueError:
|
|
136
|
+
return "." not in host # an intranet single-label host
|
|
137
|
+
# ::ffff:192.168.1.5 is 192.168.1.5 (Python before 3.12.4 judges mapped addresses apart)
|
|
138
|
+
ip = getattr(ip, "ipv4_mapped", None) or ip
|
|
139
|
+
return not ip.is_global # private, loopback, link-local, CGNAT 100.64/10, reserved...
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _heads(parts) -> set[str]:
|
|
143
|
+
"""Per part (a path segment or host label): its first word, and its first two joined
|
|
144
|
+
("sign-in" -> signin), so "/how-oauth-works" is not a sign-in page but "/oauth/x" is."""
|
|
145
|
+
out = set()
|
|
146
|
+
for p in parts:
|
|
147
|
+
w = _WORD.findall(p.lower())
|
|
148
|
+
if w:
|
|
149
|
+
out.add(w[0])
|
|
150
|
+
if len(w) > 1:
|
|
151
|
+
out.add(w[0] + w[1])
|
|
152
|
+
return out
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _all_words(parts) -> set[str]:
|
|
156
|
+
return {w for p in parts for w in _WORD.findall(p.lower())}
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _secret_query(query: str) -> bool:
|
|
160
|
+
for k, _ in parse_qsl(query, keep_blank_values=True):
|
|
161
|
+
k = k.lower()
|
|
162
|
+
if k in lists.SECRET_KEYS or any(p in k for p in lists.SECRET_PARTS):
|
|
163
|
+
return True
|
|
164
|
+
return False
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _ascii_host(host: str) -> str | None:
|
|
168
|
+
"""An IDN host as punycode ("bücher.de" -> "xn--bcher-kva.de"), or None when it has no
|
|
169
|
+
valid IDNA form."""
|
|
170
|
+
if host.isascii():
|
|
171
|
+
return host
|
|
172
|
+
try:
|
|
173
|
+
return host.encode("idna").decode("ascii")
|
|
174
|
+
except UnicodeError:
|
|
175
|
+
return None
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def drop_reason(url: str) -> str | None:
|
|
179
|
+
"""§2.1: why `url` is dropped outright, or None."""
|
|
180
|
+
try:
|
|
181
|
+
u = urlsplit(url.strip())
|
|
182
|
+
host = _ascii_host((u.hostname or "").rstrip("."))
|
|
183
|
+
_ = u.port # raises on a garbage port
|
|
184
|
+
except ValueError:
|
|
185
|
+
return "scheme"
|
|
186
|
+
if u.scheme.lower() not in ("http", "https"):
|
|
187
|
+
return "scheme"
|
|
188
|
+
if not host or not HOST_RE.match(host):
|
|
189
|
+
return "scheme"
|
|
190
|
+
if u.username or u.password:
|
|
191
|
+
return "secret"
|
|
192
|
+
if _local(host):
|
|
193
|
+
return "local"
|
|
194
|
+
parts = [unquote(p) for p in u.path.split("/")] + host.split(".")
|
|
195
|
+
words, heads = _all_words(parts), _heads(parts) # heads also join "sign_in" -> signin
|
|
196
|
+
if in_domains(host, lists.AUTH_HOSTS) or (words | heads) & lists.AUTH_WORDS:
|
|
197
|
+
return "sign-in"
|
|
198
|
+
if (in_domains(host, lists.PAY_HOSTS) or in_domains(host, lists.BANK_HOSTS)
|
|
199
|
+
or heads & lists.PAY_WORDS or words & lists.BANK_WORDS
|
|
200
|
+
or any(lists.BANK_LABEL in label for label in host.split("."))):
|
|
201
|
+
return "payment"
|
|
202
|
+
if _secret_query(u.query) or _secret_query(u.fragment):
|
|
203
|
+
return "secret"
|
|
204
|
+
return None
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _engine(host: str, path: str) -> tuple[str, str] | None:
|
|
208
|
+
"""(engine, query key) of a known search page, or None."""
|
|
209
|
+
h = host.removeprefix("www.").removeprefix("m.")
|
|
210
|
+
if re.fullmatch(r"google(\.[a-z]{2,3}){1,2}", h) and path == "/search":
|
|
211
|
+
return "google", "q"
|
|
212
|
+
if h == "bing.com" and path == "/search":
|
|
213
|
+
return "bing", "q"
|
|
214
|
+
if h in ("duckduckgo.com", "html.duckduckgo.com"):
|
|
215
|
+
return "duckduckgo", "q"
|
|
216
|
+
if h == "search.brave.com" and path.startswith("/search"):
|
|
217
|
+
return "brave", "q"
|
|
218
|
+
if h == "youtube.com" and path == "/results":
|
|
219
|
+
return "youtube", "search_query"
|
|
220
|
+
if h == "perplexity.ai" and path.startswith("/search"):
|
|
221
|
+
return "perplexity", "q"
|
|
222
|
+
if re.fullmatch(r"amazon(\.[a-z]{2,3}){1,2}", h) and path == "/s":
|
|
223
|
+
return "amazon", "k"
|
|
224
|
+
if h == "github.com" and path == "/search":
|
|
225
|
+
return "github", "q"
|
|
226
|
+
return None
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def scrub(url: str) -> tuple[str, str | None, str | None, str | None]:
|
|
230
|
+
"""§2.2: (url without query or fragment, search term, engine, YouTube id). Only a known
|
|
231
|
+
engine's search term and a YouTube watch `v=` survive, as the only query parameter."""
|
|
232
|
+
u = urlsplit(url.strip())
|
|
233
|
+
host = (u.hostname or "").rstrip(".")
|
|
234
|
+
host = _ascii_host(host) or host
|
|
235
|
+
path = u.path or "/"
|
|
236
|
+
base = f"{u.scheme.lower()}://{host}{quote(path, safe='/%:@-._~!$&()*+,;=')}"
|
|
237
|
+
q = dict(parse_qsl(u.query))
|
|
238
|
+
if eng := _engine(host, path):
|
|
239
|
+
term = " ".join(q.get(eng[1], "").split())[:TERM_MAX]
|
|
240
|
+
if term:
|
|
241
|
+
return f"{base}?{eng[1]}={quote(term)}", term, eng[0], None
|
|
242
|
+
return base, None, None, None
|
|
243
|
+
h = host.removeprefix("www.").removeprefix("m.")
|
|
244
|
+
vid = None
|
|
245
|
+
if h == "youtube.com" and path == "/watch":
|
|
246
|
+
vid = q.get("v")
|
|
247
|
+
elif h == "youtu.be":
|
|
248
|
+
vid = path.strip("/").split("/")[0]
|
|
249
|
+
if vid and re.fullmatch(r"[A-Za-z0-9_-]{6,20}", vid):
|
|
250
|
+
return f"https://www.youtube.com/watch?v={vid}", None, None, vid
|
|
251
|
+
return base, None, None, None
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _tokens(s: str) -> list[str]:
|
|
255
|
+
"""Words of any script: letters, digits and combining marks (Devanagari vowel signs)."""
|
|
256
|
+
return "".join(c if c.isalnum() or unicodedata.category(c)[0] == "M" else " "
|
|
257
|
+
for c in s).split()
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _leet(t: str) -> str:
|
|
261
|
+
return t.translate(lists.LEET) if any(c.isalpha() for c in t) or len(t) == 1 else t
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _joined(tokens: list[str]) -> list[str]:
|
|
265
|
+
"""Runs of single characters joined ("p o r n", "p.o.r.n" -> porn), leetspeak mapped."""
|
|
266
|
+
out, run = [], []
|
|
267
|
+
for t in [*tokens, " "]:
|
|
268
|
+
if len(t) == 1:
|
|
269
|
+
run.append(t)
|
|
270
|
+
continue
|
|
271
|
+
if len(run) > 1:
|
|
272
|
+
out.append("".join(run).translate(lists.LEET))
|
|
273
|
+
run = []
|
|
274
|
+
return out
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _norm(*texts: str) -> tuple[set[str], str]:
|
|
278
|
+
"""(words, the words joined by spaces) for matching: NFKC, casefold, zero-width and soft
|
|
279
|
+
hyphens dropped, Cyrillic/Greek look-alikes and leetspeak mapped, single letters joined.
|
|
280
|
+
The words before the look-alike and leetspeak mapping stay in the set too."""
|
|
281
|
+
s = unicodedata.normalize("NFKC", " ".join(t for t in texts if t)).casefold()
|
|
282
|
+
s = re.sub(r"\bstd\s*::", " ", s.translate(lists.CONFUSABLES)) # C++, not health
|
|
283
|
+
raw = _tokens(s)
|
|
284
|
+
mapped = [_leet(t) for t in _tokens(re.sub(r"[@$]", lambda m: "a" if m[0] == "@" else "s",
|
|
285
|
+
s))]
|
|
286
|
+
words = set(raw) | set(mapped) | set(_joined(raw)) | set(_HYPHENED.findall(s))
|
|
287
|
+
return words, " " + " ".join(mapped) + " "
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _words(*texts: str) -> set[str]:
|
|
291
|
+
return _norm(*texts)[0]
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def category(host: str, path: str, title: str, term: str | None = None, channel: str = ""
|
|
295
|
+
) -> tuple[str | None, bool]:
|
|
296
|
+
"""§2.4: (category or None, maybe). A built-in domain, an adult TLD, a host label starting
|
|
297
|
+
with an adult brand ("xvideos2.com"), a STRONG word or a word starting with a STRONG_STEMS
|
|
298
|
+
stem is sure; any other listed word, phrase or stem in the title, search term, channel or
|
|
299
|
+
URL words (normalised, see `_norm`) is a maybe."""
|
|
300
|
+
for c in lists.CATEGORIES:
|
|
301
|
+
if in_domains(host, lists.CATEGORY_HOSTS[c]):
|
|
302
|
+
return c, False
|
|
303
|
+
try: # an IDN host is matched in its own script, not as punycode
|
|
304
|
+
host = host.encode("ascii").decode("idna") if "xn--" in host else host
|
|
305
|
+
except UnicodeError:
|
|
306
|
+
pass
|
|
307
|
+
labels = host.split(".")
|
|
308
|
+
if labels[-1] in lists.ADULT_TLDS or any(
|
|
309
|
+
label.startswith(lists.ADULT_BRANDS) for label in labels):
|
|
310
|
+
return "adult", False
|
|
311
|
+
words, text = _norm(title, term or "", channel, host.replace(".", " "),
|
|
312
|
+
unquote(path).replace("/", " "))
|
|
313
|
+
if words & lists.STRONG or any(w.startswith(lists.STRONG_STEMS) for w in words):
|
|
314
|
+
return "adult", False
|
|
315
|
+
for c in lists.CATEGORIES:
|
|
316
|
+
if words & lists.CATEGORY_WORDS[c]:
|
|
317
|
+
return c, True
|
|
318
|
+
for c in lists.CATEGORIES:
|
|
319
|
+
if any(f" {p} " in text for p in lists.PHRASES.get(c, ())):
|
|
320
|
+
return c, True
|
|
321
|
+
for c in lists.STEM_ORDER:
|
|
322
|
+
if any(w.startswith(lists.STEMS[c]) for w in words):
|
|
323
|
+
return c, True
|
|
324
|
+
return None, False
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def text_key(text: str) -> str:
|
|
328
|
+
"""The key a local-model verdict on `text` is cached under: a hash, never the text."""
|
|
329
|
+
return hashlib.sha256(" ".join(text.casefold().split()).encode("utf-8")).hexdigest()[:16]
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def clean_title(title: str) -> str:
|
|
333
|
+
t = " ".join(str(title or "").split())
|
|
334
|
+
return _NOTIFY.sub("", t)[:TITLE_MAX]
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def judge(url: str, title: str, *, settings: Settings, channel: str = "") -> Kept | None:
|
|
338
|
+
"""Steps 1-3 and the category of step 4, before the category's skip/private action
|
|
339
|
+
(`apply`). None: dropped by a hard rule, a secret, a bank title or the user's lists.
|
|
340
|
+
`channel` (a video's, from the old extension's inbox) counts for the secret and category
|
|
341
|
+
checks."""
|
|
342
|
+
if drop_reason(url):
|
|
343
|
+
return None
|
|
344
|
+
title = clean_title(title)
|
|
345
|
+
if any(p in title.casefold() for p in lists.BANK_TITLES):
|
|
346
|
+
return None
|
|
347
|
+
clean, term, engine, vid = scrub(url)
|
|
348
|
+
# checked decoded, after the scrub: "q=api_key%3D..." hides from a check on the raw URL
|
|
349
|
+
if any(secret_pattern(t) for t in (url, unquote(url), title, term or "", channel)):
|
|
350
|
+
return None
|
|
351
|
+
u = urlsplit(clean)
|
|
352
|
+
host = u.hostname or ""
|
|
353
|
+
if in_domains(host, settings.deny) or (settings.allow
|
|
354
|
+
and not in_domains(host, settings.allow)):
|
|
355
|
+
return None
|
|
356
|
+
if in_domains(host, lists.WEBMAIL_HOSTS): # the site name only, never the subject
|
|
357
|
+
return Kept(f"https://{host}/", host, host, private=in_domains(host, settings.private))
|
|
358
|
+
if vid:
|
|
359
|
+
title = re.sub(r"\s+-\s+YouTube$", "", title)
|
|
360
|
+
cat, maybe = category(host, u.path, title, term, channel)
|
|
361
|
+
return Kept(clean, title, host, cat, in_domains(host, settings.private), term, engine,
|
|
362
|
+
vid, maybe)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def audience(category: str | None, settings: Settings) -> str:
|
|
366
|
+
"""Who may read and process a category (docs/design/data-access.md §1): "skip" (never
|
|
367
|
+
stored), "local" (local models only) or "cloud". A "maybe" counts as its category; None
|
|
368
|
+
(uncategorised) follows visible_to_claude."""
|
|
369
|
+
if category in settings.skip_categories:
|
|
370
|
+
return "skip"
|
|
371
|
+
if category in settings.hidden_from_claude or not settings.visible_to_claude:
|
|
372
|
+
return "local"
|
|
373
|
+
return "cloud"
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def apply(k: Kept | None, *, settings: Settings) -> Kept | None:
|
|
377
|
+
"""Step 4's action (a "maybe" counts as its category): a category in
|
|
378
|
+
settings.skip_categories drops the record; one in settings.hidden_from_claude keeps it for
|
|
379
|
+
the private pages only; any other stays as it is (a private_domains host stays private)."""
|
|
380
|
+
if k is None or k.category is None:
|
|
381
|
+
return k
|
|
382
|
+
if audience(k.category, settings) == "skip":
|
|
383
|
+
return None
|
|
384
|
+
return replace(k, private=True) if k.category in settings.hidden_from_claude else k
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def filter_record(url: str, title: str, *, settings: Settings, channel: str = ""
|
|
388
|
+
) -> Kept | None:
|
|
389
|
+
"""The whole §2 filter for one record (a "maybe" category counts as the category): the
|
|
390
|
+
scrubbed record, or None when it must not be stored at all."""
|
|
391
|
+
return apply(judge(url, title, settings=settings, channel=channel), settings=settings)
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""`keepfold browse selftest`: the whole browse import, end to end, on synthetic data only.
|
|
2
|
+
|
|
3
|
+
It builds a throwaway vault and synthetic Chrome, Comet (Perplexity/Comet/User Data) and
|
|
4
|
+
Firefox history files in a temp folder, runs scan and import against them and checks what the
|
|
5
|
+
owner cares about. It never opens the real vault, ~/.keepfold/config.yaml or a real browser
|
|
6
|
+
profile (default Settings, explicit paths), so the owner can see it work without exposing data.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import sqlite3
|
|
13
|
+
import tempfile
|
|
14
|
+
from collections.abc import Callable
|
|
15
|
+
from dataclasses import replace
|
|
16
|
+
from datetime import UTC, datetime, timedelta
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from keepfold.browse import build, privacy, sources
|
|
20
|
+
from keepfold.vault import PRIVATE_BROWSE_DIR, Vault
|
|
21
|
+
|
|
22
|
+
DROPPED = ("SIGNINMARKER", "BANKMARKER", "SECRETMARKER")
|
|
23
|
+
SENSITIVE = ("HEALTHMARKER", "ADULTMARKER")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _chromium(path: Path, rows: list[tuple[datetime, str, str]]) -> None:
|
|
27
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
28
|
+
con = sqlite3.connect(path)
|
|
29
|
+
con.executescript(
|
|
30
|
+
"CREATE TABLE urls(id INTEGER PRIMARY KEY, url TEXT, title TEXT);"
|
|
31
|
+
"CREATE TABLE visits(id INTEGER PRIMARY KEY, url INTEGER, visit_time INTEGER, "
|
|
32
|
+
"visit_duration INTEGER, transition INTEGER);"
|
|
33
|
+
"CREATE TABLE keyword_search_terms(keyword_id INTEGER, url_id INTEGER, term TEXT, "
|
|
34
|
+
"normalized_term TEXT);")
|
|
35
|
+
for t, url, title in rows:
|
|
36
|
+
uid = con.execute("INSERT INTO urls(url, title) VALUES (?, ?)", (url, title)).lastrowid
|
|
37
|
+
raw = int((t - sources.EPOCH).total_seconds() * 1e6) + sources.CHROME_OFFSET_US
|
|
38
|
+
con.execute("INSERT INTO visits(url, visit_time, visit_duration, transition) "
|
|
39
|
+
"VALUES (?, ?, 0, 805306368)", (uid, raw))
|
|
40
|
+
con.commit()
|
|
41
|
+
con.close()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _firefox(path: Path, rows: list[tuple[datetime, str, str]]) -> None:
|
|
45
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
46
|
+
con = sqlite3.connect(path)
|
|
47
|
+
con.executescript("CREATE TABLE moz_places(id INTEGER PRIMARY KEY, url TEXT, title TEXT);"
|
|
48
|
+
"CREATE TABLE moz_historyvisits(id INTEGER PRIMARY KEY, place_id INTEGER,"
|
|
49
|
+
" visit_date INTEGER, visit_type INTEGER);")
|
|
50
|
+
for t, url, title in rows:
|
|
51
|
+
pid = con.execute("INSERT INTO moz_places(url, title) VALUES (?, ?)",
|
|
52
|
+
(url, title)).lastrowid
|
|
53
|
+
con.execute("INSERT INTO moz_historyvisits(place_id, visit_date, visit_type) "
|
|
54
|
+
"VALUES (?, ?, 1)", (pid, int(t.timestamp() * 1e6)))
|
|
55
|
+
con.commit()
|
|
56
|
+
con.close()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _machine(local: Path, roaming: Path, now: datetime) -> None:
|
|
60
|
+
t = (now - timedelta(days=3)).replace(hour=9, minute=0, second=0, microsecond=0)
|
|
61
|
+
|
|
62
|
+
def at(mins: int, day: int = 0) -> datetime:
|
|
63
|
+
return t + timedelta(days=day, minutes=mins)
|
|
64
|
+
|
|
65
|
+
_chromium(local / "Google" / "Chrome" / "User Data" / "Default" / "History", [
|
|
66
|
+
(at(0), "https://example.org/chess/openings", "Chess openings for beginners"),
|
|
67
|
+
(at(10), "https://www.google.com/search?q=chess+endgames", "chess endgames - Google"),
|
|
68
|
+
(at(20), "https://accounts.example.com/signin", "Sign in SIGNINMARKER"),
|
|
69
|
+
(at(30), "https://www.hdfcbank.com/personal", "Net Banking BANKMARKER"),
|
|
70
|
+
(at(40), "https://example.com/cb?token=SECRETMARKER", "Callback SECRETMARKER"),
|
|
71
|
+
(at(50), "https://health.example.org/flu", "Flu symptoms HEALTHMARKER"),
|
|
72
|
+
(at(60), "https://www.pornhub.com/view_video.php?viewkey=zz", "ADULTMARKER video"),
|
|
73
|
+
(at(0, 1), "https://example.org/guitar/chords", "Guitar chords"),
|
|
74
|
+
])
|
|
75
|
+
_chromium(local / "Perplexity" / "Comet" / "User Data" / "Default" / "History",
|
|
76
|
+
[(at(90), "https://example.org/notes/linear-algebra", "Linear algebra notes")])
|
|
77
|
+
_firefox(roaming / "Mozilla" / "Firefox" / "Profiles" / "ab12.default-release"
|
|
78
|
+
/ "places.sqlite",
|
|
79
|
+
[(at(120), "https://example.org/python/typing", "Python typing guide")])
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _files(root: Path) -> dict[str, bytes]:
|
|
83
|
+
return {p.relative_to(root).as_posix(): p.read_bytes() for p in root.rglob("*")
|
|
84
|
+
if p.is_file()}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _digest(p: Path) -> str:
|
|
88
|
+
return hashlib.sha256(p.read_bytes()).hexdigest()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def run(echo: Callable[[str], None] = print) -> bool:
|
|
92
|
+
"""Run every check, echo one PASS/FAIL line each and a total; True when all pass."""
|
|
93
|
+
results: list[tuple[str, bool]] = []
|
|
94
|
+
|
|
95
|
+
def check(name: str, fn: Callable[[], bool]) -> None:
|
|
96
|
+
try:
|
|
97
|
+
ok = bool(fn())
|
|
98
|
+
except Exception as e: # a crash is a failed check, not a traceback
|
|
99
|
+
ok, name = False, f"{name} ({type(e).__name__})"
|
|
100
|
+
results.append((name, ok))
|
|
101
|
+
echo(f"{'PASS' if ok else 'FAIL'} {name}")
|
|
102
|
+
|
|
103
|
+
echo("browse selftest: synthetic history in a temp folder; your vault and browsers are "
|
|
104
|
+
"not touched")
|
|
105
|
+
old_tmp = tempfile.tempdir
|
|
106
|
+
with tempfile.TemporaryDirectory(prefix="keepfold-selftest-") as tmp:
|
|
107
|
+
base = Path(tmp)
|
|
108
|
+
local, roaming, root, scratch = (base / n for n in ("local", "roaming", "vault",
|
|
109
|
+
"scratch"))
|
|
110
|
+
root.mkdir()
|
|
111
|
+
scratch.mkdir()
|
|
112
|
+
now = datetime.now(UTC)
|
|
113
|
+
_machine(local, roaming, now)
|
|
114
|
+
srcs = sources.discover(local, roaming)
|
|
115
|
+
before = {s.key: _digest(s.path) for s in srcs}
|
|
116
|
+
# the owner's default mode (private pages only); adult kept private, not skipped, so
|
|
117
|
+
# the check can see where it went
|
|
118
|
+
settings = replace(privacy.Settings(adult="private"), visible_to_claude=False)
|
|
119
|
+
vault = Vault(root)
|
|
120
|
+
tempfile.tempdir = str(scratch) # the History copies land here, so we can see them go
|
|
121
|
+
try:
|
|
122
|
+
check("finds Chrome, Comet and Firefox history",
|
|
123
|
+
lambda: [s.browser for s in srcs] == ["chrome", "comet", "firefox"])
|
|
124
|
+
scan = sources.scan(srcs, settings)
|
|
125
|
+
check("scan reads every source (counts only)",
|
|
126
|
+
lambda: all("error" not in r for r in scan)
|
|
127
|
+
and sum(r["visits"] for r in scan) == 10)
|
|
128
|
+
check("scan: the privacy filter would drop the sign-in, bank and secret rows",
|
|
129
|
+
lambda: sum(r["dropped"] for r in scan) == 3)
|
|
130
|
+
first = build.run(vault, srcs, settings, now=now)
|
|
131
|
+
check("import reads every source", lambda: first.get("sources") == 3
|
|
132
|
+
and not first.get("sources_failed"))
|
|
133
|
+
pages = {k: v for k, v in _files(root).items() if k.startswith("browse/")}
|
|
134
|
+
check("pages written only under browse/private",
|
|
135
|
+
lambda: pages and all(k.startswith(PRIVATE_BROWSE_DIR + "/") for k in pages))
|
|
136
|
+
every = b"".join(_files(root).values())
|
|
137
|
+
check("sign-in, bank and secret rows are nowhere in the vault",
|
|
138
|
+
lambda: not any(m.encode() in every for m in DROPPED))
|
|
139
|
+
check("sensitive rows (health, adult) are on private pages only",
|
|
140
|
+
lambda: all(m.encode() in b"".join(pages.values()) for m in SENSITIVE)
|
|
141
|
+
and all(privacy.filter_record(u, t, settings=settings).private for u, t in (
|
|
142
|
+
("https://health.example.org/flu", "Flu symptoms"),
|
|
143
|
+
("https://www.pornhub.com/x", "video")))
|
|
144
|
+
and all(b"private: true" in v for k, v in pages.items()
|
|
145
|
+
if k.endswith(".md")))
|
|
146
|
+
snap = _files(root / "browse")
|
|
147
|
+
since = min((r["first"] for r in scan if r.get("first")), default=None)
|
|
148
|
+
again = build.run(vault, srcs, settings, now=now, since=since)
|
|
149
|
+
check("a second import (full rebuild) gives the same pages",
|
|
150
|
+
lambda: _files(root / "browse") == snap and again.get("days_from"))
|
|
151
|
+
whole = _files(root)
|
|
152
|
+
dry = build.run(vault, srcs, settings, now=now, since=since, dry_run=True)
|
|
153
|
+
check("--dry-run writes nothing",
|
|
154
|
+
lambda: _files(root) == whole and dry.get("private_would") == 2)
|
|
155
|
+
check("temp copies of the history files are deleted",
|
|
156
|
+
lambda: not any(scratch.iterdir()))
|
|
157
|
+
check("the browser history files are unchanged",
|
|
158
|
+
lambda: {s.key: _digest(s.path) for s in srcs} == before)
|
|
159
|
+
except Exception as e: # a step outside a check crashed: say so, never a traceback
|
|
160
|
+
check(f"selftest stopped early ({type(e).__name__})", lambda: False)
|
|
161
|
+
finally:
|
|
162
|
+
tempfile.tempdir = old_tmp
|
|
163
|
+
bad = sum(not ok for _, ok in results)
|
|
164
|
+
echo(f"PASS: all {len(results)} checks passed" if not bad
|
|
165
|
+
else f"FAIL: {bad} of {len(results)} checks failed")
|
|
166
|
+
return not bad
|