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): code-enforced iteration counter in blog_preflight (VULN-802)
Daniel109cb6152acc
diff --git a/scripts/blog_preflight.py b/scripts/blog_preflight.pyindex f3244da..61de724 100644--- a/scripts/blog_preflight.py+++ b/scripts/blog_preflight.py@@ -51,6 +51,65 @@ HEAD_TIMEOUT = 10USER_AGENT = "claude-blog/1.9.0 preflight (+https://github.com/AgriciDaniel/claude-blog)"URL_ALLOWLIST = ("localhost", "127.0.0.1", "example.com", "example.org")+# VULN-802 code-enforced iteration counter (v1.9.1).+# The contract documents "up to 3 retries before escalating." v1.9.0+# enforced this only as orchestrator prose; any draft-controlled text+# could convince the orchestrator the counter was at 0. v1.9.1 backs the+# claim with a file on disk that survives across preflight invocations.+ITERATION_COUNTER_FILE = ".iteration-count"+MAX_ITERATIONS = 3+EXIT_ITERATION_CAP = 2+++def _iteration_check(draft: Path, reset: bool = False) -> int:+ """Read/increment the per-draft iteration counter; refuse past cap.++ Behavior:+ * reset=True: counter is set to 1 (this run counts as iteration 1).+ * reset=False, counter absent or corrupt: counter is set to 1.+ * reset=False, counter at MAX_ITERATIONS: emit stderr message and+ return EXIT_ITERATION_CAP. Caller should sys.exit(2).+ * Otherwise: counter += 1; return 0.++ Fail-soft on corrupt counter file: a non-integer value resets to 1+ rather than refusing to run (an attacker who can write to the draft+ folder has bigger problems; refusing on garbage would be a self-DoS).+ """+ counter_path = draft / ITERATION_COUNTER_FILE+ if reset:+ _atomic_write_counter(counter_path, 1)+ return 0+ try:+ raw = counter_path.read_text(encoding="utf-8").strip()+ current = int(raw)+ except (FileNotFoundError, ValueError, OSError):+ current = 0+ if current >= MAX_ITERATIONS:+ sys.stderr.write(+ f"ITERATION CAP EXCEEDED: this draft has used all {MAX_ITERATIONS} "+ f"preflight iterations. Escalate to the user, or run with "+ f"--reset-iterations after a code change.\n"+ )+ return EXIT_ITERATION_CAP+ _atomic_write_counter(counter_path, current + 1)+ return 0+++def _atomic_write_counter(path: Path, value: int) -> None:+ """Atomic write of the integer counter (mkstemp + os.replace)."""+ import tempfile+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.name}.", suffix=".tmp")+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as f:+ f.write(f"{int(value)}\n")+ os.replace(tmp, str(path))+ except Exception:+ try:+ os.unlink(tmp)+ except OSError:+ pass+ raise+def _gate_result(gate: int, name: str, passed: bool, violations: Optional[list] = None, warnings: Optional[list] = None, **kwargs: Any) -> dict:return {@@ -496,6 +555,11 @@ def main() -> int:parser.add_argument("--strict", dest="strict", action="store_true", default=True)parser.add_argument("--no-strict", dest="strict", action="store_false")parser.add_argument("--json", action="store_true", help="Emit report JSON to stdout")+ parser.add_argument(+ "--reset-iterations",+ action="store_true",+ help="Reset the per-draft iteration counter to 1 (this run counts as the first).",+ )args = parser.parse_args()draft = Path(args.draft).resolve()@@ -503,6 +567,11 @@ def main() -> int:print(f"ERROR: {draft} is not a directory", file=sys.stderr)return 1+ # VULN-802 (v1.9.1): code-enforced iteration cap. Refuse past MAX_ITERATIONS.+ iteration_exit = _iteration_check(draft, reset=args.reset_iterations)+ if iteration_exit != 0:+ return iteration_exit+gates = [(1, gate_1_capability_discovery),(2, gate_2_format_completeness),diff --git a/tests/test_iteration_counter.py b/tests/test_iteration_counter.pynew file mode 100644index 0000000..6ae1cde--- /dev/null+++ b/tests/test_iteration_counter.py@@ -0,0 +1,100 @@+"""Code-enforced iteration counter tests (VULN-802, v1.9.1).++The 5-gate Blog Delivery Contract documents 'up to 3 retries before+escalating' but v1.9.0 enforced it only as orchestrator prose. This+suite locks in the file-backed counter at <draft>/.iteration-count+that survives across preflight invocations.+"""+from __future__ import annotations++import json+import subprocess+import sys+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parent.parent+PREFLIGHT = ROOT / "scripts" / "blog_preflight.py"+++def _make_minimal_draft(tmp: Path) -> Path:+ """Create a draft folder skeleton sufficient for preflight to run.++ Note: preflight will likely fail Gate 1-5 on this minimal draft.+ That's intentional; the counter test only cares about iteration+ bookkeeping, not gate outcomes.+ """+ draft = tmp / "post"+ draft.mkdir()+ (draft / "post.md").write_text(+ "---\ntitle: t\ndescription: d\n---\n# t\nbody\n",+ encoding="utf-8",+ )+ return draft+++def _run_preflight(draft: Path, *extra) -> subprocess.CompletedProcess:+ cmd = [sys.executable, str(PREFLIGHT), "--draft", str(draft), "--no-strict", *extra]+ return subprocess.run(cmd, capture_output=True, text=True, cwd=str(ROOT))+++def test_first_run_creates_counter_at_one(tmp_path):+ draft = _make_minimal_draft(tmp_path)+ assert not (draft / ".iteration-count").exists()+ _run_preflight(draft)+ counter_file = draft / ".iteration-count"+ assert counter_file.exists()+ assert counter_file.read_text(encoding="utf-8").strip() == "1"+++def test_three_runs_accumulate_to_three(tmp_path):+ draft = _make_minimal_draft(tmp_path)+ for _ in range(3):+ _run_preflight(draft)+ assert (draft / ".iteration-count").read_text(encoding="utf-8").strip() == "3"+++def test_fourth_run_exits_with_code_two(tmp_path):+ draft = _make_minimal_draft(tmp_path)+ for _ in range(3):+ _run_preflight(draft)+ result = _run_preflight(draft)+ assert result.returncode == 2, (+ f"expected exit 2 (iteration cap), got {result.returncode}\n"+ f"stdout: {result.stdout}\nstderr: {result.stderr}"+ )+ assert "ITERATION CAP" in result.stderr.upper() or "iteration" in result.stderr.lower()+++def test_reset_iterations_flag_resets_counter(tmp_path):+ draft = _make_minimal_draft(tmp_path)+ for _ in range(3):+ _run_preflight(draft)+ # 4th would refuse; --reset-iterations clears and allows a fresh run.+ result = _run_preflight(draft, "--reset-iterations")+ assert result.returncode != 2, (+ f"--reset-iterations should allow a fresh run, got exit {result.returncode}"+ )+ assert (draft / ".iteration-count").read_text(encoding="utf-8").strip() == "1"+++def test_corrupted_counter_file_resets_to_one(tmp_path):+ """Tampered counter file (non-int) is treated as 0 and run proceeds.++ Fail-soft: an attacker who can write to the draft folder already has+ bigger problems (can write review.md, modify the .md). Refusing to+ run on garbage counter would create a self-DoS vector.+ """+ draft = _make_minimal_draft(tmp_path)+ (draft / ".iteration-count").write_text("not-an-int", encoding="utf-8")+ result = _run_preflight(draft)+ assert result.returncode != 2+ assert (draft / ".iteration-count").read_text(encoding="utf-8").strip() == "1"+++def test_counter_not_incremented_on_reset_run(tmp_path):+ """--reset-iterations + same-invocation run leaves counter at 1, not 2."""+ draft = _make_minimal_draft(tmp_path)+ _run_preflight(draft, "--reset-iterations")+ assert (draft / ".iteration-count").read_text(encoding="utf-8").strip() == "1"