z-zero-mcp-server 1.10.3 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -9
- package/dist/base_backend.d.ts +2 -0
- package/dist/base_backend.js +23 -4
- package/dist/failure_taxonomy.d.ts +13 -6
- package/dist/failure_taxonomy.js +76 -6
- package/dist/index.js +365 -245
- package/dist/lib/api-base.d.ts +4 -1
- package/dist/lib/api-base.js +50 -17
- package/dist/lib/domain-lock.d.ts +16 -0
- package/dist/lib/domain-lock.js +142 -0
- package/dist/lib/extract-total-price.d.ts +23 -17
- package/dist/lib/extract-total-price.js +146 -139
- package/dist/lib/key-store.d.ts +25 -2
- package/dist/lib/key-store.js +175 -25
- package/dist/lib/url-guard.d.ts +10 -0
- package/dist/lib/url-guard.js +83 -1
- package/dist/playwright_bridge.d.ts +9 -1
- package/dist/playwright_bridge.js +379 -138
- package/dist/types.d.ts +3 -1
- package/dist/ucp_bridge.d.ts +1 -10
- package/dist/ucp_bridge.js +16 -66
- package/package.json +5 -3
- package/dist/lib/web3-detector.d.ts +0 -19
- package/dist/lib/web3-detector.js +0 -157
package/dist/lib/api-base.d.ts
CHANGED
|
@@ -1,2 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
export declare const CANONICAL_API = "https://z-zero.xyz";
|
|
2
|
+
/** The base URL every request should use: an origin, no path, no trailing slash. */
|
|
2
3
|
export declare function resolveApiBaseUrl(): string;
|
|
4
|
+
/** True when requests go somewhere other than z-zero.xyz. */
|
|
5
|
+
export declare function isCustomApi(): boolean;
|
package/dist/lib/api-base.js
CHANGED
|
@@ -12,9 +12,18 @@
|
|
|
12
12
|
// Rewriting the known legacy hosts here fixes it for every call site at once.
|
|
13
13
|
// We never re-send the key to a redirect target ourselves: that is how a key
|
|
14
14
|
// leaks to whatever host a redirect happens to name.
|
|
15
|
+
//
|
|
16
|
+
// Any other host is OFF unless the machine's owner also sets
|
|
17
|
+
// Z_ZERO_ALLOW_CUSTOM_API=1 (audit T14 F2, M.5). A project folder can carry its
|
|
18
|
+
// own MCP config; one environment variable in it must not be enough to send
|
|
19
|
+
// this machine's Passport Key somewhere else. And even when allowed, a custom
|
|
20
|
+
// host gets its own credentials file (lib/key-store.ts) — a key stored for
|
|
21
|
+
// z-zero.xyz is never sent to it.
|
|
15
22
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
23
|
+
exports.CANONICAL_API = void 0;
|
|
16
24
|
exports.resolveApiBaseUrl = resolveApiBaseUrl;
|
|
17
|
-
|
|
25
|
+
exports.isCustomApi = isCustomApi;
|
|
26
|
+
exports.CANONICAL_API = "https://z-zero.xyz";
|
|
18
27
|
// Hosts that 30x to CANONICAL. Same origin in spirit, different origin to fetch.
|
|
19
28
|
// clawcard.store is the pre-rebrand domain and is still in real configs.
|
|
20
29
|
const LEGACY_HOSTS = new Set([
|
|
@@ -24,28 +33,52 @@ const LEGACY_HOSTS = new Set([
|
|
|
24
33
|
"clawcard.store",
|
|
25
34
|
"www.clawcard.store",
|
|
26
35
|
]);
|
|
27
|
-
|
|
28
|
-
|
|
36
|
+
const warnedFor = new Set();
|
|
37
|
+
function warnOnce(key, msg) {
|
|
38
|
+
if (warnedFor.has(key))
|
|
39
|
+
return;
|
|
40
|
+
warnedFor.add(key);
|
|
41
|
+
console.error(msg);
|
|
42
|
+
}
|
|
43
|
+
/** The base URL every request should use: an origin, no path, no trailing slash. */
|
|
29
44
|
function resolveApiBaseUrl() {
|
|
30
|
-
const raw = (process.env.Z_ZERO_API_BASE_URL ||
|
|
31
|
-
|
|
32
|
-
|
|
45
|
+
const raw = (process.env.Z_ZERO_API_BASE_URL || process.env.Z_ZERO_API_BASE || "").trim();
|
|
46
|
+
if (!raw)
|
|
47
|
+
return exports.CANONICAL_API;
|
|
33
48
|
let url;
|
|
34
49
|
try {
|
|
35
50
|
url = new URL(raw);
|
|
36
51
|
}
|
|
37
52
|
catch {
|
|
38
|
-
|
|
39
|
-
return
|
|
53
|
+
warnOnce("invalid", `[Z-ZERO MCP] ⚠️ Z_ZERO_API_BASE_URL is not a valid URL — using ${exports.CANONICAL_API}.`);
|
|
54
|
+
return exports.CANONICAL_API;
|
|
55
|
+
}
|
|
56
|
+
const host = url.hostname.toLowerCase();
|
|
57
|
+
if (host === new URL(exports.CANONICAL_API).hostname && url.protocol === "https:" && url.port === "")
|
|
58
|
+
return exports.CANONICAL_API;
|
|
59
|
+
if (LEGACY_HOSTS.has(host)) {
|
|
60
|
+
warnOnce("legacy", `[Z-ZERO MCP] ⚠️ Z_ZERO_API_BASE_URL points at ${host}, which redirects to z-zero.xyz. ` +
|
|
61
|
+
`A cross-origin redirect strips the Authorization header, so every call would fail as 401. ` +
|
|
62
|
+
`Using ${exports.CANONICAL_API} instead — please update your MCP config.`);
|
|
63
|
+
return exports.CANONICAL_API;
|
|
40
64
|
}
|
|
41
|
-
if (
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
`A cross-origin redirect strips the Authorization header, so every call would fail as 401. ` +
|
|
46
|
-
`Using ${CANONICAL} instead — please update your MCP config.`);
|
|
47
|
-
}
|
|
48
|
-
return CANONICAL;
|
|
65
|
+
if (process.env.Z_ZERO_ALLOW_CUSTOM_API !== "1") {
|
|
66
|
+
warnOnce("custom-off", `[Z-ZERO MCP] ⚠️ Z_ZERO_API_BASE_URL (${url.host}) is IGNORED — using ${exports.CANONICAL_API}. ` +
|
|
67
|
+
`To run against your own Z-ZERO server, also set Z_ZERO_ALLOW_CUSTOM_API=1.`);
|
|
68
|
+
return exports.CANONICAL_API;
|
|
49
69
|
}
|
|
50
|
-
|
|
70
|
+
// The Passport Key rides on every request to this host, so it must be HTTPS.
|
|
71
|
+
// Plain http only for a server on this machine.
|
|
72
|
+
const isLocal = host === "localhost" || host === "127.0.0.1";
|
|
73
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && isLocal)) {
|
|
74
|
+
warnOnce("custom-http", `[Z-ZERO MCP] ⚠️ Z_ZERO_API_BASE_URL must be https — using ${exports.CANONICAL_API} instead.`);
|
|
75
|
+
return exports.CANONICAL_API;
|
|
76
|
+
}
|
|
77
|
+
warnOnce("custom-on", `[Z-ZERO MCP] ⚠️ Custom API ${url.origin} is ON (Z_ZERO_ALLOW_CUSTOM_API=1). ` +
|
|
78
|
+
`It gets its own key file; your z-zero.xyz key is not sent there.`);
|
|
79
|
+
return url.origin;
|
|
80
|
+
}
|
|
81
|
+
/** True when requests go somewhere other than z-zero.xyz. */
|
|
82
|
+
function isCustomApi() {
|
|
83
|
+
return resolveApiBaseUrl() !== exports.CANONICAL_API;
|
|
51
84
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export type LockCheck = {
|
|
2
|
+
ok: true;
|
|
3
|
+
} | {
|
|
4
|
+
ok: false;
|
|
5
|
+
reason: string;
|
|
6
|
+
};
|
|
7
|
+
/** Check 1 — the URL the agent wants us to pay on, before opening anything. */
|
|
8
|
+
export declare function checkCheckoutUrl(checkoutUrl: string, lockedDomain: string | null | undefined): LockCheck;
|
|
9
|
+
/** Check 2 — the page actually in front of us, right before the card is typed. */
|
|
10
|
+
export declare function checkPaymentPage(pageUrl: string, lockedDomain: string | null | undefined): LockCheck;
|
|
11
|
+
/**
|
|
12
|
+
* May a card field inside this frame receive card data? Only when the frame
|
|
13
|
+
* really comes from the locked store or a payment provider — judged by its
|
|
14
|
+
* origin, never by the frame's self-chosen name (audit MCP-03 / N3).
|
|
15
|
+
*/
|
|
16
|
+
export declare function isTrustedCardFrame(frameUrl: string, lockedDomain: string | null | undefined): boolean;
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// domain-lock.ts
|
|
3
|
+
// Where a card may be typed (founder decision 23/10/2026). Each card is locked
|
|
4
|
+
// at issue time to the store's domain; the server returns it with the card
|
|
5
|
+
// (/api/tokens/resolve → merchant_domain). Two checks use it:
|
|
6
|
+
// 1. the checkout_url the agent hands us must be on that domain — before any
|
|
7
|
+
// browser opens;
|
|
8
|
+
// 2. the page in front of us when each field is typed must be on that domain,
|
|
9
|
+
// or on a hosted payment page a store hands off to (Stripe Checkout,
|
|
10
|
+
// PayPal…). playwright_bridge.ts asks again for every field (CardGate).
|
|
11
|
+
// A reseller wrapping someone else's payment link, or a look-alike page, fails
|
|
12
|
+
// check 1; a redirect away from the store to anywhere else fails check 2.
|
|
13
|
+
//
|
|
14
|
+
// Both checks want the plain public web: https on the default port, not a
|
|
15
|
+
// `*.localhost` name (audit T11 F3/F6, T19). A store's own domain covers its
|
|
16
|
+
// subdomains (shop.x.com for x.com) — never the other way round: a card locked
|
|
17
|
+
// to alice.gumroad.com is not a card for gumroad.com (audit T11 F5).
|
|
18
|
+
//
|
|
19
|
+
// Known residue: a hosted payment page is trusted by host only, so a store that
|
|
20
|
+
// redirects to SOMEONE ELSE's Stripe/PayPal page passes. The issuer-side caps
|
|
21
|
+
// ($50, single use, no cash/funding) bound that case.
|
|
22
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
23
|
+
exports.checkCheckoutUrl = checkCheckoutUrl;
|
|
24
|
+
exports.checkPaymentPage = checkPaymentPage;
|
|
25
|
+
exports.isTrustedCardFrame = isTrustedCardFrame;
|
|
26
|
+
/** Hosted payment pages a store may legitimately hand the buyer off to. */
|
|
27
|
+
const PAYMENT_PAGE_HOSTS = [
|
|
28
|
+
"checkout.shopify.com",
|
|
29
|
+
"shop.app",
|
|
30
|
+
"checkout.stripe.com",
|
|
31
|
+
"buy.stripe.com",
|
|
32
|
+
"paypal.com",
|
|
33
|
+
"checkoutshopper-live.adyen.com",
|
|
34
|
+
"checkout.square.site",
|
|
35
|
+
"square.link",
|
|
36
|
+
"pay.checkout.com",
|
|
37
|
+
];
|
|
38
|
+
/**
|
|
39
|
+
* Suffixes for the same. `.myshopify.com` is NOT here (audit T11 F1): every
|
|
40
|
+
* Shopify store, a stranger's included, lives under it. A store whose own
|
|
41
|
+
* domain is x.myshopify.com is still covered by its lock.
|
|
42
|
+
*/
|
|
43
|
+
const PAYMENT_PAGE_SUFFIXES = [".paypal.com"];
|
|
44
|
+
/** The machine owner's explicit opt-in for a checkout served from this machine (tests). */
|
|
45
|
+
function localCheckoutAllowed(url) {
|
|
46
|
+
return process.env.Z_ZERO_ALLOW_LOCAL_CHECKOUT === "1" &&
|
|
47
|
+
(url.hostname === "localhost" || url.hostname === "127.0.0.1");
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The host of a URL a card may go to, or null: https only, default port only,
|
|
51
|
+
* no `*.localhost`. (The local opt-in above is the one exception.)
|
|
52
|
+
*/
|
|
53
|
+
function publicHostOf(raw) {
|
|
54
|
+
let url;
|
|
55
|
+
try {
|
|
56
|
+
url = new URL(raw);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
const host = url.hostname.toLowerCase().replace(/\.$/, "");
|
|
62
|
+
if (localCheckoutAllowed(url))
|
|
63
|
+
return host;
|
|
64
|
+
if (url.protocol !== "https:" || url.port !== "")
|
|
65
|
+
return null;
|
|
66
|
+
if (host === "localhost" || host.endsWith(".localhost"))
|
|
67
|
+
return null;
|
|
68
|
+
return host.replace(/^www\./, "");
|
|
69
|
+
}
|
|
70
|
+
/** Same store: equal, or a subdomain of the locked domain (shop.x.com for x.com). */
|
|
71
|
+
function sameSite(host, locked) {
|
|
72
|
+
const l = locked.toLowerCase().replace(/^www\./, "").replace(/\.$/, "");
|
|
73
|
+
return host === l || host.endsWith("." + l);
|
|
74
|
+
}
|
|
75
|
+
function isPaymentPage(host) {
|
|
76
|
+
return PAYMENT_PAGE_HOSTS.includes(host) || PAYMENT_PAGE_SUFFIXES.some((s) => host.endsWith(s));
|
|
77
|
+
}
|
|
78
|
+
function describe(raw) {
|
|
79
|
+
try {
|
|
80
|
+
const u = new URL(raw);
|
|
81
|
+
return `${u.protocol}//${u.host}`;
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return "an unreadable address";
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function noLock() {
|
|
88
|
+
return {
|
|
89
|
+
ok: false,
|
|
90
|
+
reason: "This card has no merchant domain lock (issued before the lock existed, or for a merchant name instead of a domain). " +
|
|
91
|
+
"Cancel it with cancel_payment_token and request a new card with merchant = the store's domain.",
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/** Check 1 — the URL the agent wants us to pay on, before opening anything. */
|
|
95
|
+
function checkCheckoutUrl(checkoutUrl, lockedDomain) {
|
|
96
|
+
if (!lockedDomain)
|
|
97
|
+
return noLock();
|
|
98
|
+
const host = publicHostOf(checkoutUrl);
|
|
99
|
+
if (host && sameSite(host, lockedDomain))
|
|
100
|
+
return { ok: true };
|
|
101
|
+
return {
|
|
102
|
+
ok: false,
|
|
103
|
+
reason: host
|
|
104
|
+
? `checkout_url is on ${host}, but this card is locked to ${lockedDomain}. The card is only typed on the store it was issued for.`
|
|
105
|
+
: `checkout_url ${describe(checkoutUrl)} is not a plain https page on the default port. The card is only typed on https://${lockedDomain}.`,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
/** Check 2 — the page actually in front of us, right before the card is typed. */
|
|
109
|
+
function checkPaymentPage(pageUrl, lockedDomain) {
|
|
110
|
+
if (!lockedDomain)
|
|
111
|
+
return noLock();
|
|
112
|
+
const host = publicHostOf(pageUrl);
|
|
113
|
+
if (host && (sameSite(host, lockedDomain) || isPaymentPage(host)))
|
|
114
|
+
return { ok: true };
|
|
115
|
+
return {
|
|
116
|
+
ok: false,
|
|
117
|
+
reason: `The page moved to ${describe(pageUrl)}, which is neither https://${lockedDomain} nor a known payment page. ` +
|
|
118
|
+
`The card was NOT typed in.`,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Card-field iframe providers. Exact provider domains only: `.shopify.com` was
|
|
123
|
+
* here and covers cdn.shopify.com, where any store uploads files — an uploaded
|
|
124
|
+
* SVG served from there passed as a "card frame" (audit T11 F4 / T19).
|
|
125
|
+
*/
|
|
126
|
+
const CARD_FRAME_SUFFIXES = [
|
|
127
|
+
".stripe.com", ".shopifyinc.com", ".shopifycs.com", ".braintreegateway.com",
|
|
128
|
+
".adyen.com", ".squarecdn.com", ".checkout.com", ".paypal.com",
|
|
129
|
+
];
|
|
130
|
+
/**
|
|
131
|
+
* May a card field inside this frame receive card data? Only when the frame
|
|
132
|
+
* really comes from the locked store or a payment provider — judged by its
|
|
133
|
+
* origin, never by the frame's self-chosen name (audit MCP-03 / N3).
|
|
134
|
+
*/
|
|
135
|
+
function isTrustedCardFrame(frameUrl, lockedDomain) {
|
|
136
|
+
const host = publicHostOf(frameUrl);
|
|
137
|
+
if (!host)
|
|
138
|
+
return false;
|
|
139
|
+
if (lockedDomain && sameSite(host, lockedDomain))
|
|
140
|
+
return true;
|
|
141
|
+
return CARD_FRAME_SUFFIXES.some((s) => host === s.slice(1) || host.endsWith(s));
|
|
142
|
+
}
|
|
@@ -1,22 +1,28 @@
|
|
|
1
1
|
import type { Page } from "playwright";
|
|
2
|
+
export type PriceCurrency = "USD" | "NON_USD";
|
|
3
|
+
export interface DetectedPrice {
|
|
4
|
+
amount: number;
|
|
5
|
+
currency: PriceCurrency;
|
|
6
|
+
/** The visible text the number came from (page data — untrusted). */
|
|
7
|
+
source: string;
|
|
8
|
+
}
|
|
9
|
+
/** "1,234.56" · "0,49" · "1.234,56" · "1,234" · "49" → number, or null. */
|
|
10
|
+
export declare function parseAmount(raw: string): number | null;
|
|
2
11
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* 1. Known CSS selectors for major platforms (Shopify, Stripe, Woo)
|
|
6
|
-
* 2. Aria / data-testid patterns
|
|
7
|
-
* 3. Text heuristic: find largest $ amount near keywords "total", "amount due"
|
|
12
|
+
* A price in a string: a number with a currency mark right before or after it.
|
|
13
|
+
* Returns null when there is no such pair.
|
|
8
14
|
*/
|
|
9
|
-
export declare function
|
|
15
|
+
export declare function parsePriceText(text: string): DetectedPrice | null;
|
|
10
16
|
/**
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
* issuer decline. So non-USD orders need a slightly larger card limit.
|
|
16
|
-
*
|
|
17
|
-
* Conservative by design: defaults to 'USD' unless a CLEAR non-USD signal is
|
|
18
|
-
* present. Both error directions are non-catastrophic (over-buffer → refunded
|
|
19
|
-
* at settlement; under-buffer → a decline the agent can retry), so we avoid
|
|
20
|
-
* false positives from random uppercase text via a currency-code whitelist.
|
|
17
|
+
* Multi-strategy total price extractor, visible text only.
|
|
18
|
+
* 1. Known total selectors for major platforms (Shopify, Stripe, Woo, generic)
|
|
19
|
+
* 2. Short visible texts that mention "total" / "amount due" / "you pay"
|
|
20
|
+
* 3. Median of all visible prices on the page (low confidence)
|
|
21
21
|
*/
|
|
22
|
-
export declare function
|
|
22
|
+
export declare function extractTotalPrice(page: Page): Promise<DetectedPrice | null>;
|
|
23
|
+
/**
|
|
24
|
+
* Does the page as a whole show a currency other than US dollars? A "$" alone
|
|
25
|
+
* is also how CAD/AUD/… stores print prices, so a "$" total on a page that
|
|
26
|
+
* mentions another currency is not taken as USD. Visible text only.
|
|
27
|
+
*/
|
|
28
|
+
export declare function pageMentionsOtherCurrency(page: Page): Promise<boolean>;
|
|
@@ -1,165 +1,172 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
// extract-total-price.ts
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
3
|
+
// Reads the checkout total off a page for auto_pay_checkout — as a CROSS-CHECK
|
|
4
|
+
// against the ceiling the agent passes (max_amount), never as the authority.
|
|
5
|
+
//
|
|
6
|
+
// Rules (audit T12 F4, T13 F3; M.3):
|
|
7
|
+
// - only text a person can see counts: not display:none, not transparent,
|
|
8
|
+
// not a 0px font, not parked off-screen. A page used to get a $5 item
|
|
9
|
+
// charged as $49 by hiding "$49.00" somewhere;
|
|
10
|
+
// - a number is a price only with a currency mark next to it ("48 items" is
|
|
11
|
+
// not $48);
|
|
12
|
+
// - "0,49 $" is forty-nine cents, "1.234,56 €" is one thousand two hundred…;
|
|
13
|
+
// - the currency is read with the number. Anything not clearly US dollars is
|
|
14
|
+
// reported as such; the caller does not convert it.
|
|
6
15
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
+
exports.parseAmount = parseAmount;
|
|
17
|
+
exports.parsePriceText = parsePriceText;
|
|
7
18
|
exports.extractTotalPrice = extractTotalPrice;
|
|
8
|
-
exports.
|
|
19
|
+
exports.pageMentionsOtherCurrency = pageMentionsOtherCurrency;
|
|
20
|
+
const NON_USD_SYMBOL = /[€£¥₹₩₺₽฿₴₫₱₦₪]|\b(?:CA|C|A|AU|NZ|HK|R|S|SG|MX|NT)\$/;
|
|
21
|
+
const NON_USD_CODE = /\b(?:EUR|GBP|JPY|CNY|RMB|INR|AUD|CAD|CHF|SGD|HKD|NZD|SEK|NOK|DKK|KRW|MXN|BRL|ZAR|AED|THB|MYR|PHP|VND|IDR|PLN|TRY|TWD|ILS|CZK|HUF)\b/;
|
|
22
|
+
const USD_MARK = /US\$|\bUSD\b|\$/;
|
|
23
|
+
/** "1,234.56" · "0,49" · "1.234,56" · "1,234" · "49" → number, or null. */
|
|
24
|
+
function parseAmount(raw) {
|
|
25
|
+
const s = raw.replace(/[\s ']/g, "");
|
|
26
|
+
if (!/^\d[\d.,]*$/.test(s))
|
|
27
|
+
return null;
|
|
28
|
+
const lastDot = s.lastIndexOf(".");
|
|
29
|
+
const lastComma = s.lastIndexOf(",");
|
|
30
|
+
let normalized;
|
|
31
|
+
if (lastDot >= 0 && lastComma >= 0) {
|
|
32
|
+
// The later separator is the decimal one.
|
|
33
|
+
normalized = lastDot > lastComma ? s.replace(/,/g, "") : s.replace(/\./g, "").replace(",", ".");
|
|
34
|
+
}
|
|
35
|
+
else if (lastComma >= 0) {
|
|
36
|
+
const decimals = s.length - lastComma - 1;
|
|
37
|
+
// "1,234" / "12,345,678" = thousands; "0,49" / "12,5" = decimals
|
|
38
|
+
normalized = decimals === 3 && /^\d{1,3}(,\d{3})+$/.test(s) ? s.replace(/,/g, "") : s.replace(/,(?=\d+$)/, ".").replace(/,/g, "");
|
|
39
|
+
}
|
|
40
|
+
else if (lastDot >= 0) {
|
|
41
|
+
const decimals = s.length - lastDot - 1;
|
|
42
|
+
normalized = decimals === 3 && /^\d{1,3}(\.\d{3})+$/.test(s) ? s.replace(/\./g, "") : s;
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
normalized = s;
|
|
46
|
+
}
|
|
47
|
+
const v = Number(normalized);
|
|
48
|
+
return Number.isFinite(v) && v > 0 ? Math.round(v * 100) / 100 : null;
|
|
49
|
+
}
|
|
9
50
|
/**
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
51
|
+
* A price in a string: a number with a currency mark right before or after it.
|
|
52
|
+
* Returns null when there is no such pair.
|
|
53
|
+
*/
|
|
54
|
+
function parsePriceText(text) {
|
|
55
|
+
const t = text.normalize("NFKC");
|
|
56
|
+
const MONEY = /((?:[A-Z]{2,3})?\$|US\$|[€£¥₹₩₺₽฿₴₫₱₦₪]|\b[A-Z]{3}\b)?\s*(\d[\d.,\s ]*\d|\d)\s*((?:[A-Z]{2,3})?\$|[€£¥₹₩₺₽฿₴₫₱₦₪]|\b[A-Z]{3}\b)?/g;
|
|
57
|
+
for (const m of t.matchAll(MONEY)) {
|
|
58
|
+
const before = m[1] || "";
|
|
59
|
+
const after = m[3] || "";
|
|
60
|
+
const mark = (before + " " + after).trim();
|
|
61
|
+
if (!mark)
|
|
62
|
+
continue;
|
|
63
|
+
const isNonUsd = NON_USD_SYMBOL.test(mark) || NON_USD_CODE.test(mark);
|
|
64
|
+
const isUsd = !isNonUsd && USD_MARK.test(mark);
|
|
65
|
+
if (!isNonUsd && !isUsd)
|
|
66
|
+
continue; // e.g. "48 ITEMS"
|
|
67
|
+
const amount = parseAmount(m[2]);
|
|
68
|
+
if (amount === null)
|
|
69
|
+
continue;
|
|
70
|
+
return { amount, currency: isUsd ? "USD" : "NON_USD", source: m[0].trim().slice(0, 40) };
|
|
71
|
+
}
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Multi-strategy total price extractor, visible text only.
|
|
76
|
+
* 1. Known total selectors for major platforms (Shopify, Stripe, Woo, generic)
|
|
77
|
+
* 2. Short visible texts that mention "total" / "amount due" / "you pay"
|
|
78
|
+
* 3. Median of all visible prices on the page (low confidence)
|
|
15
79
|
*/
|
|
16
80
|
async function extractTotalPrice(page) {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
81
|
+
const candidates = await page.evaluate(() => {
|
|
82
|
+
const visible = (el) => {
|
|
83
|
+
const r = el.getBoundingClientRect();
|
|
84
|
+
if (r.width < 1 || r.height < 1)
|
|
85
|
+
return false;
|
|
86
|
+
const docW = Math.max(document.documentElement.scrollWidth, window.innerWidth);
|
|
87
|
+
const docH = Math.max(document.documentElement.scrollHeight, window.innerHeight);
|
|
88
|
+
const left = r.left + window.scrollX;
|
|
89
|
+
const top = r.top + window.scrollY;
|
|
90
|
+
if (left + r.width <= 0 || top + r.height <= 0 || left >= docW || top >= docH)
|
|
91
|
+
return false;
|
|
92
|
+
let opacity = 1;
|
|
93
|
+
for (let n = el; n; n = n.parentElement) {
|
|
94
|
+
const s = getComputedStyle(n);
|
|
95
|
+
if (s.display === "none" || s.visibility === "hidden")
|
|
96
|
+
return false;
|
|
97
|
+
opacity *= parseFloat(s.opacity || "1");
|
|
98
|
+
}
|
|
99
|
+
if (opacity < 0.1)
|
|
100
|
+
return false;
|
|
101
|
+
return parseFloat(getComputedStyle(el).fontSize || "16") >= 6;
|
|
102
|
+
};
|
|
103
|
+
const textOf = (el) => (el.innerText || "").trim();
|
|
104
|
+
const out = [];
|
|
105
|
+
const known = [
|
|
106
|
+
'[data-checkout-payment-amount]', '.payment-due__price',
|
|
107
|
+
'[data-testid="total-amount"]', '.OrderAmountRow--total .OrderAmountRow-amount',
|
|
108
|
+
'.order-total .amount', '.woocommerce-Price-amount.amount',
|
|
109
|
+
'[data-testid*="total" i]', '[class*="order-total" i]', '[class*="total-price" i]',
|
|
110
|
+
'[class*="grand-total" i]', '[id*="order-total" i]', '[id*="grand-total" i]',
|
|
111
|
+
'span[class*="total"]', 'td[class*="total"]',
|
|
112
|
+
];
|
|
113
|
+
for (const sel of known) {
|
|
114
|
+
for (const el of Array.from(document.querySelectorAll(sel))) {
|
|
115
|
+
if (visible(el))
|
|
116
|
+
out.push({ strategy: 1, text: textOf(el) });
|
|
48
117
|
}
|
|
49
118
|
}
|
|
50
|
-
|
|
51
|
-
|
|
119
|
+
for (const el of Array.from(document.querySelectorAll("body *"))) {
|
|
120
|
+
if (el.children.length >= 5)
|
|
121
|
+
continue;
|
|
122
|
+
const t = textOf(el).toLowerCase();
|
|
123
|
+
if ((t.includes("total") || t.includes("amount due") || t.includes("you pay")) && t.length < 200 && visible(el)) {
|
|
124
|
+
out.push({ strategy: 2, text: textOf(el) });
|
|
125
|
+
}
|
|
52
126
|
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
.filter((el) => {
|
|
59
|
-
if (!(el instanceof HTMLElement))
|
|
60
|
-
return false;
|
|
61
|
-
const style = window.getComputedStyle(el);
|
|
62
|
-
return style.display !== 'none' && style.visibility !== 'hidden';
|
|
63
|
-
})
|
|
64
|
-
.filter(el => {
|
|
65
|
-
const text = el.innerText?.toLowerCase() ?? '';
|
|
66
|
-
return ((text.includes('total') || text.includes('amount due') || text.includes('you pay')) &&
|
|
67
|
-
el.children.length < 5 // narrow to leaf-ish nodes
|
|
68
|
-
);
|
|
69
|
-
})
|
|
70
|
-
.map(el => el.innerText ?? '');
|
|
71
|
-
// Find first valid $ pattern in those elements
|
|
72
|
-
const priceRegex = /\$\s*([\d,]+(?:\.\d{1,2})?)/;
|
|
73
|
-
for (const text of allText) {
|
|
74
|
-
const match = text.match(priceRegex);
|
|
75
|
-
if (match) {
|
|
76
|
-
const value = parseFloat(match[1].replace(/,/g, ''));
|
|
77
|
-
if (value > 0 && value < 10000)
|
|
78
|
-
return value; // sanity bound
|
|
79
|
-
}
|
|
127
|
+
for (const el of Array.from(document.querySelectorAll("body *"))) {
|
|
128
|
+
if (el.children.length === 0 && visible(el)) {
|
|
129
|
+
const t = textOf(el);
|
|
130
|
+
if (t && t.length < 200)
|
|
131
|
+
out.push({ strategy: 3, text: t });
|
|
80
132
|
}
|
|
81
|
-
return null;
|
|
82
|
-
});
|
|
83
|
-
if (amount !== null && amount > 0) {
|
|
84
|
-
console.error(`[PRICE] ✅ Strategy 2 (text heuristic) found: $${amount}`);
|
|
85
|
-
return amount;
|
|
86
133
|
}
|
|
87
|
-
|
|
88
|
-
catch
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
const bodyText = document.body.innerText ?? '';
|
|
96
|
-
const values = [];
|
|
97
|
-
let m;
|
|
98
|
-
while ((m = regex.exec(bodyText)) !== null) {
|
|
99
|
-
const v = parseFloat(m[1].replace(/,/g, ''));
|
|
100
|
-
if (v >= 0.5 && v < 10000)
|
|
101
|
-
values.push(v);
|
|
134
|
+
return out.slice(0, 3000);
|
|
135
|
+
}).catch(() => []);
|
|
136
|
+
for (const strategy of [1, 2]) {
|
|
137
|
+
for (const c of candidates.filter((x) => x.strategy === strategy)) {
|
|
138
|
+
const p = parsePriceText(c.text);
|
|
139
|
+
if (p) {
|
|
140
|
+
console.error(`[PRICE] Strategy ${strategy}: ${p.currency} ${p.amount}`);
|
|
141
|
+
return p;
|
|
102
142
|
}
|
|
103
|
-
if (values.length === 0)
|
|
104
|
-
return null;
|
|
105
|
-
// ✅ FIX 10: Use median instead of max — prevents merchant injecting hidden large price
|
|
106
|
-
values.sort((a, b) => a - b);
|
|
107
|
-
return values[Math.floor(values.length / 2)];
|
|
108
|
-
});
|
|
109
|
-
if (amount !== null && amount > 0) {
|
|
110
|
-
console.error(`[PRICE] ⚠️ Strategy 3 (largest $ on page): $${amount}. Low confidence.`);
|
|
111
|
-
return amount;
|
|
112
143
|
}
|
|
113
144
|
}
|
|
114
|
-
|
|
115
|
-
|
|
145
|
+
// Strategy 3: median of every visible price — low confidence, same currency only.
|
|
146
|
+
const all = candidates.filter((x) => x.strategy === 3)
|
|
147
|
+
.map((c) => parsePriceText(c.text))
|
|
148
|
+
.filter((p) => p !== null && p.amount < 10_000);
|
|
149
|
+
if (all.length > 0) {
|
|
150
|
+
const currency = all.some((p) => p.currency === "NON_USD") ? "NON_USD" : "USD";
|
|
151
|
+
const sorted = all.filter((p) => p.currency === currency).sort((a, b) => a.amount - b.amount);
|
|
152
|
+
const pick = sorted[Math.floor(sorted.length / 2)];
|
|
153
|
+
console.error(`[PRICE] ⚠️ Strategy 3 (median of visible prices): ${pick.currency} ${pick.amount}. Low confidence.`);
|
|
154
|
+
return pick;
|
|
116
155
|
}
|
|
117
156
|
console.error('[PRICE] ❌ Could not detect total price on this page.');
|
|
118
157
|
return null;
|
|
119
158
|
}
|
|
120
159
|
/**
|
|
121
|
-
*
|
|
122
|
-
*
|
|
123
|
-
*
|
|
124
|
-
* a conversion fee on our USD card and can drift OVER the authorized limit →
|
|
125
|
-
* issuer decline. So non-USD orders need a slightly larger card limit.
|
|
126
|
-
*
|
|
127
|
-
* Conservative by design: defaults to 'USD' unless a CLEAR non-USD signal is
|
|
128
|
-
* present. Both error directions are non-catastrophic (over-buffer → refunded
|
|
129
|
-
* at settlement; under-buffer → a decline the agent can retry), so we avoid
|
|
130
|
-
* false positives from random uppercase text via a currency-code whitelist.
|
|
160
|
+
* Does the page as a whole show a currency other than US dollars? A "$" alone
|
|
161
|
+
* is also how CAD/AUD/… stores print prices, so a "$" total on a page that
|
|
162
|
+
* mentions another currency is not taken as USD. Visible text only.
|
|
131
163
|
*/
|
|
132
|
-
async function
|
|
164
|
+
async function pageMentionsOtherCurrency(page) {
|
|
133
165
|
try {
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
// 1. Non-USD currency symbols
|
|
137
|
-
if (/[€£¥₹₩₺₽฿₴]/.test(body))
|
|
138
|
-
return 'NON_USD';
|
|
139
|
-
// 2. Ambiguous "$" with a non-US region prefix (CA$, A$, NZ$, HK$, R$, S$)
|
|
140
|
-
if (/\b(?:CA|A|NZ|HK|R|S)\$/.test(body))
|
|
141
|
-
return 'NON_USD';
|
|
142
|
-
// 3. Explicit 3-letter ISO codes — whitelist of common non-USD only
|
|
143
|
-
const NON_USD = ['EUR', 'GBP', 'JPY', 'CNY', 'INR', 'AUD', 'CAD', 'CHF', 'SGD', 'HKD', 'NZD', 'SEK', 'NOK', 'DKK', 'KRW', 'MXN', 'BRL', 'ZAR', 'AED', 'THB', 'MYR', 'PHP', 'VND', 'IDR', 'PLN', 'TRY'];
|
|
144
|
-
for (const code of NON_USD) {
|
|
145
|
-
if (new RegExp(`\\b${code}\\b`).test(body))
|
|
146
|
-
return 'NON_USD';
|
|
147
|
-
}
|
|
148
|
-
return 'USD';
|
|
149
|
-
});
|
|
166
|
+
const body = await page.evaluate(() => document.body.innerText || "");
|
|
167
|
+
return NON_USD_SYMBOL.test(body) || NON_USD_CODE.test(body);
|
|
150
168
|
}
|
|
151
169
|
catch {
|
|
152
|
-
return
|
|
170
|
+
return false;
|
|
153
171
|
}
|
|
154
172
|
}
|
|
155
|
-
// ─── Utility ─────────────────────────────────────────────────────────────────
|
|
156
|
-
function parseMoneyString(text) {
|
|
157
|
-
// Handles: "$49.99", "USD 49.99", "49,99 $", "49.99 USD"
|
|
158
|
-
const match = text.match(/[\d,]+(?:\.\d{1,2})?/);
|
|
159
|
-
if (!match)
|
|
160
|
-
return null;
|
|
161
|
-
const value = parseFloat(match[0].replace(/,/g, ''));
|
|
162
|
-
if (isNaN(value) || value <= 0)
|
|
163
|
-
return null;
|
|
164
|
-
return value;
|
|
165
|
-
}
|