tokensafe 4.5.0 → 4.5.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.
Files changed (62) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/bin/agy-tokens +10 -1
  3. package/bin/tokensafe.js +2 -1
  4. package/hooks/claude_code_hook.py +38 -126
  5. package/hooks/cursor_hook.py +45 -1
  6. package/hooks/kimi_hook.py +46 -90
  7. package/hooks/pre_invocation.py +23 -4
  8. package/hooks/pre_tool_use.py +40 -22
  9. package/hooks/session_start.py +28 -10
  10. package/hooks/zcode_hook.py +95 -0
  11. package/hooks.json +1 -1
  12. package/kimi.plugin.json +17 -1
  13. package/mcp_config.json +10 -4
  14. package/package.json +1 -1
  15. package/plugin.json +1 -1
  16. package/rules/AGENTS.md +24 -24
  17. package/server.json +3 -3
  18. package/skills/token-optimizer/SKILL.md +61 -86
  19. package/skills/token-optimizer/references/mcp-tools.md +32 -132
  20. package/src/adapter_core.py +231 -7
  21. package/src/batch_editor.py +73 -22
  22. package/src/batch_search.py +31 -11
  23. package/src/burn_monitor.py +581 -0
  24. package/src/cache_normalizer.py +2 -0
  25. package/src/cli.py +34 -4
  26. package/src/compactor.py +1 -1
  27. package/src/dashboard.py +17 -9
  28. package/src/diff_slicer.py +1 -1
  29. package/src/distiller.py +11 -1
  30. package/src/environment_auditor.py +30 -6
  31. package/src/format_parsers/ansi.py +1 -1
  32. package/src/format_parsers/lockfiles.py +22 -17
  33. package/src/format_parsers/tabular.py +6 -3
  34. package/src/fts_index.py +26 -20
  35. package/src/governor.py +2 -2
  36. package/src/graph_engine.py +31 -9
  37. package/src/guard.py +3 -3
  38. package/src/image_downscale.py +26 -0
  39. package/src/installer.py +61 -48
  40. package/src/license_manager.py +49 -16
  41. package/src/live_relay.py +9 -8
  42. package/src/mcp_server.py +487 -48
  43. package/src/metrics.py +10 -1
  44. package/src/mistakes.py +4 -2
  45. package/src/paths.py +4 -1
  46. package/src/proxy.py +302 -123
  47. package/src/result_ledger.py +39 -1
  48. package/src/schema_slicer.py +40 -18
  49. package/src/scoped_search.py +66 -23
  50. package/src/skeletonizer.py +22 -11
  51. package/src/slicer.py +6 -4
  52. package/src/stash.py +37 -7
  53. package/src/superseded.py +42 -23
  54. package/src/syntax_guard.py +2 -0
  55. package/src/team_cache.py +3 -0
  56. package/src/telemetry_sync.py +66 -53
  57. package/src/thinking_fold.py +50 -12
  58. package/src/transcript_analyzer.py +270 -68
  59. package/src/treesitter_backend.py +2 -0
  60. package/src/type_slicer.py +60 -18
  61. package/src/version_checker.py +1 -1
  62. package/src/web_reader.py +55 -22
package/src/web_reader.py CHANGED
@@ -10,6 +10,7 @@ Fetches web pages (documentation, API references, articles) and strips clutter:
10
10
 
11
11
  import os
12
12
  import re
13
+ import socket
13
14
  import ipaddress
14
15
  import urllib.request
15
16
  import urllib.parse
@@ -37,9 +38,14 @@ class _HTMLToMarkdownParser(HTMLParser):
37
38
  BLOCK_TAGS = {"p", "div", "section", "article", "blockquote", "tr"}
38
39
  HEADING_TAGS = {"h1": 1, "h2": 2, "h3": 3, "h4": 4, "h5": 5, "h6": 6}
39
40
 
41
+ VOID_TAGS = {
42
+ "area", "base", "br", "col", "embed", "hr", "img", "input",
43
+ "link", "meta", "param", "source", "track", "wbr"
44
+ }
45
+
40
46
  def __init__(self):
41
47
  super().__init__()
42
- self._ignore_depth = 0
48
+ self._ignore_stack: List[str] = []
43
49
  self._pieces: List[str] = []
44
50
  self._in_pre = False
45
51
  self._in_code = False
@@ -48,10 +54,13 @@ class _HTMLToMarkdownParser(HTMLParser):
48
54
 
49
55
  def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]):
50
56
  tag_lower = tag.lower()
51
- if tag_lower in self.IGNORE_TAGS:
52
- self._ignore_depth += 1
57
+ if self._ignore_stack:
58
+ if tag_lower not in self.VOID_TAGS:
59
+ self._ignore_stack.append(tag_lower)
53
60
  return
54
- if self._ignore_depth > 0:
61
+ if tag_lower in self.IGNORE_TAGS:
62
+ if tag_lower not in self.VOID_TAGS:
63
+ self._ignore_stack.append(tag_lower)
55
64
  return
56
65
 
57
66
  attr_dict = {k.lower(): (v or "") for k, v in attrs}
@@ -59,7 +68,8 @@ class _HTMLToMarkdownParser(HTMLParser):
59
68
  # Filter out common ad/nav/cookie banner classes/ids
60
69
  cls_and_id = (attr_dict.get("class", "") + " " + attr_dict.get("id", "")).lower()
61
70
  if any(w in cls_and_id for w in ("cookie", "banner", "advertisement", "sidebar", "nav-menu")):
62
- self._ignore_depth += 1
71
+ if tag_lower not in self.VOID_TAGS:
72
+ self._ignore_stack.append(tag_lower)
63
73
  return
64
74
 
65
75
  if tag_lower in self.HEADING_TAGS:
@@ -88,10 +98,12 @@ class _HTMLToMarkdownParser(HTMLParser):
88
98
 
89
99
  def handle_endtag(self, tag: str):
90
100
  tag_lower = tag.lower()
91
- if tag_lower in self.IGNORE_TAGS:
92
- self._ignore_depth = max(0, self._ignore_depth - 1)
93
- return
94
- if self._ignore_depth > 0:
101
+ if self._ignore_stack:
102
+ if tag_lower in self._ignore_stack:
103
+ while self._ignore_stack:
104
+ popped = self._ignore_stack.pop()
105
+ if popped == tag_lower:
106
+ break
95
107
  return
96
108
 
97
109
  if tag_lower in self.HEADING_TAGS:
@@ -114,7 +126,7 @@ class _HTMLToMarkdownParser(HTMLParser):
114
126
  self._link_text = []
115
127
 
116
128
  def handle_data(self, data: str):
117
- if self._ignore_depth > 0:
129
+ if self._ignore_stack:
118
130
  return
119
131
  if self._current_link is not None:
120
132
  self._link_text.append(data)
@@ -265,6 +277,9 @@ class WebReader:
265
277
  Queries L1 memory, L2 SQLite, and L3 Team Cache in sequence.
266
278
  Returns (content, tier) where tier in ("L1", "L2", "L3") or (None, "miss").
267
279
  """
280
+ if cls.has_auth_or_userinfo(url, custom_headers=custom_headers):
281
+ cls.last_tier = "live"
282
+ return None, "miss"
268
283
  clean_url = cls.sanitize_url(url)
269
284
  url_hash = hashlib.sha256(clean_url.encode("utf-8")).hexdigest()
270
285
 
@@ -321,6 +336,8 @@ class WebReader:
321
336
  """Stores clean Markdown into L1, L2 SQLite, and asynchronously broadcasts to L3 Team Cache."""
322
337
  if not url or not markdown:
323
338
  return
339
+ if cls.has_auth_or_userinfo(url, custom_headers=custom_headers):
340
+ return
324
341
  clean_url = cls.sanitize_url(url)
325
342
  url_hash = hashlib.sha256(clean_url.encode("utf-8")).hexdigest()
326
343
  now = int(time.time())
@@ -362,29 +379,45 @@ class WebReader:
362
379
  except Exception:
363
380
  pass
364
381
 
382
+ @staticmethod
383
+ def _is_public_ip(ip: ipaddress._BaseAddress) -> bool:
384
+ return not (
385
+ ip.is_private
386
+ or ip.is_loopback
387
+ or ip.is_link_local
388
+ or ip.is_reserved
389
+ or ip.is_unspecified
390
+ or ip.is_multicast
391
+ )
392
+
365
393
  @classmethod
366
394
  def is_safe_url(cls, url: str) -> bool:
367
395
  try:
368
396
  parsed = urllib.parse.urlparse(url)
369
397
  if parsed.scheme not in ("http", "https"):
370
398
  return False
371
- host = (parsed.hostname or "").lower().rstrip(".")
372
- if host in cls._BLOCKED_HOSTS or host.endswith(".local"):
399
+ raw_host = (parsed.hostname or "").lower().rstrip(".")
400
+ if not raw_host or "%" in raw_host:
401
+ return False
402
+ if raw_host in cls._BLOCKED_HOSTS or raw_host.endswith(".local"):
373
403
  return False
374
404
  # Literal IPs (v4/v6) — exact range checks instead of string prefixes
375
405
  try:
376
- ip = ipaddress.ip_address(host)
377
- if (
378
- ip.is_private
379
- or ip.is_loopback
380
- or ip.is_link_local
381
- or ip.is_reserved
382
- or ip.is_unspecified
383
- or ip.is_multicast
384
- ):
385
- return False
406
+ ip = ipaddress.ip_address(raw_host)
407
+ return cls._is_public_ip(ip)
386
408
  except ValueError:
387
409
  pass # hostname, not a literal IP
410
+ # DNS SSRF protection: reject hostnames resolving to internal/private IPs
411
+ try:
412
+ infos = socket.getaddrinfo(raw_host, None, type=socket.SOCK_STREAM)
413
+ for info in infos:
414
+ sockaddr = info[4]
415
+ addr = str(sockaddr[0]).split("%", 1)[0]
416
+ ip = ipaddress.ip_address(addr)
417
+ if not cls._is_public_ip(ip):
418
+ return False
419
+ except socket.gaierror:
420
+ pass # Allow offline mocked unit tests where DNS isn't reachable
388
421
  return True
389
422
  except Exception:
390
423
  return False