File size: 13,583 Bytes
584ed90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
"""Narrow Stripe Checkout client for the opt-in external test profile.

The default benchmark never imports credentials or contacts this client.  In
the Cloudflare profile the client talks only to ``stripe.internal``; the edge
proxy validates the request shape and injects the Stripe test secret.
"""

from __future__ import annotations

import hashlib
import hmac
import json
import os
import re
import time
from dataclasses import dataclass
from typing import Any, Mapping
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode, urlsplit
from urllib.request import Request, urlopen


PAYMENT_MODE_LOCAL = "local-sandbox"
PAYMENT_MODE_STRIPE_TEST = "stripe-test"
PAYMENT_MODES = frozenset({PAYMENT_MODE_LOCAL, PAYMENT_MODE_STRIPE_TEST})
STRIPE_INTERNAL_API = "http://stripe.internal/v1"
STRIPE_WEBHOOK_PATH = "/api/stripe/webhook"
STRIPE_WEBHOOK_MAX_BYTES = 64 * 1024
STRIPE_WEBHOOK_TOLERANCE_SECONDS = 300
STRIPE_SESSION_TTL_SECONDS = 30 * 60
STRIPE_MAX_PRODUCT_LINES = 99
STRIPE_PROVIDER_SESSION_PATTERN = re.compile(
    r"^cs_test_[A-Za-z0-9_]{8,240}$"
)


class StripeConfigurationError(ValueError):
    """The explicit Stripe profile is incomplete or unsafe."""


class StripeAPIError(RuntimeError):
    """A provider request failed without exposing provider response details."""


class StripeResponseError(StripeAPIError):
    """The provider returned a malformed or inconsistent response."""


class StripeSignatureError(ValueError):
    """A webhook did not carry a current valid Stripe signature."""


@dataclass(frozen=True, slots=True)
class PaymentConfig:
    mode: str
    api_base: str | None = None
    webhook_secret: str | None = None
    trust_edge_webhook: bool = False

    @property
    def stripe_enabled(self) -> bool:
        return self.mode == PAYMENT_MODE_STRIPE_TEST


def _env_flag(environment: Mapping[str, str], name: str) -> bool:
    return str(environment.get(name, "")).strip().casefold() in {
        "1",
        "true",
        "yes",
        "on",
    }


def load_payment_config(
    environment: Mapping[str, str] | None = None,
) -> PaymentConfig:
    source = os.environ if environment is None else environment
    mode = str(source.get("AMAZON_PAYMENT_MODE", PAYMENT_MODE_LOCAL)).strip()
    if mode not in PAYMENT_MODES:
        raise StripeConfigurationError(
            "AMAZON_PAYMENT_MODE must be local-sandbox or stripe-test"
        )
    if mode == PAYMENT_MODE_LOCAL:
        return PaymentConfig(mode=mode)

    api_base = str(
        source.get("AMAZON_STRIPE_API_URL", STRIPE_INTERNAL_API)
    ).strip().rstrip("/")
    parsed = urlsplit(api_base)
    if (
        parsed.scheme != "http"
        or parsed.hostname != "stripe.internal"
        or parsed.path != "/v1"
        or parsed.username
        or parsed.password
        or parsed.port is not None
        or parsed.query
        or parsed.fragment
    ):
        raise StripeConfigurationError(
            "stripe-test requires the Worker-owned http://stripe.internal/v1 proxy"
        )

    trust_edge = _env_flag(source, "AMAZON_STRIPE_WEBHOOK_TRUST_EDGE")
    webhook_secret = str(
        source.get("STRIPE_TEST_WEBHOOK_SECRET", "")
    ).strip()
    if not trust_edge and not re.fullmatch(r"whsec_[A-Za-z0-9_]{16,240}", webhook_secret):
        raise StripeConfigurationError(
            "stripe-test requires STRIPE_TEST_WEBHOOK_SECRET unless edge verification is enabled"
        )
    return PaymentConfig(
        mode=mode,
        api_base=api_base,
        webhook_secret=webhook_secret or None,
        trust_edge_webhook=trust_edge,
    )


def verify_stripe_signature(
    raw_body: bytes,
    signature_header: str,
    webhook_secret: str,
    *,
    now: int | None = None,
    tolerance_seconds: int = STRIPE_WEBHOOK_TOLERANCE_SECONDS,
) -> int:
    if not raw_body or len(raw_body) > STRIPE_WEBHOOK_MAX_BYTES:
        raise StripeSignatureError("invalid webhook body")
    if not isinstance(signature_header, str) or len(signature_header) > 4096:
        raise StripeSignatureError("invalid webhook signature")
    if not re.fullmatch(r"whsec_[A-Za-z0-9_]{16,240}", webhook_secret):
        raise StripeSignatureError("invalid webhook configuration")

    timestamps: list[int] = []
    signatures: list[str] = []
    for component in signature_header.split(","):
        name, separator, value = component.strip().partition("=")
        if not separator:
            continue
        if name == "t" and value.isascii() and value.isdecimal():
            timestamps.append(int(value))
        elif name == "v1" and re.fullmatch(r"[0-9a-fA-F]{64}", value):
            signatures.append(value.casefold())
    if len(timestamps) != 1 or not signatures:
        raise StripeSignatureError("invalid webhook signature")
    timestamp = timestamps[0]
    current = int(time.time()) if now is None else int(now)
    if abs(current - timestamp) > tolerance_seconds:
        raise StripeSignatureError("stale webhook signature")

    signed = str(timestamp).encode("ascii") + b"." + raw_body
    expected = hmac.new(
        webhook_secret.encode("utf-8"), signed, hashlib.sha256
    ).hexdigest()
    if not any(hmac.compare_digest(expected, candidate) for candidate in signatures):
        raise StripeSignatureError("invalid webhook signature")
    return timestamp


def _safe_product_name(value: Any) -> str:
    normalized = " ".join(str(value or "Amazon Clone item").split())
    if not normalized:
        normalized = "Amazon Clone item"
    return normalized[:240]


def checkout_session_form(
    preparation: Mapping[str, Any],
    *,
    success_url: str,
    cancel_url: str,
) -> list[tuple[str, str]]:
    items = preparation.get("items")
    if not isinstance(items, list) or not items:
        raise StripeResponseError("checkout snapshot has no items")
    if len(items) > STRIPE_MAX_PRODUCT_LINES:
        raise StripeResponseError(
            "Stripe Checkout supports at most 99 product lines plus shipping"
        )
    currency = str(preparation.get("currency") or "").lower()
    if re.fullmatch(r"[a-z]{3}", currency) is None:
        raise StripeResponseError("checkout currency is invalid")
    token = str(preparation.get("checkout_token") or "")
    flow_id = str(preparation.get("flow_id") or "")
    owner = str(preparation.get("owner") or "")
    fingerprint = str(preparation.get("cart_fingerprint") or "")
    amount_minor = int(preparation.get("amount_minor") or -1)
    email = str(preparation.get("customer_email") or "")
    expires_at = int(preparation.get("expires_at") or 0)
    if (
        not re.fullmatch(r"[A-Za-z0-9_-]{24,160}", token)
        or not re.fullmatch(r"payflow_[A-Za-z0-9_-]{12,120}", flow_id)
        or not re.fullmatch(r"[A-Za-z0-9._:-]{8,240}", owner)
        or not re.fullmatch(r"[0-9a-f]{64}", fingerprint)
        or amount_minor < 0
        or not re.fullmatch(r"[^@\s]+@[^@\s]+", email)
        or expires_at <= 0
    ):
        raise StripeResponseError("checkout metadata is invalid")
    for return_url in (success_url, cancel_url):
        parsed = urlsplit(return_url)
        if (
            parsed.scheme not in {"http", "https"}
            or not parsed.netloc
            or parsed.username
            or parsed.password
            or parsed.fragment
        ):
            raise StripeResponseError("checkout return URL is invalid")

    fields: list[tuple[str, str]] = [
        ("mode", "payment"),
        ("payment_method_types[0]", "card"),
        ("payment_method_types[1]", "link"),
        ("customer_email", email),
        ("success_url", success_url),
        ("cancel_url", cancel_url),
        ("client_reference_id", flow_id),
        ("expires_at", str(expires_at)),
        ("metadata[site_id]", "amazon"),
        ("metadata[flow_id]", flow_id),
        ("metadata[owner]", owner),
        ("metadata[amount_minor]", str(amount_minor)),
        ("metadata[currency]", currency.upper()),
        ("metadata[fingerprint]", fingerprint),
        ("metadata[is_simulation]", "true"),
    ]
    for index, item in enumerate(items):
        quantity = int(item.get("quantity") or 0)
        unit_amount = int(item.get("price_minor") or -1)
        if not 1 <= quantity <= 30 or unit_amount < 0:
            raise StripeResponseError("checkout item quote is invalid")
        prefix = f"line_items[{index}]"
        fields.extend(
            (
                (f"{prefix}[price_data][currency]", currency),
                (f"{prefix}[price_data][unit_amount]", str(unit_amount)),
                (
                    f"{prefix}[price_data][product_data][name]",
                    _safe_product_name(item.get("title")),
                ),
                (f"{prefix}[quantity]", str(quantity)),
            )
        )
    shipping_minor = int(preparation.get("shipping_minor") or 0)
    if shipping_minor:
        prefix = f"line_items[{len(items)}]"
        fields.extend(
            (
                (f"{prefix}[price_data][currency]", currency),
                (f"{prefix}[price_data][unit_amount]", str(shipping_minor)),
                (
                    f"{prefix}[price_data][product_data][name]",
                    "Shipping and handling",
                ),
                (f"{prefix}[quantity]", "1"),
            )
        )
    return fields


class StripeGateway:
    """Minimal Checkout Session create/read/expire client."""

    def __init__(self, api_base: str = STRIPE_INTERNAL_API, timeout: float = 10.0):
        self.api_base = api_base.rstrip("/")
        self.timeout = timeout

    def _request(
        self,
        method: str,
        path: str,
        fields: list[tuple[str, str]] | None = None,
        *,
        idempotency_key: str | None = None,
    ) -> dict[str, Any]:
        body = urlencode(fields or []).encode("utf-8") if fields is not None else None
        headers = {
            "Accept": "application/json",
            "User-Agent": "WebsiteBench-Amazon-Stripe-Test/1.0",
        }
        effects_token = os.environ.get(
            "WEBSITEBENCH_EFFECTS_INTERNAL_TOKEN",
            os.environ.get("CLAWBENCH_EFFECTS_INTERNAL_TOKEN", ""),
        ).strip()
        if effects_token:
            headers["X-WebsiteBench-Effects-Token"] = effects_token
        if body is not None:
            headers["Content-Type"] = "application/x-www-form-urlencoded"
        if idempotency_key is not None:
            headers["Idempotency-Key"] = idempotency_key
        request = Request(
            f"{self.api_base}{path}",
            data=body,
            headers=headers,
            method=method,
        )
        try:
            with urlopen(request, timeout=self.timeout) as response:
                raw = response.read(256 * 1024 + 1)
        except (HTTPError, URLError, TimeoutError, OSError) as exc:
            raise StripeAPIError("Stripe test service is temporarily unavailable") from exc
        if len(raw) > 256 * 1024:
            raise StripeResponseError("Stripe response was too large")
        try:
            payload = json.loads(raw.decode("utf-8"))
        except (UnicodeDecodeError, json.JSONDecodeError) as exc:
            raise StripeResponseError("Stripe returned an invalid response") from exc
        if not isinstance(payload, dict):
            raise StripeResponseError("Stripe returned an invalid response")
        return payload

    def create_checkout_session(
        self,
        preparation: Mapping[str, Any],
        *,
        success_url: str,
        cancel_url: str,
    ) -> dict[str, Any]:
        payload = self._request(
            "POST",
            "/checkout/sessions",
            checkout_session_form(
                preparation,
                success_url=success_url,
                cancel_url=cancel_url,
            ),
            idempotency_key=str(preparation["provider_idempotency_key"]),
        )
        session_id = str(payload.get("id") or "")
        checkout_url = str(payload.get("url") or "")
        parsed = urlsplit(checkout_url)
        if (
            STRIPE_PROVIDER_SESSION_PATTERN.fullmatch(session_id) is None
            or parsed.scheme != "https"
            or parsed.hostname != "checkout.stripe.com"
            or parsed.username
            or parsed.password
            or parsed.port is not None
            or parsed.fragment
        ):
            raise StripeResponseError("Stripe returned an invalid Checkout Session")
        return payload

    def retrieve_checkout_session(self, session_id: str) -> dict[str, Any]:
        if STRIPE_PROVIDER_SESSION_PATTERN.fullmatch(session_id) is None:
            raise StripeResponseError("Stripe Checkout Session ID is invalid")
        return self._request("GET", f"/checkout/sessions/{session_id}")

    def expire_checkout_session(self, session_id: str) -> dict[str, Any]:
        if STRIPE_PROVIDER_SESSION_PATTERN.fullmatch(session_id) is None:
            raise StripeResponseError("Stripe Checkout Session ID is invalid")
        return self._request(
            "POST", f"/checkout/sessions/{session_id}/expire", []
        )


__all__ = [
    "PAYMENT_MODE_LOCAL",
    "PAYMENT_MODE_STRIPE_TEST",
    "PaymentConfig",
    "STRIPE_MAX_PRODUCT_LINES",
    "STRIPE_PROVIDER_SESSION_PATTERN",
    "STRIPE_SESSION_TTL_SECONDS",
    "STRIPE_WEBHOOK_MAX_BYTES",
    "STRIPE_WEBHOOK_PATH",
    "StripeAPIError",
    "StripeConfigurationError",
    "StripeGateway",
    "StripeResponseError",
    "StripeSignatureError",
    "checkout_session_form",
    "load_payment_config",
    "verify_stripe_signature",
]