Files
ai-agent/backend/toolproxy/matomo.py
gabrielvidalandClaude Opus 5.5 24b9723fd3 refactor(new-project): New project moves to a live plugin
backend/newproject/ (policy, form, service, store, routes, edge shim),
its schemas and test, and `notify new-project` are gone — the
`new-project` plugin (ai-agent-plugins) owns the form, the policy, the
quota, the approval and the scaffold. The core keeps the spawn, read off
the plugin's composer mode (plugins/waiting.composer_modes_for):

- /api/spawn newProject: refused unless the mode allows it; the guest
  staging dir/scope/note live in users/runs.py (the staging scope now
  carries the guest's tool proxy so the plugin's skill reaches the hub)
- /api/me.newProjects from the mode (None without the plugin)
- /api/users/{uid}/domain(+/setup) move to users/routes.py (users/edge.py)
- hub scaffold/relocate keeps the guest's tools + scope line
- plugins/carryover.new_project: /data/new-projects.json, the
  guestDefaults.newProjects policy and projects.create guests carried
  over once (requests.json, plugin config, managed grants)
- frontend: composer toggle / + New project entry driven by
  usePluginComposerModes(); Every guest drops the policy + requests
  (link to Settings → Plugins → New project); the Web address card stays,
  without the Can create projects switch

authz/matrix.golden.txt not updated (the coordinator regenerates it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:12:01 +01:00

348 lines
15 KiB
Python

"""
The ``analytics`` tool group: the lab's Matomo (``services/analytics``) for a
guest's own sites, with the superuser token kept on the hub.
Gabriel's picks (form ``ouliapo-analytics-via-matomo_9qad10``, 2026-11-11,
after he let Dom read Ouliapo's numbers): a per-guest switch, the guest's runs
create sites and read stats through the tool proxy, no Matomo login for them.
* **Whose site** — a Matomo site is a guest's when every one of its URLs is on
their address (``users/domains.py``: ``<bucket>.<domain>`` or their root
domain, and its subdomains). Nothing to record: Dom's ``domvidal.xyz`` makes
site 10 (``https://ouliapo.domvidal.xyz``) his, the owner's shared site 1
(``gabvdl.xyz``) is nobody's. A guest can only add sites on their address,
so that stays true.
* **Reading** — the Reporting API's ``get*`` methods of the report modules
below, on one of their sites; ``idSite`` is forced to that one id (no
``all``, no lists, no bulk requests).
* **A key for a page** — a static page (Ouliapo's moderator page) reads Matomo
from the browser over JSONP, so it needs a view-only token allowed over GET.
One Matomo user per guest (``guest-<uid>-viewer``) with view access to their
sites only, its app token kept here (``TOOLS_MATOMO_PATH``) and handed back on
each ``token`` call — ``rotate`` starts the viewer over (deleting a Matomo
user drops its keys; a password change would too, but Matomo then mails the
user and fails without a mail setup).
Free, counted in the tool ledger (``units.calls``).
"""
from __future__ import annotations
import json
import os
import pathlib
import re
import secrets
import threading
import time
from urllib.parse import urlsplit
import httpx
URL = (os.environ.get("MATOMO_URL") or "http://matomo:80").rstrip("/")
PUBLIC_URL = (os.environ.get("MATOMO_PUBLIC_URL") or "https://analytics.gabvdl.xyz").rstrip("/")
PATH = pathlib.Path(os.environ.get("TOOLS_MATOMO_PATH", "/data/tools-matomo.json"))
def admin_token() -> str:
return os.environ.get("MATOMO_TOKEN") or ""
def admin_password() -> str:
return os.environ.get("MATOMO_ADMIN_PASSWORD") or ""
# The report modules a guest may read (their ``get*`` methods), plus a few
# named methods. Left out on purpose: MultiSites / SitesManager listings (other
# people's sites), UsersManager, API.getBulkRequest, anything that writes.
READ_MODULES = ("VisitsSummary", "Actions", "Events", "Referrers", "UserCountry",
"DevicesDetection", "DevicePlugins", "Resolution", "VisitTime",
"VisitFrequency", "VisitorInterest", "Goals", "Transitions",
"PagePerformance", "CustomDimensions", "Contents", "UserLanguage",
"Live")
READ_EXTRA = ("API.get", "API.getProcessedReport", "API.getReportMetadata",
"API.getMatomoVersion")
_METHOD_RE = re.compile(r"^([A-Za-z]+)\.(get[A-Za-z]*)$")
# Parameters the proxy sets itself (or that would reach past the one site).
_FORCED = {"module", "method", "idsite", "token_auth", "format", "force_api_session",
"jsoncallback", "callback", "urls", "idsites"}
_HOST_RE = re.compile(r"^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$")
class MatomoError(Exception):
def __init__(self, status: int, message: str, kind: str = "matomo"):
super().__init__(message)
self.status, self.message, self.kind = status, message, kind
def method_ok(method: str) -> bool:
if method in READ_EXTRA:
return True
m = _METHOD_RE.match(method or "")
return bool(m) and m.group(1) in READ_MODULES
def host_of(raw: str) -> str:
s = (raw or "").strip().lower()
if "://" not in s:
s = "https://" + s
try:
host = urlsplit(s).hostname or ""
except ValueError:
return ""
return host.rstrip(".")
def on_base(host: str, base: str) -> bool:
base = (base or "").strip().lower().strip(".")
return bool(base) and (host == base or host.endswith("." + base))
def base_for(deps, uid: str) -> str:
"""What a guest's addresses end with (``dom`` → ``domvidal.xyz``)."""
from users import domains as user_domains
user = deps.users.get(uid) or {"id": uid}
bucket, domain = user_domains.address_of(user, user_domains.default_domain(deps))
return user_domains.base_of(bucket, domain)
def site_hosts(site: dict) -> list[str]:
urls = [site.get("main_url") or ""] + list(site.get("alias_urls") or [])
return [h for h in (host_of(u) for u in urls if u) if h]
def is_theirs(site: dict, base: str) -> bool:
hosts = site_hosts(site)
return bool(hosts) and all(on_base(h, base) for h in hosts)
# ── the store: each guest's viewer user and its token ────────────────────────
class Viewers:
def __init__(self, path: pathlib.Path = PATH):
self.path = pathlib.Path(path)
self._lock = threading.Lock()
def _read(self) -> dict:
try:
return json.loads(self.path.read_text())
except (OSError, ValueError):
return {}
def get(self, uid: str) -> dict:
with self._lock:
return dict(self._read().get(uid) or {})
def put(self, uid: str, rec: dict) -> None:
with self._lock:
d = self._read()
d[uid] = rec
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_suffix(".tmp")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
json.dump(d, f)
os.replace(tmp, self.path)
VIEWERS = Viewers()
# ── talking to Matomo ────────────────────────────────────────────────────────
class Matomo:
def __init__(self, client: httpx.AsyncClient):
self.client = client
async def call(self, method: str, params: dict | None = None, *,
token: str | None = None, anonymous: bool = False):
"""One API call, POSTed (the token in the body)."""
data = {"module": "API", "method": method, "format": "json"}
if not anonymous:
data["token_auth"] = token if token is not None else admin_token()
for k, v in (params or {}).items():
if v is None:
continue
data[k] = "1" if v is True else "0" if v is False else str(v)
try:
r = await self.client.post(f"{URL}/index.php", data=data,
timeout=httpx.Timeout(20.0, read=120.0))
except httpx.HTTPError as e:
raise MatomoError(502, f"Matomo is unreachable ({type(e).__name__})", "upstream")
try:
out = r.json()
except ValueError:
raise MatomoError(502, f"Matomo answered {r.status_code} without JSON", "upstream")
if isinstance(out, dict) and out.get("result") == "error":
raise MatomoError(400, f"Matomo: {out.get('message') or 'error'}", "matomo")
return out
async def all_sites(self) -> list[dict]:
"""Every site with all its URLs (``getAllSites`` gives only the main
one; ownership needs the aliases too)."""
out = await self.call("SitesManager.getAllSites")
sites = list(out.values()) if isinstance(out, dict) else list(out or [])
for s in sites:
urls = await self.call("SitesManager.getSiteUrlsFromId", {"idSite": s["idsite"]})
s["alias_urls"] = [u for u in (urls or []) if u != s.get("main_url")]
return sites
def public_site(site: dict) -> dict:
return {"id": int(site["idsite"]), "name": site.get("name") or "",
"urls": [site.get("main_url") or ""] + list(site.get("alias_urls") or []),
"created": (site.get("ts_created") or "")[:10],
"timezone": site.get("timezone") or ""}
def tracking_snippet(idsite: int) -> str:
return ("<script>\n var _paq = window._paq = window._paq || [];\n"
" _paq.push(['disableCookies']);\n"
" _paq.push(['trackPageView']);\n _paq.push(['enableLinkTracking']);\n"
" (function() {\n"
f" var u='{PUBLIC_URL}/';\n"
" _paq.push(['setTrackerUrl', u+'matomo.php']);\n"
f" _paq.push(['setSiteId', '{idsite}']);\n"
" var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];\n"
" g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);\n"
" })();\n</script>")
async def sites_of(m: Matomo, deps, uid: str | None) -> list[dict]:
sites = await m.all_sites()
if uid is None:
return sites
base = base_for(deps, uid)
return [s for s in sites if is_theirs(s, base)]
async def site_for(m: Matomo, deps, uid: str | None, idsite) -> dict:
try:
sid = int(str(idsite).strip())
except (TypeError, ValueError):
raise MatomoError(400, "site must be one Matomo site id (a number)", "site")
for s in await sites_of(m, deps, uid):
if int(s["idsite"]) == sid:
return s
raise MatomoError(404, f"no site {sid} of yours — `matomo sites` lists them", "site")
# ── the operations ───────────────────────────────────────────────────────────
async def op_sites(m: Matomo, deps, uid: str | None, body: dict) -> dict:
sites = await sites_of(m, deps, uid)
out = {"sites": [public_site(s) for s in sites], "matomo": PUBLIC_URL + "/"}
if uid is not None:
out["base"] = base_for(deps, uid)
return out
async def op_add_site(m: Matomo, deps, uid: str | None, body: dict) -> dict:
host = host_of(str(body.get("url") or body.get("host") or ""))
if not _HOST_RE.match(host):
raise MatomoError(400, "give the site's address (https://<name>.<your domain>)", "url")
if uid is not None:
base = base_for(deps, uid)
if not on_base(host, base):
raise MatomoError(403, f"{host} isn't one of your addresses — a site of yours is "
f"on {base}", "url")
for s in await m.all_sites():
if host in site_hosts(s):
if uid is None or is_theirs(s, base_for(deps, uid)):
return {"site": public_site(s), "created": False,
"tracking": tracking_snippet(int(s["idsite"]))}
raise MatomoError(409, f"{host} already has a Matomo site", "exists")
name = str(body.get("name") or host.split(".")[0])[:90]
out = await m.call("SitesManager.addSite", {
"siteName": name, "urls[0]": f"https://{host}", "timezone": "Europe/Paris",
"ecommerce": False, "excludedUserAgents": "HeadlessChrome"})
idsite = int(out["value"] if isinstance(out, dict) else out)
if uid is not None:
# Their viewer, when they already have one, sees the new site too.
rec = VIEWERS.get(uid)
if rec.get("login"):
await m.call("UsersManager.setUserAccess", {
"userLogin": rec["login"], "access": "view", "idSites": idsite,
"passwordConfirmation": admin_password()})
site = await site_for(m, deps, uid, idsite)
return {"site": public_site(site), "created": True, "tracking": tracking_snippet(idsite)}
async def op_report(m: Matomo, deps, uid: str | None, body: dict) -> object:
method = str(body.get("method") or "")
if not method_ok(method):
raise MatomoError(403, f"{method or 'that method'} isn't open through the hub — the "
"Reporting API's get* methods of the report modules are "
f"({', '.join(READ_MODULES)})", "method")
site = await site_for(m, deps, uid, body.get("site"))
params = {k: v for k, v in (body.get("params") or {}).items()
if isinstance(k, str) and k.lower() not in _FORCED
and isinstance(v, (str, int, float, bool))}
params.setdefault("period", "day")
params.setdefault("date", "today")
params["idSite"] = int(site["idsite"])
return await m.call(method, params)
async def op_tracking(m: Matomo, deps, uid: str | None, body: dict) -> dict:
site = await site_for(m, deps, uid, body.get("site"))
return {"site": public_site(site), "tracking": tracking_snippet(int(site["idsite"]))}
async def _ensure_viewer(m: Matomo, deps, uid: str, ids: list[int]) -> dict:
rec = VIEWERS.get(uid)
login = rec.get("login") or f"guest-{uid}-viewer"
if not rec.get("password"):
pw = secrets.token_urlsafe(24)
add = {"userLogin": login, "password": pw, "email": f"{login}@guests.invalid",
"passwordConfirmation": admin_password()}
try:
await m.call("UsersManager.addUser", add)
except MatomoError:
# A viewer left from a lost store (its password unknown here):
# start it over.
await m.call("UsersManager.deleteUser", {
"userLogin": login, "passwordConfirmation": admin_password()})
await m.call("UsersManager.addUser", add)
rec = {"login": login, "password": pw, "t": time.time()}
VIEWERS.put(uid, rec)
if ids:
await m.call("UsersManager.setUserAccess", {
"userLogin": login, "access": "view", "idSites": ",".join(map(str, ids)),
"passwordConfirmation": admin_password()})
return rec
async def op_token(m: Matomo, deps, uid: str | None, body: dict) -> dict:
if uid is None:
raise MatomoError(400, "the owner has the superuser token already — this mints a "
"guest's view-only key", "owner")
ids = [int(s["idsite"]) for s in await sites_of(m, deps, uid)]
if not ids:
raise MatomoError(404, "you have no Matomo site yet — `matomo add-site <url>` first",
"site")
rec = VIEWERS.get(uid)
rotated = bool(rec.get("token")) and bool(body.get("rotate"))
if rotated:
# Rotating: a fresh viewer user (deleting it drops every key it had —
# a password change would, but Matomo then mails the user and fails
# without a mail setup).
try:
await m.call("UsersManager.deleteUser", {
"userLogin": rec["login"], "passwordConfirmation": admin_password()})
except MatomoError:
pass
VIEWERS.put(uid, {})
rec = await _ensure_viewer(m, deps, uid, ids)
if rec.get("token"):
return {"token": rec["token"], "login": rec["login"], "sites": ids, "rotated": False}
# Matomo mints an app token only for the user asking, with its password:
# an anonymous call that names the viewer.
out = await m.call("UsersManager.createAppSpecificTokenAuth", {
"userLogin": rec["login"], "passwordConfirmation": rec["password"],
"description": f"ai-agent hub — {uid}'s view-only key"}, anonymous=True)
token = out["value"] if isinstance(out, dict) else str(out)
VIEWERS.put(uid, {**rec, "token": token, "tokenAt": time.time()})
return {"token": token, "login": rec["login"], "sites": ids, "rotated": rotated}
OPS = {"sites": op_sites, "add-site": op_add_site, "report": op_report,
"tracking": op_tracking, "token": op_token}