z-zero-mcp-server 1.11.0 → 1.12.1
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.
- package/README.md +13 -2
- package/dist/base_backend.d.ts +46 -1
- package/dist/base_backend.js +124 -10
- package/dist/failure_taxonomy.js +5 -0
- package/dist/index.js +358 -23
- package/dist/lib/deal-search.d.ts +75 -0
- package/dist/lib/deal-search.js +182 -0
- package/dist/lib/domain-lock.d.ts +8 -0
- package/dist/lib/domain-lock.js +20 -0
- package/dist/lib/extract-total-price.d.ts +27 -0
- package/dist/lib/extract-total-price.js +141 -0
- package/dist/playwright_bridge.d.ts +17 -2
- package/dist/playwright_bridge.js +565 -29
- package/dist/types.d.ts +36 -1
- package/package.json +2 -1
|
@@ -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
|
-
|
|
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
|
-
/**
|
|
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
|
-
|
|
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
|
-
|
|
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,18 @@ 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
|
+
// A shop that says it is still working on the payment gets more time, up to this much in all.
|
|
340
|
+
// Shopify shows "Wait while we redirect you." for longer than CONFIRM_WAIT_MS before it comes
|
|
341
|
+
// back with a refusal (seen on a real LIMIT_EXCEEDED decline, 26/11/2026): leaving at 12s
|
|
342
|
+
// reported a plain decline as 'unconfirmed'.
|
|
343
|
+
const CONFIRM_WAIT_BUSY_MS = 30_000;
|
|
344
|
+
const STILL_WORKING_RE = /wait while we redirect|processing (?:your )?(?:order|payment)|(?:please )?(?:wait|hold on)[^.]{0,40}(?:process|redirect|complet)|do(?:n(?:'|’)t| not) (?:refresh|close|leave)/i;
|
|
345
|
+
/** Where a Shopify checkout keeps its card fields (seen on a live store, 26/11/2026). */
|
|
346
|
+
const SHOPIFY_CARD_PRESET = {
|
|
347
|
+
iframe_selector: "card-fields", card_selector: "#number", exp_selector: "#expiry",
|
|
348
|
+
cvv_selector: "#verification_value", name_selector: "#name", submit_selector: "#checkout-pay-button",
|
|
349
|
+
};
|
|
350
|
+
const RECEIPT_WAIT_MS = 6_000; // after a confirmation is seen: how long to wait for the order number to be drawn
|
|
282
351
|
// URL of a post-payment page (we additionally require the URL to have moved off the checkout page)
|
|
283
352
|
const SUCCESS_URL_RE = /thank[_-]?you|order[-_]?(?:received|confirmation|confirmed|complete|placed)|\/orders?\/|\/receipts?\/|payment[_-]?success|checkout\/success|confirmation/i;
|
|
284
353
|
// Strong success phrases — deliberately specific so a checkout "Order summary" panel does NOT trigger it
|
|
@@ -287,6 +356,34 @@ const SUCCESS_TEXT_RE = /thank you for your (?:order|purchase|payment)|your orde
|
|
|
287
356
|
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;
|
|
288
357
|
// Real order/confirmation number to use as receipt_id (only when confirmed)
|
|
289
358
|
const RECEIPT_RE = /(?:order|confirmation|receipt)\s*(?:number|no\.?|#)?[:\s#]*([A-Z0-9][A-Z0-9-]{3,})/i;
|
|
359
|
+
// What a checkout says in its ERROR BANNER when the card did not go through, in words that
|
|
360
|
+
// do not name a "decline" (Shopify: "There was an issue processing your payment. Try again or
|
|
361
|
+
// use a different payment method."). Read ONLY from alert elements, never from the whole page:
|
|
362
|
+
// "use a different payment method" as ordinary page text means nothing. The first real issuer
|
|
363
|
+
// decline (26/11/2026, LIMIT_EXCEEDED) came back as 'unconfirmed' because of this gap.
|
|
364
|
+
const ALERT_DECLINE_RE = /(?:issue|problem|error|trouble) (?:processing|with) (?:your |the )?(?:payment|card|order)|payment (?:can(?:'|’)?t|cannot|couldn(?:'|’)?t|could not) be (?:processed|completed|verified)|(?:payment|card) details (?:couldn(?:'|’)?t|could not|can(?:'|’)?t|cannot) be verified|(?:try again or )?use a(?:nother| different) (?:payment method|card)|(?:card|payment)(?: was| has been)? (?:not authori[sz]ed|refused|rejected)|do(?:es)? not honou?r|exceed(?:s|ed)? (?:the |your )?(?:card )?(?:limit|balance)/i;
|
|
365
|
+
/**
|
|
366
|
+
* What the page's own error banners say right now: text of visible alert elements, joined and
|
|
367
|
+
* cut short. Page text — untrusted data for whoever reads it, and scrubbed of card values and
|
|
368
|
+
* deal codes before it leaves the bridge (finish()).
|
|
369
|
+
*/
|
|
370
|
+
async function readPageAlerts(page) {
|
|
371
|
+
return page.evaluate(() => {
|
|
372
|
+
const seen = new Set();
|
|
373
|
+
for (const el of Array.from(document.querySelectorAll('[role="alert"], [aria-live="assertive"], [role="status"][aria-live], [class*="error" i][class*="banner" i], [class*="notice" i][class*="error" i]'))) {
|
|
374
|
+
const r = el.getBoundingClientRect();
|
|
375
|
+
const st = getComputedStyle(el);
|
|
376
|
+
if (r.width < 1 || r.height < 1 || st.display === "none" || st.visibility === "hidden" || parseFloat(st.opacity || "1") < 0.1)
|
|
377
|
+
continue;
|
|
378
|
+
const t = (el.innerText || "").replace(/\s+/g, " ").trim();
|
|
379
|
+
if (t.length >= 8)
|
|
380
|
+
seen.add(t.slice(0, 200));
|
|
381
|
+
if (seen.size >= 3)
|
|
382
|
+
break;
|
|
383
|
+
}
|
|
384
|
+
return Array.from(seen).join(" | ").slice(0, 300);
|
|
385
|
+
}).catch(() => "");
|
|
386
|
+
}
|
|
290
387
|
/**
|
|
291
388
|
* The text a person looking at the page can actually read (audit T12 F6, M.7).
|
|
292
389
|
* innerText still counts text that is transparent, 0px, or parked off-screen —
|
|
@@ -361,7 +458,8 @@ async function detectPaymentOutcome(page, checkoutUrl) {
|
|
|
361
458
|
return checkoutUrl.split('?')[0];
|
|
362
459
|
}
|
|
363
460
|
})();
|
|
364
|
-
const
|
|
461
|
+
const started = Date.now();
|
|
462
|
+
let deadline = started + CONFIRM_WAIT_MS;
|
|
365
463
|
while (Date.now() < deadline) {
|
|
366
464
|
let currentUrl = '';
|
|
367
465
|
let bodyText = '';
|
|
@@ -375,8 +473,9 @@ async function detectPaymentOutcome(page, checkoutUrl) {
|
|
|
375
473
|
continue;
|
|
376
474
|
}
|
|
377
475
|
// Decline is a definitive negative — check first.
|
|
378
|
-
|
|
379
|
-
|
|
476
|
+
const alerts = await readPageAlerts(page);
|
|
477
|
+
if (DECLINE_TEXT_RE.test(bodyText) || ALERT_DECLINE_RE.test(alerts)) {
|
|
478
|
+
return { kind: 'declined', page_said: alerts || undefined };
|
|
380
479
|
}
|
|
381
480
|
const movedOff = (() => {
|
|
382
481
|
try {
|
|
@@ -390,16 +489,37 @@ async function detectPaymentOutcome(page, checkoutUrl) {
|
|
|
390
489
|
const urlSignal = movedOff && SUCCESS_URL_RE.test(currentUrl);
|
|
391
490
|
const textSignal = SUCCESS_TEXT_RE.test(bodyText);
|
|
392
491
|
if (urlSignal || textSignal) {
|
|
393
|
-
|
|
394
|
-
|
|
492
|
+
// The first candidate that looks like an order NUMBER (it holds a digit). The pattern
|
|
493
|
+
// alone also matches plain words after "order" — "Order summary", "Order discount" —
|
|
494
|
+
// and the first of those used to be returned as the receipt id.
|
|
495
|
+
const readReceipt = (text) => Array.from(text.matchAll(new RegExp(RECEIPT_RE.source, "gi"))).map((m) => m[1]).find((id) => /\d/.test(id));
|
|
496
|
+
let receipt = readReceipt(bodyText);
|
|
497
|
+
// The payment IS confirmed here; only the order number may still be missing. A
|
|
498
|
+
// thank-you page is often recognised by its URL before its text is drawn (Shopify:
|
|
499
|
+
// the URL moves to …/thank-you first, "Confirmation #A2J0GRR5J" appears a moment
|
|
500
|
+
// later) — the first real deal order came back with no number for that reason
|
|
501
|
+
// (26/11/2026). Give the number a short moment; with or without it, the answer
|
|
502
|
+
// stays 'confirmed'.
|
|
503
|
+
const receiptDeadline = Date.now() + RECEIPT_WAIT_MS;
|
|
504
|
+
while (!receipt && Date.now() < receiptDeadline) {
|
|
505
|
+
await page.waitForTimeout(CONFIRM_POLL_MS).catch(() => { });
|
|
506
|
+
receipt = readReceipt(await readableText(page).catch(() => ''));
|
|
507
|
+
}
|
|
508
|
+
return { kind: 'confirmed', receipt_id: receipt };
|
|
509
|
+
}
|
|
510
|
+
// Still working, says the page → keep watching (bounded).
|
|
511
|
+
if (STILL_WORKING_RE.test(alerts) || STILL_WORKING_RE.test(bodyText.slice(0, 4000))) {
|
|
512
|
+
deadline = Math.max(deadline, Math.min(started + CONFIRM_WAIT_BUSY_MS, Date.now() + 2 * CONFIRM_POLL_MS + 1));
|
|
395
513
|
}
|
|
396
514
|
await page.waitForTimeout(CONFIRM_POLL_MS).catch(() => { });
|
|
397
515
|
}
|
|
398
|
-
// No clear signal within the window — safe default, caller will NOT burn.
|
|
399
|
-
|
|
516
|
+
// No clear signal within the window — safe default, caller will NOT burn. Whatever the
|
|
517
|
+
// page's error banner says goes back with it, so the agent can judge for itself.
|
|
518
|
+
return { kind: 'unconfirmed', page_said: (await readPageAlerts(page)) || undefined };
|
|
400
519
|
}
|
|
401
520
|
/** Map a detected outcome to the PaymentResult shape (receipt only ever real). */
|
|
402
521
|
function outcomeToResult(outcome, fieldNote) {
|
|
522
|
+
const said = outcome.page_said ? { page_detail: `the page's error banner: ${outcome.page_said}` } : {};
|
|
403
523
|
switch (outcome.kind) {
|
|
404
524
|
case 'confirmed':
|
|
405
525
|
return {
|
|
@@ -413,6 +533,7 @@ function outcomeToResult(outcome, fieldNote) {
|
|
|
413
533
|
success: false,
|
|
414
534
|
status: 'declined',
|
|
415
535
|
message: `Payment was declined by the merchant. ${fieldNote}`,
|
|
536
|
+
...said,
|
|
416
537
|
};
|
|
417
538
|
case 'unconfirmed':
|
|
418
539
|
default:
|
|
@@ -421,16 +542,21 @@ function outcomeToResult(outcome, fieldNote) {
|
|
|
421
542
|
status: 'unconfirmed',
|
|
422
543
|
message: `Card details were submitted but no order confirmation was detected. ${fieldNote} ` +
|
|
423
544
|
`The token was NOT burned — verify whether the order went through before retrying (avoid double-charge).`,
|
|
545
|
+
...said,
|
|
424
546
|
};
|
|
425
547
|
}
|
|
426
548
|
}
|
|
427
549
|
/** Click the pay button only while the page is still the one we locked to. */
|
|
428
|
-
async function clickIfStillLocked(gate, btn) {
|
|
550
|
+
async function clickIfStillLocked(gate, btn, dealState) {
|
|
429
551
|
const moved = gate.moved();
|
|
430
552
|
if (moved)
|
|
431
553
|
return moved;
|
|
432
554
|
try {
|
|
433
555
|
if (await btn.isVisible()) {
|
|
556
|
+
// Marked BEFORE the click: a click that throws may still have gone through, and
|
|
557
|
+
// "Pay may have been pressed" is what decides whether a deal code is taken back.
|
|
558
|
+
if (dealState)
|
|
559
|
+
dealState.payPressed = true;
|
|
434
560
|
await btn.click();
|
|
435
561
|
return 'clicked';
|
|
436
562
|
}
|
|
@@ -438,8 +564,353 @@ async function clickIfStillLocked(gate, btn) {
|
|
|
438
564
|
catch { /* covered, detached, … — treat as not clicked */ }
|
|
439
565
|
return 'not_clicked';
|
|
440
566
|
}
|
|
567
|
+
// ============================================================
|
|
568
|
+
// DEAL CODE — typing the single-use discount code (Agent Deal orders)
|
|
569
|
+
//
|
|
570
|
+
// The code is a secret: it is typed into ONE kind of place only — a visible text input on
|
|
571
|
+
// the main page of the locked store that is, by its own attributes, a discount / promo /
|
|
572
|
+
// coupon field. Never a frame, never a textarea or a search box, never a card field; a
|
|
573
|
+
// hint selector is held to the same rule. Then the page total is read — strictly: the row that
|
|
574
|
+
// says "Total", never "Subtotal", never struck-through text (lib/extract-total-price,
|
|
575
|
+
// extractCheckoutTotalStrict) — until it has dropped by the discount and is within the card
|
|
576
|
+
// amount, or the wait runs out. A total that cannot be read unmistakably stops the payment.
|
|
577
|
+
// ============================================================
|
|
578
|
+
const DISCOUNT_FIELD_SHAPE = /discount|coupon|promo|voucher|reduction|redeem|gift.?card/i;
|
|
579
|
+
const DISCOUNT_SELECTORS = [
|
|
580
|
+
'input[name="reductions"]', // Shopify checkout
|
|
581
|
+
'input[name*="discount" i]', 'input[id*="discount" i]', 'input[placeholder*="discount" i]', 'input[aria-label*="discount" i]',
|
|
582
|
+
'input[name*="coupon" i]', 'input[id*="coupon" i]', 'input[placeholder*="coupon" i]', 'input[aria-label*="coupon" i]',
|
|
583
|
+
'input[name*="promo" i]', 'input[id*="promo" i]', 'input[placeholder*="promo" i]', 'input[aria-label*="promo" i]',
|
|
584
|
+
];
|
|
585
|
+
const DEAL_TOTAL_WAIT_MS = 10_000;
|
|
586
|
+
const DEAL_TOTAL_POLL_MS = 500;
|
|
587
|
+
// The page saying the code did not take. Deliberately specific to codes.
|
|
588
|
+
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;
|
|
589
|
+
async function isDiscountField(gate, page, el) {
|
|
590
|
+
if (gate.moved())
|
|
591
|
+
return false;
|
|
592
|
+
const frame = await el.ownerFrame().catch(() => null);
|
|
593
|
+
if (!frame || frame !== page.mainFrame())
|
|
594
|
+
return false;
|
|
595
|
+
const info = await el.evaluate((e) => {
|
|
596
|
+
const a = (n) => e.getAttribute(n) || "";
|
|
597
|
+
// The field's own <label> counts too: a floating-label theme has no placeholder or aria-label.
|
|
598
|
+
const labels = Array.from(e.labels ?? []).map((l) => (l.textContent || "").trim()).join(" ");
|
|
599
|
+
return {
|
|
600
|
+
tag: e.tagName.toLowerCase(),
|
|
601
|
+
type: (e.type || "text").toLowerCase(),
|
|
602
|
+
attrs: [a("autocomplete"), a("name"), a("id"), a("placeholder"), a("aria-label"), labels.slice(0, 200)].join(" "),
|
|
603
|
+
};
|
|
604
|
+
}).catch(() => null);
|
|
605
|
+
if (!info || info.tag !== "input" || !["text", "search"].includes(info.type))
|
|
606
|
+
return false;
|
|
607
|
+
if (!DISCOUNT_FIELD_SHAPE.test(info.attrs))
|
|
608
|
+
return false;
|
|
609
|
+
// A field that also reads as a card field is not where a code goes.
|
|
610
|
+
if (FIELD_SHAPE.number.test(info.attrs) || FIELD_SHAPE.cvv.test(info.attrs))
|
|
611
|
+
return false;
|
|
612
|
+
return isHumanVisible(el);
|
|
613
|
+
}
|
|
614
|
+
/** What a button says: its text, value or aria-label. */
|
|
615
|
+
const BUTTON_WORDS = (b) => (b.innerText || b.value || b.getAttribute("aria-label") || "").trim();
|
|
616
|
+
/** A button that applies a code says apply / redeem first — and is never the one that pays. */
|
|
617
|
+
exports.APPLY_WORDS_RE = /^(apply|redeem)\b/i;
|
|
618
|
+
exports.PAY_WORDS_RE = /\b(pay|submit|place|complete|continue|checkout|buy|order now|confirm)\b/i;
|
|
619
|
+
async function applyDealCode(page, gate, lockedDomain, deal, hints, dealState) {
|
|
620
|
+
const moved = () => {
|
|
621
|
+
const m = gate.moved();
|
|
622
|
+
return m && !m.ok ? { ok: false, blocked: true, reason: m.reason } : null;
|
|
623
|
+
};
|
|
624
|
+
const stop = moved();
|
|
625
|
+
if (stop)
|
|
626
|
+
return stop;
|
|
627
|
+
// The card may follow the store to a hosted payment page; the store's discount code may
|
|
628
|
+
// not (lib/domain-lock, checkDealCodePage). Asked here, and again at the moment of typing.
|
|
629
|
+
const onStore = () => {
|
|
630
|
+
const here = (0, domain_lock_js_1.checkDealCodePage)(page.url(), lockedDomain);
|
|
631
|
+
return here.ok ? null : { ok: false, reason: here.reason };
|
|
632
|
+
};
|
|
633
|
+
const away = deal.code === null ? null : onStore();
|
|
634
|
+
if (away)
|
|
635
|
+
return away;
|
|
636
|
+
const max = deal.maxTotal;
|
|
637
|
+
const within = (n) => n <= max + 0.005;
|
|
638
|
+
const usd = (n) => "$" + n.toFixed(2);
|
|
639
|
+
// The total is read STRICTLY (lib/extract-total-price, extractCheckoutTotalStrict): the row
|
|
640
|
+
// that says "Total" — never "Subtotal", never a struck-through old price, never a guess from
|
|
641
|
+
// the other prices on the page. Unreadable means stop. A hint (total_selector) can name the
|
|
642
|
+
// element when a checkout's total row cannot be found by its words.
|
|
643
|
+
const totalSelector = isPlainCss(hints?.total_selector) ? hints.total_selector : undefined;
|
|
644
|
+
// A hinted element is believed only while it AGREES with the row the page itself calls
|
|
645
|
+
// "Total", when there is one. A hint (from the shared hints, or from an agent that was
|
|
646
|
+
// talked into it) pointing at the Subtotal would otherwise pass the checks below on a
|
|
647
|
+
// number that is not what the card will be charged.
|
|
648
|
+
const readNow = async () => {
|
|
649
|
+
const byWords = await (0, extract_total_price_js_1.extractCheckoutTotalStrict)(page).catch(() => null);
|
|
650
|
+
if (!totalSelector)
|
|
651
|
+
return byWords;
|
|
652
|
+
const byHint = await (0, extract_total_price_js_1.extractCheckoutTotalStrict)(page, totalSelector).catch(() => null);
|
|
653
|
+
if (!byHint || !byWords)
|
|
654
|
+
return byHint;
|
|
655
|
+
return byHint.currency === byWords.currency && Math.abs(byHint.amount - byWords.amount) < 0.005 ? byHint : null;
|
|
656
|
+
};
|
|
657
|
+
/** The visible USD total, polled for up to `ms`. null = unreadable; "non_usd" = another currency. */
|
|
658
|
+
const readTotal = async (ms) => {
|
|
659
|
+
const until = Date.now() + ms;
|
|
660
|
+
let sawNonUsd = false;
|
|
661
|
+
for (;;) {
|
|
662
|
+
const price = await readNow();
|
|
663
|
+
if (price && price.currency === "USD")
|
|
664
|
+
return price.amount;
|
|
665
|
+
if (price)
|
|
666
|
+
sawNonUsd = true;
|
|
667
|
+
if (Date.now() >= until)
|
|
668
|
+
return sawNonUsd ? "non_usd" : null;
|
|
669
|
+
await page.waitForTimeout(DEAL_TOTAL_POLL_MS);
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
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." };
|
|
673
|
+
// 1. The total BEFORE the code: the page must not ask for more than the order was priced for.
|
|
674
|
+
// (It is also the number the drop is measured from — see step 3.)
|
|
675
|
+
const before = await readTotal(3_000);
|
|
676
|
+
if (before === "non_usd")
|
|
677
|
+
return NOT_USD;
|
|
678
|
+
if (before === null) {
|
|
679
|
+
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." };
|
|
680
|
+
}
|
|
681
|
+
if (before > deal.listTotal + 0.005) {
|
|
682
|
+
return {
|
|
683
|
+
ok: false,
|
|
684
|
+
reason: `The checkout total is ${usd(before)}, above the ${usd(deal.listTotal)} this deal order was priced for. ` +
|
|
685
|
+
"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.",
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
// …and not much less either. The order was priced from the total the agent read on this
|
|
689
|
+
// page a moment ago; a "total" well under it is not the same number (a subtotal, another
|
|
690
|
+
// cart) and nothing measured from it would mean anything.
|
|
691
|
+
if (before < deal.listTotal * 0.95 - 0.005) {
|
|
692
|
+
return {
|
|
693
|
+
ok: false,
|
|
694
|
+
reason: `The checkout total reads ${usd(before)}, well below the ${usd(deal.listTotal)} this deal order was priced for. ` +
|
|
695
|
+
"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.",
|
|
696
|
+
};
|
|
697
|
+
}
|
|
698
|
+
if (deal.code === null) {
|
|
699
|
+
// A deal with nothing to type: the total as it stands must fit the card.
|
|
700
|
+
return within(before)
|
|
701
|
+
? { ok: true, total: before }
|
|
702
|
+
: { ok: false, reason: `The checkout total is ${usd(before)}, above the card amount ${usd(max)}. The card was NOT typed and nothing was charged.` };
|
|
703
|
+
}
|
|
704
|
+
// 2. Type the code — into a discount field of the store's own page, nowhere else.
|
|
705
|
+
{
|
|
706
|
+
let field = null;
|
|
707
|
+
const candidates = [...(isPlainCss(hints?.discount_selector) ? [hints.discount_selector] : []), ...DISCOUNT_SELECTORS];
|
|
708
|
+
for (const selector of candidates) {
|
|
709
|
+
let els = [];
|
|
710
|
+
try {
|
|
711
|
+
els = (await page.$$(selector));
|
|
712
|
+
}
|
|
713
|
+
catch { /* a selector the page cannot run */ }
|
|
714
|
+
for (const el of els) {
|
|
715
|
+
if (await isDiscountField(gate, page, el)) {
|
|
716
|
+
field = el;
|
|
717
|
+
break;
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
if (field)
|
|
721
|
+
break;
|
|
722
|
+
}
|
|
723
|
+
if (!field) {
|
|
724
|
+
// No attribute gives it away: look for a field by its <label> ("Discount code", "Promo code" …).
|
|
725
|
+
let labels = [];
|
|
726
|
+
try {
|
|
727
|
+
labels = (await page.$$("label"));
|
|
728
|
+
}
|
|
729
|
+
catch { /* no labels */ }
|
|
730
|
+
for (const label of labels.slice(0, 200)) {
|
|
731
|
+
const says = await label.evaluate((l) => (l.textContent || "").trim().slice(0, 120)).catch(() => "");
|
|
732
|
+
if (!DISCOUNT_FIELD_SHAPE.test(says))
|
|
733
|
+
continue;
|
|
734
|
+
const control = (await label.evaluateHandle((l) => l.control).catch(() => null))?.asElement() ?? null;
|
|
735
|
+
if (control && await isDiscountField(gate, page, control)) {
|
|
736
|
+
field = control;
|
|
737
|
+
break;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
if (!field) {
|
|
742
|
+
return {
|
|
743
|
+
ok: false,
|
|
744
|
+
reason: "No discount code field was found on the checkout page, so the deal discount could not be applied. " +
|
|
745
|
+
"The card was NOT typed and nothing was charged. If the field is behind a toggle (e.g. \"Show order summary\"), " +
|
|
746
|
+
"pass a pre_steps selector that opens it and a discount_selector hint, then try again.",
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
const gone = moved() ?? onStore();
|
|
750
|
+
if (gone)
|
|
751
|
+
return gone;
|
|
752
|
+
try {
|
|
753
|
+
// From here on the code has been at the page: whatever happens next, the caller
|
|
754
|
+
// has a code to take back if no payment follows (fillCheckoutForm).
|
|
755
|
+
dealState.codeEntered = true;
|
|
756
|
+
await field.fill(deal.code);
|
|
757
|
+
// The button that applies the code: the hinted one; else an "Apply" / "Redeem" button
|
|
758
|
+
// sitting with the field (many checkouts keep it disabled until text is typed, hence
|
|
759
|
+
// the short wait); else Enter in the field. Only a button whose OWN WORDS say
|
|
760
|
+
// apply / redeem is ever clicked here — never a Pay / Submit / Continue button.
|
|
761
|
+
// The hinted button is held to exactly that rule: a selector is a place to look,
|
|
762
|
+
// not permission to click whatever is there (a hint that named the Pay button
|
|
763
|
+
// would otherwise submit the order before the total was checked).
|
|
764
|
+
const mayApply = async (b) => {
|
|
765
|
+
if (!b)
|
|
766
|
+
return false;
|
|
767
|
+
const says = await b.evaluate(BUTTON_WORDS).catch(() => "");
|
|
768
|
+
return exports.APPLY_WORDS_RE.test(says) && !exports.PAY_WORDS_RE.test(says);
|
|
769
|
+
};
|
|
770
|
+
let applyBtn = isPlainCss(hints?.discount_apply_selector)
|
|
771
|
+
? await page.$(hints.discount_apply_selector).catch(() => null) : null;
|
|
772
|
+
if (!(await mayApply(applyBtn)))
|
|
773
|
+
applyBtn = null;
|
|
774
|
+
if (!applyBtn) {
|
|
775
|
+
await page.waitForTimeout(150);
|
|
776
|
+
applyBtn = (await field.evaluateHandle((e) => {
|
|
777
|
+
const says = (b) => (b.innerText || b.value || b.getAttribute("aria-label") || "").trim();
|
|
778
|
+
let scope = e.closest("form") ?? e.parentElement;
|
|
779
|
+
for (let depth = 0; scope && depth < 4; depth++) {
|
|
780
|
+
const hit = Array.from(scope.querySelectorAll('button, input[type="submit"], input[type="button"], [role="button"]'))
|
|
781
|
+
.find((b) => /^(apply|redeem)\b/i.test(says(b)) && !b.disabled);
|
|
782
|
+
if (hit)
|
|
783
|
+
return hit;
|
|
784
|
+
if (scope.tagName === "FORM")
|
|
785
|
+
break;
|
|
786
|
+
scope = scope.parentElement;
|
|
787
|
+
}
|
|
788
|
+
return null;
|
|
789
|
+
}).catch(() => null))?.asElement() ?? null;
|
|
790
|
+
if (!(await mayApply(applyBtn)))
|
|
791
|
+
applyBtn = null;
|
|
792
|
+
}
|
|
793
|
+
if (applyBtn && (await applyBtn.ownerFrame().catch(() => null)) === page.mainFrame() && await applyBtn.isVisible().catch(() => false) && !gate.moved()) {
|
|
794
|
+
await applyBtn.click();
|
|
795
|
+
}
|
|
796
|
+
else {
|
|
797
|
+
await field.press("Enter");
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
catch {
|
|
801
|
+
// Never rethrow or quote: a Playwright error carries the value it was typing.
|
|
802
|
+
return { ok: false, reason: "The discount code could not be entered on the checkout page. The card was NOT typed and nothing was charged." };
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
// 3. Watch the total. The code counts as applied only when the total has DROPPED by the
|
|
806
|
+
// order's discount (a total that was already under the card amount proves nothing) AND
|
|
807
|
+
// is within the card amount. Otherwise: the page refuses the code, or time runs out.
|
|
808
|
+
const dropped = (n) => n <= before - deal.discount + 0.01;
|
|
809
|
+
let last = null;
|
|
810
|
+
let nonUsd = false;
|
|
811
|
+
const deadline = Date.now() + DEAL_TOTAL_WAIT_MS;
|
|
812
|
+
for (;;) {
|
|
813
|
+
const gone = moved();
|
|
814
|
+
if (gone)
|
|
815
|
+
return gone;
|
|
816
|
+
const price = await readNow();
|
|
817
|
+
if (price) {
|
|
818
|
+
nonUsd = price.currency !== "USD";
|
|
819
|
+
last = nonUsd ? null : price.amount;
|
|
820
|
+
if (last !== null && dropped(last) && within(last))
|
|
821
|
+
return { ok: true, total: last };
|
|
822
|
+
}
|
|
823
|
+
// The code is cut out of the WHOLE page text first, and only then is a piece taken.
|
|
824
|
+
// (Cutting the piece first could slice through the code — "…ZZ-ABCD" at the edge of
|
|
825
|
+
// the window — and what is left of it no longer matches, so it would pass the last
|
|
826
|
+
// scrub in finish() and reach the agent.)
|
|
827
|
+
const text = hideDealCode(await readableText(page).catch(() => ""), deal.code);
|
|
828
|
+
const refused = CODE_REFUSED_RE.exec(text);
|
|
829
|
+
if (refused) {
|
|
830
|
+
return {
|
|
831
|
+
ok: false,
|
|
832
|
+
reason: "The shop did not accept the deal's discount code. The card was NOT typed and nothing was charged.",
|
|
833
|
+
detail: text.slice(Math.max(0, refused.index - 60), refused.index + 160),
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
if (Date.now() >= deadline)
|
|
837
|
+
break;
|
|
838
|
+
await page.waitForTimeout(DEAL_TOTAL_POLL_MS);
|
|
839
|
+
}
|
|
840
|
+
if (nonUsd)
|
|
841
|
+
return NOT_USD;
|
|
842
|
+
if (last === null) {
|
|
843
|
+
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." };
|
|
844
|
+
}
|
|
845
|
+
if (!dropped(last)) {
|
|
846
|
+
return {
|
|
847
|
+
ok: false,
|
|
848
|
+
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). ` +
|
|
849
|
+
"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).",
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
return {
|
|
853
|
+
ok: false,
|
|
854
|
+
reason: `After the discount code the checkout total is ${usd(last)}, above the card amount ${usd(max)}. ` +
|
|
855
|
+
"The card was NOT typed and nothing was charged. The cart may differ from the deal order (items, quantity, shipping), or the price changed.",
|
|
856
|
+
};
|
|
857
|
+
}
|
|
858
|
+
// ============================================================
|
|
859
|
+
// DEAL CODE — taking it back off the checkout after an attempt that did not pay.
|
|
860
|
+
//
|
|
861
|
+
// Best effort, and only ever called when no order can exist (see settleDealCode in
|
|
862
|
+
// fillCheckoutForm). The page is the store's own (same rule as typing the code). The one
|
|
863
|
+
// thing clicked is a control whose own words say remove / delete / clear AND that is about
|
|
864
|
+
// the discount — it names the code, says "discount / coupon / promo / code", or is the bare
|
|
865
|
+
// "Remove" button sitting in the small element that shows the code. Never a control about
|
|
866
|
+
// items, the cart, an address or paying. Nothing here can change the result of the attempt:
|
|
867
|
+
// every failure is swallowed, and the server deletes the code at the shop regardless.
|
|
868
|
+
// ============================================================
|
|
869
|
+
const DEAL_REMOVE_TIMEOUT_MS = 4_000;
|
|
870
|
+
async function removeDealCodeFromPage(page, lockedDomain, code) {
|
|
871
|
+
try {
|
|
872
|
+
if (page.isClosed() || !(0, domain_lock_js_1.checkDealCodePage)(page.url(), lockedDomain).ok)
|
|
873
|
+
return false;
|
|
874
|
+
const control = (await page.evaluateHandle((theCode) => {
|
|
875
|
+
const flat = (t) => t.replace(/[\s-]/g, "").toUpperCase();
|
|
876
|
+
const want = flat(theCode);
|
|
877
|
+
// Its visible text, its value, its aria-label, its title — each on its own: an icon
|
|
878
|
+
// button reads "×" on the page and "Remove discount" to a screen reader.
|
|
879
|
+
const names = (b) => [b.innerText, b.value, b.getAttribute("aria-label"), b.getAttribute("title")]
|
|
880
|
+
.map((v) => (v || "").trim()).filter(Boolean);
|
|
881
|
+
for (const b of Array.from(document.querySelectorAll('button, [role="button"], input[type="button"], a'))) {
|
|
882
|
+
const said = names(b);
|
|
883
|
+
if (!said.some((w) => /^(remove|delete|clear)\b/i.test(w)))
|
|
884
|
+
continue;
|
|
885
|
+
const t = said.join(" ");
|
|
886
|
+
if (/\b(pay|submit|place|complete|continue|checkout|buy|item|product|cart|address|card|account)\b/i.test(t))
|
|
887
|
+
continue;
|
|
888
|
+
if (flat(t).includes(want) || /discount|coupon|promo|voucher|\bcode\b/i.test(t))
|
|
889
|
+
return b;
|
|
890
|
+
// A bare "Remove" / "×" button: only when its small container is the one showing the code.
|
|
891
|
+
const box = b.parentElement;
|
|
892
|
+
const around = box ? flat(box.textContent || "") : "";
|
|
893
|
+
if (around.length <= 120 && around.includes(want))
|
|
894
|
+
return b;
|
|
895
|
+
}
|
|
896
|
+
return null;
|
|
897
|
+
}, code)).asElement();
|
|
898
|
+
if (!control)
|
|
899
|
+
return false;
|
|
900
|
+
if ((await control.ownerFrame().catch(() => null)) !== page.mainFrame())
|
|
901
|
+
return false;
|
|
902
|
+
if (!(await control.isVisible().catch(() => false)))
|
|
903
|
+
return false;
|
|
904
|
+
await control.click({ timeout: 1_500 });
|
|
905
|
+
await page.waitForTimeout(300); // let the checkout take the removal in before the browser closes
|
|
906
|
+
return true;
|
|
907
|
+
}
|
|
908
|
+
catch {
|
|
909
|
+
return false; // never quote the error: a Playwright message can carry page text
|
|
910
|
+
}
|
|
911
|
+
}
|
|
441
912
|
/** Internal implementation — called by fillCheckoutForm inside a timeout wrapper */
|
|
442
|
-
async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
913
|
+
async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints, deal, dealState = {}) {
|
|
443
914
|
const gate = new CardGate(page, cardData.merchant_domain);
|
|
444
915
|
try {
|
|
445
916
|
// ✅ FIX: Skip navigation if page already loaded (Single Browser reuse from auto_pay_checkout)
|
|
@@ -492,6 +963,24 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
|
492
963
|
if (!lock.ok) {
|
|
493
964
|
return { success: false, status: "blocked", message: lock.reason };
|
|
494
965
|
}
|
|
966
|
+
// ============================================================
|
|
967
|
+
// DEAL ORDER — the discount comes BEFORE the card (design: the card is for the
|
|
968
|
+
// discounted total, so a card typed without the discount can only be declined or
|
|
969
|
+
// overpay). Same browser, same locked page. Anything short of "the code is on the
|
|
970
|
+
// page and the total is within the card amount" stops here: no card field is touched.
|
|
971
|
+
// ============================================================
|
|
972
|
+
if (deal) {
|
|
973
|
+
const applied = await applyDealCode(page, gate, cardData.merchant_domain, deal, hints, dealState);
|
|
974
|
+
if (!applied.ok) {
|
|
975
|
+
return {
|
|
976
|
+
success: false,
|
|
977
|
+
status: applied.blocked ? "blocked" : "deal_not_applied",
|
|
978
|
+
message: applied.reason,
|
|
979
|
+
...(applied.detail ? { page_detail: applied.detail } : {}),
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
dealState.total = applied.total;
|
|
983
|
+
}
|
|
495
984
|
let filledFields = 0;
|
|
496
985
|
let cardNumberFilled = false;
|
|
497
986
|
const stopIfMoved = () => {
|
|
@@ -508,20 +997,66 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
|
508
997
|
// Name on card is always searched on the main page (outside iframe).
|
|
509
998
|
// Falls through to Strategy 1 if the card number could not be placed.
|
|
510
999
|
// ============================================================
|
|
1000
|
+
// A Shopify checkout is recognised from the page itself, so an agent that passes no
|
|
1001
|
+
// card selectors still gets its card fields found. Shopify keeps every card field in
|
|
1002
|
+
// its own frame (card-fields-number-…, -expiry-…, -verification_value-…, -name-…) served
|
|
1003
|
+
// by its card host; the default search below does not look inside frames and answered
|
|
1004
|
+
// no_fields on the first real deal order (26/11/2026). Selectors the agent did pass
|
|
1005
|
+
// are kept — the preset only fills what is missing.
|
|
1006
|
+
let cardFieldsFrom = 'agent hints';
|
|
1007
|
+
if (!(hints && (hints.card_selector || hints.exp_selector || hints.cvv_selector))) {
|
|
1008
|
+
await page.waitForLoadState("load", { timeout: 10_000 }).catch(() => { });
|
|
1009
|
+
const hasShopifyCardFrames = () => page.frames().some((f) => f !== page.mainFrame() && /^card-fields-number/.test(f.name()) &&
|
|
1010
|
+
(0, domain_lock_js_1.isTrustedCardFrame)(f.url(), cardData.merchant_domain));
|
|
1011
|
+
// The frames are attached after 'load' and sit at about:blank until their own page
|
|
1012
|
+
// arrives; one look right after 'load' missed them on a slow checkout (a real run
|
|
1013
|
+
// answered no_fields, the next one on the same link found them). On a page that is
|
|
1014
|
+
// building them, give them a few seconds.
|
|
1015
|
+
let shopifyCardFrames = hasShopifyCardFrames();
|
|
1016
|
+
if (!shopifyCardFrames && (/\/checkouts\//.test(page.url()) || await page.$('iframe[name^="card-fields"], [id*="card-fields" i]').catch(() => null))) {
|
|
1017
|
+
const until = Date.now() + 8_000;
|
|
1018
|
+
while (!shopifyCardFrames && Date.now() < until) {
|
|
1019
|
+
await page.waitForTimeout(400).catch(() => { });
|
|
1020
|
+
shopifyCardFrames = hasShopifyCardFrames();
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
if (shopifyCardFrames) {
|
|
1024
|
+
hints = { ...SHOPIFY_CARD_PRESET, ...(hints ?? {}) };
|
|
1025
|
+
cardFieldsFrom = "Z-ZERO's Shopify preset";
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
511
1028
|
if (hints && (hints.card_selector || hints.exp_selector || hints.cvv_selector)) {
|
|
512
1029
|
let cardContexts = [page];
|
|
513
|
-
|
|
1030
|
+
const frameName = hints.iframe_selector; // read once: closures below cannot rely on `hints` staying narrowed
|
|
1031
|
+
if (frameName) {
|
|
514
1032
|
// Card frames load after the page; until then they sit at about:blank
|
|
515
1033
|
// and fail the origin check.
|
|
516
1034
|
await page.waitForLoadState("load", { timeout: 10_000 }).catch(() => { });
|
|
517
1035
|
cardContexts = page.frames().filter((f) => f !== page.mainFrame() &&
|
|
518
|
-
f.name().includes(
|
|
1036
|
+
f.name().includes(frameName) &&
|
|
519
1037
|
(0, domain_lock_js_1.isTrustedCardFrame)(f.url(), cardData.merchant_domain));
|
|
520
1038
|
}
|
|
1039
|
+
// Which frame is FOR which field. A hosted card form can give every field its own
|
|
1040
|
+
// frame and still build ALL the inputs into each of them (Shopify: the frames
|
|
1041
|
+
// card-fields-number-…, -expiry-…, -verification_value-…, -name-… each hold #number,
|
|
1042
|
+
// #expiry, #verification_value and #name; only the one the frame is named after is
|
|
1043
|
+
// live). Taking the first frame that has the selector typed the expiry and the CVV
|
|
1044
|
+
// into the dead copies inside the number frame. So the frame named for the field
|
|
1045
|
+
// is tried first; the others keep their order behind it.
|
|
1046
|
+
const FRAME_FOR = {
|
|
1047
|
+
number: /number/i, exp: /expir/i, cvv: /verification|security|cvv|cvc|csc/i, name: /name/i,
|
|
1048
|
+
};
|
|
1049
|
+
const frameRank = (ctx, kind) => {
|
|
1050
|
+
if (!frameName || ctx === page)
|
|
1051
|
+
return 0;
|
|
1052
|
+
const own = ctx.name().split(frameName).join("");
|
|
1053
|
+
return FRAME_FOR[kind].test(own) ? 1 : 0;
|
|
1054
|
+
};
|
|
521
1055
|
const fillHint = async (selector, value, kind, contexts) => {
|
|
522
1056
|
if (!isPlainCss(selector))
|
|
523
1057
|
return false;
|
|
524
|
-
|
|
1058
|
+
const inOrder = [...contexts].sort((a, b) => frameRank(b, kind) - frameRank(a, kind));
|
|
1059
|
+
for (const ctx of inOrder) {
|
|
525
1060
|
const el = await ctx.$(selector).catch(() => null);
|
|
526
1061
|
if (el)
|
|
527
1062
|
return smartFill(gate, el, value, kind);
|
|
@@ -546,21 +1081,22 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
|
546
1081
|
}
|
|
547
1082
|
if (await fillHint(hints.cvv_selector, cardData.cvv, 'cvv', cardContexts))
|
|
548
1083
|
hintFilled++;
|
|
549
|
-
// Name on card —
|
|
550
|
-
|
|
1084
|
+
// Name on card — in the card frames when the form keeps it there (Shopify does:
|
|
1085
|
+
// its own frame, and the checkout will not pay without it), else on the main page.
|
|
1086
|
+
if (cardNumberFilled && await fillHint(hints.name_selector, cardData.name, 'name', hints.iframe_selector ? [...cardContexts, page] : [page]))
|
|
551
1087
|
hintFilled++;
|
|
552
1088
|
const stopped = stopIfMoved();
|
|
553
1089
|
if (stopped)
|
|
554
1090
|
return stopped;
|
|
555
1091
|
if (cardNumberFilled) {
|
|
556
1092
|
filledFields += hintFilled;
|
|
557
|
-
const modeNote = `${filledFields} fields injected via
|
|
1093
|
+
const modeNote = `${filledFields} fields injected via ${cardFieldsFrom}${hints.iframe_selector ? ' (iframe mode)' : ''}.`;
|
|
558
1094
|
// Must actually submit to have any chance of a real payment.
|
|
559
1095
|
let clicked = false;
|
|
560
1096
|
if (isPlainCss(hints.submit_selector)) {
|
|
561
1097
|
const btn = await page.$(hints.submit_selector).catch(() => null);
|
|
562
1098
|
if (btn) {
|
|
563
|
-
const c = await clickIfStillLocked(gate, btn);
|
|
1099
|
+
const c = await clickIfStillLocked(gate, btn, dealState);
|
|
564
1100
|
if (typeof c === 'object')
|
|
565
1101
|
return { success: false, status: 'blocked', message: c.ok ? '' : c.reason };
|
|
566
1102
|
clicked = c === 'clicked';
|
|
@@ -759,7 +1295,7 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
|
759
1295
|
const btn = await page.$(selector).catch(() => null);
|
|
760
1296
|
if (!btn)
|
|
761
1297
|
continue;
|
|
762
|
-
const c = await clickIfStillLocked(gate, btn);
|
|
1298
|
+
const c = await clickIfStillLocked(gate, btn, dealState);
|
|
763
1299
|
if (typeof c === 'object')
|
|
764
1300
|
return { success: false, status: 'blocked', message: c.ok ? '' : c.reason };
|
|
765
1301
|
if (c === 'clicked') {
|