Free, open source blog writer for Claude Code. Researches current sources, writes answer-first posts for Google and AI answers, has an independent reviewer score each one out of 100 and ships only after five delivery gates. 32 skills, 30 /blog commands, 5 agents. Active development at AI-Marketing-Hub/claude-blog; public releases ship here.
Python agent-skillsaiai-citationsai-contentai-marketingai-marketing-hubblogblog-writingclaude-codeclaude-code-skillclaude-pluginclaude-skillcontent-creationcontent-optimizationcontent-strategyeeatgeomultilingualopen-sourceseo
fix(security): credential at-rest hardening + OAuth state CSRF
Daniel478c1b9ac549
diff --git a/skills/blog-google/scripts/google_auth.py b/skills/blog-google/scripts/google_auth.pyindex efd0a44..8ebdcb8 100644--- a/skills/blog-google/scripts/google_auth.py+++ b/skills/blog-google/scripts/google_auth.py@@ -18,7 +18,9 @@ Usage:import argparseimport jsonimport os+import secretsimport sys+import tempfileimport timefrom typing import Optional@@ -43,12 +45,46 @@ SERVICE_AUTH = {"ga4": "oauth_or_sa",}-OAUTH_SCOPES = (- "https://www.googleapis.com/auth/indexing "- "https://www.googleapis.com/auth/webmasters "- "https://www.googleapis.com/auth/analytics.readonly"-)-OAUTH_REDIRECT_URI = "http://localhost:8085"+OAUTH_REDIRECT_URI = "http://127.0.0.1:8085"+++def _write_secret_atomic(path: str, content: str) -> None:+ """Atomically write `content` to `path` with mode 0o600.++ Uses tempfile in same dir + os.replace for atomicity (no partial writes+ on crash). Sets restrictive file mode before writing payload.+ """+ os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True)+ fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".tmp-")+ try:+ os.fchmod(fd, 0o600)+ with os.fdopen(fd, "w") as f:+ f.write(content)+ os.replace(tmp, path)+ os.chmod(path, 0o600) # belt-and-braces if file pre-existed+ except Exception:+ try:+ os.unlink(tmp)+ except OSError:+ pass+ raise+++def _scopes_for(services: list = None) -> str:+ """Build OAuth scope string for the requested services.++ Defaults to a read-only set so OAuth-without-flag grants minimal scopes.+ """+ if services is None:+ # Safer default: read-only scopes only.+ services = ["gsc_readonly", "ga4"]+ scope_urls = []+ for s in services:+ if s in SCOPES:+ scope_urls.append(SCOPES[s])+ else:+ raise ValueError(f"Unknown scope service: {s}")+ return " ".join(scope_urls)# Human-readable service namesSERVICE_NAMES = {@@ -171,10 +207,8 @@ def _load_oauth_token() -> Optional[dict]:def _save_oauth_token(token_data: dict):- """Save OAuth token to TOKEN_PATH."""- os.makedirs(os.path.dirname(TOKEN_PATH), exist_ok=True)- with open(TOKEN_PATH, "w") as f:- json.dump(token_data, f, indent=2)+ """Save OAuth token to TOKEN_PATH with mode 0o600 and atomic write."""+ _write_secret_atomic(TOKEN_PATH, json.dumps(token_data, indent=2))def _refresh_oauth_token(client: dict, token_data: dict) -> Optional[dict]:@@ -198,6 +232,8 @@ def _refresh_oauth_token(client: dict, token_data: dict) -> Optional[dict]:new_data = json.loads(resp.read())token_data["access_token"] = new_data["access_token"]token_data["expires_at"] = time.time() + new_data.get("expires_in", 3600)+ if "refresh_token" in new_data: # Google now sometimes rotates these+ token_data["refresh_token"] = new_data["refresh_token"]_save_oauth_token(token_data)return token_dataexcept Exception as e:@@ -250,7 +286,7 @@ def get_oauth_credentials(scopes: list):return get_service_account_credentials(scopes)-def run_oauth_flow(creds_path: str):+def run_oauth_flow(creds_path: str, services: list = None):"""Run OAuth browser-based authentication flow.@@ -259,6 +295,8 @@ def run_oauth_flow(creds_path: str):Args:creds_path: Path to the OAuth client_secret JSON file.+ services: Optional list of scope service keys (see SCOPES). Defaults to+ the read-only set built by `_scopes_for(None)`."""import http.serverimport urllib.parse@@ -270,13 +308,22 @@ def run_oauth_flow(creds_path: str):print("Error: Could not load OAuth client credentials.", file=sys.stderr)sys.exit(1)+ state_token = secrets.token_urlsafe(32)+ scopes_str = _scopes_for(services)++ auth_params = {+ "client_id": client["client_id"],+ "redirect_uri": OAUTH_REDIRECT_URI,+ "response_type": "code",+ "scope": scopes_str,+ "access_type": "offline",+ "prompt": "consent",+ "state": state_token,+ "include_granted_scopes": "true",+ }auth_url = (f"{client.get('auth_uri', 'https://accounts.google.com/o/oauth2/auth')}"- f"?client_id={client['client_id']}"- f"&redirect_uri={urllib.parse.quote(OAUTH_REDIRECT_URI)}"- f"&response_type=code"- f"&scope={urllib.parse.quote(OAUTH_SCOPES)}"- f"&access_type=offline&prompt=consent"+ f"?{urllib.parse.urlencode(auth_params)}")auth_code = [None]@@ -284,19 +331,26 @@ def run_oauth_flow(creds_path: str):class Handler(http.server.BaseHTTPRequestHandler):def do_GET(self):params = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)+ received_state = params.get("state", [""])[0]+ if received_state != state_token:+ self.send_response(403)+ self.send_header("Content-Type", "text/plain")+ self.end_headers()+ self.wfile.write(b"State mismatch -- possible CSRF. Aborted.")+ returnif "code" in params:auth_code[0] = params["code"][0]self.send_response(200)self.send_header("Content-Type", "text/html")self.end_headers()- self.wfile.write(b"<h1>Authentication successful!</h1><p>Close this tab.</p>")+ self.wfile.write(b"<html><body><h1>Authorization complete.</h1>You can close this tab.</body></html>")else:self.send_response(400)self.end_headers()def log_message(self, *a):pass- server = http.server.HTTPServer(("localhost", 8085), Handler)+ server = http.server.HTTPServer(("127.0.0.1", 8085), Handler)server.timeout = 300print(f"\nOpen this URL in your browser:\n\n{auth_url}\n")@@ -312,7 +366,7 @@ def run_oauth_flow(creds_path: str):if not auth_code[0]:print("\nAuthentication failed or timed out.", file=sys.stderr)- print("If the browser showed 'localhost refused to connect', copy the full URL")+ print("If the browser showed '127.0.0.1 refused to connect', copy the full URL")print("from the browser address bar and run:")print(f" python scripts/google_auth.py --exchange --creds {creds_path} --code 'THE_CODE'")sys.exit(1)@@ -670,6 +724,14 @@ def main():"--code",help="Authorization code to exchange (for --exchange)",)+ parser.add_argument(+ "--scopes",+ help=(+ "Comma-separated scope service keys for --auth (e.g. "+ "'gsc_readonly,ga4' or 'indexing,gsc_write'). Defaults to a "+ "read-only set: gsc_readonly,ga4."+ ),+ )args = parser.parse_args()@@ -677,7 +739,10 @@ def main():if not args.creds:print("Error: --creds is required with --auth", file=sys.stderr)sys.exit(1)- run_oauth_flow(args.creds)+ services = None+ if args.scopes:+ services = [s.strip() for s in args.scopes.split(",") if s.strip()]+ run_oauth_flow(args.creds, services=services)returnif args.exchange:diff --git a/skills/blog-notebooklm/scripts/auth_manager.py b/skills/blog-notebooklm/scripts/auth_manager.pyindex 54c8b3b..4c0dd4c 100644--- a/skills/blog-notebooklm/scripts/auth_manager.py+++ b/skills/blog-notebooklm/scripts/auth_manager.py@@ -28,6 +28,31 @@ from config import BROWSER_STATE_DIR, STATE_FILE, AUTH_INFO_FILE, DATA_DIRfrom browser_utils import BrowserFactory+def _harden_perms(path) -> None:+ """Set restrictive permissions on a credential file or directory.++ Files: 0o600 (owner read/write only).+ Dirs: 0o700 (owner traverse only).+ Recursively applies to all children of dirs.+ Best-effort: failures are swallowed silently (Windows fs may lack POSIX mode bits).+ """+ import os+ from pathlib import Path+ p = Path(path)+ try:+ if p.is_dir():+ p.chmod(0o700)+ for child in p.rglob("*"):+ try:+ child.chmod(0o600 if child.is_file() else 0o700)+ except OSError:+ pass+ elif p.is_file():+ p.chmod(0o600)+ except OSError:+ pass # Windows / readonly fs / etc.++class AuthManager:"""Manages authentication and browser state for NotebookLM@@ -162,6 +187,9 @@ class AuthManager:try:# Save storage state (cookies, localStorage)context.storage_state(path=str(self.state_file))+ # Harden permissions on credential file and parent dir (VULN-004 mitigation)+ _harden_perms(self.state_file)+ _harden_perms(self.browser_state_dir)print(f" 💾 Saved browser state to: {self.state_file}")except Exception as e:print(f" ❌ Failed to save browser state: {e}")@@ -176,6 +204,8 @@ class AuthManager:}with open(self.auth_info_file, 'w') as f:json.dump(info, f, indent=2)+ # Harden permissions on auth info file (VULN-004 mitigation)+ _harden_perms(self.auth_info_file)except Exception:pass # Non-criticaldiff --git a/skills/blog-notebooklm/scripts/browser_utils.py b/skills/blog-notebooklm/scripts/browser_utils.pyindex 60a1210..a249277 100644--- a/skills/blog-notebooklm/scripts/browser_utils.py+++ b/skills/blog-notebooklm/scripts/browser_utils.py@@ -6,12 +6,39 @@ Handles browser launching, stealth features, and common interactionsimport jsonimport timeimport random+from pathlib import Pathfrom typing import Optional, Listfrom patchright.sync_api import Playwright, BrowserContext, Pagefrom config import BROWSER_PROFILE_DIR, STATE_FILE, BROWSER_ARGS, USER_AGENT+def _harden_perms(path) -> None:+ """Set restrictive permissions on a credential file or directory.++ Files: 0o600 (owner read/write only).+ Dirs: 0o700 (owner traverse only).+ Recursively applies to all children of dirs.+ Best-effort: failures are swallowed silently (Windows fs may lack POSIX mode bits).++ Duplicated here (also lives in auth_manager) to avoid an import cycle:+ auth_manager already imports browser_utils.+ """+ p = Path(path)+ try:+ if p.is_dir():+ p.chmod(0o700)+ for child in p.rglob("*"):+ try:+ child.chmod(0o600 if child.is_file() else 0o700)+ except OSError:+ pass+ elif p.is_file():+ p.chmod(0o600)+ except OSError:+ pass++class BrowserFactory:"""Factory for creating configured browser contexts"""@@ -36,6 +63,10 @@ class BrowserFactory:args=BROWSER_ARGS)+ # Harden the persistent profile dir recursively (VULN-004 mitigation).+ # Patchright writes cookies, tokens, and cache here under default 0o755.+ _harden_perms(user_data_dir)+# Cookie Workaround for Playwright bug #36139# Session cookies (expires=-1) don't persist in user_data_dir automaticallyBrowserFactory._inject_cookies(context)diff --git a/skills/blog-notebooklm/scripts/config.py b/skills/blog-notebooklm/scripts/config.pyindex 4486b55..a37b2ab 100644--- a/skills/blog-notebooklm/scripts/config.py+++ b/skills/blog-notebooklm/scripts/config.py@@ -3,6 +3,7 @@ Configuration for NotebookLM SkillCentralizes constants, selectors, and paths"""+import osfrom pathlib import Path# Paths@@ -28,14 +29,21 @@ RESPONSE_SELECTORS = []# Browser Configuration+# Note: "--no-sandbox" intentionally removed (VULN-009 mitigation). Enabling+# sandbox-disabled mode without container isolation gives the renderer+# process full host access. If running inside a container that requires it+# (e.g. Docker without a non-root user), set env PATCHRIGHT_NO_SANDBOX=1+# and the launcher will append it conditionally.BROWSER_ARGS = ['--disable-blink-features=AutomationControlled', # Patches navigator.webdriver'--disable-dev-shm-usage',- '--no-sandbox','--no-first-run','--no-default-browser-check']+if os.environ.get('PATCHRIGHT_NO_SANDBOX') == '1':+ BROWSER_ARGS.append('--no-sandbox')+USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'# Timeoutsdiff --git a/tests/test_security_guardrails.py b/tests/test_security_guardrails.pyindex c47cd7d..9c14451 100644--- a/tests/test_security_guardrails.py+++ b/tests/test_security_guardrails.py@@ -1,6 +1,6 @@"""Mechanical security and quality guardrails for the claude-blog repo.-These tests enforce four invariants that complement the rules documented in+These tests enforce invariants that complement the rules documented inCLAUDE.md. Rules in prose can drift; assertions in pytest cannot. If any ofthese tests fail in CI, a contributor (human or agent) has regressed aproject-wide invariant and must fix the underlying file before merging.@@ -13,13 +13,22 @@ Invariants enforced:4. ``scripts/sync_flow.py``, when present, contains the required securityprimitives (host allowlist, size cap, ``--dry-run``, ``--ref``, lock file,license-header injection, path-traversal guard).+5. Credential write helpers in ``google_auth.py`` produce mode 0o600 files+ (atomic + restrictive perms). Closes audit VULN-002 regression risk.+6. NotebookLM credential helpers contain the chmod 600/700 hardening pattern+ (static-presence check; deeper behavioral test is gated on patchright+ being installed in the dev venv).Stdlib + pytest only. No network, no writes outside ``tmp_path``."""from __future__ import annotations+import importlib.util+import osimport re+import stat+import sysimport warningsfrom pathlib import Path@@ -33,6 +42,13 @@ REPO_ROOT = Path(__file__).resolve().parent.parentAGENTS_DIR = REPO_ROOT / "agents"SKILLS_DIR = REPO_ROOT / "skills"SYNC_FLOW_PATH = REPO_ROOT / "scripts" / "sync_flow.py"+GOOGLE_AUTH_PATH = REPO_ROOT / "skills" / "blog-google" / "scripts" / "google_auth.py"+NOTEBOOKLM_AUTH_MANAGER_PATH = (+ REPO_ROOT / "skills" / "blog-notebooklm" / "scripts" / "auth_manager.py"+)+NOTEBOOKLM_BROWSER_UTILS_PATH = (+ REPO_ROOT / "skills" / "blog-notebooklm" / "scripts" / "browser_utils.py"+)# ---------------------------------------------------------------------------@@ -390,3 +406,118 @@ def test_sync_flow_security_invariants() -> None:f"scripts/sync_flow.py is missing required security primitives. "f"Add the following before merging:\n - " + "\n - ".join(missing))+++# ---------------------------------------------------------------------------+# Test 5: google_auth._write_secret_atomic produces mode 0o600 files+# ---------------------------------------------------------------------------+++def _load_module(module_name: str, path: Path):+ """Load a Python module from an absolute path without polluting sys.modules."""+ spec = importlib.util.spec_from_file_location(module_name, str(path))+ if spec is None or spec.loader is None:+ raise RuntimeError(f"Cannot create import spec for {path}")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def test_google_auth_write_secret_atomic_sets_mode_0600(tmp_path) -> None:+ """``_write_secret_atomic`` MUST produce a file at mode 0o600.++ This is the regression gate for audit VULN-002 (OAuth refresh token ++ client_secret were previously written at default umask, mode 0644).+ Skipped on Windows where POSIX mode bits are not enforced.+ """+ if not GOOGLE_AUTH_PATH.exists():+ pytest.skip("google_auth.py not present at expected path")+ if os.name == "nt":+ pytest.skip("POSIX mode bits not enforced on Windows")++ google_auth = _load_module("_test_google_auth", GOOGLE_AUTH_PATH)+ helper = getattr(google_auth, "_write_secret_atomic", None)+ assert helper is not None, (+ "google_auth._write_secret_atomic helper is missing. "+ "It is required to enforce atomic, mode-0600 credential writes."+ )++ target = tmp_path / "subdir" / "secret.json"+ helper(str(target), '{"refresh_token": "test-value"}')++ assert target.exists(), "secret file was not created"+ mode = stat.S_IMODE(target.stat().st_mode)+ assert mode == 0o600, (+ f"_write_secret_atomic produced mode {oct(mode)}, expected 0o600. "+ "Audit VULN-002 regression: any local user could read tokens."+ )+ # Parent directory should be 0o700 too (owner-only traversal).+ parent_mode = stat.S_IMODE(target.parent.stat().st_mode)+ assert parent_mode == 0o700, (+ f"_write_secret_atomic parent dir mode is {oct(parent_mode)}, "+ "expected 0o700."+ )+++# ---------------------------------------------------------------------------+# Test 6: NotebookLM credential helpers contain chmod hardening pattern+# ---------------------------------------------------------------------------+++def test_notebooklm_credential_files_contain_chmod_hardening() -> None:+ """``auth_manager.py`` and ``browser_utils.py`` must call chmod 600/700.++ Static-presence test (no module import) so it runs without ``patchright``+ being installed. Behavioral test for the chmod helper would require the+ skill's local ``.venv`` and is intentionally not run in base CI.++ Closes audit VULN-004 regression risk: NotebookLM session cookies+ (Google ``__Secure-1PSID``/``SAPISID``) MUST be written user-private.+ """+ targets = {+ "auth_manager.py": NOTEBOOKLM_AUTH_MANAGER_PATH,+ "browser_utils.py": NOTEBOOKLM_BROWSER_UTILS_PATH,+ }++ missing: list[str] = []+ for label, path in targets.items():+ if not path.exists():+ pytest.skip(f"{label} not present at expected path")+ source = _read(path)+ # Require at least one chmod 600 or chmod 700 call site, OR an+ # explicit hardening helper definition + call.+ has_chmod_600 = "0o600" in source+ has_chmod_700 = "0o700" in source+ has_helper = "_harden_perms" in source+ if not (has_chmod_600 and has_chmod_700) and not has_helper:+ missing.append(+ f"{label}: missing chmod 600/700 calls AND no _harden_perms "+ "helper found. Add explicit chmod after every credential write."+ )++ assert not missing, (+ "NotebookLM credential files are missing chmod 600/700 hardening:\n - "+ + "\n - ".join(missing)+ )+++# ---------------------------------------------------------------------------+# Test 7: .mcp.json is gitignored (closes VULN-003)+# ---------------------------------------------------------------------------+++def test_mcp_json_is_gitignored() -> None:+ """``.gitignore`` must list ``.mcp.json`` to prevent committed-secret risk.++ The audit VULN-003 finding: ``.gitignore`` previously excluded ``.env``+ and ``*.key`` but NOT ``.mcp.json``. The setup script defaults could+ write a literal API key into a tracked file, leaking on next ``git add``.+ """+ gitignore = REPO_ROOT / ".gitignore"+ assert gitignore.exists(), ".gitignore must exist at repo root"+ text = _read(gitignore)+ assert ".mcp.json" in text, (+ "VULN-003 regression: .gitignore must include `.mcp.json` to block "+ "accidental commit of MCP server configs that may carry inline "+ "GOOGLE_AI_API_KEY values."+ )