#!/usr/bin/env python3 """Review a TESI credit pack, manage one recoverable purchase, or preview/redeem a promotional code.""" import argparse from hashlib import sha256 import http.client import json import os from pathlib import Path import re import secrets import stat import sys from urllib.parse import urlsplit DEFAULT_ORIGIN = "https://toolsenabled.ai" PRODUCTION_ORIGINS = frozenset({"https://toolsenabled.ai", "https://toolsenabled.ai"}) ENDPOINT = "/api/v1/agents/keys" MAX_BYTES = 16_384 MAX_OFFER_BYTES = 262_144 PURCHASE = re.compile(r"[a-f0-9]{64}") ORDER = re.compile(r"ago_[a-f0-9]{32}") SESSION = re.compile(r"cs_(?:live|test)_[A-Za-z0-9]{8,240}") KEY = re.compile(r"tesi_ak_[A-Za-z0-9_-]{20,80}") KEY_ID = re.compile(r"agk_[a-f0-9]{24}") WORKSPACE = re.compile(r"ws_[a-f0-9]{24}") GIFT_CODE = re.compile(r"[A-Za-z0-9_-]{6,64}") HOST_HEADER = re.compile(r"[a-z0-9.-]{1,253}(?::[0-9]{1,5})?") REFUSALS = { "agent_amount", "agent_order_unknown", "checkout_expired", "checkout_reconciling", "gift_already_claimed", "gift_request", "gift_unavailable", "gift_unknown", "key_already_claimed", "key_delivery_saved", "payment_refunded", "purchase_conflict", } class BuyerError(Exception): def __init__(self, status, exit_code=2, **fields): self.result = {"status": status, **fields} self.exit_code = exit_code def valid(pattern, value): return isinstance(value, str) and bool(pattern.fullmatch(value)) def parse_object(raw, limit=MAX_BYTES): try: value = json.loads(raw.decode("utf-8")) if len(raw) <= limit else None except (ValueError, RecursionError): value = None if not isinstance(value, dict): raise ValueError("Expected a bounded JSON object") return value def resolve_target(): raw_origin = os.environ.get("TESI_ORIGIN", DEFAULT_ORIGIN).strip().rstrip("/") parsed = urlsplit(raw_origin) if parsed.path or parsed.query or parsed.fragment or parsed.username or parsed.password: raise BuyerError("invalid_origin") if raw_origin in PRODUCTION_ORIGINS: scheme, host, port = "https", parsed.hostname, parsed.port or 443 public_host = parsed.netloc elif ( os.environ.get("TESI_ALLOW_LOOPBACK_ORIGIN") == "1" and parsed.scheme == "http" and parsed.hostname == "127.0.0.1" and parsed.port ): scheme, host, port = "http", "127.0.0.1", parsed.port public_host = f"127.0.0.1:{port}" else: raise BuyerError("invalid_origin") override = os.environ.get("TESI_HOST_HEADER", "").strip() if override: if not HOST_HEADER.fullmatch(override): raise BuyerError("invalid_origin") host_header = override else: host_header = public_host review_origin = f"https://{host_header}" if scheme == "http" and override else raw_origin return scheme, host, port, host_header, review_origin def open_connection(): scheme, host, port, host_header, review_origin = resolve_target() cls = http.client.HTTPSConnection if scheme == "https" else http.client.HTTPConnection return cls(host, port, timeout=15), host_header, review_origin class PurchaseDirectory: def __init__(self, path, create): if create: path.mkdir(mode=0o700, exist_ok=True) self.fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) info = os.fstat(self.fd) if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != 0o700: os.close(self.fd) raise BuyerError("purchase_directory_must_be_private") self.path = path def close(self): os.close(self.fd) def read(self, name): try: fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=self.fd) except FileNotFoundError: return None with os.fdopen(fd, "rb") as stream: info = os.fstat(stream.fileno()) if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != 0o600): raise BuyerError("purchase_file_must_be_private") try: return parse_object(stream.read(MAX_BYTES + 1)) except ValueError: raise BuyerError("invalid_local_purchase_file") from None def publish(self, name, data): temporary = ".pending-" + secrets.token_hex(16) fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600, dir_fd=self.fd) try: with os.fdopen(fd, "wb") as stream: os.fchmod(stream.fileno(), 0o600) stream.write((json.dumps(data, sort_keys=True) + "\n").encode("utf-8")) stream.flush() os.fsync(stream.fileno()) try: os.link(temporary, name, src_dir_fd=self.fd, dst_dir_fd=self.fd, follow_symlinks=False) except FileExistsError: pass finally: os.unlink(temporary, dir_fd=self.fd) os.fsync(self.fd) return self.read(name) def read_purchase(directory): state = directory.read("purchase.json") if not state: raise BuyerError("purchase_draft_required") amount = state.get("amountCents") if (state.get("schema") != 1 or not valid(PURCHASE, state.get("purchaseId")) or type(amount) is not int or not 0 < amount <= 9_007_199_254_740_991): raise BuyerError("invalid_local_purchase_file") return {"purchaseId": state["purchaseId"], "amountCents": amount} def draft(directory, amount): if not 0 < amount <= 9_007_199_254_740_991: raise BuyerError("invalid_amount_cents") if directory.read("purchase.json") is None: directory.publish("purchase.json", {"schema": 1, "amountCents": amount, "purchaseId": secrets.token_hex(32)}) if read_purchase(directory)["amountCents"] != amount: raise BuyerError("purchase_amount_already_fixed") return {"status": "draft_saved", "amountCents": amount, "currency": "usd"} def rate_limited(response): value = response.getheader("Retry-After") or "" seconds = int(value) if re.fullmatch(r"[0-9]{1,9}", value) else None return BuyerError("rate_limited", 3, httpStatus=429, retryAfterSeconds=seconds) def quote_pack(amount): if not 100 <= amount <= 1_000_000: raise BuyerError("invalid_amount_cents") connection, host_header, review_origin = open_connection() try: connection.request("GET", "/api/v1/agents", headers={"Accept": "application/json", "Host": host_header}) response = connection.getresponse() code = response.status if code == 429: raise rate_limited(response) if code != 200: raise BuyerError("offer_unavailable", 3, httpStatus=code) if response.getheader("Content-Type", "").split(";", 1)[0].strip().lower() != "application/json": raise BuyerError("invalid_offer", 3, httpStatus=code) try: offer = parse_object(response.read(MAX_OFFER_BYTES + 1), MAX_OFFER_BYTES) amounts = offer["amountsCents"] if (offer["service"] != "TESI Agent API" or offer["currency"] != "usd" or type(offer["available"]) is not bool or not isinstance(amounts, list) or not 1 <= len(amounts) <= 10 or any(type(item) is not int or not 100 <= item <= 1_000_000 for item in amounts) or len(amounts) != len(set(amounts))): raise ValueError except (KeyError, ValueError): raise BuyerError("invalid_offer", 3, httpStatus=code) from None finally: connection.close() if not offer["available"]: raise BuyerError("offer_unavailable", 3, httpStatus=code) if amount not in amounts: raise BuyerError("pack_unavailable", advertisedAmountsCents=amounts) return {"status": "pack_review_ready", "amountCents": amount, "currency": "usd", "reviewUrl": f"{review_origin}/agents/?agentPack={amount}#agent-funding"} def post(body, key=None): connection, host_header, _ = open_connection() headers = {"Accept": "application/json", "Content-Type": "application/json", "Host": host_header} if key: headers["Authorization"] = "Bearer " + key try: connection.request("POST", ENDPOINT, json.dumps(body), headers) response = connection.getresponse() code = response.status if code == 429: raise rate_limited(response) if response.getheader("Content-Type", "").split(";", 1)[0].strip().lower() != "application/json": raise BuyerError("unconfirmed_response", 3, httpStatus=code) try: data = parse_object(response.read(MAX_BYTES + 1)) except ValueError: raise BuyerError("unconfirmed_response", 3, httpStatus=code) from None finally: connection.close() if code not in (200, 201, 402): error = data.get("error") status = error if isinstance(error, str) and error in REFUSALS else "unconfirmed_response" exit_code = 2 if status in ("gift_unknown", "gift_already_claimed", "gift_request", "agent_amount") else 3 raise BuyerError(status, exit_code, httpStatus=code) return code, data def read_gift_code(use_stdin): if use_stdin: raw = sys.stdin.read(129) if len(raw) > 128: raise BuyerError("invalid_gift_code") code = raw.strip() else: code = os.environ.get("TESI_GIFT_CODE", "").strip() if not code: raise BuyerError("gift_code_required") if not valid(GIFT_CODE, code): raise BuyerError("invalid_gift_code") return code def preview_gift_code(code): status_code, data = post({"giftCode": code, "preview": True}) if (status_code != 200 or data.get("funding") != "promotional" or data.get("currency") != "usd" or type(data.get("creditCents")) is not int or type(data.get("redeemable")) is not bool): raise BuyerError("unconfirmed_response", 3, httpStatus=status_code) return { "status": "gift_preview_ready", "funding": "promotional", "currency": "usd", "creditCents": data["creditCents"], "redeemable": data["redeemable"], } def redeem_gift_code(directory, code): existing = directory.read("key.json") if existing is not None: if (not valid(KEY, existing.get("apiKey")) or not valid(KEY_ID, existing.get("keyId")) or not valid(WORKSPACE, existing.get("workspaceId"))): raise BuyerError("saved_key_mismatch") return { "status": "key_saved_locally", "funding": existing.get("funding", "promotional"), "keyId": existing["keyId"], "keyPrefix": existing["apiKey"][:14], "workspaceId": existing["workspaceId"], "credentialFile": str(directory.path / "key.json"), "alreadySaved": True, } status_code, data = post({"giftCode": code}) if status_code != 201: raise BuyerError("unconfirmed_claim", 3, httpStatus=status_code) entry = { "apiKey": data.get("apiKey"), "funding": "promotional", "keyId": data.get("keyId"), "workspaceId": data.get("workspaceId"), } if (not valid(KEY, entry["apiKey"]) or not valid(KEY_ID, entry["keyId"]) or not valid(WORKSPACE, entry["workspaceId"]) or type(data.get("creditCents")) is not int): raise BuyerError("unconfirmed_claim", 3) if directory.publish("key.json", entry) != entry: raise BuyerError("saved_key_mismatch") return { "status": "key_saved_locally", "funding": "promotional", "keyId": entry["keyId"], "keyPrefix": entry["apiKey"][:14], "workspaceId": entry["workspaceId"], "creditCents": data["creditCents"], "credentialFile": str(directory.path / "key.json"), } def read_session(directory, purchase): state = directory.read("session.json") if state is None: return None digest = sha256(purchase["purchaseId"].encode("ascii")).hexdigest() if (state.get("purchaseDigest") != digest or not valid(ORDER, state.get("orderId")) or not valid(SESSION, state.get("sessionId"))): raise BuyerError("saved_session_mismatch") return state def checkout(directory, purchase): prior = read_session(directory, purchase) code, data = post(purchase) status = data.get("status") amount = purchase["amountCents"] if (type(data.get("amountCents")) is not int or data["amountCents"] != amount or data.get("currency") != "usd" or not valid(ORDER, data.get("orderId")) or (prior and prior["orderId"] != data["orderId"])): raise BuyerError("checkout_does_not_match_purchase", 3) details = {"status": status, "amountCents": amount, "currency": "usd"} if code == 402 and status in ("expired", "refunded"): if prior and data.get("sessionId") != prior["sessionId"]: raise BuyerError("checkout_does_not_match_purchase", 3) return details if code == 200 and status == "claimed": if prior is None: raise BuyerError("original_session_file_required") return details expected = code == 402 and status in ("open", "pending") or code == 200 and status == "paid" claim_body = data.get("claimBody") if (not expected or data.get("claimRequiresPurchaseId") is not True or not isinstance(claim_body, dict) or claim_body.get("sessionId") != data.get("sessionId") or not valid(SESSION, data.get("sessionId"))): raise BuyerError("unconfirmed_checkout", 3) if status == "open": url = data.get("checkoutUrl") try: link = urlsplit(url) if isinstance(url, str) else None if (not link or link.scheme != "https" or link.netloc != "checkout.stripe.com" or not link.path.startswith("/") or any(char.isspace() for char in url)): raise ValueError except ValueError: raise BuyerError("unexpected_checkout_destination", 3) from None details["checkoutUrl"] = url saved = {"purchaseDigest": sha256(purchase["purchaseId"].encode("ascii")).hexdigest(), "sessionId": data["sessionId"], "orderId": data["orderId"]} if directory.publish("session.json", saved) != saved: raise BuyerError("saved_session_mismatch") return details def read_key(directory, order_id): entry = directory.read("key.json") if entry is not None and (entry.get("orderId") != order_id or not valid(KEY, entry.get("apiKey")) or not valid(KEY_ID, entry.get("keyId")) or not valid(WORKSPACE, entry.get("workspaceId"))): raise BuyerError("saved_key_mismatch") return entry def claim(directory, session, body): if read_key(directory, session["orderId"]) is not None: return {"status": "key_saved_locally", "credentialFile": str(directory.path / "key.json")} code, data = post(body) if code == 402: error = data.get("error") if error == "payment_refunded": return {"status": "refunded"} if data.get("sessionId") != session["sessionId"]: raise BuyerError("unconfirmed_claim", 3) if error == "checkout_expired": return {"status": "expired"} if error == "payment_required": return {"status": "payment_pending"} raise BuyerError("unconfirmed_claim", 3) entry = {"orderId": session["orderId"], **{name: data.get(name) for name in ("apiKey", "keyId", "workspaceId")}} if (not valid(KEY, entry["apiKey"]) or not valid(KEY_ID, entry["keyId"]) or not valid(WORKSPACE, entry["workspaceId"]) or type(data.get("keyRecoveryUntil")) is not int): raise BuyerError("unconfirmed_claim", 3) if directory.publish("key.json", entry) != entry: raise BuyerError("saved_key_mismatch") return {"status": "key_saved_locally", "credentialFile": str(directory.path / "key.json")} def confirm(directory, session, body): entry = read_key(directory, session["orderId"]) if entry is None: raise BuyerError("saved_key_required") expected = {"status": "saved", "keyId": entry["keyId"]} marker = directory.read("confirmation.json") if marker is not None and marker != expected: raise BuyerError("saved_confirmation_mismatch") if marker is None: code, data = post({**body, "saved": True}, entry["apiKey"]) if code != 200 or data != expected: raise BuyerError("unconfirmed_save", 3) if directory.publish("confirmation.json", expected) != expected: raise BuyerError("saved_confirmation_mismatch") return {"status": "delivery_confirmed"} def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest="action", required=True) quote = commands.add_parser("quote", help="read the public offer and return a link to review one exact pack") quote.add_argument("--amount-cents", type=int, required=True) preview_cmd = commands.add_parser("preview-code", help="preview a promotional code from TESI_GIFT_CODE or --code-stdin without consuming it") preview_cmd.add_argument("--code-stdin", action="store_true", help="read the promotional code from standard input") redeem_cmd = commands.add_parser("redeem-code", help="redeem a promotional code from TESI_GIFT_CODE or --code-stdin into a private 0700 directory") redeem_cmd.add_argument("directory", type=Path, help="one private 0700 directory to store mode-0600 key.json") redeem_cmd.add_argument("--code-stdin", action="store_true", help="read the promotional code from standard input") for action, help_text in ( ("draft", "save one new purchase locally without a network request"), ("checkout", "prepare or resume this purchase after purchaser approval"), ("claim", "claim or recover the funded key and save it privately"), ("confirm", "close recovery after checking the saved key"), ): command = commands.add_parser(action, help=help_text) command.add_argument("directory", type=Path, help="one private directory per purchase") if action == "draft": command.add_argument("--amount-cents", type=int, required=True) args = parser.parse_args(argv) exit_code = 0 directory = None try: if args.action == "quote": result = quote_pack(args.amount_cents) elif args.action == "preview-code": result = preview_gift_code(read_gift_code(args.code_stdin)) elif args.action == "redeem-code": code = read_gift_code(args.code_stdin) directory = PurchaseDirectory(args.directory, create=True) result = redeem_gift_code(directory, code) else: directory = PurchaseDirectory(args.directory, create=args.action == "draft") if args.action == "draft": result = draft(directory, args.amount_cents) else: purchase = read_purchase(directory) os.fsync(directory.fd) if args.action == "checkout": result = checkout(directory, purchase) else: session = read_session(directory, purchase) if session is None: raise BuyerError("original_session_file_required") body = {"sessionId": session["sessionId"], "purchaseId": purchase["purchaseId"]} result = claim(directory, session, body) if args.action == "claim" else confirm(directory, session, body) except BuyerError as error: result, exit_code = error.result, error.exit_code except (http.client.HTTPException, TimeoutError, ConnectionError): result, exit_code = {"status": "unconfirmed_response"}, 3 except OSError: result, exit_code = {"status": "file_or_connection_unavailable"}, 3 finally: if directory: directory.close() print(json.dumps(result, sort_keys=True)) return exit_code if __name__ == "__main__": raise SystemExit(main())