Open-source SEO, GEO, and marketing skills for AI agents.
fix: Windows portability + tmp-file hardening + repair unit tests (#45)
Tong Chenf3995e1024c5
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 43109d38..95d68b7c 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -5,14 +5,14 @@},"metadata": {"description": "The official Google Ads + SEO plugin from AdsAgent. SEO and Google Ads skills for Claude Code.",- "version": "0.13.0"+ "version": "0.13.1"},"plugins": [{"name": "toprank","source": "./","description": "The official Google Ads + SEO plugin from AdsAgent. SEO analysis, Google Ads management, keyword research, content optimization, schema markup, and meta tags optimization.",- "version": "0.13.0",+ "version": "0.13.1","author": {"name": "AdsAgent","url": "https://adsagent.org"diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 5d03727a..cabef5fb 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "toprank",- "version": "0.13.0",+ "version": "0.13.1","description": "The official Google Ads + SEO plugin from AdsAgent. SEO analysis, Google Ads management, keyword research, content optimization, and schema markup tools powered by Google Search Console and Google Ads APIs.","author": {"name": "AdsAgent",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ef91c23b..64b8b6a2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,20 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).---+## [0.13.1] — 2026-04-25++### Fixed+- **Windows portability** — replaced POSIX-only `os.getuid()` with a portable `_uid.portable_uid()` helper across the seo-analysis scripts (`pagespeed.py`, `analyze_gsc.py`, `list_gsc_sites.py`, `url_inspection.py`, `show_gsc.py`, `show_pagespeed.py`, all four `fetch_*_content.py` CMS connectors) and the `SKILL.md` CMS heredoc. Native CPython on Windows has no `os.getuid()`, which crashed the entire SEO analysis flow with `AttributeError`. Reported in #44 — thanks @seo4pymesjesus-ux. The new helper returns the same numeric uid on POSIX (preserving existing tmp filenames) and falls back to a sanitized username on Windows.++### Security+- **Hardened tmp-file writes against symlink attacks.** `pagespeed.py`, `analyze_gsc.py`, `list_gsc_sites.py`, and `url_inspection.py` previously wrote results to predictable paths in the system tempdir using direct `open(path, "w")` — exploitable on shared `/tmp` by pre-creating the destination as a symlink. They now use `_uid.secure_write_json()`, which writes via `tempfile.mkstemp()` + `chmod 0600` + atomic `os.replace()` (the same pattern the CMS fetchers already used). Files are also now created with mode 0600 instead of the umask default, preventing other users on shared hosts from reading cached GSC analytics or CMS content.+- **Sanitize Windows username** before interpolating into a tmp path, defending against env-var-driven path traversal in privilege-separation contexts.++### Internal+- **Repaired the unit test suite.** `test/unit/test_analyze_gsc.py`, `test_cms_scripts.py`, `test_strapi_scripts.py`, and `test_url_inspection.py` referenced a `skills/seo-analysis/scripts/` path that no longer exists (the directory was renamed to `seo/seo-analysis/scripts/`). The tests had been failing to even collect. Paths corrected and the loaders now insert the scripts directory into `sys.path` so `from _uid import …` resolves under `importlib.util.spec_from_file_location`. 255 unit tests pass.++---+## [0.13.0] — 2026-04-24### Changeddiff --git a/VERSION b/VERSIONindex 54d1a4f2..c317a918 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.13.0+0.13.1diff --git a/seo/seo-analysis/SKILL.md b/seo/seo-analysis/SKILL.mdindex 939fce83..a33d6fdc 100644--- a/seo/seo-analysis/SKILL.md+++ b/seo/seo-analysis/SKILL.md@@ -337,8 +337,7 @@ CMS_DETECT_EXIT=$?### Run preflight and fetch```bash-UID_STR=$(python3 -c "import os; print(os.getuid())")-CMS_CONTENT_FILE="/tmp/cms_content_${UID_STR}.json"+CMS_CONTENT_FILE=$(SKILL_SCRIPTS="$SKILL_SCRIPTS" python3 -c "import os, sys, tempfile; sys.path.insert(0, os.environ['SKILL_SCRIPTS']); from _uid import portable_uid; print(os.path.join(tempfile.gettempdir(), f'cms_content_{portable_uid()}.json'))")case "$CMS_TYPE" instrapi)diff --git a/seo/seo-analysis/scripts/_uid.py b/seo/seo-analysis/scripts/_uid.pynew file mode 100644index 00000000..28355b75--- /dev/null+++ b/seo/seo-analysis/scripts/_uid.py@@ -0,0 +1,91 @@+"""Portable per-user identifier and secure tmp-file helpers.++Why this exists+---------------+The seo-analysis scripts cache intermediate JSON in the system tempdir between+invocations (e.g. ``analyze_gsc.py`` writes, ``show_gsc.py`` reads). Filenames+are keyed by a per-user suffix so that on shared POSIX hosts two users running+the scripts in the same ``/tmp`` don't collide.++Two primitives:++- :func:`portable_uid` — stable, path-safe identifier for the current user.+ Uses ``os.getuid()`` on POSIX (preserving the historical filename suffix on+ Linux/macOS), sanitized ``getpass.getuser()`` on Windows where ``getuid``+ doesn't exist, and a hashed env-based fallback if neither is available.++- :func:`secure_write_json` — atomic, mode-0600, symlink-safe JSON write,+ matching the pattern already used in the CMS fetchers+ (``fetch_*_content.py``). Writes to a fresh ``mkstemp()`` file in the+ destination directory, then ``os.replace()``s it into place. Defends+ against symlink attacks on shared tmpdirs because POSIX ``rename(2)``+ removes a pre-existing symlink at the destination instead of following it.++Usage as a module: ``python3 -m _uid`` prints the portable uid (used by the+SKILL.md heredoc in place of the previous ``os.getuid()`` shell call).+"""++from __future__ import annotations++import hashlib+import json+import os+import re+import sys+import tempfile+from typing import Any++_SAFE_CHARS = re.compile(r"[^A-Za-z0-9_-]")+++def portable_uid() -> str:+ """Return a stable, path-safe identifier for the current user."""+ getuid = getattr(os, "getuid", None)+ if getuid is not None:+ return str(getuid())++ import getpass+ try:+ username = getpass.getuser()+ except Exception:+ username = ""++ # Sanitize: env-var-derived usernames could contain path separators or+ # null bytes; we interpolate the result into a filesystem path.+ safe = _SAFE_CHARS.sub("_", username)[:32].strip("_")+ if safe:+ return safe++ seed = os.environ.get("APPDATA") or os.environ.get("USERPROFILE") or ""+ if seed:+ return hashlib.sha1(seed.encode("utf-8", "replace")).hexdigest()[:8]++ return f"pid{os.getpid()}"+++def secure_write_json(path: str, data: Any) -> None:+ """Atomically write ``data`` as JSON to ``path`` with mode 0600.++ Defends against symlink-based clobber attacks on shared tempdirs.+ """+ out_dir = os.path.dirname(path) or "."+ fd, tmp_path = tempfile.mkstemp(dir=out_dir, suffix=".json.tmp")+ try:+ try:+ os.chmod(tmp_path, 0o600)+ except (OSError, NotImplementedError):+ # Windows / unusual filesystems may not honor POSIX modes.+ pass+ with os.fdopen(fd, "w") as f:+ json.dump(data, f, indent=2)+ os.replace(tmp_path, path)+ except Exception:+ try:+ os.unlink(tmp_path)+ except OSError:+ pass+ raise+++if __name__ == "__main__":+ sys.stdout.write(portable_uid())diff --git a/seo/seo-analysis/scripts/analyze_gsc.py b/seo/seo-analysis/scripts/analyze_gsc.pyindex f59ced89..c62bf4cc 100644--- a/seo/seo-analysis/scripts/analyze_gsc.py+++ b/seo/seo-analysis/scripts/analyze_gsc.py@@ -21,6 +21,8 @@ import urllib.errorfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom datetime import date, timedelta+from _uid import portable_uid, secure_write_json+DEFAULT_PAGE_GROUPS = [("blog", r"/blog/"),@@ -506,7 +508,7 @@ def main():parser.add_argument("--days", type=int, default=90, help="Days of data to pull")parser.add_argument("--brand-terms", default="",help="Comma-separated brand names for branded vs non-branded split, e.g. 'Acme,AcmeCorp'")- _default_out = os.path.join(tempfile.gettempdir(), f"gsc_analysis_{os.getuid()}.json")+ _default_out = os.path.join(tempfile.gettempdir(), f"gsc_analysis_{portable_uid()}.json")parser.add_argument("--output", default=_default_out, help="Output file")args = parser.parse_args()brand_terms = [t.strip() for t in args.brand_terms.split(",") if t.strip()]@@ -590,8 +592,7 @@ def main():"page_groups": page_groups}- with open(args.output, "w") as f:- json.dump(result, f, indent=2)+ secure_write_json(args.output, result)print(f"\nDone. Results saved to {args.output}", file=sys.stderr)print(f"\nSummary: {summary['clicks']:,} clicks | {summary['impressions']:,} impressions | "diff --git a/seo/seo-analysis/scripts/fetch_contentful_content.py b/seo/seo-analysis/scripts/fetch_contentful_content.pyindex f3cc4ed0..3197fabd 100644--- a/seo/seo-analysis/scripts/fetch_contentful_content.py+++ b/seo/seo-analysis/scripts/fetch_contentful_content.py@@ -28,6 +28,8 @@ import urllib.errorimport urllib.parseimport urllib.request+from _uid import portable_uid, secure_write_json+PAGE_SIZE = 1000 # Contentful max per request_RETRY_CODES = {429, 502, 503, 504}@@ -364,20 +366,10 @@ def main():if args.output:out_path = args.output- out_dir = os.path.dirname(out_path) or "."else:- out_dir = tempfile.gettempdir()- out_path = os.path.join(out_dir, f"cms_content_{os.getuid()}.json")+ out_path = os.path.join(tempfile.gettempdir(), f"cms_content_{portable_uid()}.json")- fd, tmp_path = tempfile.mkstemp(dir=out_dir, suffix=".json.tmp")- try:- os.chmod(tmp_path, 0o600)- with os.fdopen(fd, "w") as f:- json.dump(result, f, indent=2)- os.replace(tmp_path, out_path)- except Exception:- os.unlink(tmp_path)- raise+ secure_write_json(out_path, result)print(f"\nDone. {len(entries)} entries saved to {out_path}", file=sys.stderr)print(diff --git a/seo/seo-analysis/scripts/fetch_ghost_content.py b/seo/seo-analysis/scripts/fetch_ghost_content.pyindex df12365f..231ad779 100644--- a/seo/seo-analysis/scripts/fetch_ghost_content.py+++ b/seo/seo-analysis/scripts/fetch_ghost_content.py@@ -33,6 +33,8 @@ import urllib.errorimport urllib.parseimport urllib.request+from _uid import portable_uid, secure_write_json+PAGE_SIZE = 100 # Ghost supports up to at least 100 per request_RETRY_CODES = {429, 502, 503, 504}@@ -369,20 +371,10 @@ def main():if args.output:out_path = args.output- out_dir = os.path.dirname(out_path) or "."else:- out_dir = tempfile.gettempdir()- out_path = os.path.join(out_dir, f"cms_content_{os.getuid()}.json")+ out_path = os.path.join(tempfile.gettempdir(), f"cms_content_{portable_uid()}.json")- fd, tmp_path = tempfile.mkstemp(dir=out_dir, suffix=".json.tmp")- try:- os.chmod(tmp_path, 0o600)- with os.fdopen(fd, "w") as f:- json.dump(result, f, indent=2)- os.replace(tmp_path, out_path)- except Exception:- os.unlink(tmp_path)- raise+ secure_write_json(out_path, result)print(f"\nDone. {len(entries)} entries saved to {out_path}", file=sys.stderr)print(diff --git a/seo/seo-analysis/scripts/fetch_strapi_content.py b/seo/seo-analysis/scripts/fetch_strapi_content.pyindex 4f6a811e..02e959dd 100644--- a/seo/seo-analysis/scripts/fetch_strapi_content.py+++ b/seo/seo-analysis/scripts/fetch_strapi_content.py@@ -31,6 +31,8 @@ import urllib.errorimport urllib.parseimport urllib.request+from _uid import portable_uid, secure_write_json+PAGE_SIZE = 100 # Strapi default max; configurable up to 250 in config/api.js@@ -400,23 +402,12 @@ def main():"entries": entries,}- # Atomic write to a private tempfile, then rename into placeif args.output:out_path = args.output- out_dir = os.path.dirname(out_path) or "."else:- out_dir = tempfile.gettempdir()- out_path = os.path.join(out_dir, f"strapi_content_{os.getuid()}.json")+ out_path = os.path.join(tempfile.gettempdir(), f"strapi_content_{portable_uid()}.json")- fd, tmp_path = tempfile.mkstemp(dir=out_dir, suffix=".json.tmp")- try:- os.chmod(tmp_path, 0o600)- with os.fdopen(fd, "w") as f:- json.dump(result, f, indent=2)- os.replace(tmp_path, out_path)- except Exception:- os.unlink(tmp_path)- raise+ secure_write_json(out_path, result)print(f"\nDone. {len(entries)} entries saved to {out_path}", file=sys.stderr)print(diff --git a/seo/seo-analysis/scripts/fetch_wordpress_content.py b/seo/seo-analysis/scripts/fetch_wordpress_content.pyindex 30eff026..32e62079 100644--- a/seo/seo-analysis/scripts/fetch_wordpress_content.py+++ b/seo/seo-analysis/scripts/fetch_wordpress_content.py@@ -31,6 +31,8 @@ import urllib.errorimport urllib.parseimport urllib.request+from _uid import portable_uid, secure_write_json+PAGE_SIZE = 100_RETRY_CODES = {429, 502, 503, 504}@@ -382,20 +384,10 @@ def main():if args.output:out_path = args.output- out_dir = os.path.dirname(out_path) or "."else:- out_dir = tempfile.gettempdir()- out_path = os.path.join(out_dir, f"cms_content_{os.getuid()}.json")+ out_path = os.path.join(tempfile.gettempdir(), f"cms_content_{portable_uid()}.json")- fd, tmp_path = tempfile.mkstemp(dir=out_dir, suffix=".json.tmp")- try:- os.chmod(tmp_path, 0o600)- with os.fdopen(fd, "w") as f:- json.dump(result, f, indent=2)- os.replace(tmp_path, out_path)- except Exception:- os.unlink(tmp_path)- raise+ secure_write_json(out_path, result)print(f"\nDone. {len(entries)} entries saved to {out_path}", file=sys.stderr)print(diff --git a/seo/seo-analysis/scripts/list_gsc_sites.py b/seo/seo-analysis/scripts/list_gsc_sites.pyindex a4210328..1e16fe1f 100644--- a/seo/seo-analysis/scripts/list_gsc_sites.py+++ b/seo/seo-analysis/scripts/list_gsc_sites.py@@ -9,6 +9,8 @@ import tempfileimport urllib.requestimport urllib.error+from _uid import portable_uid, secure_write_json+def get_quota_project():"""Return the quota_project_id from the ADC JSON file, or None."""@@ -92,9 +94,8 @@ def main():print(f" Type: {ptype} | Permission: {level}")# Also output as JSON for machine parsing- sites_path = os.path.join(tempfile.gettempdir(), f"gsc_sites_{os.getuid()}.json")- with open(sites_path, "w") as f:- json.dump(sites, f, indent=2)+ sites_path = os.path.join(tempfile.gettempdir(), f"gsc_sites_{portable_uid()}.json")+ secure_write_json(sites_path, sites)print(f"\n(Full list saved to {sites_path})")diff --git a/seo/seo-analysis/scripts/pagespeed.py b/seo/seo-analysis/scripts/pagespeed.pyindex 4c3c8078..70825980 100644--- a/seo/seo-analysis/scripts/pagespeed.py+++ b/seo/seo-analysis/scripts/pagespeed.py@@ -20,6 +20,8 @@ import urllib.requestimport urllib.errorfrom concurrent.futures import ThreadPoolExecutor, as_completed+from _uid import portable_uid, secure_write_json+PSI_API = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed"@@ -262,7 +264,7 @@ def main():help="Run both mobile and desktop")parser.add_argument("--api-key", default=os.environ.get("PAGESPEED_API_KEY", ""),help="Google API key (optional, increases rate limits)")- _default_out = os.path.join(tempfile.gettempdir(), f"pagespeed_{os.getuid()}.json")+ _default_out = os.path.join(tempfile.gettempdir(), f"pagespeed_{portable_uid()}.json")parser.add_argument("--output", default=_default_out, help="Output file")args = parser.parse_args()@@ -324,8 +326,7 @@ def main():"results": results,}- with open(args.output, "w") as f:- json.dump(output, f, indent=2)+ secure_write_json(args.output, output)print(f"\nDone. Results saved to {args.output}", file=sys.stderr)if summary["avg_performance_score"] is not None:diff --git a/seo/seo-analysis/scripts/show_gsc.py b/seo/seo-analysis/scripts/show_gsc.pyindex 38f7b41c..cdf37df3 100644--- a/seo/seo-analysis/scripts/show_gsc.py+++ b/seo/seo-analysis/scripts/show_gsc.py@@ -13,7 +13,9 @@ import osimport sysimport tempfile-DEFAULT_PATH = os.path.join(tempfile.gettempdir(), f"gsc_analysis_{os.getuid()}.json")+from _uid import portable_uid++DEFAULT_PATH = os.path.join(tempfile.gettempdir(), f"gsc_analysis_{portable_uid()}.json")def fmt_ctr(ctr):diff --git a/seo/seo-analysis/scripts/show_pagespeed.py b/seo/seo-analysis/scripts/show_pagespeed.pyindex 431826ee..71c6da3e 100644--- a/seo/seo-analysis/scripts/show_pagespeed.py+++ b/seo/seo-analysis/scripts/show_pagespeed.py@@ -14,6 +14,8 @@ import osimport sysimport tempfile+from _uid import portable_uid+def rating_indicator(rating):"""Return a visual indicator for CrUX rating."""@@ -205,7 +207,7 @@ def print_result(result):def main():parser = argparse.ArgumentParser()- _default_in = os.path.join(tempfile.gettempdir(), f"pagespeed_{os.getuid()}.json")+ _default_in = os.path.join(tempfile.gettempdir(), f"pagespeed_{portable_uid()}.json")parser.add_argument("--input", default=_default_in, help="Input JSON file")args = parser.parse_args()diff --git a/seo/seo-analysis/scripts/url_inspection.py b/seo/seo-analysis/scripts/url_inspection.pyindex 7b46bfda..c0247219 100644--- a/seo/seo-analysis/scripts/url_inspection.py+++ b/seo/seo-analysis/scripts/url_inspection.py@@ -33,6 +33,8 @@ import urllib.requestimport urllib.errorfrom concurrent.futures import ThreadPoolExecutor, as_completed+from _uid import portable_uid, secure_write_json+def get_quota_project():"""Return the quota_project_id from the ADC JSON file, or None."""@@ -246,7 +248,7 @@ def main():parser.add_argument("--max-urls", type=int, default=5,help="Maximum number of URLs to inspect (API limit: 2000/day). Default: 5")_default_out = os.path.join(tempfile.gettempdir(),- f"url_inspection_{os.getuid()}.json")+ f"url_inspection_{portable_uid()}.json")parser.add_argument("--output", default=_default_out,help="Output JSON file path")parser.add_argument("--delay", type=float, default=0.1,@@ -337,8 +339,7 @@ def main():"errors": errors}- with open(args.output, "w") as f:- json.dump(output, f, indent=2)+ secure_write_json(args.output, output)print(f"\nDone. Results saved to {args.output}", file=sys.stderr)print(f"Summary: {summary['total_urls_inspected']} inspected | "diff --git a/test/unit/test_analyze_gsc.py b/test/unit/test_analyze_gsc.pyindex b7cdf88a..7b60bacb 100644--- a/test/unit/test_analyze_gsc.py+++ b/test/unit/test_analyze_gsc.py@@ -16,9 +16,12 @@ from datetime import date, timedeltafrom unittest.mock import MagicMock, patch# Load analyze_gsc.py as a module without executing main()-_SCRIPT_PATH = os.path.join(- os.path.dirname(__file__), '..', '..', 'skills', 'seo-analysis', 'scripts', 'analyze_gsc.py'+_SCRIPTS_DIR = os.path.join(+ os.path.dirname(__file__), '..', '..', 'seo', 'seo-analysis', 'scripts')+if _SCRIPTS_DIR not in sys.path:+ sys.path.insert(0, _SCRIPTS_DIR)+_SCRIPT_PATH = os.path.join(_SCRIPTS_DIR, 'analyze_gsc.py')spec = importlib.util.spec_from_file_location('analyze_gsc', _SCRIPT_PATH)gsc = importlib.util.module_from_spec(spec)# Don't run __main__ blockdiff --git a/test/unit/test_cms_scripts.py b/test/unit/test_cms_scripts.pyindex 450eab38..2b3495ba 100644--- a/test/unit/test_cms_scripts.py+++ b/test/unit/test_cms_scripts.py@@ -15,10 +15,15 @@ import unittest# ── Load scripts without executing main() ────────────────────────────────────+_SCRIPTS_DIR = os.path.join(+ os.path.dirname(__file__), '..', '..', 'seo', 'seo-analysis', 'scripts'+)+if _SCRIPTS_DIR not in sys.path:+ sys.path.insert(0, _SCRIPTS_DIR)++def _load(name):- path = os.path.join(- os.path.dirname(__file__), '..', '..', 'skills', 'seo-analysis', 'scripts', name- )+ path = os.path.join(_SCRIPTS_DIR, name)spec = importlib.util.spec_from_file_location(name.replace('.py', ''), path)mod = importlib.util.module_from_spec(spec)spec.loader.exec_module(mod)diff --git a/test/unit/test_strapi_scripts.py b/test/unit/test_strapi_scripts.pyindex 1a5f22fa..c3b9d532 100644--- a/test/unit/test_strapi_scripts.py+++ b/test/unit/test_strapi_scripts.py@@ -16,10 +16,17 @@ import unittest# ── Load scripts without executing main() ────────────────────────────────────+_SCRIPTS_DIR = os.path.join(+ os.path.dirname(__file__), '..', '..', 'seo', 'seo-analysis', 'scripts'+)+# Match how Python's direct script invocation populates sys.path so the+# scripts' `from _uid import …` resolves during importlib loading too.+if _SCRIPTS_DIR not in sys.path:+ sys.path.insert(0, _SCRIPTS_DIR)++def _load(name):- path = os.path.join(- os.path.dirname(__file__), '..', '..', 'skills', 'seo-analysis', 'scripts', name- )+ path = os.path.join(_SCRIPTS_DIR, name)spec = importlib.util.spec_from_file_location(name.replace('.py', ''), path)mod = importlib.util.module_from_spec(spec)spec.loader.exec_module(mod)diff --git a/test/unit/test_url_inspection.py b/test/unit/test_url_inspection.pyindex c37d254f..a9e37409 100644--- a/test/unit/test_url_inspection.py+++ b/test/unit/test_url_inspection.py@@ -11,9 +11,12 @@ import sysimport unittest# Load url_inspection.py as a module without executing main()-_SCRIPT_PATH = os.path.join(- os.path.dirname(__file__), '..', '..', 'skills', 'seo-analysis', 'scripts', 'url_inspection.py'+_SCRIPTS_DIR = os.path.join(+ os.path.dirname(__file__), '..', '..', 'seo', 'seo-analysis', 'scripts')+if _SCRIPTS_DIR not in sys.path:+ sys.path.insert(0, _SCRIPTS_DIR)+_SCRIPT_PATH = os.path.join(_SCRIPTS_DIR, 'url_inspection.py')spec = importlib.util.spec_from_file_location('url_inspection', _SCRIPT_PATH)ui = importlib.util.module_from_spec(spec)spec.loader.exec_module(ui)