z-zero-mcp-server 1.10.4 → 1.11.0

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.
@@ -1,10 +1,17 @@
1
1
  /**
2
- * Persist the key to ~/.z-zero/credentials with owner-only permissions.
3
- * Returns true on success. Failure is non-fatal (key still lives in memory).
2
+ * Persist the key with owner-only permissions, noting which config key (if any)
3
+ * was in place when it was written. Returns true on success. Failure is
4
+ * non-fatal (key still lives in memory).
4
5
  */
5
6
  export declare function persistPassportKey(key: string): boolean;
7
+ type KeySource = "file" | "env" | "set_api_key" | "none";
6
8
  /** Read the current active Passport Key. */
7
9
  export declare function getPassportKey(): string;
10
+ /** Where the active key came from, and whether it still has to be rotated. */
11
+ export declare function keyStatus(): {
12
+ source: KeySource;
13
+ rotation_pending: boolean;
14
+ };
8
15
  /**
9
16
  * Replace the active Passport Key in memory (no restart needed).
10
17
  * @param newKey - must start with "zk_live_" or "zk_test_"
@@ -16,3 +23,19 @@ export declare function setPassportKey(newKey: string): {
16
23
  };
17
24
  /** Check if a key is currently configured. */
18
25
  export declare function hasPassportKey(): boolean;
26
+ /**
27
+ * Make sure a key that came in through the config has been traded for a fresh
28
+ * one. Called at server start and before every authenticated request; does
29
+ * nothing once done. A network failure leaves it pending and the next request
30
+ * tries again (the config key keeps working meanwhile — it is only dead once
31
+ * the server has swapped it).
32
+ */
33
+ export declare function ensureKeyReady(): Promise<void>;
34
+ /**
35
+ * The stored key was just rejected (401). If the config holds a different key
36
+ * that has not been tried, switch to it (and rotate it). Returns true when the
37
+ * caller should retry once. Handles credentials files written before 1.11,
38
+ * which do not record which config key they replaced (audit T14 F3).
39
+ */
40
+ export declare function recoverFromRejectedKey(): Promise<boolean>;
41
+ export {};
@@ -1,62 +1,118 @@
1
1
  "use strict";
2
2
  // key-store.ts
3
- // Shared, mutable in-memory store for the Passport Key (Z_ZERO_API_KEY).
3
+ // Shared, mutable in-memory store for the Passport Key.
4
4
  // All API backends import getPassportKey() from here
5
5
  // so a single set_api_key MCP tool updates the key for ALL backends at once.
6
6
  //
7
- // v1.5.0: keys are also persisted to ~/.z-zero/credentials (chmod 600).
8
- // Load priority: credentials file > Z_ZERO_API_KEY env. The file exists
9
- // because rotate-on-connect swaps the pasted key for a fresh one that must
10
- // survive restarts WITHOUT ever entering the LLM conversation or the
11
- // claude_desktop_config.json.
7
+ // Rotate-on-connect, for EVERY way a key arrives (audit T14 F1, M.4):
8
+ // the key a person copies from the dashboard is a one-time ticket. Pasted into
9
+ // a chat (set_api_key) or written into the MCP config as Z_ZERO_API_KEY by the
10
+ // agent, it has been through an LLM conversation. So the first time this server
11
+ // uses it, it trades it for a fresh key (POST /api/keys/rotate) and keeps the
12
+ // fresh one in a local file, chmod 600. The copy in the chat or the config is
13
+ // dead from then on. Before 1.11 only set_api_key did this; a key that came in
14
+ // through the config file — the path most install tabs use — never rotated.
15
+ //
16
+ // The credentials file remembers WHICH config key it replaced (a SHA-256 of it,
17
+ // never the key). A different Z_ZERO_API_KEY in the config later means the user
18
+ // put a new key there on purpose: that one wins and is rotated in turn. Before,
19
+ // an old file silently beat any new key in the config (audit T14 F3).
20
+ //
21
+ // One file per API host (lib/api-base.ts): the z-zero.xyz key is never read
22
+ // when requests go to a custom server (audit T14 F2, M.5).
12
23
  //
13
24
  // Thread-safety: Node.js is single-threaded. Module-level `let` is safe.
14
25
  Object.defineProperty(exports, "__esModule", { value: true });
15
26
  exports.persistPassportKey = persistPassportKey;
16
27
  exports.getPassportKey = getPassportKey;
28
+ exports.keyStatus = keyStatus;
17
29
  exports.setPassportKey = setPassportKey;
18
30
  exports.hasPassportKey = hasPassportKey;
31
+ exports.ensureKeyReady = ensureKeyReady;
32
+ exports.recoverFromRejectedKey = recoverFromRejectedKey;
19
33
  const fs_1 = require("fs");
20
34
  const path_1 = require("path");
21
35
  const os_1 = require("os");
36
+ const crypto_1 = require("crypto");
37
+ const api_base_js_1 = require("./api-base.js");
38
+ const version_js_1 = require("../version.js");
22
39
  const CRED_DIR = (0, path_1.join)((0, os_1.homedir)(), ".z-zero");
23
- const CRED_FILE = (0, path_1.join)(CRED_DIR, "credentials");
24
- /** Read the persisted key from ~/.z-zero/credentials (null if absent/invalid). */
25
- function loadPersistedKey() {
40
+ /** ~/.z-zero/credentials for z-zero.xyz; credentials-<host_port> for anything else. */
41
+ function credFile() {
42
+ const base = (0, api_base_js_1.resolveApiBaseUrl)();
43
+ if (base === api_base_js_1.CANONICAL_API)
44
+ return (0, path_1.join)(CRED_DIR, "credentials");
45
+ const u = new URL(base);
46
+ return (0, path_1.join)(CRED_DIR, `credentials-${(u.host).replace(/[^a-zA-Z0-9.-]/g, "_")}`);
47
+ }
48
+ const looksLikeKey = (k) => k.startsWith("zk_live_") || k.startsWith("zk_test_");
49
+ const sha256 = (s) => (0, crypto_1.createHash)("sha256").update(s).digest("hex");
50
+ function readCred() {
26
51
  try {
27
- const raw = (0, fs_1.readFileSync)(CRED_FILE, "utf8");
28
- const parsed = JSON.parse(raw);
52
+ const parsed = JSON.parse((0, fs_1.readFileSync)(credFile(), "utf8"));
29
53
  const key = typeof parsed?.passport_key === "string" ? parsed.passport_key.trim() : "";
30
- if (key.startsWith("zk_live_") || key.startsWith("zk_test_"))
31
- return key;
32
- return null;
54
+ if (!looksLikeKey(key))
55
+ return null;
56
+ const from = typeof parsed?.from_env_sha256 === "string" ? parsed.from_env_sha256
57
+ : ("from_env_sha256" in (parsed ?? {}) ? null : undefined);
58
+ return { passport_key: key, from_env_sha256: from };
33
59
  }
34
60
  catch {
35
- return null; // no file yet, or unreadable — fall back to env
61
+ return null; // no file yet, or unreadable
36
62
  }
37
63
  }
64
+ function envKey() {
65
+ const k = (process.env.Z_ZERO_API_KEY || "").trim();
66
+ return looksLikeKey(k) ? k : "";
67
+ }
38
68
  /**
39
- * Persist the key to ~/.z-zero/credentials with owner-only permissions.
40
- * Returns true on success. Failure is non-fatal (key still lives in memory).
69
+ * Persist the key with owner-only permissions, noting which config key (if any)
70
+ * was in place when it was written. Returns true on success. Failure is
71
+ * non-fatal (key still lives in memory).
41
72
  */
42
73
  function persistPassportKey(key) {
43
74
  try {
44
75
  (0, fs_1.mkdirSync)(CRED_DIR, { recursive: true, mode: 0o700 });
45
- (0, fs_1.writeFileSync)(CRED_FILE, JSON.stringify({ passport_key: key }) + "\n", { mode: 0o600 });
46
- (0, fs_1.chmodSync)(CRED_FILE, 0o600); // enforce even if file pre-existed with looser mode
76
+ const env = envKey();
77
+ const body = { passport_key: key, from_env_sha256: env ? sha256(env) : null };
78
+ (0, fs_1.writeFileSync)(credFile(), JSON.stringify(body) + "\n", { mode: 0o600 });
79
+ (0, fs_1.chmodSync)(credFile(), 0o600); // enforce even if file pre-existed with looser mode
47
80
  return true;
48
81
  }
49
82
  catch (err) {
50
- console.error(`[KEY-STORE] ⚠️ Could not persist key to ${CRED_FILE}: ${err?.message || err}`);
83
+ console.error(`[KEY-STORE] ⚠️ Could not persist key to ${credFile()}: ${err?.message || err}`);
51
84
  return false;
52
85
  }
53
86
  }
54
- // Load priority: persisted (post-rotation) key wins over the bootstrap env key.
55
- let _passportKey = loadPersistedKey() || process.env.Z_ZERO_API_KEY || "";
87
+ let _passportKey = "";
88
+ let _source = "none";
89
+ /** The active key came from the config and has not been traded for a fresh one yet. */
90
+ let _envRotationPending = false;
91
+ /** A dead file key may fall back to the config key once. */
92
+ let _envFallbackTried = false;
93
+ (function loadInitialKey() {
94
+ const cred = readCred();
95
+ const env = envKey();
96
+ const envIsNew = !!env && env !== cred?.passport_key &&
97
+ (!cred || (cred.from_env_sha256 !== undefined && cred.from_env_sha256 !== sha256(env)));
98
+ if (envIsNew) {
99
+ _passportKey = env;
100
+ _source = "env";
101
+ _envRotationPending = true;
102
+ }
103
+ else if (cred) {
104
+ _passportKey = cred.passport_key;
105
+ _source = "file";
106
+ }
107
+ })();
56
108
  /** Read the current active Passport Key. */
57
109
  function getPassportKey() {
58
110
  return _passportKey;
59
111
  }
112
+ /** Where the active key came from, and whether it still has to be rotated. */
113
+ function keyStatus() {
114
+ return { source: _source, rotation_pending: _envRotationPending };
115
+ }
60
116
  /**
61
117
  * Replace the active Passport Key in memory (no restart needed).
62
118
  * @param newKey - must start with "zk_live_" or "zk_test_"
@@ -67,15 +123,109 @@ function setPassportKey(newKey) {
67
123
  if (!trimmed) {
68
124
  return { ok: false, message: "Key cannot be empty." };
69
125
  }
70
- if (!trimmed.startsWith("zk_live_") && !trimmed.startsWith("zk_test_")) {
71
- return { ok: false, message: `Invalid key format — must start with "zk_live_" or "zk_test_". Got: "${trimmed.slice(0, 12)}..."` };
126
+ if (!looksLikeKey(trimmed)) {
127
+ return { ok: false, message: `Invalid key format — must start with "zk_live_" or "zk_test_".` };
72
128
  }
73
129
  _passportKey = trimmed;
130
+ _source = "set_api_key";
131
+ _envRotationPending = false;
74
132
  // ✅ FIX 11: Don't log partial key — even 10 chars helps brute-force
75
133
  console.error(`[KEY-STORE] ✅ Passport Key updated successfully.`);
76
- return { ok: true, message: `Passport Key updated successfully. Active key prefix: ${trimmed.slice(0, 10)}...` };
134
+ return { ok: true, message: "Passport Key updated successfully." };
77
135
  }
78
136
  /** Check if a key is currently configured. */
79
137
  function hasPassportKey() {
80
138
  return _passportKey.length > 0;
81
139
  }
140
+ let _rotating = null;
141
+ /**
142
+ * Make sure a key that came in through the config has been traded for a fresh
143
+ * one. Called at server start and before every authenticated request; does
144
+ * nothing once done. A network failure leaves it pending and the next request
145
+ * tries again (the config key keeps working meanwhile — it is only dead once
146
+ * the server has swapped it).
147
+ */
148
+ async function ensureKeyReady() {
149
+ if (!_envRotationPending)
150
+ return;
151
+ if (!_rotating)
152
+ _rotating = rotateConfigKey().finally(() => { _rotating = null; });
153
+ await _rotating;
154
+ }
155
+ async function rotateConfigKey() {
156
+ const configKey = _passportKey;
157
+ let resp;
158
+ try {
159
+ resp = await fetch(`${(0, api_base_js_1.resolveApiBaseUrl)()}/api/keys/rotate`, {
160
+ method: "POST",
161
+ headers: { "Authorization": `Bearer ${configKey}`, "x-mcp-version": version_js_1.CURRENT_MCP_VERSION },
162
+ redirect: "manual",
163
+ signal: AbortSignal.timeout(8000),
164
+ });
165
+ }
166
+ catch (err) {
167
+ console.error(`[KEY-STORE] ⚠️ Could not rotate the config key yet (${err?.message || "network"}); will retry on the next call.`);
168
+ return;
169
+ }
170
+ if (resp.ok) {
171
+ const data = await resp.json().catch(() => null);
172
+ const fresh = typeof data?.new_key === "string" ? data.new_key : "";
173
+ if (!looksLikeKey(fresh))
174
+ return; // malformed answer: stay pending, retry later
175
+ const persisted = persistPassportKey(fresh);
176
+ _passportKey = fresh;
177
+ _source = "file";
178
+ _envRotationPending = false;
179
+ console.error(`[KEY-STORE] ✅ The key from your MCP config was swapped for a fresh one ` +
180
+ (persisted ? `(stored in ${credFile()}). ` : `(NOT stored — could not write ${credFile()}; after a restart, get a new key from the dashboard). `) +
181
+ `The copy in the config and in any chat is now dead.`);
182
+ return;
183
+ }
184
+ if (resp.status === 401 || resp.status === 409) {
185
+ // The config key is already dead: another process on this machine rotated
186
+ // it a moment ago (two MCP clients starting together), or it was revoked.
187
+ // Take what is in the credentials file, if anything.
188
+ _envRotationPending = false;
189
+ let cred = readCred();
190
+ if (!cred || cred.passport_key === configKey) {
191
+ await new Promise((r) => setTimeout(r, 1500));
192
+ cred = readCred();
193
+ }
194
+ if (cred && cred.passport_key !== configKey) {
195
+ _passportKey = cred.passport_key;
196
+ _source = "file";
197
+ console.error("[KEY-STORE] The config key was already rotated — using the stored key.");
198
+ }
199
+ else {
200
+ console.error("[KEY-STORE] ⚠️ The key in your MCP config was rejected (revoked, or already used on another machine). Get a fresh key from https://z-zero.xyz/dashboard/agents.");
201
+ }
202
+ return;
203
+ }
204
+ if (resp.status === 404) {
205
+ // A self-hosted server without the rotate endpoint: keep the config key as before.
206
+ _envRotationPending = false;
207
+ console.error("[KEY-STORE] This server has no key-rotation endpoint; the key from your MCP config stays as it is.");
208
+ return;
209
+ }
210
+ // 429 / 5xx: stay pending, retry on the next call.
211
+ console.error(`[KEY-STORE] ⚠️ Key rotation answered ${resp.status}; will retry on the next call.`);
212
+ }
213
+ /**
214
+ * The stored key was just rejected (401). If the config holds a different key
215
+ * that has not been tried, switch to it (and rotate it). Returns true when the
216
+ * caller should retry once. Handles credentials files written before 1.11,
217
+ * which do not record which config key they replaced (audit T14 F3).
218
+ */
219
+ async function recoverFromRejectedKey() {
220
+ if (_source !== "file" || _envFallbackTried)
221
+ return false;
222
+ const env = envKey();
223
+ if (!env || env === _passportKey)
224
+ return false;
225
+ _envFallbackTried = true;
226
+ _passportKey = env;
227
+ _source = "env";
228
+ _envRotationPending = true;
229
+ await ensureKeyReady();
230
+ return true;
231
+ }
@@ -96,7 +96,7 @@ function assertSafeCheckoutUrl(rawUrl) {
96
96
  catch {
97
97
  throw new Error(`Invalid checkout_url: ${rawUrl}`);
98
98
  }
99
- const hostname = url.hostname;
99
+ const hostname = url.hostname.toLowerCase();
100
100
  // Loopback checkout targets are an EXPLICIT opt-in, never a side effect of
101
101
  // NODE_ENV. This server runs on the end user's machine, where NODE_ENV is
102
102
  // essentially never "production" — so keying the bypass off that flag left it
@@ -117,6 +117,17 @@ function assertSafeCheckoutUrl(rawUrl) {
117
117
  if (url.protocol !== "https:") {
118
118
  throw new Error("checkout_url must use HTTPS.");
119
119
  }
120
+ // A store's checkout is on the default port. Another port on the same host is
121
+ // another program, not the store (audit T11 F6).
122
+ if (url.port !== "") {
123
+ throw new Error(`checkout_url must use the default HTTPS port (got :${url.port}).`);
124
+ }
125
+ // Chromium sends every *.localhost name (and "localhost.") to this machine
126
+ // itself, whatever DNS says (audit T11 F3 / T19).
127
+ const bareName = hostname.replace(/\.$/, "");
128
+ if (bareName === "localhost" || bareName.endsWith(".localhost")) {
129
+ throw new Error(`SSRF blocked host: ${hostname}`);
130
+ }
120
131
  if (PRIVATE_HOST_PATTERNS.some((p) => p.test(hostname))) {
121
132
  throw new Error(`SSRF blocked host: ${hostname}`);
122
133
  }
@@ -1,7 +1,15 @@
1
1
  import type { CardData, PaymentResult, CheckoutHints } from "./types.js";
2
+ type Page = import("playwright").Page;
2
3
  /**
3
4
  * Detects and fills credit card form fields on a checkout page.
4
5
  * Card data exists ONLY in RAM and is wiped after injection.
5
6
  * Hard timeout of 60s prevents merchant page from hanging indefinitely.
7
+ *
8
+ * Nothing this function returns may carry the card (audit T12 F3, M.1): a
9
+ * Playwright error quotes the value it was filling (`fill("4242…")`), and a page
10
+ * can echo the number back as its "order number". Every string leaving here goes
11
+ * through finish(), which strips this card's own number and CVV, then every
12
+ * other card-shaped number.
6
13
  */
7
- export declare function fillCheckoutForm(checkoutUrl: string, cardData: CardData, existingPage?: import("playwright").Page, hints?: CheckoutHints): Promise<PaymentResult>;
14
+ export declare function fillCheckoutForm(checkoutUrl: string, cardData: CardData, existingPage?: Page, hints?: CheckoutHints): Promise<PaymentResult>;
15
+ export {};