telveguard-agent 0.4.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.
@@ -0,0 +1,2 @@
1
+ """Telveguard ajanı: Cursor ve Claude Code hook'ları, kurum hesabıyla giriş (`telve`)."""
2
+ __version__ = "0.4.0"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,215 @@
1
+ """
2
+ telve: kod asistanlarını (Cursor, Claude Code) Telveguard'a bağlar.
3
+
4
+ telve setup --gateway https://telveguard.sirket.local
5
+ telve login
6
+ telve install cursor # Cursor hook'ları
7
+ telve install claude --route # Claude Code hook'ları + model trafiği Telveguard'dan
8
+ telve doctor
9
+ """
10
+ import argparse
11
+ import json
12
+ import sys
13
+ import webbrowser
14
+ from pathlib import Path
15
+
16
+ from . import __version__, client, hooks, install
17
+ from .config import ConfigError, load, managed_path, save_user
18
+
19
+
20
+ def _cfg():
21
+ try:
22
+ return load()
23
+ except ConfigError as e:
24
+ sys.exit(f"telve: {e}")
25
+
26
+
27
+ def cmd_setup(args) -> int:
28
+ cfg = _cfg()
29
+ if "gateway" in cfg.managed_keys:
30
+ print(f"Gateway adresi kurum tarafından belirlenmiş: {cfg.gateway_url} ({managed_path()})")
31
+ return 0
32
+ updates = {"gateway": args.gateway.rstrip("/")}
33
+ if args.ca_file:
34
+ updates["ca_file"] = str(Path(args.ca_file).resolve())
35
+ path = save_user(updates)
36
+ cfg = _cfg()
37
+ info = client.gateway_info(cfg)
38
+ print(f"Kaydedildi: {path}\nGateway {info.get('version')} · kimlik modu: {info['auth_mode']}")
39
+ if info["auth_mode"] == "jwt":
40
+ print("Sıradaki adım: telve login")
41
+ return 0
42
+
43
+
44
+ def cmd_login(args) -> int:
45
+ cfg = _cfg()
46
+ if args.token:
47
+ token = sys.stdin.readline().strip() if args.token == "-" else args.token
48
+ client.save_credentials({"access_token": token, "expires_at": 0})
49
+ print("Token kaydedildi.")
50
+ return 0
51
+ info = client.gateway_info(cfg)
52
+ if info["auth_mode"] != "jwt":
53
+ print("Gateway header modunda (geliştirme): giriş gerekmez. Kimlik: telve setup ile user / team.")
54
+ return 0
55
+ oidc = {**(info.get("oidc") or {}), **(cfg.oidc or {})}
56
+
57
+ def announce(url, code):
58
+ print(f"Tarayıcıda açın: {url}\nKod: {code}")
59
+ if not args.no_browser:
60
+ webbrowser.open(url)
61
+ try:
62
+ client.device_login(cfg, oidc, announce)
63
+ except client.AuthRequired as e:
64
+ sys.exit(f"telve: {e}")
65
+ print("Giriş yapıldı.")
66
+ return 0
67
+
68
+
69
+ def cmd_logout(args) -> int:
70
+ print("Çıkış yapıldı." if client.clear_credentials() else "Zaten giriş yapılmamış.")
71
+ return 0
72
+
73
+
74
+ def cmd_token(args) -> int:
75
+ """Claude Code apiKeyHelper: stdout'a yalnızca token."""
76
+ try:
77
+ print(client.access_token(_cfg()))
78
+ except (client.AuthRequired, client.GatewayError) as e:
79
+ print(f"telve: {e}", file=sys.stderr)
80
+ return 1
81
+ return 0
82
+
83
+
84
+ def cmd_hook(args) -> int:
85
+ cfg = _cfg()
86
+ if args.tool == "cursor":
87
+ return hooks.run(lambda data: hooks.cursor(cfg, data))
88
+ return hooks.run(lambda data: hooks.claude(cfg, data, routed=args.routed))
89
+
90
+
91
+ def cmd_install(args, remove: bool = False) -> int:
92
+ cfg = _cfg()
93
+ command = args.command or install.telve_command()
94
+ if args.tool == "cursor":
95
+ path = install.cursor_path(args.scope)
96
+ data = install.cursor_config({} if args.print else install._load(path), command,
97
+ cfg.fail_closed, remove)
98
+ else:
99
+ if getattr(args, "route", False) and not cfg.gateway_url:
100
+ sys.exit("telve: --route için önce telve setup --gateway ...")
101
+ path = install.claude_path(args.scope)
102
+ data = install.claude_config({} if args.print else install._load(path), command, cfg.gateway_url,
103
+ getattr(args, "route", False), cfg.fail_closed, remove)
104
+ if args.print:
105
+ print(json.dumps(data, indent=2, ensure_ascii=False))
106
+ return 0
107
+ try:
108
+ install.write(path, data)
109
+ except PermissionError:
110
+ sys.exit(f"telve: {path} yazılamadı; kurumsal kapsam yönetici yetkisi ister (sudo) ya da --print ile MDM'e verin")
111
+ print(f"{'Kaldırıldı' if remove else 'Kuruldu'}: {path}")
112
+ if not remove and args.tool == "cursor":
113
+ print("Cursor'u yeniden başlatın. Hata ayrıntısı: Output paneli > Hooks.")
114
+ return 0
115
+
116
+
117
+ def cmd_check(args) -> int:
118
+ cfg = _cfg()
119
+ text = sys.stdin.read() if args.file == "-" else Path(args.file).read_text(encoding="utf-8", errors="replace")
120
+ try:
121
+ result = client.check(cfg, args.client, args.event, text, args.model, args.routed)
122
+ except (client.AuthRequired, client.GatewayError) as e:
123
+ sys.exit(f"telve: {e}")
124
+ print(json.dumps(result, indent=2, ensure_ascii=False))
125
+ return 0 if result["action"] in ("allow", "warn", "mask") else 2
126
+
127
+
128
+ def cmd_doctor(args) -> int:
129
+ ok = True
130
+
131
+ def line(good, label, detail=""):
132
+ nonlocal ok
133
+ ok &= bool(good) or good is None
134
+ mark = {True: "✓", False: "✗", None: "–"}[good if good is None else bool(good)]
135
+ print(f"{mark} {label}" + (f": {detail}" if detail else ""))
136
+
137
+ print(f"telve {__version__}")
138
+ try:
139
+ cfg = load()
140
+ except ConfigError as e:
141
+ line(False, "Yapılandırma", str(e))
142
+ return 1
143
+ line(bool(cfg.gateway_url), "Gateway", cfg.gateway_url or "tanımlı değil (telve setup --gateway ...)")
144
+ line(None, "Kaynaklar", ", ".join(cfg.sources) or "varsayılanlar")
145
+ line(None, "Erişilemezse", "durdur (fail_closed)" if cfg.fail_closed else "yerel tarama")
146
+ if cfg.gateway_url:
147
+ try:
148
+ info = client.gateway_info(cfg)
149
+ line(True, "Bağlantı", f"Telveguard {info.get('version')} · {info['auth_mode']}")
150
+ r = client.check(cfg, "claude-code", "shell", "telve doctor")
151
+ who = r.get("identity") or {}
152
+ line(True, "Kimlik", f"{who.get('user')} ({', '.join(who.get('teams') or [])}) · "
153
+ f"{'doğrulanmış (OIDC)' if who.get('source') == 'jwt' else 'beyan (header modu)'}")
154
+ except (client.GatewayError, client.AuthRequired) as e:
155
+ line(False, "Bağlantı / kimlik", str(e))
156
+ for tool, paths in (("Cursor", install.cursor_path), ("Claude Code", install.claude_path)):
157
+ found = {scope: install.installed(paths(scope)) for scope in ("enterprise", "user", "project")}
158
+ active = [s for s, v in found.items() if v]
159
+ line(bool(active) or None, f"{tool} hook'ları", ", ".join(active) if active else "kurulu değil")
160
+ return 0 if ok else 1
161
+
162
+
163
+ def main(argv=None) -> int:
164
+ p = argparse.ArgumentParser(prog="telve", description="Kod asistanlarını Telveguard'a bağlar.")
165
+ p.add_argument("--version", action="version", version=f"telve {__version__}")
166
+ sub = p.add_subparsers(dest="cmd", required=True)
167
+
168
+ s = sub.add_parser("setup", help="gateway adresini kaydet")
169
+ s.add_argument("--gateway", required=True)
170
+ s.add_argument("--ca-file", help="kurum içi CA sertifikası (PEM)")
171
+ s.set_defaults(func=cmd_setup)
172
+
173
+ s = sub.add_parser("login", help="kurum hesabıyla giriş (OIDC cihaz akışı)")
174
+ s.add_argument("--token", help="cihaz akışı yerine hazır token ('-': stdin)")
175
+ s.add_argument("--no-browser", action="store_true")
176
+ s.set_defaults(func=cmd_login)
177
+
178
+ sub.add_parser("logout", help="kayıtlı oturumu sil").set_defaults(func=cmd_logout)
179
+ sub.add_parser("token", help="geçerli access token (Claude Code apiKeyHelper)").set_defaults(func=cmd_token)
180
+
181
+ s = sub.add_parser("hook", help="araçların çağırdığı hook (stdin JSON -> stdout JSON)")
182
+ s.add_argument("tool", choices=["cursor", "claude"])
183
+ s.add_argument("--routed", action="store_true", help="Claude Code model trafiği Telveguard'dan geçiyor")
184
+ s.set_defaults(func=cmd_hook)
185
+
186
+ for name, remove in (("install", False), ("uninstall", True)):
187
+ s = sub.add_parser(name, help=f"hook'ları {'kur' if not remove else 'kaldır'}")
188
+ s.add_argument("tool", choices=["cursor", "claude"])
189
+ s.add_argument("--scope", choices=["user", "project", "enterprise"], default="user")
190
+ s.add_argument("--print", action="store_true", help="yazma, içeriği bas (MDM paketi için)")
191
+ s.add_argument("--command", help="hook komutunun yolu (varsayılan: bulunan telve)")
192
+ if not remove:
193
+ s.add_argument("--route", action="store_true",
194
+ help="Claude Code: model trafiğini de Telveguard'a yönlendir")
195
+ s.set_defaults(func=lambda a, r=remove: cmd_install(a, r))
196
+
197
+ s = sub.add_parser("check", help="bir metni / dosyayı politikadan geçir (deneme)")
198
+ s.add_argument("file", help="dosya ya da '-' (stdin)")
199
+ s.add_argument("--client", choices=["cursor", "claude-code"], default="cursor")
200
+ s.add_argument("--event", choices=["prompt", "file", "shell", "tool_input", "tool_output"], default="prompt")
201
+ s.add_argument("--model", default="")
202
+ s.add_argument("--routed", action="store_true")
203
+ s.set_defaults(func=cmd_check)
204
+
205
+ sub.add_parser("doctor", help="kurulumu denetle").set_defaults(func=cmd_doctor)
206
+
207
+ args = p.parse_args(argv)
208
+ try:
209
+ return args.func(args)
210
+ except client.GatewayError as e:
211
+ sys.exit(f"telve: {e}")
212
+
213
+
214
+ if __name__ == "__main__":
215
+ sys.exit(main())
@@ -0,0 +1,186 @@
1
+ """
2
+ Gateway ile konuşma (yalnızca standart kütüphane: hook her olayda yeniden başlar, hızlı açılmalı)
3
+ ve kimlik: OIDC cihaz akışı (RFC 8628) ile giriş, refresh token ile sessiz yenileme.
4
+
5
+ Token'lar kullanıcının yapılandırma dizininde, yalnızca kullanıcının okuyabileceği bir dosyada
6
+ durur (gcloud / kubectl gibi). Claude Code'un apiKeyHelper'ı `telve token`ı çağırır.
7
+ """
8
+ import json
9
+ import os
10
+ import ssl
11
+ import time
12
+ import urllib.error
13
+ import urllib.parse
14
+ import urllib.request
15
+ from typing import Any, Dict, Optional, Tuple
16
+
17
+ from . import __version__
18
+ from .config import Config, default_user, user_dir
19
+
20
+
21
+ class GatewayError(Exception):
22
+ """Gateway'e ulaşılamadı ya da beklenmeyen cevap (hook fail_closed'a göre davranır)."""
23
+
24
+
25
+ class AuthRequired(Exception):
26
+ """Giriş yapılmamış ya da oturum yenilenemedi: `telve login`."""
27
+
28
+
29
+ def _ssl(cfg: Config) -> Optional[ssl.SSLContext]:
30
+ return ssl.create_default_context(cafile=cfg.ca_file) if cfg.ca_file else None
31
+
32
+
33
+ def http_json(cfg: Config, method: str, url: str, body: Any = None, headers: Optional[Dict[str, str]] = None,
34
+ form: bool = False) -> Tuple[int, Any]:
35
+ data = None
36
+ h = {"accept": "application/json", "user-agent": f"telve/{__version__}"}
37
+ if body is not None:
38
+ if form:
39
+ data = urllib.parse.urlencode(body).encode()
40
+ h["content-type"] = "application/x-www-form-urlencoded"
41
+ else:
42
+ data = json.dumps(body, ensure_ascii=False).encode("utf-8")
43
+ h["content-type"] = "application/json"
44
+ h.update(headers or {})
45
+ req = urllib.request.Request(url, data=data, headers=h, method=method)
46
+ try:
47
+ with urllib.request.urlopen(req, timeout=cfg.timeout, context=_ssl(cfg)) as resp:
48
+ status, raw = resp.status, resp.read()
49
+ except urllib.error.HTTPError as e:
50
+ status, raw = e.code, e.read()
51
+ except (urllib.error.URLError, OSError) as e:
52
+ raise GatewayError(f"{urllib.parse.urlsplit(url).netloc} adresine ulaşılamadı: "
53
+ f"{getattr(e, 'reason', e)}")
54
+ try:
55
+ return status, json.loads(raw) if raw else None
56
+ except ValueError:
57
+ raise GatewayError(f"{url} JSON olmayan cevap döndü ({status})")
58
+
59
+
60
+ # ---------------- kimlik ----------------
61
+
62
+ def _cred_path():
63
+ return user_dir() / "credentials.json"
64
+
65
+
66
+ def load_credentials() -> Optional[Dict[str, Any]]:
67
+ try:
68
+ return json.loads(_cred_path().read_text(encoding="utf-8"))
69
+ except (FileNotFoundError, ValueError):
70
+ return None
71
+
72
+
73
+ def save_credentials(creds: Dict[str, Any]) -> None:
74
+ path = _cred_path()
75
+ path.parent.mkdir(parents=True, exist_ok=True)
76
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
77
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
78
+ json.dump(creds, f)
79
+ os.chmod(path, 0o600)
80
+
81
+
82
+ def clear_credentials() -> bool:
83
+ try:
84
+ _cred_path().unlink()
85
+ return True
86
+ except FileNotFoundError:
87
+ return False
88
+
89
+
90
+ def gateway_info(cfg: Config) -> Dict[str, Any]:
91
+ status, info = http_json(cfg, "GET", f"{cfg.gateway_url}/v1/agent/config")
92
+ if status != 200 or not isinstance(info, dict):
93
+ raise GatewayError(f"Gateway kurulum bilgisi alınamadı ({status}); sürümü 0.4 öncesi olabilir")
94
+ return info
95
+
96
+
97
+ def _oidc_endpoints(cfg: Config, oidc: Dict[str, str]) -> Dict[str, Any]:
98
+ status, meta = http_json(cfg, "GET", oidc["issuer"].rstrip("/") + "/.well-known/openid-configuration")
99
+ if status != 200 or not isinstance(meta, dict):
100
+ raise GatewayError(f"OIDC keşif belgesi alınamadı ({status})")
101
+ return meta
102
+
103
+
104
+ def device_login(cfg: Config, oidc: Dict[str, str], announce) -> Dict[str, Any]:
105
+ """RFC 8628: kullanıcı tarayıcıda kodu onaylar, bu süreç token gelene kadar bekler."""
106
+ if not oidc.get("client_id"):
107
+ raise GatewayError("OIDC istemci kimliği yok: gateway'de OIDC_AGENT_CLIENT_ID tanımlanmalı")
108
+ meta = _oidc_endpoints(cfg, oidc)
109
+ if not meta.get("device_authorization_endpoint"):
110
+ raise GatewayError("Kimlik sağlayıcı cihaz akışını (device authorization grant) desteklemiyor")
111
+ status, dev = http_json(cfg, "POST", meta["device_authorization_endpoint"], form=True,
112
+ body={"client_id": oidc["client_id"], "scope": oidc.get("scope") or "openid"})
113
+ if status != 200:
114
+ raise GatewayError(f"Cihaz kodu alınamadı ({status}): {dev}")
115
+ announce(dev.get("verification_uri_complete") or dev["verification_uri"], dev["user_code"])
116
+ interval = int(dev.get("interval", 5))
117
+ deadline = time.time() + int(dev.get("expires_in", 600))
118
+ while time.time() < deadline:
119
+ time.sleep(interval)
120
+ status, tok = http_json(cfg, "POST", meta["token_endpoint"], form=True, body={
121
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
122
+ "device_code": dev["device_code"], "client_id": oidc["client_id"]})
123
+ if status == 200:
124
+ return _store(tok, meta["token_endpoint"], oidc["client_id"])
125
+ err = (tok or {}).get("error")
126
+ if err == "authorization_pending":
127
+ continue
128
+ if err == "slow_down":
129
+ interval += 5
130
+ continue
131
+ raise AuthRequired({"access_denied": "Giriş reddedildi.",
132
+ "expired_token": "Kodun süresi doldu; yeniden deneyin."}.get(err, f"Giriş başarısız: {err}"))
133
+ raise AuthRequired("Kodun süresi doldu; yeniden deneyin.")
134
+
135
+
136
+ def _store(tok: Dict[str, Any], token_endpoint: str, client_id: str, old: Optional[Dict] = None) -> Dict[str, Any]:
137
+ creds = {"access_token": tok["access_token"],
138
+ "refresh_token": tok.get("refresh_token") or (old or {}).get("refresh_token"),
139
+ "expires_at": int(time.time()) + int(tok.get("expires_in", 300)),
140
+ "token_endpoint": token_endpoint, "client_id": client_id}
141
+ save_credentials(creds)
142
+ return creds
143
+
144
+
145
+ def access_token(cfg: Config) -> str:
146
+ """Geçerli access token; süresi bitmek üzereyse refresh token ile yeniler."""
147
+ if os.environ.get("TELVEGUARD_TOKEN"):
148
+ return os.environ["TELVEGUARD_TOKEN"]
149
+ creds = load_credentials()
150
+ if not creds:
151
+ raise AuthRequired("Giriş yapılmamış: telve login")
152
+ if creds.get("expires_at", 0) - 60 > time.time() or not creds.get("token_endpoint"):
153
+ return creds["access_token"] # statik token (telve login --token) süresizdir
154
+ if not creds.get("refresh_token"):
155
+ raise AuthRequired("Oturum süresi doldu: telve login")
156
+ status, tok = http_json(cfg, "POST", creds["token_endpoint"], form=True, body={
157
+ "grant_type": "refresh_token", "refresh_token": creds["refresh_token"], "client_id": creds["client_id"]})
158
+ if status != 200:
159
+ raise AuthRequired("Oturum yenilenemedi: telve login")
160
+ return _store(tok, creds["token_endpoint"], creds["client_id"], creds)["access_token"]
161
+
162
+
163
+ def auth_headers(cfg: Config, user_hint: str = "") -> Dict[str, str]:
164
+ """jwt modunda Bearer token: kişi token'dan gelir, doğrulanır. Giriş yoksa kullanıcı / ekip
165
+ beyanı (header modu: geliştirme / demo; jwt modunda gateway bunu reddeder -> telve login).
166
+ Beyan sırası: yapılandırma (MDM) > aracın bildirdiği (Cursor: user_email) > OS kullanıcısı."""
167
+ try:
168
+ return {"authorization": f"Bearer {access_token(cfg)}"}
169
+ except AuthRequired:
170
+ return {"x-telveguard-user": cfg.user or user_hint or default_user() or "unknown",
171
+ "x-telveguard-team": cfg.team or "default"}
172
+
173
+
174
+ def check(cfg: Config, client: str, event: str, text: str, model: str = "", routed: bool = False,
175
+ user_hint: str = "") -> Dict[str, Any]:
176
+ if not cfg.gateway_url:
177
+ raise GatewayError("Gateway adresi tanımlı değil: telve setup --gateway https://...")
178
+ status, body = http_json(cfg, "POST", f"{cfg.gateway_url}/v1/agent/check", headers=auth_headers(cfg, user_hint), body={
179
+ "client": client, "event": event, "text": text, "model": model or "", "routed": routed,
180
+ "agent_version": __version__})
181
+ if status == 401:
182
+ raise AuthRequired("Gateway kimliği reddetti: telve login")
183
+ if status != 200 or not isinstance(body, dict) or "action" not in body:
184
+ msg = ((body or {}).get("error") or {}).get("message") if isinstance(body, dict) else None
185
+ raise GatewayError(f"Gateway {status} döndü" + (f": {msg}" if msg else ""))
186
+ return body
@@ -0,0 +1,108 @@
1
+ """
2
+ Yapılandırma: kurumsal (MDM ile dağıtılan) > ortam değişkeni > kullanıcı.
3
+
4
+ Kurumsal dosya yönetici yetkisiyle yazılır, kullanıcı değiştiremez: gateway adresi ve
5
+ "Telveguard'a ulaşılamazsa durdur" (fail_closed) gibi güvenlik ayarları oradan gelir.
6
+ """
7
+ import json
8
+ import os
9
+ import sys
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+ from typing import Any, Dict, List, Optional
13
+
14
+ DEFAULTS: Dict[str, Any] = {
15
+ "gateway": "", # https://telveguard.sirket.local
16
+ "fail_closed": False, # gateway'e ulaşılamazsa: True = durdur, False = yerel tarama
17
+ "timeout": 8, # saniye
18
+ "ca_file": "", # kurum içi CA (PEM); boşsa sistem sertifikaları
19
+ "user": "", # yalnızca AUTH_MODE=header (geliştirme / demo)
20
+ "team": "",
21
+ "tab_files": True, # Cursor Tab'ın okuduğu dosyalar da taransın mı
22
+ "max_file_bytes": 1_000_000, # bundan büyük dosyanın yalnızca başı taranır
23
+ "oidc": None, # {"issuer", "client_id", "scope"}; boşsa gateway'den öğrenilir
24
+ }
25
+
26
+
27
+ def managed_path() -> Path:
28
+ if sys.platform == "darwin":
29
+ return Path("/Library/Application Support/Telveguard/agent.json")
30
+ if os.name == "nt":
31
+ return Path(os.environ.get("PROGRAMDATA", r"C:\ProgramData")) / "Telveguard" / "agent.json"
32
+ return Path("/etc/telveguard/agent.json")
33
+
34
+
35
+ def user_dir() -> Path:
36
+ if os.name == "nt":
37
+ return Path(os.environ.get("APPDATA", Path.home())) / "Telveguard"
38
+ return Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "telveguard"
39
+
40
+
41
+ def cache_dir() -> Path:
42
+ if os.name == "nt":
43
+ return Path(os.environ.get("LOCALAPPDATA", Path.home())) / "Telveguard" / "cache"
44
+ return Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "telveguard"
45
+
46
+
47
+ def _read(path: Path) -> Dict[str, Any]:
48
+ try:
49
+ data = json.loads(path.read_text(encoding="utf-8"))
50
+ except FileNotFoundError:
51
+ return {}
52
+ except (OSError, ValueError) as e:
53
+ raise ConfigError(f"{path} okunamadı: {e}")
54
+ if not isinstance(data, dict):
55
+ raise ConfigError(f"{path} bir JSON nesnesi olmalı")
56
+ return data
57
+
58
+
59
+ class ConfigError(Exception):
60
+ pass
61
+
62
+
63
+ @dataclass
64
+ class Config:
65
+ values: Dict[str, Any]
66
+ managed_keys: List[str] = field(default_factory=list) # kullanıcının değiştiremedikleri
67
+ sources: List[str] = field(default_factory=list)
68
+
69
+ def __getattr__(self, name: str) -> Any:
70
+ try:
71
+ return self.__dict__["values"][name]
72
+ except KeyError:
73
+ raise AttributeError(name)
74
+
75
+ @property
76
+ def gateway_url(self) -> str:
77
+ return str(self.values["gateway"]).rstrip("/")
78
+
79
+
80
+ def load() -> Config:
81
+ values = dict(DEFAULTS)
82
+ sources = []
83
+ user_file = user_dir() / "agent.json"
84
+ user = _read(user_file)
85
+ if user:
86
+ values.update(user)
87
+ sources.append(str(user_file))
88
+ if os.environ.get("TELVEGUARD_URL"):
89
+ values["gateway"] = os.environ["TELVEGUARD_URL"]
90
+ sources.append("TELVEGUARD_URL")
91
+ managed = _read(managed_path())
92
+ if managed:
93
+ values.update(managed)
94
+ sources.append(str(managed_path()))
95
+ return Config(values, sorted(managed), sources)
96
+
97
+
98
+ def save_user(updates: Dict[str, Any]) -> Path:
99
+ path = user_dir() / "agent.json"
100
+ data = _read(path)
101
+ data.update(updates)
102
+ path.parent.mkdir(parents=True, exist_ok=True)
103
+ path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
104
+ return path
105
+
106
+
107
+ def default_user() -> Optional[str]:
108
+ return os.environ.get("USER") or os.environ.get("USERNAME")
@@ -0,0 +1,262 @@
1
+ """
2
+ Cursor ve Claude Code hook protokolleri: stdin'den olay JSON'u, stdout'a karar JSON'u.
3
+
4
+ Her olay gateway'deki /v1/agent/check'e sorulur (merkezi politika + denetim kaydı).
5
+ Gateway'e ulaşılamazsa:
6
+ * fail_closed: durdur (kurumsal yapılandırmada önerilen)
7
+ * değilse yerel tarama (telveguard-core): kişisel veri / sır / injection bulunursa yine
8
+ durdurulur, temiz içerik geçer. Kurumsal sözlük yerelde yoktur.
9
+ Hook'un kendisi hata verirse Cursor'da izin hook'ları (dosya, komut, MCP) durur, prompt geçer;
10
+ Claude Code'da işlem devam eder. Bu yüzden her yol açıkça bir karar yazar.
11
+
12
+ Protokoller:
13
+ Cursor : https://cursor.com/docs/agent/hooks
14
+ Claude : https://code.claude.com/docs/en/hooks
15
+ """
16
+ import hashlib
17
+ import json
18
+ import sys
19
+ import time
20
+ from pathlib import Path
21
+ from typing import Any, Callable, Dict, Optional
22
+
23
+ from .client import AuthRequired, GatewayError, check
24
+ from .config import Config, cache_dir
25
+
26
+ CURSOR_EVENTS = ["beforeSubmitPrompt", "beforeReadFile", "beforeTabFileRead",
27
+ "beforeShellExecution", "beforeMCPExecution"]
28
+ # Claude Code: araç girdisi (komut, MCP / web argümanları) çalışmadan önce, çıktısı modele
29
+ # gitmeden önce. Read / Grep çıktısı dosya içeriğidir: maskelenebilir, durdurmaya gerek yok.
30
+ CLAUDE_PRE_MATCHER = "Bash|WebFetch|WebSearch|mcp__.*"
31
+ CLAUDE_POST_MATCHER = "Read|Grep|Bash|WebFetch|mcp__.*"
32
+ BLOCK_NOTICE = "[Telveguard: bu içerik politika gereği modele gönderilmedi]"
33
+ CACHE_TTL = 300
34
+ CACHE_MAX = 2000
35
+
36
+
37
+ def log(msg: str) -> None:
38
+ """stderr: Cursor'da "Hooks" çıktı kanalında, Claude Code'da --debug'da görünür."""
39
+ print(f"telve: {msg}", file=sys.stderr)
40
+
41
+
42
+ # ---------------- karar ----------------
43
+
44
+ _local_engine = None
45
+
46
+
47
+ def _local(event: str, text: str) -> Dict[str, Any]:
48
+ """Gateway yokken telveguard-core ile yerel tarama (politika yok: bulunan her şey riskli)."""
49
+ global _local_engine
50
+ from telveguard_core import InjectionDetector, TrPiiEngine
51
+ if _local_engine is None:
52
+ _local_engine = (TrPiiEngine(), InjectionDetector())
53
+ pii, inj = _local_engine
54
+ findings = pii.analyze(text)
55
+ entities: Dict[str, int] = {}
56
+ for f in findings:
57
+ entities[f.entity] = entities.get(f.entity, 0) + 1
58
+ injected = event in ("prompt", "file", "tool_output") and inj.scan(text).score >= 0.85
59
+ if not entities and not injected:
60
+ return {"action": "allow", "message": "", "entities": {}, "masked_text": None}
61
+ found = ", ".join(sorted(entities)) or "prompt injection"
62
+ if event == "tool_output" and entities and not injected:
63
+ return {"action": "mask", "entities": entities, "masked_text": pii.mask(text).text,
64
+ "message": f"Telveguard (çevrimdışı): araç çıktısındaki {found} maskelendi."}
65
+ return {"action": "block", "entities": entities,
66
+ "masked_text": pii.mask(text).text if event == "tool_output" else None,
67
+ "message": f"Telveguard'a ulaşılamadı; içerik {found} içerdiği için yerel taramayla durduruldu."}
68
+
69
+
70
+ def _cache_key(client: str, event: str, text: str) -> str:
71
+ return hashlib.sha256(f"{client}\0{event}\0{text}".encode("utf-8", "surrogatepass")).hexdigest()
72
+
73
+
74
+ def _cache_get(key: str) -> Optional[Dict[str, Any]]:
75
+ try:
76
+ data = json.loads((cache_dir() / "verdicts.json").read_text(encoding="utf-8"))
77
+ except (OSError, ValueError):
78
+ return None
79
+ hit = data.get(key)
80
+ return {"action": "allow", "message": "", "masked_text": None} if hit and hit > time.time() else None
81
+
82
+
83
+ def _cache_put(key: str) -> None:
84
+ path = cache_dir() / "verdicts.json"
85
+ try:
86
+ data = json.loads(path.read_text(encoding="utf-8"))
87
+ except (OSError, ValueError):
88
+ data = {}
89
+ now = time.time()
90
+ data = {k: v for k, v in data.items() if v > now}
91
+ if len(data) >= CACHE_MAX:
92
+ data = dict(sorted(data.items(), key=lambda kv: kv[1])[-CACHE_MAX // 2:])
93
+ data[key] = now + CACHE_TTL
94
+ try:
95
+ path.parent.mkdir(parents=True, exist_ok=True)
96
+ path.write_text(json.dumps(data), encoding="utf-8")
97
+ except OSError:
98
+ pass
99
+
100
+
101
+ def decide(cfg: Config, client: str, event: str, text: str, model: str = "", routed: bool = False,
102
+ user_hint: str = "") -> Dict[str, Any]:
103
+ if not text.strip():
104
+ return {"action": "allow", "message": "", "masked_text": None}
105
+ # Temiz dosya içeriği kısa süre önbellekte: Cursor Tab aynı dosyayı tekrar tekrar okur.
106
+ # Yalnızca "izin" önbelleğe girer; durdurulan içerik her seferinde yeniden sorulur.
107
+ cacheable = event == "file"
108
+ key = _cache_key(client, event, text) if cacheable else ""
109
+ if cacheable and (hit := _cache_get(key)):
110
+ return hit
111
+ try:
112
+ result = check(cfg, client, event, text, model, routed, user_hint)
113
+ except (GatewayError, AuthRequired) as e:
114
+ log(str(e))
115
+ if cfg.fail_closed:
116
+ return {"action": "block", "masked_text": None,
117
+ "message": f"Telveguard'a ulaşılamadı ({e}); kurum politikası gereği durduruldu."}
118
+ try:
119
+ return _local(event, text)
120
+ except ImportError:
121
+ return {"action": "allow", "message": "", "masked_text": None}
122
+ if cacheable and result["action"] == "allow":
123
+ _cache_put(key)
124
+ return result
125
+
126
+
127
+ def read_text_file(path: str, limit: int) -> Optional[str]:
128
+ """Metin dosyasının (en fazla limit bayt) içeriği; ikili dosya / okunamayan dosya için None."""
129
+ try:
130
+ with open(path, "rb") as f:
131
+ raw = f.read(limit)
132
+ except OSError:
133
+ return None
134
+ if b"\0" in raw[:8192]:
135
+ return None # ikili (görsel / PDF: gateway üzerinden gidiyorsa orada OCR'la taranır)
136
+ return raw.decode("utf-8", errors="replace")
137
+
138
+
139
+ # ---------------- Cursor ----------------
140
+
141
+ def cursor(cfg: Config, data: Dict[str, Any]) -> Dict[str, Any]:
142
+ event = data.get("hook_event_name", "")
143
+ model = data.get("model") or ""
144
+ limit = int(cfg.max_file_bytes)
145
+ # Cursor oturumundaki e-posta: yalnızca giriş yapılmamışsa (header modu) kimlik beyanı olur
146
+ who = data.get("user_email") if isinstance(data.get("user_email"), str) else ""
147
+
148
+ def decide_(kind: str, text: str) -> Dict[str, Any]:
149
+ return decide(cfg, "cursor", kind, text, model, user_hint=who)
150
+
151
+ if event == "beforeSubmitPrompt":
152
+ texts = [("prompt", data.get("prompt") or "")]
153
+ for att in data.get("attachments") or []:
154
+ if isinstance(att, dict) and att.get("file_path"):
155
+ content = read_text_file(att["file_path"], limit)
156
+ if content:
157
+ texts.append(("file", content))
158
+ notes = []
159
+ for kind, text in texts:
160
+ r = decide_(kind, text)
161
+ if r["action"] == "block":
162
+ return {"continue": False, "user_message": r["message"]}
163
+ if r["message"]:
164
+ notes.append(r["message"])
165
+ return {"continue": True, **({"user_message": "\n".join(notes)} if notes else {})}
166
+
167
+ if event in ("beforeReadFile", "beforeTabFileRead"):
168
+ if event == "beforeTabFileRead" and not cfg.tab_files:
169
+ return {"permission": "allow"}
170
+ content = data.get("content")
171
+ if not isinstance(content, str):
172
+ content = read_text_file(data.get("file_path", ""), limit) or ""
173
+ r = decide_("file", content[:limit])
174
+ out = {"permission": "deny" if r["action"] == "block" else "allow"}
175
+ if r["message"] and event == "beforeReadFile":
176
+ out["user_message"] = r["message"]
177
+ return out
178
+
179
+ if event in ("beforeShellExecution", "beforeMCPExecution"):
180
+ if event == "beforeShellExecution":
181
+ kind, text = "shell", data.get("command") or ""
182
+ else:
183
+ kind = "tool_input"
184
+ text = json.dumps({"tool": data.get("tool_name"), "input": data.get("tool_input")}, ensure_ascii=False)
185
+ r = decide_(kind, text)
186
+ if r["action"] == "block":
187
+ return {"permission": "deny", "user_message": r["message"], "agent_message": r["message"]}
188
+ return {"permission": "allow", **({"user_message": r["message"]} if r["message"] else {})}
189
+
190
+ return {}
191
+
192
+
193
+ # ---------------- Claude Code ----------------
194
+
195
+ def _replace_long_strings(value: Any, notice: str) -> Any:
196
+ """Çıktının biçimini koruyarak içerik taşıyan (uzun) metinleri değiştirir. Claude Code
197
+ yerleşik araçlarda biçime uymayan updatedToolOutput'u yok sayar: "type" gibi kısa
198
+ alanlar aynen kalmalı."""
199
+ if isinstance(value, str):
200
+ return notice if len(value) >= 80 or "\n" in value else value
201
+ if isinstance(value, list):
202
+ return [_replace_long_strings(v, notice) for v in value]
203
+ if isinstance(value, dict):
204
+ return {k: _replace_long_strings(v, notice) for k, v in value.items()}
205
+ return value
206
+
207
+
208
+ def claude(cfg: Config, data: Dict[str, Any], routed: bool = False) -> Dict[str, Any]:
209
+ event = data.get("hook_event_name", "")
210
+
211
+ if event == "UserPromptSubmit":
212
+ r = decide(cfg, "claude-code", "prompt", data.get("prompt") or "", routed=routed)
213
+ if r["action"] == "block":
214
+ # suppressOriginalPrompt: engellenen prompt'taki veri ekranda / geçmişte kalmasın
215
+ return {"decision": "block", "reason": r["message"],
216
+ "hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "suppressOriginalPrompt": True}}
217
+ return {"systemMessage": r["message"]} if r["message"] else {}
218
+
219
+ if event == "PreToolUse":
220
+ tool, tool_input = data.get("tool_name", ""), data.get("tool_input") or {}
221
+ if tool == "Bash":
222
+ kind, text = "shell", str(tool_input.get("command") or "")
223
+ else:
224
+ kind, text = "tool_input", json.dumps({"tool": tool, "input": tool_input}, ensure_ascii=False)
225
+ r = decide(cfg, "claude-code", kind, text, routed=routed)
226
+ if r["action"] == "block":
227
+ return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
228
+ "permissionDecisionReason": r["message"]}}
229
+ return {"systemMessage": r["message"]} if r["message"] else {}
230
+
231
+ if event == "PostToolUse":
232
+ response = data.get("tool_response")
233
+ if response is None:
234
+ return {}
235
+ text = response if isinstance(response, str) else json.dumps(response, ensure_ascii=False)
236
+ r = decide(cfg, "claude-code", "tool_output", text, routed=routed)
237
+ if r["action"] not in ("mask", "block"):
238
+ return {"systemMessage": r["message"]} if r["message"] else {}
239
+ masked: Any = r.get("masked_text") or text
240
+ if not isinstance(response, str):
241
+ try:
242
+ masked = json.loads(masked)
243
+ except ValueError: # maskeleme JSON'u bozduysa: içeriği hiç gösterme
244
+ masked, r = response, {**r, "action": "block"}
245
+ if r["action"] == "block":
246
+ masked = _replace_long_strings(masked, BLOCK_NOTICE)
247
+ return {"systemMessage": r["message"],
248
+ "hookSpecificOutput": {"hookEventName": "PostToolUse", "updatedToolOutput": masked,
249
+ "additionalContext": r["message"]}}
250
+
251
+ return {}
252
+
253
+
254
+ def run(adapter: Callable[[Dict[str, Any]], Dict[str, Any]]) -> int:
255
+ try:
256
+ data = json.loads(sys.stdin.buffer.read().decode("utf-8", errors="replace") or "{}")
257
+ except ValueError:
258
+ log("stdin geçerli JSON değil")
259
+ data = {}
260
+ out = adapter(data if isinstance(data, dict) else {})
261
+ sys.stdout.write(json.dumps(out, ensure_ascii=False))
262
+ return 0
@@ -0,0 +1,153 @@
1
+ """
2
+ `telve install cursor|claude`: hook'ları araçların yapılandırmasına yazar.
3
+
4
+ Kapsam:
5
+ user : yalnızca bu kullanıcı (~/.cursor/hooks.json, ~/.claude/settings.json)
6
+ project : bu depo (.cursor/hooks.json, .claude/settings.json); depoyla paylaşılır
7
+ enterprise : makinedeki herkes; kullanıcı kapatamaz (yönetici yetkisi / MDM)
8
+ Cursor: /Library/Application Support/Cursor/hooks.json (Enterprise plan)
9
+ Claude: .../ClaudeCode/managed-settings.d/telveguard.json
10
+ --print yazmak yerine içeriği basar: MDM (Jamf, Intune) paketine konmak için.
11
+
12
+ Mevcut dosyadaki başka hook'lara dokunulmaz; yalnızca önceki Telveguard girdileri değiştirilir.
13
+ GUI uygulamaları kabuğun PATH'ini görmez: komut mutlak yolla yazılır.
14
+ """
15
+ import json
16
+ import os
17
+ import shutil
18
+ import sys
19
+ from pathlib import Path
20
+ from typing import Any, Dict, List, Optional
21
+
22
+ from .hooks import CLAUDE_POST_MATCHER, CLAUDE_PRE_MATCHER, CURSOR_EVENTS
23
+
24
+ MARK = "telve" # komutta "telve hook" geçen girdiler bizimdir
25
+
26
+
27
+ def telve_command() -> str:
28
+ found = shutil.which("telve")
29
+ if found:
30
+ return str(Path(found).resolve())
31
+ argv0 = Path(sys.argv[0])
32
+ return str(argv0.resolve()) if argv0.name.startswith("telve") else "telve"
33
+
34
+
35
+ def _quote(path: str) -> str:
36
+ return f'"{path}"' if " " in path else path
37
+
38
+
39
+ def _is_ours(cmd: Any) -> bool:
40
+ return isinstance(cmd, str) and f"{MARK} hook" in cmd.replace('"', "").replace(".exe", "").replace(
41
+ os.sep, " ").replace("/", " ")
42
+
43
+
44
+ def _system_dir(app: str) -> Path:
45
+ if sys.platform == "darwin":
46
+ return Path("/Library/Application Support") / app
47
+ if os.name == "nt":
48
+ root = os.environ.get("PROGRAMFILES" if app == "ClaudeCode" else "PROGRAMDATA",
49
+ r"C:\Program Files" if app == "ClaudeCode" else r"C:\ProgramData")
50
+ return Path(root) / app
51
+ return Path("/etc") / ("claude-code" if app == "ClaudeCode" else "cursor")
52
+
53
+
54
+ def cursor_path(scope: str) -> Path:
55
+ if scope == "enterprise":
56
+ return _system_dir("Cursor") / "hooks.json"
57
+ if scope == "project":
58
+ return Path.cwd() / ".cursor" / "hooks.json"
59
+ return Path.home() / ".cursor" / "hooks.json"
60
+
61
+
62
+ def claude_path(scope: str) -> Path:
63
+ if scope == "enterprise":
64
+ return _system_dir("ClaudeCode") / "managed-settings.d" / "telveguard.json"
65
+ if scope == "project":
66
+ return Path.cwd() / ".claude" / "settings.json"
67
+ return Path.home() / ".claude" / "settings.json"
68
+
69
+
70
+ def _load(path: Path) -> Dict[str, Any]:
71
+ try:
72
+ data = json.loads(path.read_text(encoding="utf-8"))
73
+ except FileNotFoundError:
74
+ return {}
75
+ if not isinstance(data, dict):
76
+ raise ValueError(f"{path} bir JSON nesnesi değil")
77
+ return data
78
+
79
+
80
+ # ---------------- Cursor ----------------
81
+
82
+ def cursor_config(existing: Dict[str, Any], command: str, fail_closed: bool, remove: bool = False) -> Dict[str, Any]:
83
+ data = dict(existing)
84
+ data.setdefault("version", 1)
85
+ hooks = {k: [h for h in v if not _is_ours(h.get("command"))] for k, v in (data.get("hooks") or {}).items()}
86
+ if not remove:
87
+ for event in CURSOR_EVENTS:
88
+ entry: Dict[str, Any] = {"command": f"{_quote(command)} hook cursor", "timeout": 15}
89
+ if fail_closed:
90
+ entry["failClosed"] = True
91
+ hooks.setdefault(event, []).append(entry)
92
+ data["hooks"] = {k: v for k, v in hooks.items() if v}
93
+ return data
94
+
95
+
96
+ # ---------------- Claude Code ----------------
97
+
98
+ def _strip(groups: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
99
+ out = []
100
+ for g in groups:
101
+ kept = [h for h in g.get("hooks", []) if not _is_ours(h.get("command"))]
102
+ if kept:
103
+ out.append({**g, "hooks": kept})
104
+ return out
105
+
106
+
107
+ def claude_config(existing: Dict[str, Any], command: str, gateway: str = "", route: bool = False,
108
+ fail_closed: bool = False, remove: bool = False) -> Dict[str, Any]:
109
+ data = dict(existing)
110
+ hooks = {k: _strip(v) for k, v in (data.get("hooks") or {}).items()}
111
+ env = dict(data.get("env") or {})
112
+ if env.pop("TELVEGUARD_ROUTED", None): # önceki --route kurulumunun izleri
113
+ for k in ("ANTHROPIC_BASE_URL", "CLAUDE_CODE_API_KEY_HELPER_TTL_MS"):
114
+ env.pop(k, None)
115
+ data.pop("apiKeyHelper", None)
116
+
117
+ if not remove:
118
+ cmd = f"{_quote(command)} hook claude" + (" --routed" if route else "")
119
+ handler: Dict[str, Any] = {"type": "command", "command": cmd, "timeout": 15}
120
+ if fail_closed:
121
+ handler["onFailure"] = "block"
122
+ hooks.setdefault("UserPromptSubmit", []).append({"hooks": [handler]})
123
+ hooks.setdefault("PreToolUse", []).append({"matcher": CLAUDE_PRE_MATCHER, "hooks": [handler]})
124
+ hooks.setdefault("PostToolUse", []).append({"matcher": CLAUDE_POST_MATCHER, "hooks": [handler]})
125
+ if route:
126
+ # Model trafiği de Telveguard'dan: maskeleme yolda, cevap geri açılır, kota / maliyet
127
+ env.update(ANTHROPIC_BASE_URL=gateway, CLAUDE_CODE_API_KEY_HELPER_TTL_MS="300000",
128
+ TELVEGUARD_ROUTED="1")
129
+ data["apiKeyHelper"] = f"{_quote(command)} token"
130
+ data["hooks"] = {k: v for k, v in hooks.items() if v}
131
+ if not data["hooks"]:
132
+ data.pop("hooks")
133
+ if env:
134
+ data["env"] = env
135
+ else:
136
+ data.pop("env", None)
137
+ return data
138
+
139
+
140
+ def write(path: Path, data: Dict[str, Any]) -> None:
141
+ path.parent.mkdir(parents=True, exist_ok=True)
142
+ if path.exists():
143
+ shutil.copy2(path, path.with_suffix(path.suffix + ".bak"))
144
+ path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
145
+
146
+
147
+ def installed(path: Path) -> Optional[bool]:
148
+ """None: dosya yok; True / False: Telveguard hook'u var mı."""
149
+ try:
150
+ text = path.read_text(encoding="utf-8")
151
+ except (FileNotFoundError, PermissionError):
152
+ return None
153
+ return "hook cursor" in text or "hook claude" in text
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.4
2
+ Name: telveguard-agent
3
+ Version: 0.4.0
4
+ Summary: Cursor ve Claude Code'u Telveguard'a bağlayan hook'lar ve kurum hesabıyla giriş (telve)
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/osmanuygar/telveguard
7
+ Project-URL: Source, https://github.com/osmanuygar/telveguard
8
+ Project-URL: Issues, https://github.com/osmanuygar/telveguard/issues
9
+ Keywords: cursor,claude-code,hooks,kvkk,dlp,ai-security
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Information Technology
13
+ Classifier: Natural Language :: Turkish
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Security
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: telveguard-core>=0.4.0
20
+ Dynamic: license-file
21
+
22
+ # telveguard-agent
23
+
24
+ [Telveguard](https://github.com/osmanuygar/telveguard) için kod asistanı ajanı (`telve`):
25
+ Cursor ve Claude Code'u kurum politikasına bağlar. Kontrol makinede, veri makineden çıkmadan önce yapılır.
26
+
27
+ ```bash
28
+ pip install telveguard-agent
29
+ telve setup --gateway https://telveguard.sirket.local
30
+ telve login # kurum hesabı (OIDC cihaz akışı)
31
+ telve install cursor
32
+ telve install claude --route
33
+ telve doctor
34
+ ```
35
+
36
+ | | Cursor | Claude Code |
37
+ |---|---|---|
38
+ | Prompt | kişisel veri / sır / injection varsa durdurulur | durdurulur; `--route` ile yolda maskelenir |
39
+ | Okunan dosya, Tab | durdurulur | çıktı maskelenir |
40
+ | Komut, MCP, web araçları | durdurulur | durdurulur |
41
+ | Araç çıktısı | — (MCP için ContextForge) | maskelenir |
42
+
43
+ Karar gateway'deki politikayla verilir ve denetim kaydına (Röntgen, POC raporu) yazılır; metnin kendisi saklanmaz.
44
+ Gateway'e ulaşılamazsa `fail_closed: true` durdurur, aksi hâlde yerel tarama yapılır.
45
+
46
+ Kurumsal dağıtım (MDM): `/Library/Application Support/Telveguard/agent.json` (Linux `/etc/telveguard/`,
47
+ Windows `C:\ProgramData\Telveguard\`) ve `telve install ... --scope enterprise --print` çıktısı.
48
+ Ayrıntı: [README](https://github.com/osmanuygar/telveguard#kod-asistanları-cursor-ve-claude-code).
49
+
50
+ Lisans: Apache-2.0
@@ -0,0 +1,13 @@
1
+ telveguard_agent/__init__.py,sha256=B6EsAfO6TpomLZBQ2-q3yRI9Gn99ngRM6sSHr5Xkkqk,116
2
+ telveguard_agent/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
3
+ telveguard_agent/cli.py,sha256=9_mWzgFW0VRBYcMWPNLy3Pp6A8-fuqNIwAP5mie7m4w,8992
4
+ telveguard_agent/client.py,sha256=yLObW64HrNOH0aUm0Mduf8zogTHBpaNqeYyybwN-PoY,8469
5
+ telveguard_agent/config.py,sha256=TEFuRYUQlB9C4itImYCJSEVdvXClZXnQJVd1xbSPxdE,3682
6
+ telveguard_agent/hooks.py,sha256=5gUfMPWulhonar0fWlxCTiJyDiqRZdp4UoCi76JAyhA,11648
7
+ telveguard_agent/install.py,sha256=-Lk1fk6XoJoJm6ZXb4psqSOcFt0VqySHEVkmQlEgFXc,5979
8
+ telveguard_agent-0.4.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
9
+ telveguard_agent-0.4.0.dist-info/METADATA,sha256=QiM4fRqAefDrqcAF5UOzdDSkj3KQh_ViD-U25ZDLO8Y,2170
10
+ telveguard_agent-0.4.0.dist-info/WHEEL,sha256=a-udL2m4V_6Yn8b-uKzWb12RjRxwwMo6ohYFM24tpaY,91
11
+ telveguard_agent-0.4.0.dist-info/entry_points.txt,sha256=hHqrhi1P0Q9sOfL0zMmgj7HyUF86CvzZMpa0EvUpDeg,52
12
+ telveguard_agent-0.4.0.dist-info/top_level.txt,sha256=MgPB1TiLVR7mb3UsGjtFYFrJiMkt8D4-IXSpbpe31uo,17
13
+ telveguard_agent-0.4.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ telve = telveguard_agent.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ telveguard_agent