z-zero-mcp-server 1.10.3 → 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.
@@ -5,53 +5,216 @@ Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.fillCheckoutForm = fillCheckoutForm;
6
6
  const with_timeout_js_1 = require("./lib/with-timeout.js");
7
7
  const browser_js_1 = require("./lib/browser.js");
8
+ const domain_lock_js_1 = require("./lib/domain-lock.js");
9
+ const failure_taxonomy_js_1 = require("./failure_taxonomy.js");
8
10
  const CHECKOUT_HARD_TIMEOUT_MS = 60_000; // 60s absolute cap — prevents slow-loris attacks
11
+ const PAGE_DETAIL_MAX = 300;
9
12
  /**
10
13
  * Detects and fills credit card form fields on a checkout page.
11
14
  * Card data exists ONLY in RAM and is wiped after injection.
12
15
  * Hard timeout of 60s prevents merchant page from hanging indefinitely.
16
+ *
17
+ * Nothing this function returns may carry the card (audit T12 F3, M.1): a
18
+ * Playwright error quotes the value it was filling (`fill("4242…")`), and a page
19
+ * can echo the number back as its "order number". Every string leaving here goes
20
+ * through finish(), which strips this card's own number and CVV, then every
21
+ * other card-shaped number.
13
22
  */
14
23
  async function fillCheckoutForm(checkoutUrl, cardData, existingPage, hints) {
24
+ // Kept only to scrub output; the bridge wipes cardData itself.
25
+ const secrets = { number: cardData.number, cvv: cardData.cvv };
15
26
  let browser = null;
16
27
  let page;
17
- if (existingPage) {
18
- page = existingPage;
19
- }
20
- else {
21
- browser = await (0, browser_js_1.launchBrowser)();
22
- const context = await browser.newContext();
23
- page = await context.newPage();
24
- }
25
28
  try {
26
- return await (0, with_timeout_js_1.withTimeout)(_fillCheckoutFormInner(page, checkoutUrl, cardData, hints), CHECKOUT_HARD_TIMEOUT_MS, 'fillCheckoutForm', async () => {
29
+ if (existingPage) {
30
+ page = existingPage;
31
+ }
32
+ else {
33
+ browser = await (0, browser_js_1.launchBrowser)();
34
+ const context = await browser.newContext();
35
+ page = await context.newPage();
36
+ }
37
+ const result = await (0, with_timeout_js_1.withTimeout)(_fillCheckoutFormInner(page, checkoutUrl, cardData, hints), CHECKOUT_HARD_TIMEOUT_MS, 'fillCheckoutForm', async () => {
27
38
  console.error('[PLAYWRIGHT] ⚠️ Hard timeout hit — force-closing browser');
28
39
  if (browser)
29
40
  await browser.close().catch(() => { });
30
41
  });
42
+ return finish(result, secrets);
31
43
  }
32
44
  catch (err) {
33
45
  if (err instanceof with_timeout_js_1.TimeoutError) {
34
- return {
46
+ return finish({
35
47
  success: false,
36
48
  status: 'error',
37
49
  message: `Checkout timed out after ${CHECKOUT_HARD_TIMEOUT_MS / 1000}s. The merchant page may be too slow or blocking automation.`,
38
- };
50
+ }, secrets);
39
51
  }
40
- const errMsg = err instanceof Error ? err.message : String(err);
41
- return { success: false, status: 'error', message: `Payment failed: ${errMsg}` };
52
+ return finish({
53
+ success: false,
54
+ status: 'error',
55
+ message: 'The browser failed during the checkout attempt.',
56
+ page_detail: err instanceof Error ? err.message : String(err),
57
+ }, secrets);
42
58
  }
43
59
  finally {
44
60
  if (browser)
45
61
  await browser.close().catch(() => { });
62
+ // Wipe the copy too: fill is over, nothing needs the values any more.
63
+ secrets.number = "";
64
+ secrets.cvv = "";
65
+ }
66
+ }
67
+ /** Last stop before a result leaves the bridge: no card value in any string. */
68
+ function finish(r, secrets) {
69
+ const out = { ...r, message: (0, failure_taxonomy_js_1.scrubCardValues)(r.message, secrets) };
70
+ if (r.page_detail) {
71
+ out.page_detail = (0, failure_taxonomy_js_1.scrubCardValues)(r.page_detail, secrets).slice(0, PAGE_DETAIL_MAX);
72
+ }
73
+ if (r.receipt_id !== undefined) {
74
+ out.receipt_id = cleanReceiptId(r.receipt_id, secrets);
75
+ }
76
+ return out;
77
+ }
78
+ /**
79
+ * An order number is page text. It goes into the agent's result, the signed
80
+ * receipt and the public receipt page, so: short, plain characters only, and
81
+ * dropped outright if it holds this card's number or CVV, or anything that can
82
+ * be a card number. A dropped id costs a convenience; a kept one could cost the
83
+ * card (audit T12 F3: a page echoed "Order number: <PAN>-<CVV>").
84
+ */
85
+ function cleanReceiptId(id, secrets) {
86
+ if (!id)
87
+ return undefined;
88
+ const plain = id.normalize("NFKC").trim();
89
+ if (!/^[A-Za-z0-9][A-Za-z0-9-]{2,63}$/.test(plain))
90
+ return undefined;
91
+ return (0, failure_taxonomy_js_1.scrubCardValues)(plain, secrets, { cards: "valid" }) === plain ? plain : undefined;
92
+ }
93
+ const FIELD_SHAPE = {
94
+ number: /cc-?number|card.?num|cardnumber|credit.?card|card.?no\b|\bccnum|\bpan\b|card[_\s-]?number/i,
95
+ exp: /cc-exp|exp(iry|iration|ires)?\b|exp[-_\s]?(date|month|year|mm|yy)|\bmm\s*\/\s*yy|valid.?thru/i,
96
+ cvv: /cc-csc|\bcvv|\bcvc|\bcsc\b|security.?code|card.?code|verification|cvn/i,
97
+ name: /cc-name|card.?holder|name.?on.?card|ccname|card.?name/i,
98
+ };
99
+ class CardGate {
100
+ page;
101
+ lockedDomain;
102
+ lockedOrigin = null;
103
+ movedTo = null;
104
+ onNav;
105
+ constructor(page, lockedDomain) {
106
+ this.page = page;
107
+ this.lockedDomain = lockedDomain;
108
+ this.onNav = (f) => {
109
+ if (f !== this.page.mainFrame() || !this.lockedOrigin || this.movedTo)
110
+ return;
111
+ if (originOf(f.url()) !== this.lockedOrigin)
112
+ this.movedTo = f.url();
113
+ };
114
+ }
115
+ /** Lock to the page in front of us now. Any later move to another origin stops the fill. */
116
+ arm() {
117
+ const lock = (0, domain_lock_js_1.checkPaymentPage)(this.page.url(), this.lockedDomain);
118
+ if (!lock.ok)
119
+ return lock;
120
+ this.lockedOrigin = originOf(this.page.url());
121
+ this.page.on('framenavigated', this.onNav);
122
+ return lock;
123
+ }
124
+ dispose() {
125
+ this.page.off('framenavigated', this.onNav);
126
+ }
127
+ /** Stop everything: the page itself has gone somewhere else. */
128
+ moved() {
129
+ if (this.movedTo)
130
+ return blockedMove(this.movedTo);
131
+ if (originOf(this.page.url()) !== this.lockedOrigin)
132
+ return blockedMove(this.page.url());
133
+ const live = (0, domain_lock_js_1.checkPaymentPage)(this.page.url(), this.lockedDomain);
134
+ return live.ok ? null : live;
135
+ }
136
+ /** May this one field receive this one value? false = skip the field, never type. */
137
+ async allows(el, kind) {
138
+ if (this.moved())
139
+ return false;
140
+ const frame = await el.ownerFrame().catch(() => null);
141
+ if (!frame)
142
+ return false;
143
+ if (frame === this.page.mainFrame()) {
144
+ if (originOf(frame.url()) !== this.lockedOrigin)
145
+ return false;
146
+ return (await looksLikeCardField(el, kind)) && (await isHumanVisible(el));
147
+ }
148
+ return (0, domain_lock_js_1.isTrustedCardFrame)(frame.url(), this.lockedDomain);
149
+ }
150
+ }
151
+ function originOf(url) {
152
+ try {
153
+ const o = new URL(url).origin;
154
+ return o === "null" ? null : o;
46
155
  }
156
+ catch {
157
+ return null;
158
+ }
159
+ }
160
+ function blockedMove(to) {
161
+ return {
162
+ ok: false,
163
+ reason: `The page moved to ${hostOf(to)} while the card was being filled in. Filling stopped; nothing more was typed and the order was not submitted.`,
164
+ };
165
+ }
166
+ function hostOf(url) {
167
+ try {
168
+ return new URL(url).host || "an unreadable address";
169
+ }
170
+ catch {
171
+ return "an unreadable address";
172
+ }
173
+ }
174
+ async function looksLikeCardField(el, kind) {
175
+ const attrs = await el.evaluate((e) => {
176
+ const a = (n) => e.getAttribute(n) || "";
177
+ return [a("autocomplete"), a("name"), a("id"), a("placeholder"), a("aria-label"), a("data-elements-stable-field-name")].join(" ");
178
+ }).catch(() => "");
179
+ return FIELD_SHAPE[kind].test(attrs);
180
+ }
181
+ async function isHumanVisible(el) {
182
+ if (!(await el.isVisible().catch(() => false)))
183
+ return false;
184
+ return el.evaluate((e) => {
185
+ const r = e.getBoundingClientRect();
186
+ if (r.width < 4 || r.height < 4)
187
+ return false;
188
+ let opacity = 1;
189
+ for (let n = e; n; n = n.parentElement) {
190
+ const s = getComputedStyle(n);
191
+ if (s.visibility === "hidden" || s.display === "none")
192
+ return false;
193
+ opacity *= parseFloat(s.opacity || "1");
194
+ }
195
+ return opacity >= 0.1;
196
+ }).catch(() => false);
47
197
  }
48
198
  // ============================================================
49
199
  // HELPER: Smart fill — handles both <input> and <select>
50
200
  // Prevents crash when dropdown uses <select> instead of <input>
51
201
  // ============================================================
52
- async function smartFill(el, value) {
202
+ async function smartFill(gate, el, value, kind) {
53
203
  try {
204
+ if (!(await gate.allows(el, kind)))
205
+ return false;
54
206
  const tag = await el.evaluate(e => e.tagName.toLowerCase());
207
+ // Card data only ever goes into a form field built to hold it: an <input> of a
208
+ // text-like type, or a <select> (expiry). Never a textarea, a hidden or email
209
+ // input, or anything else a hint selector might point at (audit MCP-03) —
210
+ // those are where a card number would end up in an order note or a page owner's log.
211
+ if (tag !== 'input' && tag !== 'select')
212
+ return false;
213
+ if (tag === 'input') {
214
+ const type = await el.evaluate(e => (e.type || 'text').toLowerCase());
215
+ if (!['text', 'tel', 'number', 'password'].includes(type))
216
+ return false;
217
+ }
55
218
  if (tag === 'select') {
56
219
  // Try by value first (most common: "01", "12", "2030")
57
220
  try {
@@ -82,21 +245,32 @@ async function smartFill(el, value) {
82
245
  }
83
246
  }
84
247
  catch {
248
+ // Never rethrow: a Playwright fill error quotes the value it was typing.
85
249
  return false;
86
250
  }
87
251
  }
88
252
  /** Try each selector in order, smartFill the first match */
89
- async function tryFillField(page, selectors, value) {
253
+ async function tryFillField(gate, ctx, selectors, value, kind) {
90
254
  for (const selector of selectors) {
91
- const el = await page.$(selector);
255
+ const el = await ctx.$(selector).catch(() => null);
92
256
  if (el) {
93
- const ok = await smartFill(el, value);
257
+ const ok = await smartFill(gate, el, value, kind);
94
258
  if (ok)
95
259
  return true;
96
260
  }
97
261
  }
98
262
  return false;
99
263
  }
264
+ /**
265
+ * A hint selector is plain CSS. Playwright also reads `>>` chains and its own
266
+ * engines (`internal:control=enter-frame`, `xpath=`…), which let one string walk
267
+ * into another site's frame (audit T12 F1). Those are refused outright.
268
+ */
269
+ function isPlainCss(selector) {
270
+ if (!selector)
271
+ return false;
272
+ return !/>>|^\s*[a-z_-]+=|internal:/i.test(selector);
273
+ }
100
274
  // ============================================================
101
275
  // CONFIRMATION DETECTION — the core of "filled ≠ paid"
102
276
  // After Pay is clicked we must observe a REAL outcome before
@@ -113,9 +287,67 @@ const SUCCESS_TEXT_RE = /thank you for your (?:order|purchase|payment)|your orde
113
287
  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
288
  // Real order/confirmation number to use as receipt_id (only when confirmed)
115
289
  const RECEIPT_RE = /(?:order|confirmation|receipt)\s*(?:number|no\.?|#)?[:\s#]*([A-Z0-9][A-Z0-9-]{3,})/i;
290
+ /**
291
+ * The text a person looking at the page can actually read (audit T12 F6, M.7).
292
+ * innerText still counts text that is transparent, 0px, or parked off-screen —
293
+ * a page could hide "Order number: …" there and have a non-payment read as paid
294
+ * (the token then burns and the money sits in USED with no way back).
295
+ */
296
+ async function readableText(page) {
297
+ return page.evaluate(() => {
298
+ const out = [];
299
+ const docW = Math.max(document.documentElement.scrollWidth, window.innerWidth);
300
+ const docH = Math.max(document.documentElement.scrollHeight, window.innerHeight);
301
+ const seen = new Map();
302
+ const readable = (el) => {
303
+ const cached = seen.get(el);
304
+ if (cached !== undefined)
305
+ return cached;
306
+ let ok = true;
307
+ const r = el.getBoundingClientRect();
308
+ if (r.width < 1 || r.height < 1)
309
+ ok = false;
310
+ const left = r.left + window.scrollX;
311
+ const top = r.top + window.scrollY;
312
+ if (ok && (left + r.width <= 0 || top + r.height <= 0 || left >= docW || top >= docH))
313
+ ok = false;
314
+ if (ok) {
315
+ let opacity = 1;
316
+ for (let n = el; n; n = n.parentElement) {
317
+ const s = getComputedStyle(n);
318
+ if (s.display === "none" || s.visibility === "hidden") {
319
+ ok = false;
320
+ break;
321
+ }
322
+ opacity *= parseFloat(s.opacity || "1");
323
+ if (n === el && parseFloat(s.fontSize || "16") < 6) {
324
+ ok = false;
325
+ break;
326
+ }
327
+ }
328
+ if (ok && opacity < 0.1)
329
+ ok = false;
330
+ }
331
+ seen.set(el, ok);
332
+ return ok;
333
+ };
334
+ const walker = document.createTreeWalker(document.body || document.documentElement, NodeFilter.SHOW_TEXT);
335
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
336
+ const t = (n.textContent || "").trim();
337
+ const parent = n.parentElement;
338
+ if (!t || !parent || ["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE"].includes(parent.tagName))
339
+ continue;
340
+ if (readable(parent))
341
+ out.push(t);
342
+ if (out.length > 4000)
343
+ break;
344
+ }
345
+ return out.join("\n");
346
+ });
347
+ }
116
348
  /**
117
349
  * 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
350
+ * Polls URL + readable text for a confirmation or decline signal until a
119
351
  * signal is seen or CONFIRM_WAIT_MS elapses. Default (no signal) is the
120
352
  * SAFE 'unconfirmed' — caller must NOT burn the token on that.
121
353
  */
@@ -135,11 +367,11 @@ async function detectPaymentOutcome(page, checkoutUrl) {
135
367
  let bodyText = '';
136
368
  try {
137
369
  currentUrl = page.url();
138
- bodyText = await page.evaluate(() => document.body?.innerText ?? '');
370
+ bodyText = await readableText(page);
139
371
  }
140
372
  catch {
141
373
  // page is mid-navigation — wait and retry
142
- await page.waitForTimeout(CONFIRM_POLL_MS);
374
+ await page.waitForTimeout(CONFIRM_POLL_MS).catch(() => { });
143
375
  continue;
144
376
  }
145
377
  // Decline is a definitive negative — check first.
@@ -161,7 +393,7 @@ async function detectPaymentOutcome(page, checkoutUrl) {
161
393
  const m = bodyText.match(RECEIPT_RE);
162
394
  return { kind: 'confirmed', receipt_id: m?.[1] };
163
395
  }
164
- await page.waitForTimeout(CONFIRM_POLL_MS);
396
+ await page.waitForTimeout(CONFIRM_POLL_MS).catch(() => { });
165
397
  }
166
398
  // No clear signal within the window — safe default, caller will NOT burn.
167
399
  return { kind: 'unconfirmed' };
@@ -192,8 +424,23 @@ function outcomeToResult(outcome, fieldNote) {
192
424
  };
193
425
  }
194
426
  }
427
+ /** Click the pay button only while the page is still the one we locked to. */
428
+ async function clickIfStillLocked(gate, btn) {
429
+ const moved = gate.moved();
430
+ if (moved)
431
+ return moved;
432
+ try {
433
+ if (await btn.isVisible()) {
434
+ await btn.click();
435
+ return 'clicked';
436
+ }
437
+ }
438
+ catch { /* covered, detached, … — treat as not clicked */ }
439
+ return 'not_clicked';
440
+ }
195
441
  /** Internal implementation — called by fillCheckoutForm inside a timeout wrapper */
196
442
  async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
443
+ const gate = new CardGate(page, cardData.merchant_domain);
197
444
  try {
198
445
  // ✅ FIX: Skip navigation if page already loaded (Single Browser reuse from auto_pay_checkout)
199
446
  // Prevents double-navigate which would reload page and lose cart/session state.
@@ -226,6 +473,8 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
226
473
  // ============================================================
227
474
  if (hints?.pre_steps && hints.pre_steps.length > 0) {
228
475
  for (const selector of hints.pre_steps) {
476
+ if (!isPlainCss(selector))
477
+ continue;
229
478
  try {
230
479
  const el = await page.$(selector);
231
480
  if (el && await el.isVisible()) {
@@ -236,95 +485,86 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
236
485
  catch { /* non-fatal — continue */ }
237
486
  }
238
487
  }
488
+ // 🔒 DOMAIN LOCK — armed on the page in front of us now, then held for every
489
+ // field (CardGate). The card goes only on its own store or a hosted payment
490
+ // page that store handed off to (lib/domain-lock.ts).
491
+ const lock = gate.arm();
492
+ if (!lock.ok) {
493
+ return { success: false, status: "blocked", message: lock.reason };
494
+ }
239
495
  let filledFields = 0;
496
+ let cardNumberFilled = false;
497
+ const stopIfMoved = () => {
498
+ const moved = gate.moved();
499
+ return moved && !moved.ok ? { success: false, status: "blocked", message: moved.reason } : null;
500
+ };
240
501
  // ============================================================
241
502
  // STRATEGY 0.5: Agent-provided selectors (from get_merchant_hints)
242
503
  // Tried first — agent already read the DOM and knows exact locations.
243
- // Supports iframe_selector: if provided, card fields are searched INSIDE
244
- // matching iframes (e.g. Shopify "card-fields-iframe") rather than main page.
504
+ // iframe_selector: card fields are searched INSIDE frames whose name holds
505
+ // that fragment AND whose real origin is the store or a card-field provider.
506
+ // No such frame → the card fields are not searched anywhere else (the main
507
+ // page is where an order note lives; audit T11 F4 / T00 F1).
245
508
  // Name on card is always searched on the main page (outside iframe).
246
- // Falls through to Strategy 1 if nothing matched.
509
+ // Falls through to Strategy 1 if the card number could not be placed.
247
510
  // ============================================================
248
511
  if (hints && (hints.card_selector || hints.exp_selector || hints.cvv_selector)) {
249
- const hintFillResults = [];
250
512
  let cardContexts = [page];
251
513
  if (hints.iframe_selector) {
252
- const matchingFrames = page.frames().filter((f) => f.name().includes(hints.iframe_selector));
253
- if (matchingFrames.length > 0)
254
- cardContexts = matchingFrames;
514
+ // Card frames load after the page; until then they sit at about:blank
515
+ // and fail the origin check.
516
+ await page.waitForLoadState("load", { timeout: 10_000 }).catch(() => { });
517
+ cardContexts = page.frames().filter((f) => f !== page.mainFrame() &&
518
+ f.name().includes(hints.iframe_selector) &&
519
+ (0, domain_lock_js_1.isTrustedCardFrame)(f.url(), cardData.merchant_domain));
255
520
  }
256
- // Card number
257
- if (hints.card_selector) {
258
- for (const ctx of cardContexts) {
259
- const el = await ctx.$(hints.card_selector);
260
- if (el) {
261
- hintFillResults.push(await smartFill(el, cardData.number));
262
- break;
263
- }
521
+ const fillHint = async (selector, value, kind, contexts) => {
522
+ if (!isPlainCss(selector))
523
+ return false;
524
+ for (const ctx of contexts) {
525
+ const el = await ctx.$(selector).catch(() => null);
526
+ if (el)
527
+ return smartFill(gate, el, value, kind);
264
528
  }
529
+ return false;
530
+ };
531
+ let hintFilled = 0;
532
+ if (await fillHint(hints.card_selector, cardData.number, 'number', cardContexts)) {
533
+ hintFilled++;
534
+ cardNumberFilled = true;
265
535
  }
266
- // Expiry combined (with space-padded slash for Shopify: "MM / YY")
267
536
  if (hints.exp_selector) {
268
- const expiryVal = `${cardData.exp_month} / ${cardData.exp_year.slice(-2)}`;
269
- for (const ctx of cardContexts) {
270
- const el = await ctx.$(hints.exp_selector);
271
- if (el) {
272
- hintFillResults.push(await smartFill(el, expiryVal));
273
- break;
274
- }
275
- }
537
+ // Expiry combined (with space-padded slash for Shopify: "MM / YY")
538
+ if (await fillHint(hints.exp_selector, `${cardData.exp_month} / ${cardData.exp_year.slice(-2)}`, 'exp', cardContexts))
539
+ hintFilled++;
276
540
  }
277
- // Expiry split month/year
278
- if (!hints.exp_selector && hints.exp_month_selector) {
279
- for (const ctx of cardContexts) {
280
- const elM = await ctx.$(hints.exp_month_selector);
281
- if (elM) {
282
- hintFillResults.push(await smartFill(elM, cardData.exp_month));
283
- break;
284
- }
285
- }
286
- if (hints.exp_year_selector) {
287
- for (const ctx of cardContexts) {
288
- const elY = await ctx.$(hints.exp_year_selector);
289
- if (elY) {
290
- hintFillResults.push(await smartFill(elY, cardData.exp_year));
291
- break;
292
- }
293
- }
294
- }
295
- }
296
- // CVV
297
- if (hints.cvv_selector) {
298
- for (const ctx of cardContexts) {
299
- const el = await ctx.$(hints.cvv_selector);
300
- if (el) {
301
- hintFillResults.push(await smartFill(el, cardData.cvv));
302
- break;
303
- }
304
- }
541
+ else if (hints.exp_month_selector) {
542
+ if (await fillHint(hints.exp_month_selector, cardData.exp_month, 'exp', cardContexts))
543
+ hintFilled++;
544
+ if (await fillHint(hints.exp_year_selector, cardData.exp_year, 'exp', cardContexts))
545
+ hintFilled++;
305
546
  }
547
+ if (await fillHint(hints.cvv_selector, cardData.cvv, 'cvv', cardContexts))
548
+ hintFilled++;
306
549
  // Name on card — ALWAYS on main page (outside iframe for Shopify/most platforms)
307
- if (hints.name_selector) {
308
- const el = await page.$(hints.name_selector);
309
- if (el) {
310
- hintFillResults.push(await smartFill(el, cardData.name));
311
- }
312
- }
313
- const hintSuccesses = hintFillResults.filter(Boolean).length;
314
- if (hintSuccesses > 0) {
315
- filledFields += hintSuccesses;
550
+ if (cardNumberFilled && await fillHint(hints.name_selector, cardData.name, 'name', [page]))
551
+ hintFilled++;
552
+ const stopped = stopIfMoved();
553
+ if (stopped)
554
+ return stopped;
555
+ if (cardNumberFilled) {
556
+ filledFields += hintFilled;
316
557
  const modeNote = `${filledFields} fields injected via agent hints${hints.iframe_selector ? ' (iframe mode)' : ''}.`;
317
558
  // Must actually submit to have any chance of a real payment.
318
559
  let clicked = false;
319
- if (hints.submit_selector) {
320
- try {
321
- const btn = await page.$(hints.submit_selector);
322
- if (btn && await btn.isVisible()) {
323
- await btn.click();
324
- clicked = true;
325
- }
560
+ if (isPlainCss(hints.submit_selector)) {
561
+ const btn = await page.$(hints.submit_selector).catch(() => null);
562
+ if (btn) {
563
+ const c = await clickIfStillLocked(gate, btn);
564
+ if (typeof c === 'object')
565
+ return { success: false, status: 'blocked', message: c.ok ? '' : c.reason };
566
+ clicked = c === 'clicked';
326
567
  }
327
- catch { /* non-fatal */ }
328
568
  }
329
569
  if (!clicked) {
330
570
  // Fields filled but no submit happened → NOT a payment. Do not fabricate success.
@@ -339,7 +579,7 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
339
579
  const outcome = await detectPaymentOutcome(page, checkoutUrl);
340
580
  return outcomeToResult(outcome, modeNote);
341
581
  }
342
- // hints provided but nothing matched → fall through to Strategy 1
582
+ // hints provided but the card number could not be placed → fall through to Strategy 1
343
583
  }
344
584
  // ============================================================
345
585
  // STRATEGY 1: Standard HTML form fields
@@ -415,84 +655,79 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
415
655
  ],
416
656
  };
417
657
  // Card Number
418
- if (await tryFillField(page, S.number, cardData.number))
658
+ if (await tryFillField(gate, page, S.number, cardData.number, 'number')) {
419
659
  filledFields++;
660
+ cardNumberFilled = true;
661
+ }
420
662
  // Expiry: try combined MM/YY first
421
663
  const expiryValue = `${cardData.exp_month}/${cardData.exp_year.slice(-2)}`;
422
- let expiryFilled = await tryFillField(page, S.expiry, expiryValue);
664
+ let expiryFilled = await tryFillField(gate, page, S.expiry, expiryValue, 'exp');
423
665
  if (expiryFilled)
424
666
  filledFields++;
425
667
  // Expiry: fallback to separate month + year (works with both <input> AND <select>)
426
668
  if (!expiryFilled) {
427
- if (await tryFillField(page, S.exp_month, cardData.exp_month))
669
+ if (await tryFillField(gate, page, S.exp_month, cardData.exp_month, 'exp'))
428
670
  filledFields++;
429
- if (await tryFillField(page, S.exp_year, cardData.exp_year))
671
+ if (await tryFillField(gate, page, S.exp_year, cardData.exp_year, 'exp'))
430
672
  filledFields++;
431
673
  }
432
674
  // CVV
433
- if (await tryFillField(page, S.cvv, cardData.cvv))
675
+ if (await tryFillField(gate, page, S.cvv, cardData.cvv, 'cvv'))
434
676
  filledFields++;
435
677
  // Name on Card
436
- if (await tryFillField(page, S.name, cardData.name))
678
+ if (await tryFillField(gate, page, S.name, cardData.name, 'name'))
437
679
  filledFields++;
680
+ const stopped1 = stopIfMoved();
681
+ if (stopped1)
682
+ return stopped1;
438
683
  // ============================================================
439
684
  // STRATEGY 2: Stripe Elements (iframe-based)
440
685
  // Stripe renders payment inputs inside iframes from js.stripe.com.
441
- // Some merchants use __privateStripeFrame* named frames.
442
686
  // Stripe has 2 modes:
443
687
  // - Unified: 1 iframe with all fields (card, exp, cvc in one)
444
688
  // - Split: separate iframes per field (cardNumber, cardExpiry, cardCvc)
445
689
  // We handle both by scanning ALL matching Stripe frames.
446
690
  // ============================================================
447
- if (filledFields === 0) {
691
+ if (!cardNumberFilled) {
692
+ await page.waitForLoadState("load", { timeout: 10_000 }).catch(() => { });
693
+ // Recognised by the frame's real origin, never by its name or a substring of
694
+ // its URL: any frame can call itself __privateStripeFrame or carry
695
+ // "js.stripe.com" in a query string (audit MCP-03 / N3).
448
696
  const stripeFrames = page.frames().filter((f) => {
449
- const url = f.url();
450
- const name = f.name();
451
- return url.includes('js.stripe.com')
452
- || url.includes('stripe.com/elements')
453
- || name.startsWith('__privateStripeFrame');
697
+ try {
698
+ const u = new URL(f.url());
699
+ return u.protocol === 'https:' && (u.hostname === 'stripe.com' || u.hostname.endsWith('.stripe.com'));
700
+ }
701
+ catch {
702
+ return false;
703
+ }
454
704
  });
455
705
  for (const frame of stripeFrames) {
456
- // Card Number
457
- for (const sel of [
706
+ if (await tryFillField(gate, frame, [
458
707
  'input[name="cardnumber"]',
459
708
  'input[autocomplete="cc-number"]',
460
709
  'input[data-elements-stable-field-name="cardNumber"]',
461
- ]) {
462
- const el = await frame.$(sel);
463
- if (el) {
464
- await el.fill(cardData.number);
465
- filledFields++;
466
- break;
467
- }
710
+ ], cardData.number, 'number')) {
711
+ filledFields++;
712
+ cardNumberFilled = true;
468
713
  }
469
714
  // Expiry (Stripe uses MM/YY without slash)
470
- for (const sel of [
715
+ if (await tryFillField(gate, frame, [
471
716
  'input[name="exp-date"]',
472
717
  'input[autocomplete="cc-exp"]',
473
718
  'input[data-elements-stable-field-name="cardExpiry"]',
474
- ]) {
475
- const el = await frame.$(sel);
476
- if (el) {
477
- await el.fill(`${cardData.exp_month}${cardData.exp_year.slice(-2)}`);
478
- filledFields++;
479
- break;
480
- }
481
- }
482
- // CVC
483
- for (const sel of [
719
+ ], `${cardData.exp_month}${cardData.exp_year.slice(-2)}`, 'exp'))
720
+ filledFields++;
721
+ if (await tryFillField(gate, frame, [
484
722
  'input[name="cvc"]',
485
723
  'input[autocomplete="cc-csc"]',
486
724
  'input[data-elements-stable-field-name="cardCvc"]',
487
- ]) {
488
- const el = await frame.$(sel);
489
- if (el) {
490
- await el.fill(cardData.cvv);
491
- filledFields++;
492
- break;
493
- }
494
- }
725
+ ], cardData.cvv, 'cvv'))
726
+ filledFields++;
495
727
  }
728
+ const stopped2 = stopIfMoved();
729
+ if (stopped2)
730
+ return stopped2;
496
731
  }
497
732
  if (filledFields === 0) {
498
733
  return {
@@ -500,11 +735,12 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
500
735
  status: 'no_fields',
501
736
  message: "Could not detect any credit card fields on this page. " +
502
737
  (landedElsewhere
503
- ? `The checkout URL redirected to ${landedUrl} — the cart/session likely did not carry over. ` +
738
+ ? "The checkout URL redirected elsewhere (see page_detail) — the cart/session likely did not carry over. " +
504
739
  "Z-Zero opens its OWN fresh browser, so checkout_url must be resumable on its own " +
505
740
  "(e.g. a Shopify/Etsy checkout-token URL), not a page that needs the agent's logged-in session. "
506
741
  : "") +
507
742
  "The checkout form may use an unsupported format, or the page requires a logged-in session.",
743
+ ...(landedElsewhere ? { page_detail: `landed on: ${landedUrl}` } : {}),
508
744
  };
509
745
  }
510
746
  // ============================================================
@@ -520,9 +756,13 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
520
756
  ];
521
757
  let clicked = false;
522
758
  for (const selector of payButtonSelectors) {
523
- const btn = await page.$(selector);
524
- if (btn && (await btn.isVisible())) {
525
- await btn.click();
759
+ const btn = await page.$(selector).catch(() => null);
760
+ if (!btn)
761
+ continue;
762
+ const c = await clickIfStillLocked(gate, btn);
763
+ if (typeof c === 'object')
764
+ return { success: false, status: 'blocked', message: c.ok ? '' : c.reason };
765
+ if (c === 'clicked') {
526
766
  clicked = true;
527
767
  break;
528
768
  }
@@ -543,14 +783,15 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
543
783
  return outcomeToResult(outcome, fieldNote);
544
784
  }
545
785
  catch (error) {
546
- const errMsg = error instanceof Error ? error.message : String(error);
547
786
  return {
548
787
  success: false,
549
788
  status: 'error',
550
- message: `Payment failed: ${errMsg}`,
789
+ message: 'The browser failed during the checkout attempt.',
790
+ page_detail: error instanceof Error ? error.message : String(error),
551
791
  };
552
792
  }
553
793
  finally {
794
+ gate.dispose();
554
795
  // ============================================================
555
796
  // RAM WIPE - Critical security step
556
797
  // ============================================================