z-zero-mcp-server 1.11.0 → 1.12.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.
@@ -2,11 +2,14 @@
2
2
  // Playwright Bridge - The "Invisible Hand"
3
3
  // Securely injects card data into checkout forms without exposing it to AI
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.PAY_WORDS_RE = exports.APPLY_WORDS_RE = void 0;
5
6
  exports.fillCheckoutForm = fillCheckoutForm;
7
+ exports.hideDealCode = hideDealCode;
6
8
  const with_timeout_js_1 = require("./lib/with-timeout.js");
7
9
  const browser_js_1 = require("./lib/browser.js");
8
10
  const domain_lock_js_1 = require("./lib/domain-lock.js");
9
11
  const failure_taxonomy_js_1 = require("./failure_taxonomy.js");
12
+ const extract_total_price_js_1 = require("./lib/extract-total-price.js");
10
13
  const CHECKOUT_HARD_TIMEOUT_MS = 60_000; // 60s absolute cap — prevents slow-loris attacks
11
14
  const PAGE_DETAIL_MAX = 300;
12
15
  /**
@@ -19,12 +22,48 @@ const PAGE_DETAIL_MAX = 300;
19
22
  * can echo the number back as its "order number". Every string leaving here goes
20
23
  * through finish(), which strips this card's own number and CVV, then every
21
24
  * other card-shaped number.
25
+ *
26
+ * `deal` (Agent Deal orders): before any card field is touched, in this same isolated
27
+ * browser, the order's single-use discount code is typed into the store's discount field
28
+ * and the page total is checked against the card amount. No field, a refused code, or a
29
+ * total above the card amount → the card is NOT typed (status 'deal_not_applied'). The
30
+ * code is a secret like the card number and is stripped from everything returned too.
22
31
  */
23
- async function fillCheckoutForm(checkoutUrl, cardData, existingPage, hints) {
32
+ async function fillCheckoutForm(checkoutUrl, cardData, existingPage, hints, deal) {
24
33
  // Kept only to scrub output; the bridge wipes cardData itself.
25
- const secrets = { number: cardData.number, cvv: cardData.cvv };
34
+ const secrets = { number: cardData.number, cvv: cardData.cvv, code: deal?.code ?? undefined };
35
+ const dealState = {};
26
36
  let browser = null;
27
37
  let page;
38
+ const lockedDomain = cardData.merchant_domain;
39
+ /**
40
+ * What becomes of the deal code after an attempt that was NOT confirmed (founder decision
41
+ * 17/11/2026 — a code must not stay usable after a payment that did not happen):
42
+ *
43
+ * 'release' nothing was submitted, or the shop said no outright. No order can exist, so
44
+ * the code is taken back at once: off the checkout if the page has a control
45
+ * for it (below, best effort), and the caller asks the server to delete it at
46
+ * the shop.
47
+ * 'hold' Pay was pressed (or may have been) and the shop did not say "declined":
48
+ * status 'unconfirmed', or a browser error / timeout after the press. An order
49
+ * MAY exist at the shop with this code on it. Taking the code off the page or
50
+ * deleting it now would destroy the one thing that tells the two cases apart —
51
+ * so it is left exactly as it is until the order's fate is known (the server's
52
+ * REVIEW road: the order sweep and the close hooks ask the shop whether the
53
+ * code was used).
54
+ */
55
+ const settleDealCode = async (r) => {
56
+ if (!deal || deal.code === null || (r.success && r.status === 'confirmed'))
57
+ return r;
58
+ const orderMayExist = dealState.payPressed === true && r.status !== 'declined';
59
+ if (orderMayExist)
60
+ return { ...r, deal_code_next: 'hold' };
61
+ if (dealState.codeEntered && page) {
62
+ // Never lets a failure here replace or delay the real result by more than a moment.
63
+ await (0, with_timeout_js_1.withTimeout)(removeDealCodeFromPage(page, lockedDomain, deal.code), DEAL_REMOVE_TIMEOUT_MS, 'removeDealCode').catch(() => { });
64
+ }
65
+ return { ...r, deal_code_next: 'release' };
66
+ };
28
67
  try {
29
68
  if (existingPage) {
30
69
  page = existingPage;
@@ -34,27 +73,28 @@ async function fillCheckoutForm(checkoutUrl, cardData, existingPage, hints) {
34
73
  const context = await browser.newContext();
35
74
  page = await context.newPage();
36
75
  }
37
- const result = await (0, with_timeout_js_1.withTimeout)(_fillCheckoutFormInner(page, checkoutUrl, cardData, hints), CHECKOUT_HARD_TIMEOUT_MS, 'fillCheckoutForm', async () => {
76
+ const result = await (0, with_timeout_js_1.withTimeout)(_fillCheckoutFormInner(page, checkoutUrl, cardData, hints, deal, dealState), CHECKOUT_HARD_TIMEOUT_MS, 'fillCheckoutForm', async () => {
38
77
  console.error('[PLAYWRIGHT] ⚠️ Hard timeout hit — force-closing browser');
39
78
  if (browser)
40
79
  await browser.close().catch(() => { });
41
80
  });
42
- return finish(result, secrets);
81
+ // Deal orders: the total read off the page after the code was applied.
82
+ return finish(await settleDealCode(dealState.total !== undefined ? { ...result, amount: dealState.total } : result), secrets);
43
83
  }
44
84
  catch (err) {
45
85
  if (err instanceof with_timeout_js_1.TimeoutError) {
46
- return finish({
86
+ return finish(await settleDealCode({
47
87
  success: false,
48
88
  status: 'error',
49
89
  message: `Checkout timed out after ${CHECKOUT_HARD_TIMEOUT_MS / 1000}s. The merchant page may be too slow or blocking automation.`,
50
- }, secrets);
90
+ }), secrets);
51
91
  }
52
- return finish({
92
+ return finish(await settleDealCode({
53
93
  success: false,
54
94
  status: 'error',
55
95
  message: 'The browser failed during the checkout attempt.',
56
96
  page_detail: err instanceof Error ? err.message : String(err),
57
- }, secrets);
97
+ }), secrets);
58
98
  }
59
99
  finally {
60
100
  if (browser)
@@ -62,16 +102,33 @@ async function fillCheckoutForm(checkoutUrl, cardData, existingPage, hints) {
62
102
  // Wipe the copy too: fill is over, nothing needs the values any more.
63
103
  secrets.number = "";
64
104
  secrets.cvv = "";
105
+ secrets.code = undefined;
65
106
  }
66
107
  }
67
- /** Last stop before a result leaves the bridge: no card value in any string. */
108
+ /**
109
+ * Cut a deal code out of a text, however the page spelled it: any letter case, the dashes
110
+ * kept, dropped, or turned into spaces. A page shows the applied code back ("ZZ-… applied"),
111
+ * and a Playwright error quotes the value it was typing.
112
+ */
113
+ function hideDealCode(text, code) {
114
+ if (!text || !code)
115
+ return text;
116
+ // Only letters and digits go into the pattern (a code is A–Z, 0–9 and dashes), so nothing needs escaping.
117
+ const parts = code.split("-").map((p) => p.replace(/[^A-Za-z0-9]/g, "")).filter(Boolean);
118
+ if (parts.length === 0)
119
+ return text;
120
+ return text.replace(new RegExp(parts.join("[\\s-]{0,3}"), "gi"), "[DEAL_CODE]");
121
+ }
122
+ /** Last stop before a result leaves the bridge: no card value and no deal code in any string. */
68
123
  function finish(r, secrets) {
69
- const out = { ...r, message: (0, failure_taxonomy_js_1.scrubCardValues)(r.message, secrets) };
124
+ // The code is cut out FIRST: card scrubbing must not chew a piece out of it and leave the rest readable.
125
+ const out = { ...r, message: (0, failure_taxonomy_js_1.scrubCardValues)(hideDealCode(r.message, secrets.code), secrets) };
70
126
  if (r.page_detail) {
71
- out.page_detail = (0, failure_taxonomy_js_1.scrubCardValues)(r.page_detail, secrets).slice(0, PAGE_DETAIL_MAX);
127
+ out.page_detail = (0, failure_taxonomy_js_1.scrubCardValues)(hideDealCode(r.page_detail, secrets.code), secrets).slice(0, PAGE_DETAIL_MAX);
72
128
  }
73
129
  if (r.receipt_id !== undefined) {
74
- out.receipt_id = cleanReceiptId(r.receipt_id, secrets);
130
+ // An "order number" that holds the code is dropped outright, like one that holds the card.
131
+ out.receipt_id = hideDealCode(r.receipt_id, secrets.code) === r.receipt_id ? cleanReceiptId(r.receipt_id, secrets) : undefined;
75
132
  }
76
133
  return out;
77
134
  }
@@ -279,6 +336,12 @@ function isPlainCss(selector) {
279
336
  // ============================================================
280
337
  const CONFIRM_WAIT_MS = 12_000; // total budget to watch for an outcome (well within the 60s hard cap)
281
338
  const CONFIRM_POLL_MS = 750;
339
+ /** Where a Shopify checkout keeps its card fields (seen on a live store, 26/11/2026). */
340
+ const SHOPIFY_CARD_PRESET = {
341
+ iframe_selector: "card-fields", card_selector: "#number", exp_selector: "#expiry",
342
+ cvv_selector: "#verification_value", name_selector: "#name", submit_selector: "#checkout-pay-button",
343
+ };
344
+ const RECEIPT_WAIT_MS = 6_000; // after a confirmation is seen: how long to wait for the order number to be drawn
282
345
  // URL of a post-payment page (we additionally require the URL to have moved off the checkout page)
283
346
  const SUCCESS_URL_RE = /thank[_-]?you|order[-_]?(?:received|confirmation|confirmed|complete|placed)|\/orders?\/|\/receipts?\/|payment[_-]?success|checkout\/success|confirmation/i;
284
347
  // Strong success phrases — deliberately specific so a checkout "Order summary" panel does NOT trigger it
@@ -390,8 +453,23 @@ async function detectPaymentOutcome(page, checkoutUrl) {
390
453
  const urlSignal = movedOff && SUCCESS_URL_RE.test(currentUrl);
391
454
  const textSignal = SUCCESS_TEXT_RE.test(bodyText);
392
455
  if (urlSignal || textSignal) {
393
- const m = bodyText.match(RECEIPT_RE);
394
- return { kind: 'confirmed', receipt_id: m?.[1] };
456
+ // The first candidate that looks like an order NUMBER (it holds a digit). The pattern
457
+ // alone also matches plain words after "order" — "Order summary", "Order discount" —
458
+ // and the first of those used to be returned as the receipt id.
459
+ const readReceipt = (text) => Array.from(text.matchAll(new RegExp(RECEIPT_RE.source, "gi"))).map((m) => m[1]).find((id) => /\d/.test(id));
460
+ let receipt = readReceipt(bodyText);
461
+ // The payment IS confirmed here; only the order number may still be missing. A
462
+ // thank-you page is often recognised by its URL before its text is drawn (Shopify:
463
+ // the URL moves to …/thank-you first, "Confirmation #A2J0GRR5J" appears a moment
464
+ // later) — the first real deal order came back with no number for that reason
465
+ // (26/11/2026). Give the number a short moment; with or without it, the answer
466
+ // stays 'confirmed'.
467
+ const receiptDeadline = Date.now() + RECEIPT_WAIT_MS;
468
+ while (!receipt && Date.now() < receiptDeadline) {
469
+ await page.waitForTimeout(CONFIRM_POLL_MS).catch(() => { });
470
+ receipt = readReceipt(await readableText(page).catch(() => ''));
471
+ }
472
+ return { kind: 'confirmed', receipt_id: receipt };
395
473
  }
396
474
  await page.waitForTimeout(CONFIRM_POLL_MS).catch(() => { });
397
475
  }
@@ -425,12 +503,16 @@ function outcomeToResult(outcome, fieldNote) {
425
503
  }
426
504
  }
427
505
  /** Click the pay button only while the page is still the one we locked to. */
428
- async function clickIfStillLocked(gate, btn) {
506
+ async function clickIfStillLocked(gate, btn, dealState) {
429
507
  const moved = gate.moved();
430
508
  if (moved)
431
509
  return moved;
432
510
  try {
433
511
  if (await btn.isVisible()) {
512
+ // Marked BEFORE the click: a click that throws may still have gone through, and
513
+ // "Pay may have been pressed" is what decides whether a deal code is taken back.
514
+ if (dealState)
515
+ dealState.payPressed = true;
434
516
  await btn.click();
435
517
  return 'clicked';
436
518
  }
@@ -438,8 +520,353 @@ async function clickIfStillLocked(gate, btn) {
438
520
  catch { /* covered, detached, … — treat as not clicked */ }
439
521
  return 'not_clicked';
440
522
  }
523
+ // ============================================================
524
+ // DEAL CODE — typing the single-use discount code (Agent Deal orders)
525
+ //
526
+ // The code is a secret: it is typed into ONE kind of place only — a visible text input on
527
+ // the main page of the locked store that is, by its own attributes, a discount / promo /
528
+ // coupon field. Never a frame, never a textarea or a search box, never a card field; a
529
+ // hint selector is held to the same rule. Then the page total is read — strictly: the row that
530
+ // says "Total", never "Subtotal", never struck-through text (lib/extract-total-price,
531
+ // extractCheckoutTotalStrict) — until it has dropped by the discount and is within the card
532
+ // amount, or the wait runs out. A total that cannot be read unmistakably stops the payment.
533
+ // ============================================================
534
+ const DISCOUNT_FIELD_SHAPE = /discount|coupon|promo|voucher|reduction|redeem|gift.?card/i;
535
+ const DISCOUNT_SELECTORS = [
536
+ 'input[name="reductions"]', // Shopify checkout
537
+ 'input[name*="discount" i]', 'input[id*="discount" i]', 'input[placeholder*="discount" i]', 'input[aria-label*="discount" i]',
538
+ 'input[name*="coupon" i]', 'input[id*="coupon" i]', 'input[placeholder*="coupon" i]', 'input[aria-label*="coupon" i]',
539
+ 'input[name*="promo" i]', 'input[id*="promo" i]', 'input[placeholder*="promo" i]', 'input[aria-label*="promo" i]',
540
+ ];
541
+ const DEAL_TOTAL_WAIT_MS = 10_000;
542
+ const DEAL_TOTAL_POLL_MS = 500;
543
+ // The page saying the code did not take. Deliberately specific to codes.
544
+ const CODE_REFUSED_RE = /(?:enter|use) a valid (?:discount|promo|coupon)|(?:discount|promo|coupon)(?: code)? (?:is(?:n.t| not) valid|is invalid|not valid|has expired|expired|couldn.t be (?:used|applied)|can.t be (?:used|applied)|isn.t available|not applicable|does(?:n.t| not) apply)|invalid (?:discount|promo|coupon)|unable to find a valid discount|minimum (?:purchase|order|subtotal)[^.]{0,40}(?:required|not met)/i;
545
+ async function isDiscountField(gate, page, el) {
546
+ if (gate.moved())
547
+ return false;
548
+ const frame = await el.ownerFrame().catch(() => null);
549
+ if (!frame || frame !== page.mainFrame())
550
+ return false;
551
+ const info = await el.evaluate((e) => {
552
+ const a = (n) => e.getAttribute(n) || "";
553
+ // The field's own <label> counts too: a floating-label theme has no placeholder or aria-label.
554
+ const labels = Array.from(e.labels ?? []).map((l) => (l.textContent || "").trim()).join(" ");
555
+ return {
556
+ tag: e.tagName.toLowerCase(),
557
+ type: (e.type || "text").toLowerCase(),
558
+ attrs: [a("autocomplete"), a("name"), a("id"), a("placeholder"), a("aria-label"), labels.slice(0, 200)].join(" "),
559
+ };
560
+ }).catch(() => null);
561
+ if (!info || info.tag !== "input" || !["text", "search"].includes(info.type))
562
+ return false;
563
+ if (!DISCOUNT_FIELD_SHAPE.test(info.attrs))
564
+ return false;
565
+ // A field that also reads as a card field is not where a code goes.
566
+ if (FIELD_SHAPE.number.test(info.attrs) || FIELD_SHAPE.cvv.test(info.attrs))
567
+ return false;
568
+ return isHumanVisible(el);
569
+ }
570
+ /** What a button says: its text, value or aria-label. */
571
+ const BUTTON_WORDS = (b) => (b.innerText || b.value || b.getAttribute("aria-label") || "").trim();
572
+ /** A button that applies a code says apply / redeem first — and is never the one that pays. */
573
+ exports.APPLY_WORDS_RE = /^(apply|redeem)\b/i;
574
+ exports.PAY_WORDS_RE = /\b(pay|submit|place|complete|continue|checkout|buy|order now|confirm)\b/i;
575
+ async function applyDealCode(page, gate, lockedDomain, deal, hints, dealState) {
576
+ const moved = () => {
577
+ const m = gate.moved();
578
+ return m && !m.ok ? { ok: false, blocked: true, reason: m.reason } : null;
579
+ };
580
+ const stop = moved();
581
+ if (stop)
582
+ return stop;
583
+ // The card may follow the store to a hosted payment page; the store's discount code may
584
+ // not (lib/domain-lock, checkDealCodePage). Asked here, and again at the moment of typing.
585
+ const onStore = () => {
586
+ const here = (0, domain_lock_js_1.checkDealCodePage)(page.url(), lockedDomain);
587
+ return here.ok ? null : { ok: false, reason: here.reason };
588
+ };
589
+ const away = deal.code === null ? null : onStore();
590
+ if (away)
591
+ return away;
592
+ const max = deal.maxTotal;
593
+ const within = (n) => n <= max + 0.005;
594
+ const usd = (n) => "$" + n.toFixed(2);
595
+ // The total is read STRICTLY (lib/extract-total-price, extractCheckoutTotalStrict): the row
596
+ // that says "Total" — never "Subtotal", never a struck-through old price, never a guess from
597
+ // the other prices on the page. Unreadable means stop. A hint (total_selector) can name the
598
+ // element when a checkout's total row cannot be found by its words.
599
+ const totalSelector = isPlainCss(hints?.total_selector) ? hints.total_selector : undefined;
600
+ // A hinted element is believed only while it AGREES with the row the page itself calls
601
+ // "Total", when there is one. A hint (from the shared hints, or from an agent that was
602
+ // talked into it) pointing at the Subtotal would otherwise pass the checks below on a
603
+ // number that is not what the card will be charged.
604
+ const readNow = async () => {
605
+ const byWords = await (0, extract_total_price_js_1.extractCheckoutTotalStrict)(page).catch(() => null);
606
+ if (!totalSelector)
607
+ return byWords;
608
+ const byHint = await (0, extract_total_price_js_1.extractCheckoutTotalStrict)(page, totalSelector).catch(() => null);
609
+ if (!byHint || !byWords)
610
+ return byHint;
611
+ return byHint.currency === byWords.currency && Math.abs(byHint.amount - byWords.amount) < 0.005 ? byHint : null;
612
+ };
613
+ /** The visible USD total, polled for up to `ms`. null = unreadable; "non_usd" = another currency. */
614
+ const readTotal = async (ms) => {
615
+ const until = Date.now() + ms;
616
+ let sawNonUsd = false;
617
+ for (;;) {
618
+ const price = await readNow();
619
+ if (price && price.currency === "USD")
620
+ return price.amount;
621
+ if (price)
622
+ sawNonUsd = true;
623
+ if (Date.now() >= until)
624
+ return sawNonUsd ? "non_usd" : null;
625
+ await page.waitForTimeout(DEAL_TOTAL_POLL_MS);
626
+ }
627
+ };
628
+ const NOT_USD = { ok: false, reason: "The checkout total is not shown in US dollars, so it could not be checked against the deal order. The card was NOT typed and nothing was charged." };
629
+ // 1. The total BEFORE the code: the page must not ask for more than the order was priced for.
630
+ // (It is also the number the drop is measured from — see step 3.)
631
+ const before = await readTotal(3_000);
632
+ if (before === "non_usd")
633
+ return NOT_USD;
634
+ if (before === null) {
635
+ return { ok: false, reason: "The checkout total could not be read, so it could not be checked against the deal order. The card was NOT typed and nothing was charged." };
636
+ }
637
+ if (before > deal.listTotal + 0.005) {
638
+ return {
639
+ ok: false,
640
+ reason: `The checkout total is ${usd(before)}, above the ${usd(deal.listTotal)} this deal order was priced for. ` +
641
+ "The card was NOT typed, the discount code was not used, and nothing was charged. The cart, shipping or price differs from the order: cancel the token and request a new one with the total the page shows now.",
642
+ };
643
+ }
644
+ // …and not much less either. The order was priced from the total the agent read on this
645
+ // page a moment ago; a "total" well under it is not the same number (a subtotal, another
646
+ // cart) and nothing measured from it would mean anything.
647
+ if (before < deal.listTotal * 0.95 - 0.005) {
648
+ return {
649
+ ok: false,
650
+ reason: `The checkout total reads ${usd(before)}, well below the ${usd(deal.listTotal)} this deal order was priced for. ` +
651
+ "The card was NOT typed, the discount code was not used, and nothing was charged. Check the cart and the total; if the page really shows a different total now, cancel the token and request a new one with it.",
652
+ };
653
+ }
654
+ if (deal.code === null) {
655
+ // A deal with nothing to type: the total as it stands must fit the card.
656
+ return within(before)
657
+ ? { ok: true, total: before }
658
+ : { ok: false, reason: `The checkout total is ${usd(before)}, above the card amount ${usd(max)}. The card was NOT typed and nothing was charged.` };
659
+ }
660
+ // 2. Type the code — into a discount field of the store's own page, nowhere else.
661
+ {
662
+ let field = null;
663
+ const candidates = [...(isPlainCss(hints?.discount_selector) ? [hints.discount_selector] : []), ...DISCOUNT_SELECTORS];
664
+ for (const selector of candidates) {
665
+ let els = [];
666
+ try {
667
+ els = (await page.$$(selector));
668
+ }
669
+ catch { /* a selector the page cannot run */ }
670
+ for (const el of els) {
671
+ if (await isDiscountField(gate, page, el)) {
672
+ field = el;
673
+ break;
674
+ }
675
+ }
676
+ if (field)
677
+ break;
678
+ }
679
+ if (!field) {
680
+ // No attribute gives it away: look for a field by its <label> ("Discount code", "Promo code" …).
681
+ let labels = [];
682
+ try {
683
+ labels = (await page.$$("label"));
684
+ }
685
+ catch { /* no labels */ }
686
+ for (const label of labels.slice(0, 200)) {
687
+ const says = await label.evaluate((l) => (l.textContent || "").trim().slice(0, 120)).catch(() => "");
688
+ if (!DISCOUNT_FIELD_SHAPE.test(says))
689
+ continue;
690
+ const control = (await label.evaluateHandle((l) => l.control).catch(() => null))?.asElement() ?? null;
691
+ if (control && await isDiscountField(gate, page, control)) {
692
+ field = control;
693
+ break;
694
+ }
695
+ }
696
+ }
697
+ if (!field) {
698
+ return {
699
+ ok: false,
700
+ reason: "No discount code field was found on the checkout page, so the deal discount could not be applied. " +
701
+ "The card was NOT typed and nothing was charged. If the field is behind a toggle (e.g. \"Show order summary\"), " +
702
+ "pass a pre_steps selector that opens it and a discount_selector hint, then try again.",
703
+ };
704
+ }
705
+ const gone = moved() ?? onStore();
706
+ if (gone)
707
+ return gone;
708
+ try {
709
+ // From here on the code has been at the page: whatever happens next, the caller
710
+ // has a code to take back if no payment follows (fillCheckoutForm).
711
+ dealState.codeEntered = true;
712
+ await field.fill(deal.code);
713
+ // The button that applies the code: the hinted one; else an "Apply" / "Redeem" button
714
+ // sitting with the field (many checkouts keep it disabled until text is typed, hence
715
+ // the short wait); else Enter in the field. Only a button whose OWN WORDS say
716
+ // apply / redeem is ever clicked here — never a Pay / Submit / Continue button.
717
+ // The hinted button is held to exactly that rule: a selector is a place to look,
718
+ // not permission to click whatever is there (a hint that named the Pay button
719
+ // would otherwise submit the order before the total was checked).
720
+ const mayApply = async (b) => {
721
+ if (!b)
722
+ return false;
723
+ const says = await b.evaluate(BUTTON_WORDS).catch(() => "");
724
+ return exports.APPLY_WORDS_RE.test(says) && !exports.PAY_WORDS_RE.test(says);
725
+ };
726
+ let applyBtn = isPlainCss(hints?.discount_apply_selector)
727
+ ? await page.$(hints.discount_apply_selector).catch(() => null) : null;
728
+ if (!(await mayApply(applyBtn)))
729
+ applyBtn = null;
730
+ if (!applyBtn) {
731
+ await page.waitForTimeout(150);
732
+ applyBtn = (await field.evaluateHandle((e) => {
733
+ const says = (b) => (b.innerText || b.value || b.getAttribute("aria-label") || "").trim();
734
+ let scope = e.closest("form") ?? e.parentElement;
735
+ for (let depth = 0; scope && depth < 4; depth++) {
736
+ const hit = Array.from(scope.querySelectorAll('button, input[type="submit"], input[type="button"], [role="button"]'))
737
+ .find((b) => /^(apply|redeem)\b/i.test(says(b)) && !b.disabled);
738
+ if (hit)
739
+ return hit;
740
+ if (scope.tagName === "FORM")
741
+ break;
742
+ scope = scope.parentElement;
743
+ }
744
+ return null;
745
+ }).catch(() => null))?.asElement() ?? null;
746
+ if (!(await mayApply(applyBtn)))
747
+ applyBtn = null;
748
+ }
749
+ if (applyBtn && (await applyBtn.ownerFrame().catch(() => null)) === page.mainFrame() && await applyBtn.isVisible().catch(() => false) && !gate.moved()) {
750
+ await applyBtn.click();
751
+ }
752
+ else {
753
+ await field.press("Enter");
754
+ }
755
+ }
756
+ catch {
757
+ // Never rethrow or quote: a Playwright error carries the value it was typing.
758
+ return { ok: false, reason: "The discount code could not be entered on the checkout page. The card was NOT typed and nothing was charged." };
759
+ }
760
+ }
761
+ // 3. Watch the total. The code counts as applied only when the total has DROPPED by the
762
+ // order's discount (a total that was already under the card amount proves nothing) AND
763
+ // is within the card amount. Otherwise: the page refuses the code, or time runs out.
764
+ const dropped = (n) => n <= before - deal.discount + 0.01;
765
+ let last = null;
766
+ let nonUsd = false;
767
+ const deadline = Date.now() + DEAL_TOTAL_WAIT_MS;
768
+ for (;;) {
769
+ const gone = moved();
770
+ if (gone)
771
+ return gone;
772
+ const price = await readNow();
773
+ if (price) {
774
+ nonUsd = price.currency !== "USD";
775
+ last = nonUsd ? null : price.amount;
776
+ if (last !== null && dropped(last) && within(last))
777
+ return { ok: true, total: last };
778
+ }
779
+ // The code is cut out of the WHOLE page text first, and only then is a piece taken.
780
+ // (Cutting the piece first could slice through the code — "…ZZ-ABCD" at the edge of
781
+ // the window — and what is left of it no longer matches, so it would pass the last
782
+ // scrub in finish() and reach the agent.)
783
+ const text = hideDealCode(await readableText(page).catch(() => ""), deal.code);
784
+ const refused = CODE_REFUSED_RE.exec(text);
785
+ if (refused) {
786
+ return {
787
+ ok: false,
788
+ reason: "The shop did not accept the deal's discount code. The card was NOT typed and nothing was charged.",
789
+ detail: text.slice(Math.max(0, refused.index - 60), refused.index + 160),
790
+ };
791
+ }
792
+ if (Date.now() >= deadline)
793
+ break;
794
+ await page.waitForTimeout(DEAL_TOTAL_POLL_MS);
795
+ }
796
+ if (nonUsd)
797
+ return NOT_USD;
798
+ if (last === null) {
799
+ return { ok: false, reason: "The checkout total could not be read after the discount code was entered, so it could not be checked against the card amount. The card was NOT typed and nothing was charged." };
800
+ }
801
+ if (!dropped(last)) {
802
+ return {
803
+ ok: false,
804
+ reason: `The discount code was entered but the checkout total did not come down (it shows ${usd(last)}; the deal takes ${usd(deal.discount)} off). ` +
805
+ "The card was NOT typed and nothing was charged. The code may not apply to this cart (different items or quantity than the deal order).",
806
+ };
807
+ }
808
+ return {
809
+ ok: false,
810
+ reason: `After the discount code the checkout total is ${usd(last)}, above the card amount ${usd(max)}. ` +
811
+ "The card was NOT typed and nothing was charged. The cart may differ from the deal order (items, quantity, shipping), or the price changed.",
812
+ };
813
+ }
814
+ // ============================================================
815
+ // DEAL CODE — taking it back off the checkout after an attempt that did not pay.
816
+ //
817
+ // Best effort, and only ever called when no order can exist (see settleDealCode in
818
+ // fillCheckoutForm). The page is the store's own (same rule as typing the code). The one
819
+ // thing clicked is a control whose own words say remove / delete / clear AND that is about
820
+ // the discount — it names the code, says "discount / coupon / promo / code", or is the bare
821
+ // "Remove" button sitting in the small element that shows the code. Never a control about
822
+ // items, the cart, an address or paying. Nothing here can change the result of the attempt:
823
+ // every failure is swallowed, and the server deletes the code at the shop regardless.
824
+ // ============================================================
825
+ const DEAL_REMOVE_TIMEOUT_MS = 4_000;
826
+ async function removeDealCodeFromPage(page, lockedDomain, code) {
827
+ try {
828
+ if (page.isClosed() || !(0, domain_lock_js_1.checkDealCodePage)(page.url(), lockedDomain).ok)
829
+ return false;
830
+ const control = (await page.evaluateHandle((theCode) => {
831
+ const flat = (t) => t.replace(/[\s-]/g, "").toUpperCase();
832
+ const want = flat(theCode);
833
+ // Its visible text, its value, its aria-label, its title — each on its own: an icon
834
+ // button reads "×" on the page and "Remove discount" to a screen reader.
835
+ const names = (b) => [b.innerText, b.value, b.getAttribute("aria-label"), b.getAttribute("title")]
836
+ .map((v) => (v || "").trim()).filter(Boolean);
837
+ for (const b of Array.from(document.querySelectorAll('button, [role="button"], input[type="button"], a'))) {
838
+ const said = names(b);
839
+ if (!said.some((w) => /^(remove|delete|clear)\b/i.test(w)))
840
+ continue;
841
+ const t = said.join(" ");
842
+ if (/\b(pay|submit|place|complete|continue|checkout|buy|item|product|cart|address|card|account)\b/i.test(t))
843
+ continue;
844
+ if (flat(t).includes(want) || /discount|coupon|promo|voucher|\bcode\b/i.test(t))
845
+ return b;
846
+ // A bare "Remove" / "×" button: only when its small container is the one showing the code.
847
+ const box = b.parentElement;
848
+ const around = box ? flat(box.textContent || "") : "";
849
+ if (around.length <= 120 && around.includes(want))
850
+ return b;
851
+ }
852
+ return null;
853
+ }, code)).asElement();
854
+ if (!control)
855
+ return false;
856
+ if ((await control.ownerFrame().catch(() => null)) !== page.mainFrame())
857
+ return false;
858
+ if (!(await control.isVisible().catch(() => false)))
859
+ return false;
860
+ await control.click({ timeout: 1_500 });
861
+ await page.waitForTimeout(300); // let the checkout take the removal in before the browser closes
862
+ return true;
863
+ }
864
+ catch {
865
+ return false; // never quote the error: a Playwright message can carry page text
866
+ }
867
+ }
441
868
  /** Internal implementation — called by fillCheckoutForm inside a timeout wrapper */
442
- async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
869
+ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints, deal, dealState = {}) {
443
870
  const gate = new CardGate(page, cardData.merchant_domain);
444
871
  try {
445
872
  // ✅ FIX: Skip navigation if page already loaded (Single Browser reuse from auto_pay_checkout)
@@ -492,6 +919,24 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
492
919
  if (!lock.ok) {
493
920
  return { success: false, status: "blocked", message: lock.reason };
494
921
  }
922
+ // ============================================================
923
+ // DEAL ORDER — the discount comes BEFORE the card (design: the card is for the
924
+ // discounted total, so a card typed without the discount can only be declined or
925
+ // overpay). Same browser, same locked page. Anything short of "the code is on the
926
+ // page and the total is within the card amount" stops here: no card field is touched.
927
+ // ============================================================
928
+ if (deal) {
929
+ const applied = await applyDealCode(page, gate, cardData.merchant_domain, deal, hints, dealState);
930
+ if (!applied.ok) {
931
+ return {
932
+ success: false,
933
+ status: applied.blocked ? "blocked" : "deal_not_applied",
934
+ message: applied.reason,
935
+ ...(applied.detail ? { page_detail: applied.detail } : {}),
936
+ };
937
+ }
938
+ dealState.total = applied.total;
939
+ }
495
940
  let filledFields = 0;
496
941
  let cardNumberFilled = false;
497
942
  const stopIfMoved = () => {
@@ -508,20 +953,54 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
508
953
  // Name on card is always searched on the main page (outside iframe).
509
954
  // Falls through to Strategy 1 if the card number could not be placed.
510
955
  // ============================================================
956
+ // A Shopify checkout is recognised from the page itself, so an agent that passes no
957
+ // card selectors still gets its card fields found. Shopify keeps every card field in
958
+ // its own frame (card-fields-number-…, -expiry-…, -verification_value-…, -name-…) served
959
+ // by its card host; the default search below does not look inside frames and answered
960
+ // no_fields on the first real deal order (26/11/2026). Selectors the agent did pass
961
+ // are kept — the preset only fills what is missing.
962
+ let cardFieldsFrom = 'agent hints';
963
+ if (!(hints && (hints.card_selector || hints.exp_selector || hints.cvv_selector))) {
964
+ await page.waitForLoadState("load", { timeout: 10_000 }).catch(() => { });
965
+ const shopifyCardFrames = page.frames().some((f) => f !== page.mainFrame() && /^card-fields-number/.test(f.name()) &&
966
+ (0, domain_lock_js_1.isTrustedCardFrame)(f.url(), cardData.merchant_domain));
967
+ if (shopifyCardFrames) {
968
+ hints = { ...SHOPIFY_CARD_PRESET, ...(hints ?? {}) };
969
+ cardFieldsFrom = "Z-ZERO's Shopify preset";
970
+ }
971
+ }
511
972
  if (hints && (hints.card_selector || hints.exp_selector || hints.cvv_selector)) {
512
973
  let cardContexts = [page];
513
- if (hints.iframe_selector) {
974
+ const frameName = hints.iframe_selector; // read once: closures below cannot rely on `hints` staying narrowed
975
+ if (frameName) {
514
976
  // Card frames load after the page; until then they sit at about:blank
515
977
  // and fail the origin check.
516
978
  await page.waitForLoadState("load", { timeout: 10_000 }).catch(() => { });
517
979
  cardContexts = page.frames().filter((f) => f !== page.mainFrame() &&
518
- f.name().includes(hints.iframe_selector) &&
980
+ f.name().includes(frameName) &&
519
981
  (0, domain_lock_js_1.isTrustedCardFrame)(f.url(), cardData.merchant_domain));
520
982
  }
983
+ // Which frame is FOR which field. A hosted card form can give every field its own
984
+ // frame and still build ALL the inputs into each of them (Shopify: the frames
985
+ // card-fields-number-…, -expiry-…, -verification_value-…, -name-… each hold #number,
986
+ // #expiry, #verification_value and #name; only the one the frame is named after is
987
+ // live). Taking the first frame that has the selector typed the expiry and the CVV
988
+ // into the dead copies inside the number frame. So the frame named for the field
989
+ // is tried first; the others keep their order behind it.
990
+ const FRAME_FOR = {
991
+ number: /number/i, exp: /expir/i, cvv: /verification|security|cvv|cvc|csc/i, name: /name/i,
992
+ };
993
+ const frameRank = (ctx, kind) => {
994
+ if (!frameName || ctx === page)
995
+ return 0;
996
+ const own = ctx.name().split(frameName).join("");
997
+ return FRAME_FOR[kind].test(own) ? 1 : 0;
998
+ };
521
999
  const fillHint = async (selector, value, kind, contexts) => {
522
1000
  if (!isPlainCss(selector))
523
1001
  return false;
524
- for (const ctx of contexts) {
1002
+ const inOrder = [...contexts].sort((a, b) => frameRank(b, kind) - frameRank(a, kind));
1003
+ for (const ctx of inOrder) {
525
1004
  const el = await ctx.$(selector).catch(() => null);
526
1005
  if (el)
527
1006
  return smartFill(gate, el, value, kind);
@@ -546,21 +1025,22 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
546
1025
  }
547
1026
  if (await fillHint(hints.cvv_selector, cardData.cvv, 'cvv', cardContexts))
548
1027
  hintFilled++;
549
- // Name on card — ALWAYS on main page (outside iframe for Shopify/most platforms)
550
- if (cardNumberFilled && await fillHint(hints.name_selector, cardData.name, 'name', [page]))
1028
+ // Name on card — in the card frames when the form keeps it there (Shopify does:
1029
+ // its own frame, and the checkout will not pay without it), else on the main page.
1030
+ if (cardNumberFilled && await fillHint(hints.name_selector, cardData.name, 'name', hints.iframe_selector ? [...cardContexts, page] : [page]))
551
1031
  hintFilled++;
552
1032
  const stopped = stopIfMoved();
553
1033
  if (stopped)
554
1034
  return stopped;
555
1035
  if (cardNumberFilled) {
556
1036
  filledFields += hintFilled;
557
- const modeNote = `${filledFields} fields injected via agent hints${hints.iframe_selector ? ' (iframe mode)' : ''}.`;
1037
+ const modeNote = `${filledFields} fields injected via ${cardFieldsFrom}${hints.iframe_selector ? ' (iframe mode)' : ''}.`;
558
1038
  // Must actually submit to have any chance of a real payment.
559
1039
  let clicked = false;
560
1040
  if (isPlainCss(hints.submit_selector)) {
561
1041
  const btn = await page.$(hints.submit_selector).catch(() => null);
562
1042
  if (btn) {
563
- const c = await clickIfStillLocked(gate, btn);
1043
+ const c = await clickIfStillLocked(gate, btn, dealState);
564
1044
  if (typeof c === 'object')
565
1045
  return { success: false, status: 'blocked', message: c.ok ? '' : c.reason };
566
1046
  clicked = c === 'clicked';
@@ -759,7 +1239,7 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
759
1239
  const btn = await page.$(selector).catch(() => null);
760
1240
  if (!btn)
761
1241
  continue;
762
- const c = await clickIfStillLocked(gate, btn);
1242
+ const c = await clickIfStillLocked(gate, btn, dealState);
763
1243
  if (typeof c === 'object')
764
1244
  return { success: false, status: 'blocked', message: c.ok ? '' : c.reason };
765
1245
  if (c === 'clicked') {