tokensafe 4.3.3 → 4.4.1

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.
package/src/web_reader.py CHANGED
@@ -8,15 +8,22 @@ Fetches web pages (documentation, API references, articles) and strips clutter:
8
8
  - Stashes full raw HTML in TokenSafe reversible stash if content is large.
9
9
  """
10
10
 
11
+ import os
11
12
  import re
12
13
  import ipaddress
13
14
  import urllib.request
14
15
  import urllib.parse
15
16
  import urllib.error
17
+ import sqlite3
18
+ import time
19
+ import hashlib
20
+ import threading
21
+ from collections import OrderedDict
16
22
  from html.parser import HTMLParser
17
23
  from typing import Tuple, Optional, Dict, Any, List
18
24
 
19
25
  from src.stash import stash_block
26
+ from src.paths import resolve_data_dir
20
27
 
21
28
 
22
29
  class _HTMLToMarkdownParser(HTMLParser):
@@ -137,9 +144,223 @@ class _SafeRedirectHandler(urllib.request.HTTPRedirectHandler):
137
144
 
138
145
 
139
146
  class WebReader:
140
- """Safely fetches web pages and returns clean Markdown."""
147
+ """Safely fetches web pages and returns clean Markdown with Local First (L1/L2) + Team Sync (L3) caching."""
141
148
 
142
149
  _BLOCKED_HOSTS = {"localhost", "127.0.0.1", "0.0.0.0", "::1", "169.254.169.254"}
150
+ _SENSITIVE_QUERY_PARAMS = {
151
+ "token", "auth", "key", "signature", "sig", "secret", "credential",
152
+ "session", "access_token", "api_key", "x-amz-signature", "x-amz-credential"
153
+ }
154
+
155
+ _TTL_SECONDS = 72 * 3600 # 72 hours
156
+ _MAX_DB_BYTES = 50 * 1024 * 1024 # 50 MB
157
+ _mem_cache: "OrderedDict[str, str]" = OrderedDict()
158
+ _mem_lock = threading.Lock()
159
+ _db_init_done = False
160
+ _db_init_lock = threading.Lock()
161
+ last_tier: str = "live"
162
+
163
+ @classmethod
164
+ def sanitize_url(cls, url: str) -> str:
165
+ """Strips userinfo (user:pass@) and sensitive authentication & signature tokens from query strings for clean canonical caching."""
166
+ try:
167
+ parsed = urllib.parse.urlparse(url.strip())
168
+ netloc = parsed.netloc
169
+ if "@" in netloc:
170
+ _, _, netloc = netloc.rpartition("@")
171
+ clean_netloc = netloc.lower()
172
+
173
+ qs = urllib.parse.parse_qsl(parsed.query, keep_blank_values=True)
174
+ cleaned_qs = [
175
+ (k, v) for k, v in qs
176
+ if k.lower() not in cls._SENSITIVE_QUERY_PARAMS and not k.lower().startswith("x-amz-")
177
+ ]
178
+ cleaned_qs.sort(key=lambda x: x[0])
179
+ new_query = urllib.parse.urlencode(cleaned_qs)
180
+ return urllib.parse.urlunparse((
181
+ parsed.scheme.lower(),
182
+ clean_netloc,
183
+ parsed.path,
184
+ parsed.params,
185
+ new_query,
186
+ "" # drop fragments
187
+ ))
188
+ except Exception:
189
+ return url.strip()
190
+
191
+ @classmethod
192
+ def has_auth_or_userinfo(cls, url: str, custom_headers: Optional[Dict[str, str]] = None) -> bool:
193
+ """Checks whether the request carries credentials, auth headers, or userinfo in URL."""
194
+ if custom_headers and any(
195
+ k.lower() in ("authorization", "cookie", "x-api-key")
196
+ for k in custom_headers
197
+ ):
198
+ return True
199
+ try:
200
+ parsed = urllib.parse.urlparse(url.strip())
201
+ if parsed.username or parsed.password or "@" in parsed.netloc:
202
+ return True
203
+ except Exception:
204
+ pass
205
+ return False
206
+
207
+ @classmethod
208
+ def _get_db_path(cls) -> str:
209
+ data_dir = resolve_data_dir()
210
+ os.makedirs(data_dir, exist_ok=True)
211
+ return os.path.join(data_dir, "web_cache.db")
212
+
213
+ @classmethod
214
+ def _init_db(cls):
215
+ db_path = cls._get_db_path()
216
+ with cls._db_init_lock:
217
+ if cls._db_init_done == db_path and os.path.exists(db_path):
218
+ return
219
+ try:
220
+ with sqlite3.connect(db_path, timeout=5.0) as conn:
221
+ conn.execute("PRAGMA journal_mode=WAL;")
222
+ conn.execute("PRAGMA busy_timeout=5000;")
223
+ conn.execute("""
224
+ CREATE TABLE IF NOT EXISTS web_cache (
225
+ url_hash TEXT PRIMARY KEY,
226
+ canonical_url TEXT NOT NULL,
227
+ markdown TEXT NOT NULL,
228
+ fetched_at INTEGER NOT NULL,
229
+ size_bytes INTEGER NOT NULL,
230
+ hit_count INTEGER DEFAULT 1
231
+ );
232
+ """)
233
+ conn.execute("CREATE INDEX IF NOT EXISTS idx_web_cache_fetched ON web_cache(fetched_at);")
234
+ conn.commit()
235
+ cls._db_init_done = db_path
236
+ except Exception:
237
+ pass
238
+
239
+ @classmethod
240
+ def clear_memory_cache(cls):
241
+ with cls._mem_lock:
242
+ cls._mem_cache.clear()
243
+
244
+ @classmethod
245
+ def _maybe_evict_l2(cls, conn: sqlite3.Connection):
246
+ """Maintains 50MB hard storage bound using LRU eviction."""
247
+ try:
248
+ db_path = cls._get_db_path()
249
+ if os.path.exists(db_path) and os.path.getsize(db_path) > cls._MAX_DB_BYTES:
250
+ conn.execute("""
251
+ DELETE FROM web_cache WHERE url_hash IN (
252
+ SELECT url_hash FROM web_cache ORDER BY fetched_at ASC LIMIT 100
253
+ );
254
+ """)
255
+ except Exception:
256
+ pass
257
+
258
+ @classmethod
259
+ def get_cached(
260
+ cls,
261
+ url: str,
262
+ custom_headers: Optional[Dict[str, str]] = None
263
+ ) -> Tuple[Optional[str], str]:
264
+ """
265
+ Queries L1 memory, L2 SQLite, and L3 Team Cache in sequence.
266
+ Returns (content, tier) where tier in ("L1", "L2", "L3") or (None, "miss").
267
+ """
268
+ clean_url = cls.sanitize_url(url)
269
+ url_hash = hashlib.sha256(clean_url.encode("utf-8")).hexdigest()
270
+
271
+ # 1. Check L1 Memory
272
+ with cls._mem_lock:
273
+ if url_hash in cls._mem_cache:
274
+ cls._mem_cache.move_to_end(url_hash)
275
+ cls.last_tier = "L1"
276
+ return cls._mem_cache[url_hash], "L1"
277
+
278
+ # 2. Check L2 SQLite
279
+ cls._init_db()
280
+ db_path = cls._get_db_path()
281
+ now = int(time.time())
282
+ try:
283
+ with sqlite3.connect(db_path, timeout=5.0) as conn:
284
+ conn.execute("PRAGMA busy_timeout=5000;")
285
+ row = conn.execute(
286
+ "SELECT markdown, fetched_at FROM web_cache WHERE url_hash = ?",
287
+ (url_hash,)
288
+ ).fetchone()
289
+ if row:
290
+ md, fetched_at = row[0], int(row[1])
291
+ if now - fetched_at < cls._TTL_SECONDS:
292
+ conn.execute("UPDATE web_cache SET hit_count = hit_count + 1 WHERE url_hash = ?", (url_hash,))
293
+ conn.commit()
294
+ with cls._mem_lock:
295
+ cls._mem_cache[url_hash] = md
296
+ if len(cls._mem_cache) > 50:
297
+ cls._mem_cache.popitem(last=False)
298
+ cls.last_tier = "L2"
299
+ return md, "L2"
300
+ except Exception:
301
+ pass
302
+
303
+ # 3. Check L3 Team Sync (Only if request carried no custom auth/cookie headers or userinfo)
304
+ has_auth = cls.has_auth_or_userinfo(url, custom_headers=custom_headers)
305
+ if not has_auth:
306
+ try:
307
+ from src.team_cache import TeamCache
308
+ team_val = TeamCache.get("WEB_DOCS", clean_url, timeout=0.6)
309
+ if team_val:
310
+ cls.set_cached(url, team_val, sync_team=False)
311
+ cls.last_tier = "L3"
312
+ return team_val, "L3"
313
+ except Exception:
314
+ pass
315
+
316
+ cls.last_tier = "live"
317
+ return None, "miss"
318
+
319
+ @classmethod
320
+ def set_cached(cls, url: str, markdown: str, sync_team: bool = True, custom_headers: Optional[Dict[str, str]] = None) -> None:
321
+ """Stores clean Markdown into L1, L2 SQLite, and asynchronously broadcasts to L3 Team Cache."""
322
+ if not url or not markdown:
323
+ return
324
+ clean_url = cls.sanitize_url(url)
325
+ url_hash = hashlib.sha256(clean_url.encode("utf-8")).hexdigest()
326
+ now = int(time.time())
327
+ size_bytes = len(markdown.encode("utf-8"))
328
+
329
+ # 1. Save L1
330
+ with cls._mem_lock:
331
+ cls._mem_cache[url_hash] = markdown
332
+ cls._mem_cache.move_to_end(url_hash)
333
+ if len(cls._mem_cache) > 50:
334
+ cls._mem_cache.popitem(last=False)
335
+
336
+ # 2. Save L2 SQLite
337
+ cls._init_db()
338
+ db_path = cls._get_db_path()
339
+ try:
340
+ with sqlite3.connect(db_path, timeout=5.0) as conn:
341
+ conn.execute("PRAGMA busy_timeout=5000;")
342
+ conn.execute("""
343
+ INSERT INTO web_cache (url_hash, canonical_url, markdown, fetched_at, size_bytes, hit_count)
344
+ VALUES (?, ?, ?, ?, ?, 1)
345
+ ON CONFLICT(url_hash) DO UPDATE SET
346
+ markdown = excluded.markdown,
347
+ fetched_at = excluded.fetched_at,
348
+ size_bytes = excluded.size_bytes;
349
+ """, (url_hash, clean_url, markdown, now, size_bytes))
350
+ cls._maybe_evict_l2(conn)
351
+ conn.commit()
352
+ except Exception:
353
+ pass
354
+
355
+ # 3. Broadcast to L3 Team Sync
356
+ has_auth = cls.has_auth_or_userinfo(url, custom_headers=custom_headers)
357
+ if sync_team and not has_auth:
358
+ try:
359
+ from src.team_cache import TeamCache
360
+ est_saved = max(50, len(markdown) // 4)
361
+ TeamCache.put("WEB_DOCS", clean_url, markdown, tokens_saved=est_saved)
362
+ except Exception:
363
+ pass
143
364
 
144
365
  @classmethod
145
366
  def is_safe_url(cls, url: str) -> bool:
@@ -151,7 +372,6 @@ class WebReader:
151
372
  if host in cls._BLOCKED_HOSTS or host.endswith(".local"):
152
373
  return False
153
374
  # Literal IPs (v4/v6) — exact range checks instead of string prefixes
154
- # (the old prefix check missed 172.17-172.31 and all of IPv6).
155
375
  try:
156
376
  ip = ipaddress.ip_address(host)
157
377
  if (
@@ -190,21 +410,36 @@ class WebReader:
190
410
  return md, False
191
411
 
192
412
  @classmethod
193
- def fetch_url(cls, url: str, timeout: float = 8.0) -> Tuple[str, bool, Optional[str]]:
413
+ def fetch_url(
414
+ cls,
415
+ url: str,
416
+ timeout: float = 8.0,
417
+ force_refresh: bool = False,
418
+ custom_headers: Optional[Dict[str, str]] = None
419
+ ) -> Tuple[str, bool, Optional[str]]:
194
420
  """
195
- Fetches URL, converts to clean Markdown.
421
+ Fetches URL or returns cached Markdown from L1/L2/L3.
196
422
  Returns (content_or_error, is_success, opt_error_msg).
423
+ Sets cls.last_tier to "L1", "L2", "L3", or "live".
197
424
  """
198
425
  if not cls.is_safe_url(url):
199
426
  return "", False, f"Refused to fetch potentially unsafe or internal URL: {url}"
200
427
 
201
- req = urllib.request.Request(
202
- url,
203
- headers={
204
- "User-Agent": "Mozilla/5.0 (compatible; TokenSafeBot/3.3; +https://tokensafe.dev)",
205
- "Accept": "text/html,application/xhtml+xml,text/plain;q=0.9",
206
- }
207
- )
428
+ # Check Local First & Team Sync caches unless force_refresh
429
+ if not force_refresh:
430
+ cached_val, tier = cls.get_cached(url, custom_headers=custom_headers)
431
+ if cached_val:
432
+ cls.last_tier = tier
433
+ return cached_val, True, None
434
+
435
+ headers = {
436
+ "User-Agent": "Mozilla/5.0 (compatible; TokenSafeBot/3.3; +https://tokensafe.dev)",
437
+ "Accept": "text/html,application/xhtml+xml,text/plain;q=0.9",
438
+ }
439
+ if custom_headers:
440
+ headers.update(custom_headers)
441
+
442
+ req = urllib.request.Request(url, headers=headers)
208
443
 
209
444
  try:
210
445
  _opener = urllib.request.build_opener(_SafeRedirectHandler)
@@ -222,8 +457,15 @@ class WebReader:
222
457
 
223
458
  if "text/html" in content_type or "<html" in raw_text.lower():
224
459
  md, _ = cls.html_to_markdown(raw_text, url=url)
225
- return md, True, None
226
460
  else:
227
- return raw_text, True, None
461
+ md = raw_text
462
+
463
+ cls.last_tier = "live"
464
+ cls.set_cached(url, md, sync_team=True, custom_headers=custom_headers)
465
+ return md, True, None
228
466
  except Exception as e:
467
+ cls.last_tier = "error"
229
468
  return "", False, f"Fetch error: {e}"
469
+
470
+
471
+ sanitize_url = WebReader.sanitize_url