[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ECXWFVB7NGQE28JNAHSCZ5":3,"skill-same:01M7ECXWFVB7NGQE28JNAHSCZ5":49},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":20,"frontMatter":21,"refName":22,"commitSha":23,"skillDirectory":24,"forksCount":13,"repositoryHtmlUrl":25,"repositoryHomepageUrl":6,"ownerHtmlUrl":26,"ownerBlogUrl":6,"ownerDescription":27,"updatedAt":28,"install":29,"resources":42},"01M7ECXWFVB7NGQE28JNAHSCZ5","x402-payment-testing",null,"jonahthan433\u002FCortexOS","jonahthan433","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F211465495?v=4","01M7ECH9HPHGA89DCXHHJBTS3C","jonah.ai","01M7ECH9JCEM45DZMWPT7148S1",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fmlops\u002Fx402-payment-testing\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"# x402-payment-testing\n\n# x402 live payment smoke test\n\n## When to use\n- You added\u002Fchanged a paid (x402 v2) endpoint and need to prove the FULL loop: 402 challenge → signed payment → facilitator validate+settle → upstream executes → 200 → ledger records provider cost + margin.\n- Unit\u002Fintegration tests with a mocked facilitator are NOT enough — the user explicitly wants a real settled payment.\n\n## Hard constraint: resource URL MUST be https\nThe CDP x402 facilitator (`api.cdp.coinbase.com\u002Fplatform\u002Fv2\u002Fx402\u002Fvalidate`) rejects any `resource.url` not matching `^https:\u002F\u002F.*$`. A localhost `http:\u002F\u002F127.0.0.1:PORT` challenge fails schema validation with `doesn't match the regular expression ^https:\u002F\u002F.*$`.\n\nFixes, in order of preference:\n1. **Expose staging over https** (real deployment behind TLS). Then the challenge `resource.url` is the public https URL and the facilitator can fetch+validate it.\n2. **Ad-hoc cloudflared tunnel** for a localhost staging server (no token needed): `cloudflared tunnel --url http:\u002F\u002F127.0.0.1:PORT` → gives `https:\u002F\u002F\u003Crandom>.trycloudflare.com`. Set the server's `X402_RESOURCE_BASE` (or make the middleware derive `resource.url` from the incoming request's `scheme:\u002F\u002Fhost`, which it should do anyway — see Pitfalls) to that URL, and point the smoke client at the public URL. Kill the tunnel afterward (it's a public exposure).\n3. Do NOT weaken payment verification to bypass this. The https requirement is an external anti-fraud constraint, not a code defect.\n\n## Signing recipe (verified with x402 2.14.0, cdp 1.47.1)\nThe test-buyer key is a raw 64-hex EOA private key (NOT a CDP-managed account). Sign with `eth_account` + the x402 EVM signer:\n\n```python\nimport os, httpx\nfrom eth_account import Account\nfrom x402.client import x402Client, x402ClientSync\nfrom x402.http.x402_http_client import x402HTTPClientSync\nfrom x402.mechanisms.evm.exact import ExactEvmScheme\nfrom x402.mechanisms.evm.signers import EthAccountSigner\n\nBASE = \"https:\u002F\u002F\u003Cpublic-or-staging-https-url>\"   # see https constraint above\naccount = Account.from_key(open(\"\u002Fpath\u002Fto\u002Ftest_buyer.key\").read().strip())\nclient = x402ClientSync(x402Client())\nclient.register(\"eip155:8453\", ExactEvmScheme(signer=EthAccountSigner(account)))\nclient.register_policy(__import__(\"x402\").prefer_network(\"eip155:8453\"))\nxhttp = x402HTTPClientSync(client)\n\nraw = httpx.post(f\"{BASE}\u002Fv1\u002Fpaid\u002Froute\", json=payload)\nassert raw.status_code == 402\nheaders, _payload = xhttp.handle_402_response(dict(raw.headers), raw.content)\nassert headers, \"failed to build signed payment headers\"\nr = httpx.post(f\"{BASE}\u002Fv1\u002Fpaid\u002Froute\", json=payload, headers=headers)\nassert r.status_code == 200, r.text\n```\n\nKey API notes (these are version-sensitive — re-check with `inspect` if the package version changed):\n- `x402ClientSync(x402Client())` — the sync client wraps the async `x402Client`.\n- `register(\"eip155:8453\", ExactEvmScheme(signer=EthAccountSigner(account)))` — scheme + EVM signer.\n- `handle_402_response(dict(headers), content)` returns `(headers_dict, payload)` — pass `dict(raw.headers)`, NOT the httpx Response object (the client expects a `requests`-style shape, not `httpx.Response`).\n- The async `x402HTTPClient` (no `Sync`) is NOT callable and has no `.request` — use the sync `x402HTTPClientSync` + manual two-step POST.\n\n### Proven async variant (used on CortexCloud staging — settled real USDC on Base)\nIf the sync `EthAccountSigner` recipe breaks on your x402 version, use the async flow from `ct_paid_tests.py` (it worked where the sync adapter errored):\n\n```python\nimport asyncio, httpx\nfrom eth_account import Account\nfrom x402 import x402Client, prefer_network\nfrom x402.http.x402_http_client import x402HTTPClient\nfrom x402.mechanisms.evm.exact import ExactEvmScheme\n\nbuyer = Account.from_key(open(\"\u002Froot\u002Fbzcheck\u002Ftest_buyer.key\").read().strip())\nclient = x402Client()\nclient.register(\"eip155:8453\", ExactEvmScheme(signer=buyer))\nclient.register_policy(prefer_network(\"eip155:8453\"))\nxhttp = x402HTTPClient(client)\n\nasync def settle(session, method, path, json_body=None, params=None):\n    kw = {\"headers\": {\"content-type\": \"application\u002Fjson\"}}\n    if json_body is not None: kw[\"json\"] = json_body\n    if params is not None: kw[\"params\"] = params\n    r1 = await session.request(method, f\"{BASE}{path}\", **kw)\n    assert r1.status_code == 402\n    pr = xhttp.get_payment_required_response(lambda n: r1.headers.get(n), r1.json())\n    payload = await xhttp.create_payment_payload(pr)\n    pay_headers = xhttp.encode_payment_signature_header(payload)\n    kw2 = {\"headers\": {**kw[\"headers\"], **pay_headers}}\n    if json_body is not None: kw2[\"json\"] = json_body\n    if params is not None: kw2[\"params\"] = params\n    return await session.request(method, f\"{BASE}{path}\", **kw2)\n# asyncio.run against a route that is LIVE + reachable at BASE (https).\n```\n`ExactEvmScheme(signer=buyer)` with the raw `Account` works directly — no sync\u002Fsigner adapter. Prefer this if you hit sync-client errors.\n\n## Where to find the test-buyer key\nAsk the user \u002F check the deployment repo. It is a raw hex private key the facilitator can settle (USDC on Base, eip155:8453). Never log the key or the resulting signed payload.\n\n## Verify ledger + metrics after a successful payment\n- Query the payments ledger table for the settled row: confirm `provider_cost_usd`, `margin_usd`, `category` are non-null and `margin ≈ amount_usd − provider_cost_usd`.\n- Hit the internal metrics endpoint (gated by `INTERNAL_TOKEN`; 503 if unset) and confirm `successful_payments`, `cortexcloud_revenue_usd`, `cortexcloud_margin_usd`, and `revenue_by_mode` reflect the new row.\n\n## Manual x402 EIP-712 signing (without the x402 Python SDK)\nWhen the x402 SDK is unavailable or the sync adapter breaks, sign manually with `eth_account`:\n\n```python\nimport base64, json, os, time\nfrom eth_account import Account\nfrom eth_account.messages import encode_typed_data\n\nbuyer = Account.from_key(open(\"\u002Froot\u002Fbzcheck\u002Ftest_buyer.key\").read().strip())\n\n# 1. POST unsigned to get 402\n# 2. Decode challenge from `payment-required` header (x402 exact) or `www-authenticate` request= field (MPP)\npr_b64 = resp.headers[\"payment-required\"].rstrip(\"=\")\npr_b64 += \"=\" * ((4 - len(pr_b64) % 4) % 4)  # fix padding\nchallenge = json.loads(base64.b64decode(pr_b64))\naccepts0 = challenge[\"accepts\"][0]\n\n# 3. Build EIP-712 typed data from accepts0\ndomain = {\n    \"name\": accepts0[\"extra\"][\"name\"], \"version\": accepts0[\"extra\"][\"version\"],\n    \"chainId\": 8453, \"verifyingContract\": accepts0[\"asset\"],\n}\nmessage = {\n    \"from\": buyer.address, \"to\": accepts0[\"payTo\"],\n    \"value\": str(accepts0[\"amount\"]), \"validAfter\": \"0\",\n    \"validBefore\": str(int(time.time()) + 120),\n    \"nonce\": \"0x\" + os.urandom(32).hex(),\n}\ntyped_data = {\n    \"types\": {\n        \"EIP712Domain\": [{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"version\",\"type\":\"string\"},\n                          {\"name\":\"chainId\",\"type\":\"uint256\"},{\"name\":\"verifyingContract\",\"type\":\"address\"}],\n        \"TransferWithAuthorization\": [{\"name\":\"from\",\"type\":\"address\"},{\"name\":\"to\",\"type\":\"address\"},\n                          {\"name\":\"value\",\"type\":\"uint256\"},{\"name\":\"validAfter\",\"type\":\"uint256\"},\n                          {\"name\":\"validBefore\",\"type\":\"uint256\"},{\"name\":\"nonce\",\"type\":\"bytes32\"}],\n    },\n    \"primaryType\": \"TransferWithAuthorization\", \"domain\": domain, \"message\": message,\n}\n\n# 4. Sign and build payment-signature payload\nsigned = buyer.sign_message(encode_typed_data(full_message=typed_data))\nsig_hex = signed.signature.hex()\npayload = {\"x402Version\": 2, \"accepted\": accepts0,\n           \"payload\": {\"authorization\": message, \"signature\": sig_hex}}\npayment_sig = base64.b64encode(json.dumps(payload).encode()).decode()\n\n# 5. Retry with payment-signature header\n```\n\n**Pitfall: base64 padding.** The `payment-required` \u002F `request=` base64 values often lack trailing `=` padding — `binascii.Error: Incorrect padding` is fixed by stripping then re-padding to a multiple of 4, NOT by appending a fixed number of `=`.\n\n**Pitfall: challenge header differs by scheme.** x402 exact puts the challenge in `payment-required`; MPP\u002FTempo puts it in `www-authenticate request=`. Parse the right header for the active scheme.\n\n## Pitfalls\n- **Cloudflare TLS termination makes the challenge `resource.url` http, not https.** When prod sits behind Cloudflare (or any TLS-terminating reverse proxy), the incoming `request.url.scheme` is `http` (the proxy forwards plain HTTP to the backend), so the middleware emits `resource.url: http:\u002F\u002Fapi.cortexcloud.org\u002F...`. The CDP facilitator requires `^https:\u002F\u002F.*$` → every paid call fails validation with `doesn't match the regular expression ^https:\u002F\u002F.*$`. **Fix in the middleware** (root cause, not a test hack): derive the scheme from `X-Forwarded-Proto` when present: `scheme = request.headers.get(\"x-forwarded-proto\", request.url.scheme)`. This makes ALL paid endpoints (Quantum included) correctly publish an https challenge. Do NOT work around it by rewriting the challenge URL inside the smoke client — that masks the real bug and real agents would hit it too. (If you must smoke against prod before the fix lands, the workaround is to patch the challenge's `resource.url` to https in both the `payment-required` header AND the response body before calling `handle_402_response`, since the x402 client reads the header in V2 — but fix the middleware for real.)\n- **Don't read cost\u002Fmargin from `request.state` set by the route** — the middleware records the payment BEFORE calling the route, so `request.state` is empty at record time. Compute provider cost in the middleware from the request body, then record it.\n- **SQLAlchemy `func.interval(\"24 hours\")` is broken** — it emits `interval($3::VARCHAR)`, which Postgres rejects (`syntax error at or near \"$3\"`). Use `text(\"interval '24 hours'\")` instead. (Found via a 500 on the metrics endpoint.)\n- **Keep the staging server alive across tool calls.** On Proxmox `pct exec`, a foreground `uvicorn` dies when the exec session ends. Launch it as a background terminal process from the agent host (ssh + `exec uvicorn …`) so it persists; or `setsid nohup … & disown` inside the CT.\n- **Multiple stale uvicorn processes on the same port** silently serve old code and cause confusing \"address already in use\" \u002F wrong-config results. Before each relaunch: `pkill -9 -f \"port 8001\"` (or the relevant port), confirm `ss -ltnp | grep 8001` is free, then start exactly one.\n\n## What a green smoke proves vs. what it doesn't\n- Proves: payment settles, upstream executes, 200 returned, ledger\u002Fmetrics correct.\n- Does NOT prove the upstream provider credential is valid. If the upstream returns 401 (e.g. an expired API key) the payment STILL settles and is recorded — you'll see `validate 200, settle 200, then \u003Cupstream> 401`. That's a credential issue, not a code defect; flag it separately.\n- **503 `provider_unconfigured` BEFORE settlement is a config gap, not a code bug.** If the route returns `{\"error\":\"provider_unconfigured\",\"detail\":\"... API key not configured on gateway\"}`, the provider key (e.g. `ALCHEMY_API_KEY`) is empty in the deploy's config\u002F.env — the facilitator never gets reached. This surfaces per-provider: a CoinGecko-free endpoint (no key needed) can still prove the FULL money path (402→settle→200→margin) while the keyed provider's endpoints 503. Fix by adding the real key to the deploy env; do not code around it.\n- **Header spoofing cannot complete settlement on a throwaway localhost instance.** Injecting `host: api.cortexcloud.org` + `x-forwarded-proto: https` gets past the facilitator's `url_https` check, but the facilitator then runs an **`endpoint_reachable` preflight GET** on `resource.url` (the real public host). If the route is disabled\u002Funreachable there, preflight fails `Not Found` and settlement is rejected — even though your localhost instance would have served it. So: to smoke a route, it MUST be live + reachable at the public https URL (enable it on the staging instance, or use a real tunnel). Spoofing headers alone is insufficient; don't chase that dead end.\n",{},"main","38b32c99e7ed0b8e215d638e92cfa452c1ec3079","skills\u002Fimported\u002Fmlops\u002Fx402-payment-testing","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS","https:\u002F\u002Fgithub.com\u002Fjonahthan433","AI Consultant","2026-10-24 05:13:39",{"source":7,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add jonahthan433\u002FCortexOS --skill x402-payment-testing",{"tool":35,"command":36},"bunx","bunx skills add jonahthan433\u002FCortexOS --skill x402-payment-testing",{"tool":38,"command":39},"pnpm","pnpm dlx skills add jonahthan433\u002FCortexOS --skill x402-payment-testing","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fmlops\u002Fx402-payment-testing\u002FSKILL.md",true,[43],{"path":44,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":47,"sourceHtmlUrl":48},"skill.json","REFERENCE","参考文档",361,"https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fmlops\u002Fx402-payment-testing\u002Fskill.json",[50,56,62,68,74,80],{"skillNo":51,"name":52,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M7EDQZDQX3Q8Y7GCQX6KN9V7","opportunity-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fsales\u002Fopportunity-brief\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M7EDQYA0V9Y99VKBREJJ3MRT","morning-intel","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fmorning-intel\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M7EDQVX1JVY0B6PDHKKGM19G","decision-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fdecision-brief\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M7EDQV1GENZAC2SZSD8KZ3GM","weekly-review","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fproductivity\u002Fweekly-review\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M7EDQT2KETJ1Y3CGVN9EKW2J","system-health","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fsystem-health\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":18},"01M7EDQQN2JK3XPWMS1M4T0F3K","backup-restore","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fbackup-restore\u002FSKILL.md",[],[]]