zerochat 10.27.0__tar.gz → 10.28.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zerochat
3
- Version: 10.27.0
3
+ Version: 10.28.0
4
4
  Summary: Private local web client for AI models, tools and MCP services
5
5
  Author: Alberto Alday
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "zerochat"
7
- version = "10.27.0"
7
+ version = "10.28.0"
8
8
  description = "Private local web client for AI models, tools and MCP services"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zerochat
3
- Version: 10.27.0
3
+ Version: 10.28.0
4
4
  Summary: Private local web client for AI models, tools and MCP services
5
5
  Author: Alberto Alday
6
6
  License-Expression: MIT
@@ -1575,7 +1575,7 @@ def dispatch_browser(method: str, params: dict) -> RpcOutcome:
1575
1575
 
1576
1576
 
1577
1577
 
1578
- SOURCE_BACKEND_VERSION = "10.27.0"
1578
+ SOURCE_BACKEND_VERSION = "10.28.0"
1579
1579
 
1580
1580
 
1581
1581
  def _read_source_version(filename: str) -> str | None:
@@ -2422,6 +2422,8 @@ WORKSPACE_TRUST_PIPE_FILTERS = frozenset([
2422
2422
  ])
2423
2423
  WORKSPACE_TRUST_GLOBAL_COMMANDS = re.compile(r"(?:^|\s)(?:sudo|su|doas|mkfs|reboot|shutdown|systemctl)\b")
2424
2424
  WORKSPACE_TRUST_OUTSIDE_REFERENCE = re.compile(r"(?:^|[\s=:'\"])(?:[\\/~]|[A-Za-z]:[\\/])|\$|(?:^|[\s=:'\"\\/])\.\.(?=[\s\\/'\"]|$)")
2425
+ _COMMAND_PATH_START = re.compile(r"^(?:[/\\]|(?:\.\.(?:$|[/\\]))|[A-Za-z]:[\\/])")
2426
+ _COMMAND_INTERNAL_OUTSIDE_REF = re.compile(r"[\s:'\"](?:[\\/~]|[A-Za-z]:[\\/]|\.\.(?:$|[\s\\/]))")
2425
2427
 
2426
2428
 
2427
2429
  def parse_directory_rule(raw_rule: str) -> dict | None:
@@ -2543,6 +2545,34 @@ def is_workspace_local_command(segment: str) -> bool:
2543
2545
  return not WORKSPACE_TRUST_GLOBAL_COMMANDS.search(segment) and not WORKSPACE_TRUST_OUTSIDE_REFERENCE.search(segment)
2544
2546
 
2545
2547
 
2548
+ def command_outside_references(segment: str) -> list[str] | None:
2549
+ """
2550
+ Rutas externas o con '..' que aparecen como argumentos del subcomando para validarlas frente a
2551
+ directoryRules; [] si es local al proyecto, o None si lleva órdenes globales, $, ~ o texto con
2552
+ rutas incrustadas no validables como argumento de ruta.
2553
+ """
2554
+ if is_workspace_local_command(segment):
2555
+ return []
2556
+ if WORKSPACE_TRUST_GLOBAL_COMMANDS.search(segment) or "$" in segment or "~" in segment:
2557
+ return None
2558
+ try:
2559
+ tokens = shlex.split(segment)
2560
+ except ValueError:
2561
+ return None
2562
+ if not tokens:
2563
+ return None
2564
+ refs = []
2565
+ for token in tokens:
2566
+ if not WORKSPACE_TRUST_OUTSIDE_REFERENCE.search(token):
2567
+ continue
2568
+ candidate = token.split("=", 1)[1] if ("=" in token and not _COMMAND_PATH_START.match(token)) else token
2569
+ tail = candidate[2:] if re.match(r"^[A-Za-z]:[\\/]", candidate) else candidate[1:]
2570
+ if not _COMMAND_PATH_START.match(candidate) or _COMMAND_INTERNAL_OUTSIDE_REF.search(tail):
2571
+ return None
2572
+ refs.append(candidate)
2573
+ return refs
2574
+
2575
+
2546
2576
  @functools.lru_cache(maxsize=512)
2547
2577
  def compile_command_pattern(pattern: str) -> tuple[tuple[tuple[re.Pattern, bool], ...], bool]:
2548
2578
  """
@@ -6578,7 +6608,7 @@ def job_details(job: CommandJob) -> dict:
6578
6608
 
6579
6609
 
6580
6610
 
6581
- POLICY_STATE_VERSION = 6
6611
+ POLICY_STATE_VERSION = 7
6582
6612
  CHALLENGE_TTL_MS = 600_000
6583
6613
  MAX_POLICY_ENTRIES = 500
6584
6614
  # Proyectos con sesión en memoria: al pasar del tope se olvida la del usado hace más tiempo sin comandos en marcha.
@@ -6631,13 +6661,19 @@ class AccessController:
6631
6661
  """Única definición del estado permanente y de sus valores por defecto."""
6632
6662
  data = raw if isinstance(raw, dict) else {}
6633
6663
  patterns = data.get("commandPatterns") if isinstance(data.get("commandPatterns"), dict) else {}
6664
+ raw_dir_rules = data.get("directoryRules")
6665
+ dir_rules = {
6666
+ str(project): list(rules)
6667
+ for project, rules in raw_dir_rules.items()
6668
+ if isinstance(project, str) and isinstance(rules, list) and rules
6669
+ } if isinstance(raw_dir_rules, dict) else {}
6634
6670
  # run_command nunca se guarda autorizado entero: sus permisos permanentes son patrones.
6635
6671
  tools = {tid: entry for tid, entry in dict(data.get("tools") or {}).items()
6636
6672
  if not (tid == COMMAND_TOOL and isinstance(entry, dict) and entry.get("policy") == POLICY_ALLOW)}
6637
6673
  return {
6638
6674
  "version": POLICY_STATE_VERSION,
6639
6675
  "globalMcpPolicy": data.get("globalMcpPolicy") or GLOBAL_POLICY_ASK,
6640
- "directoryRules": list(data.get("directoryRules") or []),
6676
+ "directoryRules": dir_rules,
6641
6677
  "tools": tools,
6642
6678
  "servers": dict(data.get("servers") or {}),
6643
6679
  "commandPatterns": {"global": list(patterns.get("global") or []), "projects": dict(patterns.get("projects") or {})}
@@ -6658,7 +6694,11 @@ class AccessController:
6658
6694
  session = self._session(context)
6659
6695
  return {
6660
6696
  "globalMcpPolicy": session.global_policy if session.global_policy is not None else state["globalMcpPolicy"],
6661
- "directoryRules": list(session.directory_rules) if session.directory_rules is not None else state["directoryRules"],
6697
+ "directoryRules": (
6698
+ list(session.directory_rules)
6699
+ if session.directory_rules is not None
6700
+ else list(state["directoryRules"].get(context.key) or [])
6701
+ ),
6662
6702
  "tools": {**state["tools"], **session.tools},
6663
6703
  "servers": {**state["servers"], **session.servers},
6664
6704
  "commandPatterns": {**state["commandPatterns"], "session": list(session.command_patterns)}
@@ -6734,7 +6774,9 @@ class AccessController:
6734
6774
  @staticmethod
6735
6775
  def _check_entry_limit(state: dict):
6736
6776
  """Único tope de entradas, sobre el estado resultante (guardado o capa de sesión)."""
6737
- total = len(state.get("directoryRules") or []) + len(state.get("tools") or {}) + len(state.get("servers") or {})
6777
+ dir_rules = state.get("directoryRules")
6778
+ dir_count = sum(len(v) for v in dir_rules.values()) if isinstance(dir_rules, dict) else len(dir_rules or [])
6779
+ total = dir_count + len(state.get("tools") or {}) + len(state.get("servers") or {})
6738
6780
  if total > MAX_POLICY_ENTRIES:
6739
6781
  raise ValueError(f"El número total de entradas ({total}) supera el máximo permitido ({MAX_POLICY_ENTRIES}).")
6740
6782
 
@@ -6764,22 +6806,29 @@ class AccessController:
6764
6806
  added_rules = self._validate_directory_rules(state["addDirectoryRules"], context) if "addDirectoryRules" in state else []
6765
6807
  clean_patterns = normalize_command_patterns(state["commandPatterns"]) if "commandPatterns" in state else None
6766
6808
 
6809
+ project = context.key
6810
+
6767
6811
  def mutator(current: dict) -> dict:
6768
- self._apply_state_patch(current, clean_global, clean_rules, added_rules, clean_tools, clean_servers, clean_patterns)
6812
+ self._apply_state_patch(current, project, clean_global, clean_rules, added_rules, clean_tools, clean_servers, clean_patterns)
6769
6813
  self._check_entry_limit(current)
6770
6814
  return current
6771
6815
  self._update_permanent(mutator)
6772
- self._forget_session_overrides(clean_global, clean_rules, added_rules, clean_tools, clean_servers)
6816
+ self._forget_session_overrides(project, clean_global, clean_rules, added_rules, clean_tools, clean_servers)
6773
6817
  return self.export_state(context)
6774
6818
 
6775
- def _apply_state_patch(self, current: dict, clean_global, clean_rules, added_rules, clean_tools, clean_servers, clean_patterns):
6819
+ def _apply_state_patch(self, current: dict, project: str, clean_global, clean_rules, added_rules, clean_tools, clean_servers, clean_patterns):
6776
6820
  """Aplica sobre el estado guardado los apartados del parche que vienen (None es «no cambiar»)."""
6777
6821
  if clean_global is not None:
6778
6822
  current["globalMcpPolicy"] = clean_global
6779
6823
  if clean_rules is not None:
6780
- current["directoryRules"] = clean_rules
6824
+ if clean_rules:
6825
+ current["directoryRules"][project] = clean_rules
6826
+ else:
6827
+ current["directoryRules"].pop(project, None)
6781
6828
  if added_rules:
6782
- current["directoryRules"] = self._append_rules(current["directoryRules"], added_rules)
6829
+ merged = self._append_rules(current["directoryRules"].get(project) or [], added_rules)
6830
+ if merged:
6831
+ current["directoryRules"][project] = merged
6783
6832
  if clean_tools is not None:
6784
6833
  current["tools"] = self._apply_entry_patch(current.get("tools"), clean_tools)
6785
6834
  if clean_servers is not None:
@@ -6787,16 +6836,17 @@ class AccessController:
6787
6836
  if clean_patterns is not None:
6788
6837
  current["commandPatterns"] = clean_patterns
6789
6838
 
6790
- def _forget_session_overrides(self, clean_global, clean_rules, added_rules, clean_tools, clean_servers):
6791
- """Lo guardado vale para todos los proyectos: sustituye o revoca lo equivalente en la sesión de cada uno."""
6839
+ def _forget_session_overrides(self, project: str, clean_global, clean_rules, added_rules, clean_tools, clean_servers):
6840
+ """Lo guardado sustituye o revoca lo equivalente en la sesión (las reglas de carpeta, solo en su proyecto)."""
6792
6841
  with self._lock:
6793
- for session in self.sessions.values():
6842
+ for key, session in self.sessions.items():
6794
6843
  if clean_global is not None:
6795
6844
  session.global_policy = None
6796
- if clean_rules is not None:
6797
- session.directory_rules = None
6798
- elif added_rules and session.directory_rules is not None:
6799
- session.directory_rules = self._append_rules(session.directory_rules, added_rules)
6845
+ if key == project:
6846
+ if clean_rules is not None:
6847
+ session.directory_rules = None
6848
+ elif added_rules and session.directory_rules is not None:
6849
+ session.directory_rules = self._append_rules(session.directory_rules, added_rules)
6800
6850
  for kind, patch in (("tools", clean_tools), ("servers", clean_servers)):
6801
6851
  for item_id in patch or {}:
6802
6852
  session.entries(kind).pop(item_id, None)
@@ -7024,11 +7074,13 @@ class AccessController:
7024
7074
  def mutator(state: dict) -> dict:
7025
7075
  self._store_decision(state, decision, pattern, project, tool, server_name, server_id)
7026
7076
  if rules:
7027
- state["directoryRules"] = self._append_rules(state["directoryRules"], rules)
7077
+ merged = self._append_rules(state["directoryRules"].get(project) or [], rules)
7078
+ if merged:
7079
+ state["directoryRules"][project] = merged
7028
7080
  self._check_entry_limit(state)
7029
7081
  return state
7030
7082
  self._update_permanent(mutator)
7031
- self._drop_superseded_session_entries(decision, pattern, tool, server_id, rules)
7083
+ self._drop_superseded_session_entries(decision, pattern, tool, server_id, project, rules)
7032
7084
 
7033
7085
  def _allow_for_session(self, context: SecurityContext, tool: str, server_name: str, pattern: str | None):
7034
7086
  """«Permitir en la sesión»: el patrón de comando aprobado o, sin él, la herramienta."""
@@ -7054,15 +7106,16 @@ class AccessController:
7054
7106
  elif decision == "allow_server_always":
7055
7107
  state["servers"][server_id] = self._make_entry("servers", POLICY_ALLOW, SCOPE_PERMANENT, server_name or server_id)
7056
7108
 
7057
- def _drop_superseded_session_entries(self, decision: str, pattern: str | None, tool: str, server_id: str, rules: list[str]):
7058
- """Lo que se acaba de guardar sustituye a lo equivalente en la sesión de cada proyecto."""
7109
+ def _drop_superseded_session_entries(self, decision: str, pattern: str | None, tool: str, server_id: str,
7110
+ project: str, rules: list[str]):
7111
+ """Lo que se acaba de guardar sustituye a lo equivalente en la sesión (las reglas de carpeta, solo en su proyecto)."""
7059
7112
  with self._lock:
7060
- for session in self.sessions.values():
7113
+ for key, session in self.sessions.items():
7061
7114
  if decision == "allow_always" and not pattern:
7062
7115
  session.tools.pop(tool, None)
7063
7116
  elif decision == "allow_server_always":
7064
7117
  session.servers.pop(server_id, None)
7065
- if rules and session.directory_rules is not None:
7118
+ if key == project and rules and session.directory_rules is not None:
7066
7119
  session.directory_rules = self._append_rules(session.directory_rules, rules)
7067
7120
 
7068
7121
  def evaluate_authorization(self, tool_name: str, raw_args: dict | None, context: SecurityContext,
@@ -7108,31 +7161,57 @@ class AccessController:
7108
7161
  return self._evaluate_path(tool_name, access, path, view, ctx)
7109
7162
  return POLICY_ASK, "mcp_default_ask", "", None
7110
7163
 
7164
+ @staticmethod
7165
+ def _has_full_directory_access(rules: list[str]) -> bool:
7166
+ """Indica si el proyecto tiene acceso RW a todo el sistema de ficheros (RW:/** o RW:/)."""
7167
+ return any(
7168
+ (parsed := parse_directory_rule(raw)) is not None
7169
+ and parsed["access"] == "RW"
7170
+ and parsed["path"] in ("/**", "/")
7171
+ for raw in rules
7172
+ )
7173
+
7174
+ @staticmethod
7175
+ def _command_target(cwd: Path, raw_path: str) -> str:
7176
+ return raw_path if re.match(r"^(/|[A-Za-z]:[\\/])", raw_path) else str(cwd / raw_path)
7177
+
7178
+ def _is_allowed_trust_segment(self, segment: str, cwd: Path, directory_rules: list[str], ctx: SecurityContext) -> bool:
7179
+ """Subcomando permitido por Workspace Trust: local o con argumentos de ruta dentro de reglas RW del proyecto."""
7180
+ refs = command_outside_references(segment)
7181
+ if refs is None:
7182
+ return False
7183
+ return all(
7184
+ self.evaluate_directory_rule("RW", self._command_target(cwd, ref), directory_rules, ctx)["allowed"]
7185
+ for ref in refs
7186
+ )
7187
+
7111
7188
  def _evaluate_command(self, raw_command: str, view: dict, ctx: SecurityContext) -> tuple[str, str, str, dict | None]:
7112
7189
  """
7113
7190
  Valida cada subcomando por separado: un cd tiene que llevar a una carpeta cubierta por las reglas
7114
7191
  de directorio, y los subcomandos siguientes se ejecutan en ella; el resto tiene que estar cubierto
7115
- por un patrón o, con Workspace Trust, quedarse en el proyecto (tras una tubería, solo un filtro).
7116
- Un patrón es una vía más de permitir, nunca una puerta que anule Workspace Trust.
7192
+ por un patrón o, con Workspace Trust, quedarse en el proyecto o en reglas RW del proyecto (tras una
7193
+ tubería, solo un filtro). Con RW:/** en Workspace Trust, el proyecto queda sin restricción de comandos.
7117
7194
  """
7195
+ trust = view["globalMcpPolicy"] == GLOBAL_POLICY_WORKSPACE_TRUST
7196
+ if trust and self._has_full_directory_access(view["directoryRules"]):
7197
+ return POLICY_ALLOW, "directory_rule_allow", "", None
7118
7198
  segments = split_command(raw_command)
7119
7199
  if segments is None:
7120
7200
  return (POLICY_ASK, "command_chaining_requires_approval",
7121
7201
  f"El comando usa sintaxis de shell que no se puede validar por partes: {raw_command}", None)
7122
7202
  patterns = self._command_patterns(view, ctx)
7123
- trust = view["globalMcpPolicy"] == GLOBAL_POLICY_WORKSPACE_TRUST
7124
7203
  cwd, by_trust, uncovered = ctx.workspace_dir, False, []
7125
7204
  for operator, segment in segments:
7126
7205
  directory = cd_target(segment)
7127
7206
  if directory is not None:
7128
- target = directory if re.match(r"^(/|[A-Za-z]:[\\/])", directory) else str(cwd / directory)
7207
+ target = self._command_target(cwd, directory)
7129
7208
  if not any(self.evaluate_directory_rule(a, target, view["directoryRules"], ctx)["allowed"] for a in ("R", "W")):
7130
7209
  return (POLICY_ASK, "command_directory_outside_rules",
7131
7210
  f"El comando se ejecuta fuera de las reglas de directorio: {directory}", None)
7132
- cwd = ctx.resolve_path(target)
7211
+ cwd = ctx.resolve_path(target) or cwd
7133
7212
  elif any(matches_command_pattern(segment, p) for p in patterns):
7134
7213
  continue
7135
- elif trust and is_workspace_local_command(segment) and (
7214
+ elif trust and self._is_allowed_trust_segment(segment, cwd, view["directoryRules"], ctx) and (
7136
7215
  operator != "|" or segment.split()[0] in WORKSPACE_TRUST_PIPE_FILTERS):
7137
7216
  by_trust = True
7138
7217
  else:
@@ -8575,6 +8654,16 @@ def with_job_key(args: dict, job_key: str | None) -> dict:
8575
8654
  return {**args, "job_key": job_key} if job_key else args
8576
8655
 
8577
8656
 
8657
+ def _security_deny_result(reason: str, detail: str = "") -> tuple[dict, None, str]:
8658
+ err_msg = f"Bloqueado por política de seguridad: {detail or reason}"
8659
+ return {
8660
+ "content": [{"type": "text", "text": f"Error: {err_msg}"}],
8661
+ "isError": True,
8662
+ "securityStatus": "deny",
8663
+ "reason": reason
8664
+ }, None, err_msg
8665
+
8666
+
8578
8667
  def authorize_or_challenge(origin: str, tool_name: str, args: dict, ctx: SecurityContext,
8579
8668
  job_key: str | None = None, conversation_id: str = "") -> tuple[dict | None, dict | None, str] | None:
8580
8669
  """Evalúa la política de seguridad y devuelve respuesta de denegación o reto si procede."""
@@ -8588,13 +8677,16 @@ def authorize_or_challenge(origin: str, tool_name: str, args: dict, ctx: Securit
8588
8677
  tool_name, args, context=ctx, server_name=server_name, server_id=server_id
8589
8678
  )
8590
8679
  if decision.status == POLICY_DENY:
8591
- err_msg = f"Bloqueado por política de seguridad: {decision.reason}"
8592
- return {"content": [{"type": "text", "text": f"Error: {err_msg}"}], "isError": True, "securityStatus": "deny", "reason": decision.reason}, None, err_msg
8680
+ return _security_deny_result(decision.reason)
8593
8681
  if decision.status == POLICY_ASK:
8594
8682
  session = current_run_session()
8595
- if session is not None and session.take_approved_call(tool_name, args):
8596
- log_event(f"[run] {tool_name}: se ejecuta la llamada que la persona aprobó al reanudar")
8597
- return None
8683
+ if session is not None:
8684
+ if session.take_approved_call(tool_name, args):
8685
+ log_event(f"[run] {tool_name}: se ejecuta la llamada que la persona aprobó al reanudar")
8686
+ return None
8687
+ if origin == "external":
8688
+ return None
8689
+ return _security_deny_result(decision.reason, decision.details)
8598
8690
  ch =ACCESS_CONTROLLER.create_challenge(
8599
8691
  tool_name, args, decision, server_name=server_name, server_id=server_id, origin=origin,
8600
8692
  context=ctx, job_key=job_key, conversation_id=conversation_id
@@ -9787,11 +9879,13 @@ def reset_session_authorizations():
9787
9879
  ACCESS_CONTROLLER.apply_tool_decision(tool_decision, ctx, server_id=server_id)
9788
9880
  permanent_tools = ACCESS_CONTROLLER.export_state(ctx).get("tools") or {}
9789
9881
  ACCESS_CONTROLLER.apply_session_overlay({
9790
- "globalMcpPolicy": GLOBAL_POLICY_ALLOW_ALL,
9882
+ "globalMcpPolicy": GLOBAL_POLICY_WORKSPACE_TRUST,
9791
9883
  "tools": {
9792
9884
  name: {"policy": POLICY_ALLOW}
9793
9885
  for name in LOCAL_TOOL_HANDLERS
9794
- if (permanent_tools.get(name) or {}).get("policy") != POLICY_DENY
9886
+ if name != COMMAND_TOOL
9887
+ and not get_integrated_path_access(name)
9888
+ and (permanent_tools.get(name) or {}).get("policy") != POLICY_DENY
9795
9889
  }
9796
9890
  }, ctx)
9797
9891
 
File without changes
File without changes
File without changes