← Files Cactus: Real Estate AnalysisARCHIVED FILE
skills/cactus/scripts/transfer-file.py
4.05 KB · Dec 1, 2026 · 00:13 UTC
"""Transfer an authorized local attachment with a Cactus file-scoped POST ticket.
inspect FILE prints metadata. upload FILE reads data.upload JSON from stdin.
Tickets must never be placed in command arguments, logs, or committed files.
"""
import argparse
import base64
import hashlib
import json
import mimetypes
from pathlib import Path
import re
import sys
from urllib.error import HTTPError, URLError
from urllib.parse import urlparse
from urllib.request import HTTPRedirectHandler, Request, build_opener
import uuid
MAX_BYTES = 25 * 1024 * 1024
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["inspect", "upload"])
parser.add_argument("file", type=Path)
args = parser.parse_args()
with args.file.open("rb") as source:
data = source.read(MAX_BYTES + 1)
if not 0 < len(data) <= MAX_BYTES:
raise ValueError("File is empty or exceeds the supported size.")
digest = hashlib.sha256(data).hexdigest()
if args.action == "inspect":
print(json.dumps({"filename": args.file.name, "size_bytes": len(data),
"sha256": digest,
"content_type": mimetypes.guess_type(args.file.name)[0]
or "application/octet-stream"}))
return
raw = sys.stdin.read(65537)
if len(raw) > 65536:
raise ValueError("Upload authorization is too large.")
ticket = json.loads(raw)
parsed = urlparse(ticket["url"])
fields = ticket["fields"]
if (parsed.scheme != "https" or parsed.username or parsed.password
or parsed.port not in (None, 443) or parsed.query or parsed.fragment
or not re.fullmatch(r"[a-z0-9.-]+\.s3(?:\.[a-z0-9-]+)?\.amazonaws\.com", parsed.hostname or "")
or not isinstance(fields, dict)
or not str(fields.get("key", "")).startswith("plugin-sessions/")
or ticket.get("size_bytes") != len(data) or ticket.get("sha256") != digest
or fields.get("x-amz-checksum-algorithm") != "SHA256"
or fields.get("x-amz-checksum-sha256") != base64.b64encode(bytes.fromhex(digest)).decode()):
raise ValueError("File does not match its upload authorization.")
boundary = "cactus-" + uuid.uuid4().hex
body = bytearray()
for name, value in fields.items():
if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_-]+", name) or not isinstance(value, str):
raise ValueError("Invalid upload authorization field.")
body.extend(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n'.encode())
body.extend(value.encode())
body.extend(b"\r\n")
# A fixed multipart filename avoids interpreting characters in a local path.
body.extend(f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="upload"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode())
body.extend(data)
body.extend(f"\r\n--{boundary}--\r\n".encode())
request = Request(ticket["url"], data=bytes(body), method="POST",
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"})
with build_opener(NoRedirect).open(request, timeout=180) as response:
if not 200 <= response.status < 300:
raise ValueError("Upload was not accepted.")
print(json.dumps({"uploaded": True, "size_bytes": len(data), "sha256": digest,
"next_action": "complete_plugin_session_upload"}))
if __name__ == "__main__":
try:
main()
except HTTPError as error:
print(json.dumps({"uploaded": False, "error": f"Upload rejected (HTTP {error.code}). Refresh authorization and retry."}))
sys.exit(1)
except (OSError, ValueError, KeyError, TypeError, URLError):
# Avoid printing signed URLs, filesystem details or remote response bodies.
print(json.dumps({"uploaded": False, "error": "Could not upload this file. Check file access and refresh authorization."}))
sys.exit(1)
SHA-256: c512a013b641d65e9e19d351eea33c0ec4465589ef39b8dc085eccf30a2d2209