z-zero-mcp-server 1.10.4 → 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.
- package/README.md +22 -11
- package/dist/base_backend.d.ts +46 -1
- package/dist/base_backend.js +143 -12
- package/dist/failure_taxonomy.d.ts +13 -6
- package/dist/failure_taxonomy.js +79 -6
- package/dist/index.js +650 -252
- package/dist/lib/api-base.d.ts +4 -1
- package/dist/lib/api-base.js +48 -26
- 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 +79 -16
- package/dist/lib/extract-total-price.d.ts +49 -16
- package/dist/lib/extract-total-price.js +286 -138
- package/dist/lib/key-store.d.ts +25 -2
- package/dist/lib/key-store.js +175 -25
- package/dist/lib/url-guard.js +12 -1
- package/dist/playwright_bridge.d.ts +25 -2
- package/dist/playwright_bridge.js +842 -146
- package/dist/types.d.ts +37 -1
- package/dist/ucp_bridge.js +12 -0
- package/package.json +4 -2
- package/dist/lib/web3-detector.d.ts +0 -19
- package/dist/lib/web3-detector.js +0 -157
|
@@ -2,56 +2,264 @@
|
|
|
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");
|
|
11
|
+
const failure_taxonomy_js_1 = require("./failure_taxonomy.js");
|
|
12
|
+
const extract_total_price_js_1 = require("./lib/extract-total-price.js");
|
|
9
13
|
const CHECKOUT_HARD_TIMEOUT_MS = 60_000; // 60s absolute cap — prevents slow-loris attacks
|
|
14
|
+
const PAGE_DETAIL_MAX = 300;
|
|
10
15
|
/**
|
|
11
16
|
* Detects and fills credit card form fields on a checkout page.
|
|
12
17
|
* Card data exists ONLY in RAM and is wiped after injection.
|
|
13
18
|
* Hard timeout of 60s prevents merchant page from hanging indefinitely.
|
|
19
|
+
*
|
|
20
|
+
* Nothing this function returns may carry the card (audit T12 F3, M.1): a
|
|
21
|
+
* Playwright error quotes the value it was filling (`fill("4242…")`), and a page
|
|
22
|
+
* can echo the number back as its "order number". Every string leaving here goes
|
|
23
|
+
* through finish(), which strips this card's own number and CVV, then every
|
|
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.
|
|
14
31
|
*/
|
|
15
|
-
async function fillCheckoutForm(checkoutUrl, cardData, existingPage, hints) {
|
|
32
|
+
async function fillCheckoutForm(checkoutUrl, cardData, existingPage, hints, deal) {
|
|
33
|
+
// Kept only to scrub output; the bridge wipes cardData itself.
|
|
34
|
+
const secrets = { number: cardData.number, cvv: cardData.cvv, code: deal?.code ?? undefined };
|
|
35
|
+
const dealState = {};
|
|
16
36
|
let browser = null;
|
|
17
37
|
let page;
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
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
|
+
};
|
|
26
67
|
try {
|
|
27
|
-
|
|
68
|
+
if (existingPage) {
|
|
69
|
+
page = existingPage;
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
browser = await (0, browser_js_1.launchBrowser)();
|
|
73
|
+
const context = await browser.newContext();
|
|
74
|
+
page = await context.newPage();
|
|
75
|
+
}
|
|
76
|
+
const result = await (0, with_timeout_js_1.withTimeout)(_fillCheckoutFormInner(page, checkoutUrl, cardData, hints, deal, dealState), CHECKOUT_HARD_TIMEOUT_MS, 'fillCheckoutForm', async () => {
|
|
28
77
|
console.error('[PLAYWRIGHT] ⚠️ Hard timeout hit — force-closing browser');
|
|
29
78
|
if (browser)
|
|
30
79
|
await browser.close().catch(() => { });
|
|
31
80
|
});
|
|
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);
|
|
32
83
|
}
|
|
33
84
|
catch (err) {
|
|
34
85
|
if (err instanceof with_timeout_js_1.TimeoutError) {
|
|
35
|
-
return {
|
|
86
|
+
return finish(await settleDealCode({
|
|
36
87
|
success: false,
|
|
37
88
|
status: 'error',
|
|
38
89
|
message: `Checkout timed out after ${CHECKOUT_HARD_TIMEOUT_MS / 1000}s. The merchant page may be too slow or blocking automation.`,
|
|
39
|
-
};
|
|
90
|
+
}), secrets);
|
|
40
91
|
}
|
|
41
|
-
|
|
42
|
-
|
|
92
|
+
return finish(await settleDealCode({
|
|
93
|
+
success: false,
|
|
94
|
+
status: 'error',
|
|
95
|
+
message: 'The browser failed during the checkout attempt.',
|
|
96
|
+
page_detail: err instanceof Error ? err.message : String(err),
|
|
97
|
+
}), secrets);
|
|
43
98
|
}
|
|
44
99
|
finally {
|
|
45
100
|
if (browser)
|
|
46
101
|
await browser.close().catch(() => { });
|
|
102
|
+
// Wipe the copy too: fill is over, nothing needs the values any more.
|
|
103
|
+
secrets.number = "";
|
|
104
|
+
secrets.cvv = "";
|
|
105
|
+
secrets.code = undefined;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
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. */
|
|
123
|
+
function finish(r, 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) };
|
|
126
|
+
if (r.page_detail) {
|
|
127
|
+
out.page_detail = (0, failure_taxonomy_js_1.scrubCardValues)(hideDealCode(r.page_detail, secrets.code), secrets).slice(0, PAGE_DETAIL_MAX);
|
|
128
|
+
}
|
|
129
|
+
if (r.receipt_id !== undefined) {
|
|
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;
|
|
132
|
+
}
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* An order number is page text. It goes into the agent's result, the signed
|
|
137
|
+
* receipt and the public receipt page, so: short, plain characters only, and
|
|
138
|
+
* dropped outright if it holds this card's number or CVV, or anything that can
|
|
139
|
+
* be a card number. A dropped id costs a convenience; a kept one could cost the
|
|
140
|
+
* card (audit T12 F3: a page echoed "Order number: <PAN>-<CVV>").
|
|
141
|
+
*/
|
|
142
|
+
function cleanReceiptId(id, secrets) {
|
|
143
|
+
if (!id)
|
|
144
|
+
return undefined;
|
|
145
|
+
const plain = id.normalize("NFKC").trim();
|
|
146
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9-]{2,63}$/.test(plain))
|
|
147
|
+
return undefined;
|
|
148
|
+
return (0, failure_taxonomy_js_1.scrubCardValues)(plain, secrets, { cards: "valid" }) === plain ? plain : undefined;
|
|
149
|
+
}
|
|
150
|
+
const FIELD_SHAPE = {
|
|
151
|
+
number: /cc-?number|card.?num|cardnumber|credit.?card|card.?no\b|\bccnum|\bpan\b|card[_\s-]?number/i,
|
|
152
|
+
exp: /cc-exp|exp(iry|iration|ires)?\b|exp[-_\s]?(date|month|year|mm|yy)|\bmm\s*\/\s*yy|valid.?thru/i,
|
|
153
|
+
cvv: /cc-csc|\bcvv|\bcvc|\bcsc\b|security.?code|card.?code|verification|cvn/i,
|
|
154
|
+
name: /cc-name|card.?holder|name.?on.?card|ccname|card.?name/i,
|
|
155
|
+
};
|
|
156
|
+
class CardGate {
|
|
157
|
+
page;
|
|
158
|
+
lockedDomain;
|
|
159
|
+
lockedOrigin = null;
|
|
160
|
+
movedTo = null;
|
|
161
|
+
onNav;
|
|
162
|
+
constructor(page, lockedDomain) {
|
|
163
|
+
this.page = page;
|
|
164
|
+
this.lockedDomain = lockedDomain;
|
|
165
|
+
this.onNav = (f) => {
|
|
166
|
+
if (f !== this.page.mainFrame() || !this.lockedOrigin || this.movedTo)
|
|
167
|
+
return;
|
|
168
|
+
if (originOf(f.url()) !== this.lockedOrigin)
|
|
169
|
+
this.movedTo = f.url();
|
|
170
|
+
};
|
|
47
171
|
}
|
|
172
|
+
/** Lock to the page in front of us now. Any later move to another origin stops the fill. */
|
|
173
|
+
arm() {
|
|
174
|
+
const lock = (0, domain_lock_js_1.checkPaymentPage)(this.page.url(), this.lockedDomain);
|
|
175
|
+
if (!lock.ok)
|
|
176
|
+
return lock;
|
|
177
|
+
this.lockedOrigin = originOf(this.page.url());
|
|
178
|
+
this.page.on('framenavigated', this.onNav);
|
|
179
|
+
return lock;
|
|
180
|
+
}
|
|
181
|
+
dispose() {
|
|
182
|
+
this.page.off('framenavigated', this.onNav);
|
|
183
|
+
}
|
|
184
|
+
/** Stop everything: the page itself has gone somewhere else. */
|
|
185
|
+
moved() {
|
|
186
|
+
if (this.movedTo)
|
|
187
|
+
return blockedMove(this.movedTo);
|
|
188
|
+
if (originOf(this.page.url()) !== this.lockedOrigin)
|
|
189
|
+
return blockedMove(this.page.url());
|
|
190
|
+
const live = (0, domain_lock_js_1.checkPaymentPage)(this.page.url(), this.lockedDomain);
|
|
191
|
+
return live.ok ? null : live;
|
|
192
|
+
}
|
|
193
|
+
/** May this one field receive this one value? false = skip the field, never type. */
|
|
194
|
+
async allows(el, kind) {
|
|
195
|
+
if (this.moved())
|
|
196
|
+
return false;
|
|
197
|
+
const frame = await el.ownerFrame().catch(() => null);
|
|
198
|
+
if (!frame)
|
|
199
|
+
return false;
|
|
200
|
+
if (frame === this.page.mainFrame()) {
|
|
201
|
+
if (originOf(frame.url()) !== this.lockedOrigin)
|
|
202
|
+
return false;
|
|
203
|
+
return (await looksLikeCardField(el, kind)) && (await isHumanVisible(el));
|
|
204
|
+
}
|
|
205
|
+
return (0, domain_lock_js_1.isTrustedCardFrame)(frame.url(), this.lockedDomain);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
function originOf(url) {
|
|
209
|
+
try {
|
|
210
|
+
const o = new URL(url).origin;
|
|
211
|
+
return o === "null" ? null : o;
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
function blockedMove(to) {
|
|
218
|
+
return {
|
|
219
|
+
ok: false,
|
|
220
|
+
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.`,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
function hostOf(url) {
|
|
224
|
+
try {
|
|
225
|
+
return new URL(url).host || "an unreadable address";
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
return "an unreadable address";
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
async function looksLikeCardField(el, kind) {
|
|
232
|
+
const attrs = await el.evaluate((e) => {
|
|
233
|
+
const a = (n) => e.getAttribute(n) || "";
|
|
234
|
+
return [a("autocomplete"), a("name"), a("id"), a("placeholder"), a("aria-label"), a("data-elements-stable-field-name")].join(" ");
|
|
235
|
+
}).catch(() => "");
|
|
236
|
+
return FIELD_SHAPE[kind].test(attrs);
|
|
237
|
+
}
|
|
238
|
+
async function isHumanVisible(el) {
|
|
239
|
+
if (!(await el.isVisible().catch(() => false)))
|
|
240
|
+
return false;
|
|
241
|
+
return el.evaluate((e) => {
|
|
242
|
+
const r = e.getBoundingClientRect();
|
|
243
|
+
if (r.width < 4 || r.height < 4)
|
|
244
|
+
return false;
|
|
245
|
+
let opacity = 1;
|
|
246
|
+
for (let n = e; n; n = n.parentElement) {
|
|
247
|
+
const s = getComputedStyle(n);
|
|
248
|
+
if (s.visibility === "hidden" || s.display === "none")
|
|
249
|
+
return false;
|
|
250
|
+
opacity *= parseFloat(s.opacity || "1");
|
|
251
|
+
}
|
|
252
|
+
return opacity >= 0.1;
|
|
253
|
+
}).catch(() => false);
|
|
48
254
|
}
|
|
49
255
|
// ============================================================
|
|
50
256
|
// HELPER: Smart fill — handles both <input> and <select>
|
|
51
257
|
// Prevents crash when dropdown uses <select> instead of <input>
|
|
52
258
|
// ============================================================
|
|
53
|
-
async function smartFill(el, value) {
|
|
259
|
+
async function smartFill(gate, el, value, kind) {
|
|
54
260
|
try {
|
|
261
|
+
if (!(await gate.allows(el, kind)))
|
|
262
|
+
return false;
|
|
55
263
|
const tag = await el.evaluate(e => e.tagName.toLowerCase());
|
|
56
264
|
// Card data only ever goes into a form field built to hold it: an <input> of a
|
|
57
265
|
// text-like type, or a <select> (expiry). Never a textarea, a hidden or email
|
|
@@ -94,21 +302,32 @@ async function smartFill(el, value) {
|
|
|
94
302
|
}
|
|
95
303
|
}
|
|
96
304
|
catch {
|
|
305
|
+
// Never rethrow: a Playwright fill error quotes the value it was typing.
|
|
97
306
|
return false;
|
|
98
307
|
}
|
|
99
308
|
}
|
|
100
309
|
/** Try each selector in order, smartFill the first match */
|
|
101
|
-
async function tryFillField(
|
|
310
|
+
async function tryFillField(gate, ctx, selectors, value, kind) {
|
|
102
311
|
for (const selector of selectors) {
|
|
103
|
-
const el = await
|
|
312
|
+
const el = await ctx.$(selector).catch(() => null);
|
|
104
313
|
if (el) {
|
|
105
|
-
const ok = await smartFill(el, value);
|
|
314
|
+
const ok = await smartFill(gate, el, value, kind);
|
|
106
315
|
if (ok)
|
|
107
316
|
return true;
|
|
108
317
|
}
|
|
109
318
|
}
|
|
110
319
|
return false;
|
|
111
320
|
}
|
|
321
|
+
/**
|
|
322
|
+
* A hint selector is plain CSS. Playwright also reads `>>` chains and its own
|
|
323
|
+
* engines (`internal:control=enter-frame`, `xpath=`…), which let one string walk
|
|
324
|
+
* into another site's frame (audit T12 F1). Those are refused outright.
|
|
325
|
+
*/
|
|
326
|
+
function isPlainCss(selector) {
|
|
327
|
+
if (!selector)
|
|
328
|
+
return false;
|
|
329
|
+
return !/>>|^\s*[a-z_-]+=|internal:/i.test(selector);
|
|
330
|
+
}
|
|
112
331
|
// ============================================================
|
|
113
332
|
// CONFIRMATION DETECTION — the core of "filled ≠ paid"
|
|
114
333
|
// After Pay is clicked we must observe a REAL outcome before
|
|
@@ -117,6 +336,12 @@ async function tryFillField(page, selectors, value) {
|
|
|
117
336
|
// ============================================================
|
|
118
337
|
const CONFIRM_WAIT_MS = 12_000; // total budget to watch for an outcome (well within the 60s hard cap)
|
|
119
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
|
|
120
345
|
// URL of a post-payment page (we additionally require the URL to have moved off the checkout page)
|
|
121
346
|
const SUCCESS_URL_RE = /thank[_-]?you|order[-_]?(?:received|confirmation|confirmed|complete|placed)|\/orders?\/|\/receipts?\/|payment[_-]?success|checkout\/success|confirmation/i;
|
|
122
347
|
// Strong success phrases — deliberately specific so a checkout "Order summary" panel does NOT trigger it
|
|
@@ -125,9 +350,67 @@ const SUCCESS_TEXT_RE = /thank you for your (?:order|purchase|payment)|your orde
|
|
|
125
350
|
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
351
|
// Real order/confirmation number to use as receipt_id (only when confirmed)
|
|
127
352
|
const RECEIPT_RE = /(?:order|confirmation|receipt)\s*(?:number|no\.?|#)?[:\s#]*([A-Z0-9][A-Z0-9-]{3,})/i;
|
|
353
|
+
/**
|
|
354
|
+
* The text a person looking at the page can actually read (audit T12 F6, M.7).
|
|
355
|
+
* innerText still counts text that is transparent, 0px, or parked off-screen —
|
|
356
|
+
* a page could hide "Order number: …" there and have a non-payment read as paid
|
|
357
|
+
* (the token then burns and the money sits in USED with no way back).
|
|
358
|
+
*/
|
|
359
|
+
async function readableText(page) {
|
|
360
|
+
return page.evaluate(() => {
|
|
361
|
+
const out = [];
|
|
362
|
+
const docW = Math.max(document.documentElement.scrollWidth, window.innerWidth);
|
|
363
|
+
const docH = Math.max(document.documentElement.scrollHeight, window.innerHeight);
|
|
364
|
+
const seen = new Map();
|
|
365
|
+
const readable = (el) => {
|
|
366
|
+
const cached = seen.get(el);
|
|
367
|
+
if (cached !== undefined)
|
|
368
|
+
return cached;
|
|
369
|
+
let ok = true;
|
|
370
|
+
const r = el.getBoundingClientRect();
|
|
371
|
+
if (r.width < 1 || r.height < 1)
|
|
372
|
+
ok = false;
|
|
373
|
+
const left = r.left + window.scrollX;
|
|
374
|
+
const top = r.top + window.scrollY;
|
|
375
|
+
if (ok && (left + r.width <= 0 || top + r.height <= 0 || left >= docW || top >= docH))
|
|
376
|
+
ok = false;
|
|
377
|
+
if (ok) {
|
|
378
|
+
let opacity = 1;
|
|
379
|
+
for (let n = el; n; n = n.parentElement) {
|
|
380
|
+
const s = getComputedStyle(n);
|
|
381
|
+
if (s.display === "none" || s.visibility === "hidden") {
|
|
382
|
+
ok = false;
|
|
383
|
+
break;
|
|
384
|
+
}
|
|
385
|
+
opacity *= parseFloat(s.opacity || "1");
|
|
386
|
+
if (n === el && parseFloat(s.fontSize || "16") < 6) {
|
|
387
|
+
ok = false;
|
|
388
|
+
break;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
if (ok && opacity < 0.1)
|
|
392
|
+
ok = false;
|
|
393
|
+
}
|
|
394
|
+
seen.set(el, ok);
|
|
395
|
+
return ok;
|
|
396
|
+
};
|
|
397
|
+
const walker = document.createTreeWalker(document.body || document.documentElement, NodeFilter.SHOW_TEXT);
|
|
398
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
|
399
|
+
const t = (n.textContent || "").trim();
|
|
400
|
+
const parent = n.parentElement;
|
|
401
|
+
if (!t || !parent || ["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE"].includes(parent.tagName))
|
|
402
|
+
continue;
|
|
403
|
+
if (readable(parent))
|
|
404
|
+
out.push(t);
|
|
405
|
+
if (out.length > 4000)
|
|
406
|
+
break;
|
|
407
|
+
}
|
|
408
|
+
return out.join("\n");
|
|
409
|
+
});
|
|
410
|
+
}
|
|
128
411
|
/**
|
|
129
412
|
* Watches the page after Pay is clicked and classifies the real outcome.
|
|
130
|
-
* Polls URL +
|
|
413
|
+
* Polls URL + readable text for a confirmation or decline signal until a
|
|
131
414
|
* signal is seen or CONFIRM_WAIT_MS elapses. Default (no signal) is the
|
|
132
415
|
* SAFE 'unconfirmed' — caller must NOT burn the token on that.
|
|
133
416
|
*/
|
|
@@ -147,11 +430,11 @@ async function detectPaymentOutcome(page, checkoutUrl) {
|
|
|
147
430
|
let bodyText = '';
|
|
148
431
|
try {
|
|
149
432
|
currentUrl = page.url();
|
|
150
|
-
bodyText = await page
|
|
433
|
+
bodyText = await readableText(page);
|
|
151
434
|
}
|
|
152
435
|
catch {
|
|
153
436
|
// page is mid-navigation — wait and retry
|
|
154
|
-
await page.waitForTimeout(CONFIRM_POLL_MS);
|
|
437
|
+
await page.waitForTimeout(CONFIRM_POLL_MS).catch(() => { });
|
|
155
438
|
continue;
|
|
156
439
|
}
|
|
157
440
|
// Decline is a definitive negative — check first.
|
|
@@ -170,10 +453,25 @@ async function detectPaymentOutcome(page, checkoutUrl) {
|
|
|
170
453
|
const urlSignal = movedOff && SUCCESS_URL_RE.test(currentUrl);
|
|
171
454
|
const textSignal = SUCCESS_TEXT_RE.test(bodyText);
|
|
172
455
|
if (urlSignal || textSignal) {
|
|
173
|
-
|
|
174
|
-
|
|
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 };
|
|
175
473
|
}
|
|
176
|
-
await page.waitForTimeout(CONFIRM_POLL_MS);
|
|
474
|
+
await page.waitForTimeout(CONFIRM_POLL_MS).catch(() => { });
|
|
177
475
|
}
|
|
178
476
|
// No clear signal within the window — safe default, caller will NOT burn.
|
|
179
477
|
return { kind: 'unconfirmed' };
|
|
@@ -204,8 +502,372 @@ function outcomeToResult(outcome, fieldNote) {
|
|
|
204
502
|
};
|
|
205
503
|
}
|
|
206
504
|
}
|
|
505
|
+
/** Click the pay button only while the page is still the one we locked to. */
|
|
506
|
+
async function clickIfStillLocked(gate, btn, dealState) {
|
|
507
|
+
const moved = gate.moved();
|
|
508
|
+
if (moved)
|
|
509
|
+
return moved;
|
|
510
|
+
try {
|
|
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;
|
|
516
|
+
await btn.click();
|
|
517
|
+
return 'clicked';
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
catch { /* covered, detached, … — treat as not clicked */ }
|
|
521
|
+
return 'not_clicked';
|
|
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
|
+
}
|
|
207
868
|
/** Internal implementation — called by fillCheckoutForm inside a timeout wrapper */
|
|
208
|
-
async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
869
|
+
async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints, deal, dealState = {}) {
|
|
870
|
+
const gate = new CardGate(page, cardData.merchant_domain);
|
|
209
871
|
try {
|
|
210
872
|
// ✅ FIX: Skip navigation if page already loaded (Single Browser reuse from auto_pay_checkout)
|
|
211
873
|
// Prevents double-navigate which would reload page and lose cart/session state.
|
|
@@ -238,6 +900,8 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
|
238
900
|
// ============================================================
|
|
239
901
|
if (hints?.pre_steps && hints.pre_steps.length > 0) {
|
|
240
902
|
for (const selector of hints.pre_steps) {
|
|
903
|
+
if (!isPlainCss(selector))
|
|
904
|
+
continue;
|
|
241
905
|
try {
|
|
242
906
|
const el = await page.$(selector);
|
|
243
907
|
if (el && await el.isVisible()) {
|
|
@@ -248,103 +912,139 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
|
248
912
|
catch { /* non-fatal — continue */ }
|
|
249
913
|
}
|
|
250
914
|
}
|
|
251
|
-
// 🔒 DOMAIN LOCK —
|
|
252
|
-
//
|
|
253
|
-
//
|
|
254
|
-
const lock =
|
|
915
|
+
// 🔒 DOMAIN LOCK — armed on the page in front of us now, then held for every
|
|
916
|
+
// field (CardGate). The card goes only on its own store or a hosted payment
|
|
917
|
+
// page that store handed off to (lib/domain-lock.ts).
|
|
918
|
+
const lock = gate.arm();
|
|
255
919
|
if (!lock.ok) {
|
|
256
920
|
return { success: false, status: "blocked", message: lock.reason };
|
|
257
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
|
+
}
|
|
258
940
|
let filledFields = 0;
|
|
941
|
+
let cardNumberFilled = false;
|
|
942
|
+
const stopIfMoved = () => {
|
|
943
|
+
const moved = gate.moved();
|
|
944
|
+
return moved && !moved.ok ? { success: false, status: "blocked", message: moved.reason } : null;
|
|
945
|
+
};
|
|
259
946
|
// ============================================================
|
|
260
947
|
// STRATEGY 0.5: Agent-provided selectors (from get_merchant_hints)
|
|
261
948
|
// Tried first — agent already read the DOM and knows exact locations.
|
|
262
|
-
//
|
|
263
|
-
//
|
|
949
|
+
// iframe_selector: card fields are searched INSIDE frames whose name holds
|
|
950
|
+
// that fragment AND whose real origin is the store or a card-field provider.
|
|
951
|
+
// No such frame → the card fields are not searched anywhere else (the main
|
|
952
|
+
// page is where an order note lives; audit T11 F4 / T00 F1).
|
|
264
953
|
// Name on card is always searched on the main page (outside iframe).
|
|
265
|
-
// Falls through to Strategy 1 if
|
|
954
|
+
// Falls through to Strategy 1 if the card number could not be placed.
|
|
266
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
|
+
}
|
|
267
972
|
if (hints && (hints.card_selector || hints.exp_selector || hints.cvv_selector)) {
|
|
268
|
-
const hintFillResults = [];
|
|
269
973
|
let cardContexts = [page];
|
|
270
|
-
|
|
271
|
-
|
|
974
|
+
const frameName = hints.iframe_selector; // read once: closures below cannot rely on `hints` staying narrowed
|
|
975
|
+
if (frameName) {
|
|
976
|
+
// Card frames load after the page; until then they sit at about:blank
|
|
977
|
+
// and fail the origin check.
|
|
978
|
+
await page.waitForLoadState("load", { timeout: 10_000 }).catch(() => { });
|
|
979
|
+
cardContexts = page.frames().filter((f) => f !== page.mainFrame() &&
|
|
980
|
+
f.name().includes(frameName) &&
|
|
272
981
|
(0, domain_lock_js_1.isTrustedCardFrame)(f.url(), cardData.merchant_domain));
|
|
273
|
-
if (matchingFrames.length > 0)
|
|
274
|
-
cardContexts = matchingFrames;
|
|
275
982
|
}
|
|
276
|
-
//
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
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
|
+
};
|
|
999
|
+
const fillHint = async (selector, value, kind, contexts) => {
|
|
1000
|
+
if (!isPlainCss(selector))
|
|
1001
|
+
return false;
|
|
1002
|
+
const inOrder = [...contexts].sort((a, b) => frameRank(b, kind) - frameRank(a, kind));
|
|
1003
|
+
for (const ctx of inOrder) {
|
|
1004
|
+
const el = await ctx.$(selector).catch(() => null);
|
|
1005
|
+
if (el)
|
|
1006
|
+
return smartFill(gate, el, value, kind);
|
|
284
1007
|
}
|
|
1008
|
+
return false;
|
|
1009
|
+
};
|
|
1010
|
+
let hintFilled = 0;
|
|
1011
|
+
if (await fillHint(hints.card_selector, cardData.number, 'number', cardContexts)) {
|
|
1012
|
+
hintFilled++;
|
|
1013
|
+
cardNumberFilled = true;
|
|
285
1014
|
}
|
|
286
|
-
// Expiry combined (with space-padded slash for Shopify: "MM / YY")
|
|
287
1015
|
if (hints.exp_selector) {
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
if (el) {
|
|
292
|
-
hintFillResults.push(await smartFill(el, expiryVal));
|
|
293
|
-
break;
|
|
294
|
-
}
|
|
295
|
-
}
|
|
1016
|
+
// Expiry combined (with space-padded slash for Shopify: "MM / YY")
|
|
1017
|
+
if (await fillHint(hints.exp_selector, `${cardData.exp_month} / ${cardData.exp_year.slice(-2)}`, 'exp', cardContexts))
|
|
1018
|
+
hintFilled++;
|
|
296
1019
|
}
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
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
|
-
}
|
|
315
|
-
}
|
|
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
|
-
}
|
|
325
|
-
}
|
|
326
|
-
// 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
|
-
}
|
|
1020
|
+
else if (hints.exp_month_selector) {
|
|
1021
|
+
if (await fillHint(hints.exp_month_selector, cardData.exp_month, 'exp', cardContexts))
|
|
1022
|
+
hintFilled++;
|
|
1023
|
+
if (await fillHint(hints.exp_year_selector, cardData.exp_year, 'exp', cardContexts))
|
|
1024
|
+
hintFilled++;
|
|
332
1025
|
}
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
1026
|
+
if (await fillHint(hints.cvv_selector, cardData.cvv, 'cvv', cardContexts))
|
|
1027
|
+
hintFilled++;
|
|
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]))
|
|
1031
|
+
hintFilled++;
|
|
1032
|
+
const stopped = stopIfMoved();
|
|
1033
|
+
if (stopped)
|
|
1034
|
+
return stopped;
|
|
1035
|
+
if (cardNumberFilled) {
|
|
1036
|
+
filledFields += hintFilled;
|
|
1037
|
+
const modeNote = `${filledFields} fields injected via ${cardFieldsFrom}${hints.iframe_selector ? ' (iframe mode)' : ''}.`;
|
|
337
1038
|
// Must actually submit to have any chance of a real payment.
|
|
338
1039
|
let clicked = false;
|
|
339
|
-
if (hints.submit_selector) {
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
1040
|
+
if (isPlainCss(hints.submit_selector)) {
|
|
1041
|
+
const btn = await page.$(hints.submit_selector).catch(() => null);
|
|
1042
|
+
if (btn) {
|
|
1043
|
+
const c = await clickIfStillLocked(gate, btn, dealState);
|
|
1044
|
+
if (typeof c === 'object')
|
|
1045
|
+
return { success: false, status: 'blocked', message: c.ok ? '' : c.reason };
|
|
1046
|
+
clicked = c === 'clicked';
|
|
346
1047
|
}
|
|
347
|
-
catch { /* non-fatal */ }
|
|
348
1048
|
}
|
|
349
1049
|
if (!clicked) {
|
|
350
1050
|
// Fields filled but no submit happened → NOT a payment. Do not fabricate success.
|
|
@@ -359,7 +1059,7 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
|
359
1059
|
const outcome = await detectPaymentOutcome(page, checkoutUrl);
|
|
360
1060
|
return outcomeToResult(outcome, modeNote);
|
|
361
1061
|
}
|
|
362
|
-
// hints provided but
|
|
1062
|
+
// hints provided but the card number could not be placed → fall through to Strategy 1
|
|
363
1063
|
}
|
|
364
1064
|
// ============================================================
|
|
365
1065
|
// STRATEGY 1: Standard HTML form fields
|
|
@@ -435,89 +1135,79 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
|
435
1135
|
],
|
|
436
1136
|
};
|
|
437
1137
|
// Card Number
|
|
438
|
-
if (await tryFillField(page, S.number, cardData.number))
|
|
1138
|
+
if (await tryFillField(gate, page, S.number, cardData.number, 'number')) {
|
|
439
1139
|
filledFields++;
|
|
1140
|
+
cardNumberFilled = true;
|
|
1141
|
+
}
|
|
440
1142
|
// Expiry: try combined MM/YY first
|
|
441
1143
|
const expiryValue = `${cardData.exp_month}/${cardData.exp_year.slice(-2)}`;
|
|
442
|
-
let expiryFilled = await tryFillField(page, S.expiry, expiryValue);
|
|
1144
|
+
let expiryFilled = await tryFillField(gate, page, S.expiry, expiryValue, 'exp');
|
|
443
1145
|
if (expiryFilled)
|
|
444
1146
|
filledFields++;
|
|
445
1147
|
// Expiry: fallback to separate month + year (works with both <input> AND <select>)
|
|
446
1148
|
if (!expiryFilled) {
|
|
447
|
-
if (await tryFillField(page, S.exp_month, cardData.exp_month))
|
|
1149
|
+
if (await tryFillField(gate, page, S.exp_month, cardData.exp_month, 'exp'))
|
|
448
1150
|
filledFields++;
|
|
449
|
-
if (await tryFillField(page, S.exp_year, cardData.exp_year))
|
|
1151
|
+
if (await tryFillField(gate, page, S.exp_year, cardData.exp_year, 'exp'))
|
|
450
1152
|
filledFields++;
|
|
451
1153
|
}
|
|
452
1154
|
// CVV
|
|
453
|
-
if (await tryFillField(page, S.cvv, cardData.cvv))
|
|
1155
|
+
if (await tryFillField(gate, page, S.cvv, cardData.cvv, 'cvv'))
|
|
454
1156
|
filledFields++;
|
|
455
1157
|
// Name on Card
|
|
456
|
-
if (await tryFillField(page, S.name, cardData.name))
|
|
1158
|
+
if (await tryFillField(gate, page, S.name, cardData.name, 'name'))
|
|
457
1159
|
filledFields++;
|
|
1160
|
+
const stopped1 = stopIfMoved();
|
|
1161
|
+
if (stopped1)
|
|
1162
|
+
return stopped1;
|
|
458
1163
|
// ============================================================
|
|
459
1164
|
// STRATEGY 2: Stripe Elements (iframe-based)
|
|
460
1165
|
// Stripe renders payment inputs inside iframes from js.stripe.com.
|
|
461
|
-
// Some merchants use __privateStripeFrame* named frames.
|
|
462
1166
|
// Stripe has 2 modes:
|
|
463
1167
|
// - Unified: 1 iframe with all fields (card, exp, cvc in one)
|
|
464
1168
|
// - Split: separate iframes per field (cardNumber, cardExpiry, cardCvc)
|
|
465
1169
|
// We handle both by scanning ALL matching Stripe frames.
|
|
466
1170
|
// ============================================================
|
|
467
|
-
if (
|
|
1171
|
+
if (!cardNumberFilled) {
|
|
1172
|
+
await page.waitForLoadState("load", { timeout: 10_000 }).catch(() => { });
|
|
468
1173
|
// Recognised by the frame's real origin, never by its name or a substring of
|
|
469
1174
|
// its URL: any frame can call itself __privateStripeFrame or carry
|
|
470
1175
|
// "js.stripe.com" in a query string (audit MCP-03 / N3).
|
|
471
1176
|
const stripeFrames = page.frames().filter((f) => {
|
|
472
1177
|
try {
|
|
473
|
-
const
|
|
474
|
-
return
|
|
1178
|
+
const u = new URL(f.url());
|
|
1179
|
+
return u.protocol === 'https:' && (u.hostname === 'stripe.com' || u.hostname.endsWith('.stripe.com'));
|
|
475
1180
|
}
|
|
476
1181
|
catch {
|
|
477
1182
|
return false;
|
|
478
1183
|
}
|
|
479
1184
|
});
|
|
480
1185
|
for (const frame of stripeFrames) {
|
|
481
|
-
|
|
482
|
-
for (const sel of [
|
|
1186
|
+
if (await tryFillField(gate, frame, [
|
|
483
1187
|
'input[name="cardnumber"]',
|
|
484
1188
|
'input[autocomplete="cc-number"]',
|
|
485
1189
|
'input[data-elements-stable-field-name="cardNumber"]',
|
|
486
|
-
]) {
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
await el.fill(cardData.number);
|
|
490
|
-
filledFields++;
|
|
491
|
-
break;
|
|
492
|
-
}
|
|
1190
|
+
], cardData.number, 'number')) {
|
|
1191
|
+
filledFields++;
|
|
1192
|
+
cardNumberFilled = true;
|
|
493
1193
|
}
|
|
494
1194
|
// Expiry (Stripe uses MM/YY without slash)
|
|
495
|
-
|
|
1195
|
+
if (await tryFillField(gate, frame, [
|
|
496
1196
|
'input[name="exp-date"]',
|
|
497
1197
|
'input[autocomplete="cc-exp"]',
|
|
498
1198
|
'input[data-elements-stable-field-name="cardExpiry"]',
|
|
499
|
-
])
|
|
500
|
-
|
|
501
|
-
|
|
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 [
|
|
1199
|
+
], `${cardData.exp_month}${cardData.exp_year.slice(-2)}`, 'exp'))
|
|
1200
|
+
filledFields++;
|
|
1201
|
+
if (await tryFillField(gate, frame, [
|
|
509
1202
|
'input[name="cvc"]',
|
|
510
1203
|
'input[autocomplete="cc-csc"]',
|
|
511
1204
|
'input[data-elements-stable-field-name="cardCvc"]',
|
|
512
|
-
])
|
|
513
|
-
|
|
514
|
-
if (el) {
|
|
515
|
-
await el.fill(cardData.cvv);
|
|
516
|
-
filledFields++;
|
|
517
|
-
break;
|
|
518
|
-
}
|
|
519
|
-
}
|
|
1205
|
+
], cardData.cvv, 'cvv'))
|
|
1206
|
+
filledFields++;
|
|
520
1207
|
}
|
|
1208
|
+
const stopped2 = stopIfMoved();
|
|
1209
|
+
if (stopped2)
|
|
1210
|
+
return stopped2;
|
|
521
1211
|
}
|
|
522
1212
|
if (filledFields === 0) {
|
|
523
1213
|
return {
|
|
@@ -525,11 +1215,12 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
|
525
1215
|
status: 'no_fields',
|
|
526
1216
|
message: "Could not detect any credit card fields on this page. " +
|
|
527
1217
|
(landedElsewhere
|
|
528
|
-
?
|
|
1218
|
+
? "The checkout URL redirected elsewhere (see page_detail) — the cart/session likely did not carry over. " +
|
|
529
1219
|
"Z-Zero opens its OWN fresh browser, so checkout_url must be resumable on its own " +
|
|
530
1220
|
"(e.g. a Shopify/Etsy checkout-token URL), not a page that needs the agent's logged-in session. "
|
|
531
1221
|
: "") +
|
|
532
1222
|
"The checkout form may use an unsupported format, or the page requires a logged-in session.",
|
|
1223
|
+
...(landedElsewhere ? { page_detail: `landed on: ${landedUrl}` } : {}),
|
|
533
1224
|
};
|
|
534
1225
|
}
|
|
535
1226
|
// ============================================================
|
|
@@ -545,9 +1236,13 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
|
545
1236
|
];
|
|
546
1237
|
let clicked = false;
|
|
547
1238
|
for (const selector of payButtonSelectors) {
|
|
548
|
-
const btn = await page.$(selector);
|
|
549
|
-
if (btn
|
|
550
|
-
|
|
1239
|
+
const btn = await page.$(selector).catch(() => null);
|
|
1240
|
+
if (!btn)
|
|
1241
|
+
continue;
|
|
1242
|
+
const c = await clickIfStillLocked(gate, btn, dealState);
|
|
1243
|
+
if (typeof c === 'object')
|
|
1244
|
+
return { success: false, status: 'blocked', message: c.ok ? '' : c.reason };
|
|
1245
|
+
if (c === 'clicked') {
|
|
551
1246
|
clicked = true;
|
|
552
1247
|
break;
|
|
553
1248
|
}
|
|
@@ -568,14 +1263,15 @@ async function _fillCheckoutFormInner(page, checkoutUrl, cardData, hints) {
|
|
|
568
1263
|
return outcomeToResult(outcome, fieldNote);
|
|
569
1264
|
}
|
|
570
1265
|
catch (error) {
|
|
571
|
-
const errMsg = error instanceof Error ? error.message : String(error);
|
|
572
1266
|
return {
|
|
573
1267
|
success: false,
|
|
574
1268
|
status: 'error',
|
|
575
|
-
message:
|
|
1269
|
+
message: 'The browser failed during the checkout attempt.',
|
|
1270
|
+
page_detail: error instanceof Error ? error.message : String(error),
|
|
576
1271
|
};
|
|
577
1272
|
}
|
|
578
1273
|
finally {
|
|
1274
|
+
gate.dispose();
|
|
579
1275
|
// ============================================================
|
|
580
1276
|
// RAM WIPE - Critical security step
|
|
581
1277
|
// ============================================================
|