z-zero-mcp-server 1.2.2 β 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -31
- package/dist/index.js +226 -134
- package/dist/lib/url-guard.d.ts +7 -0
- package/dist/lib/url-guard.js +45 -0
- package/dist/lib/web3-detector.js +12 -12
- package/dist/playwright_bridge.js +153 -18
- package/dist/types.d.ts +2 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +4 -3
- package/dist/wdk_backend.js +35 -32
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ A Zero-Trust Payment Protocol built for AI Agents using the [Model Context Proto
|
|
|
4
4
|
|
|
5
5
|
**What makes it different:**
|
|
6
6
|
- π **Zero-trust** β AI never sees PAN, CVV, or expiry. Card data exists only in RAM, injected via Playwright, then wiped.
|
|
7
|
-
- π **Web3 + Fiat** β Auto-detects crypto checkout (EIP-681) and routes to on
|
|
7
|
+
- π **Web3 + Fiat** β Auto-detects crypto checkout (EIP-681) and routes to a gasless USDC transfer on Base (Coinbase Paymaster). Falls back to JIT Visa for fiat.
|
|
8
8
|
- π§ **Smart Routing** β Cloud Knowledge Base (`get_merchant_hints`) provides platform-specific checkout playbooks for Shopify, Etsy, WooCommerce, and more.
|
|
9
9
|
- π **Self-Healing** β Failed checkouts are logged via `report_checkout_fail` for admin review, improving future success rates.
|
|
10
10
|
|
|
@@ -12,36 +12,39 @@ A Zero-Trust Payment Protocol built for AI Agents using the [Model Context Proto
|
|
|
12
12
|
|
|
13
13
|
## How It Works
|
|
14
14
|
|
|
15
|
-
```mermaid
|
|
16
|
-
sequenceDiagram
|
|
17
|
-
actor User
|
|
18
|
-
participant AI as AI Agent
|
|
19
|
-
participant MCP as MCP Tools
|
|
20
|
-
participant API as Z-ZERO API
|
|
21
|
-
participant DB as Supabase DB
|
|
22
|
-
|
|
23
|
-
User->>AI: "Buy me this Shopify item"
|
|
24
|
-
Note over AI: Scans available MCP Tools
|
|
25
|
-
AI->>MCP: Reads description of auto_pay_checkout
|
|
26
|
-
MCP-->>AI: "β οΈ MANDATORY: Read mcp://resources/sop first"
|
|
27
|
-
Note over AI: Fetches SOP before proceeding
|
|
28
|
-
AI->>MCP: Fetch resource mcp://resources/sop
|
|
29
|
-
MCP-->>AI: Platform rules + 3-Group payment SOP
|
|
30
|
-
Note over AI: "Shopify = physical goods. Must collect shipping first."
|
|
31
|
-
AI->>MCP: get_merchant_hints("_platform_shopify")
|
|
32
|
-
MCP->>API: GET /api/checkout-hints?domain=_platform_shopify&fields=merchant
|
|
33
|
-
API->>DB: Query checkout_hints table
|
|
34
|
-
DB-->>API: Platform hints data
|
|
35
|
-
API-->>MCP: Returns pre_steps + notes only
|
|
36
|
-
MCP-->>AI: "Fill shipping form first, click Next..."
|
|
37
|
-
Note over AI: Navigates checkout, fills shipping, waits for payment page
|
|
38
|
-
AI->>MCP: request_payment_token(amount, card_alias)
|
|
39
|
-
MCP-->>AI: Token: temp_auth_XYZ (1hr TTL)
|
|
40
|
-
AI->>MCP: execute_payment(token, checkout_url)
|
|
41
|
-
Note over MCP: Playwright auto-fills card form, burns token after use
|
|
42
|
-
MCP-->>AI: Success β payment complete
|
|
43
|
-
AI-->>User: "Done! Your Shopify item has been ordered."
|
|
44
15
|
```
|
|
16
|
+
User AI Agent MCP Tools Z-ZERO API
|
|
17
|
+
β β β β
|
|
18
|
+
β "Buy me this β β β
|
|
19
|
+
β Shopify item" β β β
|
|
20
|
+
βββββββββββββββββββΆβ β β
|
|
21
|
+
β β read mcp://resources/sop (MANDATORY) β
|
|
22
|
+
β βββββββββββββββββββββββΆβ β
|
|
23
|
+
β ββββ platform rules ββββ€ β
|
|
24
|
+
β β + payment SOP β β
|
|
25
|
+
β β β β
|
|
26
|
+
β β get_merchant_hints("_platform_shopify") β
|
|
27
|
+
β βββββββββββββββββββββββΆβ GET /checkout-hints β
|
|
28
|
+
β β βββββββββββββββββββββββΆβ
|
|
29
|
+
β ββββ pre_steps+notes βββ€βββββ hints data ββββββ€
|
|
30
|
+
β β β β
|
|
31
|
+
β β (fills shipping form, reaches payment page) β
|
|
32
|
+
β β β β
|
|
33
|
+
β β request_payment_token(amount, card_alias) β
|
|
34
|
+
β βββββββββββββββββββββββΆβ β
|
|
35
|
+
β ββββ temp_auth token βββ€ (1-hour TTL) β
|
|
36
|
+
β β β β
|
|
37
|
+
β β execute_payment(token, checkout_url) β
|
|
38
|
+
β βββββββββββββββββββββββΆβ β
|
|
39
|
+
β β Playwright auto-fills card form, β
|
|
40
|
+
β β burns token after single use π₯ β
|
|
41
|
+
β ββββββ β
success ββββββ€ β
|
|
42
|
+
β "Done! Your item β β β
|
|
43
|
+
β is ordered." β β β
|
|
44
|
+
ββββββββββββββββββββ€ β β
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
*The AI agent never touches card data β it only handles single-use tokens. Real card details are injected by Playwright at the last step and wiped from RAM.*
|
|
45
48
|
|
|
46
49
|
---
|
|
47
50
|
|
|
@@ -86,7 +89,7 @@ Get your Passport Key at: **[clawcard.store/dashboard/agents](https://www.clawca
|
|
|
86
89
|
|------|-------------|
|
|
87
90
|
| `list_cards` | List all virtual card aliases and balances |
|
|
88
91
|
| `check_balance` | Check spendable USD balance for a card alias |
|
|
89
|
-
| `get_deposit_addresses` | Get
|
|
92
|
+
| `get_deposit_addresses` | Get your Base deposit address to top up with USDC (stablecoin on Base) |
|
|
90
93
|
| `set_api_key` | Activate a new Passport Key instantly, no restart needed |
|
|
91
94
|
| `show_api_key_status` | Check if a Passport Key is currently loaded (prefix only) |
|
|
92
95
|
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
"use strict";
|
|
3
|
-
//
|
|
3
|
+
// Z-Zero MCP Server (z-zero-mcp-server) β version from package.json (see CURRENT_MCP_VERSION)
|
|
4
4
|
// Exposes secure JIT payment tools to AI Agents via Model Context Protocol
|
|
5
|
-
// Status: Connected to Z-ZERO Gateway β
|
|
5
|
+
// Status: Connected to Z-ZERO Gateway β JIT virtual cards + gasless USDC on Base
|
|
6
6
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
7
7
|
if (k2 === undefined) k2 = k;
|
|
8
8
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
@@ -63,6 +63,15 @@ const web3_detector_js_1 = require("./lib/web3-detector.js");
|
|
|
63
63
|
const extract_total_price_js_1 = require("./lib/extract-total-price.js");
|
|
64
64
|
const playwright_1 = require("playwright");
|
|
65
65
|
const key_store_js_1 = require("./lib/key-store.js"); // β
Hot-Swap support
|
|
66
|
+
const url_guard_js_1 = require("./lib/url-guard.js");
|
|
67
|
+
/** Masked, non-reconstructable hint for a secret key (for debug output only). */
|
|
68
|
+
function maskKey(key) {
|
|
69
|
+
if (!key)
|
|
70
|
+
return "";
|
|
71
|
+
if (key.length <= 8)
|
|
72
|
+
return "β’β’β’β’";
|
|
73
|
+
return `${key.slice(0, 4)}β¦${key.slice(-2)}`;
|
|
74
|
+
}
|
|
66
75
|
// ============================================================
|
|
67
76
|
// CREATE MCP SERVER
|
|
68
77
|
// ============================================================
|
|
@@ -155,7 +164,7 @@ server.tool("check_balance", "Check spendable USD balance for a card alias. For
|
|
|
155
164
|
// ============================================================
|
|
156
165
|
// TOOL 2.5: Get deposit addresses (Phase 14 feature)
|
|
157
166
|
// ============================================================
|
|
158
|
-
server.tool("get_deposit_addresses", "Get
|
|
167
|
+
server.tool("get_deposit_addresses", "Get your Base deposit address to top up your wallet with USDC (or any supported stablecoin on Base).", {}, async () => {
|
|
159
168
|
const data = await getDepositAddressesRemote();
|
|
160
169
|
if (data?.error === "AUTH_REQUIRED") {
|
|
161
170
|
return {
|
|
@@ -168,32 +177,30 @@ server.tool("get_deposit_addresses", "Get crypto deposit addresses (EVM + Tron)
|
|
|
168
177
|
isError: true
|
|
169
178
|
};
|
|
170
179
|
}
|
|
171
|
-
// ββ
|
|
180
|
+
// ββ Base smart-account wallet βββββββββββββββββββββββββββββββββββββββββ
|
|
172
181
|
if (data?.wdk_wallet?.address) {
|
|
173
|
-
const
|
|
182
|
+
const walletAddr = data.wdk_wallet.address;
|
|
174
183
|
const balance = data.wdk_wallet.balance_usdt ?? 0;
|
|
175
|
-
const tronAddr = data.wdk_wallet.tron_address;
|
|
176
184
|
return {
|
|
177
185
|
content: [{
|
|
178
186
|
type: "text",
|
|
179
187
|
text: JSON.stringify({
|
|
180
|
-
wallet_type: "
|
|
181
|
-
|
|
188
|
+
wallet_type: "Base smart account",
|
|
189
|
+
balance_usdc: balance,
|
|
182
190
|
supported_chains: [
|
|
183
|
-
{ chain: "
|
|
184
|
-
...(tronAddr ? [{ chain: "Tron", token: "USDT", address: tronAddr }] : []),
|
|
191
|
+
{ chain: "Base", token: "USDC", address: walletAddr },
|
|
185
192
|
],
|
|
186
|
-
instructions: `Send
|
|
187
|
-
note: "Gasless
|
|
193
|
+
instructions: `Send USDC (or any supported stablecoin) on Base to: ${walletAddr}`,
|
|
194
|
+
note: "Gasless spending via the Coinbase Paymaster on Base."
|
|
188
195
|
}, null, 2),
|
|
189
196
|
}],
|
|
190
197
|
};
|
|
191
198
|
}
|
|
192
|
-
// No
|
|
199
|
+
// No Base wallet connected
|
|
193
200
|
return {
|
|
194
201
|
content: [{
|
|
195
202
|
type: "text",
|
|
196
|
-
text: "No
|
|
203
|
+
text: "No Base wallet found. Please create one at https://www.clawcard.store/dashboard/agent-wallet",
|
|
197
204
|
}],
|
|
198
205
|
isError: true,
|
|
199
206
|
};
|
|
@@ -201,7 +208,7 @@ server.tool("get_deposit_addresses", "Get crypto deposit addresses (EVM + Tron)
|
|
|
201
208
|
// ============================================================
|
|
202
209
|
// TOOL 3: Request a temporary payment token (issues secure JIT card)
|
|
203
210
|
// ============================================================
|
|
204
|
-
server.tool("request_payment_token", "β οΈ
|
|
211
|
+
server.tool("request_payment_token", "Request a single-use JIT virtual card ($1β$100) locked to one amount + merchant. β οΈ Read mcp://resources/sop first. Only call once the FINAL total is visible β for physical goods that is AFTER shipping is submitted (use get_merchant_hints to navigate there). For digital goods with the price already visible, prefer auto_pay_checkout instead.", {
|
|
205
212
|
card_alias: zod_1.z
|
|
206
213
|
.string()
|
|
207
214
|
.describe("Which card to charge, e.g. 'Card_01'"),
|
|
@@ -279,7 +286,7 @@ server.tool("get_merchant_hints", "Get merchant navigation flow for a domain or
|
|
|
279
286
|
.string()
|
|
280
287
|
.describe("The main domain of the checkout page, e.g. 'amazon.com' or 'shopify.com'. Strip 'www.' prefix."),
|
|
281
288
|
}, async ({ domain }) => {
|
|
282
|
-
const ZZERO_API = process.env.Z_ZERO_API_BASE || "https://www.clawcard.store";
|
|
289
|
+
const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://www.clawcard.store";
|
|
283
290
|
const INTERNAL_SECRET = process.env.Z_ZERO_INTERNAL_SECRET || "";
|
|
284
291
|
try {
|
|
285
292
|
const resp = await fetch(`${ZZERO_API}/api/checkout-hints?domain=${encodeURIComponent(domain)}&fields=merchant`, {
|
|
@@ -306,7 +313,7 @@ server.tool("get_merchant_hints", "Get merchant navigation flow for a domain or
|
|
|
306
313
|
// ============================================================
|
|
307
314
|
// TOOL 4b: Execute payment (The "Invisible Hand")
|
|
308
315
|
// ============================================================
|
|
309
|
-
server.tool("execute_payment", "Execute a payment
|
|
316
|
+
server.tool("execute_payment", "Execute a payment with a one-time token: Z-Zero opens a headless browser, injects the card (you NEVER see the PAN), clicks Pay, then watches for a REAL confirmation before reporting success. Returns a `status`: `confirmed` (order placed β token burned, receipt_id may hold a real order #), `declined` (merchant rejected β token kept for refund), `unconfirmed` (submitted but no confirmation seen β do NOT retry blindly, verify first), `not_submitted` (no Pay button β supply a submit_selector hint), or `no_fields`. ALWAYS pass actual_amount so overcharges are blocked and underspend refunded.", {
|
|
310
317
|
token: zod_1.z
|
|
311
318
|
.string()
|
|
312
319
|
.describe("The temporary payment token from request_payment_token"),
|
|
@@ -317,7 +324,7 @@ server.tool("execute_payment", "Execute a payment using a temporary token. This
|
|
|
317
324
|
actual_amount: zod_1.z
|
|
318
325
|
.number()
|
|
319
326
|
.optional()
|
|
320
|
-
.describe("The
|
|
327
|
+
.describe("STRONGLY RECOMMENDED. The final total shown on the checkout page (incl. shipping + tax). Enables the overcharge block and the underspend refund β omit only if it is genuinely unreadable."),
|
|
321
328
|
hints: zod_1.z
|
|
322
329
|
.object({
|
|
323
330
|
pre_steps: zod_1.z.array(zod_1.z.string()).optional(),
|
|
@@ -332,6 +339,23 @@ server.tool("execute_payment", "Execute a payment using a temporary token. This
|
|
|
332
339
|
.optional()
|
|
333
340
|
.describe("Optional hints from get_merchant_hints β selectors and pre-steps to guide Playwright. Use when default selectors fail or for complex multi-step checkouts."),
|
|
334
341
|
}, async ({ token, checkout_url, actual_amount, hints }) => {
|
|
342
|
+
// Step 0: SSRF / scheme guard BEFORE we drive a browser to this URL and inject a real PAN/CVV.
|
|
343
|
+
try {
|
|
344
|
+
(0, url_guard_js_1.assertSafeCheckoutUrl)(checkout_url);
|
|
345
|
+
}
|
|
346
|
+
catch (e) {
|
|
347
|
+
return {
|
|
348
|
+
content: [{
|
|
349
|
+
type: "text",
|
|
350
|
+
text: JSON.stringify({
|
|
351
|
+
success: false,
|
|
352
|
+
status: "blocked",
|
|
353
|
+
message: `π¨ Refused to open checkout_url: ${e instanceof Error ? e.message : String(e)}`,
|
|
354
|
+
}, null, 2),
|
|
355
|
+
}],
|
|
356
|
+
isError: true,
|
|
357
|
+
};
|
|
358
|
+
}
|
|
335
359
|
// Step 1: Resolve token β card data (RAM only)
|
|
336
360
|
const cardData = await resolveTokenRemote(token);
|
|
337
361
|
if (cardData?.error === "AUTH_REQUIRED") {
|
|
@@ -383,31 +407,35 @@ server.tool("execute_payment", "Execute a payment using a temporary token. This
|
|
|
383
407
|
}
|
|
384
408
|
// Step 2: Use Playwright to inject card into checkout form (with optional agent hints)
|
|
385
409
|
const result = await (0, playwright_bridge_js_1.fillCheckoutForm)(checkout_url, cardData, undefined, hints);
|
|
386
|
-
// Step 3: Burn the token ONLY
|
|
387
|
-
//
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
// Partner card issuer will fire a 'card.authorization.declined' webhook β refund handled there
|
|
410
|
+
// Step 3: Burn the token ONLY on a CONFIRMED payment (result.success === status 'confirmed').
|
|
411
|
+
// Every other outcome (declined / unconfirmed / not_submitted / no_fields / error) leaves the
|
|
412
|
+
// token UNBURNED so the funds stay recoverable. "Filled a field" is NOT a payment.
|
|
413
|
+
if (!result.success) {
|
|
414
|
+
// `declined` = merchant rejected β webhook refund flow handles it.
|
|
415
|
+
// Everything else = we couldn't prove a charge happened β funds stay locked, recoverable.
|
|
416
|
+
const isDeclined = result.status === 'declined';
|
|
394
417
|
return {
|
|
395
418
|
content: [
|
|
396
419
|
{
|
|
397
420
|
type: "text",
|
|
398
421
|
text: JSON.stringify({
|
|
399
422
|
success: false,
|
|
400
|
-
|
|
423
|
+
status: result.status,
|
|
424
|
+
message: result.message || "Payment was not confirmed.",
|
|
401
425
|
token_status: "ACTIVE",
|
|
402
|
-
note:
|
|
426
|
+
note: isDeclined
|
|
427
|
+
? "Token NOT burned. Funds will be refunded automatically via the decline webhook within minutes."
|
|
428
|
+
: "Token NOT burned β no confirmed charge. If you are unsure whether the order went through, do NOT retry blindly (double-charge risk); verify the merchant, or call cancel_payment_token to release the funds.",
|
|
403
429
|
}, null, 2),
|
|
404
430
|
},
|
|
405
431
|
],
|
|
406
432
|
isError: true,
|
|
407
433
|
};
|
|
408
434
|
}
|
|
435
|
+
// Confirmed β burn the token, passing the REAL receipt id if one was scraped.
|
|
436
|
+
await burnTokenRemote(token, result.receipt_id);
|
|
409
437
|
// Step 4: Refund underspend if actual amount was less than token amount
|
|
410
|
-
if (actual_amount !== undefined
|
|
438
|
+
if (actual_amount !== undefined) {
|
|
411
439
|
await refundUnderspendRemote(token, actual_amount);
|
|
412
440
|
}
|
|
413
441
|
// Step 5: Return result (NEVER includes card numbers)
|
|
@@ -416,11 +444,12 @@ server.tool("execute_payment", "Execute a payment using a temporary token. This
|
|
|
416
444
|
{
|
|
417
445
|
type: "text",
|
|
418
446
|
text: JSON.stringify({
|
|
419
|
-
success:
|
|
447
|
+
success: true,
|
|
448
|
+
status: "confirmed",
|
|
420
449
|
message: result.message,
|
|
421
450
|
receipt_id: result.receipt_id || null,
|
|
422
451
|
token_status: "BURNED",
|
|
423
|
-
note: "Token has been permanently invalidated after this transaction.",
|
|
452
|
+
note: "Token has been permanently invalidated after this confirmed transaction.",
|
|
424
453
|
}, null, 2),
|
|
425
454
|
},
|
|
426
455
|
],
|
|
@@ -524,7 +553,46 @@ server.tool("set_api_key", "Activate a new Passport Key instantly, no restart ne
|
|
|
524
553
|
.string()
|
|
525
554
|
.describe("The new Passport Key to activate. Must start with 'zk_live_' or 'zk_test_'. Get from: https://www.clawcard.store/dashboard/agents"),
|
|
526
555
|
}, async ({ api_key }) => {
|
|
527
|
-
|
|
556
|
+
// Step 1: Format validation
|
|
557
|
+
const trimmed = api_key.trim();
|
|
558
|
+
if (!trimmed.startsWith("zk_live_") && !trimmed.startsWith("zk_test_")) {
|
|
559
|
+
return {
|
|
560
|
+
content: [{ type: "text", text: `β Invalid key format β must start with "zk_live_" or "zk_test_".` }],
|
|
561
|
+
isError: true,
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
// Step 2: Validate new key against Dashboard API before swapping
|
|
565
|
+
const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://www.clawcard.store";
|
|
566
|
+
try {
|
|
567
|
+
const resp = await fetch(`${ZZERO_API}/api/wdk/balance`, {
|
|
568
|
+
headers: {
|
|
569
|
+
"Authorization": `Bearer ${trimmed}`,
|
|
570
|
+
"x-mcp-version": version_js_2.CURRENT_MCP_VERSION,
|
|
571
|
+
},
|
|
572
|
+
signal: AbortSignal.timeout(8000),
|
|
573
|
+
});
|
|
574
|
+
if (resp.status === 401) {
|
|
575
|
+
return {
|
|
576
|
+
content: [{ type: "text", text: `β Key rejected by server β invalid or deactivated. Please check your key at https://www.clawcard.store/dashboard/agents` }],
|
|
577
|
+
isError: true,
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
// 426 = version outdated, but key itself could be valid β allow swap
|
|
581
|
+
if (!resp.ok && resp.status !== 426) {
|
|
582
|
+
return {
|
|
583
|
+
content: [{ type: "text", text: `β Could not validate key (server returned ${resp.status}). Try again later.` }],
|
|
584
|
+
isError: true,
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
catch (err) {
|
|
589
|
+
return {
|
|
590
|
+
content: [{ type: "text", text: `β Could not reach server to validate key: ${err?.message || 'timeout'}. Try again later.` }],
|
|
591
|
+
isError: true,
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
// Step 3: Swap key in RAM (old key is soft-revoked β just forgotten)
|
|
595
|
+
const result = (0, key_store_js_1.setPassportKey)(trimmed);
|
|
528
596
|
if (!result.ok) {
|
|
529
597
|
return {
|
|
530
598
|
content: [{ type: "text", text: `β ${result.message}` }],
|
|
@@ -537,8 +605,9 @@ server.tool("set_api_key", "Activate a new Passport Key instantly, no restart ne
|
|
|
537
605
|
text: JSON.stringify({
|
|
538
606
|
status: "SUCCESS",
|
|
539
607
|
message: `β
${result.message}`,
|
|
540
|
-
|
|
541
|
-
|
|
608
|
+
// Masked hint only β never echo a usable portion of the secret to the chat/model context.
|
|
609
|
+
active_key_hint: maskKey(trimmed),
|
|
610
|
+
note: "All subsequent API calls will use this key. Previous key removed from this session (soft revoke).",
|
|
542
611
|
}, null, 2),
|
|
543
612
|
}],
|
|
544
613
|
};
|
|
@@ -554,8 +623,7 @@ server.tool("show_api_key_status", "Check if Passport Key is configured. Shows p
|
|
|
554
623
|
type: "text",
|
|
555
624
|
text: JSON.stringify({
|
|
556
625
|
configured: hasKey,
|
|
557
|
-
|
|
558
|
-
wallet_mode: process.env.Z_ZERO_WALLET_MODE || "custodial",
|
|
626
|
+
key_hint: hasKey ? maskKey(key) : null,
|
|
559
627
|
note: hasKey
|
|
560
628
|
? "Key is active. Call set_api_key to update it."
|
|
561
629
|
: "No key configured. Call set_api_key with your Passport Key from https://www.clawcard.store/dashboard/agents",
|
|
@@ -572,8 +640,14 @@ server.tool("auto_pay_checkout", "β οΈ MANDATORY: Read mcp://resources/sop fir
|
|
|
572
640
|
.string()
|
|
573
641
|
.describe("Card alias to charge for JIT Fiat fallback, e.g. 'Card_01'."),
|
|
574
642
|
}, async ({ checkout_url, card_alias }) => {
|
|
575
|
-
const ZZERO_API = process.env.Z_ZERO_API_BASE || "https://www.clawcard.store";
|
|
643
|
+
const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://www.clawcard.store";
|
|
576
644
|
const API_KEY = (0, key_store_js_1.getPassportKey)(); // β
FIX: use hot-swap key store, not process.env
|
|
645
|
+
// Spend guard for the autonomous path. auto_pay derives the amount itself
|
|
646
|
+
// (scraped fiat total OR on-chain amount from an EIP-681 link / calldata), so there is
|
|
647
|
+
// no human-authorized token to cross-check against β this range IS the only amount guard.
|
|
648
|
+
// It bounds the blast radius if price extraction or a payment link is wrong/malicious.
|
|
649
|
+
const AUTO_PAY_MIN_USD = 1;
|
|
650
|
+
const AUTO_PAY_MAX_USD = 100;
|
|
577
651
|
if (!API_KEY) {
|
|
578
652
|
return {
|
|
579
653
|
content: [{ type: "text", text: JSON.stringify({
|
|
@@ -583,31 +657,8 @@ server.tool("auto_pay_checkout", "β οΈ MANDATORY: Read mcp://resources/sop fir
|
|
|
583
657
|
isError: true,
|
|
584
658
|
};
|
|
585
659
|
}
|
|
586
|
-
// ββ SSRF guard
|
|
587
|
-
(()
|
|
588
|
-
let url;
|
|
589
|
-
try {
|
|
590
|
-
url = new URL(checkout_url);
|
|
591
|
-
}
|
|
592
|
-
catch {
|
|
593
|
-
throw new Error(`Invalid checkout_url: ${checkout_url}`);
|
|
594
|
-
}
|
|
595
|
-
const isDev = process.env.NODE_ENV !== "production";
|
|
596
|
-
const hostname = url.hostname;
|
|
597
|
-
if (!(isDev && (hostname === "localhost" || hostname === "127.0.0.1"))) {
|
|
598
|
-
if (url.protocol !== "https:") {
|
|
599
|
-
throw new Error(`checkout_url must use HTTPS.`);
|
|
600
|
-
}
|
|
601
|
-
const privatePatterns = [
|
|
602
|
-
/^localhost$/i, /^127\./, /^10\./,
|
|
603
|
-
/^172\.(1[6-9]|2\d|3[01])\./, /^192\.168\./,
|
|
604
|
-
/^169\.254\./, /^\[::1\]$/, /^0\.0\.0\.0$/,
|
|
605
|
-
];
|
|
606
|
-
if (privatePatterns.some(p => p.test(hostname))) {
|
|
607
|
-
throw new Error(`SSRF blocked host: ${hostname}`);
|
|
608
|
-
}
|
|
609
|
-
}
|
|
610
|
-
})();
|
|
660
|
+
// ββ SSRF guard (shared helper) βββββββββββββββββββββββββββββββ
|
|
661
|
+
(0, url_guard_js_1.assertSafeCheckoutUrl)(checkout_url);
|
|
611
662
|
// ββ Single Browser Instance for efficiency ββββββββββββββββββ
|
|
612
663
|
const browser = await playwright_1.chromium.launch({ headless: true });
|
|
613
664
|
const context = await browser.newContext();
|
|
@@ -631,9 +682,20 @@ server.tool("auto_pay_checkout", "β οΈ MANDATORY: Read mcp://resources/sop fir
|
|
|
631
682
|
}, null, 2) }],
|
|
632
683
|
};
|
|
633
684
|
}
|
|
685
|
+
// Same spend guard as the fiat route β the on-chain amount comes from an
|
|
686
|
+
// untrusted EIP-681 link / calldata, so cap it before sending USDC.
|
|
687
|
+
if (amount < AUTO_PAY_MIN_USD || amount > AUTO_PAY_MAX_USD) {
|
|
688
|
+
return {
|
|
689
|
+
content: [{ type: "text", text: JSON.stringify({
|
|
690
|
+
route: "WEB3", status: "AMOUNT_OUT_OF_RANGE", recipient: to, detected_amount: amount,
|
|
691
|
+
message: `π¨ BLOCKED: Web3 amount $${amount} is outside the allowed $${AUTO_PAY_MIN_USD}β$${AUTO_PAY_MAX_USD} range. No funds were sent.`,
|
|
692
|
+
}, null, 2) }],
|
|
693
|
+
isError: true,
|
|
694
|
+
};
|
|
695
|
+
}
|
|
634
696
|
const resp = await fetch(`${ZZERO_API}/api/wdk/transfer`, {
|
|
635
697
|
method: "POST",
|
|
636
|
-
headers: { "Content-Type": "application/json", "
|
|
698
|
+
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${API_KEY}` },
|
|
637
699
|
body: JSON.stringify({ to, amount, card_alias }),
|
|
638
700
|
});
|
|
639
701
|
const txResult = await resp.json();
|
|
@@ -648,9 +710,9 @@ server.tool("auto_pay_checkout", "β οΈ MANDATORY: Read mcp://resources/sop fir
|
|
|
648
710
|
return {
|
|
649
711
|
content: [{ type: "text", text: JSON.stringify({
|
|
650
712
|
route: "WEB3", method: web3Result.method, status: "SUCCESS",
|
|
651
|
-
recipient: to,
|
|
652
|
-
message: `β
Web3 payment sent on-chain! ${amount}
|
|
653
|
-
gas_savings: "~$0.001 (
|
|
713
|
+
recipient: to, amount_usdc: amount, tx_hash: txResult.txHash,
|
|
714
|
+
message: `β
Web3 payment sent on-chain! ${amount} USDC β ${to}.`,
|
|
715
|
+
gas_savings: "~$0.001 (Coinbase Paymaster on Base, gasless for user)",
|
|
654
716
|
}, null, 2) }],
|
|
655
717
|
};
|
|
656
718
|
}
|
|
@@ -665,10 +727,11 @@ server.tool("auto_pay_checkout", "β οΈ MANDATORY: Read mcp://resources/sop fir
|
|
|
665
727
|
isError: true,
|
|
666
728
|
};
|
|
667
729
|
}
|
|
668
|
-
if (totalPrice <
|
|
730
|
+
if (totalPrice < AUTO_PAY_MIN_USD || totalPrice > AUTO_PAY_MAX_USD) {
|
|
669
731
|
return {
|
|
670
732
|
content: [{ type: "text", text: JSON.stringify({
|
|
671
733
|
route: "FIAT", status: "AMOUNT_OUT_OF_RANGE", detected_price: totalPrice,
|
|
734
|
+
message: `Detected total $${totalPrice} is outside the allowed $${AUTO_PAY_MIN_USD}β$${AUTO_PAY_MAX_USD} range.`,
|
|
672
735
|
}, null, 2) }],
|
|
673
736
|
isError: true,
|
|
674
737
|
};
|
|
@@ -683,18 +746,25 @@ server.tool("auto_pay_checkout", "β οΈ MANDATORY: Read mcp://resources/sop fir
|
|
|
683
746
|
throw new Error("Card resolve failed");
|
|
684
747
|
// Fill Form (Reusing the same page!)
|
|
685
748
|
const fillResult = await (0, playwright_bridge_js_1.fillCheckoutForm)(checkout_url, cardData, page);
|
|
749
|
+
// Burn ONLY on a confirmed charge. Any other outcome leaves the JIT token unburned
|
|
750
|
+
// so the locked funds are recoverable (cancel/expire/decline-webhook).
|
|
686
751
|
if (fillResult.success) {
|
|
687
|
-
const burnOk = await burnTokenRemote(token.token);
|
|
752
|
+
const burnOk = await burnTokenRemote(token.token, fillResult.receipt_id);
|
|
688
753
|
if (!burnOk)
|
|
689
754
|
console.error(`[WARN] Token burn failed for ${token.token} β manual check needed`);
|
|
690
755
|
}
|
|
756
|
+
else {
|
|
757
|
+
// Release the freshly-issued JIT token so the price funds don't sit locked on a non-payment.
|
|
758
|
+
await cancelTokenRemote(token.token).catch(() => { });
|
|
759
|
+
}
|
|
691
760
|
return {
|
|
692
761
|
content: [{ type: "text", text: JSON.stringify({
|
|
693
|
-
route: "FIAT",
|
|
762
|
+
route: "FIAT",
|
|
763
|
+
status: fillResult.success ? "SUCCESS" : (fillResult.status || "FILL_FAILED").toUpperCase(),
|
|
694
764
|
detected_price: totalPrice,
|
|
695
765
|
message: fillResult.success
|
|
696
|
-
? `β
JIT card issued for $${totalPrice} and
|
|
697
|
-
: `β
|
|
766
|
+
? `β
Confirmed: JIT card issued for $${totalPrice} and order confirmed by merchant.`
|
|
767
|
+
: `β Not confirmed (${fillResult.status}): ${fillResult.message} Token released.`,
|
|
698
768
|
receipt_id: fillResult.receipt_id || null,
|
|
699
769
|
}, null, 2) }],
|
|
700
770
|
isError: !fillResult.success,
|
|
@@ -733,7 +803,7 @@ server.tool("report_checkout_fail", "Report a checkout URL that you could not co
|
|
|
733
803
|
.optional()
|
|
734
804
|
.describe("Brief description of what went wrong, e.g. 'Could not find card number field' or 'Page redirected to CAPTCHA'."),
|
|
735
805
|
}, async ({ url, error_type, error_message }) => {
|
|
736
|
-
const ZZERO_API = process.env.Z_ZERO_API_BASE || "https://www.clawcard.store";
|
|
806
|
+
const ZZERO_API = process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "https://www.clawcard.store";
|
|
737
807
|
const INTERNAL_SECRET = process.env.Z_ZERO_INTERNAL_SECRET || "";
|
|
738
808
|
try {
|
|
739
809
|
await fetch(`${ZZERO_API}/api/checkout-hints`, {
|
|
@@ -765,93 +835,115 @@ server.resource("Standard Operating Procedure (SOP) for Autonomous Payments", "m
|
|
|
765
835
|
description: "A comprehensive guide on how AI agents should use the Z-ZERO tools to execute secure, zero-trust payments."
|
|
766
836
|
}, async (uri) => {
|
|
767
837
|
const sopContent = `
|
|
768
|
-
# Z-ZERO Autonomous Payment
|
|
838
|
+
# Z-ZERO Autonomous Payment SOP (v2.1.0 β matches MCP β₯ 1.3.0)
|
|
839
|
+
|
|
840
|
+
How an AI Agent uses Z-ZERO to buy goods for the user WITHOUT ever handling raw card data.
|
|
841
|
+
Mental model: you only ever hold a one-time **token** + a **URL**. Z-ZERO does the privileged
|
|
842
|
+
card injection in the background. "Filling a form" is NOT "paying" β always read the result \`status\`.
|
|
843
|
+
|
|
844
|
+
---
|
|
769
845
|
|
|
770
|
-
|
|
846
|
+
## STEP 0 β Route the request (decide FIRST)
|
|
847
|
+
|
|
848
|
+
One question: **is the final price visible now, or only after shipping?**
|
|
849
|
+
- **Digital / SaaS / API / on-chain** (price visible now) β **PATH A** (one call).
|
|
850
|
+
- **Physical goods** (Shopify, Etsy, WooCommerce β price appears only AFTER shipping) β **PATH B**.
|
|
851
|
+
|
|
852
|
+
Always do WALLET & SAFETY first.
|
|
771
853
|
|
|
772
854
|
---
|
|
773
855
|
|
|
774
|
-
##
|
|
856
|
+
## WALLET & SAFETY (do first, every time)
|
|
775
857
|
|
|
776
858
|
Tools: \`check_balance\`, \`list_cards\`, \`get_deposit_addresses\`, \`set_api_key\`, \`show_api_key_status\`
|
|
777
859
|
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
4. Never ask for the API key proactively β only call \`set_api_key\` when the user explicitly gives you one.
|
|
860
|
+
1. Confirm exactly what the user wants and the expected USD price.
|
|
861
|
+
2. \`check_balance\` on the default \`card_alias\` β if insufficient, STOP and ask the user to deposit
|
|
862
|
+
USDC on Base (\`get_deposit_addresses\`).
|
|
863
|
+
3. \`list_cards\` = see aliases + active tokens, NOT spendable balance.
|
|
864
|
+
4. Never ask for the API key proactively; only \`set_api_key\` when the user explicitly hands you one.
|
|
784
865
|
|
|
785
866
|
---
|
|
786
867
|
|
|
787
|
-
##
|
|
868
|
+
## PATH A β Digital goods / SaaS / API (price already visible)
|
|
788
869
|
|
|
789
|
-
|
|
870
|
+
Call \`auto_pay_checkout(checkout_url, card_alias)\` β one call:
|
|
871
|
+
- Auto-detects on-chain (sends USDC on Base, gasless via Coinbase Paymaster) vs fiat (issues a JIT
|
|
872
|
+
card + fills the form).
|
|
873
|
+
- Amount is read from the page and capped to $1β$100.
|
|
874
|
+
- Read the returned \`status\` β see **PAYMENT OUTCOMES** below.
|
|
790
875
|
|
|
791
|
-
|
|
876
|
+
---
|
|
792
877
|
|
|
793
|
-
|
|
794
|
-
Confirm item, price, and check balance (see Group 1).
|
|
878
|
+
## PATH B β Physical goods (price only after shipping)
|
|
795
879
|
|
|
796
|
-
|
|
797
|
-
Use browser tools to navigate to the final payment page where card fields are visible and the FINAL total (including shipping + tax) is displayed.
|
|
798
|
-
- β DO NOT call \`request_payment_token\` until BOTH conditions are true:
|
|
799
|
-
1. Shipping/personal info submitted successfully
|
|
800
|
-
2. Card input fields are visible on screen
|
|
880
|
+
Tools: \`get_merchant_hints\`, \`request_payment_token\`, \`execute_payment\`, \`request_human_approval\`
|
|
801
881
|
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
882
|
+
1. \`get_merchant_hints(domain or _platform_key, e.g. _platform_shopify)\` β \`pre_steps\`, \`notes\`, \`platform\`.
|
|
883
|
+
2. Follow \`pre_steps\` in YOUR browser: navigate, add to cart, submit shipping (ask the user via
|
|
884
|
+
\`request_human_approval\` if shipping info is unknown).
|
|
885
|
+
3. Wait until the card section is visible AND the FINAL total (incl. shipping + tax) is shown.
|
|
886
|
+
4. \`request_payment_token(card_alias, amount = exact final total, merchant)\` β one-time token, valid 1h.
|
|
887
|
+
5. \`execute_payment(token, checkout_url, actual_amount = final total)\`. ALWAYS pass actual_amount.
|
|
805
888
|
|
|
806
|
-
|
|
807
|
-
Call \`execute_payment\` with the token + checkout URL.
|
|
808
|
-
Z-ZERO opens a headless browser, injects the card securely, clicks Pay. Token burns instantly after success.
|
|
889
|
+
β Never call \`request_payment_token\` before BOTH: shipping submitted AND card fields + final total visible.
|
|
809
890
|
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
-
|
|
814
|
-
|
|
891
|
+
β οΈ **Resumable URL required.** \`execute_payment\` opens its OWN fresh, cookieless browser at \`checkout_url\` β
|
|
892
|
+
your own browsing session does NOT carry over. So \`checkout_url\` must reload the cart + final total + card
|
|
893
|
+
fields on its own (e.g. a Shopify \`/checkouts/c/<token>\` or Etsy checkout-token URL). If it instead needs
|
|
894
|
+
your logged-in session/cookies, the cold browser lands on an empty cart and you'll get \`no_fields\` β in that
|
|
895
|
+
case finish the purchase in your own browser, or use a merchant whose checkout URL is self-resumable.
|
|
896
|
+
|
|
897
|
+
### Platform detection
|
|
898
|
+
| Platform | Signal |
|
|
899
|
+
|---|---|
|
|
900
|
+
| Shopify | \`window.Shopify\`, OR \`<script src="cdn.shopify.com">\`, OR \`<meta name="shopify-checkout-api-token">\` |
|
|
901
|
+
| Etsy | URL matches \`*.etsy.com\` |
|
|
902
|
+
| WooCommerce | \`<body class="β¦ woocommerce β¦">\`, OR assets from \`wp-content/plugins/woocommerce\` |
|
|
815
903
|
|
|
816
904
|
---
|
|
817
905
|
|
|
818
|
-
##
|
|
906
|
+
## PAYMENT OUTCOMES β how to read execute_payment / auto_pay_checkout
|
|
819
907
|
|
|
820
|
-
|
|
908
|
+
Both return a \`status\`. Act on it β do not assume success:
|
|
909
|
+
- \`confirmed\` β order placed and confirmed; token burned; \`receipt_id\` = real order # if found. β
Done.
|
|
910
|
+
- \`declined\` β merchant rejected the card; token kept ACTIVE; a refund webhook handles it. Report to
|
|
911
|
+
the user; do not blindly retry the same card.
|
|
912
|
+
- \`unconfirmed\` β card submitted but NO confirmation seen. Token NOT burned. β οΈ Do NOT retry blindly
|
|
913
|
+
(double-charge risk). First VERIFY in your own browser whether the order went through; if not, retry
|
|
914
|
+
or \`cancel_payment_token\` to release the funds.
|
|
915
|
+
- \`not_submitted\` β fields filled but no Pay button was clicked. Token NOT burned. Get a
|
|
916
|
+
\`submit_selector\` via \`get_merchant_hints\` and retry, or click Pay in your own browser.
|
|
917
|
+
- \`no_fields\` β no card fields found (wrong page or unsupported form). Token NOT burned β
|
|
918
|
+
\`report_checkout_fail\`.
|
|
821
919
|
|
|
822
|
-
|
|
823
|
-
For pages where the final total is already visible, call \`auto_pay_checkout\`:
|
|
824
|
-
- It auto-detects Web3 (sends USDT on-chain via WDK) vs Fiat (issues JIT Visa card + auto-fills form).
|
|
825
|
-
- One call handles everything.
|
|
920
|
+
After \`confirmed\`/\`unconfirmed\`, prefer to visually confirm the order page with your own browser tools.
|
|
826
921
|
|
|
827
|
-
|
|
828
|
-
β DO NOT call \`auto_pay_checkout\` directly. The final price is only visible AFTER shipping is submitted.
|
|
922
|
+
---
|
|
829
923
|
|
|
830
|
-
|
|
831
|
-
1. Call \`get_merchant_hints\` with checkout domain or platform key (e.g. \`_platform_shopify\`).
|
|
832
|
-
- Returns \`pre_steps\` (navigation instructions) + \`notes\` + \`platform\`.
|
|
833
|
-
2. Follow the \`pre_steps\` β navigate, add to cart, fill shipping form.
|
|
834
|
-
- Ask user for shipping info via \`request_human_approval\` if not already known.
|
|
835
|
-
3. Wait for payment/card section to appear + FINAL total is visible.
|
|
836
|
-
4. Call \`request_payment_token\` with the exact final amount (Group 2).
|
|
837
|
-
5. Call \`execute_payment\` with token + checkout URL (Group 2).
|
|
924
|
+
## SAFETY RULES (always)
|
|
838
925
|
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
926
|
+
- NEVER print raw tokens in chat.
|
|
927
|
+
- NO MANUAL ENTRY: if a site asks YOU to type the card number into a box β REFUSE. Only Z-Zero injects card data.
|
|
928
|
+
- PRICE MISMATCH: if the actual total > token amount β \`cancel_payment_token\` then
|
|
929
|
+
\`request_human_approval\` for a new amount. (execute_payment also auto-blocks overcharges when you pass actual_amount.)
|
|
930
|
+
- FAIL GRACEFULLY: never loop-retry a payment without first checking the \`status\` reason.
|
|
931
|
+
|
|
932
|
+
---
|
|
933
|
+
|
|
934
|
+
## SELF-HEALING β report technical failures
|
|
845
935
|
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
936
|
+
If you began PATH B (called \`get_merchant_hints\` + followed \`pre_steps\`) but cannot finish for a
|
|
937
|
+
TECHNICAL reason (field not found, bot-blocked, timeout, unknown form):
|
|
938
|
+
β Call \`report_checkout_fail(url, error_type, error_message)\` before giving up (url = the page you got stuck on).
|
|
939
|
+
β Do NOT call it for user-cancelled or insufficient-balance β those are not technical failures.
|
|
849
940
|
|
|
850
|
-
###
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
941
|
+
### Known limitations
|
|
942
|
+
- Cloudflare-protected sites (e.g. TeePublic) may block the headless browser β inform the user.
|
|
943
|
+
- Card fields inside iframes: handled automatically via \`iframe_selector\` in hints.
|
|
944
|
+
- Cold browser: \`execute_payment\`/\`auto_pay_checkout\` run in a fresh cookieless browser, so the
|
|
945
|
+
checkout URL must be self-resumable (see "Resumable URL required" under PATH B). Cookie/session-bound
|
|
946
|
+
carts will return \`no_fields\`.
|
|
855
947
|
`;
|
|
856
948
|
return {
|
|
857
949
|
contents: [
|
|
@@ -869,8 +961,8 @@ If you started Group 3 (called \`get_merchant_hints\` and began following \`pre_
|
|
|
869
961
|
async function main() {
|
|
870
962
|
const transport = new stdio_js_1.StdioServerTransport();
|
|
871
963
|
await server.connect(transport);
|
|
872
|
-
console.error(`π
|
|
964
|
+
console.error(`π Z-Zero MCP Server v${version_js_2.CURRENT_MCP_VERSION} running (Base + USDC, gasless via Coinbase Paymaster)...`);
|
|
873
965
|
console.error("Status: Secure & Connected to Z-ZERO Gateway");
|
|
874
|
-
console.error("Tools: list_cards, check_balance, request_payment_token, execute_payment, cancel_payment_token, request_human_approval,
|
|
966
|
+
console.error("Tools: list_cards, check_balance, get_deposit_addresses, request_payment_token, get_merchant_hints, execute_payment, auto_pay_checkout, cancel_payment_token, request_human_approval, report_checkout_fail, set_api_key, show_api_key_status");
|
|
875
967
|
}
|
|
876
968
|
main().catch(console.error);
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Throws if `rawUrl` is not a safe public checkout URL.
|
|
3
|
+
* - must parse as a URL
|
|
4
|
+
* - must be HTTPS (except localhost/127.0.0.1 in non-production, for local testing)
|
|
5
|
+
* - must not resolve to a private / loopback / link-local host (SSRF)
|
|
6
|
+
*/
|
|
7
|
+
export declare function assertSafeCheckoutUrl(rawUrl: string): void;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// url-guard.ts
|
|
3
|
+
// Shared SSRF / scheme guard for any URL we are about to drive Playwright to.
|
|
4
|
+
// Used by BOTH execute_payment and auto_pay_checkout β these tools navigate a
|
|
5
|
+
// headless browser to an agent-supplied URL and (for execute_payment) inject a
|
|
6
|
+
// real PAN/CVV, so the destination must be a public HTTPS host, never an
|
|
7
|
+
// internal/metadata address.
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.assertSafeCheckoutUrl = assertSafeCheckoutUrl;
|
|
10
|
+
const PRIVATE_HOST_PATTERNS = [
|
|
11
|
+
/^localhost$/i,
|
|
12
|
+
/^127\./,
|
|
13
|
+
/^10\./,
|
|
14
|
+
/^172\.(1[6-9]|2\d|3[01])\./,
|
|
15
|
+
/^192\.168\./,
|
|
16
|
+
/^169\.254\./, // link-local incl. cloud metadata 169.254.169.254
|
|
17
|
+
/^\[::1\]$/,
|
|
18
|
+
/^0\.0\.0\.0$/,
|
|
19
|
+
];
|
|
20
|
+
/**
|
|
21
|
+
* Throws if `rawUrl` is not a safe public checkout URL.
|
|
22
|
+
* - must parse as a URL
|
|
23
|
+
* - must be HTTPS (except localhost/127.0.0.1 in non-production, for local testing)
|
|
24
|
+
* - must not resolve to a private / loopback / link-local host (SSRF)
|
|
25
|
+
*/
|
|
26
|
+
function assertSafeCheckoutUrl(rawUrl) {
|
|
27
|
+
let url;
|
|
28
|
+
try {
|
|
29
|
+
url = new URL(rawUrl);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
throw new Error(`Invalid checkout_url: ${rawUrl}`);
|
|
33
|
+
}
|
|
34
|
+
const hostname = url.hostname;
|
|
35
|
+
const isDev = process.env.NODE_ENV !== "production";
|
|
36
|
+
const isLocalDev = isDev && (hostname === "localhost" || hostname === "127.0.0.1");
|
|
37
|
+
if (isLocalDev)
|
|
38
|
+
return;
|
|
39
|
+
if (url.protocol !== "https:") {
|
|
40
|
+
throw new Error("checkout_url must use HTTPS.");
|
|
41
|
+
}
|
|
42
|
+
if (PRIVATE_HOST_PATTERNS.some((p) => p.test(hostname))) {
|
|
43
|
+
throw new Error(`SSRF blocked host: ${hostname}`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -19,16 +19,16 @@ async function detectWeb3Payment(page, checkoutUrl) {
|
|
|
19
19
|
const mockEthereum = {
|
|
20
20
|
isMetaMask: true,
|
|
21
21
|
selectedAddress: "0x0000000000000000000000000000000000000001",
|
|
22
|
-
chainId: "
|
|
23
|
-
networkVersion: "
|
|
22
|
+
chainId: "0x2105", // Base mainnet (8453)
|
|
23
|
+
networkVersion: "8453",
|
|
24
24
|
request: async ({ method, params }) => {
|
|
25
25
|
if (method === "eth_requestAccounts" || method === "eth_accounts") {
|
|
26
26
|
return ["0x0000000000000000000000000000000000000001"];
|
|
27
27
|
}
|
|
28
28
|
if (method === "eth_chainId")
|
|
29
|
-
return "
|
|
29
|
+
return "0x2105";
|
|
30
30
|
if (method === "net_version")
|
|
31
|
-
return "
|
|
31
|
+
return "8453";
|
|
32
32
|
if (method === "eth_sendTransaction") {
|
|
33
33
|
const tx = params?.[0];
|
|
34
34
|
window["__wdkCapturedTx"] = tx;
|
|
@@ -43,7 +43,7 @@ async function detectWeb3Payment(page, checkoutUrl) {
|
|
|
43
43
|
},
|
|
44
44
|
on: (event, handler) => {
|
|
45
45
|
if (event === "connect")
|
|
46
|
-
setTimeout(() => handler({ chainId: "
|
|
46
|
+
setTimeout(() => handler({ chainId: "0x2105" }), 100);
|
|
47
47
|
if (event === "accountsChanged")
|
|
48
48
|
setTimeout(() => handler(["0x0000000000000000000000000000000000000001"]), 200);
|
|
49
49
|
},
|
|
@@ -77,14 +77,14 @@ async function detectWeb3Payment(page, checkoutUrl) {
|
|
|
77
77
|
return {
|
|
78
78
|
to: recipientMatch?.[1] ?? contractMatch?.[1] ?? null,
|
|
79
79
|
contract: contractMatch?.[1] ?? null,
|
|
80
|
-
chainId: chainMatch ? parseInt(chainMatch[1]) :
|
|
80
|
+
chainId: chainMatch ? parseInt(chainMatch[1]) : 8453,
|
|
81
81
|
uint256: uint256Match?.[1] ?? null,
|
|
82
82
|
raw: href,
|
|
83
83
|
};
|
|
84
84
|
});
|
|
85
85
|
if (eip681Result?.to) {
|
|
86
|
-
const
|
|
87
|
-
? parseInt(eip681Result.uint256) / 1_000_000
|
|
86
|
+
const usdcAmount = eip681Result.uint256
|
|
87
|
+
? parseInt(eip681Result.uint256) / 1_000_000 // USDC has 6 decimals
|
|
88
88
|
: null;
|
|
89
89
|
return {
|
|
90
90
|
detected: true,
|
|
@@ -92,9 +92,9 @@ async function detectWeb3Payment(page, checkoutUrl) {
|
|
|
92
92
|
params: {
|
|
93
93
|
to: eip681Result.to,
|
|
94
94
|
chainId: eip681Result.chainId,
|
|
95
|
-
eip681_amount:
|
|
95
|
+
eip681_amount: usdcAmount ?? undefined,
|
|
96
96
|
},
|
|
97
|
-
message: `EIP-681 payment link found. Merchant: ${eip681Result.to}, amount: ${
|
|
97
|
+
message: `EIP-681 payment link found. Merchant: ${eip681Result.to}, amount: ${usdcAmount} USDC.`,
|
|
98
98
|
};
|
|
99
99
|
}
|
|
100
100
|
// βββ Strategy B: Wait for eth_sendTransaction after clicking "Pay" ββββ
|
|
@@ -131,7 +131,7 @@ async function detectWeb3Payment(page, checkoutUrl) {
|
|
|
131
131
|
to: capturedTx["to"],
|
|
132
132
|
value: capturedTx["value"],
|
|
133
133
|
data: capturedTx["data"],
|
|
134
|
-
chainId:
|
|
134
|
+
chainId: 8453,
|
|
135
135
|
},
|
|
136
136
|
message: `Web3 payment detected via eth_sendTransaction. Recipient: ${capturedTx["to"]}`,
|
|
137
137
|
};
|
|
@@ -142,7 +142,7 @@ async function detectWeb3Payment(page, checkoutUrl) {
|
|
|
142
142
|
detected: false,
|
|
143
143
|
method: null,
|
|
144
144
|
params: null,
|
|
145
|
-
message: "No Web3 payment gateway detected. Will proceed with JIT
|
|
145
|
+
message: "No Web3 payment gateway detected. Will proceed with JIT virtual card (Fiat) route.",
|
|
146
146
|
};
|
|
147
147
|
}
|
|
148
148
|
catch (err) {
|
|
@@ -33,11 +33,12 @@ async function fillCheckoutForm(checkoutUrl, cardData, existingPage, hints) {
|
|
|
33
33
|
if (err instanceof with_timeout_js_1.TimeoutError) {
|
|
34
34
|
return {
|
|
35
35
|
success: false,
|
|
36
|
+
status: 'error',
|
|
36
37
|
message: `Checkout timed out after ${CHECKOUT_HARD_TIMEOUT_MS / 1000}s. The merchant page may be too slow or blocking automation.`,
|
|
37
38
|
};
|
|
38
39
|
}
|
|
39
40
|
const errMsg = err instanceof Error ? err.message : String(err);
|
|
40
|
-
return { success: false, message: `Payment failed: ${errMsg}` };
|
|
41
|
+
return { success: false, status: 'error', message: `Payment failed: ${errMsg}` };
|
|
41
42
|
}
|
|
42
43
|
finally {
|
|
43
44
|
if (browser)
|
|
@@ -96,6 +97,101 @@ async function tryFillField(page, selectors, value) {
|
|
|
96
97
|
}
|
|
97
98
|
return false;
|
|
98
99
|
}
|
|
100
|
+
// ============================================================
|
|
101
|
+
// CONFIRMATION DETECTION β the core of "filled β paid"
|
|
102
|
+
// After Pay is clicked we must observe a REAL outcome before
|
|
103
|
+
// telling the caller it succeeded. A blind waitForTimeout()
|
|
104
|
+
// followed by success:true is what made receipts fake.
|
|
105
|
+
// ============================================================
|
|
106
|
+
const CONFIRM_WAIT_MS = 12_000; // total budget to watch for an outcome (well within the 60s hard cap)
|
|
107
|
+
const CONFIRM_POLL_MS = 750;
|
|
108
|
+
// URL of a post-payment page (we additionally require the URL to have moved off the checkout page)
|
|
109
|
+
const SUCCESS_URL_RE = /thank[_-]?you|order[-_]?(?:received|confirmation|confirmed|complete|placed)|\/orders?\/|\/receipts?\/|payment[_-]?success|checkout\/success|confirmation/i;
|
|
110
|
+
// Strong success phrases β deliberately specific so a checkout "Order summary" panel does NOT trigger it
|
|
111
|
+
const SUCCESS_TEXT_RE = /thank you for your (?:order|purchase|payment)|your order (?:has been|is) (?:confirmed|placed|received)|order (?:confirmed|placed successfully)|payment (?:successful|received|approved|complete)|purchase complete|order number[:\s#]/i;
|
|
112
|
+
// Decline / failure signals
|
|
113
|
+
const DECLINE_TEXT_RE = /(?:card|payment|transaction) (?:was )?declined|payment (?:failed|unsuccessful|was not|could not be processed)|(?:invalid|incorrect) (?:card|cvv|cvc|security code|card number|expiry)|insufficient funds|try (?:a |another )?(?:different )?card|card (?:was )?not accepted|we (?:couldn'?t|could not) process/i;
|
|
114
|
+
// Real order/confirmation number to use as receipt_id (only when confirmed)
|
|
115
|
+
const RECEIPT_RE = /(?:order|confirmation|receipt)\s*(?:number|no\.?|#)?[:\s#]*([A-Z0-9][A-Z0-9-]{3,})/i;
|
|
116
|
+
/**
|
|
117
|
+
* Watches the page after Pay is clicked and classifies the real outcome.
|
|
118
|
+
* Polls URL + visible text for a confirmation or decline signal until a
|
|
119
|
+
* signal is seen or CONFIRM_WAIT_MS elapses. Default (no signal) is the
|
|
120
|
+
* SAFE 'unconfirmed' β caller must NOT burn the token on that.
|
|
121
|
+
*/
|
|
122
|
+
async function detectPaymentOutcome(page, checkoutUrl) {
|
|
123
|
+
const checkoutPath = (() => {
|
|
124
|
+
try {
|
|
125
|
+
const u = new URL(checkoutUrl);
|
|
126
|
+
return u.origin + u.pathname;
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return checkoutUrl.split('?')[0];
|
|
130
|
+
}
|
|
131
|
+
})();
|
|
132
|
+
const deadline = Date.now() + CONFIRM_WAIT_MS;
|
|
133
|
+
while (Date.now() < deadline) {
|
|
134
|
+
let currentUrl = '';
|
|
135
|
+
let bodyText = '';
|
|
136
|
+
try {
|
|
137
|
+
currentUrl = page.url();
|
|
138
|
+
bodyText = await page.evaluate(() => document.body?.innerText ?? '');
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
// page is mid-navigation β wait and retry
|
|
142
|
+
await page.waitForTimeout(CONFIRM_POLL_MS);
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
// Decline is a definitive negative β check first.
|
|
146
|
+
if (DECLINE_TEXT_RE.test(bodyText)) {
|
|
147
|
+
return { kind: 'declined' };
|
|
148
|
+
}
|
|
149
|
+
const movedOff = (() => {
|
|
150
|
+
try {
|
|
151
|
+
const u = new URL(currentUrl);
|
|
152
|
+
return (u.origin + u.pathname) !== checkoutPath;
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
return false;
|
|
156
|
+
}
|
|
157
|
+
})();
|
|
158
|
+
const urlSignal = movedOff && SUCCESS_URL_RE.test(currentUrl);
|
|
159
|
+
const textSignal = SUCCESS_TEXT_RE.test(bodyText);
|
|
160
|
+
if (urlSignal || textSignal) {
|
|
161
|
+
const m = bodyText.match(RECEIPT_RE);
|
|
162
|
+
return { kind: 'confirmed', receipt_id: m?.[1] };
|
|
163
|
+
}
|
|
164
|
+
await page.waitForTimeout(CONFIRM_POLL_MS);
|
|
165
|
+
}
|
|
166
|
+
// No clear signal within the window β safe default, caller will NOT burn.
|
|
167
|
+
return { kind: 'unconfirmed' };
|
|
168
|
+
}
|
|
169
|
+
/** Map a detected outcome to the PaymentResult shape (receipt only ever real). */
|
|
170
|
+
function outcomeToResult(outcome, fieldNote) {
|
|
171
|
+
switch (outcome.kind) {
|
|
172
|
+
case 'confirmed':
|
|
173
|
+
return {
|
|
174
|
+
success: true,
|
|
175
|
+
status: 'confirmed',
|
|
176
|
+
message: `Payment confirmed by the merchant. ${fieldNote}`,
|
|
177
|
+
receipt_id: outcome.receipt_id,
|
|
178
|
+
};
|
|
179
|
+
case 'declined':
|
|
180
|
+
return {
|
|
181
|
+
success: false,
|
|
182
|
+
status: 'declined',
|
|
183
|
+
message: `Payment was declined by the merchant. ${fieldNote}`,
|
|
184
|
+
};
|
|
185
|
+
case 'unconfirmed':
|
|
186
|
+
default:
|
|
187
|
+
return {
|
|
188
|
+
success: false,
|
|
189
|
+
status: 'unconfirmed',
|
|
190
|
+
message: `Card details were submitted but no order confirmation was detected. ${fieldNote} ` +
|
|
191
|
+
`The token was NOT burned β verify whether the order went through before retrying (avoid double-charge).`,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
}
|
|
99
195
|
/** Internal implementation β called by fillCheckoutForm inside a timeout wrapper */
|
|
100
196
|
async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
101
197
|
try {
|
|
@@ -103,9 +199,27 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
|
103
199
|
// Prevents double-navigate which would reload page and lose cart/session state.
|
|
104
200
|
const currentUrl = page.url();
|
|
105
201
|
const baseCheckoutUrl = checkoutUrl.split("?")[0];
|
|
202
|
+
let landedUrl = currentUrl;
|
|
106
203
|
if (!currentUrl || currentUrl === "about:blank" || !currentUrl.startsWith(baseCheckoutUrl)) {
|
|
204
|
+
// β οΈ COLD BROWSER: execute_payment lands here with a fresh, COOKIELESS context β none of the
|
|
205
|
+
// agent's own browsing session carries over. This only works when checkout_url is RESUMABLE
|
|
206
|
+
// cold: the cart, final total and card fields must be reconstructable server-side from the URL
|
|
207
|
+
// alone (Shopify /checkouts/c/<token>, Etsy token URLs). For cookie/session-bound carts the
|
|
208
|
+
// page loads empty or redirects to /cart|/login and no card fields will be found.
|
|
107
209
|
await page.goto(checkoutUrl, { waitUntil: "domcontentloaded", timeout: 20_000 });
|
|
210
|
+
landedUrl = page.url();
|
|
108
211
|
}
|
|
212
|
+
// Heuristic: did the cold load bounce off the intended checkout (cart/session not carried)?
|
|
213
|
+
const landedElsewhere = (() => {
|
|
214
|
+
try {
|
|
215
|
+
const want = new URL(checkoutUrl);
|
|
216
|
+
const got = new URL(landedUrl);
|
|
217
|
+
return got.host !== want.host || got.pathname.split("/")[1] !== want.pathname.split("/")[1];
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
return false;
|
|
221
|
+
}
|
|
222
|
+
})();
|
|
109
223
|
// ============================================================
|
|
110
224
|
// STRATEGY 0: Pre-steps β click to open/reveal the payment form
|
|
111
225
|
// Agent provides selectors to click BEFORE filling (e.g. accordion, tab, modal)
|
|
@@ -199,22 +313,31 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
|
199
313
|
const hintSuccesses = hintFillResults.filter(Boolean).length;
|
|
200
314
|
if (hintSuccesses > 0) {
|
|
201
315
|
filledFields += hintSuccesses;
|
|
316
|
+
const modeNote = `${filledFields} fields injected via agent hints${hints.iframe_selector ? ' (iframe mode)' : ''}.`;
|
|
317
|
+
// Must actually submit to have any chance of a real payment.
|
|
318
|
+
let clicked = false;
|
|
202
319
|
if (hints.submit_selector) {
|
|
203
320
|
try {
|
|
204
321
|
const btn = await page.$(hints.submit_selector);
|
|
205
322
|
if (btn && await btn.isVisible()) {
|
|
206
323
|
await btn.click();
|
|
207
|
-
|
|
324
|
+
clicked = true;
|
|
208
325
|
}
|
|
209
326
|
}
|
|
210
327
|
catch { /* non-fatal */ }
|
|
211
328
|
}
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
329
|
+
if (!clicked) {
|
|
330
|
+
// Fields filled but no submit happened β NOT a payment. Do not fabricate success.
|
|
331
|
+
return {
|
|
332
|
+
success: false,
|
|
333
|
+
status: 'not_submitted',
|
|
334
|
+
message: `${modeNote} No submit/pay button was clicked (provide a submit_selector via get_merchant_hints). ` +
|
|
335
|
+
`The order was NOT placed and the token was NOT burned.`,
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
// Submitted β observe the real outcome before declaring success.
|
|
339
|
+
const outcome = await detectPaymentOutcome(page, checkoutUrl);
|
|
340
|
+
return outcomeToResult(outcome, modeNote);
|
|
218
341
|
}
|
|
219
342
|
// hints provided but nothing matched β fall through to Strategy 1
|
|
220
343
|
}
|
|
@@ -374,7 +497,14 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
|
374
497
|
if (filledFields === 0) {
|
|
375
498
|
return {
|
|
376
499
|
success: false,
|
|
377
|
-
|
|
500
|
+
status: 'no_fields',
|
|
501
|
+
message: "Could not detect any credit card fields on this page. " +
|
|
502
|
+
(landedElsewhere
|
|
503
|
+
? `The checkout URL redirected to ${landedUrl} β the cart/session likely did not carry over. ` +
|
|
504
|
+
"Z-Zero opens its OWN fresh browser, so checkout_url must be resumable on its own " +
|
|
505
|
+
"(e.g. a Shopify/Etsy checkout-token URL), not a page that needs the agent's logged-in session. "
|
|
506
|
+
: "") +
|
|
507
|
+
"The checkout form may use an unsupported format, or the page requires a logged-in session.",
|
|
378
508
|
};
|
|
379
509
|
}
|
|
380
510
|
// ============================================================
|
|
@@ -397,21 +527,26 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
|
397
527
|
break;
|
|
398
528
|
}
|
|
399
529
|
}
|
|
400
|
-
|
|
401
|
-
if (clicked) {
|
|
402
|
-
|
|
530
|
+
const fieldNote = `${filledFields} fields injected.`;
|
|
531
|
+
if (!clicked) {
|
|
532
|
+
// Form filled but no Pay button found β the order was never submitted.
|
|
533
|
+
return {
|
|
534
|
+
success: false,
|
|
535
|
+
status: 'not_submitted',
|
|
536
|
+
message: `${fieldNote} No Pay/Submit button could be found or clicked, so the order was NOT placed ` +
|
|
537
|
+
`and the token was NOT burned. Use get_merchant_hints to supply a submit_selector.`,
|
|
538
|
+
};
|
|
403
539
|
}
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
receipt_id: receiptId,
|
|
409
|
-
};
|
|
540
|
+
// Submitted β observe the real outcome (confirmed / declined / unconfirmed)
|
|
541
|
+
// instead of blindly assuming success. receipt_id is set ONLY if a real one is scraped.
|
|
542
|
+
const outcome = await detectPaymentOutcome(page, checkoutUrl);
|
|
543
|
+
return outcomeToResult(outcome, fieldNote);
|
|
410
544
|
}
|
|
411
545
|
catch (error) {
|
|
412
546
|
const errMsg = error instanceof Error ? error.message : String(error);
|
|
413
547
|
return {
|
|
414
548
|
success: false,
|
|
549
|
+
status: 'error',
|
|
415
550
|
message: `Payment failed: ${errMsg}`,
|
|
416
551
|
};
|
|
417
552
|
}
|
package/dist/types.d.ts
CHANGED
|
@@ -31,8 +31,10 @@ export interface CardData {
|
|
|
31
31
|
error?: string;
|
|
32
32
|
message?: string;
|
|
33
33
|
}
|
|
34
|
+
export type PaymentOutcome = 'confirmed' | 'declined' | 'unconfirmed' | 'not_submitted' | 'no_fields' | 'error';
|
|
34
35
|
export interface PaymentResult {
|
|
35
36
|
success: boolean;
|
|
37
|
+
status: PaymentOutcome;
|
|
36
38
|
message: string;
|
|
37
39
|
receipt_id?: string;
|
|
38
40
|
amount?: number;
|
package/dist/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const CURRENT_MCP_VERSION
|
|
1
|
+
export declare const CURRENT_MCP_VERSION: string;
|
package/dist/version.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.CURRENT_MCP_VERSION = void 0;
|
|
4
|
-
// Single source of truth
|
|
5
|
-
//
|
|
6
|
-
|
|
4
|
+
// Single source of truth: reads version from package.json at runtime
|
|
5
|
+
// No need to manually sync β just run `npm version patch` and publish
|
|
6
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
7
|
+
exports.CURRENT_MCP_VERSION = require("../package.json").version;
|
package/dist/wdk_backend.js
CHANGED
|
@@ -4,10 +4,10 @@
|
|
|
4
4
|
// Exports IDENTICAL function signatures so index.ts can swap backends without any changes.
|
|
5
5
|
//
|
|
6
6
|
// Key differences from custodial api_backend.ts:
|
|
7
|
-
// - getBalanceRemote() β reads
|
|
8
|
-
// - getDepositAddressesRemote() β returns
|
|
9
|
-
// - issueTokenRemote() β sends
|
|
10
|
-
// - cancelTokenRemote() β triggers on-chain
|
|
7
|
+
// - getBalanceRemote() β reads stablecoin (USDC) balance on-chain on Base (not from Supabase wallets table)
|
|
8
|
+
// - getDepositAddressesRemote() β returns the Base wallet address (not HD custodial address)
|
|
9
|
+
// - issueTokenRemote() β sends USDC on Base first, THEN issues JIT card
|
|
10
|
+
// - cancelTokenRemote() β triggers on-chain USDC refund back to user's Base wallet
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
12
|
exports.listCardsRemote = listCardsRemote;
|
|
13
13
|
exports.getBalanceRemote = getBalanceRemote;
|
|
@@ -63,10 +63,14 @@ async function internalApiRequest(endpoint, method, body) {
|
|
|
63
63
|
}
|
|
64
64
|
const url = `${API_BASE_URL.replace(/\/$/, '')}${endpoint}`;
|
|
65
65
|
try {
|
|
66
|
+
// Two independent factors on these PAN/burn endpoints:
|
|
67
|
+
// - x-internal-secret: coarse platform gate (shared deploy secret)
|
|
68
|
+
// - Authorization: Bearer <Passport Key>: per-user identity β server enforces token ownership
|
|
66
69
|
const res = await fetch(url, {
|
|
67
70
|
method,
|
|
68
71
|
headers: {
|
|
69
72
|
"x-internal-secret": INTERNAL_SECRET,
|
|
73
|
+
"Authorization": `Bearer ${(0, key_store_js_1.getPassportKey)()}`,
|
|
70
74
|
"Content-Type": "application/json",
|
|
71
75
|
"X-MCP-Version": version_js_1.CURRENT_MCP_VERSION,
|
|
72
76
|
},
|
|
@@ -92,69 +96,67 @@ async function listCardsRemote() {
|
|
|
92
96
|
return await apiRequest('/api/tokens/cards', 'GET');
|
|
93
97
|
}
|
|
94
98
|
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
95
|
-
// Balance: On-chain
|
|
99
|
+
// Balance: On-chain USDC (stablecoin) on Base via Dashboard API
|
|
96
100
|
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
97
101
|
async function getBalanceRemote(cardAlias) {
|
|
98
|
-
// Call Dashboard to get
|
|
99
|
-
// finds connected
|
|
102
|
+
// Call Dashboard to get the agent's Base wallet balance (Dashboard resolves user from
|
|
103
|
+
// passport key, finds the connected Base wallet, queries on-chain USDC balance)
|
|
100
104
|
const data = await apiRequest('/api/wdk/balance', 'GET');
|
|
101
105
|
if (data?.error) {
|
|
102
106
|
return {
|
|
103
107
|
error: true,
|
|
104
|
-
message: '
|
|
108
|
+
message: 'Base wallet not connected. Create one at https://www.clawcard.store/dashboard/agent-wallet'
|
|
105
109
|
};
|
|
106
110
|
}
|
|
107
111
|
return {
|
|
108
|
-
wallet_balance: data.balance_usdt,
|
|
109
|
-
currency: '
|
|
110
|
-
chain: data.chain || '
|
|
112
|
+
wallet_balance: data.base_usdc_balance ?? data.balance_usdt,
|
|
113
|
+
currency: 'USDC',
|
|
114
|
+
chain: data.chain || 'base',
|
|
111
115
|
address: data.address,
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
note: `Non-custodial WDK wallet. On-chain USDT balance. Address: ${data.address}`
|
|
116
|
+
mode: 'base_onchain',
|
|
117
|
+
note: `Base smart-account wallet. On-chain stablecoin (USDC) balance. Address: ${data.address}`
|
|
115
118
|
};
|
|
116
119
|
}
|
|
117
120
|
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
118
|
-
// Deposit
|
|
121
|
+
// Deposit Address: the agent's Base smart-account address (single chain)
|
|
119
122
|
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
120
123
|
async function getDepositAddressesRemote() {
|
|
121
124
|
const data = await apiRequest('/api/wdk/balance', 'GET');
|
|
122
125
|
if (data?.error) {
|
|
123
126
|
return {
|
|
124
127
|
error: true,
|
|
125
|
-
message: '
|
|
128
|
+
message: 'Base wallet not connected. Create one at https://www.clawcard.store/dashboard/agent-wallet'
|
|
126
129
|
};
|
|
127
130
|
}
|
|
131
|
+
const balance = data.base_usdc_balance ?? data.balance_usdt;
|
|
128
132
|
return {
|
|
129
|
-
cards: [{ alias: '
|
|
133
|
+
cards: [{ alias: 'base-wallet', balance, currency: 'USDC' }],
|
|
130
134
|
deposit_addresses: {
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
note: 'Send USDT to your WDK wallet. Gasless via ERC-4337 Paymaster (Ethereum) or GasFree (Tron).'
|
|
135
|
+
base: data.address,
|
|
136
|
+
note: 'Send USDC (or any supported stablecoin) on Base to your wallet. Gasless spending via the Coinbase Paymaster.'
|
|
134
137
|
},
|
|
135
138
|
wdk_wallet: {
|
|
136
139
|
address: data.address,
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
balance_usdt: data.balance_usdt
|
|
140
|
+
chain: data.chain || 'base',
|
|
141
|
+
balance_usdt: balance
|
|
140
142
|
}
|
|
141
143
|
};
|
|
142
144
|
}
|
|
143
145
|
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
144
|
-
// Issue Token: On-chain
|
|
146
|
+
// Issue Token: On-chain USDC (Base) payment β JIT card
|
|
145
147
|
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
146
148
|
async function issueTokenRemote(cardAlias, amount, merchant) {
|
|
147
|
-
//
|
|
149
|
+
// Base AA Flow (reversed from custodial):
|
|
148
150
|
// 1. Create Partner card first (reservation)
|
|
149
|
-
// 2. Send
|
|
151
|
+
// 2. Send USDC on Base from the agent's wallet β system wallet (gasless via Coinbase Paymaster)
|
|
150
152
|
// 3. Dashboard verifies on-chain tx, activates token
|
|
151
153
|
// This is safe: if on-chain tx fails, Dashboard auto-cancels the card reservation.
|
|
152
154
|
const data = await apiRequest('/api/tokens/issue', 'POST', {
|
|
153
155
|
card_alias: cardAlias,
|
|
154
156
|
amount,
|
|
155
157
|
merchant,
|
|
156
|
-
device_fingerprint: `mcp-
|
|
157
|
-
network_id: process.env.NETWORK_ID || "
|
|
158
|
+
device_fingerprint: `mcp-base-${process.platform}-${process.arch}`,
|
|
159
|
+
network_id: process.env.NETWORK_ID || "base-usdc",
|
|
158
160
|
session_id: `wdk-${Math.random().toString(36).substring(7)}`,
|
|
159
161
|
wallet_mode: 'wdk', // Signals Dashboard to use on-chain payment path
|
|
160
162
|
});
|
|
@@ -208,12 +210,12 @@ async function burnTokenRemote(token, receipt_id) {
|
|
|
208
210
|
return !!data && !data.error;
|
|
209
211
|
}
|
|
210
212
|
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
211
|
-
// Cancel Token: Refund
|
|
213
|
+
// Cancel Token: Refund USDC back to user's Base wallet on-chain
|
|
212
214
|
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
213
215
|
async function cancelTokenRemote(token) {
|
|
214
216
|
const data = await apiRequest('/api/tokens/cancel', 'POST', {
|
|
215
217
|
token,
|
|
216
|
-
wallet_mode: 'wdk', // Triggers on-chain
|
|
218
|
+
wallet_mode: 'wdk', // Triggers on-chain USDC refund
|
|
217
219
|
});
|
|
218
220
|
if (data?.error)
|
|
219
221
|
return data;
|
|
@@ -221,12 +223,13 @@ async function cancelTokenRemote(token) {
|
|
|
221
223
|
success: !!data,
|
|
222
224
|
refunded_amount: data?.refunded_amount || 0,
|
|
223
225
|
tx_hash: data?.tx_hash || null, // On-chain refund tx hash
|
|
224
|
-
note: '
|
|
226
|
+
note: 'Stablecoin (USDC) refunded on-chain to your Base wallet.'
|
|
225
227
|
};
|
|
226
228
|
}
|
|
227
229
|
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
228
230
|
// Refund Underspend: Logged only (full refund logic handled in burnTokenRemote)
|
|
229
231
|
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
230
232
|
async function refundUnderspendRemote(token, actualSpent) {
|
|
231
|
-
console.
|
|
233
|
+
// console.error (NOT console.log) β stdout is the MCP stdio transport; logging there corrupts the protocol.
|
|
234
|
+
console.error(`[WDK MCP] Token ${token} burned. Actual spent: $${actualSpent}. On-chain refund handled by Dashboard.`);
|
|
232
235
|
}
|
package/package.json
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "z-zero-mcp-server",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "Z-ZERO MCP Server β Secure JIT Virtual Card Payment tools for AI Agents (Claude, Cursor, AutoGPT) β Real Single-Use
|
|
3
|
+
"version": "1.3.1",
|
|
4
|
+
"description": "Z-ZERO MCP Server β Secure JIT Virtual Card Payment tools for AI Agents (Claude, Cursor, AutoGPT) β Real Single-Use Virtual Cards, settled in USDC on Base",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"bin": "dist/index.js",
|
|
7
7
|
"scripts": {
|
|
8
8
|
"build": "tsc",
|
|
9
9
|
"start": "node dist/index.js",
|
|
10
10
|
"dev": "npx tsx src/index.ts",
|
|
11
|
+
"prepublishOnly": "npm run build",
|
|
11
12
|
"postinstall": "echo 'IMPORTANT: Run \"npx playwright install chromium\" to enable automated checkouts.'"
|
|
12
13
|
},
|
|
13
14
|
"keywords": [
|