Skip to content

Autonomous AI sales agent powered by Claude Code or Codex. Finds prospects, writes cold emails, sends campaigns, handles replies, books meetings. No API keys needed — runs on your Claude or Codex subscriptions.

Integrate #16 with validated checkout URLs and credential-safe fallback

Ethan+c63b6ced14bb
diff --cc harvey/integrations/precleared.py
index dd2c32a,bfdef68..fbf81e5
--- a/harvey/integrations/precleared.py
+++ b/harvey/integrations/precleared.py
@@@ -27,10 -25,10 +27,13 @@@ reason gives the checkout link from Pre
"""
import hashlib
++import ipaddress
import json
import logging
++import re
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
++from urllib.parse import unquote, urlsplit
import httpx
@@@ -173,18 -167,6 +176,18 @@@ class PreclearedClient
reason="Precleared daily allowance used up; add PRECLEARED_API_KEY "
"(free key: https://precleared.dev/get-key) or wait until tomorrow",
)
+ if resp.status_code == 402:
+ # The key's free checks for today are used and it has no credits left,
+ # so another key won't help: a pack (or tomorrow's allowance) will.
+ # The 402 answer carries a checkout link for this key.
+ return Clearance(
+ allowed=False, held=True,
+ reason=self._redact(
+ "Precleared: today's free checks on your key are used and it has "
- f"no credits left; add a pack ({_buy_url(resp)}) "
++ f"no credits left; add a pack ({_buy_url(resp, self.api_key)}) "
+ "or wait until tomorrow"
+ ),
+ )
if resp.status_code == 401:
return Clearance(allowed=False, held=True,
reason="PRECLEARED_API_KEY was rejected (wrong or revoked)")
@@@ -225,28 -207,6 +228,65 @@@ def _text(value) -> str
return value.strip() if isinstance(value, str) else ""
- def _buy_url(resp: httpx.Response) -> str:
++def _buy_url(resp: httpx.Response, api_key: str = "") -> str:
+ """The checkout link from a 402 answer's ``buy_url``, or BUY_URL.
+
+ Only a plain https link of sane length is used; a missing, malformed or
+ non-JSON body falls back to Precleared's buy page.
+ """
+ try:
+ data = resp.json()
+ except ValueError:
+ return BUY_URL
+ url = data.get("buy_url") if isinstance(data, dict) else None
- if (
++ if not (
+ isinstance(url, str)
- and url.startswith("https://")
+ and len(url) <= MAX_BUY_URL
+ and url.isprintable()
+ and not any(ch.isspace() for ch in url)
++ and "\\" not in url
+ ):
- return url
- return BUY_URL
++ return BUY_URL
++ try:
++ parsed = urlsplit(url)
++ host = parsed.hostname
++ port = parsed.port # Access validates numeric syntax and range.
++ if (parsed.scheme != "https" or not host or parsed.username is not None
++ or parsed.password is not None or "%" in parsed.netloc
++ or parsed.netloc.endswith(":") or port == 0):
++ return BUY_URL
++ if ":" in host:
++ ipaddress.IPv6Address(host)
++ # urlsplit accepts suffixes after the closing bracket; a browser
++ # need not interpret that malformed authority the same way.
++ if not re.fullmatch(r"\[[0-9a-fA-F:.]+\](?::[0-9]+)?", parsed.netloc):
++ return BUY_URL
++ else:
++ ascii_host = host.encode("idna").decode("ascii").rstrip(".")
++ if len(ascii_host) > 253 or not all(
++ re.fullmatch(r"[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?", label)
++ for label in ascii_host.split(".")
++ ):
++ return BUY_URL
++ except (ValueError, UnicodeError):
++ return BUY_URL
++
++ if api_key:
++ # Inspect decoded copies, but keep a usable checkout/session URL intact.
++ # Reject excessive nesting instead of logging a credential we could not
++ # finish checking. unquote handles upper/lower-case percent escapes.
++ decoded = url
++ for _ in range(8):
++ if api_key in decoded:
++ return BUY_URL
++ next_decoded = unquote(decoded)
++ if next_decoded == decoded:
++ return url
++ decoded = next_decoded
++ return BUY_URL
++ return url
+
+
def _reason(data: dict) -> str:
"""One readable line: the rule that decided it (or the note), then the next step.
diff --cc tests/test_precleared_checkout.py
index 0000000,0000000..e63a1db
new file mode 100644
--- /dev/null
+++ b/tests/test_precleared_checkout.py
@@@ -1,0 -1,0 +1,97 @@@
++"""Checkout safety and quota recovery; all requests and sending are mocked."""
++from urllib.parse import quote, unquote
++import httpx
++import pytest
++from harvey.integrations.precleared import PreclearedClient, SETTINGS_PREFIX, BUY_URL
++from tests.test_precleared import state, queue, with_check, OK_BODY
++from tests.test_outbox_native import seed_prospect, FakeProvider, make_sender
++
++ 'https://',
++ 'https:///buy',
++ 'https://?checkout=123',
++ 'https://precleared.dev:invalid/buy',
++ 'https://precleared.dev:65536/buy',
++ 'https://precleared.dev:/buy',
++ 'https://precleared.dev:0/buy',
++ 'https://[email protected]/buy',
++ 'https://user:[email protected]/buy',
++ 'https://precleared.dev\\@evil.example/buy',
++ 'https://%70recleared.dev/buy',
++ 'https://[not-ipv6]/buy',
++ 'https://bad_host.example/buy',
++ 'https://-bad.example/buy',
++ 'https://a..example/buy',
++ 'https://[::1]extra/buy',
++])
++async def test_malformed_https_link_uses_fallback(state, url):
++ client = PreclearedClient("GB", api_key="pc_test_review", transport=httpx.MockTransport(
++ lambda r: httpx.Response(402, json={"buy_url": url})))
++ result = await client.clear("[email protected]", state)
++ assert result.held and not result.allowed
++ assert f"add a pack ({BUY_URL})" in result.reason
++
++async def test_402_holds_sequences_allows_reply_then_recovers_next_cycle(state):
++ first = await seed_prospect(state)
++ second = await seed_prospect(state, email="[email protected]")
++ reply = await seed_prospect(state, email="[email protected]", status="replied")
++ await queue(state, first)
++ await queue(state, second, to="[email protected]")
++ await queue(state, reply, kind="reply", to="[email protected]")
++ calls = []
++ def limited(request):
++ calls.append(request)
++ return httpx.Response(402, json={"buy_url": "https://checkout.stripe.com/c/pay/example"})
++ provider = FakeProvider()
++ sender = with_check(make_sender(state, provider), httpx.MockTransport(limited), api_key="pc_test_review")
++ await sender._drain_due()
++ assert len(calls) == 1
++ assert [m["to"] for m in provider.sent] == ["[email protected]"]
++ assert len(await state.get_outbox(status="approved")) == 2
++ assert not await state.get_outbox(status="failed")
++ assert await state.get_setting(SETTINGS_PREFIX + "[email protected]") == ""
++ sender.precleared._transport = httpx.MockTransport(lambda r: httpx.Response(200, json=OK_BODY))
++ await sender._drain_due()
++ assert sorted(m["to"] for m in provider.sent) == ["[email protected]", "[email protected]", "[email protected]"]
++ assert not await state.get_outbox(status="approved")
++
[email protected]("encoding", ["literal", "upper", "lower", "mixed", "nested", "excessive"])
[email protected]("location", ["path", "query", "fragment"])
++async def test_encoded_key_not_exposed_in_checkout_reason(state, encoding, location):
++ key = "pc_live_secret123"
++ encoded = "".join("%{:02X}".format(ord(c)) for c in key)
++ if encoding == "literal":
++ encoded = key
++ elif encoding == "lower":
++ encoded = encoded.lower()
++ elif encoding == "mixed":
++ encoded = "".join(c.lower() if i % 2 else c for i, c in enumerate(encoded))
++ elif encoding in ("nested", "excessive"):
++ for _ in range(2 if encoding == "nested" else 10):
++ encoded = quote(encoded, safe="")
++ checkout = "https://checkout.stripe.com/" + {
++ "path": encoded, "query": "pay?key=" + encoded, "fragment": "pay#" + encoded,
++ }[location]
++ client = PreclearedClient("GB", api_key=key, transport=httpx.MockTransport(
++ lambda r: httpx.Response(402, json={"buy_url": checkout})))
++ result = await client.clear("[email protected]", state)
++ assert f"add a pack ({BUY_URL})" in result.reason
++ assert key not in unquote(result.reason)
++ assert await state.get_setting(SETTINGS_PREFIX + "[email protected]") == ""
++
++
[email protected]("checkout", [
++ "https://checkout.stripe.com/c/pay/cs_test_example123#fidexample",
++ "https://checkout.stripe.com:443/c/pay/cs_test_example123?return=a%2Fb#fid%23example",
++ "https://checkout.stripe.com/c/pay/pc_live_unrelated456#fidexample",
++])
++async def test_valid_checkout_is_preserved_exactly(state, checkout):
++ client = PreclearedClient("GB", api_key="pc_live_secret123", transport=httpx.MockTransport(
++ lambda r: httpx.Response(402, json={"buy_url": checkout})))
++ result = await client.clear("[email protected]", state)
++ assert result.held and not result.allowed
++ assert f"add a pack ({checkout})" in result.reason