z-zero-mcp-server 1.8.0 → 1.10.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.
@@ -0,0 +1,886 @@
1
+ "use strict";
2
+ // UCP Bridge — the "Official Rail"
3
+ // Pays Shopify (and any UCP-compliant) checkouts through the Universal Commerce
4
+ // Protocol instead of browser automation. Shopify's platform-wide robots policy
5
+ // ("Checkouts are for humans... no scripted form fills, browser automation")
6
+ // makes this the ONLY sanctioned lane on Shopify stores — the card is submitted
7
+ // as a structured UCP payment instrument to the merchant's declared
8
+ // dev.shopify.card handler, never typed into a DOM form.
9
+ //
10
+ // Same security contract as playwright_bridge: CardData lives only in RAM inside
11
+ // this module, is wiped after submission, and NEVER enters LLM context.
12
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ var desc = Object.getOwnPropertyDescriptor(m, k);
15
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16
+ desc = { enumerable: true, get: function() { return m[k]; } };
17
+ }
18
+ Object.defineProperty(o, k2, desc);
19
+ }) : (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k;
21
+ o[k2] = m[k];
22
+ }));
23
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
24
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
25
+ }) : function(o, v) {
26
+ o["default"] = v;
27
+ });
28
+ var __importStar = (this && this.__importStar) || (function () {
29
+ var ownKeys = function(o) {
30
+ ownKeys = Object.getOwnPropertyNames || function (o) {
31
+ var ar = [];
32
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
33
+ return ar;
34
+ };
35
+ return ownKeys(o);
36
+ };
37
+ return function (mod) {
38
+ if (mod && mod.__esModule) return mod;
39
+ var result = {};
40
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
41
+ __setModuleDefault(result, mod);
42
+ return result;
43
+ };
44
+ })();
45
+ Object.defineProperty(exports, "__esModule", { value: true });
46
+ exports.__ucpInternals = exports.UcpMcpClient = void 0;
47
+ exports.makePinnedLookup = makePinnedLookup;
48
+ exports.planRedirect = planRedirect;
49
+ exports.pinnedRequest = pinnedRequest;
50
+ exports.minorUnitExponent = minorUnitExponent;
51
+ exports.minorToMajor = minorToMajor;
52
+ exports.ucpDiscover = ucpDiscover;
53
+ exports.ucpCreateCheckout = ucpCreateCheckout;
54
+ exports.ucpGetCheckout = ucpGetCheckout;
55
+ exports.ucpPayCheckout = ucpPayCheckout;
56
+ const with_timeout_js_1 = require("./lib/with-timeout.js");
57
+ const url_guard_js_1 = require("./lib/url-guard.js");
58
+ const node_dns_1 = require("node:dns");
59
+ const node_net_1 = require("node:net");
60
+ const https = __importStar(require("node:https"));
61
+ const UCP_HARD_TIMEOUT_MS = 45_000;
62
+ const FETCH_TIMEOUT_MS = 15_000;
63
+ const MAX_REDIRECTS = 3;
64
+ // ============================================================
65
+ // SSRF guard for every URL this module touches: the agent-supplied
66
+ // shop URL, every redirect hop during discovery, AND the MCP endpoint
67
+ // the merchant's document points at (a hostile .well-known/ucp could
68
+ // otherwise steer us to localhost / LAN / cloud metadata).
69
+ // ============================================================
70
+ function assertSafeUcpUrl(rawUrl, what) {
71
+ try {
72
+ (0, url_guard_js_1.assertSafeCheckoutUrl)(rawUrl);
73
+ // The UCP lane never talks to loopback — no local opt-in here, unlike the Playwright lane.
74
+ const host = new URL(rawUrl).hostname;
75
+ const bare = host.replace(/^\[|\]$/g, "");
76
+ // Hostnames are vetted at resolve time (resolvePublic); only IP LITERALS are judged here.
77
+ if (/^localhost$/i.test(host) || ((0, node_net_1.isIP)(bare) && isPrivateIp(bare)))
78
+ throw new Error(`SSRF blocked host: ${host}`);
79
+ }
80
+ catch (err) {
81
+ throw new Error(`UCP ${what} rejected: ${err?.message ?? err}`);
82
+ }
83
+ }
84
+ /** Expand any IPv6 literal (::, zone id, embedded dotted IPv4) to 8 numeric groups; null if malformed. */
85
+ function expandIpv6(ip) {
86
+ let str = ip.toLowerCase().split("%")[0];
87
+ const dotted = str.match(/^(.*:)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
88
+ if (dotted) {
89
+ const v4 = dotted[2].split(".").map(Number);
90
+ if (v4.some((n) => n > 255))
91
+ return null;
92
+ str = dotted[1] + ((v4[0] << 8) | v4[1]).toString(16) + ":" + ((v4[2] << 8) | v4[3]).toString(16);
93
+ }
94
+ const halves = str.split("::");
95
+ if (halves.length > 2)
96
+ return null;
97
+ const head = halves[0] ? halves[0].split(":") : [];
98
+ const tail = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
99
+ const fill = halves.length === 2 ? 8 - head.length - tail.length : 0;
100
+ if (fill < 0 || (halves.length === 1 && head.length !== 8))
101
+ return null;
102
+ const groups = [...head, ...new Array(fill).fill("0"), ...tail].map((g) => (/^[0-9a-f]{1,4}$/.test(g) ? parseInt(g, 16) : NaN));
103
+ if (groups.length !== 8 || groups.some((n) => Number.isNaN(n)))
104
+ return null;
105
+ return groups;
106
+ }
107
+ /**
108
+ * RFC1918 / loopback / link-local / CGNAT / multicast / unspecified for IPv4;
109
+ * for IPv6: ::/96 (unspecified, loopback, deprecated IPv4-compatible), IPv4-mapped
110
+ * ::ffff:0:0/96 in ANY spelling (dotted or hex — "::ffff:7f00:1" IS 127.0.0.1),
111
+ * NAT64 64:ff9b::/96, ULA fc00::/7, link-local fe80::/10, site-local fec0::/10,
112
+ * multicast ff00::/8. Unparseable literals are treated as unsafe.
113
+ */
114
+ function isPrivateIp(ip) {
115
+ const v = (0, node_net_1.isIP)(ip);
116
+ if (v === 4) {
117
+ const [a, b] = ip.split(".").map(Number);
118
+ return a === 0 || a === 10 || a === 127 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31)
119
+ || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224;
120
+ }
121
+ if (v === 6) {
122
+ const g = expandIpv6(ip);
123
+ if (!g)
124
+ return true;
125
+ const v4 = (hi, lo) => `${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`;
126
+ const zero5 = g[0] === 0 && g[1] === 0 && g[2] === 0 && g[3] === 0 && g[4] === 0;
127
+ if (zero5 && g[5] === 0xffff)
128
+ return isPrivateIp(v4(g[6], g[7])); // IPv4-mapped, any spelling
129
+ if (zero5 && g[5] === 0)
130
+ return true; // ::, ::1, ::a.b.c.d
131
+ if (g[0] === 0x64 && g[1] === 0xff9b && g[2] === 0 && g[3] === 0 && g[4] === 0 && g[5] === 0) {
132
+ return isPrivateIp(v4(g[6], g[7])); // NAT64
133
+ }
134
+ if ((g[0] & 0xfe00) === 0xfc00)
135
+ return true; // ULA fc00::/7
136
+ if ((g[0] & 0xffc0) === 0xfe80)
137
+ return true; // link-local
138
+ if ((g[0] & 0xffc0) === 0xfec0)
139
+ return true; // site-local (deprecated)
140
+ if ((g[0] & 0xff00) === 0xff00)
141
+ return true; // multicast
142
+ return false;
143
+ }
144
+ return true; // not an IP literal at all → caller must not treat as safe
145
+ }
146
+ /**
147
+ * Resolve the host, reject if ANY address is private, and RETURN the vetted
148
+ * addresses so the socket can be pinned to them. Resolving here and letting the
149
+ * HTTP client resolve again would be a DNS-rebinding hole (review 14/08).
150
+ */
151
+ async function resolvePublic(rawUrl, what) {
152
+ const host = new URL(rawUrl).hostname.replace(/^\[|\]$/g, "");
153
+ const lit = (0, node_net_1.isIP)(host);
154
+ if (lit) {
155
+ if (isPrivateIp(host))
156
+ throw new Error(`UCP ${what} rejected: SSRF blocked IP ${host}`);
157
+ return [{ address: host, family: lit }];
158
+ }
159
+ let addrs;
160
+ try {
161
+ addrs = await node_dns_1.promises.lookup(host, { all: true });
162
+ }
163
+ catch (err) {
164
+ throw new Error(`UCP ${what} rejected: DNS lookup failed for ${host} (${err?.code ?? err?.message})`);
165
+ }
166
+ if (!addrs.length)
167
+ throw new Error(`UCP ${what} rejected: ${host} did not resolve`);
168
+ const bad = addrs.find((a) => isPrivateIp(a.address));
169
+ if (bad)
170
+ throw new Error(`UCP ${what} rejected: ${host} resolves to private address ${bad.address}`);
171
+ return addrs;
172
+ }
173
+ /** Lookup override that ignores the hostname and returns ONLY the pre-vetted addresses. */
174
+ function makePinnedLookup(addrs) {
175
+ return (_hostname, options, callback) => {
176
+ const cb = typeof options === "function" ? options : callback;
177
+ const opts = typeof options === "function" ? {} : (options ?? {});
178
+ if (opts.all)
179
+ return cb(null, addrs.map((a) => ({ address: a.address, family: a.family })));
180
+ return cb(null, addrs[0].address, addrs[0].family);
181
+ };
182
+ }
183
+ /**
184
+ * Redirect policy (pure, unit-tested):
185
+ * - non-GET requests NEVER follow redirects (an MCP POST must land where discovery said);
186
+ * - cross-origin GET redirects are followed but credential-bearing headers are stripped.
187
+ */
188
+ function planRedirect(current, location, init) {
189
+ const next = new URL(location, current).toString();
190
+ const method = (init.method ?? "GET").toUpperCase();
191
+ const from = new URL(current).origin;
192
+ const to = new URL(next).origin;
193
+ if (method !== "GET")
194
+ throw new Error(`redirect refused for ${method} (${from} → ${to})`);
195
+ const headers = { ...(init.headers ?? {}) };
196
+ if (from !== to) {
197
+ for (const k of Object.keys(headers)) {
198
+ if (/^(authorization|mcp-session-id|cookie|proxy-authorization)$/i.test(k))
199
+ delete headers[k];
200
+ }
201
+ }
202
+ return { next, headers };
203
+ }
204
+ const MAX_BODY_BYTES = 5 * 1024 * 1024; // 5 MB — a UCP document/checkout is a few KB
205
+ /**
206
+ * One request whose TCP connection is pinned to the vetted addresses (SNI/Host stay the hostname).
207
+ * Guards against slow-loris (absolute deadline → destroy) and response bombs (body cap → destroy).
208
+ */
209
+ function pinnedRequest(url, init, addrs, opts = {}) {
210
+ const u = new URL(url);
211
+ const deadlineMs = opts.deadlineMs ?? FETCH_TIMEOUT_MS;
212
+ const maxBody = opts.maxBodyBytes ?? MAX_BODY_BYTES;
213
+ const requestFn = opts.requestFn ?? https.request;
214
+ return new Promise((resolve, reject) => {
215
+ let settled = false;
216
+ const fail = (err) => { if (!settled) {
217
+ settled = true;
218
+ clearTimeout(deadline);
219
+ reject(err);
220
+ } };
221
+ const done = (r) => { if (!settled) {
222
+ settled = true;
223
+ clearTimeout(deadline);
224
+ resolve(r);
225
+ } };
226
+ const req = requestFn({
227
+ protocol: u.protocol,
228
+ host: u.hostname,
229
+ servername: u.protocol === "https:" ? u.hostname : undefined,
230
+ port: u.port ? Number(u.port) : (u.protocol === "https:" ? 443 : 80),
231
+ path: u.pathname + u.search,
232
+ method: init.method ?? "GET",
233
+ headers: init.headers ?? {},
234
+ lookup: makePinnedLookup(addrs),
235
+ timeout: deadlineMs, // idle guard; the absolute deadline below is the real cap
236
+ }, (res) => {
237
+ const chunks = [];
238
+ let received = 0;
239
+ res.on("data", (c) => {
240
+ received += c.length;
241
+ if (received > maxBody) {
242
+ res.destroy();
243
+ req.destroy();
244
+ fail(new Error(`response exceeded ${maxBody} bytes`));
245
+ return;
246
+ }
247
+ chunks.push(c);
248
+ });
249
+ res.on("error", fail);
250
+ res.on("end", () => {
251
+ if (settled)
252
+ return;
253
+ const body = Buffer.concat(chunks).toString("utf8");
254
+ const status = res.statusCode ?? 0;
255
+ done({
256
+ status,
257
+ ok: status >= 200 && status < 300,
258
+ headers: {
259
+ get: (name) => {
260
+ const v = res.headers[name.toLowerCase()];
261
+ return Array.isArray(v) ? v.join(", ") : (v ?? null);
262
+ },
263
+ },
264
+ text: async () => body,
265
+ json: async () => JSON.parse(body),
266
+ });
267
+ });
268
+ });
269
+ const deadline = setTimeout(() => {
270
+ req.destroy();
271
+ fail(new Error(`deadline exceeded after ${deadlineMs}ms`));
272
+ }, deadlineMs);
273
+ req.on("timeout", () => { req.destroy(); fail(new Error(`idle timeout after ${deadlineMs}ms`)); });
274
+ req.on("error", fail);
275
+ if (init.body)
276
+ req.write(init.body);
277
+ req.end();
278
+ });
279
+ }
280
+ const DEFAULT_USER_AGENT = "z-zero-mcp-ucp-bridge";
281
+ async function safeFetch(url, init = {}, what = "url") {
282
+ let current = url;
283
+ let headers = { ...(init.headers ?? {}) };
284
+ // Always identify as a declared agent. Shopify answers 403 to UA-less requests,
285
+ // and never spoofing a human browser is a hard-coded discipline of this bridge.
286
+ if (!Object.keys(headers).some((k) => k.toLowerCase() === "user-agent"))
287
+ headers["User-Agent"] = DEFAULT_USER_AGENT;
288
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
289
+ assertSafeUcpUrl(current, what);
290
+ const addrs = await resolvePublic(current, what);
291
+ const res = await pinnedRequest(current, { ...init, headers }, addrs);
292
+ if (res.status >= 300 && res.status < 400) {
293
+ const loc = res.headers.get("location");
294
+ if (!loc)
295
+ return res;
296
+ const plan = planRedirect(current, loc, { method: init.method, headers });
297
+ current = plan.next;
298
+ headers = plan.headers;
299
+ continue;
300
+ }
301
+ return res;
302
+ }
303
+ throw new Error(`UCP ${what}: too many redirects (>${MAX_REDIRECTS})`);
304
+ }
305
+ // ISO 4217 minor-unit exponent from the runtime's currency data (CLF/UYW=4,
306
+ // KWD=3, VND/JPY=0, USD=2 …). Unknown/invalid codes fall back to 2.
307
+ function minorUnitExponent(currency) {
308
+ const c = (currency ?? "").toUpperCase();
309
+ if (!/^[A-Z]{3}$/.test(c))
310
+ return 2;
311
+ try {
312
+ const d = new Intl.NumberFormat("en", { style: "currency", currency: c }).resolvedOptions().maximumFractionDigits;
313
+ return typeof d === "number" ? d : 2;
314
+ }
315
+ catch {
316
+ return 2;
317
+ }
318
+ }
319
+ function minorToMajor(minor, currency) {
320
+ if (minor == null)
321
+ return null;
322
+ return minor / Math.pow(10, minorUnitExponent(currency));
323
+ }
324
+ /**
325
+ * Fetches and parses a merchant's UCP discovery document.
326
+ * Returns null when the merchant does not speak UCP (→ caller falls back to Playwright).
327
+ * Throws only on SSRF rejection (never silently "fall back" past a blocked host).
328
+ */
329
+ async function ucpDiscover(merchantUrl) {
330
+ let origin;
331
+ try {
332
+ origin = new URL(merchantUrl).origin;
333
+ }
334
+ catch {
335
+ return null;
336
+ }
337
+ assertSafeUcpUrl(origin, "shop_url");
338
+ let doc;
339
+ try {
340
+ const res = await safeFetch(`${origin}/.well-known/ucp`, { headers: { Accept: "application/json" } }, "discovery");
341
+ if (!res.ok) {
342
+ if (res.status !== 404)
343
+ console.error(`[UCP] discovery ${origin} → HTTP ${res.status}`);
344
+ return null;
345
+ }
346
+ doc = await res.json();
347
+ }
348
+ catch (err) {
349
+ if (/rejected|redirects/.test(String(err?.message)))
350
+ throw err;
351
+ console.error(`[UCP] discovery failed for ${origin}: ${err?.message ?? err}`);
352
+ return null;
353
+ }
354
+ const ucp = doc?.ucp;
355
+ if (!ucp || typeof ucp !== "object")
356
+ return null;
357
+ // MCP endpoint from services (dev.ucp.shopping, transport "mcp")
358
+ let mcpEndpoint = null;
359
+ const services = ucp.services ?? {};
360
+ for (const entries of Object.values(services)) {
361
+ if (!Array.isArray(entries))
362
+ continue;
363
+ const mcp = entries.find((e) => e?.transport === "mcp" && typeof e?.endpoint === "string");
364
+ if (mcp) {
365
+ mcpEndpoint = mcp.endpoint;
366
+ break;
367
+ }
368
+ }
369
+ if (!mcpEndpoint)
370
+ return null;
371
+ // The merchant document is untrusted input — its endpoint must pass the same guard.
372
+ assertSafeUcpUrl(mcpEndpoint, "mcp endpoint (from merchant discovery)");
373
+ const handlers = [];
374
+ const handlerMap = ucp.payment_handlers ?? {};
375
+ for (const [handler_name, entries] of Object.entries(handlerMap)) {
376
+ if (!Array.isArray(entries))
377
+ continue;
378
+ for (const e of entries) {
379
+ handlers.push({
380
+ handler_name,
381
+ id: String(e?.id ?? handler_name),
382
+ version: String(e?.version ?? ""),
383
+ config: e?.config ?? {},
384
+ });
385
+ }
386
+ }
387
+ return {
388
+ version: String(ucp.version ?? ""),
389
+ mcpEndpoint,
390
+ handlers,
391
+ cardHandler: handlers.find((h) => h.handler_name === "dev.shopify.card") ?? null,
392
+ raw: ucp,
393
+ };
394
+ }
395
+ // ============================================================
396
+ // Minimal MCP client — JSON-RPC 2.0 over Streamable HTTP
397
+ // Stateless-first (spec 2026-07-28); falls back to initialize
398
+ // handshake if the server demands it. Accepts JSON and SSE replies.
399
+ // ============================================================
400
+ // Agent profile sent in meta["ucp-agent"] for capability negotiation.
401
+ // TODO(z-zero): host our own profile at https://z-zero.xyz/.well-known/ucp-agent.json
402
+ // and switch the default — Shopify's published example profile is used until then.
403
+ const DEFAULT_AGENT_PROFILE = process.env.UCP_AGENT_PROFILE ??
404
+ "https://shopify.dev/ucp/agent-profiles/examples/2026-04-08/valid-with-capabilities.json";
405
+ class UcpMcpClient {
406
+ endpoint;
407
+ opts;
408
+ nextId = 1;
409
+ sessionId = null;
410
+ initialized = false;
411
+ constructor(endpoint, opts = {}) {
412
+ this.endpoint = endpoint;
413
+ this.opts = opts;
414
+ assertSafeUcpUrl(endpoint, "mcp endpoint");
415
+ }
416
+ headers() {
417
+ const h = {
418
+ "Content-Type": "application/json",
419
+ Accept: "application/json, text/event-stream",
420
+ // Declared agent — never spoof a human browser (hard-coded discipline).
421
+ "User-Agent": this.opts.userAgent ?? "z-zero-mcp-ucp-bridge",
422
+ };
423
+ if (this.opts.bearerToken)
424
+ h.Authorization = `Bearer ${this.opts.bearerToken}`;
425
+ if (this.sessionId)
426
+ h["Mcp-Session-Id"] = this.sessionId;
427
+ return h;
428
+ }
429
+ async rpc(method, params) {
430
+ const body = JSON.stringify({ jsonrpc: "2.0", id: this.nextId++, method, params });
431
+ const res = await safeFetch(this.endpoint, { method: "POST", headers: this.headers(), body }, "mcp call");
432
+ const sid = res.headers.get("mcp-session-id");
433
+ if (sid)
434
+ this.sessionId = sid;
435
+ const ctype = res.headers.get("content-type") ?? "";
436
+ let payload = null;
437
+ if (ctype.includes("text/event-stream")) {
438
+ // Collect the last JSON-RPC response object in the SSE stream.
439
+ const text = await res.text();
440
+ for (const line of text.split("\n")) {
441
+ const trimmed = line.trim();
442
+ if (trimmed.startsWith("data:")) {
443
+ try {
444
+ const parsed = JSON.parse(trimmed.slice(5).trim());
445
+ if (parsed && (parsed.result !== undefined || parsed.error !== undefined))
446
+ payload = parsed;
447
+ }
448
+ catch { /* keep scanning */ }
449
+ }
450
+ }
451
+ }
452
+ else {
453
+ try {
454
+ payload = await res.json();
455
+ }
456
+ catch {
457
+ payload = null;
458
+ }
459
+ }
460
+ if (!res.ok && !payload) {
461
+ throw new Error(`UCP MCP HTTP ${res.status} on ${method}`);
462
+ }
463
+ if (payload?.error) {
464
+ const err = new Error(`UCP MCP error ${payload.error.code}: ${payload.error.message}`);
465
+ err.rpcCode = payload.error.code;
466
+ err.rpcData = payload.error.data;
467
+ throw err;
468
+ }
469
+ return payload?.result;
470
+ }
471
+ async ensureInitialized() {
472
+ if (this.initialized)
473
+ return;
474
+ try {
475
+ await this.rpc("initialize", {
476
+ protocolVersion: "2026-07-28",
477
+ capabilities: {},
478
+ clientInfo: { name: "z-zero-ucp-bridge", version: "1.0.0" },
479
+ });
480
+ // Best-effort — notification has no id and some stateless servers reject it.
481
+ await safeFetch(this.endpoint, {
482
+ method: "POST",
483
+ headers: this.headers(),
484
+ body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }),
485
+ }).catch(() => { });
486
+ }
487
+ catch {
488
+ // Stateless servers may not implement initialize at all — that's fine.
489
+ }
490
+ this.initialized = true;
491
+ }
492
+ /** Calls a UCP tool. Retries once through the initialize handshake on "not initialized" errors. */
493
+ async callTool(name, args) {
494
+ // Inject the agent profile into meta unless the caller already set one.
495
+ const m = (args.meta ?? {});
496
+ if (!m["ucp-agent"]) {
497
+ m["ucp-agent"] = { profile: this.opts.agentProfile ?? DEFAULT_AGENT_PROFILE };
498
+ }
499
+ args = { ...args, meta: m };
500
+ const doCall = () => this.rpc("tools/call", { name, arguments: args });
501
+ try {
502
+ return this.unwrap(await doCall());
503
+ }
504
+ catch (err) {
505
+ const msg = String(err?.message ?? "");
506
+ if (err?.rpcCode === -32002 || /initializ/i.test(msg)) {
507
+ await this.ensureInitialized();
508
+ return this.unwrap(await doCall());
509
+ }
510
+ // Anonymous tier has tight rate limits — back off once before giving up.
511
+ if (err?.rpcCode === -32000 || /rate limit/i.test(msg)) {
512
+ await new Promise((r) => setTimeout(r, 2_500));
513
+ return this.unwrap(await doCall());
514
+ }
515
+ throw err;
516
+ }
517
+ }
518
+ /**
519
+ * MCP tool results wrap payloads in content blocks; UCP puts JSON in structuredContent
520
+ * or a text block. Shopify marks results isError even when the payload is a perfectly
521
+ * valid checkout resource in a recoverable state (e.g. delivery_address_required) —
522
+ * so a parseable UCP resource is RETURNED, never thrown; only opaque errors throw.
523
+ */
524
+ unwrap(result) {
525
+ if (result == null)
526
+ return result;
527
+ let payload;
528
+ if (result.structuredContent !== undefined)
529
+ payload = result.structuredContent;
530
+ else if (Array.isArray(result.content)) {
531
+ const textBlock = result.content.find((c) => c?.type === "text" && typeof c.text === "string");
532
+ if (textBlock) {
533
+ try {
534
+ payload = JSON.parse(textBlock.text);
535
+ }
536
+ catch {
537
+ payload = textBlock.text;
538
+ }
539
+ }
540
+ }
541
+ if (result.isError) {
542
+ const isUcpResource = payload && typeof payload === "object" && (payload.id || payload.status || payload.ucp);
543
+ if (isUcpResource)
544
+ return payload;
545
+ const text = typeof payload === "string" ? payload : JSON.stringify(payload ?? result);
546
+ throw new Error(`UCP tool error: ${text}`);
547
+ }
548
+ return payload ?? result;
549
+ }
550
+ }
551
+ exports.UcpMcpClient = UcpMcpClient;
552
+ const uuid = () => globalThis.crypto.randomUUID();
553
+ /** Standard UCP meta block sent with every call. */
554
+ function meta(extra) {
555
+ return { ...extra };
556
+ }
557
+ function pickMoney(obj, keys) {
558
+ for (const k of keys) {
559
+ const v = obj?.[k];
560
+ if (v == null)
561
+ continue;
562
+ if (typeof v === "number")
563
+ return { amount: v, currency: obj?.currency ?? null };
564
+ if (typeof v === "object") {
565
+ const amount = Number(v.amount ?? v.value ?? NaN);
566
+ if (!Number.isNaN(amount))
567
+ return { amount, currency: v.currency ?? v.currency_code ?? null };
568
+ }
569
+ const parsed = Number(v);
570
+ if (!Number.isNaN(parsed))
571
+ return { amount: parsed, currency: obj?.currency ?? null };
572
+ }
573
+ return { amount: null, currency: null };
574
+ }
575
+ function summarizeCheckout(checkout) {
576
+ const c = checkout?.checkout ?? checkout ?? {};
577
+ // Shopify shape: totals = [{type:"total", amount, display_text}, ...]; amounts in the
578
+ // currency's MINOR units for decimal currencies, whole units for zero-decimal (VND, JPY).
579
+ let amount = null;
580
+ let currency = c.currency ?? null;
581
+ if (Array.isArray(c.totals)) {
582
+ const totalRow = c.totals.find((t) => t?.type === "total") ?? c.totals[c.totals.length - 1];
583
+ if (totalRow && totalRow.amount != null)
584
+ amount = Number(totalRow.amount);
585
+ }
586
+ else {
587
+ const money = pickMoney(c.totals ?? c.total ?? c.cost ?? c, ["total", "grand_total", "total_amount", "amount"]);
588
+ amount = money.amount;
589
+ currency = currency ?? money.currency;
590
+ }
591
+ const messages = [];
592
+ for (const m of c.messages ?? []) {
593
+ if (typeof m === "string")
594
+ messages.push(m);
595
+ else if (m?.content)
596
+ messages.push(`[${m.code ?? m.severity ?? "msg"}] ${m.content}`);
597
+ else if (m?.message)
598
+ messages.push(String(m.message));
599
+ else if (m?.content_html)
600
+ messages.push(String(m.content_html));
601
+ }
602
+ return {
603
+ checkout_id: String(c.id ?? ""),
604
+ status: String(c.status ?? "unknown"),
605
+ total_minor: amount,
606
+ total_major: minorToMajor(amount, currency),
607
+ currency,
608
+ continue_url: c.continue_url ?? c.escalation?.continue_url ?? null,
609
+ messages,
610
+ };
611
+ }
612
+ /**
613
+ * Creates a checkout for the given line items and returns the merchant's quote
614
+ * (total, status, escalation info). NO money moves here — this is the read step
615
+ * the agent uses before requesting a JIT card for the exact total.
616
+ */
617
+ async function ucpCreateCheckout(client, items, buyer, shippingAddress) {
618
+ const checkout = {
619
+ line_items: items.map((i) => ({ item: { id: i.item_id }, quantity: i.quantity })),
620
+ buyer,
621
+ };
622
+ const result = await client.callTool("create_checkout", { meta: meta(), checkout });
623
+ let created = { ...summarizeCheckout(result), raw: result };
624
+ // Address goes in a SECOND call: Shopify validation demands line_items re-sent and
625
+ // destinations as FLAT postal_address objects with line_item_ids (learned live 14/08).
626
+ if (shippingAddress && created.checkout_id) {
627
+ const c = result?.checkout ?? result ?? {};
628
+ const lineItems = (c.line_items ?? []).map((li) => ({
629
+ id: li.id,
630
+ item: { id: li.item?.id },
631
+ quantity: li.quantity,
632
+ }));
633
+ const upd = await client.callTool("update_checkout", {
634
+ meta: meta(),
635
+ id: created.checkout_id,
636
+ checkout: {
637
+ line_items: lineItems,
638
+ buyer,
639
+ fulfillment: {
640
+ methods: [{
641
+ type: "shipping",
642
+ line_item_ids: lineItems.map((li) => li.id),
643
+ destinations: [shippingAddress],
644
+ }],
645
+ },
646
+ },
647
+ });
648
+ created = { ...summarizeCheckout(upd), raw: upd };
649
+ }
650
+ return created;
651
+ }
652
+ async function ucpGetCheckout(client, checkoutId) {
653
+ const result = await client.callTool("get_checkout", { meta: meta(), id: checkoutId });
654
+ return { ...summarizeCheckout(result), raw: result };
655
+ }
656
+ // ============================================================
657
+ // Payment — submit the Z-Zero JIT card via dev.shopify.card
658
+ // ============================================================
659
+ const BRAND_BY_PREFIX = [
660
+ [/^4/, "visa"],
661
+ [/^5[1-5]/, "master"],
662
+ [/^2[2-7]/, "master"],
663
+ [/^3[47]/, "american_express"],
664
+ [/^6(?:011|5)/, "discover"],
665
+ [/^3(?:0[0-5]|[68])/, "diners_club"],
666
+ ];
667
+ function detectBrand(pan) {
668
+ for (const [re, brand] of BRAND_BY_PREFIX)
669
+ if (re.test(pan))
670
+ return brand;
671
+ return "visa";
672
+ }
673
+ // ⛔ PAYMENT LANE IS NOT YET ENABLED.
674
+ // Two things are unverified against a live Token-tier shop: (1) the exact credential
675
+ // shape dev.shopify.card accepts, (2) whether extension_interaction_required clears at
676
+ // Token-tier. Until a real e2e passes, ucpPayCheckout refuses to run unless the machine
677
+ // owner opts in explicitly. No MCP tool calls this function today.
678
+ const UCP_PAY_ENABLED = process.env.Z_ZERO_UCP_PAY_ENABLED === "1";
679
+ /**
680
+ * Attaches the card instrument and completes the checkout.
681
+ * Mirrors playwright_bridge semantics: returns PaymentResult where success=true
682
+ * ONLY on a merchant-confirmed order (that is the caller's sole burn gate).
683
+ */
684
+ async function ucpPayCheckout(params) {
685
+ const { cardData } = params;
686
+ if (!UCP_PAY_ENABLED) {
687
+ // Wipe immediately — we are not going to use the card.
688
+ cardData.number = "0000000000000000";
689
+ cardData.cvv = "000";
690
+ cardData.exp_month = "00";
691
+ cardData.exp_year = "0000";
692
+ cardData.name = "";
693
+ return {
694
+ success: false,
695
+ status: "not_submitted",
696
+ message: "UCP payment lane is not enabled (Z_ZERO_UCP_PAY_ENABLED is unset). The lane currently supports discovery + " +
697
+ "quote/draft + continue_url only; completion requires Shopify Token-tier auth and an unverified card-credential shape. " +
698
+ "Nothing was charged, token NOT burned.",
699
+ };
700
+ }
701
+ try {
702
+ return await (0, with_timeout_js_1.withTimeout)(_ucpPayInner(params), UCP_HARD_TIMEOUT_MS, "ucpPayCheckout");
703
+ }
704
+ catch (err) {
705
+ if (err instanceof with_timeout_js_1.TimeoutError) {
706
+ return {
707
+ success: false,
708
+ status: "unconfirmed",
709
+ message: `UCP checkout timed out after ${UCP_HARD_TIMEOUT_MS / 1000}s AFTER submission started. ` +
710
+ `Token NOT burned — verify with get_order/merchant before any retry (double-charge risk).`,
711
+ };
712
+ }
713
+ const msg = err instanceof Error ? err.message : String(err);
714
+ return { success: false, status: "error", message: `UCP payment failed: ${msg}` };
715
+ }
716
+ finally {
717
+ // RAM WIPE — same contract as playwright_bridge
718
+ cardData.number = "0000000000000000";
719
+ cardData.cvv = "000";
720
+ cardData.exp_month = "00";
721
+ cardData.exp_year = "0000";
722
+ cardData.name = "";
723
+ }
724
+ }
725
+ async function _ucpPayInner(params) {
726
+ const { merchantUrl, checkoutId, cardData, buyer, billingAddress, bearerToken, expectedTotalMajor } = params;
727
+ const discovery = await ucpDiscover(merchantUrl);
728
+ if (!discovery) {
729
+ return { success: false, status: "no_fields", message: "Merchant does not expose /.well-known/ucp — UCP lane unavailable. Fall back to the standard flow." };
730
+ }
731
+ if (!discovery.cardHandler) {
732
+ return {
733
+ success: false,
734
+ status: "no_fields",
735
+ message: `Merchant speaks UCP but declares no dev.shopify.card handler ` +
736
+ `(handlers: ${discovery.handlers.map((h) => h.handler_name).join(", ") || "none"}). ` +
737
+ `Card payment is not possible on the UCP lane here.`,
738
+ };
739
+ }
740
+ const client = params.client ?? new UcpMcpClient(discovery.mcpEndpoint, { bearerToken });
741
+ // Pre-flight: re-read the checkout, verify state & total BEFORE attaching the card.
742
+ const quote = await ucpGetCheckout(client, checkoutId);
743
+ if (quote.status === "completed") {
744
+ return { success: false, status: "error", message: "Checkout is already completed — refusing to pay twice." };
745
+ }
746
+ if (quote.status === "canceled") {
747
+ return { success: false, status: "error", message: "Checkout was canceled by the merchant." };
748
+ }
749
+ if (expectedTotalMajor != null && quote.total_major != null && quote.total_major > expectedTotalMajor + 0.005) {
750
+ return {
751
+ success: false,
752
+ status: "not_submitted",
753
+ message: `🚨 BLOCKED before submission: merchant total ${quote.total_major} ${quote.currency ?? ""} exceeds the authorized ${expectedTotalMajor}. ` +
754
+ `Token NOT burned. Re-quote and request a new token for the correct amount.`,
755
+ };
756
+ }
757
+ // Card instrument for dev.shopify.card. Credential shape follows the UCP
758
+ // payment-handler pattern. ⚠️ UNVERIFIED against a live Token-tier shop: the
759
+ // raw-card-fields guess may need to become the encrypted-credential variant.
760
+ // That is exactly why this whole function sits behind Z_ZERO_UCP_PAY_ENABLED —
761
+ // server validation errors are surfaced verbatim below to drive the fix.
762
+ const pan = cardData.number.replace(/\D/g, "");
763
+ const instrument = {
764
+ id: `zz_${uuid().slice(0, 8)}`,
765
+ handler_id: discovery.cardHandler.id,
766
+ type: "card",
767
+ billing_address: billingAddress,
768
+ credential: {
769
+ type: "card",
770
+ number: pan,
771
+ exp_month: Number(cardData.exp_month),
772
+ exp_year: Number(cardData.exp_year.length === 2 ? `20${cardData.exp_year}` : cardData.exp_year),
773
+ verification_value: cardData.cvv,
774
+ name: cardData.name,
775
+ },
776
+ display: {
777
+ brand: detectBrand(pan),
778
+ last_digits: pan.slice(-4),
779
+ },
780
+ selected: true,
781
+ };
782
+ // Attach instrument (update), then complete with an idempotency key.
783
+ // update_checkout has PUT semantics: anything omitted can be dropped. Re-send
784
+ // line_items AND the fulfillment state (address + selected method) from the
785
+ // pre-flight read, or the address we just collected gets wiped (review 14/08).
786
+ const quoteCheckout = quote.raw?.checkout ?? quote.raw ?? {};
787
+ const lineItemsPatch = (quoteCheckout.line_items ?? []).map((li) => ({
788
+ id: li.id,
789
+ item: { id: li.item?.id },
790
+ quantity: li.quantity,
791
+ }));
792
+ const fulfillmentPatch = quoteCheckout.fulfillment && Array.isArray(quoteCheckout.fulfillment.methods) && quoteCheckout.fulfillment.methods.length
793
+ ? quoteCheckout.fulfillment
794
+ : undefined;
795
+ let updated;
796
+ try {
797
+ const upd = await client.callTool("update_checkout", {
798
+ meta: meta(),
799
+ id: checkoutId,
800
+ checkout: {
801
+ line_items: lineItemsPatch,
802
+ buyer,
803
+ ...(fulfillmentPatch ? { fulfillment: fulfillmentPatch } : {}),
804
+ payment: { instruments: [instrument] },
805
+ },
806
+ });
807
+ updated = { ...summarizeCheckout(upd), raw: upd };
808
+ }
809
+ catch (err) {
810
+ return {
811
+ success: false,
812
+ status: "not_submitted",
813
+ message: `Merchant rejected the payment instrument BEFORE completion (nothing charged): ${err?.message ?? err}`,
814
+ };
815
+ }
816
+ if (updated.status === "requires_escalation") {
817
+ return {
818
+ success: false,
819
+ status: "not_submitted",
820
+ message: `Merchant requires buyer escalation before completing — nothing was charged. ` +
821
+ (updated.continue_url ? `Hand the buyer this URL to finish: ${updated.continue_url}. ` : "") +
822
+ updated.messages.join(" "),
823
+ };
824
+ }
825
+ const idempotencyKey = uuid();
826
+ let completed;
827
+ try {
828
+ completed = await client.callTool("complete_checkout", {
829
+ meta: meta({ "idempotency-key": idempotencyKey }),
830
+ id: checkoutId,
831
+ checkout: { payment: { instruments: [instrument] } },
832
+ });
833
+ }
834
+ catch (err) {
835
+ const msg = String(err?.message ?? err);
836
+ // Auth-gate: Shopify only allows Token-tier agents to complete.
837
+ if (/401|403|unauthorized|forbidden|permission/i.test(msg)) {
838
+ return {
839
+ success: false,
840
+ status: "not_submitted",
841
+ message: `complete_checkout requires Token-tier agent auth on this shop (Shopify Dev Dashboard JWT or a shop access token) — nothing was charged. ` +
842
+ (updated.continue_url ? `Buyer can finish manually at: ${updated.continue_url}. ` : "") +
843
+ `Server said: ${msg}`,
844
+ };
845
+ }
846
+ if (/declin|insufficient|invalid card|card.*not accepted/i.test(msg)) {
847
+ return { success: false, status: "declined", message: `Merchant declined the card at completion: ${msg}` };
848
+ }
849
+ // Submission started but the outcome is unknown — the dangerous case.
850
+ return {
851
+ success: false,
852
+ status: "unconfirmed",
853
+ message: `complete_checkout errored AFTER submission (idempotency-key ${idempotencyKey}) — outcome unknown, token NOT burned. ` +
854
+ `Retry with the SAME key or verify via get_order before anything else. Server said: ${msg}`,
855
+ };
856
+ }
857
+ const final = summarizeCheckout(completed);
858
+ const order = completed?.order ?? completed?.checkout?.order ?? null;
859
+ const orderId = order?.id ?? order?.order_number ?? completed?.order_id ?? undefined;
860
+ if (final.status === "completed" || orderId) {
861
+ return {
862
+ success: true,
863
+ status: "confirmed",
864
+ message: `✅ Order confirmed via the official UCP rail (dev.shopify.card — no browser, no form-fill).` +
865
+ (final.total_major != null ? ` Total ${final.total_major} ${final.currency ?? ""}.` : ""),
866
+ receipt_id: orderId ? String(orderId) : undefined,
867
+ amount: final.total_major ?? undefined,
868
+ };
869
+ }
870
+ if (final.status === "requires_escalation") {
871
+ return {
872
+ success: false,
873
+ status: "not_submitted",
874
+ message: `Completion halted — merchant demands buyer action. ` +
875
+ (final.continue_url ? `Continue at: ${final.continue_url}. ` : "") + final.messages.join(" "),
876
+ };
877
+ }
878
+ return {
879
+ success: false,
880
+ status: "unconfirmed",
881
+ message: `complete_checkout returned status "${final.status}" with no order id — token NOT burned. ` +
882
+ `Poll get_checkout/get_order before retrying (idempotency-key ${idempotencyKey}). ${final.messages.join(" ")}`,
883
+ };
884
+ }
885
+ // Exposed for offline unit tests only — not part of the public bridge API.
886
+ exports.__ucpInternals = { isPrivateIp, expandIpv6, assertSafeUcpUrl, summarizeCheckout, pinnedRequest };