zerochat 10.40.0__tar.gz → 10.41.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.40.0
3
+ Version: 10.41.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.40.0"
7
+ version = "10.41.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.40.0
3
+ Version: 10.41.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
@@ -35,6 +35,7 @@ import json
35
35
  import math
36
36
  import os
37
37
  import queue
38
+ import random
38
39
  import re
39
40
  import secrets
40
41
  import select
@@ -1132,7 +1133,7 @@ def parse_nonneg_int(value, label: str, default: int = 0) -> int:
1132
1133
 
1133
1134
 
1134
1135
 
1135
- SOURCE_BACKEND_VERSION = "10.40.0"
1136
+ SOURCE_BACKEND_VERSION = "10.41.0"
1136
1137
 
1137
1138
 
1138
1139
  def _read_source_version(filename: str) -> str | None:
@@ -3816,13 +3817,32 @@ def list_project_secret_names(project_key: str) -> list[str]:
3816
3817
 
3817
3818
  def save_project_secret(project_key: str, name: str, value: str) -> list[str]:
3818
3819
  clean_name = validate_project_secret_name(name)
3820
+ if not isinstance(value, str) or not value.strip():
3821
+ raise ValueError("El secreto no puede estar vacío")
3822
+ clean_val = value.strip()
3823
+ if len(clean_val) > MAX_SECRET_LENGTH:
3824
+ raise ValueError(f"El secreto no puede superar {MAX_SECRET_LENGTH} caracteres")
3819
3825
  prefix = project_secret_prefix(project_key)
3820
- existing = secret_names(prefix)
3821
3826
  full_key = f"{prefix}{clean_name}"
3822
- if full_key not in existing and len(existing) >= MAX_PROJECT_SECRETS:
3823
- raise ValueError(f"Un proyecto no puede tener más de {MAX_PROJECT_SECRETS} secretos")
3824
- save_secret(full_key, value)
3825
- return list_project_secret_names(project_key)
3827
+ now = int(time.time() * 1000)
3828
+ with open_storage() as conn:
3829
+ conn.isolation_level = None
3830
+ conn.execute("BEGIN IMMEDIATE;")
3831
+ try:
3832
+ rows = conn.execute(
3833
+ "SELECT name FROM secrets WHERE substr(name, 1, ?) = ?;",
3834
+ (len(prefix), prefix),
3835
+ ).fetchall()
3836
+ existing = {row["name"] for row in rows}
3837
+ if full_key not in existing and len(existing) >= MAX_PROJECT_SECRETS:
3838
+ raise ValueError(f"Un proyecto no puede tener más de {MAX_PROJECT_SECRETS} secretos")
3839
+ _write_secret_on_conn(conn, full_key, clean_val, now)
3840
+ conn.execute("COMMIT;")
3841
+ existing.add(full_key)
3842
+ except Exception:
3843
+ conn.execute("ROLLBACK;")
3844
+ raise
3845
+ return sorted(key[len(prefix):] for key in existing)
3826
3846
 
3827
3847
 
3828
3848
  def delete_project_secret(project_key: str, name: str) -> list[str]:
@@ -3850,28 +3870,47 @@ def delete_project_storage(project_key: str) -> list[str]:
3850
3870
  return deleted_ids
3851
3871
 
3852
3872
 
3873
+ def _has_prefix_match(conn: sqlite3.Connection, query: str, p1: str, p2: str) -> bool:
3874
+ return conn.execute(query, (len(p1), p1, len(p2), p2)).fetchone() is not None
3875
+
3876
+
3853
3877
  def has_nested_project_data(project_key: str) -> bool:
3854
- """True si existen entornos, políticas o conversaciones guardadas de subproyectos bajo `project_key`."""
3878
+ """True si existen entornos, políticas, secretos o conversaciones guardadas de subproyectos bajo `project_key`."""
3855
3879
  clean_key = str(project_key or "").strip().rstrip("/\\")
3856
3880
  if not clean_key:
3857
3881
  return False
3858
- prefixes = (f"{clean_key}/%", f"{clean_key}\\%")
3859
- policy_prefixes = (f"{PROJECT_SECURITY_POLICY_PREFIX}{clean_key}/%", f"{PROJECT_SECURITY_POLICY_PREFIX}{clean_key}\\%")
3882
+ p_slash, p_back = f"{clean_key}/", f"{clean_key}\\"
3883
+ pol_slash = f"{PROJECT_SECURITY_POLICY_PREFIX}{p_slash}"
3884
+ pol_back = f"{PROJECT_SECURITY_POLICY_PREFIX}{p_back}"
3885
+ sec_slash, sec_back = f"project:{p_slash}", f"project:{p_back}"
3860
3886
  with open_storage() as conn:
3861
- if conn.execute(
3862
- "SELECT 1 FROM project_environments WHERE project_key LIKE ? OR project_key LIKE ? LIMIT 1;",
3863
- prefixes,
3864
- ).fetchone():
3887
+ if _has_prefix_match(
3888
+ conn,
3889
+ "SELECT 1 FROM project_environments WHERE substr(project_key, 1, ?) = ? OR substr(project_key, 1, ?) = ? LIMIT 1;",
3890
+ p_slash,
3891
+ p_back,
3892
+ ):
3865
3893
  return True
3866
- if conn.execute(
3867
- "SELECT 1 FROM security_policies WHERE id LIKE ? OR id LIKE ? LIMIT 1;",
3868
- policy_prefixes,
3869
- ).fetchone():
3894
+ if _has_prefix_match(
3895
+ conn,
3896
+ "SELECT 1 FROM security_policies WHERE substr(id, 1, ?) = ? OR substr(id, 1, ?) = ? LIMIT 1;",
3897
+ pol_slash,
3898
+ pol_back,
3899
+ ):
3870
3900
  return True
3871
- if conn.execute(
3872
- "SELECT 1 FROM conversations WHERE json_extract(extra_json, '$.project') LIKE ? OR json_extract(extra_json, '$.project') LIKE ? LIMIT 1;",
3873
- prefixes,
3874
- ).fetchone():
3901
+ if _has_prefix_match(
3902
+ conn,
3903
+ "SELECT 1 FROM secrets WHERE substr(name, 1, ?) = ? OR substr(name, 1, ?) = ? LIMIT 1;",
3904
+ sec_slash,
3905
+ sec_back,
3906
+ ):
3907
+ return True
3908
+ if _has_prefix_match(
3909
+ conn,
3910
+ "SELECT 1 FROM conversations WHERE substr(json_extract(extra_json, '$.project'), 1, ?) = ? OR substr(json_extract(extra_json, '$.project'), 1, ?) = ? LIMIT 1;",
3911
+ p_slash,
3912
+ p_back,
3913
+ ):
3875
3914
  return True
3876
3915
  return False
3877
3916
 
@@ -3883,27 +3922,59 @@ def has_nested_project_data(project_key: str) -> bool:
3883
3922
 
3884
3923
 
3885
3924
  # Configuración del navegador de Playwright MCP (sección Navegador de Ajustes).
3886
- # Modo propio: un motor de Playwright en memoria (--isolated), o con almacenamiento persistente con nombre
3887
- # en ~/zerochat/playwright/profile/<motor>/<nombre>.
3925
+ # Modo propio: un motor de Playwright o canal del sistema en memoria (--isolated), o con almacenamiento
3926
+ # persistente con nombre en ~/zerochat/playwright/profile/<motor>/<nombre>.
3888
3927
  # Modo del usuario: su Chrome, Edge o Chromium mediante la extensión de Playwright (--extension).
3889
3928
  BROWSER_MODES = ("own", "user")
3890
3929
  OWN_BROWSER_ENGINES = ("chromium", "firefox", "webkit")
3930
+ OWN_SYSTEM_ENGINES = ("chrome", "msedge")
3931
+ ALL_OWN_ENGINES = (*OWN_BROWSER_ENGINES, *OWN_SYSTEM_ENGINES)
3891
3932
  USER_BROWSERS = ("chrome", "msedge", "chromium")
3892
- BROWSER_CONFIG_DEFAULTS = {"mode": "own", "engine": "chromium", "userBrowser": "chrome", "headless": True, "extensionToken": ""}
3933
+ USER_AGENT_MODES = ("auto", "rotate", "custom")
3934
+ USER_AGENT_MAX_LEN = 512
3935
+ BROWSER_CONFIG_DEFAULTS = {
3936
+ "mode": "own",
3937
+ "engine": "chromium",
3938
+ "userBrowser": "chrome",
3939
+ "headless": True,
3940
+ "extensionToken": "",
3941
+ "userAgentMode": "auto",
3942
+ "userAgent": "",
3943
+ }
3893
3944
  BROWSER_CONFIG_KEY = "browser"
3945
+ LAST_FRONTEND_USER_AGENT_KEY = "browser:last_user_agent"
3894
3946
  BROWSER_EXTENSION_TOKEN_KEY = "browser:extension_token" # noqa: S105 - nombre de fila en la tabla secrets
3895
3947
  # Identificador de la extensión de Playwright en la tienda de Chrome, que también usa Edge.
3896
3948
  PLAYWRIGHT_SERVER_ID = "playwright"
3897
3949
  PLAYWRIGHT_EXTENSION_ID = "mmlmfjhmonkocbjadbfplnigmagldckm"
3898
3950
  # Token que muestra la extensión: con él la conexión no pide aceptarla en el navegador.
3899
3951
  _EXTENSION_TOKEN = re.compile(r"^[A-Za-z0-9_-]{0,256}$")
3900
- _BROWSER_CONFIG_CHOICES = {"mode": BROWSER_MODES, "engine": OWN_BROWSER_ENGINES, "userBrowser": USER_BROWSERS}
3952
+ _BROWSER_CONFIG_CHOICES = {
3953
+ "mode": BROWSER_MODES,
3954
+ "engine": ALL_OWN_ENGINES,
3955
+ "userBrowser": USER_BROWSERS,
3956
+ "userAgentMode": USER_AGENT_MODES,
3957
+ }
3958
+ MODERN_USER_AGENTS = (
3959
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
3960
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
3961
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",
3962
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36 Edg/142.0.0.0",
3963
+ )
3901
3964
 
3902
3965
 
3903
3966
  def own_browser_profile_dir(engine: str) -> Path:
3904
3967
  return get_data_dir() / "playwright" / "profile" / engine
3905
3968
 
3906
3969
 
3970
+ def _validate_user_agent(value) -> str:
3971
+ if not isinstance(value, str):
3972
+ raise ValueError("userAgent debe ser una cadena")
3973
+ if len(value) > USER_AGENT_MAX_LEN or any(ch in value for ch in ("\r", "\n", "\x00")):
3974
+ raise ValueError(f"userAgent debe tener hasta {USER_AGENT_MAX_LEN} caracteres sin saltos de línea")
3975
+ return value.strip()
3976
+
3977
+
3907
3978
  def validate_browser_config(raw) -> dict:
3908
3979
  """Devuelve la configuración completa o lanza ValueError; los campos que faltan toman su valor por defecto."""
3909
3980
  if not isinstance(raw, dict):
@@ -3919,6 +3990,9 @@ def validate_browser_config(raw) -> dict:
3919
3990
  raise ValueError("headless debe ser un booleano")
3920
3991
  if not isinstance(config["extensionToken"], str) or not _EXTENSION_TOKEN.match(config["extensionToken"]):
3921
3992
  raise ValueError("extensionToken debe tener hasta 256 letras, cifras, guiones o guiones bajos")
3993
+ config["userAgent"] = _validate_user_agent(config["userAgent"])
3994
+ if config["userAgentMode"] == "custom" and not config["userAgent"]:
3995
+ raise ValueError("userAgent es obligatorio cuando userAgentMode es custom")
3922
3996
  return config
3923
3997
 
3924
3998
 
@@ -3989,20 +4063,65 @@ def playwright_launch_env(config: dict) -> dict[str, str]:
3989
4063
  return {}
3990
4064
 
3991
4065
 
3992
- def _playwright_launch(user_agent: str | None = None) -> tuple[list[str], dict[str, str]]:
4066
+ def _playwright_launch(service_user_agent: str | None = None) -> tuple[list[str], dict[str, str]]:
3993
4067
  """Argumentos y entorno de Playwright MCP según la configuración guardada."""
3994
4068
  config = load_browser_config()
3995
- return playwright_launch_args(config, user_agent), playwright_launch_env(config)
4069
+ effective_ua = resolve_playwright_user_agent(config, service_user_agent)
4070
+ return playwright_launch_args(config, effective_ua), playwright_launch_env(config)
3996
4071
 
3997
4072
 
3998
4073
  # User-Agent que usan los motores propios de Playwright; lo fija el servidor con el User-Agent
3999
- # activo de las salidas web (ff-server) para que ambos compartan el mismo fingerprint.
4074
+ # activo de las salidas web (web/fetch) para que ambos compartan el mismo fingerprint.
4000
4075
  SERVICE_USER_AGENT: str | None = None
4076
+ _FRONTEND_USER_AGENT_CAPTURED: bool = False
4001
4077
 
4002
4078
 
4003
- def set_service_user_agent(user_agent: str | None) -> None:
4004
- global SERVICE_USER_AGENT
4079
+ def set_service_user_agent(user_agent: str | None, *, from_frontend: bool = False) -> None:
4080
+ global SERVICE_USER_AGENT, _FRONTEND_USER_AGENT_CAPTURED
4005
4081
  SERVICE_USER_AGENT = user_agent
4082
+ _FRONTEND_USER_AGENT_CAPTURED = from_frontend
4083
+
4084
+
4085
+ def load_last_frontend_user_agent() -> str | None:
4086
+ """Último User-Agent real capturado del navegador y guardado en SQLite, o None si no hay."""
4087
+ try:
4088
+ stored = get_setting(LAST_FRONTEND_USER_AGENT_KEY)
4089
+ except (OSError, ValueError, TypeError, sqlite3.Error):
4090
+ return None
4091
+ if not isinstance(stored, str):
4092
+ return None
4093
+ cleaned = stored.strip()
4094
+ if not cleaned or len(cleaned) > USER_AGENT_MAX_LEN or any(ch in cleaned for ch in ("\r", "\n", "\x00")):
4095
+ return None
4096
+ return cleaned
4097
+
4098
+
4099
+ def save_last_frontend_user_agent(user_agent: str) -> None:
4100
+ """Persiste en SQLite el User-Agent real del navegador para reutilizarlo en ejecuciones desatendidas."""
4101
+ try:
4102
+ cleaned = _validate_user_agent(user_agent)
4103
+ if cleaned:
4104
+ set_setting(LAST_FRONTEND_USER_AGENT_KEY, cleaned)
4105
+ except (OSError, ValueError, TypeError, sqlite3.Error):
4106
+ return
4107
+
4108
+
4109
+ def resolve_playwright_user_agent(config: dict, service_user_agent: str | None = None) -> str | None:
4110
+ """User-Agent efectivo para un arranque de Playwright en modo propio según userAgentMode."""
4111
+ mode = config.get("userAgentMode", "auto")
4112
+ if mode == "custom":
4113
+ custom = config.get("userAgent", "").strip()
4114
+ if custom:
4115
+ return custom
4116
+ if mode == "rotate":
4117
+ candidates: list[str] = []
4118
+ for candidate in (load_last_frontend_user_agent(), *MODERN_USER_AGENTS, service_user_agent):
4119
+ if isinstance(candidate, str) and candidate.strip() and candidate not in candidates:
4120
+ candidates.append(candidate)
4121
+ return random.choice(candidates) if candidates else service_user_agent # noqa: S311 - rotación de fingerprint, no criptografía
4122
+ if _FRONTEND_USER_AGENT_CAPTURED and service_user_agent:
4123
+ return service_user_agent
4124
+ return load_last_frontend_user_agent() or service_user_agent
4006
4125
 
4007
4126
 
4008
4127
  # Argumentos y entorno que añade ZeroChat al arrancar un servicio gestionado,
@@ -4032,8 +4151,8 @@ def _playwright_active() -> bool:
4032
4151
 
4033
4152
  def clear_own_browser_data(engine) -> dict:
4034
4153
  """Borra el perfil persistente del motor (cookies, sesiones, almacenamiento de los sitios)."""
4035
- if engine not in OWN_BROWSER_ENGINES:
4036
- raise ValueError(f"engine debe ser uno de: {', '.join(OWN_BROWSER_ENGINES)}")
4154
+ if engine not in ALL_OWN_ENGINES:
4155
+ raise ValueError(f"engine debe ser uno de: {', '.join(ALL_OWN_ENGINES)}")
4037
4156
  # El navegador abierto tiene el perfil bloqueado y volvería a escribirlo.
4038
4157
  if _playwright_active():
4039
4158
  raise ValueError("Detén Playwright MCP antes de borrar los datos del navegador.")
@@ -6117,14 +6236,16 @@ def browser_action(action: str, url: str | None = None, selector: str | None = N
6117
6236
  BROWSER_SECRET_MODES = ("input", "keypad")
6118
6237
 
6119
6238
 
6239
+ def _scrub_secret(text: str, secret_value: str) -> str:
6240
+ return text.replace(secret_value, "***") if secret_value and text else text
6241
+
6242
+
6120
6243
  def _mcp_call_error(tool_name: str, arguments: dict, secret_value: str) -> str | None:
6121
6244
  result = GLOBAL_MCP_MANAGER.call(public_tool_name(PLAYWRIGHT_SERVER_ID, tool_name), arguments)
6122
6245
  if not (isinstance(result, dict) and result.get("isError")):
6123
6246
  return None
6124
6247
  parts = [str(item.get("text") or "") for item in (result.get("content") or []) if isinstance(item, dict)]
6125
- detail = " ".join(p for p in parts if p).strip()
6126
- if secret_value and detail:
6127
- detail = detail.replace(secret_value, "***")
6248
+ detail = _scrub_secret(" ".join(p for p in parts if p).strip(), secret_value)
6128
6249
  return detail or f"Playwright {tool_name} failed."
6129
6250
 
6130
6251
 
@@ -6197,7 +6318,7 @@ def browser_fill_secret(
6197
6318
  else _fill_keypad_secret(secret_value, keypad_map)
6198
6319
  )
6199
6320
  except Exception as exc:
6200
- return _tool_error(f"Error ejecutando Playwright MCP: {exc}")
6321
+ return _tool_error(f"Error ejecutando Playwright MCP: {_scrub_secret(str(exc), secret_value)}")
6201
6322
  if err:
6202
6323
  return _tool_error(err)
6203
6324
  payload: dict = {"success": True, "mode": mode, "secret": secret}
@@ -10155,18 +10276,27 @@ METADATA_HOSTS = frozenset({
10155
10276
  "instance-data",
10156
10277
  "100.100.100.200",
10157
10278
  })
10158
- DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
10279
+ DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36"
10159
10280
  # El User-Agent activo se sustituye por el de la primera petición del frontend (variabilidad de
10160
- # fingerprint); sin frontend (--prompt/--conversation) se queda el valor por defecto.
10281
+ # fingerprint); sin frontend (--prompt/--conversation) se usa el último guardado o el por defecto.
10161
10282
  ACTIVE_USER_AGENT = DEFAULT_USER_AGENT
10162
10283
 
10163
10284
 
10164
10285
  def capture_frontend_user_agent(user_agent: str) -> None:
10165
- """Adopta el User-Agent de la primera petición del frontend como User-Agent de las salidas web."""
10286
+ """Adopta y persiste el User-Agent de la primera petición del frontend para las salidas web y Playwright."""
10166
10287
  global ACTIVE_USER_AGENT
10167
- if ACTIVE_USER_AGENT is DEFAULT_USER_AGENT and isinstance(user_agent, str) and user_agent.strip():
10168
- ACTIVE_USER_AGENT = user_agent.strip()
10169
- set_service_user_agent(ACTIVE_USER_AGENT)
10288
+ cleaned = user_agent.strip() if isinstance(user_agent, str) else ""
10289
+ if ACTIVE_USER_AGENT is DEFAULT_USER_AGENT and cleaned:
10290
+ ACTIVE_USER_AGENT = cleaned
10291
+ set_service_user_agent(ACTIVE_USER_AGENT, from_frontend=True)
10292
+ save_last_frontend_user_agent(cleaned)
10293
+
10294
+
10295
+ def effective_user_agent() -> str:
10296
+ """User-Agent activo del servidor o, en desatendido sin frontend, el último capturado del navegador."""
10297
+ if ACTIVE_USER_AGENT is not DEFAULT_USER_AGENT:
10298
+ return ACTIVE_USER_AGENT
10299
+ return load_last_frontend_user_agent() or DEFAULT_USER_AGENT
10170
10300
 
10171
10301
 
10172
10302
  # Los motores propios de Playwright arrancan con el User-Agent por defecto hasta que el
@@ -10296,7 +10426,7 @@ def _fetch_web_resource_unpaced(url: str, params: dict, hostname: str, parsed, t
10296
10426
  as_binary = bool(params.get("binary", False))
10297
10427
  accept = params.get("accept")
10298
10428
  req_headers = {
10299
- "User-Agent": ACTIVE_USER_AGENT,
10429
+ "User-Agent": effective_user_agent(),
10300
10430
  "Accept": accept if isinstance(accept, str) and accept else "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
10301
10431
  "Accept-Language": "es-ES,es;q=0.9,en;q=0.8",
10302
10432
  "Accept-Encoding": "gzip, deflate",
File without changes
File without changes
File without changes