Skip to content

Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.

fix(matomo): store the API token in ~/.config/claude-seo, not settings.json

Agrici Daniel56f3365f166b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c016934..aa5dc54 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,7 +18,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
Response parsing is verified live against Matomo 5, including array-shaped
DataTables, count-based bounce fields, `Referrers.getReferrerType` naming,
and locale-independent anonymized-keyword detection via the row `segment`
- field. (#275)
+ field. Credentials live in `~/.config/claude-seo/matomo.json` (0600, written
+ atomically), with the `MATOMO_URL` / `MATOMO_API_TOKEN` / `MATOMO_SITE_ID`
+ environment variables still taking precedence. Every request to the instance
+ goes through `url_safety`'s DNS-pinned helpers; a self-hosted instance on a
+ private address is reached by naming it in `CLAUDE_SEO_LOCAL_TARGETS`, which
+ both installers print at install time, and a redirect away from the instance
+ is refused rather than followed. (#275)
### Changed
diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md
index 79da961..097cdcc 100644
--- a/docs/COMMANDS.md
+++ b/docs/COMMANDS.md
@@ -678,7 +678,7 @@ Bing Webmaster Tools + IndexNow (extension). **Prerequisites:** Bing extension i
### `/seo matomo [command] [site-id]`
-Matomo Reporting API (extension). **Prerequisites:** Matomo extension installed (`./extensions/matomo/install.sh`) with `MATOMO_URL`, `MATOMO_API_TOKEN`, and optionally `MATOMO_SITE_ID`. Works against self-hosted Matomo or Matomo Cloud.
+Matomo Reporting API (extension). **Prerequisites:** Matomo extension installed (`./extensions/matomo/install.sh`), which writes the instance URL, API token, and optional default site ID to `~/.config/claude-seo/matomo.json` (0600). `MATOMO_URL`, `MATOMO_API_TOKEN`, and `MATOMO_SITE_ID` in the environment override the file. Works against self-hosted Matomo or Matomo Cloud; an instance on a private address must be named in `CLAUDE_SEO_LOCAL_TARGETS`.
Use as a GA4 alternative or supplement when you want full data ownership, no Google dependency, or privacy-first analytics.
```
diff --git a/extensions/matomo/docs/MATOMO-SETUP.md b/extensions/matomo/docs/MATOMO-SETUP.md
index 3e07571..22db383 100644
--- a/extensions/matomo/docs/MATOMO-SETUP.md
+++ b/extensions/matomo/docs/MATOMO-SETUP.md
@@ -26,9 +26,21 @@ You'll be prompted for:
- Default `idSite` (optional, e.g. `1`) — saves having to pass
`--site-id` on every call
-The installer writes `MATOMO_URL`, `MATOMO_API_TOKEN`, and
-`MATOMO_SITE_ID` (if set) to `~/.claude/settings.json` under `env`
-with `0o600` permissions.
+The installer writes them to `~/.config/claude-seo/matomo.json` with `0600`
+permissions, atomically (temp file plus rename, so a crash never leaves a
+half-written or truncated credential file). This is the same location and the
+same guarded write pattern the `backlinks_auth` module uses for the Moz and
+Bing keys. The token is deliberately kept out of `~/.claude/settings.json`,
+which is a general-purpose config file that tooling reads, prints, and syncs.
+
+Environment variables still take precedence for any field the file does not
+supply, and remain the right choice on a shared machine or in CI:
+
+```bash
+export MATOMO_URL="https://analytics.example.com"
+export MATOMO_API_TOKEN="...32 hex..."
+export MATOMO_SITE_ID="1"
+```
## Token setup checklist
@@ -108,13 +120,18 @@ have both GA4 and Matomo configured.
./extensions/matomo/uninstall.sh
```
+This removes the skill, the agent, and
+`~/.config/claude-seo/matomo.json`, and clears any `MATOMO_*` entries a
+pre-v2.4.0 installer had left in `~/.claude/settings.json`.
+
PowerShell manual removal:
```powershell
Remove-Item -Recurse -Force "$HOME\.claude\skills\seo-matomo"
Remove-Item -Force "$HOME\.claude\agents\seo-matomo.md"
-notepad "$HOME\.claude\settings.json"
+Remove-Item -Force "$HOME\.config\claude-seo\matomo.json"
```
-In `settings.json`, remove `MATOMO_URL`, `MATOMO_API_TOKEN`, and
-`MATOMO_SITE_ID` from the top-level `env` object.
\ No newline at end of file
+If you installed a pre-v2.4.0 build, also open `~/.claude/settings.json` and
+remove `MATOMO_URL`, `MATOMO_API_TOKEN`, and `MATOMO_SITE_ID` from the
+top-level `env` object.
\ No newline at end of file
diff --git a/extensions/matomo/install.ps1 b/extensions/matomo/install.ps1
index 35d2743..15dc231 100644
--- a/extensions/matomo/install.ps1
+++ b/extensions/matomo/install.ps1
@@ -2,7 +2,6 @@ $ErrorActionPreference = "Stop"
if (-not (Get-Command python -ErrorAction SilentlyContinue)) { throw "Python 3 required" }
$SkillDir = Join-Path $HOME ".claude/skills"
$AgentsDir = Join-Path $HOME ".claude/agents"
-$SettingsJson = Join-Path $HOME ".claude/settings.json"
if (-not (Test-Path (Join-Path $SkillDir "seo"))) { throw "claude-seo not installed" }
$MatomoUrl = Read-Host "Matomo instance URL (e.g. https://analytics.example.com)"
if (-not $MatomoUrl) { throw "Matomo URL required" }
@@ -31,22 +30,32 @@ Copy-Item (Join-Path $SourceDir "skills/seo-matomo/SKILL.md") (Join-Path $SkillT
$AgentTarget = Join-Path $AgentsDir "seo-matomo.md"
New-Item -ItemType Directory -Path $AgentsDir -Force | Out-Null
Copy-Item (Join-Path $SourceDir "agents/seo-matomo.md") $AgentTarget -Force
+# Credentials go to ~/.config/claude-seo/matomo.json (0600 on POSIX, an
+# icacls-restricted ACL on Windows), written atomically via os.replace, not
+# into ~/.claude/settings.json: settings.json is a general-purpose config file
+# that tooling reads, prints, and syncs, and an API token has no business in
+# it. matomo_auth.py still falls back to the MATOMO_* environment variables.
+if (-not (Test-Path $MatomoAuth)) { throw "$MatomoAuth not found" }
$py = @"
-import json, os, sys, tempfile
-path, url, token, site = sys.argv[1:5]
-data = {}
-if os.path.exists(path):
- try: data = json.load(open(path))
- except: data = {}
-env = data.setdefault('env', {})
-env['MATOMO_URL'] = url
-env['MATOMO_API_TOKEN'] = token
-if site:
- env['MATOMO_SITE_ID'] = site
-fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path) or '.', prefix='.settings.', suffix='.json')
-with os.fdopen(fd, 'w') as fh:
- json.dump(data, fh, indent=2)
-os.replace(tmp, path)
+import importlib.util, sys
+
+# PowerShell 5.1 drops an empty string argument to a native command, so the
+# optional site ID may simply not arrive. Tolerate that rather than crashing
+# the installer after the token has already been typed.
+args = sys.argv[1:]
+auth_path, url, token = args[0], args[1], args[2]
+site = args[3] if len(args) > 3 else ""
+spec = importlib.util.spec_from_file_location('matomo_auth', auth_path)
+matomo_auth = importlib.util.module_from_spec(spec)
+sys.modules['matomo_auth'] = matomo_auth
+spec.loader.exec_module(matomo_auth)
+
+matomo_auth.save_config({
+ 'matomo_url': url,
+ 'matomo_token': token,
+ 'matomo_site_id': site,
+})
+print('Wrote Matomo credentials to ' + matomo_auth.CONFIG_PATH)
"@
-$py | python - $SettingsJson $MatomoUrl $TokenPlain $SiteId
-Write-Host "Done."
\ No newline at end of file
+$py | python - $MatomoAuth $MatomoUrl $TokenPlain $SiteId
+Write-Host "Done. MATOMO_URL / MATOMO_API_TOKEN / MATOMO_SITE_ID still override the file."
\ No newline at end of file
diff --git a/extensions/matomo/install.sh b/extensions/matomo/install.sh
index 0c6db06..e28d76f 100755
--- a/extensions/matomo/install.sh
+++ b/extensions/matomo/install.sh
@@ -12,7 +12,6 @@ set -euo pipefail
main() {
SKILL_DIR="${HOME}/.claude/skills"
AGENTS_DIR="${HOME}/.claude/agents"
- SETTINGS_JSON="${HOME}/.claude/settings.json"
echo "════════════════════════════════════════"
echo "║ Claude SEO — Matomo extension ║"
@@ -56,30 +55,40 @@ main() {
cp "${SOURCE_DIR}/agents/seo-matomo.md" "${AGENTS_DIR}/seo-matomo.md"
echo "✓ Installed agent: ${AGENTS_DIR}/seo-matomo.md"
- python3 - "${SETTINGS_JSON}" "${MATOMO_URL}" "${MATOMO_TOKEN}" "${MATOMO_SITE_ID}" <<'PY'
-import json, os, sys, tempfile
-path, url, token, site = sys.argv[1:5]
-data = {}
-if os.path.exists(path):
- try: data = json.load(open(path))
- except json.JSONDecodeError: data = {}
-env = data.setdefault("env", {})
-env["MATOMO_URL"] = url
-env["MATOMO_API_TOKEN"] = token
-if site:
- env["MATOMO_SITE_ID"] = site
-fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path) or ".", prefix=".settings.", suffix=".json")
-with os.fdopen(fd, "w") as fh:
- json.dump(data, fh, indent=2)
-os.chmod(tmp, 0o600)
-os.replace(tmp, path)
-print(f"✓ Wrote MATOMO_* env to {path}")
+ # Credentials go to ~/.config/claude-seo/matomo.json (0600, atomic), not
+ # into ~/.claude/settings.json: settings.json is a general-purpose config
+ # file that tooling reads, prints, and syncs, and an API token has no
+ # business in it. matomo_auth.py still falls back to the MATOMO_*
+ # environment variables, which stays the right choice on a shared machine.
+ [ -f "${MATOMO_AUTH}" ] || { echo "✗ ${MATOMO_AUTH} not found."; exit 1; }
+ python3 - "${MATOMO_AUTH}" "${MATOMO_URL}" "${MATOMO_TOKEN}" "${MATOMO_SITE_ID}" <<'PY'
+import importlib.util, sys
+
+# PowerShell 5.1 drops an empty string argument to a native command, so the
+# optional site ID may simply not arrive. Tolerate that rather than crashing
+# the installer after the token has already been typed.
+args = sys.argv[1:]
+auth_path, url, token = args[0], args[1], args[2]
+site = args[3] if len(args) > 3 else ""
+spec = importlib.util.spec_from_file_location("matomo_auth", auth_path)
+matomo_auth = importlib.util.module_from_spec(spec)
+sys.modules["matomo_auth"] = matomo_auth
+spec.loader.exec_module(matomo_auth)
+
+matomo_auth.save_config({
+ "matomo_url": url,
+ "matomo_token": token,
+ "matomo_site_id": site,
+})
+print("✓ Wrote Matomo credentials to " + matomo_auth.CONFIG_PATH + " (0600)")
PY
echo
echo "Done. Verify with:"
echo " \"\${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo\" run matomo_auth.py --check"
echo " \"\${CLAUDE_PLUGIN_ROOT}/scripts/claude-seo\" run matomo_report.py check --json"
+ echo "Credentials live in ~/.config/claude-seo/matomo.json (0600)."
+ echo "MATOMO_URL / MATOMO_API_TOKEN / MATOMO_SITE_ID still override the file."
echo "Full docs: extensions/matomo/docs/MATOMO-SETUP.md"
}
main "$@"
\ No newline at end of file
diff --git a/extensions/matomo/skills/seo-matomo/SKILL.md b/extensions/matomo/skills/seo-matomo/SKILL.md
index 319e729..cb8a751 100644
--- a/extensions/matomo/skills/seo-matomo/SKILL.md
+++ b/extensions/matomo/skills/seo-matomo/SKILL.md
@@ -3,7 +3,7 @@ name: seo-matomo
description: Matomo Reporting API extension. Self-hosted or Matomo Cloud analytics as a GA4 alternative or complement. Organic traffic, landing pages, device / country breakdowns, referrers, search keywords. Triggers on "Matomo", "self-hosted analytics", "analytics ohne Google", "GA4 alternative", "Matomo Reporting", "Piwik".
metadata:
version: "2.3.0"
-compatibility: "Requires MATOMO_URL, MATOMO_API_TOKEN, and (optionally) MATOMO_SITE_ID in ~/.claude/settings.json env. Run extensions/matomo/install.sh to configure."
+compatibility: "Requires a Matomo instance URL and API token in ~/.config/claude-seo/matomo.json (0600), or MATOMO_URL / MATOMO_API_TOKEN / MATOMO_SITE_ID in the environment. Run extensions/matomo/install.sh to configure."
---
# seo-matomo
diff --git a/extensions/matomo/uninstall.sh b/extensions/matomo/uninstall.sh
index 52af9c5..e2219eb 100755
--- a/extensions/matomo/uninstall.sh
+++ b/extensions/matomo/uninstall.sh
@@ -3,22 +3,51 @@ set -euo pipefail
SKILL_DIR="${HOME}/.claude/skills/seo-matomo"
AGENT_FILE="${HOME}/.claude/agents/seo-matomo.md"
SETTINGS_JSON="${HOME}/.claude/settings.json"
+CONFIG_JSON="${HOME}/.config/claude-seo/matomo.json"
[ -d "${SKILL_DIR}" ] && rm -rf "${SKILL_DIR}" && echo "✓ Removed ${SKILL_DIR}"
[ -f "${AGENT_FILE}" ] && rm -f "${AGENT_FILE}" && echo "✓ Removed ${AGENT_FILE}"
+[ -f "${CONFIG_JSON}" ] && rm -f "${CONFIG_JSON}" && echo "✓ Removed ${CONFIG_JSON}"
+# Installers before v2.4.0 put the token in settings.json env. Clear it there
+# too, so an upgrade-then-uninstall does not leave the old copy behind.
if [ -f "${SETTINGS_JSON}" ]; then
python3 - "${SETTINGS_JSON}" <<'PY'
import json, os, sys, tempfile
-path = sys.argv[1]; data = json.load(open(path))
+path = sys.argv[1]
+try:
+ with open(path) as fh:
+ data = json.load(fh)
+except (OSError, json.JSONDecodeError):
+ sys.exit(0)
env = data.get("env", {})
removed = []
for k in ("MATOMO_URL", "MATOMO_API_TOKEN", "MATOMO_TOKEN",
"MATOMO_SITE_ID", "MATOMO_IDSITE"):
if k in env:
- env.pop(k); removed.append(k)
+ env.pop(k)
+ removed.append(k)
if removed:
- fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".settings.", suffix=".json")
- with os.fdopen(fd, "w") as fh: json.dump(data, fh, indent=2)
- os.chmod(tmp, 0o600); os.replace(tmp, path)
- print(f"✓ Cleared {', '.join(removed)}")
+ directory = os.path.dirname(path) or "."
+ fd, tmp = tempfile.mkstemp(dir=directory, prefix=".settings.", suffix=".json")
+ try:
+ os.fchmod(fd, 0o600)
+ except (AttributeError, OSError):
+ pass
+ try:
+ with os.fdopen(fd, "w") as fh:
+ json.dump(data, fh, indent=2)
+ fh.flush()
+ os.fsync(fh.fileno())
+ os.chmod(tmp, 0o600)
+ os.replace(tmp, path)
+ except BaseException:
+ try:
+ os.unlink(tmp)
+ except OSError:
+ pass
+ raise
+ print("\u2713 Cleared " + ", ".join(removed) + " from " + path)
PY
-fi
\ No newline at end of file
+fi
+
+echo "Note: CLAUDE_SEO_LOCAL_TARGETS, if you set it for a private instance,"
+echo "is your own environment setting and was not touched."
diff --git a/scripts/matomo_auth.py b/scripts/matomo_auth.py
index 020f8ff..a1527ff 100644
--- a/scripts/matomo_auth.py
+++ b/scripts/matomo_auth.py
@@ -18,7 +18,9 @@ import json
import os
import re
import socket
+import subprocess
import sys
+import tempfile
from typing import Optional
from urllib.parse import urlparse
@@ -39,6 +41,17 @@ from url_safety import ( # noqa: E402 (path bootstrap must run first)
safe_requests_session,
)
+try:
+ # Reuse the shared legacy-permission remediation helper rather than
+ # duplicating it. It is path/mode-generic, as backlinks_auth.py already
+ # relies on.
+ from google_auth import _chmod_quiet # noqa: E402
+except ImportError as _import_exc: # pragma: no cover - hard dependency
+ raise RuntimeError(
+ "scripts/google_auth.py is required alongside matomo_auth.py. "
+ "Install with: pip install -r requirements.txt"
+ ) from _import_exc
+
CONFIG_PATH = os.path.expanduser("~/.config/claude-seo/matomo.json")
DEFAULT_TIMEOUT = 15
USER_AGENT = "ClaudeSEO/2.3.0"
@@ -57,6 +70,99 @@ def redact(text: str) -> str:
return _SECRET_RE.sub(r"\1=<redacted>", str(text))
+def _restrict_to_current_user_windows(path: str) -> None:
+ """Best-effort Windows ACL restriction to the current user (issue #290).
+
+ POSIX mode bits are meaningless on NTFS, so ``icacls`` is the closest
+ equivalent. Mirrors ``backlinks_auth._restrict_to_current_user_windows``;
+ failures are warnings, never fatal, and POSIX never reaches this function.
+ """
+ if os.name != "nt":
+ return
+ user = os.environ.get("USERNAME", "").strip()
+ if not user:
+ print(
+ f"Warning: USERNAME is not set; could not restrict {path} to the current user",
+ file=sys.stderr,
+ )
+ return
+ try:
+ result = subprocess.run(
+ ["icacls", path, "/inheritance:r", "/grant:r", f"{user}:F"],
+ check=False, capture_output=True, text=True, timeout=10,
+ )
+ if result.returncode != 0:
+ detail = (result.stderr or result.stdout or "").strip()
+ print(
+ f"Warning: icacls could not restrict {path} to {user} "
+ f"(exit {result.returncode}): {detail}",
+ file=sys.stderr,
+ )
+ except Exception as exc: # best-effort hardening only; never fatal
+ print(
+ f"Warning: could not restrict {path} to the current user via icacls: {exc}",
+ file=sys.stderr,
+ )
+
+
+def _write_secure_json(path: str, data: dict) -> None:
+ """Write ``data`` to ``path`` as 0600 JSON, atomically.
+
+ The permission half is ``backlinks_auth._write_secure_json``'s pattern:
+ pre-chmod an existing file (closes a legacy umask=022 window), create with
+ an explicit 0600 mode, then ``fchmod`` the open fd to force 0600 even if
+ the file pre-existed, which defeats the exists()/open() TOCTOU race. On
+ Windows, a best-effort ``icacls`` pass, since the mode bits are a no-op
+ there.
+
+ The atomic half is this file's addition: the token is written to a
+ same-directory temp file and ``os.replace``d into position, so a crash or
+ a concurrent reader never sees a half-written credential file, and a
+ failed write leaves the previous credentials intact rather than truncated.
+ The temp file is 0600 from creation, so the token is never world-readable
+ even for the instant it exists under the temp name.
+ """
+ directory = os.path.dirname(path) or "."
+ os.makedirs(directory, exist_ok=True)
+ if os.path.exists(path):
+ _chmod_quiet(path, 0o600)
+
+ fd, tmp = tempfile.mkstemp(dir=directory, prefix=".matomo.", suffix=".json")
+ try:
+ fchmod = getattr(os, "fchmod", None)
+ if fchmod is not None:
+ try:
+ fchmod(fd, 0o600)
+ except OSError:
+ pass # FS may not support fchmod (some Windows filesystems)
+ with os.fdopen(fd, "w") as fh:
+ json.dump(data, fh, indent=2)
+ fh.flush()
+ os.fsync(fh.fileno())
+ _chmod_quiet(tmp, 0o600)
+ os.replace(tmp, path)
+ except BaseException:
+ try:
+ os.unlink(tmp)
+ except OSError:
+ pass
+ raise
+ _restrict_to_current_user_windows(path)
+
+
+def save_config(config: dict) -> None:
+ """Persist Matomo credentials to CONFIG_PATH with hardened permissions.
+
+ Only the keys this module reads are written, and empty values are dropped
+ so an optional field left blank at install time does not shadow an
+ environment variable later.
+ """
+ payload = {k: v for k, v in config.items()
+ if k in ("matomo_url", "matomo_token", "matomo_site_id")
+ and v not in (None, "")}
+ _write_secure_json(CONFIG_PATH, payload)
+
+
def load_config() -> dict:
"""
Load configuration from config file with environment variable fallbacks.
@@ -74,6 +180,10 @@ def load_config() -> dict:
}
if os.path.exists(CONFIG_PATH):
+ # A file written by an older installer (or copied in by hand) may be
+ # world-readable; tighten it before reading the token out of it.
+ _chmod_quiet(CONFIG_PATH, 0o600)
+ _restrict_to_current_user_windows(CONFIG_PATH)
try:
with open(CONFIG_PATH, "r") as f:
file_config = json.load(f)
diff --git a/tests/test_matomo_report.py b/tests/test_matomo_report.py
index e7a2ce6..07db3e0 100644
--- a/tests/test_matomo_report.py
+++ b/tests/test_matomo_report.py
@@ -8,6 +8,7 @@ Covers:
- SSRF: every request goes through url_safety's pinned helpers; a private
instance needs CLAUDE_SEO_LOCAL_TARGETS; redirects off the instance refused
- Env-var and config-file credential loading (env wins over file when both set)
+- Credential storage: 0600, atomic, argv-based, never in ~/.claude/settings.json
- Args / CLI error paths surface a structured error envelope
- Token redaction of incoming Matomo ``result=error`` messages
"""
@@ -16,7 +17,10 @@ from __future__ import annotations
import contextlib
import json
+import os
+import re
import socket
+import subprocess
import sys
from pathlib import Path
from unittest.mock import Mock, patch
@@ -687,3 +691,208 @@ def test_resolves_to_private_address_drives_the_installer_hint(monkeypatch):
assert not matomo_auth.resolves_to_private_address("https://93.184.216.34")
# A malformed URL is not a private address.
assert not matomo_auth.resolves_to_private_address("not-a-url")
+
+
+# --------------------------------------------------------------------------
+# Credential storage: ~/.config/claude-seo/matomo.json, 0600, atomic.
+# --------------------------------------------------------------------------
+
+INSTALL_SH = ROOT / "extensions" / "matomo" / "install.sh"
+INSTALL_PS1 = ROOT / "extensions" / "matomo" / "install.ps1"
+UNINSTALL_SH = ROOT / "extensions" / "matomo" / "uninstall.sh"
+
+
+ sys.platform == "win32",
+ reason="asserts 0o600 mode bits, which Windows does not represent",
+)
+def test_save_config_writes_0600(monkeypatch, tmp_path):
+ target = tmp_path / "nested" / "matomo.json"
+ monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(target))
+ matomo_auth.save_config({
+ "matomo_url": "https://analytics.example.com",
+ "matomo_token": SECRET_TOKEN,
+ "matomo_site_id": "1",
+ })
+ assert target.stat().st_mode & 0o777 == 0o600
+ assert json.loads(target.read_text()) == {
+ "matomo_url": "https://analytics.example.com",
+ "matomo_token": SECRET_TOKEN,
+ "matomo_site_id": "1",
+ }
+
+
+def test_save_config_drops_empty_and_unknown_keys(monkeypatch, tmp_path):
+ """A blank optional field must not shadow the env fallback later."""
+ target = tmp_path / "matomo.json"
+ monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(target))
+ matomo_auth.save_config({
+ "matomo_url": "https://analytics.example.com",
+ "matomo_token": SECRET_TOKEN,
+ "matomo_site_id": "",
+ "something_else": "dropped",
+ })
+ stored = json.loads(target.read_text())
+ assert "matomo_site_id" not in stored
+ assert "something_else" not in stored
+
+ monkeypatch.setenv("MATOMO_SITE_ID", "9")
+ assert matomo_auth.load_config()["matomo_site_id"] == "9"
+
+
+def test_save_config_is_atomic_and_leaves_no_temp_file(monkeypatch, tmp_path):
+ """A failed write leaves the previous credentials intact, not truncated."""
+ target = tmp_path / "matomo.json"
+ monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(target))
+ matomo_auth.save_config({"matomo_url": "https://old.example.com",
+ "matomo_token": "old-token"})
+ before = target.read_text()
+
+ def boom(src, dst):
+ raise OSError("simulated crash during rename")
+
+ monkeypatch.setattr(matomo_auth.os, "replace", boom)
+ with pytest.raises(OSError):
+ matomo_auth.save_config({"matomo_url": "https://new.example.com",
+ "matomo_token": SECRET_TOKEN})
+
+ assert target.read_text() == before
+ assert SECRET_TOKEN not in target.read_text()
+ assert sorted(f.name for f in tmp_path.iterdir()) == ["matomo.json"]
+
+
+def test_env_still_overrides_the_config_file(monkeypatch, tmp_path):
+ """The env fallback is kept: it is the right answer on a shared machine."""
+ target = tmp_path / "matomo.json"
+ monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(target))
+ matomo_auth.save_config({"matomo_url": "https://file.example.com",
+ "matomo_token": "file-token"})
+ cfg = matomo_auth.load_config()
+ assert cfg["matomo_url"] == "https://file.example.com"
+
+ # Nothing in the file: env supplies the rest.
+ monkeypatch.setenv("MATOMO_SITE_ID", "42")
+ assert matomo_auth.load_config()["matomo_site_id"] == "42"
+
+
+ sys.platform == "win32",
+ reason="asserts 0o600 mode bits, which Windows does not represent",
+)
+def test_load_config_tightens_a_world_readable_file(monkeypatch, tmp_path):
+ """A file left 0644 by an older installer is remediated before it is read."""
+ target = tmp_path / "matomo.json"
+ target.write_text(json.dumps({"matomo_url": "https://m.test",
+ "matomo_token": SECRET_TOKEN}))
+ target.chmod(0o644)
+ monkeypatch.setattr(matomo_auth, "CONFIG_PATH", str(target))
+ cfg = matomo_auth.load_config()
+ assert cfg["matomo_token"] == SECRET_TOKEN
+ assert target.stat().st_mode & 0o777 == 0o600
+
+
+def test_installers_do_not_put_the_token_in_settings_json():
+ """The token belongs in ~/.config/claude-seo/matomo.json, not settings.json.
+
+ settings.json is a general-purpose config file that tooling reads, prints,
+ and syncs. The PR's installers wrote MATOMO_API_TOKEN into its env block.
+ """
+ forbidden = (
+ 'SETTINGS_JSON=', # the shell variable the old installer used
+ '$SettingsJson', # its PowerShell counterpart
+ 'setdefault("env"', # the env-block write itself
+ "setdefault('env'",
+ 'env["MATOMO',
+ "env['MATOMO",
+ )
+ for path in (INSTALL_SH, INSTALL_PS1):
+ text = path.read_text(encoding="utf-8")
+ for needle in forbidden:
+ assert needle not in text, (
+ f"{path.name} still writes credentials into settings.json ({needle})"
+ )
+ assert "save_config" in text, f"{path.name} must use matomo_auth.save_config"
+ assert ".config/claude-seo" in text or "CONFIG_PATH" in text, (
+ f"{path.name} must name the credential file it writes"
+ )
+
+
+def test_installers_pass_credentials_through_argv_not_source():
+ """No credential is interpolated into a Python source string (issue #189)."""
+ sh = INSTALL_SH.read_text(encoding="utf-8")
+ assert "<<'PY'" in sh, "install.sh must use a quoted heredoc"
+ assert "sys.argv" in sh
+ assert ("'" * 3 + "${") not in sh
+
+ ps1 = INSTALL_PS1.read_text(encoding="utf-8")
+ # PowerShell here-strings: @" ... "@ interpolates, so the credential must
+ # arrive on the pipeline as an argument, never inside the here-string.
+ assert "sys.argv" in ps1
+ assert "$TokenPlain" not in ps1.split('@"')[1].split('"@')[0]
+ assert "python - $MatomoAuth $MatomoUrl $TokenPlain $SiteId" in ps1
+
+
+def test_uninstall_removes_the_config_and_the_legacy_env_entry():
+ text = UNINSTALL_SH.read_text(encoding="utf-8")
+ assert ".config/claude-seo/matomo.json" in text
+ assert "MATOMO_API_TOKEN" in text, "must still clear the pre-v2.4.0 env entry"
+ assert "os.replace" in text, "the settings.json rewrite must stay atomic"
+
+
+def test_installers_warn_about_a_private_instance_address():
+ for path in (INSTALL_SH, INSTALL_PS1):
+ text = path.read_text(encoding="utf-8")
+ assert "--local-target-hint" in text, (
+ f"{path.name} must print the CLAUDE_SEO_LOCAL_TARGETS hint"
+ )
+
+
+_HEREDOC_RE = re.compile(r"<<'PY'\n(.*?)\nPY\n", re.DOTALL)
+
+
+def _installer_writer() -> str:
+ """The credential-writing Python the shell installer feeds to python3."""
+ match = _HEREDOC_RE.search(INSTALL_SH.read_text(encoding="utf-8"))
+ assert match, "install.sh has no quoted <<'PY' heredoc"
+ return match.group(1)
+
+
+ sys.platform == "win32",
+ reason="asserts 0o600 mode bits, which Windows does not represent",
+)
+def test_installer_writer_is_inert_against_an_injection_shaped_token(tmp_path):
+ """A token full of shell and Python metacharacters is data, not code."""
+ home = tmp_path / "home"
+ home.mkdir()
+ nasty = "tok" + "'" * 3 + '"$(touch ' + str(tmp_path / "pwned") + ")"
+ proc = subprocess.run(
+ [sys.executable, "-c", _installer_writer(),
+ str(ROOT / "scripts" / "matomo_auth.py"),
+ "https://analytics.example.com", nasty, "3"],
+ capture_output=True, text=True,
+ env={**os.environ, "HOME": str(home)},
+ )
+ assert proc.returncode == 0, proc.stderr
+ assert not (tmp_path / "pwned").exists(), "installer executed the token"
+
+ written = home / ".config" / "claude-seo" / "matomo.json"
+ assert written.stat().st_mode & 0o777 == 0o600
+ assert json.loads(written.read_text())["matomo_token"] == nasty
+
+
+def test_installer_writer_survives_a_dropped_optional_argument(tmp_path):
+ """PowerShell 5.1 drops an empty native argument; the site ID is optional."""
+ home = tmp_path / "home"
+ home.mkdir()
+ proc = subprocess.run(
+ [sys.executable, "-c", _installer_writer(),
+ str(ROOT / "scripts" / "matomo_auth.py"),
+ "https://analytics.example.com", SECRET_TOKEN], # no 4th argument
+ capture_output=True, text=True,
+ env={**os.environ, "HOME": str(home)},
+ )
+ assert proc.returncode == 0, proc.stderr
+ stored = json.loads((home / ".config" / "claude-seo" / "matomo.json").read_text())
+ assert stored["matomo_token"] == SECRET_TOKEN
+ assert "matomo_site_id" not in stored