z-zero-mcp-server 1.10.0 → 1.10.2

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/dist/index.js CHANGED
@@ -64,7 +64,7 @@ const playwright_bridge_js_1 = require("./playwright_bridge.js");
64
64
  const ucp_bridge_js_1 = require("./ucp_bridge.js");
65
65
  const web3_detector_js_1 = require("./lib/web3-detector.js");
66
66
  const extract_total_price_js_1 = require("./lib/extract-total-price.js");
67
- const playwright_1 = require("playwright");
67
+ const browser_js_1 = require("./lib/browser.js");
68
68
  const key_store_js_1 = require("./lib/key-store.js"); // ✅ Hot-Swap + rotate-on-connect
69
69
  const url_guard_js_1 = require("./lib/url-guard.js");
70
70
  const api_base_js_1 = require("./lib/api-base.js");
@@ -990,22 +990,41 @@ server.registerTool("set_api_key", {
990
990
  isError: true,
991
991
  };
992
992
  }
993
- // Step 3: Swap key in RAM (old key is soft-revoked — just forgotten)
994
- const result = (0, key_store_js_1.setPassportKey)(trimmed);
995
- if (!result.ok) {
996
- return {
997
- content: [{ type: "text", text: `❌ ${result.message}` }],
998
- isError: true,
999
- };
1000
- }
1001
- // Step 4: ROTATE-ON-CONNECT (v1.5.0). The key the user just pasted has
1002
- // been through the LLM conversation → treat it as burned. Swap it for a
1003
- // fresh key that NEVER enters the chat: server → this process → disk.
993
+ // Step 3: ROTATE-ON-CONNECT (v1.5.0), FAIL-CLOSED (v1.11, W2a).
994
+ // The key the user just pasted has been through the LLM conversation →
995
+ // treat it as burned. Ask the server to swap it for a fresh key that
996
+ // NEVER enters the chat: server → this process → disk.
997
+ //
998
+ // Nothing is activated until the server has answered. Before W2a the
999
+ // pasted key was put in RAM first and a failed/lost rotate still returned
1000
+ // SUCCESS — the process then ran on a key that had been in the chat while
1001
+ // claiming it had not. Now: rotate fails → the previous key stays active
1002
+ // and the caller gets the real error.
1003
+ //
1004
1004
  // Side effect by design: connecting a second machine with a copied key
1005
1005
  // rotates it and disconnects the first one ("one key = one agent").
1006
- let rotated = false;
1006
+ const previousHint = maskKey((0, key_store_js_1.getPassportKey)());
1007
+ // remote_status tells the agent what the SERVER side looks like:
1008
+ // UNKNOWN — the request may have reached the server; the pasted key may
1009
+ // already be dead and its replacement lost with the reply.
1010
+ // REJECTED — the server refused the pasted key; nothing happened.
1011
+ // ERROR — the server answered but could not rotate; nothing happened.
1012
+ const failClosed = (remote, why, next) => ({
1013
+ content: [{
1014
+ type: "text",
1015
+ text: JSON.stringify({
1016
+ status: "NOT_SWITCHED",
1017
+ remote_status: remote,
1018
+ message: `❌ Key rotation did not complete: ${why}`,
1019
+ active_key_hint: previousHint,
1020
+ note: `Your previous key is still active — nothing changed. ${next}`,
1021
+ }, null, 2),
1022
+ }],
1023
+ isError: true,
1024
+ });
1025
+ let rotateResp;
1007
1026
  try {
1008
- const rotateResp = await fetch(`${ZZERO_API}/api/keys/rotate`, {
1027
+ rotateResp = await fetch(`${ZZERO_API}/api/keys/rotate`, {
1009
1028
  method: "POST",
1010
1029
  headers: {
1011
1030
  "Authorization": `Bearer ${trimmed}`,
@@ -1013,39 +1032,43 @@ server.registerTool("set_api_key", {
1013
1032
  },
1014
1033
  signal: AbortSignal.timeout(8000),
1015
1034
  });
1016
- if (rotateResp.ok) {
1017
- const rotateData = await rotateResp.json();
1018
- const newKey = typeof rotateData?.new_key === "string" ? rotateData.new_key : "";
1019
- if (newKey.startsWith("zk_live_") || newKey.startsWith("zk_test_")) {
1020
- // Persist FIRST, then activate — if the disk write fails we
1021
- // keep using the (already-rotated) key in RAM and warn.
1022
- const persisted = (0, key_store_js_1.persistPassportKey)(newKey);
1023
- (0, key_store_js_1.setPassportKey)(newKey);
1024
- rotated = true;
1025
- if (!persisted) {
1026
- console.error("[SET-KEY] ⚠️ Rotated key active in RAM but NOT persisted — re-connect with a fresh key from the dashboard after restart.");
1027
- }
1028
- }
1029
- }
1030
- // Non-OK (404 = server not yet deployed, 429, 5xx) → keep pasted key, no rotation. Backward compatible.
1031
1035
  }
1032
- catch {
1033
- // Network error → keep pasted key. Backward compatible.
1036
+ catch (err) {
1037
+ // The request may or may not have reached the server. If it did, the
1038
+ // pasted key is already dead and the fresh one is lost with the reply.
1039
+ return failClosed("UNKNOWN", `could not reach the server (${err?.message || "timeout"}).`, "Retry set_api_key with the same key. If the server then rejects it, the rotation went through and its reply was lost — get a fresh key from https://z-zero.xyz/dashboard/agents.");
1040
+ }
1041
+ if (rotateResp.status === 401) {
1042
+ return failClosed("REJECTED", "the server rejected the pasted key (already rotated on another machine, or revoked).", "Get a fresh key from https://z-zero.xyz/dashboard/agents.");
1043
+ }
1044
+ if (!rotateResp.ok) {
1045
+ return failClosed("ERROR", `the server returned ${rotateResp.status}.`, rotateResp.status === 429 ? "Wait a minute, then retry set_api_key with the same key." : "Retry set_api_key with the same key in a moment.");
1046
+ }
1047
+ const rotateData = await rotateResp.json().catch(() => null);
1048
+ const newKey = typeof rotateData?.new_key === "string" ? rotateData.new_key : "";
1049
+ if (!newKey.startsWith("zk_live_") && !newKey.startsWith("zk_test_")) {
1050
+ return failClosed("ERROR", "the server answered without a usable key.", "Retry set_api_key with the same key in a moment.");
1051
+ }
1052
+ // Step 4: Persist FIRST, then activate. Only now does the identity change.
1053
+ const persisted = (0, key_store_js_1.persistPassportKey)(newKey);
1054
+ const activated = (0, key_store_js_1.setPassportKey)(newKey);
1055
+ if (!activated.ok) {
1056
+ return failClosed("ERROR", `the fresh key could not be activated (${activated.message}).`, "Get a fresh key from https://z-zero.xyz/dashboard/agents.");
1057
+ }
1058
+ if (!persisted) {
1059
+ console.error("[SET-KEY] ⚠️ Rotated key active in RAM but NOT persisted — re-connect with a fresh key from the dashboard after restart.");
1034
1060
  }
1035
1061
  return {
1036
1062
  content: [{
1037
1063
  type: "text",
1038
1064
  text: JSON.stringify({
1039
1065
  status: "SUCCESS",
1040
- message: rotated
1041
- ? "✅ Connected. For security, the key you pasted was immediately replaced with a fresh one stored locally (~/.z-zero/credentials) — the pasted key is now dead everywhere, including this conversation."
1042
- : `✅ ${result.message}`,
1066
+ message: "✅ Connected. For security, the key you pasted was immediately replaced with a fresh one stored locally (~/.z-zero/credentials) — the pasted key is now dead everywhere, including this conversation.",
1043
1067
  // Masked hint only — never echo a usable portion of the secret to the chat/model context.
1044
1068
  active_key_hint: maskKey((0, key_store_js_1.getPassportKey)()),
1045
- rotated_on_connect: rotated,
1046
- note: rotated
1047
- ? "One key = one agent: connecting another agent/machine with this account's key will disconnect this one."
1048
- : "All subsequent API calls will use this key. Previous key removed from this session (soft revoke).",
1069
+ rotated_on_connect: true,
1070
+ ...(persisted ? {} : { persist_warning: "The fresh key is active in memory but could not be written to ~/.z-zero/credentials — after a restart, get a fresh key from the dashboard." }),
1071
+ note: "One key = one agent: connecting another agent/machine with this account's key will disconnect this one.",
1049
1072
  }, null, 2),
1050
1073
  }],
1051
1074
  };
@@ -1116,7 +1139,7 @@ server.registerTool("auto_pay_checkout", {
1116
1139
  // ── SSRF guard (shared helper) ───────────────────────────────
1117
1140
  (0, url_guard_js_1.assertSafeCheckoutUrl)(checkout_url);
1118
1141
  // ── Single Browser Instance for efficiency ──────────────────
1119
- const browser = await playwright_1.chromium.launch({ headless: true });
1142
+ const browser = await (0, browser_js_1.launchBrowser)();
1120
1143
  const context = await browser.newContext();
1121
1144
  const page = await context.newPage();
1122
1145
  try {
@@ -1600,6 +1623,7 @@ server.prompt("wallet_status", "Summarize the Z-ZERO wallet: card aliases, spend
1600
1623
  async function main() {
1601
1624
  const transport = new stdio_js_1.StdioServerTransport();
1602
1625
  await server.connect(transport);
1626
+ (0, browser_js_1.warmUpBrowser)();
1603
1627
  console.error(`🔐 Z-Zero MCP Server v${version_js_2.CURRENT_MCP_VERSION} running (Base + USDC, gasless via Coinbase Paymaster)...`);
1604
1628
  console.error("Status: Secure & Connected to Z-ZERO Gateway");
1605
1629
  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, ucp_probe_checkout, verify_receipt, set_api_key, show_api_key_status");
@@ -0,0 +1,19 @@
1
+ /**
2
+ * lib/browser.ts
3
+ * Launches the headless Chromium the "Invisible Hand" fills checkouts with.
4
+ *
5
+ * `playwright` ships no install script (and we keep none — Socket score), so a
6
+ * fresh `npx` install has NO browser: the first purchase used to die with
7
+ * "Executable doesn't exist". Launch order now:
8
+ * 1. Playwright's headless shell, if already downloaded
9
+ * 2. the user's installed Google Chrome (no download needed)
10
+ * 3. one-time download of the headless shell into Playwright's cache, then retry
11
+ * `warmUpBrowser()` starts that download in the background at server start, so
12
+ * it is normally finished long before the first checkout.
13
+ */
14
+ import { type Browser } from "playwright";
15
+ /** Runs `playwright install --only-shell chromium`. Idempotent (~0.3s when already installed). */
16
+ export declare function ensureBrowserInstalled(): Promise<void>;
17
+ /** Background pre-download at server start. Never throws. */
18
+ export declare function warmUpBrowser(): void;
19
+ export declare function launchBrowser(): Promise<Browser>;
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ /**
3
+ * lib/browser.ts
4
+ * Launches the headless Chromium the "Invisible Hand" fills checkouts with.
5
+ *
6
+ * `playwright` ships no install script (and we keep none — Socket score), so a
7
+ * fresh `npx` install has NO browser: the first purchase used to die with
8
+ * "Executable doesn't exist". Launch order now:
9
+ * 1. Playwright's headless shell, if already downloaded
10
+ * 2. the user's installed Google Chrome (no download needed)
11
+ * 3. one-time download of the headless shell into Playwright's cache, then retry
12
+ * `warmUpBrowser()` starts that download in the background at server start, so
13
+ * it is normally finished long before the first checkout.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.ensureBrowserInstalled = ensureBrowserInstalled;
17
+ exports.warmUpBrowser = warmUpBrowser;
18
+ exports.launchBrowser = launchBrowser;
19
+ const playwright_1 = require("playwright");
20
+ const node_child_process_1 = require("node:child_process");
21
+ const node_path_1 = require("node:path");
22
+ const INSTALL_TIMEOUT_MS = 5 * 60_000; // ~100MB download on a slow line
23
+ let installing = null;
24
+ function isMissingBrowser(err) {
25
+ return err instanceof Error && /Executable doesn't exist|browserType\.launch: .*not found/i.test(err.message);
26
+ }
27
+ /** Runs `playwright install --only-shell chromium`. Idempotent (~0.3s when already installed). */
28
+ function ensureBrowserInstalled() {
29
+ if (installing)
30
+ return installing;
31
+ installing = new Promise((resolve, reject) => {
32
+ const cli = (0, node_path_1.join)((0, node_path_1.dirname)(require.resolve("playwright/package.json")), "cli.js");
33
+ // stdout must stay clean — it carries the MCP JSON-RPC stream.
34
+ const child = (0, node_child_process_1.spawn)(process.execPath, [cli, "install", "--only-shell", "chromium"], {
35
+ stdio: ["ignore", "pipe", "pipe"],
36
+ });
37
+ let tail = "";
38
+ const keep = (chunk) => { tail = (tail + chunk.toString()).slice(-2000); };
39
+ child.stdout.on("data", keep);
40
+ child.stderr.on("data", keep);
41
+ const timer = setTimeout(() => child.kill(), INSTALL_TIMEOUT_MS);
42
+ child.on("error", (err) => { clearTimeout(timer); reject(err); });
43
+ child.on("close", (code) => {
44
+ clearTimeout(timer);
45
+ if (code === 0)
46
+ resolve();
47
+ else
48
+ reject(new Error(`Browser download failed (exit ${code}): ${tail.trim().split("\n").slice(-3).join(" | ")}`));
49
+ });
50
+ }).catch((err) => {
51
+ installing = null; // let the next call retry
52
+ throw err;
53
+ });
54
+ return installing;
55
+ }
56
+ /** Background pre-download at server start. Never throws. */
57
+ function warmUpBrowser() {
58
+ ensureBrowserInstalled()
59
+ .then(() => console.error("[BROWSER] Checkout browser ready"))
60
+ .catch((err) => console.error(`[BROWSER] ⚠️ Pre-download failed, will retry at checkout: ${err.message}`));
61
+ }
62
+ async function launchBrowser() {
63
+ try {
64
+ return await playwright_1.chromium.launch({ headless: true });
65
+ }
66
+ catch (err) {
67
+ if (!isMissingBrowser(err))
68
+ throw err;
69
+ }
70
+ try {
71
+ return await playwright_1.chromium.launch({ headless: true, channel: "chrome" });
72
+ }
73
+ catch {
74
+ // no system Chrome either — fall through to the download
75
+ }
76
+ console.error("[BROWSER] No browser found — downloading headless Chromium (one-time, ~100MB)...");
77
+ await ensureBrowserInstalled();
78
+ return playwright_1.chromium.launch({ headless: true });
79
+ }
@@ -0,0 +1,32 @@
1
+ import type { PaymentToken, CardData } from "./types.js";
2
+ /**
3
+ * Issue a temporary payment token for a specific card and amount.
4
+ * Token is valid for `ttlSeconds` (default: 900 = 15 minutes).
5
+ */
6
+ export declare function issueToken(cardAlias: string, amount: number, merchant: string, ttlSeconds?: number): PaymentToken | null;
7
+ /**
8
+ * Resolve a token to real card data.
9
+ * CRITICAL: The returned CardData object lives ONLY in RAM.
10
+ * It must NEVER be logged, serialized, or returned to the AI.
11
+ */
12
+ export declare function resolveToken(tokenId: string): CardData | null;
13
+ /**
14
+ * Burn a token after use - makes it permanently invalid.
15
+ * Also deducts the amount from the card balance.
16
+ */
17
+ export declare function burnToken(tokenId: string): boolean;
18
+ /**
19
+ * Check balance of a card (safe to expose to AI).
20
+ */
21
+ export declare function getBalance(cardAlias: string): {
22
+ balance: number;
23
+ currency: string;
24
+ } | null;
25
+ /**
26
+ * List available card aliases (safe to expose to AI - no sensitive data).
27
+ */
28
+ export declare function listCards(): Array<{
29
+ alias: string;
30
+ balance: number;
31
+ currency: string;
32
+ }>;
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ // Mock Neobank Backend - Simulates the card vault and token issuing system
3
+ // In production, this would be replaced by your real Neobank API
4
+ var __importDefault = (this && this.__importDefault) || function (mod) {
5
+ return (mod && mod.__esModule) ? mod : { "default": mod };
6
+ };
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.issueToken = issueToken;
9
+ exports.resolveToken = resolveToken;
10
+ exports.burnToken = burnToken;
11
+ exports.getBalance = getBalance;
12
+ exports.listCards = listCards;
13
+ const crypto_1 = __importDefault(require("crypto"));
14
+ // ============================================================
15
+ // CARD VAULT (In-memory store - simulates encrypted database)
16
+ // ============================================================
17
+ const cardVault = new Map([
18
+ [
19
+ "Card_01",
20
+ {
21
+ alias: "Card_01",
22
+ number: "4242424242424242", // Stripe test card
23
+ exp_month: "12",
24
+ exp_year: "2030",
25
+ cvv: "123",
26
+ name: "AI Agent Card 01",
27
+ balance: 50.0,
28
+ currency: "USD",
29
+ },
30
+ ],
31
+ [
32
+ "Card_02",
33
+ {
34
+ alias: "Card_02",
35
+ number: "5555555555554444", // Mastercard test
36
+ exp_month: "06",
37
+ exp_year: "2029",
38
+ cvv: "456",
39
+ name: "AI Agent Card 02",
40
+ balance: 100.0,
41
+ currency: "USD",
42
+ },
43
+ ],
44
+ ]);
45
+ // ============================================================
46
+ // TOKEN STORE (Active JIT tokens)
47
+ // ============================================================
48
+ const tokenStore = new Map();
49
+ // ============================================================
50
+ // PUBLIC API
51
+ // ============================================================
52
+ /**
53
+ * Issue a temporary payment token for a specific card and amount.
54
+ * Token is valid for `ttlSeconds` (default: 900 = 15 minutes).
55
+ */
56
+ function issueToken(cardAlias, amount, merchant, ttlSeconds = 900) {
57
+ const card = cardVault.get(cardAlias);
58
+ if (!card) {
59
+ return null;
60
+ }
61
+ if (card.balance < amount) {
62
+ return null;
63
+ }
64
+ const token = {
65
+ token: `temp_auth_${crypto_1.default.randomBytes(4).toString("hex")}`,
66
+ card_alias: cardAlias,
67
+ amount,
68
+ merchant,
69
+ created_at: Date.now(),
70
+ ttl_seconds: ttlSeconds,
71
+ used: false,
72
+ };
73
+ tokenStore.set(token.token, token);
74
+ return token;
75
+ }
76
+ /**
77
+ * Resolve a token to real card data.
78
+ * CRITICAL: The returned CardData object lives ONLY in RAM.
79
+ * It must NEVER be logged, serialized, or returned to the AI.
80
+ */
81
+ function resolveToken(tokenId) {
82
+ const token = tokenStore.get(tokenId);
83
+ if (!token) {
84
+ return null; // Token doesn't exist
85
+ }
86
+ if (token.used) {
87
+ return null; // Already burned
88
+ }
89
+ // Check TTL expiration
90
+ const age = (Date.now() - token.created_at) / 1000;
91
+ if (age > token.ttl_seconds) {
92
+ tokenStore.delete(tokenId); // Expired, clean up
93
+ return null;
94
+ }
95
+ const card = cardVault.get(token.card_alias);
96
+ if (!card) {
97
+ return null;
98
+ }
99
+ // Return card data (RAM only - never log this!)
100
+ return {
101
+ number: card.number,
102
+ exp_month: card.exp_month,
103
+ exp_year: card.exp_year,
104
+ cvv: card.cvv,
105
+ name: card.name,
106
+ };
107
+ }
108
+ /**
109
+ * Burn a token after use - makes it permanently invalid.
110
+ * Also deducts the amount from the card balance.
111
+ */
112
+ function burnToken(tokenId) {
113
+ const token = tokenStore.get(tokenId);
114
+ if (!token)
115
+ return false;
116
+ token.used = true;
117
+ // Deduct balance
118
+ const card = cardVault.get(token.card_alias);
119
+ if (card) {
120
+ card.balance -= token.amount;
121
+ }
122
+ // Schedule complete removal from memory
123
+ setTimeout(() => {
124
+ tokenStore.delete(tokenId);
125
+ }, 5000);
126
+ return true;
127
+ }
128
+ /**
129
+ * Check balance of a card (safe to expose to AI).
130
+ */
131
+ function getBalance(cardAlias) {
132
+ const card = cardVault.get(cardAlias);
133
+ if (!card)
134
+ return null;
135
+ return { balance: card.balance, currency: card.currency };
136
+ }
137
+ /**
138
+ * List available card aliases (safe to expose to AI - no sensitive data).
139
+ */
140
+ function listCards() {
141
+ const result = [];
142
+ for (const card of cardVault.values()) {
143
+ result.push({
144
+ alias: card.alias,
145
+ balance: card.balance,
146
+ currency: card.currency,
147
+ });
148
+ }
149
+ return result;
150
+ }
@@ -3,8 +3,8 @@
3
3
  // Securely injects card data into checkout forms without exposing it to AI
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.fillCheckoutForm = fillCheckoutForm;
6
- const playwright_1 = require("playwright");
7
6
  const with_timeout_js_1 = require("./lib/with-timeout.js");
7
+ const browser_js_1 = require("./lib/browser.js");
8
8
  const CHECKOUT_HARD_TIMEOUT_MS = 60_000; // 60s absolute cap — prevents slow-loris attacks
9
9
  /**
10
10
  * Detects and fills credit card form fields on a checkout page.
@@ -18,7 +18,7 @@ async function fillCheckoutForm(checkoutUrl, cardData, existingPage, hints) {
18
18
  page = existingPage;
19
19
  }
20
20
  else {
21
- browser = await playwright_1.chromium.launch({ headless: true });
21
+ browser = await (0, browser_js_1.launchBrowser)();
22
22
  const context = await browser.newContext();
23
23
  page = await context.newPage();
24
24
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "z-zero-mcp-server",
3
- "version": "1.10.0",
3
+ "version": "1.10.2",
4
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": {