diff --git a/docs/payment-billing.md b/docs/payment-billing.md new file mode 100644 index 00000000..22356db9 --- /dev/null +++ b/docs/payment-billing.md @@ -0,0 +1,165 @@ +# Top-ups and payment billing + +Payments create explicit USD top-ups through Stripe Checkout. A browser redirect +has no effect on a balance. Credits come only from signed processor evidence and +the configured credits ledger callback. + +## Configuration + +Payments are disabled by default. With `PAYMENTS_ENABLED` unset, empty or false, +every `/v1/payments/*` request returns JSON 404 without payment storage or +processor access. A malformed flag or configuration disables payments and emits +one warning without configuration values. + +An enabled example uses references to privately configured secrets: + +```json +{ + "PAYMENTS_ENABLED": "true", + "PAYMENT_PROCESSOR_CONFIG_JSON": "{\"processor\":\"stripe\",\"secret_key_ref\":\"STRIPE_MERCHANT_SECRET\",\"return_origins\":[\"https://billing.example.com\"],\"product_name\":\"Gateway credits\"}", + "PAYMENT_WEBHOOK_KEY_REF": "STRIPE_ENDPOINT_SECRET" +} +``` + +The merchant key and webhook signing secret are supplied by the host's secret +resolver. Their values never belong in the JSON configuration, responses or +logs. Use a webhook endpoint belonging to the same direct Stripe merchant as +the Checkout key. Connected-account events are rejected. Test and live mode +must match the Checkout Session returned by Stripe. + +Payment routes require a migrated durable store. The private D1 domain is +`http://intelligence.internal/v1/managed-state/payments`, with fixed reserve, +save, find, claim and finish operations. `D1PaymentStore` accepts a private +transport; `SqlPaymentStore` accepts an existing migrated SQLite database. +Neither creates tables or falls back to memory. Missing tables, missing +columns, unavailable storage or unconnected storage return JSON 503 +`payments_unavailable` before any processor request. Apply the additive payment +migration through the normal migration process before enabling the flag. + +## Checkout + +Send a gateway key to `POST /v1/payments/checkout` with: + +```json +{ + "amount_microusd": 500000, + "currency": "USD", + "idempotency_key": "topup-2026-10-09-001", + "return_url": "https://billing.example.com/return" +} +``` + +The default permission grants only the verified key owner in the legacy +single-principal scope. Organisation workspaces require the injected permission +authority to verify a billing or admin role and an injected verified tenant +context resolver. Client body fields cannot select a workspace. Gateway key +scope enforcement also applies. + +Amounts are integer micro-USD, in whole cents: multiples of 10,000, from 500,000 +($0.50) to 1,000,000,000 ($1,000). The currency is exactly `USD`. The return URL +must use HTTPS and match an allowlisted origin, including its port, exactly. +An idempotency key is an opaque 1–128 character identifier using letters, +digits, underscores, colons, periods or hyphens. + +At most ten distinct checkout reservations are accepted per principal per UTC +day, including processor failures. Reusing the same scoped idempotency key and +body returns the same checkout without consuming another reservation. Reusing +it with a different body returns 409 `payment_idempotency_conflict`. Concurrent +creation in another process can return retryable 503 +`payment_checkout_processing`; retry the same key and body. + +The processor request is form encoded, goes only to +`https://api.stripe.com/v1/checkout/sessions`, has redirects disabled and uses +the opaque checkout ID as Stripe's idempotency key and client reference. Its +only metadata is that opaque ID. Processor failures return 503 +`payment_processor_unavailable`; retrying preserves the original processor +idempotency ID. + +A successful checkout response is: + +```json +{ + "checkout_id": "pay_example", + "url": "https://checkout.stripe.com/c/example", + "amount_microusd": 500000, + "currency": "USD", + "status": "pending" +} +``` + +Opening the URL allows payment at Stripe. Returning to the browser URL never +credits a balance. The returned `pending` describes the checkout response, +not a confirmed payment. + +## Processor evidence and reconciliation + +Configure Stripe to deliver these types to `POST /v1/payments/webhook`, and +confirm them in the Stripe dashboard: + +- `checkout.session.completed`: credit only with `payment_status=paid`. +- `checkout.session.async_payment_succeeded`: credit the delayed payment. +- `checkout.session.async_payment_failed`: record failure without credit. +- `charge.refunded`: append the increase in cumulative refunded amount. +- `charge.dispute.created`: append a dispute compensation or hold through the + ledger callback, using the dispute ID as its stable operation identity. + +The webhook requires no gateway key and is CSRF-exempt. It reads raw bytes +before parsing JSON, verifies every supported `v1` signature candidate with +HMAC-SHA256 and requires the timestamp to be within 300 seconds in either +direction. Re-serialization invalidates signatures. Unsupported schemes never +authorize an event. Bodies are limited to 65,536 bytes. + +Signed events must match the stored session, direct merchant, mode, currency and +amount. Refunds and disputes must link through the payment intent recorded on +verified session evidence. Refund totals cannot exceed the original charge; +disputes cannot exceed the checkout amount. Mismatches and unknown types are +recorded and acknowledged without credit. + +Refund or dispute evidence arriving before the session's payment intent is known +is retained as `pending_match` and returns 503 for retry. After the verified +session links the intent, the same event can be reconciled without losing its +original evidence hash or audit history. + +An atomic event claim precedes the immutable `PaymentEvent` callback. A +completed replay returns 200 without invoking it again. Both session success +types share one credit operation, cumulative refund notifications apply only +their delta, and repeat dispute IDs share one compensation operation. An event +ID reused with different bytes returns 400 `payment_event_conflict`. + +The callback is the only credit authority. It must apply its immutable +idempotency ID atomically, including when recovering from a process crash after +ledger application but before the payment record is finalized. A missing, +denied, failing or unbound callback leaves `pending_credit` evidence and returns +503 `payment_credit_unavailable`, allowing Stripe to retry. Concurrent active +claims also return this error. A claim can be recovered after a 60-second lease; +retry the original event first before processing other events for that checkout. +Do not acknowledge outstanding credit work manually as paid. Ledger history is +never erased by refunds or disputes. + +## Errors, retention and billing policy + +Invalid checkout input or signature returns 400; absent authentication returns +401; denied billing permission returns 403; disabled payments return 404; +idempotency conflicts return 409; velocity exhaustion returns 429 +`payment_velocity_limited`; unavailable processor, permission, storage or credit +authority returns 503. Payment responses use `Cache-Control: no-store` and +contain no secrets. Unknown payment methods return 405 when enabled. + +Stored records contain opaque identity and checkout scope, processor IDs, +integer amounts, mode, event/body hashes, claims, revisions and content-free +audit outcomes. Return URLs and raw webhook bodies are not stored. Card data, +customer names and email addresses are not stored. Operational records have no +automatic purge; retain them according to reconciliation policy. Velocity +counters use UTC day partitions and are independent of refund history. + +Taxes, invoices, processor fees and charge policies remain explicit operator +settings. The top-up amount is the credit amount; estimated usage is not an +invoice. Rehearse the configured checkout and webhook flow in the merchant +sandbox before accepting live payments. + +The fixed processor contract follows the Stripe documentation: +[webhooks](https://docs.stripe.com/webhooks), +[signature verification](https://docs.stripe.com/webhooks/signature), +[Checkout Session creation](https://docs.stripe.com/api/checkout/sessions/create), +[Checkout metadata](https://docs.stripe.com/payments/checkout-sessions), and +[currency units](https://docs.stripe.com/glossary). Verify endpoint event selection in the Stripe dashboard. diff --git a/intelligence-migrations/0038_payment_billing.sql b/intelligence-migrations/0038_payment_billing.sql new file mode 100644 index 00000000..1baf823b --- /dev/null +++ b/intelligence-migrations/0038_payment_billing.sql @@ -0,0 +1,51 @@ +CREATE TABLE IF NOT EXISTS payment_checkouts ( + checkout_id TEXT PRIMARY KEY, + principal TEXT NOT NULL, + context_json TEXT NOT NULL, + idempotency_key TEXT NOT NULL, + body_hash TEXT NOT NULL, + amount_microusd INTEGER NOT NULL CHECK(amount_microusd BETWEEN 500000 AND 1000000000 AND amount_microusd % 10000 = 0), + currency TEXT NOT NULL CHECK(currency = 'USD'), + status TEXT NOT NULL DEFAULT 'creating', + checkout_url TEXT, + session_id TEXT UNIQUE, + payment_intent TEXT UNIQUE, + merchant TEXT, + livemode INTEGER, + credited INTEGER NOT NULL DEFAULT 0, + refunded INTEGER NOT NULL DEFAULT 0, + revision INTEGER NOT NULL DEFAULT 0, + claim_token TEXT, + claim_until INTEGER NOT NULL DEFAULT 0, + active_event TEXT, + created_at INTEGER NOT NULL, + UNIQUE(principal, context_json, idempotency_key) +); +CREATE TABLE IF NOT EXISTS payment_events ( + event_id TEXT PRIMARY KEY, + evidence_hash TEXT NOT NULL, + checkout_id TEXT, + kind TEXT NOT NULL, + status TEXT NOT NULL, + amount INTEGER NOT NULL DEFAULT 0, + target_amount INTEGER NOT NULL DEFAULT 0, + operation_id TEXT, + revision INTEGER NOT NULL DEFAULT 0, + claim_token TEXT, + claim_until INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL +); +CREATE TABLE IF NOT EXISTS payment_velocity ( + principal TEXT NOT NULL, + utc_day TEXT NOT NULL, + attempts INTEGER NOT NULL CHECK(attempts BETWEEN 0 AND 10), + PRIMARY KEY(principal, utc_day) +); +CREATE TABLE IF NOT EXISTS payment_audit ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + checkout_id TEXT, + event_id TEXT, + outcome TEXT NOT NULL, + created_at INTEGER NOT NULL +); +CREATE INDEX IF NOT EXISTS payment_events_checkout ON payment_events(checkout_id, created_at); diff --git a/package.json b/package.json index a5dd4c0b..a2b61607 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "lint": "ruff check . --select E9,F63,F7,F82", "typecheck": "mypy --ignore-missing-imports --follow-imports=skip --disable-error-code import-untyped --disable-error-code var-annotated --disable-error-code arg-type --disable-error-code assignment --disable-error-code operator app.py routes services providers streaming", "test": "python -m pytest -q", - "test:worker": "node --test tests/test_cloudflare_worker.mjs tests/test_cascades_worker.mjs tests/test_cascades_dashboard.mjs tests/test_image_quality_worker.mjs tests/test_secret_scan_worker.mjs tests/test_secret_firewall_worker.mjs tests/test_secret_firewall_coverage_worker.mjs tests/test_roleplay_compaction_budget_worker.mjs tests/test_roleplay_compaction_model_worker.mjs tests/test_roleplay_stream_validation_worker.mjs tests/test_aihubmix_worker.mjs tests/test_gpt_image_moderation_worker.mjs tests/test_dashboard_scripts.mjs tests/test_operations_dashboard.mjs tests/test_opencode_reasoning_worker.mjs tests/test_opencode_thinking_worker.mjs tests/test_nanogpt_reasoning_worker.mjs tests/test_nanogpt_speed_routing_worker.mjs tests/test_sse_heartbeat_worker.mjs tests/test_roleplay_worker.mjs tests/test_roleplay_config_worker.mjs tests/test_roleplay_glm_failover_worker.mjs tests/test_roleplay_intelligence_worker.mjs tests/test_roleplay_memory_worker.mjs tests/test_roleplay_compatibility_worker.mjs tests/test_roleplay_history_reconciliation_worker.mjs tests/test_roleplay_output_contract_analysis.mjs tests/test_roleplay_output_contract_cleanup_worker.mjs tests/test_roleplay_output_contract_nonstream_worker.mjs tests/test_roleplay_output_contract_worker.mjs tests/test_roleplay_performance_worker.mjs tests/test_roleplay_quality_routing_worker.mjs tests/test_roleplay_reasoning_worker.mjs tests/test_roleplay_session_storage_worker.mjs tests/test_roleplay_transport_failure_worker.mjs tests/test_roleplay_unlimited_worker.mjs tests/test_roleplay_workbench_worker.mjs tests/test_roleplay_candidate_context_worker.mjs tests/test_roleplay_operator_worker.mjs tests/test_workbench_stream.mjs tests/test_intelligence_worker.mjs tests/test_intelligence_d1_worker.mjs tests/test_intelligence_auth_worker.mjs tests/test_intelligence_outbound_worker.mjs tests/test_intelligence_operator.mjs tests/test_control_users_worker.mjs tests/test_control_audit_worker.mjs tests/test_access_sso_worker.mjs tests/test_d1_schema_worker.mjs tests/test_shadow_eval_worker.mjs tests/test_auto_routes_worker.mjs tests/test_ai_outbound_worker.mjs tests/test_knowledge_*.mjs tests/test_control_state_worker.mjs tests/test_route_health_worker.mjs tests/test_gateway_mcp_worker.mjs tests/test_usage_ledger_worker.mjs tests/test_media_outbound_worker.mjs tests/test_media_files_worker.mjs tests/test_media_jobs_worker.mjs tests/test_tool_repair_worker.mjs tests/test_prometheus_worker.mjs tests/test_evaluation_noise_floor_worker.mjs tests/test_prompt_templates_worker.mjs tests/test_config_snapshots_worker.mjs tests/test_managed_idempotency_worker.mjs tests/test_wave3_hub_worker.mjs tests/test_wave3_transport_worker.mjs tests/test_admission_leases_worker.mjs tests/test_edge_request_metrics_worker.mjs tests/test_request_cancellation_worker.mjs tests/test_mcp_contract_drift_worker.mjs tests/test_zero_content_retention_worker.mjs tests/test_prompt_cache_cost_worker.mjs tests/test_config_revision_sync_worker.mjs tests/test_gateway_alerts_worker.mjs tests/test_session_tiers_worker.mjs tests/test_usage_reservations_worker.mjs tests/test_shared_generation_cache_worker.mjs tests/test_deferred_tools_worker.mjs tests/test_generation_deadline_worker.mjs tests/test_wave4_worker.mjs tests/test_responses_state_worker.mjs tests/test_gateway_batches_worker.mjs tests/test_semantic_generation_cache_worker.mjs tests/test_canary_traffic_worker.mjs tests/test_context_pages_worker.mjs tests/test_observability_exports_worker.mjs tests/test_prompt_injection_worker.mjs tests/test_pii_rehydration_worker.mjs tests/test_wave5_worker.mjs tests/test_usage_receipts_worker.mjs tests/test_learned_cooldown_worker.mjs tests/test_stream_cost_breaker_worker.mjs tests/test_realtime_worker.mjs tests/test_latency_slo_worker.mjs tests/test_context_canary_worker.mjs tests/test_enterprise_contracts_worker.mjs tests/test_wave6_worker.mjs tests/test_credits_ledger_worker.mjs tests/test_scim_provisioning_worker.mjs tests/test_saml_federation_worker.mjs tests/test_tenant_governance_worker.mjs tests/test_tenant_hierarchy_worker.mjs", + "test:worker": "node --test tests/test_cloudflare_worker.mjs tests/test_cascades_worker.mjs tests/test_cascades_dashboard.mjs tests/test_image_quality_worker.mjs tests/test_secret_scan_worker.mjs tests/test_secret_firewall_worker.mjs tests/test_secret_firewall_coverage_worker.mjs tests/test_roleplay_compaction_budget_worker.mjs tests/test_roleplay_compaction_model_worker.mjs tests/test_roleplay_stream_validation_worker.mjs tests/test_aihubmix_worker.mjs tests/test_gpt_image_moderation_worker.mjs tests/test_dashboard_scripts.mjs tests/test_operations_dashboard.mjs tests/test_opencode_reasoning_worker.mjs tests/test_opencode_thinking_worker.mjs tests/test_nanogpt_reasoning_worker.mjs tests/test_nanogpt_speed_routing_worker.mjs tests/test_sse_heartbeat_worker.mjs tests/test_roleplay_worker.mjs tests/test_roleplay_config_worker.mjs tests/test_roleplay_glm_failover_worker.mjs tests/test_roleplay_intelligence_worker.mjs tests/test_roleplay_memory_worker.mjs tests/test_roleplay_compatibility_worker.mjs tests/test_roleplay_history_reconciliation_worker.mjs tests/test_roleplay_output_contract_analysis.mjs tests/test_roleplay_output_contract_cleanup_worker.mjs tests/test_roleplay_output_contract_nonstream_worker.mjs tests/test_roleplay_output_contract_worker.mjs tests/test_roleplay_performance_worker.mjs tests/test_roleplay_quality_routing_worker.mjs tests/test_roleplay_reasoning_worker.mjs tests/test_roleplay_session_storage_worker.mjs tests/test_roleplay_transport_failure_worker.mjs tests/test_roleplay_unlimited_worker.mjs tests/test_roleplay_workbench_worker.mjs tests/test_roleplay_candidate_context_worker.mjs tests/test_roleplay_operator_worker.mjs tests/test_workbench_stream.mjs tests/test_intelligence_worker.mjs tests/test_intelligence_d1_worker.mjs tests/test_intelligence_auth_worker.mjs tests/test_intelligence_outbound_worker.mjs tests/test_intelligence_operator.mjs tests/test_control_users_worker.mjs tests/test_control_audit_worker.mjs tests/test_access_sso_worker.mjs tests/test_d1_schema_worker.mjs tests/test_shadow_eval_worker.mjs tests/test_auto_routes_worker.mjs tests/test_ai_outbound_worker.mjs tests/test_knowledge_*.mjs tests/test_control_state_worker.mjs tests/test_route_health_worker.mjs tests/test_gateway_mcp_worker.mjs tests/test_usage_ledger_worker.mjs tests/test_media_outbound_worker.mjs tests/test_media_files_worker.mjs tests/test_media_jobs_worker.mjs tests/test_tool_repair_worker.mjs tests/test_prometheus_worker.mjs tests/test_evaluation_noise_floor_worker.mjs tests/test_prompt_templates_worker.mjs tests/test_config_snapshots_worker.mjs tests/test_managed_idempotency_worker.mjs tests/test_wave3_hub_worker.mjs tests/test_wave3_transport_worker.mjs tests/test_admission_leases_worker.mjs tests/test_edge_request_metrics_worker.mjs tests/test_request_cancellation_worker.mjs tests/test_mcp_contract_drift_worker.mjs tests/test_zero_content_retention_worker.mjs tests/test_prompt_cache_cost_worker.mjs tests/test_config_revision_sync_worker.mjs tests/test_gateway_alerts_worker.mjs tests/test_session_tiers_worker.mjs tests/test_usage_reservations_worker.mjs tests/test_shared_generation_cache_worker.mjs tests/test_deferred_tools_worker.mjs tests/test_generation_deadline_worker.mjs tests/test_wave4_worker.mjs tests/test_responses_state_worker.mjs tests/test_gateway_batches_worker.mjs tests/test_semantic_generation_cache_worker.mjs tests/test_canary_traffic_worker.mjs tests/test_context_pages_worker.mjs tests/test_observability_exports_worker.mjs tests/test_prompt_injection_worker.mjs tests/test_pii_rehydration_worker.mjs tests/test_wave5_worker.mjs tests/test_usage_receipts_worker.mjs tests/test_learned_cooldown_worker.mjs tests/test_stream_cost_breaker_worker.mjs tests/test_realtime_worker.mjs tests/test_latency_slo_worker.mjs tests/test_context_canary_worker.mjs tests/test_enterprise_contracts_worker.mjs tests/test_wave6_worker.mjs tests/test_payment_billing_worker.mjs tests/test_credits_ledger_worker.mjs tests/test_scim_provisioning_worker.mjs tests/test_saml_federation_worker.mjs tests/test_tenant_governance_worker.mjs tests/test_tenant_hierarchy_worker.mjs", "db:migrate": "python scripts/validate_sqlite_schema.py --apply", "db:validate": "python scripts/validate_sqlite_schema.py", "security:secrets": "python scripts/check_static_secrets.py", diff --git a/routes/payments.py b/routes/payments.py new file mode 100644 index 00000000..45c061bc --- /dev/null +++ b/routes/payments.py @@ -0,0 +1,71 @@ +"""Authenticated checkout and raw, CSRF-exempt processor evidence.""" +import json + +from flask import g, jsonify, request + +from route_helpers import api_authenticate_only +from services import payment_billing as payments +from services.enterprise_contract import TenantContext + + +def register_payment_routes(app, csrf, *, service=None, context_resolver=None): + if app.extensions.get("payment_routes_registered"): + return + service = service or payments.PaymentBilling() + app.extensions["payment_billing"] = service + app.extensions["payment_routes_registered"] = True + + def failed(error): + return jsonify({"error": {"code": error.code, "message": "Payment operation unavailable."}}), error.status + + def payment_gate(): + if not request.path.startswith("/v1/payments/"): + return None + try: + service.config() + except payments.PaymentError as error: + return failed(error) + if request.content_length is not None and request.content_length > payments.MAX_BODY: + return failed(payments.PaymentError("invalid_payment_body", 400)) + return None + + app.before_request_funcs.setdefault(None, []).insert(0, payment_gate) + + @app.after_request + def payment_headers(response): + if request.path.startswith("/v1/payments/"): + response.headers["Cache-Control"] = "no-store" + return response + + @app.post("/v1/payments/checkout") + @csrf.exempt + @api_authenticate_only(required_scope="models") + def payment_checkout(): + try: + user = g.authenticated_user + owner = str(user.get("id") or user.get("username") or "") + context = context_resolver(user) if context_resolver else TenantContext(owner) + if not request.is_json: + raise payments.PaymentError("invalid_payment_checkout", 400) + raw = request.stream.read(payments.MAX_BODY + 1) + if len(raw) > payments.MAX_BODY: + raise payments.PaymentError("invalid_payment_body", 400) + try: + body = json.loads(raw) + except (ValueError, UnicodeError, RecursionError): + raise payments.PaymentError("invalid_payment_checkout", 400) from None + return jsonify(service.checkout(context, owner, body)) + except payments.PaymentError as error: + return failed(error) + except (ValueError, TypeError): + return failed(payments.PaymentError("payment_permission_denied", 403)) + + @app.post("/v1/payments/webhook") + @csrf.exempt + def payment_webhook(): + try: + # Signature validation always precedes parsing or reading identity. + raw = request.stream.read(payments.MAX_BODY + 1) + return jsonify(service.webhook(raw, request.headers.get("Stripe-Signature", ""))) + except payments.PaymentError as error: + return failed(error) diff --git a/services/payment_billing.py b/services/payment_billing.py new file mode 100644 index 00000000..26704304 --- /dev/null +++ b/services/payment_billing.py @@ -0,0 +1,453 @@ +"""Fixed Stripe checkout transport and verified, durable payment evidence.""" +from __future__ import annotations + +import hashlib +import hmac +import json +import logging +import re +import sqlite3 +import threading +import time +import uuid +from contextlib import contextmanager +from dataclasses import asdict, dataclass +from datetime import datetime, timezone +from functools import lru_cache +from pathlib import Path +from urllib.parse import urlencode, urlsplit + +import requests + +from services.enterprise_contract import (PaymentCallback, PaymentEvent, TenantContext, deliver_payment, + register_enterprise_adapters) + +logger = logging.getLogger(__name__) +ENDPOINT = "https://api.stripe.com/v1/checkout/sessions" +MAX_BODY = 65536 +LEASE_SECONDS = 60 +LABEL = re.compile(r"[A-Za-z0-9_:.-]{1,128}\Z") +REF = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,127}\Z") +SCHEMA_QUERIES = ( + "SELECT checkout_id,principal,context_json,idempotency_key,body_hash,amount_microusd,currency,status,checkout_url,session_id,payment_intent,merchant,livemode,credited,refunded,revision,claim_token,claim_until,active_event,created_at FROM payment_checkouts LIMIT 0", + "SELECT event_id,evidence_hash,checkout_id,kind,status,amount,target_amount,operation_id,revision,claim_token,claim_until,created_at FROM payment_events LIMIT 0", + "SELECT principal,utc_day,attempts FROM payment_velocity LIMIT 0", + "SELECT id,checkout_id,event_id,outcome,created_at FROM payment_audit LIMIT 0") + + +class PaymentError(Exception): + def __init__(self, code="payments_unavailable", status=503): + super().__init__(code) + self.code, self.status = code, status + + +@lru_cache(maxsize=2) +def _warn_once(kind): + logger.warning("Invalid payment %s; payments disabled", kind) + + +@dataclass(frozen=True) +class ProcessorConfig: + secret_key_ref: str + webhook_key_ref: str + return_origins: tuple[str, ...] + product_name: str + + +def origin(url): + if not isinstance(url, str) or len(url) > 2048 or any(ord(c) <= 32 or ord(c) == 127 for c in url): + raise ValueError("Invalid URL") + parsed = urlsplit(url) + if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password or "\\" in url: + raise ValueError("Invalid URL") + return f"https://{parsed.hostname.lower()}" + (f":{parsed.port}" if parsed.port not in (None, 443) else "") + + +def settings(env) -> ProcessorConfig | None: + raw = env.get("PAYMENTS_ENABLED", "") + flag = raw.strip().lower() if isinstance(raw, str) else "invalid" if raw is not None else "" + if flag in {"", "0", "false", "off", "no"}: + return None + if flag not in {"1", "true", "on", "yes"}: + _warn_once("flag") + return None + try: + value = json.loads(env.get("PAYMENT_PROCESSOR_CONFIG_JSON") or "{}") + webhook = env.get("PAYMENT_WEBHOOK_KEY_REF", "") + if (type(value) is not dict or set(value) != {"processor", "secret_key_ref", "return_origins", "product_name"} + or value["processor"] != "stripe" or not isinstance(webhook, str) or not REF.fullmatch(webhook) + or not isinstance(value["secret_key_ref"], str) or not REF.fullmatch(value["secret_key_ref"]) + or not isinstance(value["product_name"], str) or not 1 <= len(value["product_name"]) <= 128 + or any(ord(c) < 32 for c in value["product_name"]) + or type(value["return_origins"]) is not list or not 1 <= len(value["return_origins"]) <= 16): + raise ValueError() + origins = tuple(origin(url) for url in value["return_origins"]) + if any(url != normalized for url, normalized in zip(value["return_origins"], origins)): + raise ValueError() + return ProcessorConfig(value["secret_key_ref"], webhook, origins, value["product_name"]) + except (ValueError, TypeError, KeyError): + _warn_once("configuration") + return None + + +def verify_signature(raw: bytes, header: str, secret: str, now: int) -> bool: + try: + if not isinstance(raw, bytes) or len(raw) > MAX_BODY or not secret or len(header) > 8192: + return False + pieces = [part.strip().split("=", 1) for part in header.split(",")] + timestamps = [value for key, value in pieces if key == "t"] + signatures = [value for key, value in pieces if key == "v1"] + if len(timestamps) != 1 or not re.fullmatch(r"[0-9]{1,12}", timestamps[0]): + return False + timestamp = timestamps[0] + if abs(now - int(timestamp)) > 300: + return False + expected = hmac.new(secret.encode(), timestamp.encode() + b"." + raw, hashlib.sha256).hexdigest() + return any(hmac.compare_digest(expected, candidate) for candidate in signatures + if re.fullmatch(r"[0-9a-f]{64}", candidate)) + except (TypeError, ValueError, AttributeError, UnicodeError): + return False + + +def owner_permission(context, owner): + return context.principal_id == owner and context.org_id is None and context.team_id is None + + +def checked_checkout(body, config): + if (type(body) is not dict or set(body) != {"amount_microusd", "currency", "idempotency_key", "return_url"} + or type(body["amount_microusd"]) is not int or not 500000 <= body["amount_microusd"] <= 1000000000 + or body["amount_microusd"] % 10000 or body["currency"] != "USD" + or not isinstance(body["idempotency_key"], str) or not LABEL.fullmatch(body["idempotency_key"])): + raise PaymentError("invalid_payment_checkout", 400) + try: + if origin(body["return_url"]) not in config.return_origins: + raise ValueError() + except (ValueError, TypeError): + raise PaymentError("invalid_payment_checkout", 400) from None + return hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":")).encode()).hexdigest() + + +def public_checkout(row): + return {"checkout_id": row["checkout_id"], "url": row["checkout_url"], + "amount_microusd": row["amount_microusd"], "currency": "USD", "status": "pending"} + + +def stripe_http(url, *, headers, body): + """The only processor transport; redirects never receive merchant credentials.""" + if url != ENDPOINT: + raise PaymentError() + response = requests.post(ENDPOINT, headers=headers, data=body, timeout=(3, 10), allow_redirects=False) + if response.status_code != 200: + raise PaymentError("payment_processor_unavailable", 503) + return response.json() + + +class SqlPaymentStore: + """A migrated SQLite authority; no runtime schema creation or memory fallback.""" + def __init__(self, path): + self.path = path + + @contextmanager + def transaction(self): + db = None + try: + db = sqlite3.connect(Path(self.path).resolve().as_uri() + "?mode=rw", uri=True, timeout=10) + db.row_factory = sqlite3.Row + for query in SCHEMA_QUERIES: + db.execute(query) + db.execute("BEGIN IMMEDIATE") + yield db + db.commit() + except sqlite3.Error: + if db is not None: + db.rollback() + raise PaymentError() from None + finally: + if db is not None: + db.close() + + def call(self, operation, **data): + with self.transaction() as db: + handler = getattr(self, "_" + operation, None) + if operation not in {"reserve", "save", "find", "claim", "finish"} or handler is None: + raise PaymentError("invalid_payment_operation", 400) + return handler(db, **data) + + def _reserve(self, db, *, context, body_hash, idempotency_key, checkout_id, amount, now, token): + scope = json.dumps(context, sort_keys=True, separators=(",", ":")) + row = db.execute("SELECT * FROM payment_checkouts WHERE principal=? AND context_json=? AND idempotency_key=?", + (context["principal_id"], scope, idempotency_key)).fetchone() + if row: + if row["body_hash"] != body_hash: + raise PaymentError("payment_idempotency_conflict", 409) + if not row["checkout_url"] and row["claim_until"] <= now: + db.execute("UPDATE payment_checkouts SET claim_token=?,claim_until=? WHERE checkout_id=?", + (token, now + LEASE_SECONDS, row["checkout_id"])) + else: + day = datetime.fromtimestamp(now, timezone.utc).strftime("%Y-%m-%d") + db.execute("INSERT INTO payment_velocity VALUES (?,?,0) ON CONFLICT DO NOTHING", (context["principal_id"], day)) + changed = db.execute("UPDATE payment_velocity SET attempts=attempts+1 WHERE principal=? AND utc_day=? AND attempts<10", + (context["principal_id"], day)).rowcount + if not changed: + raise PaymentError("payment_velocity_limited", 429) + db.execute("INSERT INTO payment_checkouts (checkout_id,principal,context_json,idempotency_key,body_hash,amount_microusd,currency,claim_token,claim_until,created_at) VALUES (?,?,?,?,?,?,'USD',?,?,?)", + (checkout_id, context["principal_id"], scope, idempotency_key, body_hash, amount, token, now+LEASE_SECONDS, now)) + db.execute("INSERT INTO payment_audit (checkout_id,outcome,created_at) VALUES (?,'created',?)", (checkout_id, now)) + row = db.execute("SELECT * FROM payment_checkouts WHERE principal=? AND context_json=? AND idempotency_key=?", + (context["principal_id"], scope, idempotency_key)).fetchone() + return dict(row) + + def _save(self, db, *, checkout_id, token, session_id=None, url=None, livemode=None, merchant=None): + if session_id is None: + db.execute("UPDATE payment_checkouts SET claim_until=0 WHERE checkout_id=? AND claim_token=?", (checkout_id, token)) + else: + changed = db.execute("UPDATE payment_checkouts SET session_id=?,checkout_url=?,livemode=?,merchant=?,status='pending',claim_until=0,claim_token=NULL WHERE checkout_id=? AND claim_token=?", + (session_id, url, int(livemode), merchant, checkout_id, token)).rowcount + if not changed: + raise PaymentError("payment_checkout_processing", 503) + return None + + def _find(self, db, *, checkout_id=None, payment_intent=None): + row = db.execute("SELECT * FROM payment_checkouts WHERE checkout_id=?" if checkout_id else + "SELECT * FROM payment_checkouts WHERE payment_intent=?", (checkout_id or payment_intent,)).fetchone() + return dict(row) if row else None + + def _claim(self, db, *, event_id, evidence_hash, checkout_id, kind, status, amount, target_amount, + operation_id, payment_intent, now, token): + existing = db.execute("SELECT * FROM payment_events WHERE event_id=?", (event_id,)).fetchone() + if existing: + if existing["evidence_hash"] != evidence_hash: + raise PaymentError("payment_event_conflict", 400) + if existing["status"] not in {"processing", "pending_credit", "pending_match"}: + return {**dict(existing), "claimed": False} + if existing["status"] == "pending_match": + if status == "pending_match": + return {**dict(existing), "claimed": False} + existing = None + if existing and existing["claim_until"] > now: + raise PaymentError("payment_credit_unavailable", 503) + row = db.execute("SELECT * FROM payment_checkouts WHERE checkout_id=?", (checkout_id,)).fetchone() + if status == "processing" and row: + if row["active_event"] and row["active_event"] != event_id: + active = db.execute("SELECT claim_until FROM payment_events WHERE event_id=?", (row["active_event"],)).fetchone() + # Retry the original event first, preserving its immutable callback. + if active: + raise PaymentError("payment_credit_unavailable", 503) + if not existing: + prior = db.execute("SELECT status FROM payment_events WHERE operation_id=? AND status IN ('credited','refunded','disputed') LIMIT 1", + (operation_id,)).fetchone() + if prior or (kind == "credit" and row["credited"]): + status = "ignored" + if kind != "credit" and not row["credited"]: + raise PaymentError("payment_credit_unavailable", 503) + if kind == "refund": + amount = max(0, target_amount - row["refunded"]) + if amount == 0: + status = "ignored" + revision = existing["revision"] if existing else row["revision"] if row else 0 + if not existing: + db.execute("INSERT INTO payment_events (event_id,evidence_hash,checkout_id,kind,status,amount,target_amount,operation_id,revision,claim_token,claim_until,created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(event_id) DO UPDATE SET checkout_id=excluded.checkout_id,kind=excluded.kind,status=excluded.status,amount=excluded.amount,target_amount=excluded.target_amount,operation_id=excluded.operation_id,revision=excluded.revision,claim_token=excluded.claim_token,claim_until=excluded.claim_until WHERE payment_events.status='pending_match' AND payment_events.evidence_hash=excluded.evidence_hash", + (event_id, evidence_hash, checkout_id, kind, status, amount, target_amount, operation_id, revision, + token, now+LEASE_SECONDS if status == "processing" else 0, now)) + db.execute("INSERT INTO payment_audit (checkout_id,event_id,outcome,created_at) VALUES (?,?,?,?)", + (checkout_id, event_id, status, now)) + else: + db.execute("UPDATE payment_events SET status='processing',claim_token=?,claim_until=? WHERE event_id=?", (token, now+LEASE_SECONDS, event_id)) + if status == "processing": + db.execute("UPDATE payment_checkouts SET active_event=?,payment_intent=COALESCE(payment_intent,?) WHERE checkout_id=?", + (event_id, payment_intent, checkout_id)) + elif status == "failed" and row and not row["credited"]: + db.execute("UPDATE payment_checkouts SET status='failed' WHERE checkout_id=?", (checkout_id,)) + result = dict(db.execute("SELECT * FROM payment_events WHERE event_id=?", (event_id,)).fetchone()) + return {**result, "claimed": status == "processing"} + + def _finish(self, db, *, event_id, token, status, now): + row = db.execute("SELECT * FROM payment_events WHERE event_id=? AND claim_token=? AND status='processing'", (event_id, token)).fetchone() + if not row: + raise PaymentError("payment_credit_unavailable", 503) + if status != "pending_credit" and status != {"credit": "credited", "refund": "refunded", "dispute": "disputed"}[row["kind"]]: + raise PaymentError("invalid_payment_operation", 400) + db.execute("UPDATE payment_events SET status=?,claim_until=0 WHERE event_id=?", (status, event_id)) + if status != "pending_credit": + db.execute("UPDATE payment_checkouts SET active_event=NULL,revision=revision+1,credited=CASE WHEN ?='credit' THEN 1 ELSE credited END,refunded=CASE WHEN ?='refund' THEN ? ELSE refunded END,status=? WHERE checkout_id=? AND active_event=?", + (row["kind"], row["kind"], row["target_amount"], status, row["checkout_id"], event_id)) + db.execute("INSERT INTO payment_audit (checkout_id,event_id,outcome,created_at) VALUES (?,?,?,?)", (row["checkout_id"], event_id, status, now)) + return None + + +class D1PaymentStore: + """Injected private transport returns the same fixed domain operations as SQL.""" + def __init__(self, transport): + self.transport = transport + + def call(self, operation, **data): + try: + reply = self.transport({"version": 1, "operation": operation, **data}) + if not isinstance(reply, dict) or set(reply) != {"version", "result"} or reply["version"] != 1: + raise PaymentError() + return reply["result"] + except PaymentError: + raise + except Exception: + raise PaymentError() from None + + +class PaymentBilling: + def __init__(self, *, env=None, store=None, http=None, secret_resolver=None, callback: PaymentCallback | None = None, + permission=owner_permission, clock=time.time): + # Configuration and secret access are supplied by the host, never file reads. + import os + self.env = os.environ if env is None else env + self.store, self.http, self.callback = store, http or stripe_http, callback + self.secret_resolver = secret_resolver or self.env.get + self.permission, self.clock = permission, clock + self.lock = threading.RLock() + + def config(self): + config = settings(self.env) + if config is None: + raise PaymentError("not_found", 404) + return config + + def state(self, operation, **values): + if self.store is None: + raise PaymentError() + return self.store.call(operation, **values) + + def checkout(self, context, owner, body): + config = self.config() + try: + allowed = type(context) is TenantContext and self.permission(context, owner) is True + except Exception: + raise PaymentError("payment_permission_unavailable", 503) from None + if not allowed: + raise PaymentError("payment_permission_denied", 403) + body_hash = checked_checkout(body, config) + with self.lock: + token, now = uuid.uuid4().hex, int(self.clock()) + row = self.state("reserve", context=asdict(context), body_hash=body_hash, + idempotency_key=body["idempotency_key"], checkout_id="pay_"+uuid.uuid4().hex, + amount=body["amount_microusd"], now=now, token=token) + if row["checkout_url"]: + return public_checkout(row) + if row["claim_token"] != token: + raise PaymentError("payment_checkout_processing", 503) + try: + session = self.create_session(config, row, body) + self.state("save", checkout_id=row["checkout_id"], token=token, session_id=session["id"], + url=session["url"], livemode=session["livemode"], merchant="direct") + except Exception: + self.state("save", checkout_id=row["checkout_id"], token=token) + raise PaymentError("payment_processor_unavailable", 503) from None + return public_checkout({**row, "checkout_url": session["url"]}) + + def create_session(self, config, row, body): + secret = self.secret_resolver(config.secret_key_ref) + if not secret or self.http is None: + raise PaymentError() + form = {"mode": "payment", "line_items[0][price_data][currency]": "usd", + "line_items[0][price_data][unit_amount]": str(row["amount_microusd"] // 10000), + "line_items[0][price_data][product_data][name]": config.product_name, + "line_items[0][quantity]": "1", "success_url": body["return_url"], "cancel_url": body["return_url"], + "client_reference_id": row["checkout_id"], "metadata[checkout_id]": row["checkout_id"]} + session = self.http(ENDPOINT, headers={"Authorization": "Bearer " + secret, + "Content-Type": "application/x-www-form-urlencoded", "Idempotency-Key": row["checkout_id"]}, body=urlencode(form)) + if (type(session) is not dict or session.get("object") != "checkout.session" + or not isinstance(session.get("id"), str) or not LABEL.fullmatch(session["id"]) + or type(session.get("amount_total")) is not int or session["amount_total"]*10000 != row["amount_microusd"] + or session.get("currency") != "usd" or type(session.get("livemode")) is not bool + or origin(session.get("url")) != "https://checkout.stripe.com"): + raise PaymentError() + return session + + def webhook(self, raw, signature): + config = self.config() + try: + secret = self.secret_resolver(config.webhook_key_ref) + except Exception: + raise PaymentError() from None + if not secret: + raise PaymentError() + now = int(self.clock()) + if not verify_signature(raw, signature, secret, now): + raise PaymentError("invalid_payment_signature", 400) + try: + value = json.loads(raw) + if type(value) is not dict or value.get("object") != "event" or not LABEL.fullmatch(value.get("id", "")): + raise ValueError() + evidence_hash = hashlib.sha256(raw).hexdigest() + except (ValueError, TypeError, UnicodeError, RecursionError): + raise PaymentError("invalid_payment_event", 400) from None + with self.lock: + row, decision = self.classify(value) + token = uuid.uuid4().hex + claimed = self.state("claim", event_id=value["id"], evidence_hash=evidence_hash, + checkout_id=row["checkout_id"] if row else None, now=now, token=token, **decision) + if not claimed["claimed"]: + if claimed["status"] == "pending_match": + raise PaymentError("payment_credit_unavailable", 503) + return {"received": True, "status": claimed["status"]} + event = PaymentEvent(TenantContext(**json.loads(row["context_json"])), row["checkout_id"], claimed["revision"], + claimed["operation_id"], "stripe", value["id"], claimed["kind"], "USD", claimed["amount"], True) + try: + deliver_payment(register_enterprise_adapters(payment=self.callback), event) + except Exception: + self.state("finish", event_id=value["id"], token=token, status="pending_credit", now=now) + raise PaymentError("payment_credit_unavailable", 503) from None + status = {"credit": "credited", "refund": "refunded", "dispute": "disputed"}[event.kind] + self.state("finish", event_id=value["id"], token=token, status=status, now=now) + return {"received": True, "status": status} + + def classify(self, value): + kind = value.get("type") + decision = {"kind": "ignored", "status": "ignored", "amount": 0, "target_amount": 0, + "operation_id": None, "payment_intent": None} + kinds = {"checkout.session.completed": "credit", "checkout.session.async_payment_succeeded": "credit", + "checkout.session.async_payment_failed": "failed", "charge.refunded": "refund", "charge.dispute.created": "dispute"} + if not isinstance(kind, str) or kind not in kinds: + return None, decision + obj = value.get("data", {}).get("object", {}) if type(value.get("data")) is dict else {} + if type(obj) is not dict: + return None, {**decision, "status": "mismatch"} + session = kind.startswith("checkout.session.") + checkout_id = obj.get("client_reference_id") if session else None + intent = obj.get("payment_intent") + if not isinstance(intent, str) or not LABEL.fullmatch(intent): + intent = None + if (session and (not isinstance(checkout_id, str) or not LABEL.fullmatch(checkout_id))) or (not session and intent is None): + return None, {**decision, "status": "mismatch"} + row = self.state("find", checkout_id=checkout_id, payment_intent=intent) + if row is None and not session: + return None, {**decision, "status": "pending_match"} + amount = obj.get("amount_total") if session else obj.get("amount") + metadata = obj.get("metadata", {}) + mismatch = (row is None or obj.get("currency") != "usd" or type(amount) is not int + or type(value.get("livemode")) is not bool or value["livemode"] != bool(row["livemode"]) + or type(obj.get("livemode")) is not bool or obj["livemode"] != bool(row["livemode"]) + or (value.get("account") or "direct") != row["merchant"]) + if not mismatch and session: + mismatch = (amount*10000 != row["amount_microusd"] or obj.get("id") != row["session_id"] + or type(metadata) is not dict or metadata.get("checkout_id") != checkout_id + or (row["payment_intent"] is not None and intent != row["payment_intent"])) + if not mismatch and not session: + mismatch = (amount <= 0 or amount*10000 > row["amount_microusd"] + or (kind == "charge.refunded" and amount*10000 != row["amount_microusd"])) + if mismatch: + return row, {**decision, "status": "mismatch"} + mapped = kinds[kind] + if kind == "checkout.session.completed" and obj.get("payment_status") != "paid": + return row, decision + if mapped == "failed": + return row, {**decision, "status": "failed"} + target = 0 + if mapped == "refund": + target = obj.get("amount_refunded") + if type(target) is not int or not 0 < target <= amount: + return row, {**decision, "status": "mismatch"} + target *= 10000 + object_id = obj.get("id") + if mapped == "dispute" and (not isinstance(object_id, str) or not LABEL.fullmatch(object_id)): + return row, {**decision, "status": "mismatch"} + operation = f"credit:{row['checkout_id']}" if mapped == "credit" else f"refund:{row['checkout_id']}:{target}" if mapped == "refund" else "dispute:" + hashlib.sha256(object_id.encode()).hexdigest() + return row, {"kind": mapped, "status": "processing", "amount": amount*10000, + "target_amount": target, "operation_id": operation, "payment_intent": intent} diff --git a/tests/fixtures/secret_firewall_coverage.json b/tests/fixtures/secret_firewall_coverage.json index a5d9d554..5d5d1bd1 100644 --- a/tests/fixtures/secret_firewall_coverage.json +++ b/tests/fixtures/secret_firewall_coverage.json @@ -150,6 +150,10 @@ "routes/optimized.py": [ "app.route('/optimize/v1/chat/completions', methods=['POST', 'OPTIONS'])" ], + "routes/payments.py": [ + "app.post('/v1/payments/checkout')", + "app.post('/v1/payments/webhook')" + ], "routes/prompt_templates.py": [ "app.route('/admin/workbench/prompts', methods=['GET', 'POST'])", "app.route('/v1/prompt-templates//render', methods=['POST', 'OPTIONS'])" @@ -370,6 +374,7 @@ "worker/opencode/reasoning-policy.mjs", "worker/opencode/reasoning-request.mjs", "worker/opencode/reasoning-response.mjs", + "worker/payment-webhooks.mjs", "worker/pii-redaction.mjs", "worker/pii-rehydration.mjs", "worker/prometheus.mjs", diff --git a/tests/test_payment_billing.py b/tests/test_payment_billing.py new file mode 100644 index 00000000..e01c4268 --- /dev/null +++ b/tests/test_payment_billing.py @@ -0,0 +1,393 @@ +"""Offline checkout, signed evidence, durable claims and authenticated routes.""" +import hashlib +import hmac +import json +import sqlite3 +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from types import SimpleNamespace +from urllib.parse import parse_qs + +import pytest +from flask import Flask, g + +from services import payment_billing as pb +from services.enterprise_contract import AuthorityResult, TenantContext +from routes import payments + +NOW = 1700000000 +SECRET = "public-test-webhook-secret" +VECTOR = b'{"id":"evt_vector","object":"event","type":"unknown","livemode":false}' +SIGNATURE = hmac.new(SECRET.encode(), str(NOW).encode() + b"." + VECTOR, hashlib.sha256).hexdigest() +ROOT = Path(__file__).resolve().parents[1] +CONFIG = {"processor": "stripe", "secret_key_ref": "PAYMENT_TEST_KEY", + "return_origins": ["https://portal.test"], "product_name": "Gateway credits"} +ENV = {"PAYMENTS_ENABLED": "true", "PAYMENT_PROCESSOR_CONFIG_JSON": json.dumps(CONFIG), + "PAYMENT_WEBHOOK_KEY_REF": "PAYMENT_TEST_WEBHOOK"} +BODY = {"amount_microusd": 500000, "currency": "USD", "idempotency_key": "order-1", + "return_url": "https://portal.test/paid"} + + +@pytest.fixture +def setup(tmp_path): + path = tmp_path / "payments.sqlite" + with sqlite3.connect(path) as db: + db.execute("CREATE TABLE old_rows (value TEXT)") + db.execute("INSERT INTO old_rows VALUES ('retained')") + migration = (ROOT / "intelligence-migrations/0038_payment_billing.sql").read_text() + db.executescript(migration) + db.executescript(migration) + assert db.execute("SELECT value FROM old_rows").fetchone()[0] == "retained" + store = pb.SqlPaymentStore(path) + calls, credited = [], [] + def http(url, *, headers, body): + calls.append((url, headers, parse_qs(body))) + fields = calls[-1][2] + return {"id": "cs_" + fields["client_reference_id"][0], "object": "checkout.session", + "url": "https://checkout.stripe.com/c/pay_test", "amount_total": int(fields["line_items[0][price_data][unit_amount]"][0]), + "currency": "usd", "livemode": False} + def callback(event): + credited.append(event) + return AuthorityResult(event.context, event.scoped_id, event.revision + 1, event.idempotency_id, True) + service = pb.PaymentBilling(store=store, env=ENV, http=http, secret_resolver=lambda ref: SECRET, + callback=callback, clock=lambda: NOW) + return SimpleNamespace(store=store, service=service, calls=calls, credited=credited, path=path) + + +def checkout(setup, **changes): + return setup.service.checkout(TenantContext("alice"), "alice", {**BODY, **changes}) + + +def event(row, kind="checkout.session.completed", **changes): + obj = {"id": "cs_" + row["checkout_id"], "client_reference_id": row["checkout_id"], + "metadata": {"checkout_id": row["checkout_id"]}, "payment_status": "paid", + "amount_total": row["amount_microusd"] // 10000, "currency": "usd", "livemode": False, + "payment_intent": "pi_test"} + obj.update(changes.pop("object_changes", {})) + return {"id": "evt_paid", "object": "event", "type": kind, "livemode": False, + "data": {"object": obj}, **changes} + + +def deliver(service, value): + raw = json.dumps(value, separators=(",", ":")).encode() + signature = hmac.new(SECRET.encode(), str(NOW).encode() + b"." + raw, hashlib.sha256).hexdigest() + return service.webhook(raw, f"t={NOW},v1={signature}") + + +@pytest.mark.parametrize("flag", [None, "", "false", "0", "junk"]) +def test_default_off_has_no_io(flag, caplog): + env = {**ENV, "PAYMENTS_ENABLED": flag} + service = pb.PaymentBilling(env=env, secret_resolver=lambda _: pytest.fail("disabled secret")) + with pytest.raises(pb.PaymentError) as caught: + service.checkout(TenantContext("alice"), "alice", BODY) + assert caught.value.status == 404 + with pytest.raises(pb.PaymentError): + service.webhook(VECTOR, "") + + +@pytest.mark.parametrize("config", ["{", "[]", '{"processor":"other"}', json.dumps({**CONFIG, "secret_key_ref": "bad ref"}), + json.dumps({**CONFIG, "return_origins": ["https://portal.test/path"]})]) +def test_invalid_configuration_disables_without_values(config, caplog): + pb._warn_once.cache_clear() + for _ in range(2): + assert pb.settings({**ENV, "PAYMENT_PROCESSOR_CONFIG_JSON": config}) is None + assert len(caplog.records) == 1 and config not in caplog.text + + +@pytest.mark.parametrize("amount", [True, 1, 499999, 500001, 1000000001, 500000.0, "500000"]) +def test_amount_contract_before_http(setup, amount): + with pytest.raises(pb.PaymentError) as caught: + checkout(setup, amount_microusd=amount) + assert caught.value.status == 400 and not setup.calls + + +@pytest.mark.parametrize("url", ["https://portal.test.evil/", "https://portal.test@evil.test/", "http://portal.test/", "https://portal.test:444/", "https://portal.test/\n"]) +def test_exact_return_origin(setup, url): + with pytest.raises(pb.PaymentError): + checkout(setup, return_url=url) + assert not setup.calls + + +def test_checkout_fixed_schema_idempotency_velocity_and_concurrency(setup): + with ThreadPoolExecutor(max_workers=4) as pool: + rows = list(pool.map(lambda _: checkout(setup), range(4))) + assert rows == [rows[0]] * 4 and len(setup.calls) == 1 + assert rows[0]["status"] == "pending" and not setup.credited + url, headers, fields = setup.calls[0] + assert url == "https://api.stripe.com/v1/checkout/sessions" + assert headers["Idempotency-Key"] == rows[0]["checkout_id"] + assert fields["metadata[checkout_id]"] == [rows[0]["checkout_id"]] + assert fields["client_reference_id"] == [rows[0]["checkout_id"]] + assert fields["line_items[0][price_data][unit_amount]"] == ["50"] + with pytest.raises(pb.PaymentError) as conflict: + checkout(setup, amount_microusd=510000) + assert conflict.value.status == 409 + for n in range(9): + checkout(setup, idempotency_key=f"order-{n+2}") + with pytest.raises(pb.PaymentError) as limited: + checkout(setup, idempotency_key="eleven") + assert limited.value.code == "payment_velocity_limited" and limited.value.status == 429 + + +def test_foreign_workspace_requires_explicit_permission(setup): + with pytest.raises(pb.PaymentError) as caught: + setup.service.checkout(TenantContext("alice", "foreign"), "alice", BODY) + assert caught.value.status == 403 and not setup.calls + setup.service.permission = lambda context, owner: context.org_id == "allowed" and owner == "alice" + assert setup.service.checkout(TenantContext("alice", "allowed"), "alice", BODY)["status"] == "pending" + + +def test_signature_shared_vector_rotation_raw_bytes_and_time(): + assert pb.verify_signature(VECTOR, f"t={NOW},v1={'0'*64},v1={SIGNATURE}", SECRET, NOW) + assert pb.verify_signature(VECTOR, f"t={NOW},v1={SIGNATURE}", SECRET, NOW + 300) + for raw, header, now in [(VECTOR+b" ", f"t={NOW},v1={SIGNATURE}", NOW), + (VECTOR, f"t={NOW},v0={SIGNATURE}", NOW), + (VECTOR, f"t={NOW},t={NOW},v1={SIGNATURE}", NOW), + (VECTOR, f"t={NOW},v1={SIGNATURE}", NOW + 301), + (VECTOR, f"t={NOW},v1={SIGNATURE}", NOW - 301)]: + assert not pb.verify_signature(raw, header, SECRET, now) + + +def test_invalid_signature_has_no_state_change(setup): + with pytest.raises(pb.PaymentError) as caught: + setup.service.webhook(VECTOR, f"t={NOW},v1={'0'*64}") + assert caught.value.status == 400 + with sqlite3.connect(setup.path) as db: + assert db.execute("SELECT COUNT(*) FROM payment_events").fetchone()[0] == 0 + + +def test_verified_payment_once_across_replays_and_success_types(setup): + row = checkout(setup) + value = event(row) + with ThreadPoolExecutor(max_workers=4) as pool: + results = list(pool.map(lambda _: deliver(setup.service, value), range(4))) + assert all(result["received"] for result in results) + assert len(setup.credited) == 1 + assert deliver(setup.service, event(row, "checkout.session.async_payment_succeeded", id="evt_async"))["received"] + assert len(setup.credited) == 1 and setup.credited[0].verified + assert setup.credited[0].amount == 500000 + with pytest.raises(Exception): + setup.credited[0].amount = 0 + + +@pytest.mark.parametrize("change", [{"account": "foreign"}, {"livemode": True}, + {"object_changes": {"currency": "eur"}}, + {"object_changes": {"amount_total": 51}}, + {"object_changes": {"id": "cs_other"}}]) +def test_mismatch_recorded_without_credit(setup, change): + row = checkout(setup) + assert deliver(setup.service, event(row, **change))["status"] == "mismatch" + assert not setup.credited + + +def test_delayed_payment_failure_unknown_and_missing_callback_retry(setup): + row = checkout(setup) + assert deliver(setup.service, event(row, object_changes={"payment_status": "unpaid"}))["status"] == "ignored" + assert not setup.credited + assert deliver(setup.service, event(row, "checkout.session.async_payment_failed", id="evt_failed"))["status"] == "failed" + assert deliver(setup.service, {"id": "evt_unknown", "type": "unknown", "object": "event"})["status"] == "ignored" + setup.service.callback = None + paid = event(row, "checkout.session.async_payment_succeeded", id="evt_retry") + with pytest.raises(pb.PaymentError) as unavailable: + deliver(setup.service, paid) + assert unavailable.value.code == "payment_credit_unavailable" + with sqlite3.connect(setup.path) as db: + assert db.execute("SELECT status FROM payment_events WHERE event_id='evt_retry'").fetchone()[0] == "pending_credit" + setup.service.callback = lambda e: AuthorityResult(e.context, e.scoped_id, e.revision + 1, e.idempotency_id, True) + assert deliver(setup.service, paid)["status"] == "credited" + + +def test_refund_cumulative_delta_and_dispute_append(setup): + row = checkout(setup) + deliver(setup.service, event(row)) + charge = {"id": "ch_test", "payment_intent": "pi_test", "amount": 50, "amount_refunded": 20, "currency": "usd", "livemode": False} + value = {"id": "evt_refund", "object": "event", "type": "charge.refunded", "livemode": False, "data": {"object": charge}} + assert deliver(setup.service, value)["status"] == "refunded" + deliver(setup.service, {**value, "id": "evt_refund_duplicate"}) + charge = {**charge, "amount_refunded": 50} + deliver(setup.service, {**value, "id": "evt_refund_rest", "data": {"object": charge}}) + dispute = {"id": "dp_test", "charge": "ch_test", "payment_intent": "pi_test", "amount": 50, "currency": "usd", "livemode": False} + deliver(setup.service, {**value, "id": "evt_dispute", "type": "charge.dispute.created", "data": {"object": dispute}}) + deliver(setup.service, {**value, "id": "evt_dispute_repeated", "type": "charge.dispute.created", "data": {"object": dispute}}) + assert [(e.kind, e.amount) for e in setup.credited] == [("credit", 500000), ("refund", 200000), ("refund", 300000), ("dispute", 500000)] + + +def test_callback_failure_keeps_stable_operation_and_no_false_success(setup): + row = checkout(setup) + operations = [] + def failure(e): + operations.append(e.idempotency_id) + raise RuntimeError("private detail") + setup.service.callback = failure + with pytest.raises(pb.PaymentError) as caught: + deliver(setup.service, event(row)) + assert caught.value.code == "payment_credit_unavailable" and "private" not in str(caught.value) + def success(e): + operations.append(e.idempotency_id) + return AuthorityResult(e.context, e.scoped_id, e.revision+1, e.idempotency_id, True) + setup.service.callback = success + deliver(setup.service, event(row)) + assert operations[0] == operations[1] + + +def test_refund_before_session_is_retried_and_reconciled(setup): + row = checkout(setup) + value = {"id": "evt_early", "object": "event", "type": "charge.refunded", "livemode": False, + "data": {"object": {"id": "ch_test", "payment_intent": "pi_test", "amount": 50, + "amount_refunded": 20, "currency": "usd", "livemode": False}}} + for _ in range(2): + with pytest.raises(pb.PaymentError) as caught: + deliver(setup.service, value) + assert caught.value.code == "payment_credit_unavailable" + assert not setup.credited + deliver(setup.service, event(row)) + assert deliver(setup.service, value)["status"] == "refunded" + assert [(e.kind, e.amount) for e in setup.credited] == [("credit", 500000), ("refund", 200000)] + with sqlite3.connect(setup.path) as db: + assert db.execute("SELECT COUNT(*) FROM payment_events WHERE event_id='evt_early'").fetchone()[0] == 1 + assert db.execute("SELECT COUNT(*) FROM payment_audit WHERE event_id='evt_early'").fetchone()[0] >= 3 + + +def test_missing_schema_fails_before_provider(setup, tmp_path): + setup.service.store = pb.SqlPaymentStore(tmp_path / "missing.sqlite") + with pytest.raises(pb.PaymentError) as caught: + checkout(setup) + assert caught.value.status == 503 and caught.value.code == "payments_unavailable" and not setup.calls + assert not (tmp_path / "missing.sqlite").exists() + + +def test_separate_instances_share_claims_and_callbacks(setup): + row = checkout(setup) + services = [pb.PaymentBilling(store=setup.store, env=ENV, secret_resolver=lambda _: SECRET, + callback=setup.service.callback, clock=lambda: NOW) for _ in range(4)] + def run(service): + try: + return deliver(service, event(row)) + except pb.PaymentError as error: + assert error.code == "payment_credit_unavailable" and error.status == 503 + return None + with ThreadPoolExecutor(max_workers=4) as pool: + list(pool.map(run, services)) + assert len(setup.credited) == 1 + assert deliver(services[0], event(row))["status"] == "credited" + + +def test_processor_failure_retries_same_opaque_id_without_new_velocity(setup): + original = setup.service.http + attempted = [] + def failure(url, *, headers, body): + attempted.append(headers["Idempotency-Key"]) + raise RuntimeError("private processor detail") + setup.service.http = failure + with pytest.raises(pb.PaymentError) as caught: + checkout(setup) + assert caught.value.code == "payment_processor_unavailable" + setup.service.http = original + row = checkout(setup) + assert attempted == [row["checkout_id"]] + with sqlite3.connect(setup.path) as db: + assert db.execute("SELECT attempts FROM payment_velocity").fetchone()[0] == 1 + + +def test_fixed_http_disallows_redirects_and_suppresses_processor_errors(monkeypatch): + calls = [] + def post(url, **kwargs): + calls.append((url, kwargs)) + return SimpleNamespace(status_code=302, json=lambda: pytest.fail("redirect body")) + monkeypatch.setattr(pb.requests, "post", post) + with pytest.raises(pb.PaymentError): + pb.stripe_http(pb.ENDPOINT, headers={}, body="mode=payment") + assert calls[0][1]["allow_redirects"] is False and calls[0][1]["timeout"] == (3, 10) + with pytest.raises(pb.PaymentError): + pb.stripe_http("https://foreign.test", headers={}, body="") + assert len(calls) == 1 + + +def test_d1_adapter_preserves_fixed_protocol_without_fallback(): + bodies = [] + def transport(body): + bodies.append(body) + return {"version": 1, "result": None} + store = pb.D1PaymentStore(transport) + assert store.call("find", checkout_id="pay_one", payment_intent=None) is None + assert bodies == [{"version": 1, "operation": "find", "checkout_id": "pay_one", "payment_intent": None}] + with pytest.raises(pb.PaymentError): + pb.D1PaymentStore(lambda _: {"version": 1}).call("find") + + +def test_missing_columns_and_webhook_schema_are_503(setup): + row = checkout(setup) + with sqlite3.connect(setup.path) as db: + db.execute("ALTER TABLE payment_events RENAME TO old_payment_events") + db.execute("CREATE TABLE payment_events (event_id TEXT)") + with pytest.raises(pb.PaymentError) as caught: + deliver(setup.service, event(row)) + assert caught.value.code == "payments_unavailable" and not setup.credited + + +@pytest.mark.parametrize("obj", [{"type": []}, {"type": "checkout.session.completed", "data": []}, + {"type": "checkout.session.completed", "data": {"object": []}}]) +def test_malformed_payload_never_crashes_or_credits(setup, obj): + result = deliver(setup.service, {"id": "evt_malformed", "object": "event", **obj}) + assert result["status"] in {"ignored", "mismatch"} and not setup.credited + + +def test_velocity_utc_reset_and_owner_isolation(setup): + for n in range(10): + checkout(setup, idempotency_key=f"day-{n}") + setup.service.clock = lambda: NOW+86400 + assert checkout(setup, idempotency_key="next-day")["status"] == "pending" + setup.service.checkout(TenantContext("bob"), "bob", BODY) + + +def test_permission_callback_failures_do_not_grant_access(setup): + setup.service.permission = lambda *_: "billing" + with pytest.raises(pb.PaymentError) as caught: + checkout(setup) + assert caught.value.status == 403 + def unavailable(*_): + raise RuntimeError("private permission detail") + setup.service.permission = unavailable + with pytest.raises(pb.PaymentError) as caught: + checkout(setup) + assert caught.value.status == 503 and not setup.calls + + +def test_registered_paths_off_auth_raw_webhook_redirect(setup, monkeypatch): + def authenticate(**kwargs): + def decorate(target): + def wrapper(*args, **kw): + if not g.get("authenticated_user"): + return {"error": "authentication_required"}, 401 + return target(*args, **kw) + wrapper.__name__ = target.__name__ + return wrapper + return decorate + monkeypatch.setattr(payments, "api_authenticate_only", authenticate) + app = Flask(__name__) + @app.before_request + def user(): + from flask import request + if request.headers.get("Authorization") == "Bearer test": + g.authenticated_user = {"id": "alice"} + exempted = [] + csrf = SimpleNamespace(exempt=lambda f: exempted.append(f.__name__) or f) + payments.register_payment_routes(app, csrf, service=setup.service) + client = app.test_client() + setup.service.env = {} + assert client.post("/v1/payments/checkout").status_code == 404 + assert client.post("/v1/payments/webhook").status_code == 404 + setup.service.env = ENV + assert client.post("/v1/payments/checkout", json=BODY).status_code == 401 + row = client.post("/v1/payments/checkout", json=BODY, headers={"Authorization": "Bearer test"}).json + assert client.get("/v1/payments/checkout").status_code == 405 + assert client.get("/paid").status_code == 404 and not setup.credited + assert client.post("/v1/payments/checkout", data="{", content_type="application/json", + headers={"Authorization": "Bearer test"}).status_code == 400 + assert client.post("/v1/payments/checkout", data="x"*(pb.MAX_BODY+1), content_type="application/json", + headers={"Authorization": "Bearer test"}).status_code == 400 + assert "payment_webhook" in exempted + raw = json.dumps(event(row)).encode() + signature = hmac.new(SECRET.encode(), str(NOW).encode()+b"."+raw, hashlib.sha256).hexdigest() + assert client.post("/v1/payments/webhook", data=raw, headers={"Stripe-Signature": f"t={NOW},v1={signature}"}).status_code == 200 + assert len(setup.credited) == 1 diff --git a/tests/test_payment_billing_worker.mjs b/tests/test_payment_billing_worker.mjs new file mode 100644 index 00000000..42ac8a1c --- /dev/null +++ b/tests/test_payment_billing_worker.mjs @@ -0,0 +1,219 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { readFileSync } from "node:fs"; +import { DatabaseSync } from "node:sqlite"; +import { createHmac } from "node:crypto"; +import { fileURLToPath } from "node:url"; +import { convertV4MiniflareOptions, Miniflare } from "miniflare"; +import { loadWorkerModule } from "./helpers/load_cloudflare_worker.mjs"; +import { handlePaymentStoreRequest, verifyPaymentSignature, paymentSettings } from "../worker/payment-webhooks.mjs"; + +const NOW = 1700000000; +const SECRET = "public-test-webhook-secret"; +const VECTOR = '{"id":"evt_vector","object":"event","type":"unknown","livemode":false}'; +const SIGNATURE = createHmac("sha256", SECRET).update(`${NOW}.${VECTOR}`).digest("hex"); +const ENV = { PAYMENTS_ENABLED: "true", PAYMENT_PROCESSOR_CONFIG_JSON: JSON.stringify({ processor: "stripe", + secret_key_ref: "PAYMENT_TEST_KEY", return_origins: ["https://portal.test"], product_name: "Gateway credits" }), + PAYMENT_WEBHOOK_KEY_REF: "PAYMENT_TEST_WEBHOOK" }; +const context = { principal_id: "alice", org_id: null, team_id: null, grants_revision: 0 }; + +function database(t, schema = true) { + const sql = new DatabaseSync(":memory:"); + t.after(() => sql.close()); + sql.exec("CREATE TABLE old_rows (value TEXT); INSERT INTO old_rows VALUES ('retained')"); + const migration = readFileSync(new URL("../intelligence-migrations/0038_payment_billing.sql", import.meta.url), "utf8"); + if (schema) { sql.exec(migration); sql.exec(migration); } + const db = { prepare(query) { + let values = []; + const statement = { bind(...args) { values = args; return statement; }, + first() { return sql.prepare(query).get(...values) ?? null; }, + all() { + const prepared = sql.prepare(query); + return prepared.columns().length ? { results: prepared.all(...values), meta: { changes: 0 } } + : { results: [], meta: { changes: Number(prepared.run(...values).changes) } }; + }, run() { return statement.all(); } }; + return statement; + }, async batch(statements) { + sql.exec("BEGIN IMMEDIATE"); + try { const result = statements.map(statement => statement.all()); sql.exec("COMMIT"); return result; } + catch (error) { sql.exec("ROLLBACK"); throw error; } + } }; + const env = { ...ENV, INTELLIGENCE_DB: db }; + const call = async (operation, data = {}) => { + const response = await handlePaymentStoreRequest(new Request("http://intelligence.internal/v1/managed-state/payments", { + method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ version: 1, operation, ...data }) }), env); + return { status: response.status, body: await response.json() }; + }; + return { sql, env, call }; +} +function reserve(overrides = {}) { + return { context, body_hash: "a".repeat(64), idempotency_key: "order-1", checkout_id: "pay_one", + amount: 500000, now: NOW, token: "token_one", ...overrides }; +} +function claim(overrides = {}) { + return { event_id: "evt_one", evidence_hash: "b".repeat(64), checkout_id: "pay_one", kind: "credit", + status: "processing", amount: 500000, target_amount: 0, operation_id: "credit:pay_one", + payment_intent: "pi_one", now: NOW, token: "claim_one", ...overrides }; +} +async function saved(call) { + assert.equal((await call("reserve", reserve())).status, 200); + assert.equal((await call("save", { checkout_id: "pay_one", token: "token_one", session_id: "cs_one", + url: "https://checkout.stripe.com/c/pay_test", livemode: false, merchant: "direct" })).status, 200); +} + +test("shared raw signature vectors, rotation, timestamp, no downgrade", async () => { + const raw = new TextEncoder().encode(VECTOR); + assert.equal(await verifyPaymentSignature(raw, `t=${NOW},v1=${"0".repeat(64)},v1=${SIGNATURE}`, SECRET, NOW), true); + assert.equal(await verifyPaymentSignature(raw, `t=${NOW},v1=${SIGNATURE}`, SECRET, NOW+300), true); + for (const [body, header, now] of [ + [VECTOR+" ", `t=${NOW},v1=${SIGNATURE}`, NOW], [VECTOR, `t=${NOW},v0=${SIGNATURE}`, NOW], + [VECTOR, `t=${NOW},t=${NOW},v1=${SIGNATURE}`, NOW], [VECTOR, `t=${NOW},v1=${SIGNATURE}`, NOW+301], + [VECTOR, `t=${NOW},v1=${SIGNATURE}`, NOW-301], [VECTOR, "garbage", NOW], + ]) assert.equal(await verifyPaymentSignature(new TextEncoder().encode(body), header, SECRET, now), false); +}); + +test("default off and invalid config perform no storage, warning excludes values", async () => { + for (const flag of [undefined, "", "false", "junk"]) { + const response = await handlePaymentStoreRequest(new Request("http://intelligence.internal/v1/managed-state/payments", { method: "POST" }), + { ...ENV, PAYMENTS_ENABLED: flag, INTELLIGENCE_DB: { prepare() { assert.fail("disabled storage"); } } }); + assert.equal(response.status, 404); + } + assert.equal(paymentSettings({ ...ENV, PAYMENT_PROCESSOR_CONFIG_JSON: "[]" }), null); + assert.equal(paymentSettings({ ...ENV, PAYMENT_WEBHOOK_KEY_REF: "bad ref" }), null); +}); + +test("private target validation and missing table fail closed", async t => { + const { env, call } = database(t, false); + assert.equal((await call("reserve", reserve())).status, 503); + for (const url of ["https://outside.test/v1/managed-state/payments", "http://intelligence.internal/v1/managed-state/payments?x=1"]) { + assert.equal((await handlePaymentStoreRequest(new Request(url, { method: "POST" }), env)).status, 404); + } + assert.equal((await call("unknown")).status, 400); + assert.equal((await call("reserve", reserve({ amount: 500001 }))).status, 400); + assert.equal((await call("reserve", { ...reserve(), secret: "unwanted" })).status, 400); + assert.equal((await call("reserve", reserve({ idempotency_key: "order-1\n" }))).status, 400); +}); + +test("migration preserves old rows, reserve CAS scopes, velocity and retry", async t => { + const { sql, call } = database(t); + assert.equal(sql.prepare("SELECT value FROM old_rows").get().value, "retained"); + const rows = await Promise.all(Array.from({ length: 4 }, () => call("reserve", reserve()))); + assert.ok(rows.every(row => row.status === 200 && row.body.result.checkout_id === "pay_one")); + assert.equal(sql.prepare("SELECT attempts FROM payment_velocity").get().attempts, 1); + assert.equal((await call("reserve", reserve({ body_hash: "c".repeat(64) }))).status, 409); + for (let n = 2; n <= 10; n++) assert.equal((await call("reserve", reserve({ idempotency_key: `order-${n}`, checkout_id: `pay_${n}` }))).status, 200); + assert.equal((await call("reserve", reserve({ idempotency_key: "eleven", checkout_id: "pay_11" }))).status, 429); + assert.equal((await call("reserve", reserve({ context: { ...context, principal_id: "bob" }, checkout_id: "pay_bob" }))).status, 200); + assert.equal((await call("reserve", reserve({ context: { ...context, org_id: "org_one" }, checkout_id: "pay_org", now: NOW+86400 }))).status, 200); +}); + +test("event CAS before callback, retries and distinct completion events credit once", async t => { + const { call, sql } = database(t); + await saved(call); + const rows = await Promise.all(Array.from({ length: 4 }, (_, n) => call("claim", claim({ token: `claim_${n}` })))); + assert.equal(rows.filter(row => row.status === 200 && row.body.result.claimed).length, 1); + const winner = rows.find(row => row.status === 200).body.result; + assert.equal((await call("finish", { event_id: "evt_one", token: winner.claim_token, status: "pending_credit", now: NOW })).status, 200); + const retry = await call("claim", claim({ token: "claim_retry" })); + assert.equal(retry.body.result.operation_id, "credit:pay_one"); + assert.equal((await call("finish", { event_id: "evt_one", token: "claim_retry", status: "credited", now: NOW })).status, 200); + const duplicate = await call("claim", claim()); + assert.equal(duplicate.body.result.claimed, false); + const asyncEvent = await call("claim", claim({ event_id: "evt_async" })); + assert.equal(asyncEvent.body.result.claimed, false); + assert.equal(sql.prepare("SELECT credited,revision FROM payment_checkouts").get().credited, 1); + assert.equal(sql.prepare("SELECT COUNT(*) AS n FROM payment_events").get().n, 2); +}); + +test("refund deltas, operation deduplication and content-free audit", async t => { + const { call, sql } = database(t); + await saved(call); + await call("claim", claim()); + await call("finish", { event_id: "evt_one", token: "claim_one", status: "credited", now: NOW }); + const refund = claim({ event_id: "evt_refund", kind: "refund", target_amount: 200000, + operation_id: "refund:pay_one:200000", token: "refund_one" }); + assert.equal((await call("claim", refund)).body.result.amount, 200000); + await call("finish", { event_id: "evt_refund", token: "refund_one", status: "refunded", now: NOW }); + assert.equal((await call("claim", { ...refund, event_id: "evt_refund_again" })).body.result.claimed, false); + assert.equal(sql.prepare("SELECT refunded FROM payment_checkouts").get().refunded, 200000); + assert.deepEqual(sql.prepare("PRAGMA table_info(payment_audit)").all().map(row => row.name), ["id", "checkout_id", "event_id", "outcome", "created_at"]); + assert.equal((await call("finish", { event_id: "evt_refund", token: "foreign", status: "refunded", now: NOW })).status, 503); +}); + +test("unmatched event evidence resumes after the verified intent is linked", async t => { + const { call, sql } = database(t); + await saved(call); + const unmatched = claim({ event_id: "evt_early", checkout_id: null, kind: "ignored", status: "pending_match", + amount: 0, target_amount: 0, operation_id: null, payment_intent: null }); + assert.equal((await call("claim", unmatched)).body.result.status, "pending_match"); + await call("claim", claim()); + await call("finish", { event_id: "evt_one", token: "claim_one", status: "credited", now: NOW }); + const matched = claim({ event_id: "evt_early", kind: "refund", target_amount: 200000, + operation_id: "refund:pay_one:200000", token: "refund_early" }); + assert.equal((await call("claim", matched)).body.result.amount, 200000); + await call("finish", { event_id: "evt_early", token: "refund_early", status: "refunded", now: NOW }); + assert.equal(sql.prepare("SELECT COUNT(*) AS n FROM payment_events WHERE event_id='evt_early'").get().n, 1); +}); + +test("unknown events and mismatches are recorded without credit claims", async t => { + const { call, sql } = database(t); + for (const status of ["ignored", "mismatch"]) { + const result = await call("claim", claim({ event_id: `evt_${status}`, checkout_id: null, + kind: "ignored", status, amount: 0, operation_id: null, payment_intent: null })); + assert.equal(result.status, 200); + assert.equal(result.body.result.claimed, false); + } + assert.equal(sql.prepare("SELECT COUNT(*) AS n FROM payment_events").get().n, 2); +}); + +test("Worker forwards unauthenticated webhook raw bytes and signature to the Container", async t => { + const worker = (await loadWorkerModule()).default; + const raw = new TextEncoder().encode(' {"fixture":"é"}\r\n'); + let forwards = 0; + t.mock.method(globalThis, "fetch", () => assert.fail("unexpected external network")); + const env = { MULTILLM_PROXY_CONTAINER: { getByName(name) { + assert.equal(name, "primary"); + return { async fetch(request) { + forwards++; + assert.equal(new URL(request.url).pathname, "/v1/payments/webhook"); + assert.equal(request.headers.get("Authorization"), null); + assert.equal(request.headers.get("Stripe-Signature"), "signature-fixture"); + assert.deepEqual(new Uint8Array(await request.arrayBuffer()), raw); + return Response.json({ received: true }); + } }; + } } }; + const response = await worker.fetch(new Request("https://gateway.test/v1/payments/webhook", { + method: "POST", headers: { "content-type": "application/json", "Stripe-Signature": "signature-fixture" }, body: raw }), env, + { waitUntil() {} }); + assert.equal(response.status, 200); + assert.equal(forwards, 1); +}); + +test("real D1 batches preserve velocity and event CAS", async t => { + const entry = fileURLToPath(new URL("../worker/payment-test-entry.mjs", import.meta.url)); + const modules = [ + { type: "ESModule", path: entry, contents: 'import {handlePaymentStoreRequest} from "./payment-webhooks.mjs"; export default {fetch(request,env) {return handlePaymentStoreRequest(new Request("http://intelligence.internal/v1/managed-state/payments",request),env);}}' }, + ...["payment-webhooks.mjs", "enterprise-contract.mjs"].map(name => ({ type: "ESModule", + path: fileURLToPath(new URL(`../worker/${name}`, import.meta.url)), + contents: readFileSync(new URL(`../worker/${name}`, import.meta.url), "utf8") })), + ]; + const mf = new Miniflare(convertV4MiniflareOptions({ modules, compatibilityDate: "2026-08-18", + d1Databases: ["INTELLIGENCE_DB"], bindings: ENV })); + t.after(() => mf.dispose()); + const db = await mf.getD1Database("INTELLIGENCE_DB"); + const migration = readFileSync(new URL("../intelligence-migrations/0038_payment_billing.sql", import.meta.url), "utf8"); + await db.batch(migration.split(";").map(sql => sql.trim()).filter(Boolean).map(sql => db.prepare(sql))); + const call = async (operation, data) => { + const response = await mf.dispatchFetch("https://payment.test/", { method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ version: 1, operation, ...data }) }); + return { status: response.status, body: await response.json() }; + }; + await saved(call); + assert.equal((await call("reserve", reserve())).body.result.checkout_id, "pay_one"); + assert.equal((await db.prepare("SELECT attempts FROM payment_velocity").first()).attempts, 1); + const claims = await Promise.all(Array.from({ length: 4 }, (_, n) => call("claim", claim({ token: `claim_${n}` })))); + assert.equal(claims.filter(result => result.status === 200 && result.body.result.claimed).length, 1); + const token = claims.find(result => result.status === 200).body.result.claim_token; + assert.equal((await call("finish", { event_id: "evt_one", token, status: "credited", now: NOW })).status, 200); + assert.equal((await call("claim", claim())).body.result.claimed, false); +}); diff --git a/worker/container-env.mjs b/worker/container-env.mjs index 054dfd01..0b6d24fb 100644 --- a/worker/container-env.mjs +++ b/worker/container-env.mjs @@ -43,6 +43,9 @@ const DIRECT_ENV_KEYS = [ "CREDITS_CURRENCY", "CREDITS_ENABLED", "ORGANISATIONS_ENABLED", + "PAYMENTS_ENABLED", + "PAYMENT_PROCESSOR_CONFIG_JSON", + "PAYMENT_WEBHOOK_KEY_REF", "SAML_BROKER_URL", "SAML_CALLBACK_URL", "SAML_ENABLED", diff --git a/worker/d1-schema.mjs b/worker/d1-schema.mjs index 49694b2d..e9a7347a 100644 --- a/worker/d1-schema.mjs +++ b/worker/d1-schema.mjs @@ -10,7 +10,7 @@ export const REQUIRED_D1_TABLES = Object.freeze(["intelligence_policy", "intelli "usage_events", "usage_daily", "usage_batches", "media_jobs", "media_job_items", "shadow_eval_samples", "shadow_eval_results", "shadow_eval_config", "shadow_eval_policy_backups", "prompt_templates", - "config_snapshot_revisions", "config_snapshots", "config_snapshot_applications", "control_revisions", "tool_grants", "generation_cache", "usage_reservation_budgets", "usage_reservations", "usage_reservation_transitions", "session_tiers", "gateway_alert_rules", "gateway_alert_events", "managed_idempotency", "context_pages", "canary_traffic", "semantic_generation_cache", "gateway_batch_files", "gateway_batches", "gateway_batch_items", "hosted_responses", "realtime_tickets", "realtime_sessions", "learned_cooldown", "usage_receipt_keys", "usage_receipt_heads", "usage_receipts", "tenant_organisations", "tenant_teams", "tenant_memberships", "tenant_bindings", "tenant_audit", "tenant_governance_policies", "tenant_governance_reservations", "tenant_governance_components", "tenant_governance_baselines", "tenant_governance_audit", "saml_requests", "saml_subject_links", "saml_audit", "scim_resources", "scim_group_members", "scim_token_digests", "scim_audit", "credits_balances", "credits_entries", "credits_audit"]); + "config_snapshot_revisions", "config_snapshots", "config_snapshot_applications", "control_revisions", "tool_grants", "generation_cache", "usage_reservation_budgets", "usage_reservations", "usage_reservation_transitions", "session_tiers", "gateway_alert_rules", "gateway_alert_events", "managed_idempotency", "context_pages", "canary_traffic", "semantic_generation_cache", "gateway_batch_files", "gateway_batches", "gateway_batch_items", "hosted_responses", "realtime_tickets", "realtime_sessions", "learned_cooldown", "usage_receipt_keys", "usage_receipt_heads", "usage_receipts", "tenant_organisations", "tenant_teams", "tenant_memberships", "tenant_bindings", "tenant_audit", "tenant_governance_policies", "tenant_governance_reservations", "tenant_governance_components", "tenant_governance_baselines", "tenant_governance_audit", "saml_requests", "saml_subject_links", "saml_audit", "scim_resources", "scim_group_members", "scim_token_digests", "scim_audit", "credits_balances", "credits_entries", "credits_audit", "payment_checkouts", "payment_events", "payment_velocity", "payment_audit"]); /** * Readiness for the D1 schema. A deploy that skipped `wrangler d1 migrations apply` reports diff --git a/worker/payment-webhooks.mjs b/worker/payment-webhooks.mjs new file mode 100644 index 00000000..880d19b0 --- /dev/null +++ b/worker/payment-webhooks.mjs @@ -0,0 +1,250 @@ +/** Private, durable payment domain. Public Stripe delivery stays in the Container. */ +import { TenantContext } from "./enterprise-contract.mjs"; + +const MAX_BODY = 65536, LEASE = 60; +const LABEL = /^[A-Za-z0-9_:.-]{1,128}(?![\s\S])/, REF = /^[A-Za-z_][A-Za-z0-9_]{0,127}(?![\s\S])/, HASH = /^[0-9a-f]{64}(?![\s\S])/; +const columns = { + payment_checkouts: "checkout_id,principal,context_json,idempotency_key,body_hash,amount_microusd,currency,status,checkout_url,session_id,payment_intent,merchant,livemode,credited,refunded,revision,claim_token,claim_until,active_event,created_at", + payment_events: "event_id,evidence_hash,checkout_id,kind,status,amount,target_amount,operation_id,revision,claim_token,claim_until,created_at", + payment_velocity: "principal,utc_day,attempts", payment_audit: "id,checkout_id,event_id,outcome,created_at", +}; +let warnedFlag = false, warnedConfig = false; +class PaymentError extends Error { + constructor(code = "payments_unavailable", status = 503) { super(code); this.code = code; this.status = status; } +} +function invalid() { throw new PaymentError("invalid_payment_operation", 400); } +function label(value, nullable = false) { + if (nullable && value === null) return; + if (typeof value !== "string" || !LABEL.test(value)) invalid(); +} +function integer(value, maximum = 1000000000) { + if (!Number.isSafeInteger(value) || value < 0 || value > maximum) invalid(); +} +function origin(value) { + if (typeof value !== "string" || value.length > 2048 || /[\x00-\x20\x7f\\]/.test(value)) invalid(); + const url = new URL(value); + if (url.protocol !== "https:" || !url.hostname || url.username || url.password) invalid(); + return url.origin; +} +export function paymentSettings(env = {}, warn = message => console.warn(message)) { + const raw = env.PAYMENTS_ENABLED; + const flag = raw == null ? "" : typeof raw === "string" ? raw.trim().toLowerCase() : "invalid"; + if (["", "0", "false", "off", "no"].includes(flag)) return null; + if (!["1", "true", "on", "yes"].includes(flag)) { + if (!warnedFlag) { warnedFlag = true; warn("Invalid payment flag; payments disabled"); } + return null; + } + try { + const config = JSON.parse(env.PAYMENT_PROCESSOR_CONFIG_JSON || "{}"); + if (!config || Array.isArray(config) || Object.keys(config).sort().join() !== "processor,product_name,return_origins,secret_key_ref" + || config.processor !== "stripe" || typeof config.secret_key_ref !== "string" || !REF.test(config.secret_key_ref) + || typeof env.PAYMENT_WEBHOOK_KEY_REF !== "string" || !REF.test(env.PAYMENT_WEBHOOK_KEY_REF) + || typeof config.product_name !== "string" || config.product_name.length < 1 || config.product_name.length > 128 + || /[\x00-\x1f]/.test(config.product_name) || !Array.isArray(config.return_origins) + || config.return_origins.length < 1 || config.return_origins.length > 16 + || config.return_origins.some(value => origin(value) !== value)) throw new Error(); + return Object.freeze({ ...config, webhook_key_ref: env.PAYMENT_WEBHOOK_KEY_REF }); + } catch { + if (!warnedConfig) { warnedConfig = true; warn("Invalid payment configuration; payments disabled"); } + return null; + } +} + +export async function verifyPaymentSignature(raw, header, secret, now) { + try { + if (!(raw instanceof Uint8Array) || raw.byteLength > MAX_BODY || typeof secret !== "string" || !secret + || typeof header !== "string" || header.length > 8192 || !Number.isSafeInteger(now)) return false; + const pieces = header.split(",").map(piece => { + const index = piece.indexOf("="); + if (index < 0) throw new Error(); + return [piece.slice(0, index).trim(), piece.slice(index+1).trim()]; + }); + const timestamps = pieces.filter(([key]) => key === "t").map(([, value]) => value); + if (timestamps.length !== 1 || !/^[0-9]{1,12}$/.test(timestamps[0]) || Math.abs(now-Number(timestamps[0])) > 300) return false; + const prefix = new TextEncoder().encode(`${timestamps[0]}.`); + const signed = new Uint8Array(prefix.length+raw.length); signed.set(prefix); signed.set(raw, prefix.length); + const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]); + // WebCrypto performs the HMAC comparison rather than JavaScript string equality. + let matched = false; + for (const [scheme, value] of pieces) { + if (scheme !== "v1" || !HASH.test(value)) continue; + const signature = Uint8Array.from(value.match(/../g).map(byte => parseInt(byte, 16))); + matched = await crypto.subtle.verify("HMAC", key, signature, signed) || matched; + } + return matched; + } catch { return false; } +} + +function checked(body) { + const fields = { + reserve: ["context", "body_hash", "idempotency_key", "checkout_id", "amount", "now", "token"], + save: ["checkout_id", "token"], find: ["checkout_id", "payment_intent"], + claim: ["event_id", "evidence_hash", "checkout_id", "kind", "status", "amount", "target_amount", "operation_id", "payment_intent", "now", "token"], + finish: ["event_id", "token", "status", "now"], + }; + if (!body || Array.isArray(body) || body.version !== 1 || !Object.hasOwn(fields, body.operation)) invalid(); + const optional = body.operation === "save" ? ["session_id", "url", "livemode", "merchant"] : []; + const required = ["version", "operation", ...fields[body.operation]]; + if (required.some(name => !Object.hasOwn(body, name)) || Object.keys(body).some(name => !required.includes(name) && !optional.includes(name))) invalid(); + for (const name of ["checkout_id", "payment_intent", "operation_id"]) if (name in body) label(body[name], true); + for (const name of ["token", "event_id", "idempotency_key"]) if (name in body) label(body[name]); + for (const name of ["now", "amount", "target_amount"]) if (name in body) integer(body[name], name === "now" ? 999999999999 : 1000000000); + for (const name of ["body_hash", "evidence_hash"]) if (name in body && (typeof body[name] !== "string" || !HASH.test(body[name]))) invalid(); + if (body.operation === "reserve") { + body.context = new TenantContext(body.context); + if (body.amount < 500000 || body.amount % 10000 || !body.checkout_id) invalid(); + } + if (body.operation === "save" && body.session_id != null) { + label(body.session_id); + if (origin(body.url) !== "https://checkout.stripe.com" || typeof body.livemode !== "boolean" || body.merchant !== "direct" + || optional.some(name => !Object.hasOwn(body, name))) invalid(); + } else if (body.operation === "save" && optional.some(name => Object.hasOwn(body, name))) invalid(); + if (body.operation === "claim") { + if (!["credit", "refund", "dispute", "ignored"].includes(body.kind) || !["processing", "ignored", "mismatch", "failed", "pending_match"].includes(body.status)) invalid(); + if (body.status === "processing" && (!body.checkout_id || !body.operation_id || body.kind === "ignored" || body.amount === 0)) invalid(); + if (body.kind === "refund" && body.target_amount > body.amount) invalid(); + } + if (body.operation === "finish" && !["pending_credit", "credited", "refunded", "disputed"].includes(body.status)) invalid(); + return body; +} +async function ready(env) { + const db = env.INTELLIGENCE_DB; + if (!db?.prepare || !db?.batch) throw new PaymentError(); + for (const [table, names] of Object.entries(columns)) await db.prepare(`SELECT ${names} FROM ${table} LIMIT 0`).all(); + return db; +} +function canonicalContext(context) { + return JSON.stringify({ grants_revision: context.grants_revision, org_id: context.org_id, + principal_id: context.principal_id, team_id: context.team_id }); +} +const stmt = (db, sql, ...args) => db.prepare(sql).bind(...args); + +async function reserve(db, b) { + const scope = canonicalContext(b.context), principal = b.context.principal_id; + const lookup = () => stmt(db, "SELECT * FROM payment_checkouts WHERE principal=? AND context_json=? AND idempotency_key=?", principal, scope, b.idempotency_key).first(); + let row = await lookup(); + if (row && row.body_hash !== b.body_hash) throw new PaymentError("payment_idempotency_conflict", 409); + if (!row) { + const day = new Date(b.now*1000).toISOString().slice(0, 10); + await db.batch([ + stmt(db, "INSERT INTO payment_velocity VALUES (?,?,0) ON CONFLICT DO NOTHING", principal, day), + stmt(db, "INSERT INTO payment_checkouts (checkout_id,principal,context_json,idempotency_key,body_hash,amount_microusd,currency,claim_token,claim_until,created_at) SELECT ?,?,?,?,?,?,'USD',?,?,? WHERE EXISTS (SELECT 1 FROM payment_velocity WHERE principal=? AND utc_day=? AND attempts<10) ON CONFLICT(principal,context_json,idempotency_key) DO NOTHING", + b.checkout_id, principal, scope, b.idempotency_key, b.body_hash, b.amount, b.token, b.now+LEASE, b.now, principal, day), + stmt(db, "UPDATE payment_velocity SET attempts=attempts+1 WHERE principal=? AND utc_day=? AND changes()=1", principal, day), + stmt(db, "INSERT INTO payment_audit (checkout_id,outcome,created_at) SELECT ?,'created',? WHERE changes()=1", b.checkout_id, b.now), + ]); + row = await lookup(); + if (!row) throw new PaymentError("payment_velocity_limited", 429); + if (row.body_hash !== b.body_hash) throw new PaymentError("payment_idempotency_conflict", 409); + } else if (!row.checkout_url && row.claim_until <= b.now) { + await stmt(db, "UPDATE payment_checkouts SET claim_token=?,claim_until=? WHERE checkout_id=? AND claim_until<=? AND checkout_url IS NULL", + b.token, b.now+LEASE, row.checkout_id, b.now).run(); + row = await lookup(); + } + return row; +} +async function save(db, b) { + if (b.session_id == null) { + await stmt(db, "UPDATE payment_checkouts SET claim_until=0 WHERE checkout_id=? AND claim_token=?", b.checkout_id, b.token).run(); + } else { + const result = await stmt(db, "UPDATE payment_checkouts SET session_id=?,checkout_url=?,livemode=?,merchant=?,status='pending',claim_until=0,claim_token=NULL WHERE checkout_id=? AND claim_token=?", + b.session_id, b.url, Number(b.livemode), b.merchant, b.checkout_id, b.token).run(); + if (result.meta.changes !== 1) throw new PaymentError("payment_checkout_processing", 503); + } + return null; +} +async function find(db, b) { + return b.checkout_id ? await stmt(db, "SELECT * FROM payment_checkouts WHERE checkout_id=?", b.checkout_id).first() + : await stmt(db, "SELECT * FROM payment_checkouts WHERE payment_intent=?", b.payment_intent).first(); +} +async function claim(db, b) { + let existing = await stmt(db, "SELECT * FROM payment_events WHERE event_id=?", b.event_id).first(); + if (existing) { + if (existing.evidence_hash !== b.evidence_hash) throw new PaymentError("payment_event_conflict", 400); + if (!["processing", "pending_credit", "pending_match"].includes(existing.status)) return { ...existing, claimed: false }; + if (existing.status === "pending_match") { + if (b.status === "pending_match") return { ...existing, claimed: false }; + existing = null; + } + if (existing && existing.claim_until > b.now) throw new PaymentError("payment_credit_unavailable", 503); + } + const row = b.checkout_id ? await find(db, b) : null; + let status = b.status, amount = b.amount; + if (status === "processing") { + if (!row || (row.active_event && row.active_event !== b.event_id)) throw new PaymentError("payment_credit_unavailable", 503); + if (!existing) { + const prior = await stmt(db, "SELECT status FROM payment_events WHERE operation_id=? AND status IN ('credited','refunded','disputed') LIMIT 1", b.operation_id).first(); + if (prior || (b.kind === "credit" && row.credited)) status = "ignored"; + if (b.kind !== "credit" && !row.credited) throw new PaymentError("payment_credit_unavailable", 503); + if (b.kind === "refund") { amount = Math.max(0, b.target_amount-row.refunded); if (amount === 0) status = "ignored"; } + } + } + const statements = []; + if (existing) { + statements.push(stmt(db, "UPDATE payment_events SET status='processing',claim_token=?,claim_until=? WHERE event_id=? AND claim_until<=? AND EXISTS (SELECT 1 FROM payment_checkouts WHERE checkout_id=? AND active_event=? AND revision=?)", + b.token, b.now+LEASE, b.event_id, b.now, existing.checkout_id, b.event_id, existing.revision)); + } else { + const guard = row ? " WHERE EXISTS (SELECT 1 FROM payment_checkouts WHERE checkout_id=? AND revision=? AND (active_event IS NULL OR active_event=?))" : ""; + statements.push(stmt(db, "INSERT INTO payment_events (event_id,evidence_hash,checkout_id,kind,status,amount,target_amount,operation_id,revision,claim_token,claim_until,created_at) SELECT ?,?,?,?,?,?,?,?,?,?,?,?" + guard + " ON CONFLICT(event_id) DO UPDATE SET checkout_id=excluded.checkout_id,kind=excluded.kind,status=excluded.status,amount=excluded.amount,target_amount=excluded.target_amount,operation_id=excluded.operation_id,revision=excluded.revision,claim_token=excluded.claim_token,claim_until=excluded.claim_until WHERE payment_events.status='pending_match' AND payment_events.evidence_hash=excluded.evidence_hash", + b.event_id, b.evidence_hash, b.checkout_id, b.kind, status, amount, b.target_amount, b.operation_id, row?.revision ?? 0, + b.token, status === "processing" ? b.now+LEASE : 0, b.now, ...(row ? [row.checkout_id, row.revision, b.event_id] : []))); + } + if (status === "processing") { + statements.push(stmt(db, "UPDATE payment_checkouts SET active_event=?,payment_intent=COALESCE(payment_intent,?) WHERE checkout_id=? AND EXISTS (SELECT 1 FROM payment_events WHERE event_id=? AND claim_token=? AND status='processing')", + b.event_id, b.payment_intent, b.checkout_id, b.event_id, b.token)); + } else if (status === "failed" && row && !row.credited) { + statements.push(stmt(db, "UPDATE payment_checkouts SET status='failed' WHERE checkout_id=? AND credited=0 AND EXISTS (SELECT 1 FROM payment_events WHERE event_id=? AND claim_token=?)", row.checkout_id, b.event_id, b.token)); + } + statements.push(stmt(db, "INSERT INTO payment_audit (checkout_id,event_id,outcome,created_at) SELECT ?,?,?,? WHERE EXISTS (SELECT 1 FROM payment_events WHERE event_id=? AND claim_token=?)", + b.checkout_id, b.event_id, status, b.now, b.event_id, b.token)); + const results = await db.batch(statements); + existing = await stmt(db, "SELECT * FROM payment_events WHERE event_id=?", b.event_id).first(); + if (!existing || (results[0].meta.changes !== 1 && ["processing", "pending_credit"].includes(existing.status))) throw new PaymentError("payment_credit_unavailable", 503); + if (existing.evidence_hash !== b.evidence_hash) throw new PaymentError("payment_event_conflict", 400); + return { ...existing, claimed: existing.status === "processing" && existing.claim_token === b.token }; +} +async function finish(db, b) { + const row = await stmt(db, "SELECT * FROM payment_events WHERE event_id=? AND claim_token=? AND status='processing'", b.event_id, b.token).first(); + if (!row) throw new PaymentError("payment_credit_unavailable", 503); + const expected = { credit: "credited", refund: "refunded", dispute: "disputed" }[row.kind]; + if (b.status !== "pending_credit" && b.status !== expected) invalid(); + const statements = [stmt(db, "UPDATE payment_events SET status=?,claim_until=0 WHERE event_id=? AND claim_token=? AND status='processing'", b.status, b.event_id, b.token)]; + if (b.status !== "pending_credit") statements.push(stmt(db, "UPDATE payment_checkouts SET active_event=NULL,revision=revision+1,credited=CASE WHEN ?='credit' THEN 1 ELSE credited END,refunded=CASE WHEN ?='refund' THEN ? ELSE refunded END,status=? WHERE checkout_id=? AND active_event=? AND revision=? AND changes()=1", + row.kind, row.kind, row.target_amount, b.status, row.checkout_id, b.event_id, row.revision)); + statements.push(stmt(db, "INSERT INTO payment_audit (checkout_id,event_id,outcome,created_at) SELECT ?,?,?,? WHERE changes()=1", row.checkout_id, b.event_id, b.status, b.now)); + const results = await db.batch(statements); + if (results[0].meta.changes !== 1) throw new PaymentError("payment_credit_unavailable", 503); + return null; +} +const operations = { reserve, save, find, claim, finish }; + +export async function handlePaymentStoreRequest(request, env) { + const failed = error => Response.json({ error: { code: error instanceof PaymentError ? error.code : "payments_unavailable", + message: "Payment operation unavailable." } }, { status: error instanceof PaymentError ? error.status : 503, headers: { "Cache-Control": "no-store" } }); + if (!paymentSettings(env)) return failed(new PaymentError("not_found", 404)); + const url = new URL(request.url); + if (url.origin !== "http://intelligence.internal" || url.pathname !== "/v1/managed-state/payments" + || url.search || url.hash || url.username || url.password || request.method !== "POST") return failed(new PaymentError("not_found", 404)); + let body; + try { + if (request.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase() !== "application/json") invalid(); + const reader = request.body?.getReader(); + if (!reader) invalid(); + const chunks = []; let length = 0; + try { + while (true) { + const { done, value } = await reader.read(); if (done) break; + length += value.length; + if (length > MAX_BODY) { await reader.cancel(); invalid(); } + chunks.push(value); + } + } finally { reader.releaseLock(); } + const bytes = new Uint8Array(length); let offset = 0; + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length; } + body = checked(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes))); + } catch { return failed(new PaymentError("invalid_payment_operation", 400)); } + try { + const db = await ready(env), result = await operations[body.operation](db, body); + return Response.json({ version: 1, result }, { headers: { "Cache-Control": "no-store" } }); + } catch (error) { return failed(error); } +}