tokensafe 4.6.2 → 4.6.4
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/.codex-plugin/plugin.json +1 -1
- package/README.md +38 -5
- package/hooks/claude_code_hook.py +22 -0
- package/hooks/kimi_hook.py +20 -0
- package/hooks/pre_tool_use.py +0 -9
- package/hooks/session_start.py +16 -4
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/adapter_core.py +57 -21
- package/src/auto_inject.py +517 -0
- package/src/batch_editor.py +36 -2
- package/src/batch_search.py +31 -5
- package/src/cli.py +152 -10
- package/src/command_sanitizer.py +92 -6
- package/src/guard.py +75 -11
- package/src/installer.py +6 -0
- package/src/mcp_server.py +84 -25
- package/src/oumv_gateway.py +168 -19
- package/src/paths.py +58 -0
- package/src/retrofit.py +219 -45
- package/src/savings.py +81 -0
- package/src/scaffold.py +190 -8
- package/src/session_brief.py +154 -0
- package/src/snapshot.py +3 -2
- package/src/telemetry_sync.py +98 -26
- package/src/transcript_analyzer.py +13 -9
- package/src/version_checker.py +1 -1
- package/hooks/__pycache__/claude_code_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/cursor_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/kimi_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/pre_invocation.cpython-312.pyc +0 -0
- package/hooks/__pycache__/pre_tool_use.cpython-312.pyc +0 -0
- package/hooks/__pycache__/session_start.cpython-312.pyc +0 -0
- package/hooks/__pycache__/stop_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/zcode_hook.cpython-312.pyc +0 -0
package/src/batch_search.py
CHANGED
|
@@ -137,7 +137,13 @@ def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5, max_results: in
|
|
|
137
137
|
raw_out = strip_ansi(proc.stdout or "").strip()
|
|
138
138
|
lines = [l for l in raw_out.splitlines() if l.strip()]
|
|
139
139
|
limited = lines[:max_results]
|
|
140
|
-
return {
|
|
140
|
+
return {
|
|
141
|
+
"matches": limited,
|
|
142
|
+
# count is the true number of matching lines; matches may be truncated.
|
|
143
|
+
"count": len(lines),
|
|
144
|
+
"truncated": len(lines) > len(limited),
|
|
145
|
+
"raw": "\n".join(limited),
|
|
146
|
+
}
|
|
141
147
|
except subprocess.TimeoutExpired:
|
|
142
148
|
return {"error": f"git query timed out after {timeout_sec}s", "matches": [], "count": 0}
|
|
143
149
|
except Exception as e:
|
|
@@ -152,7 +158,8 @@ def _run_rg_query(
|
|
|
152
158
|
case_sensitive: bool = False,
|
|
153
159
|
file_type: Optional[str] = None,
|
|
154
160
|
glob_filter: Optional[str] = None,
|
|
155
|
-
max_results: int = 25
|
|
161
|
+
max_results: int = 25,
|
|
162
|
+
scope: str = "all"
|
|
156
163
|
) -> Optional[List[Dict[str, Any]]]:
|
|
157
164
|
"""Attempts fast search via ripgrep if available."""
|
|
158
165
|
rg_bin = shutil.which("rg")
|
|
@@ -195,6 +202,7 @@ def _run_rg_query(
|
|
|
195
202
|
# rg exits 1 for "no matches" (not an error) and 2 for real failures.
|
|
196
203
|
if proc.returncode not in (0, 1) and err_text:
|
|
197
204
|
raise RuntimeError(f"ripgrep failed: {err_text.splitlines()[0]}")
|
|
205
|
+
scope_all = str(scope or "all").lower() in ("", "all")
|
|
198
206
|
matches = []
|
|
199
207
|
_rg_line_re = re.compile(r"^(.*):(\d+):(.*)$")
|
|
200
208
|
for line in proc.stdout.splitlines():
|
|
@@ -204,6 +212,15 @@ def _run_rg_query(
|
|
|
204
212
|
if m_line:
|
|
205
213
|
raw_file, raw_lnum, raw_txt = m_line.groups()
|
|
206
214
|
f_path = os.path.relpath(raw_file, cwd)
|
|
215
|
+
# ripgrep has no notion of TokenSafe scopes: apply the same matcher
|
|
216
|
+
# the Python fallback uses so results do not change with rg presence.
|
|
217
|
+
if not scope_all:
|
|
218
|
+
try:
|
|
219
|
+
from src.scoped_search import ScopedSearch
|
|
220
|
+
if not ScopedSearch.is_match_file(f_path, f_path, str(scope).lower()):
|
|
221
|
+
continue
|
|
222
|
+
except Exception:
|
|
223
|
+
pass
|
|
207
224
|
try:
|
|
208
225
|
l_num = int(raw_lnum)
|
|
209
226
|
except ValueError:
|
|
@@ -304,8 +321,16 @@ def _run_python_text_search(
|
|
|
304
321
|
ext = os.path.splitext(full_path)[1].lower()
|
|
305
322
|
if ext in IGNORED_EXTENSIONS:
|
|
306
323
|
continue
|
|
307
|
-
|
|
308
|
-
|
|
324
|
+
# One matcher for every scope ("code", "config", extensions, globs):
|
|
325
|
+
# reusing ScopedSearch keeps the fallback identical to the rg path.
|
|
326
|
+
if str(scope or "all").lower() not in ("", "all"):
|
|
327
|
+
try:
|
|
328
|
+
from src.scoped_search import ScopedSearch
|
|
329
|
+
if not ScopedSearch.is_match_file(full_path, rel_p, str(scope).lower()):
|
|
330
|
+
continue
|
|
331
|
+
except Exception:
|
|
332
|
+
if scope == "code" and ext not in CODE_EXTENSIONS:
|
|
333
|
+
continue
|
|
309
334
|
if type_exts is not None and ext not in type_exts:
|
|
310
335
|
continue
|
|
311
336
|
if glob_filter and not (fnmatch.fnmatch(os.path.basename(full_path), glob_filter) or fnmatch.fnmatch(rel_p, glob_filter)):
|
|
@@ -431,7 +456,8 @@ def _execute_single_query(query_dict: Dict[str, Any], cwd: str) -> Dict[str, Any
|
|
|
431
456
|
case_sensitive=case_sensitive,
|
|
432
457
|
file_type=file_type,
|
|
433
458
|
glob_filter=glob_filter,
|
|
434
|
-
max_results=max_res
|
|
459
|
+
max_results=max_res,
|
|
460
|
+
scope=scope
|
|
435
461
|
)
|
|
436
462
|
|
|
437
463
|
try:
|
package/src/cli.py
CHANGED
|
@@ -9,6 +9,7 @@ Used by:
|
|
|
9
9
|
|
|
10
10
|
import sys
|
|
11
11
|
import os
|
|
12
|
+
import shutil
|
|
12
13
|
import subprocess
|
|
13
14
|
from typing import Optional, List, Dict, Any
|
|
14
15
|
|
|
@@ -97,13 +98,15 @@ def summarize_unittest_output(raw: str, full_traceback: bool = False) -> str:
|
|
|
97
98
|
def _print_help():
|
|
98
99
|
print("TokenSafe CLI — usage: tokensafe <command> [args]\n")
|
|
99
100
|
print("Commands:")
|
|
100
|
-
print(" dev [dir] [--port
|
|
101
|
+
print(" dev [dir] [--port N] [--host H] [--open] Start Vite+React DevServer with OUMV (zero repo footprint)")
|
|
101
102
|
print(" integrate [--dry-run] Retrofit OUMV into existing project (React, Vue, FastAPI, Go)")
|
|
103
|
+
print(" inject [status|apply|revert] Auto-wire adapters with zero repo footprint (add --dry-run)")
|
|
102
104
|
print(" adapters [list] Catalog of frontend/backend OUMV runtime adapters")
|
|
103
105
|
print(" oumv doctor / status Diagnose OUMV configuration, ports, and permissions")
|
|
104
106
|
print(" create <name> [--template ...] Greenfield project scaffolder (tokensafe-ui + tokensafe-backend)")
|
|
105
107
|
print(" init [--template ...] Initialize TokenSafe stack in current directory")
|
|
106
108
|
print(" stats / markdown / html Savings analytics (terminal / .md report / dashboard)")
|
|
109
|
+
print(" savings [--json] Canonical totals + last event (cite these numbers, never guess)")
|
|
107
110
|
print(" status One-screen health check: hooks, weekly savings, tier, sync")
|
|
108
111
|
print(" budget [--transcript=...] Context Window Budget HUD & Context Quality Score (Grade S-F)")
|
|
109
112
|
print(" compact <transcript.jsonl> Fold conversation transcript into Consolidated State Ledger")
|
|
@@ -335,6 +338,27 @@ def main(argv: Optional[List[str]] = None):
|
|
|
335
338
|
print(ledger)
|
|
336
339
|
print()
|
|
337
340
|
|
|
341
|
+
elif command in ("savings", "saved"):
|
|
342
|
+
# Canonical, machine-readable savings numbers. Agents must cite this
|
|
343
|
+
# command instead of guessing (see the footer rule in AGENTS.md).
|
|
344
|
+
from src.savings import build_savings_report
|
|
345
|
+
|
|
346
|
+
report = build_savings_report()
|
|
347
|
+
if "--json" in args:
|
|
348
|
+
import json as _json
|
|
349
|
+
print(_json.dumps(report, indent=2, ensure_ascii=False))
|
|
350
|
+
else:
|
|
351
|
+
last = report.get("last_event") or {}
|
|
352
|
+
print("\n\033[1m\033[36m⚡ TOKENSAFE SAVINGS (canonical) ⚡\033[0m\n")
|
|
353
|
+
print(f" Data dir: {report['data_dir']}")
|
|
354
|
+
print(f" Events / sessions: {report['total_events']} / {report['sessions']}")
|
|
355
|
+
print(f" Saved (live): {report['saved_tokens_live']:,} tokens")
|
|
356
|
+
print(f" Saved (pruned+sync): {report['pruned_synced_saved_tokens']:,} tokens")
|
|
357
|
+
print(f" Cumulative: {report['cumulative_saved_tokens']:,} tokens (≈${report['usd_saved_approx']:.2f})")
|
|
358
|
+
if last:
|
|
359
|
+
print(f" Last event: {last.get('event_type')} — {last.get('saved_tokens'):,} tokens at {last.get('timestamp')}")
|
|
360
|
+
print()
|
|
361
|
+
|
|
338
362
|
elif command in ("stats", "dashboard"):
|
|
339
363
|
tracker = MetricsTracker()
|
|
340
364
|
dashboard = Dashboard(tracker)
|
|
@@ -573,6 +597,16 @@ def main(argv: Optional[List[str]] = None):
|
|
|
573
597
|
template = "fullstack"
|
|
574
598
|
force = False
|
|
575
599
|
|
|
600
|
+
if "--list" in args:
|
|
601
|
+
print("\nAvailable recipes:")
|
|
602
|
+
print(" react-fastapi React 18 + Vite + FastAPI (recommended)")
|
|
603
|
+
print(" react-go React 18 + Vite + Go/Gin")
|
|
604
|
+
print(" vue-gin Vue 3 + Vite + Go/Gin")
|
|
605
|
+
print(" react / vue frontend only (OUMV via `tokensafe dev`)")
|
|
606
|
+
print(" fastapi / gin backend only (auto-mount)")
|
|
607
|
+
print(" backend, ui, fullstack legacy TokenSafe-native templates\n")
|
|
608
|
+
return
|
|
609
|
+
|
|
576
610
|
i = 1
|
|
577
611
|
while i < len(args):
|
|
578
612
|
arg = args[i]
|
|
@@ -581,13 +615,17 @@ def main(argv: Optional[List[str]] = None):
|
|
|
581
615
|
print("Usage:")
|
|
582
616
|
print(" tokensafe create <project-name> [options]\n")
|
|
583
617
|
print("Options:")
|
|
584
|
-
print(" --template <type>
|
|
618
|
+
print(" --template <type> recipe or stack:")
|
|
619
|
+
print(" react-fastapi (recommended), react-go, vue-gin,")
|
|
620
|
+
print(" react, vue, fastapi, gin, backend, ui, fullstack")
|
|
585
621
|
print(" --force, -f Overwrite existing files")
|
|
586
622
|
print(" --help, -h Show this help screen\n")
|
|
587
623
|
print("Examples:")
|
|
588
624
|
print(" tokensafe create my-app")
|
|
589
625
|
print(" tokensafe create my-dashboard --template ui")
|
|
590
|
-
print(" tokensafe create store-api --template
|
|
626
|
+
print(" tokensafe create store-api --template fastapi")
|
|
627
|
+
print(" tokensafe create shop --template react-fastapi")
|
|
628
|
+
print(" tokensafe create edge-api --template gin\n")
|
|
591
629
|
return
|
|
592
630
|
elif arg in ("--template", "-t") and i + 1 < len(args):
|
|
593
631
|
template = args[i + 1]
|
|
@@ -644,7 +682,9 @@ def main(argv: Optional[List[str]] = None):
|
|
|
644
682
|
print("Usage:")
|
|
645
683
|
print(" tokensafe init [options]\n")
|
|
646
684
|
print("Options:")
|
|
647
|
-
print(" --template <type>
|
|
685
|
+
print(" --template <type> recipe or stack:")
|
|
686
|
+
print(" react-fastapi (recommended), react-go, vue-gin,")
|
|
687
|
+
print(" react, vue, fastapi, gin, backend, ui, fullstack")
|
|
648
688
|
print(" --force, -f Overwrite existing files\n")
|
|
649
689
|
return
|
|
650
690
|
elif arg in ("--template", "-t") and i + 1 < len(args):
|
|
@@ -695,13 +735,85 @@ def main(argv: Optional[List[str]] = None):
|
|
|
695
735
|
print(f" \033[33m[DRY-RUN]\033[0m Proposed configuration (.tokensafe/oumv.json):")
|
|
696
736
|
print(json.dumps(cfg, indent=4))
|
|
697
737
|
elif created:
|
|
738
|
+
mutate_enabled = cfg.get("permissions", {}).get("mutate", True)
|
|
739
|
+
policy = (
|
|
740
|
+
"\033[32menabled out-of-the-box (OCC + syntax guard + backups)\033[0m"
|
|
741
|
+
if mutate_enabled
|
|
742
|
+
else "\033[33mread-only (mutate: false)\033[0m"
|
|
743
|
+
)
|
|
698
744
|
print(f" ✔ Generated OUMV config: \033[1m{conf_file}\033[0m")
|
|
699
|
-
print(f" ✔ Mutation policy:
|
|
745
|
+
print(f" ✔ Mutation policy: {policy}")
|
|
700
746
|
print(f" ✔ Profiles enabled: {', '.join(cfg.get('oumv', {}).get('profiles', []))}")
|
|
701
747
|
print("\n Project is now retrofitted for OUMV. AI coding agents can inspect components and endpoints.\n")
|
|
702
748
|
else:
|
|
703
749
|
print(f" ✔ Existing configuration preserved: \033[1m{conf_file}\033[0m (use --force to overwrite)\n")
|
|
704
750
|
|
|
751
|
+
elif command in ("run-backend", "run_backend"):
|
|
752
|
+
# Executes the user's dev-server command with the OUMV autoload hook active.
|
|
753
|
+
# Nothing is written into the repository: the hook lives in ~/.tokensafe.
|
|
754
|
+
from src.auto_inject import backend_env, ensure_python_autoload
|
|
755
|
+
|
|
756
|
+
argv_rest = [a for a in args[1:]]
|
|
757
|
+
if not argv_rest:
|
|
758
|
+
print("usage: tokensafe run-backend <command...> e.g. tokensafe run-backend uvicorn app:app --reload")
|
|
759
|
+
return
|
|
760
|
+
ensure_python_autoload()
|
|
761
|
+
env = backend_env()
|
|
762
|
+
tool = argv_rest[0]
|
|
763
|
+
resolved = shutil.which(tool)
|
|
764
|
+
if not resolved:
|
|
765
|
+
print(f"tokensafe run-backend: `{tool}` not found on PATH")
|
|
766
|
+
return
|
|
767
|
+
os.execvpe(resolved, argv_rest, env)
|
|
768
|
+
|
|
769
|
+
elif command in ("inject", "wire"):
|
|
770
|
+
from src import auto_inject
|
|
771
|
+
|
|
772
|
+
if "--status" in args:
|
|
773
|
+
sub = "status"
|
|
774
|
+
elif "--revert" in args:
|
|
775
|
+
sub = "revert"
|
|
776
|
+
else:
|
|
777
|
+
positional = [a for a in args[1:] if not a.startswith("-")]
|
|
778
|
+
sub = positional[0] if positional and positional[0] in ("status", "apply", "revert") else "apply"
|
|
779
|
+
dry_run = "--dry-run" in args
|
|
780
|
+
workspace = os.getcwd()
|
|
781
|
+
|
|
782
|
+
if sub == "status":
|
|
783
|
+
data = auto_inject.plan(workspace)
|
|
784
|
+
print(f"\n\033[1m\033[36m⚡ TOKENSAFE OUMV INJECT PLAN ⚡\033[0m\n")
|
|
785
|
+
print(f" Profiles: {', '.join(data['profiles']) or 'none detected'}")
|
|
786
|
+
for action in data["actions"]:
|
|
787
|
+
writes = "writes repo" if action["writes_repo"] else "zero repo footprint"
|
|
788
|
+
print(f" - {action['kind']:<24} {action['profile']:<9} {writes}")
|
|
789
|
+
if action.get("entrypoint"):
|
|
790
|
+
print(f" entrypoint: {action['entrypoint']} (patched: {action.get('already_patched')})")
|
|
791
|
+
if action.get("install"):
|
|
792
|
+
print(f" install: {action['install']}")
|
|
793
|
+
if action.get("run"):
|
|
794
|
+
print(f" run: {action['run']}")
|
|
795
|
+
print(f" Python autoload: {'✔ installed' if data['python_autoload_present'] else '○ not installed'}")
|
|
796
|
+
print(f" Revertable: {'✔ yes' if data['revertable'] else '○ no'}\n")
|
|
797
|
+
elif sub == "revert":
|
|
798
|
+
result = auto_inject.revert(workspace)
|
|
799
|
+
state = result.get("go", {}).get("status", "nothing-to-revert")
|
|
800
|
+
print(f" Go patch: {state}")
|
|
801
|
+
if result.get("go", {}).get("entrypoint"):
|
|
802
|
+
print(f" Restored: {result['go']['entrypoint']}")
|
|
803
|
+
else:
|
|
804
|
+
result = auto_inject.apply(workspace, dry_run=dry_run, include_go=True)
|
|
805
|
+
prefix = "[DRY-RUN] " if dry_run else ""
|
|
806
|
+
cfg = result.get("config", {})
|
|
807
|
+
print(f"\n{prefix}OUMV config: {cfg.get('path')} ({'created' if cfg.get('created') else 'preserved'}), mutate={cfg.get('mutate')}")
|
|
808
|
+
for action in result.get("actions", []):
|
|
809
|
+
status = action.get("status", "?")
|
|
810
|
+
print(f" {prefix}{action['kind']}: {status}")
|
|
811
|
+
if action.get("run"):
|
|
812
|
+
print(f" run: {action['run']}")
|
|
813
|
+
if action.get("reason"):
|
|
814
|
+
print(f" reason: {action['reason']}")
|
|
815
|
+
print()
|
|
816
|
+
|
|
705
817
|
elif command in ("adapters", "adapter"):
|
|
706
818
|
from src.retrofit import get_adapters_catalog
|
|
707
819
|
catalog = get_adapters_catalog()
|
|
@@ -725,8 +837,16 @@ def main(argv: Optional[List[str]] = None):
|
|
|
725
837
|
be = doc['detected_stack'].get('backend')
|
|
726
838
|
print(f" Detected Frontend: {fe['framework'] if fe else 'None'}")
|
|
727
839
|
print(f" Detected Backend: {be['framework'] if be else 'None'}")
|
|
728
|
-
mut = doc['permissions'].get('mutate',
|
|
729
|
-
print(f" Mutation Permission: {'✔ Enabled' if mut else '○ Read-
|
|
840
|
+
mut = doc['permissions'].get('mutate', True)
|
|
841
|
+
print(f" Mutation Permission: {'✔ Enabled (out-of-the-box, guarded)' if mut else '○ Read-only (mutate: false)'}")
|
|
842
|
+
for profile, item in (doc.get('adapter_readiness') or {}).items():
|
|
843
|
+
state = "✔ ready" if item["ready"] else "○ not ready"
|
|
844
|
+
live = " (live)" if item["live"] else ""
|
|
845
|
+
print(f" Adapter {profile:<10} {state}{live}: {item['provider']}/{item['framework']} — {item['evidence']}")
|
|
846
|
+
print(f" Ready for agent: {'✔ yes' if doc.get('ready_for_agent') else '○ no'}")
|
|
847
|
+
for reason in doc.get('blocking') or []:
|
|
848
|
+
print(f" - {reason}")
|
|
849
|
+
print()
|
|
730
850
|
else:
|
|
731
851
|
from src.oumv_gateway import OUMVGateway
|
|
732
852
|
status = OUMVGateway.status()
|
|
@@ -741,20 +861,42 @@ def main(argv: Optional[List[str]] = None):
|
|
|
741
861
|
port_val: Optional[int] = None
|
|
742
862
|
host_val: Optional[str] = None
|
|
743
863
|
open_browser = False
|
|
744
|
-
|
|
864
|
+
unknown_flags: List[str] = []
|
|
865
|
+
i = 1
|
|
866
|
+
while i < len(args):
|
|
867
|
+
a = args[i]
|
|
868
|
+
nxt = args[i + 1] if i + 1 < len(args) else None
|
|
745
869
|
if a.startswith("--port="):
|
|
746
870
|
try:
|
|
747
871
|
port_val = int(a.split("=", 1)[1])
|
|
748
872
|
except ValueError:
|
|
749
873
|
pass
|
|
874
|
+
elif a == "--port":
|
|
875
|
+
if nxt is not None:
|
|
876
|
+
try:
|
|
877
|
+
port_val = int(nxt)
|
|
878
|
+
i += 1
|
|
879
|
+
except ValueError:
|
|
880
|
+
unknown_flags.append(a)
|
|
881
|
+
else:
|
|
882
|
+
unknown_flags.append(a)
|
|
750
883
|
elif a.startswith("--host="):
|
|
751
884
|
host_val = a.split("=", 1)[1]
|
|
752
885
|
elif a == "--host":
|
|
753
|
-
|
|
886
|
+
if nxt is not None and not nxt.startswith("-"):
|
|
887
|
+
host_val = nxt
|
|
888
|
+
i += 1
|
|
889
|
+
else:
|
|
890
|
+
host_val = "true"
|
|
754
891
|
elif a == "--open":
|
|
755
892
|
open_browser = True
|
|
756
|
-
elif
|
|
893
|
+
elif a.startswith("-"):
|
|
894
|
+
unknown_flags.append(a)
|
|
895
|
+
else:
|
|
757
896
|
target_dir = os.path.abspath(a)
|
|
897
|
+
i += 1
|
|
898
|
+
if unknown_flags:
|
|
899
|
+
print(f"⚠ Ignoring unsupported 'tokensafe dev' flag(s): {' '.join(unknown_flags)}")
|
|
758
900
|
cmd, source = resolve_zero_footprint_vite_command(
|
|
759
901
|
target_dir, port=port_val, host=host_val, open_browser=open_browser
|
|
760
902
|
)
|
package/src/command_sanitizer.py
CHANGED
|
@@ -387,6 +387,12 @@ class CommandSanitizer:
|
|
|
387
387
|
if dev_guard:
|
|
388
388
|
return dev_guard
|
|
389
389
|
|
|
390
|
+
# FastAPI dev servers: run through `tokensafe run-backend` so the global
|
|
391
|
+
# autoload hook mounts OUMV without editing the project.
|
|
392
|
+
py_dev_guard = cls._optimize_python_dev_stage(stage, cwd)
|
|
393
|
+
if py_dev_guard:
|
|
394
|
+
return py_dev_guard
|
|
395
|
+
|
|
390
396
|
# find: prune unbounded recursion on simple directory crawls (avoid breaking -o / -exec / -delete expressions)
|
|
391
397
|
if cmd_tok == "find" and "node_modules" not in stage and ".git" not in stage:
|
|
392
398
|
has_complex = any(a in ("-o", "-or", "-exec", "-execdir", "-delete", "(") for a in cmd_args)
|
|
@@ -682,12 +688,77 @@ class CommandSanitizer:
|
|
|
682
688
|
wrapped = f"tokensafe wrap {shlex.quote(stage)}"
|
|
683
689
|
return wrapped, saved, reason, None
|
|
684
690
|
|
|
691
|
+
@classmethod
|
|
692
|
+
def _tokensafe_ui_available(cls, cwd: str) -> bool:
|
|
693
|
+
"""True when a tokensafe-ui CLI is installed locally or globally.
|
|
694
|
+
|
|
695
|
+
Without it the rewrite would make `npm run dev` fetch the companion package
|
|
696
|
+
via npx at dev-server start (or fail offline), so the command must stay as-is.
|
|
697
|
+
"""
|
|
698
|
+
try:
|
|
699
|
+
from src.retrofit import resolve_tokensafe_ui_cli
|
|
700
|
+
return resolve_tokensafe_ui_cli(cwd) is not None
|
|
701
|
+
except Exception:
|
|
702
|
+
return False
|
|
703
|
+
|
|
704
|
+
@classmethod
|
|
705
|
+
def _is_fastapi_workspace(cls, cwd: Optional[str]) -> bool:
|
|
706
|
+
"""Cheap, side-effect-free FastAPI detection for the rewrite decision."""
|
|
707
|
+
if not cwd or not os.path.isdir(cwd):
|
|
708
|
+
return False
|
|
709
|
+
for name in ("pyproject.toml", "requirements.txt", "main.py", "app.py"):
|
|
710
|
+
path = os.path.join(cwd, name)
|
|
711
|
+
try:
|
|
712
|
+
if os.path.isfile(path):
|
|
713
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
714
|
+
if "fastapi" in f.read().lower():
|
|
715
|
+
return True
|
|
716
|
+
except OSError:
|
|
717
|
+
continue
|
|
718
|
+
app_dir = os.path.join(cwd, "app")
|
|
719
|
+
for name in ("main.py", "app.py"):
|
|
720
|
+
path = os.path.join(app_dir, name)
|
|
721
|
+
try:
|
|
722
|
+
if os.path.isfile(path):
|
|
723
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
724
|
+
if "fastapi" in f.read().lower():
|
|
725
|
+
return True
|
|
726
|
+
except OSError:
|
|
727
|
+
continue
|
|
728
|
+
return False
|
|
729
|
+
|
|
730
|
+
@classmethod
|
|
731
|
+
def _optimize_python_dev_stage(cls, stage: str, cwd: Optional[str] = None) -> Optional[Tuple[str, int, str, None]]:
|
|
732
|
+
"""Rewrites `uvicorn ...` / `python -m uvicorn ...` into `tokensafe run-backend ...`.
|
|
733
|
+
|
|
734
|
+
The wrapper only sets PYTHONPATH/TOKENSAFE_OUMV_AUTOMOUNT and execs the same
|
|
735
|
+
command, so the agent keeps control of ports/flags and the repository stays
|
|
736
|
+
untouched.
|
|
737
|
+
"""
|
|
738
|
+
stripped = stage.strip()
|
|
739
|
+
if "tokensafe run-backend" in stripped or "tokensafe inject" in stripped:
|
|
740
|
+
return None
|
|
741
|
+
if not re.match(r"^(?:[A-Za-z_]\w*=\S*\s+)*(?:sudo\s+)?(?:python[0-9.]*\s+-m\s+)?uvicorn\b", stripped):
|
|
742
|
+
return None
|
|
743
|
+
if not cls._is_fastapi_workspace(cwd):
|
|
744
|
+
return None
|
|
745
|
+
return (
|
|
746
|
+
f"tokensafe run-backend {stripped}",
|
|
747
|
+
1400,
|
|
748
|
+
"Routed FastAPI dev server through `tokensafe run-backend` (auto-mounts OUMV, no repo changes)",
|
|
749
|
+
None,
|
|
750
|
+
)
|
|
751
|
+
|
|
685
752
|
@classmethod
|
|
686
753
|
def _optimize_vite_dev_stage(cls, stage: str, cwd: Optional[str] = None) -> Optional[Tuple[str, int, str, None]]:
|
|
687
754
|
"""
|
|
688
755
|
Rewrites Vite+React dev server launches (`vite`, `npm run dev`, `bun run dev`, `pnpm dev`, `yarn dev`)
|
|
689
756
|
to zero-footprint `tokensafe dev` when `tokensafe-ui` is not yet wired in the project's Vite config,
|
|
690
757
|
so live OUMV RPC starts automatically without mutating repository files.
|
|
758
|
+
|
|
759
|
+
Only launches whose flags `tokensafe dev` can reproduce are rewritten: any other
|
|
760
|
+
flag (`--mode`, `--config`, `--`, …) means the original command is preserved,
|
|
761
|
+
because dropping it would silently start the dev server in a different config.
|
|
691
762
|
"""
|
|
692
763
|
if not cwd or not os.path.isdir(cwd):
|
|
693
764
|
return None
|
|
@@ -702,12 +773,20 @@ class CommandSanitizer:
|
|
|
702
773
|
|
|
703
774
|
is_vite_dev = False
|
|
704
775
|
passthrough: List[str] = []
|
|
776
|
+
unknown: List[str] = []
|
|
705
777
|
|
|
706
|
-
def _extract_vite_flags(args_list: List[str]) -> List[str]:
|
|
778
|
+
def _extract_vite_flags(args_list: List[str]) -> Tuple[List[str], List[str]]:
|
|
779
|
+
"""Splits dev flags tokensafe-ui supports from everything it would drop."""
|
|
707
780
|
out: List[str] = []
|
|
781
|
+
rest: List[str] = []
|
|
708
782
|
i = 0
|
|
783
|
+
if args_list[:1] == ["--"]:
|
|
784
|
+
i = 1
|
|
709
785
|
while i < len(args_list):
|
|
710
786
|
a = args_list[i]
|
|
787
|
+
if a == "--":
|
|
788
|
+
rest.extend(args_list[i:])
|
|
789
|
+
break
|
|
711
790
|
if a in ("--open",):
|
|
712
791
|
out.append(a)
|
|
713
792
|
elif a == "--host":
|
|
@@ -721,8 +800,10 @@ class CommandSanitizer:
|
|
|
721
800
|
elif a in ("--port", "-p") and i + 1 < len(args_list):
|
|
722
801
|
out.append(f"--port={args_list[i + 1]}")
|
|
723
802
|
i += 1
|
|
803
|
+
else:
|
|
804
|
+
rest.append(a)
|
|
724
805
|
i += 1
|
|
725
|
-
return out
|
|
806
|
+
return out, rest
|
|
726
807
|
|
|
727
808
|
pkg_json_path = os.path.join(cwd, "package.json")
|
|
728
809
|
if not os.path.isfile(pkg_json_path):
|
|
@@ -751,10 +832,12 @@ class CommandSanitizer:
|
|
|
751
832
|
|
|
752
833
|
if cmd_tok == "vite" and (not cmd_args or cmd_args[0].startswith("-") or cmd_args[0] in ("dev", "serve")):
|
|
753
834
|
is_vite_dev = True
|
|
754
|
-
|
|
835
|
+
rest_args = cmd_args[1:] if cmd_args[:1] in (["dev"], ["serve"]) else cmd_args
|
|
836
|
+
passthrough, unknown = _extract_vite_flags(rest_args)
|
|
755
837
|
elif cmd_tok in ("npx", "bunx") and cmd_args[:1] == ["vite"] and (len(cmd_args) == 1 or cmd_args[1].startswith("-") or cmd_args[1] in ("dev", "serve")):
|
|
756
838
|
is_vite_dev = True
|
|
757
|
-
|
|
839
|
+
rest_args = cmd_args[2:] if cmd_args[1:2] in (["dev"], ["serve"]) else cmd_args[1:]
|
|
840
|
+
passthrough, unknown = _extract_vite_flags(rest_args)
|
|
758
841
|
elif cmd_tok in ("npm", "bun", "pnpm", "yarn"):
|
|
759
842
|
sub = cmd_args[:2]
|
|
760
843
|
is_dev_script = (sub == ["run", "dev"]) or (cmd_tok in ("pnpm", "yarn") and cmd_args[:1] == ["dev"])
|
|
@@ -763,9 +846,12 @@ class CommandSanitizer:
|
|
|
763
846
|
dev_script = str(scripts.get("dev") or "")
|
|
764
847
|
if re.search(r"(?:^|\s)vite(?:\s|$)", dev_script):
|
|
765
848
|
is_vite_dev = True
|
|
766
|
-
|
|
849
|
+
script_idx = 2 if sub == ["run", "dev"] else 1
|
|
850
|
+
passthrough, unknown = _extract_vite_flags(cmd_args[script_idx:])
|
|
767
851
|
|
|
768
|
-
if not is_vite_dev or
|
|
852
|
+
if not is_vite_dev or unknown:
|
|
853
|
+
return None
|
|
854
|
+
if not cls._tokensafe_ui_available(cwd):
|
|
769
855
|
return None
|
|
770
856
|
|
|
771
857
|
flags_str = (" " + " ".join(passthrough)) if passthrough else ""
|
package/src/guard.py
CHANGED
|
@@ -23,6 +23,64 @@ from src.command_sanitizer import CommandSanitizer
|
|
|
23
23
|
|
|
24
24
|
_TOKENSAFE_SRC_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
25
25
|
|
|
26
|
+
# --------------------------------------------------------------------------- #
|
|
27
|
+
# Network data-exfiltration detection (shell-flow aware)
|
|
28
|
+
#
|
|
29
|
+
# The previous single regex matched `-d` inside `tokensafe-dev` together with the
|
|
30
|
+
# word `token` inside `tokensafe-python`, across a `;` separator, so read-only
|
|
31
|
+
# checks like `curl … https://pypi.org/… ; gh secret list -R org/repo` were
|
|
32
|
+
# blocked. It also flagged any script that merely quoted such a command in a
|
|
33
|
+
# heredoc. Detection is now per shell segment and only fires on a sensitive
|
|
34
|
+
# *file* actually being uploaded.
|
|
35
|
+
# --------------------------------------------------------------------------- #
|
|
36
|
+
|
|
37
|
+
_EXFIL_SENSITIVE_PATH = (
|
|
38
|
+
r"(?:\.env(?:\.[\w-]+)?|id_rsa|id_ed25519|credentials\.json|service_account\.json|"
|
|
39
|
+
r"\.npmrc|\.pypirc|[\w.-]*\.(?:pem|key)|secrets?\.(?:json|ya?ml|toml|env))"
|
|
40
|
+
)
|
|
41
|
+
_EXFIL_FILE = rf"(?:[\w./~-]*/)?{_EXFIL_SENSITIVE_PATH}"
|
|
42
|
+
_EXFIL_NET = r"(?:sudo\s+)?(?:curl|wget|nc|ncat|netcat)"
|
|
43
|
+
|
|
44
|
+
_EXFIL_PATTERNS = (
|
|
45
|
+
rf"\b{_EXFIL_NET}\b[^;|&\n]*(?:--data(?:-binary|-raw)?|--post-file|-d|-T|--upload-file)(?:[=\s]+)@?['\"]?{_EXFIL_FILE}",
|
|
46
|
+
rf"\b{_EXFIL_NET}\b[^;|&\n]*(?:-F|--form)\s+[^=\s]*=@['\"]?{_EXFIL_FILE}",
|
|
47
|
+
rf"\b{_EXFIL_NET}\b[^;|&\n]*<\s*['\"]?{_EXFIL_FILE}",
|
|
48
|
+
rf"\bcat\s+['\"]?{_EXFIL_FILE}['\"]?\s*\|\s*{_EXFIL_NET}\b",
|
|
49
|
+
# command substitution / backticks reading a sensitive file into the URL
|
|
50
|
+
rf"\b{_EXFIL_NET}\b[^;|&\n]*\$\(\s*(?:cat\s+)?['\"]?{_EXFIL_FILE}",
|
|
51
|
+
rf"\b{_EXFIL_NET}\b[^;|&\n]*`cat\s+['\"]?{_EXFIL_FILE}",
|
|
52
|
+
)
|
|
53
|
+
_EXFIL_COMPILED = tuple(re.compile(p, re.IGNORECASE) for p in _EXFIL_PATTERNS)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _strip_heredocs(command: str) -> str:
|
|
57
|
+
"""Drops heredoc bodies: their text is data for an interpreter, not shell flow."""
|
|
58
|
+
lines = command.splitlines()
|
|
59
|
+
kept = []
|
|
60
|
+
i = 0
|
|
61
|
+
while i < len(lines):
|
|
62
|
+
line = lines[i]
|
|
63
|
+
kept.append(line)
|
|
64
|
+
match = re.search(r"<<-?\s*['\"]?([A-Za-z_]\w*)['\"]?", line)
|
|
65
|
+
if match:
|
|
66
|
+
tag = match.group(1)
|
|
67
|
+
i += 1
|
|
68
|
+
while i < len(lines) and lines[i].strip() != tag:
|
|
69
|
+
i += 1
|
|
70
|
+
i += 1
|
|
71
|
+
return "\n".join(kept)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _detect_shell_exfiltration(command: str):
|
|
75
|
+
"""Returns the offending fragment when a sensitive file is sent to a network client."""
|
|
76
|
+
shell = _strip_heredocs(command or "")
|
|
77
|
+
for pattern in _EXFIL_COMPILED:
|
|
78
|
+
match = pattern.search(shell)
|
|
79
|
+
if match:
|
|
80
|
+
return match.group(0)
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
|
|
26
84
|
class GuardResult(NamedTuple):
|
|
27
85
|
blocked: bool
|
|
28
86
|
reason: Optional[str] = None
|
|
@@ -536,20 +594,15 @@ class TokenSafeGuard:
|
|
|
536
594
|
),
|
|
537
595
|
)
|
|
538
596
|
|
|
539
|
-
# 3. Network Data Exfiltration Prevention (
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
rf"""(?:\b(?:curl|wget|nc|ncat|netcat)\b.*?(?:\$\(\s*(?:cat\s+)?<?\s*[^)]*{_SENS_EXFIL}[^)]*\)|`cat\s+[^`]*{_SENS_EXFIL}[^`]*`|(?:-d|--data|--data-binary|--data-raw|-T|--upload-file)[=\s]*@?[^\s]*{_SENS_EXFIL}|-F\s+[^=]*=@[^\s]*{_SENS_EXFIL}|--post-file[=\s]+[^\s]*{_SENS_EXFIL}|<\s*[^\s]*{_SENS_EXFIL})|\bcat\s+[^\s|]*{_SENS_EXFIL}\s*\|\s*(?:curl|wget|nc|ncat|netcat)\b)""",
|
|
543
|
-
cmd,
|
|
544
|
-
re.IGNORECASE
|
|
545
|
-
)
|
|
546
|
-
if exfil_pattern:
|
|
597
|
+
# 3. Network Data Exfiltration Prevention (uploading sensitive FILES to a network client)
|
|
598
|
+
exfil_hit = _detect_shell_exfiltration(cmd)
|
|
599
|
+
if exfil_hit:
|
|
547
600
|
return GuardResult(
|
|
548
601
|
blocked=True,
|
|
549
602
|
check_name="DATA_EXFILTRATION",
|
|
550
603
|
reason=(
|
|
551
|
-
f"Blocked potential credential exfiltration via network command: '{
|
|
552
|
-
f"
|
|
604
|
+
f"Blocked potential credential exfiltration via network command: '{exfil_hit}'. "
|
|
605
|
+
f"Uploading local sensitive files (.env / private keys) to remote endpoints is prohibited."
|
|
553
606
|
)
|
|
554
607
|
)
|
|
555
608
|
|
|
@@ -598,11 +651,22 @@ class TokenSafeGuard:
|
|
|
598
651
|
|
|
599
652
|
return GuardResult(blocked=False)
|
|
600
653
|
|
|
654
|
+
@classmethod
|
|
655
|
+
def _oumv_curl_guard_enabled(cls) -> bool:
|
|
656
|
+
"""Kill switch in the FileState style: TOKENSAFE_OUMV_CURL_GUARD=0/false/no/off."""
|
|
657
|
+
return os.environ.get("TOKENSAFE_OUMV_CURL_GUARD", "").strip().lower() not in ("0", "false", "no", "off")
|
|
658
|
+
|
|
601
659
|
@classmethod
|
|
602
660
|
def _check_live_oumv_curl(cls, stages: List[str], cwd: str = "") -> Optional[str]:
|
|
603
|
-
"""Blocks raw curl/wget against localhost ports managed by a live OUMV runtime.
|
|
661
|
+
"""Blocks raw curl/wget against localhost ports managed by a live OUMV runtime.
|
|
662
|
+
|
|
663
|
+
get_live_ports() only returns ports that are fresh and actually listening, so a
|
|
664
|
+
stale descriptor (crashed dev server, port reused) can never hard-block curl.
|
|
665
|
+
"""
|
|
604
666
|
if not cwd or not os.path.isdir(cwd):
|
|
605
667
|
return None
|
|
668
|
+
if not cls._oumv_curl_guard_enabled():
|
|
669
|
+
return None
|
|
606
670
|
try:
|
|
607
671
|
from src.oumv_gateway import OUMVGateway
|
|
608
672
|
live_ports = OUMVGateway.get_live_ports(cwd)
|
package/src/installer.py
CHANGED
|
@@ -2799,6 +2799,12 @@ WantedBy=default.target
|
|
|
2799
2799
|
ui_sync = cls._ensure_tokensafe_ui_global(npm_bins=target_npm_bins, install_if_missing=False)
|
|
2800
2800
|
if ui_sync.get("ok"):
|
|
2801
2801
|
print(f" {GREEN}✔{RESET} tokensafe-ui {ui_sync['action']} globally ({ui_sync['npm']}).")
|
|
2802
|
+
else:
|
|
2803
|
+
# `tokensafe dev` and the vite-dev rewrite both need this companion CLI.
|
|
2804
|
+
print(
|
|
2805
|
+
f" {YELLOW}⚠{RESET} tokensafe-ui not installed — run "
|
|
2806
|
+
f"`tokensafe install` to enable zero-footprint live Vite+React OUMV."
|
|
2807
|
+
)
|
|
2802
2808
|
for npm_bin in target_npm_bins:
|
|
2803
2809
|
npm_env = cls._npm_subprocess_env(npm_bin)
|
|
2804
2810
|
for pkg in ("create-tokensafe-ui",):
|