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.
@@ -6,52 +6,203 @@ 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
8
  const domain_lock_js_1 = require("./lib/domain-lock.js");
9
+ const failure_taxonomy_js_1 = require("./failure_taxonomy.js");
9
10
  const CHECKOUT_HARD_TIMEOUT_MS = 60_000; // 60s absolute cap — prevents slow-loris attacks
11
+ const PAGE_DETAIL_MAX = 300;
10
12
  /**
11
13
  * Detects and fills credit card form fields on a checkout page.
12
14
  * Card data exists ONLY in RAM and is wiped after injection.
13
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.
14
22
  */
15
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 };
16
26
  let browser = null;
17
27
  let page;
18
- if (existingPage) {
19
- page = existingPage;
20
- }
21
- else {
22
- browser = await (0, browser_js_1.launchBrowser)();
23
- const context = await browser.newContext();
24
- page = await context.newPage();
25
- }
26
28
  try {
27
- 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 () => {
28
38
  console.error('[PLAYWRIGHT] ⚠️ Hard timeout hit — force-closing browser');
29
39
  if (browser)
30
40
  await browser.close().catch(() => { });
31
41
  });
42
+ return finish(result, secrets);
32
43
  }
33
44
  catch (err) {
34
45
  if (err instanceof with_timeout_js_1.TimeoutError) {
35
- return {
46
+ return finish({
36
47
  success: false,
37
48
  status: 'error',
38
49
  message: `Checkout timed out after ${CHECKOUT_HARD_TIMEOUT_MS / 1000}s. The merchant page may be too slow or blocking automation.`,
39
- };
50
+ }, secrets);
40
51
  }
41
- const errMsg = err instanceof Error ? err.message : String(err);
42
- 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);
43
58
  }
44
59
  finally {
45
60
  if (browser)
46
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);
47
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;
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);
48
197
  }
49
198
  // ============================================================
50
199
  // HELPER: Smart fill — handles both <input> and <select>
51
200
  // Prevents crash when dropdown uses <select> instead of <input>
52
201
  // ============================================================
53
- async function smartFill(el, value) {
202
+ async function smartFill(gate, el, value, kind) {
54
203
  try {
204
+ if (!(await gate.allows(el, kind)))
205
+ return false;
55
206
  const tag = await el.evaluate(e => e.tagName.toLowerCase());
56
207
  // Card data only ever goes into a form field built to hold it: an <input> of a
57
208
  // text-like type, or a <select> (expiry). Never a textarea, a hidden or email
@@ -94,21 +245,32 @@ async function smartFill(el, value) {
94
245
  }
95
246
  }
96
247
  catch {
248
+ // Never rethrow: a Playwright fill error quotes the value it was typing.
97
249
  return false;
98
250
  }
99
251
  }
100
252
  /** Try each selector in order, smartFill the first match */
101
- async function tryFillField(page, selectors, value) {
253
+ async function tryFillField(gate, ctx, selectors, value, kind) {
102
254
  for (const selector of selectors) {
103
- const el = await page.$(selector);
255
+ const el = await ctx.$(selector).catch(() => null);
104
256
  if (el) {
105
- const ok = await smartFill(el, value);
257
+ const ok = await smartFill(gate, el, value, kind);
106
258
  if (ok)
107
259
  return true;
108
260
  }
109
261
  }
110
262
  return false;
111
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
+ }
112
274
  // ============================================================
113
275
  // CONFIRMATION DETECTION — the core of "filled ≠ paid"
114
276
  // After Pay is clicked we must observe a REAL outcome before
@@ -125,9 +287,67 @@ const SUCCESS_TEXT_RE = /thank you for your (?:order|purchase|payment)|your orde
125
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;
126
288
  // Real order/confirmation number to use as receipt_id (only when confirmed)
127
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
+ }
128
348
  /**
129
349
  * Watches the page after Pay is clicked and classifies the real outcome.
130
- * 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
131
351
  * signal is seen or CONFIRM_WAIT_MS elapses. Default (no signal) is the
132
352
  * SAFE 'unconfirmed' — caller must NOT burn the token on that.
133
353
  */
@@ -147,11 +367,11 @@ async function detectPaymentOutcome(page, checkoutUrl) {
147
367
  let bodyText = '';
148
368
  try {
149
369
  currentUrl = page.url();
150
- bodyText = await page.evaluate(() => document.body?.innerText ?? '');
370
+ bodyText = await readableText(page);
151
371
  }
152
372
  catch {
153
373
  // page is mid-navigation — wait and retry
154
- await page.waitForTimeout(CONFIRM_POLL_MS);
374
+ await page.waitForTimeout(CONFIRM_POLL_MS).catch(() => { });
155
375
  continue;
156
376
  }
157
377
  // Decline is a definitive negative — check first.
@@ -173,7 +393,7 @@ async function detectPaymentOutcome(page, checkoutUrl) {
173
393
  const m = bodyText.match(RECEIPT_RE);
174
394
  return { kind: 'confirmed', receipt_id: m?.[1] };
175
395
  }
176
- await page.waitForTimeout(CONFIRM_POLL_MS);
396
+ await page.waitForTimeout(CONFIRM_POLL_MS).catch(() => { });
177
397
  }
178
398
  // No clear signal within the window — safe default, caller will NOT burn.
179
399
  return { kind: 'unconfirmed' };
@@ -204,8 +424,23 @@ function outcomeToResult(outcome, fieldNote) {
204
424
  };
205
425
  }
206
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
+ }
207
441
  /** Internal implementation — called by fillCheckoutForm inside a timeout wrapper */
208
442
  async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
443
+ const gate = new CardGate(page, cardData.merchant_domain);
209
444
  try {
210
445
  // ✅ FIX: Skip navigation if page already loaded (Single Browser reuse from auto_pay_checkout)
211
446
  // Prevents double-navigate which would reload page and lose cart/session state.
@@ -238,6 +473,8 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
238
473
  // ============================================================
239
474
  if (hints?.pre_steps && hints.pre_steps.length > 0) {
240
475
  for (const selector of hints.pre_steps) {
476
+ if (!isPlainCss(selector))
477
+ continue;
241
478
  try {
242
479
  const el = await page.$(selector);
243
480
  if (el && await el.isVisible()) {
@@ -248,103 +485,86 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
248
485
  catch { /* non-fatal — continue */ }
249
486
  }
250
487
  }
251
- // 🔒 DOMAIN LOCK — last look before the card is typed. Navigation and
252
- // pre_steps may have moved us; the card goes only on its own store or a
253
- // hosted payment page that store handed off to (lib/domain-lock.ts).
254
- const lock = (0, domain_lock_js_1.checkPaymentPage)(page.url(), cardData.merchant_domain);
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();
255
492
  if (!lock.ok) {
256
493
  return { success: false, status: "blocked", message: lock.reason };
257
494
  }
258
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
+ };
259
501
  // ============================================================
260
502
  // STRATEGY 0.5: Agent-provided selectors (from get_merchant_hints)
261
503
  // Tried first — agent already read the DOM and knows exact locations.
262
- // Supports iframe_selector: if provided, card fields are searched INSIDE
263
- // 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).
264
508
  // Name on card is always searched on the main page (outside iframe).
265
- // Falls through to Strategy 1 if nothing matched.
509
+ // Falls through to Strategy 1 if the card number could not be placed.
266
510
  // ============================================================
267
511
  if (hints && (hints.card_selector || hints.exp_selector || hints.cvv_selector)) {
268
- const hintFillResults = [];
269
512
  let cardContexts = [page];
270
513
  if (hints.iframe_selector) {
271
- const matchingFrames = page.frames().filter((f) => f.name().includes(hints.iframe_selector) &&
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) &&
272
519
  (0, domain_lock_js_1.isTrustedCardFrame)(f.url(), cardData.merchant_domain));
273
- if (matchingFrames.length > 0)
274
- cardContexts = matchingFrames;
275
520
  }
276
- // Card number
277
- if (hints.card_selector) {
278
- for (const ctx of cardContexts) {
279
- const el = await ctx.$(hints.card_selector);
280
- if (el) {
281
- hintFillResults.push(await smartFill(el, cardData.number));
282
- break;
283
- }
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);
284
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;
285
535
  }
286
- // Expiry combined (with space-padded slash for Shopify: "MM / YY")
287
536
  if (hints.exp_selector) {
288
- const expiryVal = `${cardData.exp_month} / ${cardData.exp_year.slice(-2)}`;
289
- for (const ctx of cardContexts) {
290
- const el = await ctx.$(hints.exp_selector);
291
- if (el) {
292
- hintFillResults.push(await smartFill(el, expiryVal));
293
- break;
294
- }
295
- }
296
- }
297
- // Expiry split month/year
298
- if (!hints.exp_selector && hints.exp_month_selector) {
299
- for (const ctx of cardContexts) {
300
- const elM = await ctx.$(hints.exp_month_selector);
301
- if (elM) {
302
- hintFillResults.push(await smartFill(elM, cardData.exp_month));
303
- break;
304
- }
305
- }
306
- if (hints.exp_year_selector) {
307
- for (const ctx of cardContexts) {
308
- const elY = await ctx.$(hints.exp_year_selector);
309
- if (elY) {
310
- hintFillResults.push(await smartFill(elY, cardData.exp_year));
311
- break;
312
- }
313
- }
314
- }
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++;
315
540
  }
316
- // CVV
317
- if (hints.cvv_selector) {
318
- for (const ctx of cardContexts) {
319
- const el = await ctx.$(hints.cvv_selector);
320
- if (el) {
321
- hintFillResults.push(await smartFill(el, cardData.cvv));
322
- break;
323
- }
324
- }
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++;
325
546
  }
547
+ if (await fillHint(hints.cvv_selector, cardData.cvv, 'cvv', cardContexts))
548
+ hintFilled++;
326
549
  // Name on card — ALWAYS on main page (outside iframe for Shopify/most platforms)
327
- if (hints.name_selector) {
328
- const el = await page.$(hints.name_selector);
329
- if (el) {
330
- hintFillResults.push(await smartFill(el, cardData.name));
331
- }
332
- }
333
- const hintSuccesses = hintFillResults.filter(Boolean).length;
334
- if (hintSuccesses > 0) {
335
- 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;
336
557
  const modeNote = `${filledFields} fields injected via agent hints${hints.iframe_selector ? ' (iframe mode)' : ''}.`;
337
558
  // Must actually submit to have any chance of a real payment.
338
559
  let clicked = false;
339
- if (hints.submit_selector) {
340
- try {
341
- const btn = await page.$(hints.submit_selector);
342
- if (btn && await btn.isVisible()) {
343
- await btn.click();
344
- clicked = true;
345
- }
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';
346
567
  }
347
- catch { /* non-fatal */ }
348
568
  }
349
569
  if (!clicked) {
350
570
  // Fields filled but no submit happened → NOT a payment. Do not fabricate success.
@@ -359,7 +579,7 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
359
579
  const outcome = await detectPaymentOutcome(page, checkoutUrl);
360
580
  return outcomeToResult(outcome, modeNote);
361
581
  }
362
- // 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
363
583
  }
364
584
  // ============================================================
365
585
  // STRATEGY 1: Standard HTML form fields
@@ -435,89 +655,79 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
435
655
  ],
436
656
  };
437
657
  // Card Number
438
- if (await tryFillField(page, S.number, cardData.number))
658
+ if (await tryFillField(gate, page, S.number, cardData.number, 'number')) {
439
659
  filledFields++;
660
+ cardNumberFilled = true;
661
+ }
440
662
  // Expiry: try combined MM/YY first
441
663
  const expiryValue = `${cardData.exp_month}/${cardData.exp_year.slice(-2)}`;
442
- let expiryFilled = await tryFillField(page, S.expiry, expiryValue);
664
+ let expiryFilled = await tryFillField(gate, page, S.expiry, expiryValue, 'exp');
443
665
  if (expiryFilled)
444
666
  filledFields++;
445
667
  // Expiry: fallback to separate month + year (works with both <input> AND <select>)
446
668
  if (!expiryFilled) {
447
- if (await tryFillField(page, S.exp_month, cardData.exp_month))
669
+ if (await tryFillField(gate, page, S.exp_month, cardData.exp_month, 'exp'))
448
670
  filledFields++;
449
- if (await tryFillField(page, S.exp_year, cardData.exp_year))
671
+ if (await tryFillField(gate, page, S.exp_year, cardData.exp_year, 'exp'))
450
672
  filledFields++;
451
673
  }
452
674
  // CVV
453
- if (await tryFillField(page, S.cvv, cardData.cvv))
675
+ if (await tryFillField(gate, page, S.cvv, cardData.cvv, 'cvv'))
454
676
  filledFields++;
455
677
  // Name on Card
456
- if (await tryFillField(page, S.name, cardData.name))
678
+ if (await tryFillField(gate, page, S.name, cardData.name, 'name'))
457
679
  filledFields++;
680
+ const stopped1 = stopIfMoved();
681
+ if (stopped1)
682
+ return stopped1;
458
683
  // ============================================================
459
684
  // STRATEGY 2: Stripe Elements (iframe-based)
460
685
  // Stripe renders payment inputs inside iframes from js.stripe.com.
461
- // Some merchants use __privateStripeFrame* named frames.
462
686
  // Stripe has 2 modes:
463
687
  // - Unified: 1 iframe with all fields (card, exp, cvc in one)
464
688
  // - Split: separate iframes per field (cardNumber, cardExpiry, cardCvc)
465
689
  // We handle both by scanning ALL matching Stripe frames.
466
690
  // ============================================================
467
- if (filledFields === 0) {
691
+ if (!cardNumberFilled) {
692
+ await page.waitForLoadState("load", { timeout: 10_000 }).catch(() => { });
468
693
  // Recognised by the frame's real origin, never by its name or a substring of
469
694
  // its URL: any frame can call itself __privateStripeFrame or carry
470
695
  // "js.stripe.com" in a query string (audit MCP-03 / N3).
471
696
  const stripeFrames = page.frames().filter((f) => {
472
697
  try {
473
- const host = new URL(f.url()).hostname;
474
- return host === 'stripe.com' || host.endsWith('.stripe.com');
698
+ const u = new URL(f.url());
699
+ return u.protocol === 'https:' && (u.hostname === 'stripe.com' || u.hostname.endsWith('.stripe.com'));
475
700
  }
476
701
  catch {
477
702
  return false;
478
703
  }
479
704
  });
480
705
  for (const frame of stripeFrames) {
481
- // Card Number
482
- for (const sel of [
706
+ if (await tryFillField(gate, frame, [
483
707
  'input[name="cardnumber"]',
484
708
  'input[autocomplete="cc-number"]',
485
709
  'input[data-elements-stable-field-name="cardNumber"]',
486
- ]) {
487
- const el = await frame.$(sel);
488
- if (el) {
489
- await el.fill(cardData.number);
490
- filledFields++;
491
- break;
492
- }
710
+ ], cardData.number, 'number')) {
711
+ filledFields++;
712
+ cardNumberFilled = true;
493
713
  }
494
714
  // Expiry (Stripe uses MM/YY without slash)
495
- for (const sel of [
715
+ if (await tryFillField(gate, frame, [
496
716
  'input[name="exp-date"]',
497
717
  'input[autocomplete="cc-exp"]',
498
718
  'input[data-elements-stable-field-name="cardExpiry"]',
499
- ]) {
500
- const el = await frame.$(sel);
501
- if (el) {
502
- await el.fill(`${cardData.exp_month}${cardData.exp_year.slice(-2)}`);
503
- filledFields++;
504
- break;
505
- }
506
- }
507
- // CVC
508
- for (const sel of [
719
+ ], `${cardData.exp_month}${cardData.exp_year.slice(-2)}`, 'exp'))
720
+ filledFields++;
721
+ if (await tryFillField(gate, frame, [
509
722
  'input[name="cvc"]',
510
723
  'input[autocomplete="cc-csc"]',
511
724
  'input[data-elements-stable-field-name="cardCvc"]',
512
- ]) {
513
- const el = await frame.$(sel);
514
- if (el) {
515
- await el.fill(cardData.cvv);
516
- filledFields++;
517
- break;
518
- }
519
- }
725
+ ], cardData.cvv, 'cvv'))
726
+ filledFields++;
520
727
  }
728
+ const stopped2 = stopIfMoved();
729
+ if (stopped2)
730
+ return stopped2;
521
731
  }
522
732
  if (filledFields === 0) {
523
733
  return {
@@ -525,11 +735,12 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
525
735
  status: 'no_fields',
526
736
  message: "Could not detect any credit card fields on this page. " +
527
737
  (landedElsewhere
528
- ? `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. " +
529
739
  "Z-Zero opens its OWN fresh browser, so checkout_url must be resumable on its own " +
530
740
  "(e.g. a Shopify/Etsy checkout-token URL), not a page that needs the agent's logged-in session. "
531
741
  : "") +
532
742
  "The checkout form may use an unsupported format, or the page requires a logged-in session.",
743
+ ...(landedElsewhere ? { page_detail: `landed on: ${landedUrl}` } : {}),
533
744
  };
534
745
  }
535
746
  // ============================================================
@@ -545,9 +756,13 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
545
756
  ];
546
757
  let clicked = false;
547
758
  for (const selector of payButtonSelectors) {
548
- const btn = await page.$(selector);
549
- if (btn && (await btn.isVisible())) {
550
- 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') {
551
766
  clicked = true;
552
767
  break;
553
768
  }
@@ -568,14 +783,15 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
568
783
  return outcomeToResult(outcome, fieldNote);
569
784
  }
570
785
  catch (error) {
571
- const errMsg = error instanceof Error ? error.message : String(error);
572
786
  return {
573
787
  success: false,
574
788
  status: 'error',
575
- message: `Payment failed: ${errMsg}`,
789
+ message: 'The browser failed during the checkout attempt.',
790
+ page_detail: error instanceof Error ? error.message : String(error),
576
791
  };
577
792
  }
578
793
  finally {
794
+ gate.dispose();
579
795
  // ============================================================
580
796
  // RAM WIPE - Critical security step
581
797
  // ============================================================