@tonder.io/ionic-lite-sdk 1.0.1 → 1.0.2-beta.TEC-394.94acdc1
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/dist/helpers/safeUrl.d.ts +15 -0
- package/dist/helpers/sanitize3dsMarkup.d.ts +18 -0
- package/dist/helpers/validations.d.ts +1 -0
- package/dist/index.js +1 -1
- package/jest.config.ts +11 -1
- package/package.json +1 -1
- package/src/classes/3dsHandler.ts +29 -1
- package/src/classes/BaseInlineCheckout.ts +8 -0
- package/src/helpers/safeUrl.ts +26 -0
- package/src/helpers/sanitize3dsMarkup.ts +133 -0
- package/src/helpers/validations.ts +9 -0
- package/src/shared/constants/messages.ts +4 -4
- package/tests/redirectToChallenge.test.ts +149 -0
- package/tests/sanitize3dsMarkup.test.ts +248 -0
- package/tests/secureTokenBoundary.test.ts +81 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scheme check shared by every sink a URL from the 3DS payload can reach: the
|
|
3
|
+
* attributes of the ACS markup and the challenge redirect.
|
|
4
|
+
*
|
|
5
|
+
* Resolution goes through the platform's URL parser rather than a prefix match. The
|
|
6
|
+
* parser strips the leading whitespace and the embedded tabs and newlines a crafted
|
|
7
|
+
* string uses to hide its scheme, and lowercases the result, so "JavaScript:" and a
|
|
8
|
+
* scheme followed by a comment that merely contains the word http are both classified
|
|
9
|
+
* on what they actually are.
|
|
10
|
+
*
|
|
11
|
+
* https only. A production ACS is always https — the card schemes require it — so
|
|
12
|
+
* allowing http would only add a downgrade path for someone on the network to serve
|
|
13
|
+
* the challenge. If a local sandbox over http is ever needed, widen this deliberately.
|
|
14
|
+
*/
|
|
15
|
+
export declare function isHttpsUrl(value: unknown): boolean;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The 3DS Method step cannot be rendered as text: the ACS sends back a hidden form
|
|
3
|
+
* and the iframe it targets, and the flow submits that form by id. So the markup has
|
|
4
|
+
* to reach the DOM as markup, and the only safe handling is to strip what the step
|
|
5
|
+
* never needs — script execution, event handlers, CSS, beacons and non-https URLs —
|
|
6
|
+
* before insertion.
|
|
7
|
+
*
|
|
8
|
+
* Parsing happens in a document with no browsing context, so nothing loads, navigates
|
|
9
|
+
* or executes while the markup is being inspected. That inertness does not survive the
|
|
10
|
+
* move: a script carried out of a parsed document into a live one has not been marked
|
|
11
|
+
* already-started, so insertion runs it. Removal is the protection, never inertness.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Parses 3DS markup and returns a fragment owned by the current document, with every
|
|
15
|
+
* executable construct removed. Throws nothing: unparseable markup yields an empty
|
|
16
|
+
* fragment, which the caller treats as a missing redirection.
|
|
17
|
+
*/
|
|
18
|
+
export declare function sanitize3dsMarkup(markup: string): DocumentFragment;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export declare function validateSecureToken(secureToken: unknown): secureToken is string;
|
|
1
2
|
export declare function validateCardNumber(cardNumber: string): boolean;
|
|
2
3
|
export declare function validateCardholderName(name: string): boolean;
|
|
3
4
|
export declare function validateCVV(cvv: string): boolean;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"skyflow-js";function t(e,t,r,o){return new(r||(r=Promise))((function(i,n){function s(e){try{d(o.next(e))}catch(e){n(e)}}function a(e){try{d(o.throw(e))}catch(e){n(e)}}function d(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}d((o=o.apply(e,t||[])).next())}))}function r(e,t,r,o){if("a"===r&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?o:"a"===r?o.call(e):o?o.value:t.get(e)}function o(e,t,r,o,i){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?i.call(e,r):i?i.value=r:t.set(e,r),r}function i(e,r,o){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/v1/payments/business/${r}`,{headers:{Authorization:`Token ${r}`},signal:o});return yield t.json()}))}var n;"function"==typeof SuppressedError&&SuppressedError,function(e){e.INIT_ERROR="INIT_ERROR",e.CREATE_ERROR="CREATE_ERROR",e.REMOVE_SDK_ERROR="REMOVE_SDK_ERROR",e.INVALID_TYPE="INVALID_TYPE",e.STATE_ERROR="STATE_ERROR",e.FETCH_BUSINESS_ERROR="FETCH_BUSINESS_ERROR",e.INVALID_CONFIG="INVALID_CONFIG",e.MERCHANT_CREDENTIAL_REQUIRED="MERCHANT_CREDENTIAL_REQUIRED",e.INVALID_PAYMENT_REQUEST="INVALID_PAYMENT_REQUEST",e.INVALID_PAYMENT_REQUEST_CARD_PM="INVALID_PAYMENT_REQUEST_CARD_PM",e.TYPE_SDK_REQUIRED="TYPE_SDK_REQUIRED",e.ENVIRONMENT_REQUIRED="ENVIRONMENT_REQUIRED",e.FETCH_CARDS_ERROR="FETCH_CARDS_ERROR",e.FETCH_TRANSACTION_ERROR="FETCH_TRANSACTION_ERROR",e.CUSTOMER_AUTH_TOKEN_NOT_VALID="CUSTOMER_AUTH_TOKEN_NOT_VALID",e.SAVE_CARD_ERROR="SAVE_CARD_ERROR",e.REMOVE_CARD_ERROR="REMOVE_CARD_ERROR",e.SUMMARY_CARD_ERROR="SUMMARY_CARD_ERROR",e.CREATE_PAYMENT_ERROR="CREATE_PAYMENT_ERROR",e.PAYMENT_PROCESS_ERROR="PAYMENT_PROCESS_ERROR",e.INVALID_CARD_DATA="INVALID_CARD_DATA",e.SAVE_CARD_PROCESS_ERROR="SAVE_CARD_PROCESS_ERROR",e.START_CHECKOUT_ERROR="START_CHECKOUT_ERROR",e.CREATE_ORDER_ERROR="CREATE_ORDER_ERROR",e.BUSINESS_ID_REQUIRED="BUSINESS_ID_REQUIRED",e.CLIENT_ID_REQUIRED="CLIENT_ID_REQUIRED",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INVALID_ITEMS="INVALID_ITEMS",e.CUSTOMER_OPERATION_ERROR="CUSTOMER_OPERATION_ERROR",e.INVALID_EMAIL="INVALID_EMAIL",e.FETCH_PAYMENT_METHODS_ERROR="FETCH_PAYMENT_METHODS_ERROR",e.INVALID_VAULT_TOKEN="INVALID_VAULT_TOKEN",e.VAULT_TOKEN_ERROR="VAULT_TOKEN_ERROR",e.SECURE_TOKEN_ERROR="SECURE_TOKEN_ERROR",e.SECURE_TOKEN_INVALID="SECURE_TOKEN_INVALID",e.INVALID_SECRET_API_KEY="INVALID_SECRET_API_KEY",e.REMOVE_CARD="REMOVE_CARD",e.SKYFLOW_NOT_INITIALIZED="SKYFLOW_NOT_INITIALIZED",e.ERROR_LOAD_PAYMENT_FORM="ERROR_LOAD_PAYMENT_FORM",e.ERROR_LOAD_ENROLLMENT_FORM="ERROR_LOAD_ENROLLMENT_FORM",e.MOUNT_COLLECT_ERROR="MOUNT_COLLECT_ERROR",e.CARD_ON_FILE_DECLINED="CARD_ON_FILE_DECLINED",e.CARD_SAVED_SUCCESSFULLY="CARD_SAVED_SUCCESSFULLY",e.CARD_REMOVED_SUCCESSFULLY="CARD_REMOVED_SUCCESSFULLY",e.REQUEST_ABORTED="REQUEST_ABORTED",e.REQUEST_FAILED="REQUEST_FAILED",e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.THREEDS_REDIRECTION_ERROR="THREEDS_REDIRECTION_ERROR"}(n||(n={}));const s={[n.INIT_ERROR]:"Error initializing the SDK.",[n.INVALID_TYPE]:"SDK Type invalid.",[n.STATE_ERROR]:"Error updating SDK state.",[n.FETCH_BUSINESS_ERROR]:"Error retrieving merchant information.",[n.INVALID_CONFIG]:"Required configuration options.",[n.MERCHANT_CREDENTIAL_REQUIRED]:"Merchant credential required.",[n.INVALID_PAYMENT_REQUEST]:"The payment data must be of type: :::interface:::.",[n.INVALID_PAYMENT_REQUEST_CARD_PM]:"The fields card and payment_method cannot be provided together.",[n.TYPE_SDK_REQUIRED]:"SDK type required.",[n.ENVIRONMENT_REQUIRED]:"Environment required.",[n.FETCH_CARDS_ERROR]:"Error retrieving cards.",[n.CUSTOMER_AUTH_TOKEN_NOT_VALID]:"The customer's auth token is invalid. Please verify that the customer's data was provided when creating the SDK (sdk.create) and try again.",[n.SAVE_CARD_ERROR]:"Error saving the card.",[n.REMOVE_CARD_ERROR]:"Error deleting the card.",[n.CREATE_PAYMENT_ERROR]:"Error creating the payment.",[n.PAYMENT_PROCESS_ERROR]:"There was an issue processing the payment.",[n.CARD_SAVED_SUCCESSFULLY]:"Card saved successfully.",[n.CARD_REMOVED_SUCCESSFULLY]:"Card deleted successfully.",[n.SAVE_CARD_PROCESS_ERROR]:"Error processing card data.",[n.START_CHECKOUT_ERROR]:"Error processing the payment.",[n.CREATE_ORDER_ERROR]:"Error creating the order.",[n.BUSINESS_ID_REQUIRED]:"Business ID is required.",[n.CLIENT_ID_REQUIRED]:"Client ID is required.",[n.INVALID_AMOUNT]:"Invalid amount.",[n.INVALID_ITEMS]:"Invalid items.",[n.CUSTOMER_OPERATION_ERROR]:"Error registering or fetching customer",[n.INVALID_EMAIL]:"Invalid email.",[n.FETCH_PAYMENT_METHODS_ERROR]:"Error retrieving active payment methods.",[n.INVALID_VAULT_TOKEN]:"An invalid vault token response was received.",[n.VAULT_TOKEN_ERROR]:"Error retrieving the vault token.",[n.SECURE_TOKEN_ERROR]:"Error getting secure token.",[n.SECURE_TOKEN_INVALID]:"Invalid secure token.",[n.INVALID_SECRET_API_KEY]:"SECRET API KEY is required.",[n.REMOVE_CARD]:"Card deleted successfully",[n.SKYFLOW_NOT_INITIALIZED]:"Skyflow not initialized.",[n.ERROR_LOAD_PAYMENT_FORM]:"There was an issue loading the payment form.",[n.INVALID_CARD_DATA]:"Invalid card data.",[n.ERROR_LOAD_ENROLLMENT_FORM]:"There was an issue loading the card form.",[n.MOUNT_COLLECT_ERROR]:"Mount failed. Make sure all inputs are complete and valid.",[n.CARD_ON_FILE_DECLINED]:"Transaction declined. Please verify your card details.",[n.REQUEST_ABORTED]:"Requests canceled.",[n.REQUEST_FAILED]:"Request failed.",[n.UNKNOWN_ERROR]:"An unexpected error occurred.",[n.CREATE_ERROR]:"Error creating the SDK.",[n.FETCH_TRANSACTION_ERROR]:"Error retrieving the transaction.",[n.THREEDS_REDIRECTION_ERROR]:"Ocurrió un error durante la redirección de 3DS.",[n.REMOVE_SDK_ERROR]:"Ocurrió un error removiendo la instancia del SDK."};n.INIT_ERROR,n.STATE_ERROR,n.FETCH_BUSINESS_ERROR,n.INVALID_CONFIG,n.TYPE_SDK_REQUIRED,n.ENVIRONMENT_REQUIRED,n.FETCH_CARDS_ERROR,n.SAVE_CARD_ERROR,n.REMOVE_CARD_ERROR,n.CREATE_PAYMENT_ERROR,n.START_CHECKOUT_ERROR,n.CREATE_ORDER_ERROR,n.BUSINESS_ID_REQUIRED,n.CLIENT_ID_REQUIRED,n.INVALID_AMOUNT,n.INVALID_ITEMS,n.CUSTOMER_OPERATION_ERROR,n.INVALID_EMAIL,n.FETCH_PAYMENT_METHODS_ERROR,n.INVALID_VAULT_TOKEN,n.VAULT_TOKEN_ERROR,n.SECURE_TOKEN_ERROR,n.INVALID_SECRET_API_KEY,n.CUSTOMER_AUTH_TOKEN_NOT_VALID,n.SECURE_TOKEN_INVALID,n.REMOVE_CARD,n.SKYFLOW_NOT_INITIALIZED,n.INVALID_TYPE,n.PAYMENT_PROCESS_ERROR,n.INVALID_PAYMENT_REQUEST,n.INVALID_PAYMENT_REQUEST_CARD_PM,n.SAVE_CARD_PROCESS_ERROR,n.ERROR_LOAD_PAYMENT_FORM,n.INVALID_CARD_DATA,n.ERROR_LOAD_ENROLLMENT_FORM,n.MOUNT_COLLECT_ERROR,n.CARD_ON_FILE_DECLINED,n.CARD_SAVED_SUCCESSFULLY,n.CARD_REMOVED_SUCCESSFULLY,n.REQUEST_ABORTED,n.REQUEST_FAILED,n.UNKNOWN_ERROR,n.CREATE_ERROR,n.FETCH_TRANSACTION_ERROR,n.THREEDS_REDIRECTION_ERROR,n.REMOVE_SDK_ERROR;class a extends Error{constructor(e){var t,r;const o=e.message||s[e.code]||"Unknown error";super(o),this.name="TonderError",this.code=e.code,this.details={code:(null===(t=e.details)||void 0===t?void 0:t.code)||e.code,message:(null===(r=e.details)||void 0===r?void 0:r.message)||o}}}const d=Object.freeze({production:"https://d35a75syrgujp0.cloudfront.net",sandbox:"https://static.staging.tonder.io",stage:"https://static.staging.tonder.io",development:"https://static.staging.tonder.io"});function l(e="stage"){return d[e]||d.stage}const c=()=>({javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent}),u=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},h=(e,t="stage")=>{const r=l(t);return"Visa"===e?`${r}/cards/visa.png`:"Mastercard"===e?`${r}/cards/mastercard.png`:"American Express"===e?`${r}/cards/american_express.png`:`${r}/cards/default_card.png`},E="__tonderLockErrorCode__";function _(e){return"object"==typeof e&&null!==e}class R extends Error{constructor(e){var t,r;const o=R.resolveStatusCode(e.statusCode,e.originalError),i=R.resolveMessage(e.errorCode,e.message),n=R.resolveSystemError(null===(t=e.details)||void 0===t?void 0:t.systemError,e.originalError);super(i),this.status="error",Object.setPrototypeOf(this,new.target.prototype),this.name="TonderError",this.code=e.errorCode,this.statusCode=o,this.originalError=e.originalError,this.details={code:e.errorCode,statusCode:o,systemError:n},e.lockErrorCode&&Object.defineProperty(this,E,{value:!0,enumerable:!1,configurable:!0}),null===(r=Error.captureStackTrace)||void 0===r||r.call(Error,this,R)}static isRecord(e){return"object"==typeof e&&null!==e}static parseStatusCode(e){const t=Number(e);return Number.isFinite(t)?t<100||t>599?500:Math.trunc(t):500}static resolveStatusCode(e,t){const r=[e];if(R.isRecord(t)){r.push(t.statusCode,t.status);const e=R.isRecord(t.body)?t.body:null;e&&r.push(e.statusCode,e.status)}for(const e of r)if(R.isHttpStatusCode(e))return Math.trunc(Number(e));return 500}static resolveMessage(e,t){return t||(s[e]||s[n.UNKNOWN_ERROR]||"An unexpected error occurred.")}static isHttpStatusCode(e){const t=Number(e);return Number.isFinite(t)&&t>=100&&t<=599}static normalizeSystemError(e){if("string"!=typeof e)return null;return e.trim()||null}static resolveSystemError(e,t){const r=[e];if(R.isRecord(t)){const e=R.isRecord(t.details)?t.details:null,o=R.isRecord(t.body)?t.body:null,i=o&&R.isRecord(o.details)?o.details:null;r.push(t.systemError,t.code,null==e?void 0:e.systemError,null==e?void 0:e.code,null==o?void 0:o.systemError,null==o?void 0:o.code,null==i?void 0:i.systemError,null==i?void 0:i.code)}for(const e of r){const t=R.normalizeSystemError(e);if(t)return t}return"APP_INTERNAL_001"}}function m(e){return _(e)&&!0===e[E]}function p(e){return e instanceof R&&void 0!==e.originalError?e.originalError:e}function y(e,t){var r;if(!(null==e?void 0:e.errorCode))throw new Error("buildPublicAppError requires errorCode");const o=null===(r=e.details)||void 0===r?void 0:r.systemError,i=!!e.message||void 0!==e.statusCode||void 0!==o;return!function(e){return _(e)&&"TonderError"===e.name&&"string"==typeof e.code}(t)||(e.lockErrorCode&&function(e){Object.defineProperty(e,E,{value:!0,enumerable:!1,configurable:!0})}(t),i||e.errorCode!==t.code&&!m(t))?new R({errorCode:e.errorCode,message:e.message,statusCode:e.statusCode,details:void 0!==o?{systemError:o}:void 0,originalError:p(t),lockErrorCode:e.lockErrorCode||m(t)}):t}function v(e){var r,o;return t(this,void 0,void 0,(function*(){const i=yield function(e){return t(this,void 0,void 0,(function*(){try{return yield e.clone().json()}catch(e){}try{return(yield e.text())||void 0}catch(e){return}}))}(e.response),n={status:e.response.status};return e.response.statusText&&(n.statusText=e.response.statusText),void 0!==i&&(n.body=i),new R({errorCode:e.errorCode,message:e.message,statusCode:null!==(r=e.statusCode)&&void 0!==r?r:e.response.status,details:void 0!==(null===(o=e.details)||void 0===o?void 0:o.systemError)?{systemError:e.details.systemError}:void 0,originalError:n,lockErrorCode:e.lockErrorCode})}))}function C(e,t){return(null==e?void 0:e.response)?v(e):y(e,t)}class A{constructor({payload:e=null,apiKey:t,baseUrl:r,redirectOnComplete:o,tdsIframeId:i,tonderPayButtonId:n,callBack:s}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=r,this.apiKey=t,this.payload=e,this.tdsIframeId=i,this.tonderPayButtonId=n,this.redirectOnComplete=o,this.callBack=s}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,r,o,i,n;const s=null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===r?void 0:r.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(n=null===(i=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===i?void 0:i.iframe_resources)||void 0===n?void 0:n.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getUrlWithExpiration(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,r;if(null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===r?void 0:r.iframe)return new Promise(((e,t)=>{var r,o,i;const n=null===(i=null===(o=null===(r=this.payload)||void 0===r?void 0:r.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===i?void 0:i.iframe;if(n){this.saveVerifyTransactionUrl();const r=document.createElement("div");r.innerHTML=n,document.body.appendChild(r);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',r.appendChild(o);const i=document.getElementById("tdsMmethodTgtFrame");i?i.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,r;return null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===r?void 0:r.url}redirectToChallenge(){const e=this.getRedirectUrl();if(e)if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=e;else{const r=document.querySelector(`#${this.tdsIframeId}`);if(r){r.setAttribute("src",e),r.setAttribute("style","display: block");const o=this,i=e=>t(this,void 0,void 0,(function*(){const e=()=>{try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}r&&r.setAttribute("style","display: none"),o.callBack&&o.callBack(o.payload),r.removeEventListener("load",i)},n=r=>t(this,void 0,void 0,(function*(){const i=yield new Promise(((e,t)=>e(r)));if(i){if((e=>"Pending"!==(null==e?void 0:e.transaction_status))(i))return e();{const e=setTimeout((()=>t(this,void 0,void 0,(function*(){clearTimeout(e),yield n(o.requestTransactionStatus())}))),7e3)}}}));yield n(o.requestTransactionStatus())}));r.addEventListener("load",i)}else console.log("No iframe found")}else this.callBack&&this.callBack(this.payload)}requestTransactionStatus(){return t(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration(),t=e.startsWith("https://")?e:`${this.baseUrl}${e}`,r=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});if(200!==r.status)return console.error("La verificación de la transacción falló."),null;return yield r.json()}))}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[r,o]of t)e[r]=o;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return t(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const r=document.createElement("input");r.type="hidden",r.name=e.creq,r.value=e.creq,t.appendChild(r);const o=document.createElement("input");o.type="hidden",o.name=e.term_url,o.value=e.TermUrl,t.appendChild(o),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return t(this,void 0,void 0,(function*(){const t=yield e.json();return"Pending"===t.status&&t.redirect_post_url?yield this.handle3dsChallenge(t):["Success","Authorized"].includes(t.status)?this.handleSuccessTransaction(t):(this.handleDeclinedTransaction(e),t)}))}verifyTransactionStatus(){return t(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration();if(e){const t=e.startsWith("https://")?e:`${this.baseUrl}${e}`;try{const e=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==e.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),e):yield this.handleTransactionResponse(e)}catch(e){console.error("Error al verificar la transacción:",e),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const O=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function T(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/checkout-router/`,i=o,s=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(Object.assign(Object.assign({},i),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(s.ok)return yield s.json();throw yield C({response:s,errorCode:n.START_CHECKOUT_ERROR})}))}function f(e,r,o=!0,i=null){return t(this,void 0,void 0,(function*(){let t=yield window.OpenPay;return t.setId(e),t.setApiKey(r),t.setSandboxMode(o),yield t.deviceData.setup({signal:i})}))}function S(e,t,r){const o=t.replace(/\[(\w+)\]/g,".$1").split(".").filter((e=>""!==e));let i=e;for(const e of o){if(null==i)return r;i=i[e]}return void 0===i?r:i}const I=Object.freeze({production:"https://api.tonder.io",sandbox:"https://api-stage.tonder.io",stage:"https://api-stage.tonder.io",development:"https://api-stage.tonder.io"}),g=Object.freeze({TELEMETRY:"/telemetry/v1/events",ACQ_SUBSCRIPTION_TOKEN:"/acq-kushki/subscription/token",ACQ_SUBSCRIPTION_CREATE:"/acq-kushki/subscription/create"});function N(e="stage"){return`${I[e]}${g.TELEMETRY}`}const b="https://cdn.kushkipagos.com/kushki.min.js",D=n.CARD_ON_FILE_DECLINED;let M=!1,k=null;class P{constructor(e){var t;this.acquirerInstance=null,this.isTestEnvironment=null===(t=e.isTestEnvironment)||void 0===t||t;const r=this.isTestEnvironment?"stage":"production";this.apiUrl=function(e="stage"){return I[e]}(r),this.merchantId=e.merchantId,this.apiKey=e.apiKey}initialize(){return t(this,void 0,void 0,(function*(){yield function(){return t(this,void 0,void 0,(function*(){return M?Promise.resolve():k||(k=new Promise(((e,t)=>{if(document.querySelector(`script[src="${b}"]`))return M=!0,void e();const r=document.createElement("script");r.src=b,r.async=!0,r.onload=()=>{M=!0,e()},r.onerror=()=>{k=null,t(C({errorCode:D,lockErrorCode:!0,details:{step:"load_acquirer_script",message:"Failed to load acquirer script"}}))},document.head.appendChild(r)})),k)}))}(),this.acquirerInstance=function(e,t){if(!window.Kushki)throw C({errorCode:D,lockErrorCode:!0,details:{step:"create_acquirer_instance",message:"Acquirer script not loaded. Call initialize() first."}});return new window.Kushki({merchantId:e,inTestEnvironment:t})}(this.merchantId,this.isTestEnvironment)}))}getAcquirerInstance(){if(!this.acquirerInstance)throw C({errorCode:D,lockErrorCode:!0,details:{step:"get_acquirer_instance",message:"CardOnFile not initialized. Call initialize() first."}});return this.acquirerInstance}getJwt(e){return t(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((r,o)=>{t.requestSecureInit({card:{number:e}},(e=>{if("code"in e&&e.code)return void o(C({errorCode:D,lockErrorCode:!0,details:{step:"get_jwt",acquirerResponse:e}}));const t=e;t.jwt?r(t.jwt):o(C({errorCode:D,lockErrorCode:!0,details:{step:"get_jwt",message:"No JWT returned from acquirer",acquirerResponse:t}}))}))}))}))}generateToken(e){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${g.ACQ_SUBSCRIPTION_TOKEN}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield C({response:t,errorCode:D,lockErrorCode:!0,details:{step:"generate_token"}});return t.json()}))}createSubscription(e){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${g.ACQ_SUBSCRIPTION_CREATE}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield C({response:t,errorCode:D,lockErrorCode:!0,details:{step:"create_subscription"}});return t.json()}))}validate3DS(e,r){return t(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((o,i)=>{t.requestValidate3DS({secureId:e,security:r},(e=>{const t=e;t.code&&"3DS000"!==t.code?i(C({errorCode:D,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}})):!1!==t.isValid?o(!0):i(C({errorCode:D,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}}))}))}))}))}process(e){var r,o;return t(this,void 0,void 0,(function*(){const t=yield this.getJwt(e.cardBin),i=yield this.generateToken({card:e.cardTokens,currency:e.currency,jwt:t}),n=i.secureId||(null===(r=i.details)||void 0===r?void 0:r.secureId),s=i.security||(null===(o=i.details)||void 0===o?void 0:o.security);if(!n||!s)throw C({errorCode:D,lockErrorCode:!0,details:{step:"process",message:"Missing secureId or security in token response",tokenResponse:i}});return yield this.validate3DS(n,s),this.createSubscription({token:i.token,contactDetails:e.contactDetails,metadata:{customerId:e.customerId},currency:e.currency})}))}}class U{constructor(e){this.REQUEST_TIMEOUT_MS=5e3,this.MAX_MESSAGE_LENGTH=500,this.config=e}captureException(e,t){try{const r=this.buildEvent(e,t||{});this.sendEvent(r)}catch(e){}}extractErrorInfo(e){try{if(e instanceof Error)return{name:e.name||"Error",message:this.truncate(e.message||"Unknown error",this.MAX_MESSAGE_LENGTH),stack:e.stack||void 0};const t=this.safeStringify(e);return{name:"NonErrorException",message:this.truncate(t,this.MAX_MESSAGE_LENGTH),stack:void 0}}catch(e){return{name:"SerializationError",message:"Failed to serialize error",stack:void 0}}}safeStringify(e){try{const t=new WeakSet;return JSON.stringify(e,((e,r)=>{if("object"==typeof r&&null!==r){if(t.has(r))return"[Circular]";t.add(r)}return r}))}catch(t){return String(e)}}buildEvent(e,t){const r=this.extractErrorInfo(e),o=Object.assign({},t.metadata||{});void 0===o.error&&(o.error=e),"undefined"!=typeof window&&(o.url=window.location.href);const i={platform:this.config.platform,platform_version:this.config.platform_version,env:this.config.mode,feature:t.feature||"unknown",level:"error",message:r.message,name:r.name,metadata:o};return t.tenant_id&&(i.tenant_id=t.tenant_id),t.request_id&&(i.request_id=t.request_id),t.process_id&&(i.process_id=t.process_id),t.user_id&&(i.user_id=t.user_id),r.stack&&(i.stack=r.stack),t.error_code&&(i.error_code=t.error_code),t.http_status&&(i.http_status=t.http_status),i}truncate(e,t){return e.length<=t?e:e.substring(0,t)+"..."}sendEvent(e){this.sendHttpRequest(e).then((()=>{})).catch((()=>{}))}sendHttpRequest(e){return t(this,void 0,void 0,(function*(){try{const t=JSON.stringify(e),r=new AbortController,o=setTimeout((()=>r.abort()),this.REQUEST_TIMEOUT_MS);try{const e=yield fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.config.apiKey}`},body:t,keepalive:!0,signal:r.signal});return clearTimeout(o),e.ok}catch(e){return clearTimeout(o),!1}}catch(e){return!1}}))}}const L=Object.freeze({name:"@tonder.io/ionic-lite-sdk",version:"1.0.1"});var w,V,F,K,j,x,B,Y,$,H,z,q,X;class Q{constructor({mode:e="stage",customization:t,apiKey:r,apiKeyTonder:o,returnUrl:i,tdsIframeId:n,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d,sdkInfo:l}){w.add(this),this.baseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.order_reference=null,this.card={},this.currency="",this.cardOnFileInstance=null,V.set(this,void 0),F.set(this,void 0),this.apiKeyTonder=o||r||"",this.returnUrl=i,this.callBack=s,this.mode=e,this.customer={},this.baseUrl=a||O[this.mode]||O.stage,this.abortController=new AbortController,this.requestId=this.generateRequestId(),this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new A({apiKey:r,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:n,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=n;const c=l||L;this.telemetry=new U({endpoint:N(this.mode),apiKey:this.apiKeyTonder,platform:c.name,platform_version:c.version,mode:this.mode||"stage"})}configureCheckout(e){"secureToken"in e&&r(this,w,"m",x).call(this,e.secureToken),r(this,w,"m",K).call(this,e)}getCustomerId(){var e,t;return null===(t=null===(e=r(this,F,"f"))||void 0===e?void 0:e.id)||void 0===t?void 0:t.toString()}reportSdkError(e,t){var r,o,i,n;try{const s=this.getCustomerId(),a=e instanceof R&&void 0!==e.originalError?e.originalError:e,d=Object.assign(Object.assign({},(null==t?void 0:t.metadata)||{}),void 0===(null===(r=null==t?void 0:t.metadata)||void 0===r?void 0:r.error)?{error:a}:{}),l=Object.assign(Object.assign({tenant_id:null===(n=null===(i=null===(o=this.merchantData)||void 0===o?void 0:o.business)||void 0===i?void 0:i.pk)||void 0===n?void 0:n.toString(),user_id:s},t||{}),{metadata:d,request_id:this.requestId});l.user_id||delete l.user_id,l.feature=(null==t?void 0:t.feature)||"unknown",this.telemetry.captureException(e,l)}catch(e){}}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}verify3dsTransaction(){return t(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield r(this,w,"m",z).call(this,e);return this.process3ds.setPayload(t),this._handle3dsRedirect(t)}))}payment(e){return new Promise(((o,i)=>t(this,void 0,void 0,(function*(){var t,s;let a;try{r(this,w,"m",K).call(this,e),a=yield this._checkout(e),this.process3ds.setPayload(a);if(yield this._handle3dsRedirect(a)){try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}this.callBack&&this.callBack(a),o(a)}}catch(r){this.reportSdkError(r,{feature:"payment",process_id:(null==a?void 0:a.payment_id)||(null===(t=null==a?void 0:a.payment)||void 0===t?void 0:t.id)||(null===(s=null==a?void 0:a.payment)||void 0===s?void 0:s.pk),metadata:{step:"payment",request:e,response:a}}),i(C({errorCode:n.PAYMENT_PROCESS_ERROR},r))}}))))}getSecureToken(e){return t(this,void 0,void 0,(function*(){try{return yield function(e,r,o=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:o});if(t.ok)return yield t.json();throw yield C({response:t,errorCode:n.SECURE_TOKEN_ERROR})}))}(this.baseUrl,e)}catch(e){throw this.reportSdkError(e,{feature:"secure-token",metadata:{step:"getSecureToken"}}),C({errorCode:n.SECURE_TOKEN_ERROR},e)}}))}_initializeCheckout(){return t(this,void 0,void 0,(function*(){const e=yield this._fetchMerchantData();e&&e.mercado_pago&&e.mercado_pago.active&&function(){try{const e=document.createElement("script");e.src="https://www.mercadopago.com/v2/security.js",e.setAttribute("view",""),e.onload=()=>{},e.onerror=e=>{console.error("Error loading Mercado Pago script:",e)},document.head.appendChild(e)}catch(e){console.error("Error attempting to inject Mercado Pago script:",e)}}(),this._hasCardOnFileKeys()&&(yield this._initializeCardOnFile())}))}_checkout(e){return t(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(e){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(e=null){return t(this,void 0,void 0,(function*(){return r(this,F,"f")||o(this,F,yield function(e,r,o,i=null){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/customer/`,s={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},a=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},signal:i,body:JSON.stringify(s)});if(a.ok)return yield a.json();throw yield C({response:a,errorCode:n.CUSTOMER_OPERATION_ERROR})}))}(this.baseUrl,this.apiKeyTonder,this.customer,e),"f"),r(this,F,"f")}))}_handleCheckout({card:e,payment_method:o,customer:i,isSandbox:s,enable_card_on_file:a,returnUrl:d}){return t(this,void 0,void 0,(function*(){const{openpay_keys:l,reference:u,business:h}=this.merchantData,E=Number(this.cartTotal);let _,R,m;try{let p;!p&&l.merchant_id&&l.public_key&&!o&&(p=yield f(l.merchant_id,l.public_key,s,this.abortController.signal));const{id:y,auth_token:v}=i;_={business:this.apiKeyTonder,client:v,billing_address_id:null,shipping_address_id:null,amount:E,status:"A",reference:u,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata};const A=yield function(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/orders/`,i=o,s=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(i)});if(s.ok)return yield s.json();throw yield C({response:s,errorCode:n.CREATE_ORDER_ERROR})}))}(this.baseUrl,this.apiKeyTonder,_),O=(new Date).toISOString();R={business_pk:h.pk,client_id:y,amount:E,date:O,order_id:A.id,customer_order_reference:this.order_reference?this.order_reference:u,items:this.cartItems,currency:this.currency,metadata:this.metadata};const I=yield function(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${o.business_pk}/payments/`,i=o,s=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(i)});if(s.ok)return yield s.json();throw yield C({response:s,errorCode:n.CREATE_PAYMENT_ERROR})}))}(this.baseUrl,this.apiKeyTonder,R);m=Object.assign(Object.assign(Object.assign(Object.assign({name:S(this.customer,"firstName",S(this.customer,"name","")),last_name:S(this.customer,"lastName",S(this.customer,"lastname","")),email_client:S(this.customer,"email",""),phone_number:S(this.customer,"phone",""),return_url:d||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:E,title_ship:"shipping",description:"transaction",device_session_id:p||null,token_id:"",order_id:A.id,business_id:h.pk,payment_id:I.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:c(),currency:this.currency},o?{payment_method:o}:{card:e}),{apm_config:r(this,V,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),void 0!==a?{enable_card_on_file:a}:{});const g=yield T(this.baseUrl,this.apiKeyTonder,m);return g||!1}catch(e){throw this.reportSdkError(e,{feature:"payment",process_id:null==m?void 0:m.payment_id,metadata:{step:"_handleCheckout",orderItems:_,paymentItems:R,routerItems:m}}),e}}))}_fetchMerchantData(){return t(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(e){return this.reportSdkError(e,{feature:"fetch-merchant-data",metadata:{step:"_fetchMerchantData"}}),this.merchantData}}))}_getCustomerCards(e,r){return t(this,void 0,void 0,(function*(){return yield function(e,r,o,i,s=null){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${i}/cards/`,a=yield fetch(t,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r},signal:s});if(a.ok)return yield a.json();if(401===a.status)return{user_id:0,cards:[]};throw yield C({response:a,errorCode:n.FETCH_CARDS_ERROR})}))}(this.baseUrl,e,this.secureToken,r)}))}_saveCustomerCard(e,r,o,i=!1){return t(this,void 0,void 0,(function*(){return yield function(e,r,o,i,s,a=!1){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${i}/cards/`,d=yield fetch(t,{method:"POST",headers:Object.assign({Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r},a?{"X-App-Origin":"sdk/ionic"}:{}),body:JSON.stringify(s)});if(d.ok)return yield d.json();throw yield C({response:d,errorCode:n.SAVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,r,o,i)}))}_removeCustomerCard(e,r,o){return t(this,void 0,void 0,(function*(){return yield function(e,r,o,i="",a){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${a}/cards/${i}`,d=yield fetch(t,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r}});if(204===d.status)return s[n.CARD_REMOVED_SUCCESSFULLY];if(d.ok&&"json"in d)return yield d.json();throw yield C({response:d,errorCode:n.REMOVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,o,r)}))}_fetchCustomerPaymentMethods(){return t(this,void 0,void 0,(function*(){return yield function(e,r,o={status:"active",pagesize:"10000"},i=null){return t(this,void 0,void 0,(function*(){const t=new URLSearchParams(o).toString(),s=yield fetch(`${e}/api/v1/payment_methods?${t}`,{method:"GET",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:i});if(s.ok)return yield s.json();throw yield C({response:s,errorCode:n.FETCH_PAYMENT_METHODS_ERROR})}))}(this.baseUrl,this.apiKeyTonder)}))}_hasCardOnFileKeys(){var e,t;return!!(null===(t=null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys)||void 0===t?void 0:t.public_key)}_initializeCardOnFile(){var e;return t(this,void 0,void 0,(function*(){return this.cardOnFileInstance||(this.cardOnFileInstance=new P({merchantId:null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys.public_key,apiKey:this.apiKeyTonder,isTestEnvironment:"production"!==this.mode}),yield this.cardOnFileInstance.initialize()),this.cardOnFileInstance}))}_handle3dsRedirect(e){var r,o;return t(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(o=null===(r=null==e?void 0:e.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((t=>{console.log("Error loading iframe:",t),this.reportSdkError(t,{feature:"3ds-verification",metadata:{step:"_handle3dsRedirect",response:e}})}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}}function W(e,r,o=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${r}`},signal:o});if(t.ok){return(yield t.json()).token}throw yield C({response:t,errorCode:n.VAULT_TOKEN_ERROR})}))}V=new WeakMap,F=new WeakMap,w=new WeakSet,K=function(e){var t,o;!e||e&&0===Object.keys(e).length||(r(this,w,"m",j).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),r(this,w,"m",B).call(this,(null===(o=e.cart)||void 0===o?void 0:o.items)||[]),r(this,w,"m",Y).call(this,e),r(this,w,"m",$).call(this,e),r(this,w,"m",H).call(this,e),r(this,w,"m",q).call(this,e))},j=function(e){e&&(this.customer=e)},x=function(e){this.secureToken=e},B=function(e){this.cartItems=e},Y=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},$=function(e){this.currency=null==e?void 0:e.currency},H=function(e){this.card=null==e?void 0:e.card},z=function(e){var r,o,i,n,s;return t(this,void 0,void 0,(function*(){if("Hard"===(null===(r=null==e?void 0:e.decline)||void 0===r?void 0:r.error_type)||(null===(o=null==e?void 0:e.checkout)||void 0===o?void 0:o.is_route_finished)||(null==e?void 0:e.is_route_finished)||["Pending"].includes(null==e?void 0:e.transaction_status))return e;if(["Success","Authorized"].includes(null==e?void 0:e.transaction_status))return e;if(e){const t={checkout_id:(null===(i=e.checkout)||void 0===i?void 0:i.id)||(null==e?void 0:e.checkout_id)};try{return yield T(this.baseUrl,this.apiKeyTonder,t)}catch(t){this.reportSdkError(t,{feature:"payment",process_id:(null==e?void 0:e.payment_id)||(null===(n=null==e?void 0:e.payment)||void 0===n?void 0:n.id)||(null===(s=null==e?void 0:e.payment)||void 0===s?void 0:s.pk),metadata:{step:"#resumeCheckout",response:e}})}return e}}))},q=function(e){o(this,V,null==e?void 0:e.apm_config,"f")},function(e){e.CARD_NUMBER="card_number",e.CVV="cvv",e.EXPIRATION_MONTH="expiration_month",e.EXPIRATION_YEAR="expiration_year",e.CARDHOLDER_NAME="cardholder_name"}(X||(X={}));const J={type:e.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},G=RegExp("^(?!s*$).+"),Z={type:e.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:G,error:"El campo es requerido"}},ee="Titular de la tarjeta",te="Número de tarjeta",re="CVC/CVV",oe="Mes",ie="Año",ne="Fecha de expiración",se="Nombre como aparece en la tarjeta",ae="1234 1234 1234 1234",de="3-4 dígitos",le="MM",ce="AA",ue={base:{border:"1px solid #e0e0e0",padding:"10px 7px",borderRadius:"5px",color:"#1d1d1d",marginTop:"2px",backgroundColor:"white",fontFamily:'"Inter", sans-serif',fontSize:"16px","&::placeholder":{color:"#ccc"}},complete:{color:"#4caf50"},invalid:{border:"1px solid #f44336"},empty:{},focus:{},global:{"@import":'url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;700&display=swap")'}},he={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},Ee={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function _e({baseUrl:r,apiKey:o,vault_id:i,vault_url:s,data:a}){return t(this,void 0,void 0,(function*(){const d=e.init({vaultID:i,vaultURL:s,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield W(r,o)})),options:{logLevel:e.LogLevel.ERROR,env:e.Env.DEV}}).container(e.ContainerType.COLLECT),l=yield function(r,o){return t(this,void 0,void 0,(function*(){const i=yield function(r,o){return t(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(r).map((r=>t(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:r,type:e.ElementType.INPUT_FIELD}),key:r}})))))}))}(r,o);return i?i.map((e=>new Promise((t=>{var o;const i=document.createElement("div");i.hidden=!0,i.id=`id-${e.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(i),setTimeout((()=>{e.element.mount(`#id-${e.key}`),setInterval((()=>{if(e.element.isMounted()){const o=r[e.key];return e.element.setValue(o),t(e.element.isMounted())}}),120)}),120)})))):[]}))}(a,d);if((yield Promise.all(l)).some((e=>!e)))throw C({errorCode:n.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}});try{const e=yield d.collect();if(e)return e.records[0].fields;throw C({errorCode:n.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}})}catch(e){throw C({errorCode:n.SAVE_CARD_PROCESS_ERROR},e)}}))}function Re(t){const{element:r,fieldMessage:o="",errorStyles:i={},requiredMessage:n="Campo requerido",invalidMessage:s="Campo no válido",events:a}=t;"on"in r&&(r.on(e.EventName.CHANGE,(e=>{pe({eventName:"onChange",data:e,events:a}),me({element:r,errorStyles:i,color:"transparent"})})),r.on(e.EventName.BLUR,(e=>{if(pe({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?n:""!=o?`El campo ${o} no es válido`:s;r.setError(t)}me({element:r,errorStyles:i})})),r.on(e.EventName.FOCUS,(e=>{pe({eventName:"onFocus",data:e,events:a}),me({element:r,errorStyles:i,color:"transparent"}),r.resetError()})))}function me(e){const{element:t,errorStyles:r={},color:o=""}=e;Object.keys(r).length>0&&t.update({errorTextStyles:Object.assign(Object.assign({},r),{base:Object.assign(Object.assign({},r.base&&Object.assign({},r.base)),""!=o&&{color:o})})})}const pe=e=>{const{eventName:t,data:r,events:o}=e;if(o&&t in o){const e=o[t];"function"==typeof e&&e({elementType:S(r,"elementType",""),isEmpty:S(r,"isEmpty",!1),isFocused:S(r,"isFocused",!1),isValid:S(r,"isValid",!1),value:S(r,"value","")})}};function ye(e){return t(this,void 0,void 0,(function*(){const{element:t,containerId:r,retries:o=2,delay:i=30}=e;for(let e=0;e<=o;e++){if(document.querySelector(r))return void t.mount(r);e<o&&(yield new Promise((e=>setTimeout(e,i))))}console.warn(`[mountCardFields] Container ${r} was not found after ${o+1} attempts`)}))}const ve=Object.freeze({SORIANA:"SORIANA",OXXO:"OXXO",OXXOPAY:"OXXOPAY",SPEI:"SPEI",CODI:"CODI",MERCADOPAGO:"MERCADOPAGO",PAYPAL:"PAYPAL",COMERCIALMEXICANA:"COMERCIALMEXICANA",BANCOMER:"BANCOMER",WALMART:"WALMART",BODEGA:"BODEGA",SAMSCLUB:"SAMSCLUB",SUPERAMA:"SUPERAMA",CALIMAX:"CALIMAX",EXTRA:"EXTRA",CIRCULOK:"CIRCULOK",SEVEN11:"7ELEVEN",TELECOMM:"TELECOMM",BANORTE:"BANORTE",BENAVIDES:"BENAVIDES",DELAHORRO:"DELAHORRO",ELASTURIANO:"ELASTURIANO",WALDOS:"WALDOS",ALSUPER:"ALSUPER",KIOSKO:"KIOSKO",STAMARIA:"STAMARIA",LAMASBARATA:"LAMASBARATA",FARMROMA:"FARMROMA",FARMUNION:"FARMUNION",FARMATODO:"FARMATODO",SFDEASIS:"SFDEASIS",FARM911:"FARM911",FARMECONOMICAS:"FARMECONOMICAS",FARMMEDICITY:"FARMMEDICITY",RIANXEIRA:"RIANXEIRA",WESTERNUNION:"WESTERNUNION",ZONAPAGO:"ZONAPAGO",CAJALOSANDES:"CAJALOSANDES",CAJAPAITA:"CAJAPAITA",CAJASANTA:"CAJASANTA",CAJASULLANA:"CAJASULLANA",CAJATRUJILLO:"CAJATRUJILLO",EDPYME:"EDPYME",KASNET:"KASNET",NORANDINO:"NORANDINO",QAPAQ:"QAPAQ",RAIZ:"RAIZ",PAYSER:"PAYSER",WUNION:"WUNION",BANCOCONTINENTAL:"BANCOCONTINENTAL",GMONEY:"GMONEY",GOPAY:"GOPAY",WU:"WU",PUNTOSHEY:"PUNTOSHEY",AMPM:"AMPM",JUMBOMARKET:"JUMBOMARKET",SMELPUEBLO:"SMELPUEBLO",BAM:"BAM",REFACIL:"REFACIL",ACYVALORES:"ACYVALORES"}),Ce={[ve.SORIANA]:{label:"Soriana",iconPath:"/payment_methods/soriana.png"},[ve.OXXO]:{label:"Oxxo",iconPath:"/payment_methods/oxxo.png"},[ve.CODI]:{label:"CoDi",iconPath:"/payment_methods/codi.png"},[ve.MERCADOPAGO]:{label:"Mercado Pago",iconPath:"/payment_methods/mercadopago.png"},[ve.OXXOPAY]:{label:"Oxxo Pay",iconPath:"/payment_methods/oxxopay.png"},[ve.SPEI]:{label:"SPEI",iconPath:"/payment_methods/spei.png"},[ve.PAYPAL]:{label:"Paypal",iconPath:"/payment_methods/paypal.png"},[ve.COMERCIALMEXICANA]:{label:"Comercial Mexicana",iconPath:"/payment_methods/comercial_exicana.png"},[ve.BANCOMER]:{label:"Bancomer",iconPath:"/payment_methods/bancomer.png"},[ve.WALMART]:{label:"Walmart",iconPath:"/payment_methods/walmart.png"},[ve.BODEGA]:{label:"Bodega Aurrera",iconPath:"/payment_methods/bodega_aurrera.png"},[ve.SAMSCLUB]:{label:"Sam´s Club",iconPath:"/payment_methods/sams_club.png"},[ve.SUPERAMA]:{label:"Superama",iconPath:"/payment_methods/superama.png"},[ve.CALIMAX]:{label:"Calimax",iconPath:"/payment_methods/calimax.png"},[ve.EXTRA]:{label:"Tiendas Extra",iconPath:"/payment_methods/tiendas_extra.png"},[ve.CIRCULOK]:{label:"Círculo K",iconPath:"/payment_methods/circulo_k.png"},[ve.SEVEN11]:{label:"7 Eleven",iconPath:"/payment_methods/7_eleven.png"},[ve.TELECOMM]:{label:"Telecomm",iconPath:"/payment_methods/telecomm.png"},[ve.BANORTE]:{label:"Banorte",iconPath:"/payment_methods/banorte.png"},[ve.BENAVIDES]:{label:"Farmacias Benavides",iconPath:"/payment_methods/farmacias_benavides.png"},[ve.DELAHORRO]:{label:"Farmacias del Ahorro",iconPath:"/payment_methods/farmacias_ahorro.png"},[ve.ELASTURIANO]:{label:"El Asturiano",iconPath:"/payment_methods/asturiano.png"},[ve.WALDOS]:{label:"Waldos",iconPath:"/payment_methods/waldos.png"},[ve.ALSUPER]:{label:"Alsuper",iconPath:"/payment_methods/al_super.png"},[ve.KIOSKO]:{label:"Kiosko",iconPath:"/payment_methods/kiosko.png"},[ve.STAMARIA]:{label:"Farmacias Santa María",iconPath:"/payment_methods/farmacias_santa_maria.png"},[ve.LAMASBARATA]:{label:"Farmacias la más barata",iconPath:"/payment_methods/farmacias_barata.png"},[ve.FARMROMA]:{label:"Farmacias Roma",iconPath:"/payment_methods/farmacias_roma.png"},[ve.FARMUNION]:{label:"Pago en Farmacias Unión",iconPath:"/payment_methods/farmacias_union.png"},[ve.FARMATODO]:{label:"Pago en Farmacias Farmatodo",iconPath:"/payment_methods/farmacias_farmatodo.png\t"},[ve.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",iconPath:"/payment_methods/farmacias_san_francisco.png"},[ve.FARM911]:{label:"Farmacias 911",iconPath:"/payment_methods/store.png"},[ve.FARMECONOMICAS]:{label:"Farmacias Economicas",iconPath:"/payment_methods/store.png"},[ve.FARMMEDICITY]:{label:"Farmacias Medicity",iconPath:"/payment_methods/store.png"},[ve.RIANXEIRA]:{label:"Rianxeira",iconPath:"/payment_methods/store.png"},[ve.WESTERNUNION]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[ve.ZONAPAGO]:{label:"Zona Pago",iconPath:"/payment_methods/store.png"},[ve.CAJALOSANDES]:{label:"Caja Los Andes",iconPath:"/payment_methods/store.png"},[ve.CAJAPAITA]:{label:"Caja Paita",iconPath:"/payment_methods/store.png"},[ve.CAJASANTA]:{label:"Caja Santa",iconPath:"/payment_methods/store.png"},[ve.CAJASULLANA]:{label:"Caja Sullana",iconPath:"/payment_methods/store.png"},[ve.CAJATRUJILLO]:{label:"Caja Trujillo",iconPath:"/payment_methods/store.png"},[ve.EDPYME]:{label:"Edpyme",iconPath:"/payment_methods/store.png"},[ve.KASNET]:{label:"KasNet",iconPath:"/payment_methods/store.png"},[ve.NORANDINO]:{label:"Norandino",iconPath:"/payment_methods/store.png"},[ve.QAPAQ]:{label:"Qapaq",iconPath:"/payment_methods/store.png"},[ve.RAIZ]:{label:"Raiz",iconPath:"/payment_methods/store.png"},[ve.PAYSER]:{label:"Paysera",iconPath:"/payment_methods/store.png"},[ve.WUNION]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[ve.BANCOCONTINENTAL]:{label:"Banco Continental",iconPath:"/payment_methods/store.png"},[ve.GMONEY]:{label:"Go money",iconPath:"/payment_methods/store.png"},[ve.GOPAY]:{label:"Go pay",iconPath:"/payment_methods/store.png"},[ve.WU]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[ve.PUNTOSHEY]:{label:"Puntoshey",iconPath:"/payment_methods/store.png"},[ve.AMPM]:{label:"Ampm",iconPath:"/payment_methods/store.png"},[ve.JUMBOMARKET]:{label:"Jumbomarket",iconPath:"/payment_methods/store.png"},[ve.SMELPUEBLO]:{label:"Smelpueblo",iconPath:"/payment_methods/store.png"},[ve.BAM]:{label:"Bam",iconPath:"/payment_methods/store.png"},[ve.REFACIL]:{label:"Refacil",iconPath:"/payment_methods/store.png"},[ve.ACYVALORES]:{label:"Acyvalores",iconPath:"/payment_methods/store.png"}},Ae=(e,t="stage")=>{const r=e.toUpperCase().trim().replace(/\s+/g,"");const o=Ce[r]||{iconPath:"/payment_methods/store.png",label:""};return{label:o.label,icon:`${l(t)}${o.iconPath}`}};class Oe extends Q{constructor({apiKey:e,mode:t,returnUrl:r,callBack:o,apiKeyTonder:i,baseUrlTonder:n,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:r,callBack:o,apiKeyTonder:i,baseUrlTonder:n,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe",sdkInfo:L}),this.activeAPMs=[],this.mountedElementsByContext=new Map,this.customerCardsCache=null,this.lastCollectedTokens=null,this.skyflowInstance=null,this.events=d||{}}injectCheckout(){return t(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return t(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),t=yield this._getCustomerCards(e,this.merchantData.business.pk);return this.customerCardsCache=t,Object.assign(Object.assign({},t),{cards:t.cards.map((e=>Object.assign(Object.assign({},e),{fields:Object.assign(Object.assign({},e.fields),{subscription_id:this._hasCardOnFileKeys()?e.fields.subscription_id:void 0}),icon:h(e.fields.card_scheme,this.mode)})))})}catch(e){throw this.reportSdkError(e,{feature:"get-cards",process_id:this.getCustomerId(),metadata:{step:"getCustomerCards"}}),C({errorCode:n.FETCH_CARDS_ERROR},e)}}))}saveCustomerCard(){return t(this,void 0,void 0,(function*(){let e=null;try{yield this._fetchMerchantData();const t=yield this._getCustomer(),{auth_token:r,first_name:o="",last_name:i="",email:s=""}=t,{business:a}=this.merchantData,d=this._hasCardOnFileKeys(),l=yield this.collectCreateCardTokens(),c=yield this._saveCustomerCard(r,null==a?void 0:a.pk,l,d);if(e=c.skyflow_id,d){const e=c.card_bin;if(!e)throw new Error("Card BIN not returned from save card");const t=yield this._initializeCardOnFile();let d;try{d=yield t.process({cardTokens:{name:l.cardholder_name,number:l.card_number,expiryMonth:l.expiration_month,expiryYear:l.expiration_year,cvv:l.cvv},cardBin:e,contactDetails:{firstName:o||"",lastName:i||"",email:s||""},customerId:r,currency:this.currency||"MXN"})}catch(e){throw C({errorCode:n.CARD_ON_FILE_DECLINED,lockErrorCode:!0},e)}const u={skyflow_id:l.skyflow_id,subscription_id:d.subscriptionId};yield this._saveCustomerCard(r,null==a?void 0:a.pk,u)}return c}catch(t){throw e&&(yield this.removeCustomerCard(e)),this.reportSdkError(t,{feature:"save-card",process_id:e||this.getCustomerId(),metadata:{step:"saveCustomerCard"}}),C({errorCode:n.SAVE_CARD_ERROR},t)}}))}removeCustomerCard(e){return t(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{business:r}=this.merchantData;return yield this._removeCustomerCard(t,null==r?void 0:r.pk,e)}catch(t){throw this.reportSdkError(t,{feature:"remove-card",process_id:e,metadata:{step:"removeCustomerCard"}}),C({errorCode:n.REMOVE_CARD_ERROR},t)}}))}getCustomerPaymentMethods(){return t(this,void 0,void 0,(function*(){try{const e=yield this._fetchCustomerPaymentMethods();return(e&&"results"in e&&e.results.length>0?e.results:[]).filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},Ae(e.payment_method,this.mode)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw this.reportSdkError(e,{feature:"get-payment-methods",metadata:{step:"getCustomerPaymentMethods"}}),C({errorCode:n.FETCH_PAYMENT_METHODS_ERROR},e)}}))}mountCardFields(r){var o;return t(this,void 0,void 0,(function*(){const i=r.card_id?`update:${r.card_id}`:"create",n=null!==(o=r.unmount_context)&&void 0!==o?o:"all";"none"!==n&&("current"===n?this.unmountCardFields(i):this.unmountCardFields(n)),yield this.createSkyflowInstance();const s=yield function(r){var o,i,n,s,a,d,l,c,u,h,E,_,R;return t(this,void 0,void 0,(function*(){const{skyflowInstance:t,data:m,customization:p,events:y}=r,v=t.container(e.ContainerType.COLLECT),C=[],A={[X.CVV]:e.ElementType.CVV,[X.CARD_NUMBER]:e.ElementType.CARD_NUMBER,[X.EXPIRATION_MONTH]:e.ElementType.EXPIRATION_MONTH,[X.EXPIRATION_YEAR]:e.ElementType.EXPIRATION_YEAR,[X.CARDHOLDER_NAME]:e.ElementType.CARDHOLDER_NAME},O={[X.CVV]:[Z],[X.CARD_NUMBER]:[Z],[X.EXPIRATION_MONTH]:[Z],[X.EXPIRATION_YEAR]:[Z],[X.CARDHOLDER_NAME]:[J,Z]},T={[X.CARDHOLDER_NAME]:"cardholderName",[X.CARD_NUMBER]:"cardNumber",[X.CVV]:"cvv",[X.EXPIRATION_MONTH]:"expirationMonth",[X.EXPIRATION_YEAR]:"expirationYear"},f=e=>{var t,r,o,i,n,s,a,d,l;const c=null===(t=null==p?void 0:p.styles)||void 0===t?void 0:t[T[e]],u=null===(r=null==p?void 0:p.styles)||void 0===r?void 0:r.cardForm,h=null!==(i=null!==(o=null==c?void 0:c.inputStyles)&&void 0!==o?o:null==u?void 0:u.inputStyles)&&void 0!==i?i:ue;return{inputStyles:e===X.CARD_NUMBER&&!1!==(null===(n=null==p?void 0:p.styles)||void 0===n?void 0:n.enableCardIcon)?Object.assign(Object.assign({},h),{base:Object.assign({paddingLeft:"15px"},null==h?void 0:h.base)}):h,labelStyles:null!==(a=null!==(s=null==c?void 0:c.labelStyles)&&void 0!==s?s:null==u?void 0:u.labelStyles)&&void 0!==a?a:he,errorStyles:null!==(l=null!==(d=null==c?void 0:c.errorStyles)&&void 0!==d?d:null==u?void 0:u.errorStyles)&&void 0!==l?l:Ee}},S={cardholder_name:(null===(o=null==p?void 0:p.labels)||void 0===o?void 0:o.name)||ee,card_number:(null===(i=null==p?void 0:p.labels)||void 0===i?void 0:i.card_number)||te,cvv:(null===(n=null==p?void 0:p.labels)||void 0===n?void 0:n.cvv)||re,expiration_date:(null===(s=null==p?void 0:p.labels)||void 0===s?void 0:s.expiry_date)||ne,expiration_month:(null===(a=null==p?void 0:p.labels)||void 0===a?void 0:a.expiration_month)||oe,expiration_year:(null===(d=null==p?void 0:p.labels)||void 0===d?void 0:d.expiration_year)||ie},I={cardholder_name:(null===(l=null==p?void 0:p.placeholders)||void 0===l?void 0:l.name)||se,card_number:(null===(c=null==p?void 0:p.placeholders)||void 0===c?void 0:c.card_number)||ae,cvv:(null===(u=null==p?void 0:p.placeholders)||void 0===u?void 0:u.cvv)||de,expiration_month:(null===(h=null==p?void 0:p.placeholders)||void 0===h?void 0:h.expiration_month)||le,expiration_year:(null===(E=null==p?void 0:p.placeholders)||void 0===E?void 0:E.expiration_year)||ce},g={[X.CVV]:null==y?void 0:y.cvvEvents,[X.CARD_NUMBER]:null==y?void 0:y.cardNumberEvents,[X.EXPIRATION_MONTH]:null==y?void 0:y.monthEvents,[X.EXPIRATION_YEAR]:null==y?void 0:y.yearEvents,[X.CARDHOLDER_NAME]:null==y?void 0:y.cardHolderEvents};if("fields"in m&&Array.isArray(m.fields)){const e={enableCardIcon:null===(R=null===(_=null==p?void 0:p.styles)||void 0===_?void 0:_.enableCardIcon)||void 0===R||R};if(m.fields.length>0&&"string"==typeof m.fields[0])for(const t of m.fields){const r=v.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:A[t],validations:O[t]},f(t)),{label:S[t],placeholder:I[t]}),m.card_id?{skyflowID:m.card_id}:{}),t===X.CARD_NUMBER?e:void 0);Re({element:r,errorStyles:f(t).errorStyles,fieldMessage:[X.CVV,X.EXPIRATION_MONTH,X.EXPIRATION_YEAR].includes(t)?"":S[t],events:g[t]});const o=`#collect_${String(t)}`+(m.card_id?`_${m.card_id}`:"");yield ye({element:r,containerId:o}),C.push({element:r,containerId:o})}else for(const t of m.fields){const r=t.field,o=v.create(Object.assign(Object.assign(Object.assign({table:"cards",column:r,type:A[r],validations:O[r]},f(r)),{label:S[r],placeholder:I[r]}),m.card_id?{skyflowID:m.card_id}:{}),r===X.CARD_NUMBER?e:void 0);Re({element:o,errorStyles:f(r).errorStyles,fieldMessage:[X.CVV,X.EXPIRATION_MONTH,X.EXPIRATION_YEAR].includes(r)?"":S[r],events:g[r]});const i=t.container_id||`#collect_${String(r)}`+(m.card_id?`_${m.card_id}`:"");yield ye({element:o,containerId:i}),C.push({element:o,containerId:i})}}return{elements:C.map((e=>e.element)),container:v}}))}({skyflowInstance:this.skyflowInstance,data:r,customization:this.customization,events:this.events});this.mountedElementsByContext.set(i,{elements:s.elements||[],container:s})}))}getContainerByCardId(e){var t;const r=`update:${e}`,o=this.mountedElementsByContext.get(r);return(null===(t=null==o?void 0:o.container)||void 0===t?void 0:t.container)||null}collectCardTokens(e){var r,o,i;return t(this,void 0,void 0,(function*(){const t=this.getContainerByCardId(e);if(!t)return null;try{const e=yield t.collect();return(null===(o=null===(r=null==e?void 0:e.records)||void 0===r?void 0:r[0])||void 0===o?void 0:o.fields)||null}catch(t){const r=null===(i=null==t?void 0:t.error)||void 0===i?void 0:i.description;throw this.reportSdkError(t,{feature:"collect-card-tokens",process_id:e,metadata:{step:"collectCardTokens"}}),new a({code:n.MOUNT_COLLECT_ERROR,details:{message:r}})}}))}collectCreateCardTokens(){var e,r,o,i;return t(this,void 0,void 0,(function*(){const t=this.mountedElementsByContext.get("create"),s=null===(e=null==t?void 0:t.container)||void 0===e?void 0:e.container;if(!s)throw new a({code:n.MOUNT_COLLECT_ERROR,details:{message:"No card fields are mounted. Call mountCardFields() with the required fields before proceeding."}});try{const e=yield s.collect(),t=(null===(o=null===(r=null==e?void 0:e.records)||void 0===r?void 0:r[0])||void 0===o?void 0:o.fields)||{};return this.lastCollectedTokens=t,t}catch(e){const t=null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.description;throw this.reportSdkError(e,{feature:"collect-create-card-tokens",metadata:{step:"collectCreateCardTokens"}}),new a({code:n.MOUNT_COLLECT_ERROR,details:{message:t}})}}))}revealCardFields(r){return t(this,void 0,void 0,(function*(){if(!this.lastCollectedTokens)throw C({errorCode:n.MOUNT_COLLECT_ERROR,details:{message:"No card tokens available. Call saveCustomerCard() or payment() with a new card before calling revealCardFields()."}});if(!this.skyflowInstance)throw C({errorCode:n.MOUNT_COLLECT_ERROR,details:{message:"Skyflow instance not initialized. Ensure mountCardFields() was called before saveCustomerCard() or payment()."}});yield function(r){var o,i,n,s,a,d;return t(this,void 0,void 0,(function*(){const{skyflowInstance:t,tokens:l,request:c}=r,u=t.container(e.ContainerType.REVEAL),h={[X.CARD_NUMBER]:"MASKED",[X.CARDHOLDER_NAME]:"PLAIN_TEXT",[X.EXPIRATION_MONTH]:"PLAIN_TEXT",[X.EXPIRATION_YEAR]:"PLAIN_TEXT"};for(const t of c.fields){const r="string"==typeof t,E=r?t:t.field;if(E===X.CVV){console.warn("[revealCardFields] CVV cannot be revealed (PCI DSS req. 3.2.1). Skipping.");continue}const _=l[E];if(!_){console.warn(`[revealCardFields] No token found for field "${E}", skipping.`);continue}const R=r?{}:t,m=null!==(o=R.container_id)&&void 0!==o?o:`#reveal_${E}`,p=h[E],y=null!==(i=R.styles)&&void 0!==i?i:{},v=null!==(n=c.styles)&&void 0!==n?n:{},C=u.create(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({token:_,redaction:e.RedactionType[p]},void 0!==R.altText&&{altText:R.altText}),void 0!==R.label&&{label:R.label}),y.inputStyles||v.inputStyles?{inputStyles:null!==(s=y.inputStyles)&&void 0!==s?s:v.inputStyles}:{}),y.labelStyles||v.labelStyles?{labelStyles:null!==(a=y.labelStyles)&&void 0!==a?a:v.labelStyles}:{}),y.errorTextStyles||v.errorTextStyles?{errorTextStyles:null!==(d=y.errorTextStyles)&&void 0!==d?d:v.errorTextStyles}:{}));yield ye({element:C,containerId:m})}try{yield u.reveal()}catch(e){console.warn("[revealCardFields] reveal completed with errors:",e)}}))}({skyflowInstance:this.skyflowInstance,tokens:this.lastCollectedTokens,request:r})}))}unmountCardFields(e="all"){"all"===e?(this.mountedElementsByContext.forEach(((e,t)=>{this.unmountContext(t)})),this.mountedElementsByContext.clear()):(this.unmountContext(e),this.mountedElementsByContext.delete(e))}unmountContext(e){const t=this.mountedElementsByContext.get(e);if(!t)return;const{elements:r}=t;r&&r.length>0&&r.forEach((t=>{try{t&&"function"==typeof t.unmount&&t.unmount()}catch(t){console.warn(`Error unmounting Skyflow element from context '${e}':`,t),this.reportSdkError(t,{feature:"unmount-card-fields",metadata:{step:"unmountContext",context:e}})}}))}getBusiness(){return t(this,void 0,void 0,(function*(){try{return yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw this.reportSdkError(e,{feature:"get-business",metadata:{step:"getBusiness"}}),C({errorCode:n.FETCH_BUSINESS_ERROR},e)}}))}createSkyflowInstance(){return t(this,void 0,void 0,(function*(){if(this.skyflowInstance)return this.skyflowInstance;yield this._fetchMerchantData();const{vault_id:r,vault_url:o}=this.merchantData;this.skyflowInstance=yield function({baseUrl:r,apiKey:o,vault_id:i,vault_url:n,mode:s}){return t(this,void 0,void 0,(function*(){const a="production"===s?e.Env.PROD:e.Env.DEV;return e.init({vaultID:i,vaultURL:n,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield W(r,o)})),options:{logLevel:e.LogLevel.ERROR,env:a}})}))}({vault_id:r,vault_url:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder,mode:this.mode})}))}getOpenpayDeviceSessionID(e,r,o){return t(this,void 0,void 0,(function*(){try{return yield f(e,r,o)}catch(e){throw this.reportSdkError(e,{feature:"get-openpay-device-session",metadata:{step:"getOpenpayDeviceSessionID"}}),C({errorCode:n.START_CHECKOUT_ERROR},e)}}))}getSkyflowTokens({vault_id:e,vault_url:r,data:o}){return t(this,void 0,void 0,(function*(){return yield _e({vault_id:e,vault_url:r,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:r,isSandbox:o,returnUrl:i}){var s,a;return t(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const d=yield this._getCustomer(this.abortController.signal),{business:l}=this.merchantData,{auth_token:c,first_name:u="",last_name:h="",email:E=""}=d,_=this._hasCardOnFileKeys();let R,m=null,p=null,y=null,v=!1;const A=()=>t(this,void 0,void 0,(function*(){var e,t;(null===(t=null===(e=this.customerCardsCache)||void 0===e?void 0:e.cards)||void 0===t?void 0:t.length)||(this.customerCardsCache=yield this._getCustomerCards(c,this.merchantData.business.pk))}));if(!r){if("string"==typeof e)if(p=e,R={skyflow_id:e},_){yield A();const t=null===(a=null===(s=this.customerCardsCache)||void 0===s?void 0:s.cards)||void 0===a?void 0:a.find((t=>t.fields.skyflow_id===e));if(!t)throw new Error("Card not found for card-on-file processing");const r=!!t.fields.subscription_id;r||(yield this.collectCardTokens(e)),r&&(m={subscriptionId:t.fields.subscription_id})}else yield this.collectCardTokens(e);else R=yield this.collectCreateCardTokens(),p=R.skyflow_id,_&&(y={name:R.cardholder_name,number:R.card_number,expiryMonth:R.expiration_month,expiryYear:R.expiration_year,cvv:R.cvv},v=!0);if(v){if(!p||!y)throw new Error("Missing card data for card-on-file processing");let e=null;try{const t=yield this._saveCustomerCard(c,null==l?void 0:l.pk,{skyflow_id:p},!0);e=t.skyflow_id;const r=t.card_bin;if(!r)throw new Error("Card BIN not returned from save card");const o=yield this._initializeCardOnFile();let i;try{i=yield o.process({cardTokens:y,cardBin:r,contactDetails:{firstName:u||"",lastName:h||"",email:E||""},customerId:c,currency:this.currency||"MXN"})}catch(e){throw C({errorCode:n.CARD_ON_FILE_DECLINED,lockErrorCode:!0},e)}m={subscriptionId:i.subscriptionId},yield this._saveCustomerCard(c,null==l?void 0:l.pk,{skyflow_id:p,subscription_id:m.subscriptionId})}catch(t){throw e&&(yield this.removeCustomerCard(e)),this.reportSdkError(t,{feature:"payment",process_id:e||this.getCustomerId(),metadata:{step:"card_on_file"}}),t}}}return yield this._handleCheckout({card:R,payment_method:r,customer:d,isSandbox:o,returnUrl:i,enable_card_on_file:!!(null==m?void 0:m.subscriptionId)&&_})}))}customerRegister(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/customer/`,r={email:e},o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield C({response:o,errorCode:n.CUSTOMER_OPERATION_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"customer-register",metadata:{step:"customerRegister"}}),C({errorCode:n.CUSTOMER_OPERATION_ERROR},e)}}))}createOrder(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/orders/`,r=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield C({response:o,errorCode:n.CREATE_ORDER_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-order",metadata:{step:"createOrder"}}),C({errorCode:n.CREATE_ORDER_ERROR},e)}}))}createPayment(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/business/${e.business_pk}/payments/`,r=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield C({response:o,errorCode:n.CREATE_PAYMENT_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-payment",metadata:{step:"createPayment"}}),C({errorCode:n.CREATE_PAYMENT_ERROR},e)}}))}startCheckoutRouter(e){return t(this,void 0,void 0,(function*(){const t=yield T(this.baseUrl,this.apiKeyTonder,e);if(yield this.init3DSRedirect(t))return t}))}init3DSRedirect(e){return t(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this._handle3dsRedirect(e)}))}startCheckoutRouterFull(e){return t(this,void 0,void 0,(function*(){try{const{order:t,total:r,customer:o,skyflowTokens:i,return_url:s,isSandbox:a,metadata:d,currency:l,payment_method:u}=e,h=yield this._fetchMerchantData(),E=yield this.customerRegister(o.email);if(!(E&&"auth_token"in E&&h&&"reference"in h))throw C({errorCode:n.START_CHECKOUT_ERROR,details:{message:"Merchant or customer reposne errors",merchantResult:h,customerResult:E}});{const e={business:this.apiKeyTonder,client:E.auth_token,billing_address_id:null,shipping_address_id:null,amount:r,reference:h.reference,is_oneclick:!0,items:t.items},_=yield this.createOrder(e),R=(new Date).toISOString();if(!("id"in _&&"id"in E&&"business"in h))throw C({errorCode:n.START_CHECKOUT_ERROR,details:{message:"Order response errors",orderResult:_}});{const e={business_pk:h.business.pk,amount:r,date:R,order_id:_.id,client_id:E.id},t=yield this.createPayment(e);let n;const{openpay_keys:m,business:p}=h;m.merchant_id&&m.public_key&&(n=yield f(m.merchant_id,m.public_key,a));const y=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:s,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:r,title_ship:"shipping",description:"transaction",device_session_id:n||null,token_id:"",order_id:"id"in _&&_.id,business_id:p.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:c(),currency:l},u?{payment_method:u}:{card:i}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),v=yield T(this.baseUrl,this.apiKeyTonder,y);if(yield this.init3DSRedirect(v))return v}}}catch(e){throw this.reportSdkError(e,{feature:"start-checkout-router-full",metadata:{step:"startCheckoutRouterFull"}}),C({errorCode:n.START_CHECKOUT_ERROR},e)}}))}registerCustomerCard(e,r,o){return t(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const t=yield fetch(`${this.baseUrl}/api/v1/business/${u(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":r,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(t.ok)return yield t.json();throw yield C({response:t,errorCode:n.SAVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"register-customer-card",metadata:{step:"registerCustomerCard"}}),C({errorCode:n.SAVE_CARD_ERROR},e)}}))}deleteCustomerCard(e,r=""){return t(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const t=yield fetch(`${this.baseUrl}/api/v1/business/${u(this.merchantData)}/cards/${r}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(t.ok)return!0;throw yield C({response:t,errorCode:n.REMOVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"delete-customer-card",process_id:r,metadata:{step:"deleteCustomerCard"}}),C({errorCode:n.REMOVE_CARD_ERROR},e)}}))}getActiveAPMs(){return t(this,void 0,void 0,(function*(){try{const e=yield function(e,r,o="?status=active&page_size=10000&country=México",i=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:i});if(t.ok)return yield t.json();throw yield C({response:t,errorCode:n.FETCH_PAYMENT_METHODS_ERROR})}))}(this.baseUrl,this.apiKeyTonder),r=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=r.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},Ae(e.payment_method,this.mode)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}function Te(e){return/^\d{12,19}$/.test(e)&&Ne(e)}function fe(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function Se(e){return/^\d{3,4}$/.test(e)}function Ie(e){return/^(0[1-9]|1[0-2])$/.test(e)}function ge(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const Ne=e=>{const t=`${e}`.split("").reverse().map((e=>Number.parseInt(e))),r=t.shift();let o=t.reduce(((e,t,r)=>r%2!=0?e+t:e+((t*=2)>9?t-9:t)),0);return o+=r,o%10==0};export{R as AppError,Q as BaseInlineCheckout,Oe as LiteCheckout,U as SdkTelemetryClient,Se as validateCVV,Te as validateCardNumber,fe as validateCardholderName,Ie as validateExpirationMonth,ge as validateExpirationYear};
|
|
1
|
+
import e from"skyflow-js";function t(e,t,r,o){return new(r||(r=Promise))((function(i,n){function s(e){try{d(o.next(e))}catch(e){n(e)}}function a(e){try{d(o.throw(e))}catch(e){n(e)}}function d(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}d((o=o.apply(e,t||[])).next())}))}function r(e,t,r,o){if("a"===r&&!o)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!o:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?o:"a"===r?o.call(e):o?o.value:t.get(e)}function o(e,t,r,o,i){if("m"===o)throw new TypeError("Private method is not writable");if("a"===o&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===o?i.call(e,r):i?i.value=r:t.set(e,r),r}function i(e,r,o){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/v1/payments/business/${r}`,{headers:{Authorization:`Token ${r}`},signal:o});return yield t.json()}))}var n;"function"==typeof SuppressedError&&SuppressedError,function(e){e.INIT_ERROR="INIT_ERROR",e.CREATE_ERROR="CREATE_ERROR",e.REMOVE_SDK_ERROR="REMOVE_SDK_ERROR",e.INVALID_TYPE="INVALID_TYPE",e.STATE_ERROR="STATE_ERROR",e.FETCH_BUSINESS_ERROR="FETCH_BUSINESS_ERROR",e.INVALID_CONFIG="INVALID_CONFIG",e.MERCHANT_CREDENTIAL_REQUIRED="MERCHANT_CREDENTIAL_REQUIRED",e.INVALID_PAYMENT_REQUEST="INVALID_PAYMENT_REQUEST",e.INVALID_PAYMENT_REQUEST_CARD_PM="INVALID_PAYMENT_REQUEST_CARD_PM",e.TYPE_SDK_REQUIRED="TYPE_SDK_REQUIRED",e.ENVIRONMENT_REQUIRED="ENVIRONMENT_REQUIRED",e.FETCH_CARDS_ERROR="FETCH_CARDS_ERROR",e.FETCH_TRANSACTION_ERROR="FETCH_TRANSACTION_ERROR",e.CUSTOMER_AUTH_TOKEN_NOT_VALID="CUSTOMER_AUTH_TOKEN_NOT_VALID",e.SAVE_CARD_ERROR="SAVE_CARD_ERROR",e.REMOVE_CARD_ERROR="REMOVE_CARD_ERROR",e.SUMMARY_CARD_ERROR="SUMMARY_CARD_ERROR",e.CREATE_PAYMENT_ERROR="CREATE_PAYMENT_ERROR",e.PAYMENT_PROCESS_ERROR="PAYMENT_PROCESS_ERROR",e.INVALID_CARD_DATA="INVALID_CARD_DATA",e.SAVE_CARD_PROCESS_ERROR="SAVE_CARD_PROCESS_ERROR",e.START_CHECKOUT_ERROR="START_CHECKOUT_ERROR",e.CREATE_ORDER_ERROR="CREATE_ORDER_ERROR",e.BUSINESS_ID_REQUIRED="BUSINESS_ID_REQUIRED",e.CLIENT_ID_REQUIRED="CLIENT_ID_REQUIRED",e.INVALID_AMOUNT="INVALID_AMOUNT",e.INVALID_ITEMS="INVALID_ITEMS",e.CUSTOMER_OPERATION_ERROR="CUSTOMER_OPERATION_ERROR",e.INVALID_EMAIL="INVALID_EMAIL",e.FETCH_PAYMENT_METHODS_ERROR="FETCH_PAYMENT_METHODS_ERROR",e.INVALID_VAULT_TOKEN="INVALID_VAULT_TOKEN",e.VAULT_TOKEN_ERROR="VAULT_TOKEN_ERROR",e.SECURE_TOKEN_ERROR="SECURE_TOKEN_ERROR",e.SECURE_TOKEN_INVALID="SECURE_TOKEN_INVALID",e.INVALID_SECRET_API_KEY="INVALID_SECRET_API_KEY",e.REMOVE_CARD="REMOVE_CARD",e.SKYFLOW_NOT_INITIALIZED="SKYFLOW_NOT_INITIALIZED",e.ERROR_LOAD_PAYMENT_FORM="ERROR_LOAD_PAYMENT_FORM",e.ERROR_LOAD_ENROLLMENT_FORM="ERROR_LOAD_ENROLLMENT_FORM",e.MOUNT_COLLECT_ERROR="MOUNT_COLLECT_ERROR",e.CARD_ON_FILE_DECLINED="CARD_ON_FILE_DECLINED",e.CARD_SAVED_SUCCESSFULLY="CARD_SAVED_SUCCESSFULLY",e.CARD_REMOVED_SUCCESSFULLY="CARD_REMOVED_SUCCESSFULLY",e.REQUEST_ABORTED="REQUEST_ABORTED",e.REQUEST_FAILED="REQUEST_FAILED",e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.THREEDS_REDIRECTION_ERROR="THREEDS_REDIRECTION_ERROR"}(n||(n={}));const s={[n.INIT_ERROR]:"Error initializing the SDK.",[n.INVALID_TYPE]:"SDK Type invalid.",[n.STATE_ERROR]:"Error updating SDK state.",[n.FETCH_BUSINESS_ERROR]:"Error retrieving merchant information.",[n.INVALID_CONFIG]:"Required configuration options.",[n.MERCHANT_CREDENTIAL_REQUIRED]:"Merchant credential required.",[n.INVALID_PAYMENT_REQUEST]:"The payment data must be of type: :::interface:::.",[n.INVALID_PAYMENT_REQUEST_CARD_PM]:"The fields card and payment_method cannot be provided together.",[n.TYPE_SDK_REQUIRED]:"SDK type required.",[n.ENVIRONMENT_REQUIRED]:"Environment required.",[n.FETCH_CARDS_ERROR]:"Error retrieving cards.",[n.CUSTOMER_AUTH_TOKEN_NOT_VALID]:"The customer's auth token is invalid. Please verify that the customer's data was provided when creating the SDK (sdk.create) and try again.",[n.SAVE_CARD_ERROR]:"Error saving the card.",[n.REMOVE_CARD_ERROR]:"Error deleting the card.",[n.CREATE_PAYMENT_ERROR]:"Error creating the payment.",[n.PAYMENT_PROCESS_ERROR]:"There was an issue processing the payment.",[n.CARD_SAVED_SUCCESSFULLY]:"Card saved successfully.",[n.CARD_REMOVED_SUCCESSFULLY]:"Card deleted successfully.",[n.SAVE_CARD_PROCESS_ERROR]:"Error processing card data.",[n.START_CHECKOUT_ERROR]:"Error processing the payment.",[n.CREATE_ORDER_ERROR]:"Error creating the order.",[n.BUSINESS_ID_REQUIRED]:"Business ID is required.",[n.CLIENT_ID_REQUIRED]:"Client ID is required.",[n.INVALID_AMOUNT]:"Invalid amount.",[n.INVALID_ITEMS]:"Invalid items.",[n.CUSTOMER_OPERATION_ERROR]:"Error registering or fetching customer",[n.INVALID_EMAIL]:"Invalid email.",[n.FETCH_PAYMENT_METHODS_ERROR]:"Error retrieving active payment methods.",[n.INVALID_VAULT_TOKEN]:"An invalid vault token response was received.",[n.VAULT_TOKEN_ERROR]:"Error retrieving the vault token.",[n.SECURE_TOKEN_ERROR]:"Error getting secure token.",[n.SECURE_TOKEN_INVALID]:"Invalid secure token.",[n.INVALID_SECRET_API_KEY]:"SECRET API KEY is required.",[n.REMOVE_CARD]:"Card deleted successfully",[n.SKYFLOW_NOT_INITIALIZED]:"Skyflow not initialized.",[n.ERROR_LOAD_PAYMENT_FORM]:"There was an issue loading the payment form.",[n.INVALID_CARD_DATA]:"Invalid card data.",[n.ERROR_LOAD_ENROLLMENT_FORM]:"There was an issue loading the card form.",[n.MOUNT_COLLECT_ERROR]:"Mount failed. Make sure all inputs are complete and valid.",[n.CARD_ON_FILE_DECLINED]:"Transaction declined. Please verify your card details.",[n.REQUEST_ABORTED]:"Requests canceled.",[n.REQUEST_FAILED]:"Request failed.",[n.UNKNOWN_ERROR]:"An unexpected error occurred.",[n.CREATE_ERROR]:"Error creating the SDK.",[n.FETCH_TRANSACTION_ERROR]:"Error retrieving the transaction.",[n.THREEDS_REDIRECTION_ERROR]:"An error occurred during the 3DS redirection.",[n.REMOVE_SDK_ERROR]:"An error occurred while removing the SDK instance."};n.INIT_ERROR,n.STATE_ERROR,n.FETCH_BUSINESS_ERROR,n.INVALID_CONFIG,n.TYPE_SDK_REQUIRED,n.ENVIRONMENT_REQUIRED,n.FETCH_CARDS_ERROR,n.SAVE_CARD_ERROR,n.REMOVE_CARD_ERROR,n.CREATE_PAYMENT_ERROR,n.START_CHECKOUT_ERROR,n.CREATE_ORDER_ERROR,n.BUSINESS_ID_REQUIRED,n.CLIENT_ID_REQUIRED,n.INVALID_AMOUNT,n.INVALID_ITEMS,n.CUSTOMER_OPERATION_ERROR,n.INVALID_EMAIL,n.FETCH_PAYMENT_METHODS_ERROR,n.INVALID_VAULT_TOKEN,n.VAULT_TOKEN_ERROR,n.SECURE_TOKEN_ERROR,n.INVALID_SECRET_API_KEY,n.CUSTOMER_AUTH_TOKEN_NOT_VALID,n.SECURE_TOKEN_INVALID,n.REMOVE_CARD,n.SKYFLOW_NOT_INITIALIZED,n.INVALID_TYPE,n.PAYMENT_PROCESS_ERROR,n.INVALID_PAYMENT_REQUEST,n.INVALID_PAYMENT_REQUEST_CARD_PM,n.SAVE_CARD_PROCESS_ERROR,n.ERROR_LOAD_PAYMENT_FORM,n.INVALID_CARD_DATA,n.ERROR_LOAD_ENROLLMENT_FORM,n.MOUNT_COLLECT_ERROR,n.CARD_ON_FILE_DECLINED,n.CARD_SAVED_SUCCESSFULLY,n.CARD_REMOVED_SUCCESSFULLY,n.REQUEST_ABORTED,n.REQUEST_FAILED,n.UNKNOWN_ERROR,n.CREATE_ERROR,n.FETCH_TRANSACTION_ERROR,n.THREEDS_REDIRECTION_ERROR,n.REMOVE_SDK_ERROR;class a extends Error{constructor(e){var t,r;const o=e.message||s[e.code]||"Unknown error";super(o),this.name="TonderError",this.code=e.code,this.details={code:(null===(t=e.details)||void 0===t?void 0:t.code)||e.code,message:(null===(r=e.details)||void 0===r?void 0:r.message)||o}}}const d=Object.freeze({production:"https://d35a75syrgujp0.cloudfront.net",sandbox:"https://static.staging.tonder.io",stage:"https://static.staging.tonder.io",development:"https://static.staging.tonder.io"});function l(e="stage"){return d[e]||d.stage}const c=()=>({javascript_enabled:!0,time_zone:(new Date).getTimezoneOffset(),language:navigator.language||"en-US",color_depth:window.screen?window.screen.colorDepth:null,screen_width:window.screen?window.screen.width*window.devicePixelRatio||window.screen.width:null,screen_height:window.screen?window.screen.height*window.devicePixelRatio||window.screen.height:null,user_agent:navigator.userAgent}),u=e=>{var t;return e&&"business"in e?null===(t=null==e?void 0:e.business)||void 0===t?void 0:t.pk:""},h=(e,t="stage")=>{const r=l(t);return"Visa"===e?`${r}/cards/visa.png`:"Mastercard"===e?`${r}/cards/mastercard.png`:"American Express"===e?`${r}/cards/american_express.png`:`${r}/cards/default_card.png`},E="__tonderLockErrorCode__";function _(e){return"object"==typeof e&&null!==e}class m extends Error{constructor(e){var t,r;const o=m.resolveStatusCode(e.statusCode,e.originalError),i=m.resolveMessage(e.errorCode,e.message),n=m.resolveSystemError(null===(t=e.details)||void 0===t?void 0:t.systemError,e.originalError);super(i),this.status="error",Object.setPrototypeOf(this,new.target.prototype),this.name="TonderError",this.code=e.errorCode,this.statusCode=o,this.originalError=e.originalError,this.details={code:e.errorCode,statusCode:o,systemError:n},e.lockErrorCode&&Object.defineProperty(this,E,{value:!0,enumerable:!1,configurable:!0}),null===(r=Error.captureStackTrace)||void 0===r||r.call(Error,this,m)}static isRecord(e){return"object"==typeof e&&null!==e}static parseStatusCode(e){const t=Number(e);return Number.isFinite(t)?t<100||t>599?500:Math.trunc(t):500}static resolveStatusCode(e,t){const r=[e];if(m.isRecord(t)){r.push(t.statusCode,t.status);const e=m.isRecord(t.body)?t.body:null;e&&r.push(e.statusCode,e.status)}for(const e of r)if(m.isHttpStatusCode(e))return Math.trunc(Number(e));return 500}static resolveMessage(e,t){return t||(s[e]||s[n.UNKNOWN_ERROR]||"An unexpected error occurred.")}static isHttpStatusCode(e){const t=Number(e);return Number.isFinite(t)&&t>=100&&t<=599}static normalizeSystemError(e){if("string"!=typeof e)return null;return e.trim()||null}static resolveSystemError(e,t){const r=[e];if(m.isRecord(t)){const e=m.isRecord(t.details)?t.details:null,o=m.isRecord(t.body)?t.body:null,i=o&&m.isRecord(o.details)?o.details:null;r.push(t.systemError,t.code,null==e?void 0:e.systemError,null==e?void 0:e.code,null==o?void 0:o.systemError,null==o?void 0:o.code,null==i?void 0:i.systemError,null==i?void 0:i.code)}for(const e of r){const t=m.normalizeSystemError(e);if(t)return t}return"APP_INTERNAL_001"}}function R(e){return _(e)&&!0===e[E]}function p(e){return e instanceof m&&void 0!==e.originalError?e.originalError:e}function y(e,t){var r;if(!(null==e?void 0:e.errorCode))throw new Error("buildPublicAppError requires errorCode");const o=null===(r=e.details)||void 0===r?void 0:r.systemError,i=!!e.message||void 0!==e.statusCode||void 0!==o;return!function(e){return _(e)&&"TonderError"===e.name&&"string"==typeof e.code}(t)||(e.lockErrorCode&&function(e){Object.defineProperty(e,E,{value:!0,enumerable:!1,configurable:!0})}(t),i||e.errorCode!==t.code&&!R(t))?new m({errorCode:e.errorCode,message:e.message,statusCode:e.statusCode,details:void 0!==o?{systemError:o}:void 0,originalError:p(t),lockErrorCode:e.lockErrorCode||R(t)}):t}function v(e){var r,o;return t(this,void 0,void 0,(function*(){const i=yield function(e){return t(this,void 0,void 0,(function*(){try{return yield e.clone().json()}catch(e){}try{return(yield e.text())||void 0}catch(e){return}}))}(e.response),n={status:e.response.status};return e.response.statusText&&(n.statusText=e.response.statusText),void 0!==i&&(n.body=i),new m({errorCode:e.errorCode,message:e.message,statusCode:null!==(r=e.statusCode)&&void 0!==r?r:e.response.status,details:void 0!==(null===(o=e.details)||void 0===o?void 0:o.systemError)?{systemError:e.details.systemError}:void 0,originalError:n,lockErrorCode:e.lockErrorCode})}))}function C(e,t){return(null==e?void 0:e.response)?v(e):y(e,t)}const A=new Set(["https:"]);function f(e){if("string"!=typeof e)return!1;try{return A.has(new URL(e,document.baseURI).protocol)}catch(e){return!1}}const O=new Set(["script","object","embed","applet","link","meta","base","style","template"]),T=new Set(["srcdoc","style","ping","srcset"]),S=new Set(["src","href","action","formaction","data","poster","background"]);function I(e){const t=e.trim();return""===t||("about:blank"===t.toLowerCase()||f(t))}function g(e){for(const t of Array.from(e.attributes)){const r=t.localName.toLowerCase();r.startsWith("on")||T.has(r)?e.removeAttributeNode(t):S.has(r)&&!I(t.value)&&e.removeAttributeNode(t)}}class N{constructor({payload:e=null,apiKey:t,baseUrl:r,redirectOnComplete:o,tdsIframeId:i,tonderPayButtonId:n,callBack:s}){this.localStorageKey="verify_transaction_status_url",this.setPayload=e=>{this.payload=e},this.baseUrl=r,this.apiKey=t,this.payload=e,this.tdsIframeId=i,this.tonderPayButtonId=n,this.redirectOnComplete=o,this.callBack=s}setStorageItem(e){return localStorage.setItem(this.localStorageKey,JSON.stringify(e))}getStorageItem(){return localStorage.getItem(this.localStorageKey)}removeStorageItem(){return localStorage.removeItem(this.localStorageKey)}saveVerifyTransactionUrl(){var e,t,r,o,i,n;const s=null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===r?void 0:r.verify_transaction_status_url;if(s)this.saveUrlWithExpiration(s);else{const e=null===(n=null===(i=null===(o=this.payload)||void 0===o?void 0:o.next_action)||void 0===i?void 0:i.iframe_resources)||void 0===n?void 0:n.verify_transaction_status_url;e?this.saveUrlWithExpiration(e):console.log("No verify_transaction_status_url found")}}saveUrlWithExpiration(e){try{const t={url:e,expires:(new Date).getTime()+12e5};this.setStorageItem(t)}catch(e){console.log("error: ",e)}}getUrlWithExpiration(){const e=this.getStorageItem();if(e){const t=JSON.parse(e);if(!t)return;return(new Date).getTime()>t.expires?(this.removeVerifyTransactionUrl(),null):t.url}return null}removeVerifyTransactionUrl(){return this.removeStorageItem()}getVerifyTransactionUrl(){return this.getStorageItem()}loadIframe(){var e,t,r;if(null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.iframe_resources)||void 0===r?void 0:r.iframe)return new Promise(((e,t)=>{var r,o,i;const n=null===(i=null===(o=null===(r=this.payload)||void 0===r?void 0:r.next_action)||void 0===o?void 0:o.iframe_resources)||void 0===i?void 0:i.iframe;if(n){this.saveVerifyTransactionUrl();const r=document.createElement("div");r.style.display="none",r.appendChild(function(e){const t=(new DOMParser).parseFromString(e,"text/html");for(const e of Array.from(t.body.querySelectorAll("*")))"http://www.w3.org/1999/xhtml"!==e.namespaceURI||O.has(e.localName)?e.remove():g(e);const r=document.createDocumentFragment();for(const e of Array.from(t.body.childNodes))r.appendChild(document.importNode(e,!0));return r}(n)),document.body.appendChild(r);const o=document.createElement("script");o.textContent='document.getElementById("tdsMmethodForm").submit();',r.appendChild(o);const i=document.getElementById("tdsMmethodTgtFrame");i?i.onload=()=>e(!0):(console.log("No redirection found"),t(!1))}else console.log("No redirection found"),t(!1)}))}getRedirectUrl(){var e,t,r;return null===(r=null===(t=null===(e=this.payload)||void 0===e?void 0:e.next_action)||void 0===t?void 0:t.redirect_to_url)||void 0===r?void 0:r.url}redirectToChallenge(){const e=this.getRedirectUrl();if(e){if(!f(e))throw C({errorCode:n.THREEDS_REDIRECTION_ERROR,statusCode:400,lockErrorCode:!0});if(this.saveVerifyTransactionUrl(),this.redirectOnComplete)window.location=e;else{const r=document.querySelector(`#${this.tdsIframeId}`);if(r){r.setAttribute("src",e),r.setAttribute("style","display: block");const o=this,i=e=>t(this,void 0,void 0,(function*(){const e=()=>{try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}r&&r.setAttribute("style","display: none"),o.callBack&&o.callBack(o.payload),r.removeEventListener("load",i)},n=r=>t(this,void 0,void 0,(function*(){const i=yield new Promise(((e,t)=>e(r)));if(i){if((e=>"Pending"!==(null==e?void 0:e.transaction_status))(i))return e();{const e=setTimeout((()=>t(this,void 0,void 0,(function*(){clearTimeout(e),yield n(o.requestTransactionStatus())}))),7e3)}}}));yield n(o.requestTransactionStatus())}));r.addEventListener("load",i)}else console.log("No iframe found")}}else this.callBack&&this.callBack(this.payload)}requestTransactionStatus(){return t(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration(),t=e.startsWith("https://")?e:`${this.baseUrl}${e}`,r=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});if(200!==r.status)return console.error("La verificación de la transacción falló."),null;return yield r.json()}))}getURLParameters(){const e={},t=new URLSearchParams(window.location.search);for(const[r,o]of t)e[r]=o;return e}handleSuccessTransaction(e){return this.removeVerifyTransactionUrl(),e}handleDeclinedTransaction(e){return this.removeVerifyTransactionUrl(),e}handle3dsChallenge(e){return t(this,void 0,void 0,(function*(){const t=document.createElement("form");t.name="frm",t.method="POST",t.action=e.redirect_post_url;const r=document.createElement("input");r.type="hidden",r.name=e.creq,r.value=e.creq,t.appendChild(r);const o=document.createElement("input");o.type="hidden",o.name=e.term_url,o.value=e.TermUrl,t.appendChild(o),document.body.appendChild(t),t.submit(),yield this.verifyTransactionStatus()}))}handleTransactionResponse(e){return t(this,void 0,void 0,(function*(){const t=yield e.json();return"Pending"===t.status&&t.redirect_post_url?yield this.handle3dsChallenge(t):["Success","Authorized"].includes(t.status)?this.handleSuccessTransaction(t):(this.handleDeclinedTransaction(e),t)}))}verifyTransactionStatus(){return t(this,void 0,void 0,(function*(){const e=this.getUrlWithExpiration();if(e){const t=e.startsWith("https://")?e:`${this.baseUrl}${e}`;try{const e=yield fetch(t,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`}});return 200!==e.status?(console.error("La verificación de la transacción falló."),this.removeVerifyTransactionUrl(),e):yield this.handleTransactionResponse(e)}catch(e){console.error("Error al verificar la transacción:",e),this.removeVerifyTransactionUrl()}}else console.log("No verify_transaction_status_url found")}))}}const b=Object.freeze({production:"https://app.tonder.io",sandbox:"https://sandbox.tonder.io",stage:"https://stage.tonder.io",development:"http://localhost:8000"});function D(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/checkout-router/`,i=o,s=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(Object.assign(Object.assign({},i),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}))});if(s.ok)return yield s.json();throw yield C({response:s,errorCode:n.START_CHECKOUT_ERROR})}))}function M(e,r,o=!0,i=null){return t(this,void 0,void 0,(function*(){let t=yield window.OpenPay;return t.setId(e),t.setApiKey(r),t.setSandboxMode(o),yield t.deviceData.setup({signal:i})}))}function k(e){return/^\d{12,19}$/.test(e)&&V(e)}function P(e){return/^([a-zA-Z\\ \\,\\.\\-\\']{2,})$/.test(e)}function U(e){return/^\d{3,4}$/.test(e)}function L(e){return/^(0[1-9]|1[0-2])$/.test(e)}function w(e){if(!/^\d{2}$/.test(e))return!1;const t=(new Date).getFullYear()%100;return parseInt(e,10)>=t}const V=e=>{const t=`${e}`.split("").reverse().map((e=>Number.parseInt(e))),r=t.shift();let o=t.reduce(((e,t,r)=>r%2!=0?e+t:e+((t*=2)>9?t-9:t)),0);return o+=r,o%10==0};function F(e,t,r){const o=t.replace(/\[(\w+)\]/g,".$1").split(".").filter((e=>""!==e));let i=e;for(const e of o){if(null==i)return r;i=i[e]}return void 0===i?r:i}const K=Object.freeze({production:"https://api.tonder.io",sandbox:"https://api-stage.tonder.io",stage:"https://api-stage.tonder.io",development:"https://api-stage.tonder.io"}),x=Object.freeze({TELEMETRY:"/telemetry/v1/events",ACQ_SUBSCRIPTION_TOKEN:"/acq-kushki/subscription/token",ACQ_SUBSCRIPTION_CREATE:"/acq-kushki/subscription/create"});function j(e="stage"){return`${K[e]}${x.TELEMETRY}`}const B="https://cdn.kushkipagos.com/kushki.min.js",Y=n.CARD_ON_FILE_DECLINED;let $=!1,H=null;class z{constructor(e){var t;this.acquirerInstance=null,this.isTestEnvironment=null===(t=e.isTestEnvironment)||void 0===t||t;const r=this.isTestEnvironment?"stage":"production";this.apiUrl=function(e="stage"){return K[e]}(r),this.merchantId=e.merchantId,this.apiKey=e.apiKey}initialize(){return t(this,void 0,void 0,(function*(){yield function(){return t(this,void 0,void 0,(function*(){return $?Promise.resolve():H||(H=new Promise(((e,t)=>{if(document.querySelector(`script[src="${B}"]`))return $=!0,void e();const r=document.createElement("script");r.src=B,r.async=!0,r.onload=()=>{$=!0,e()},r.onerror=()=>{H=null,t(C({errorCode:Y,lockErrorCode:!0,details:{step:"load_acquirer_script",message:"Failed to load acquirer script"}}))},document.head.appendChild(r)})),H)}))}(),this.acquirerInstance=function(e,t){if(!window.Kushki)throw C({errorCode:Y,lockErrorCode:!0,details:{step:"create_acquirer_instance",message:"Acquirer script not loaded. Call initialize() first."}});return new window.Kushki({merchantId:e,inTestEnvironment:t})}(this.merchantId,this.isTestEnvironment)}))}getAcquirerInstance(){if(!this.acquirerInstance)throw C({errorCode:Y,lockErrorCode:!0,details:{step:"get_acquirer_instance",message:"CardOnFile not initialized. Call initialize() first."}});return this.acquirerInstance}getJwt(e){return t(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((r,o)=>{t.requestSecureInit({card:{number:e}},(e=>{if("code"in e&&e.code)return void o(C({errorCode:Y,lockErrorCode:!0,details:{step:"get_jwt",acquirerResponse:e}}));const t=e;t.jwt?r(t.jwt):o(C({errorCode:Y,lockErrorCode:!0,details:{step:"get_jwt",message:"No JWT returned from acquirer",acquirerResponse:t}}))}))}))}))}generateToken(e){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${x.ACQ_SUBSCRIPTION_TOKEN}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield C({response:t,errorCode:Y,lockErrorCode:!0,details:{step:"generate_token"}});return t.json()}))}createSubscription(e){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${this.apiUrl}${x.ACQ_SUBSCRIPTION_CREATE}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKey}`},body:JSON.stringify(e)});if(!t.ok)throw yield C({response:t,errorCode:Y,lockErrorCode:!0,details:{step:"create_subscription"}});return t.json()}))}validate3DS(e,r){return t(this,void 0,void 0,(function*(){const t=this.getAcquirerInstance();return new Promise(((o,i)=>{t.requestValidate3DS({secureId:e,security:r},(e=>{const t=e;t.code&&"3DS000"!==t.code?i(C({errorCode:Y,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}})):!1!==t.isValid?o(!0):i(C({errorCode:Y,lockErrorCode:!0,details:{step:"validate_3ds",message:"3DS validation failed",acquirerResponse:t}}))}))}))}))}process(e){var r,o;return t(this,void 0,void 0,(function*(){const t=yield this.getJwt(e.cardBin),i=yield this.generateToken({card:e.cardTokens,currency:e.currency,jwt:t}),n=i.secureId||(null===(r=i.details)||void 0===r?void 0:r.secureId),s=i.security||(null===(o=i.details)||void 0===o?void 0:o.security);if(!n||!s)throw C({errorCode:Y,lockErrorCode:!0,details:{step:"process",message:"Missing secureId or security in token response",tokenResponse:i}});return yield this.validate3DS(n,s),this.createSubscription({token:i.token,contactDetails:e.contactDetails,metadata:{customerId:e.customerId},currency:e.currency})}))}}class q{constructor(e){this.REQUEST_TIMEOUT_MS=5e3,this.MAX_MESSAGE_LENGTH=500,this.config=e}captureException(e,t){try{const r=this.buildEvent(e,t||{});this.sendEvent(r)}catch(e){}}extractErrorInfo(e){try{if(e instanceof Error)return{name:e.name||"Error",message:this.truncate(e.message||"Unknown error",this.MAX_MESSAGE_LENGTH),stack:e.stack||void 0};const t=this.safeStringify(e);return{name:"NonErrorException",message:this.truncate(t,this.MAX_MESSAGE_LENGTH),stack:void 0}}catch(e){return{name:"SerializationError",message:"Failed to serialize error",stack:void 0}}}safeStringify(e){try{const t=new WeakSet;return JSON.stringify(e,((e,r)=>{if("object"==typeof r&&null!==r){if(t.has(r))return"[Circular]";t.add(r)}return r}))}catch(t){return String(e)}}buildEvent(e,t){const r=this.extractErrorInfo(e),o=Object.assign({},t.metadata||{});void 0===o.error&&(o.error=e),"undefined"!=typeof window&&(o.url=window.location.href);const i={platform:this.config.platform,platform_version:this.config.platform_version,env:this.config.mode,feature:t.feature||"unknown",level:"error",message:r.message,name:r.name,metadata:o};return t.tenant_id&&(i.tenant_id=t.tenant_id),t.request_id&&(i.request_id=t.request_id),t.process_id&&(i.process_id=t.process_id),t.user_id&&(i.user_id=t.user_id),r.stack&&(i.stack=r.stack),t.error_code&&(i.error_code=t.error_code),t.http_status&&(i.http_status=t.http_status),i}truncate(e,t){return e.length<=t?e:e.substring(0,t)+"..."}sendEvent(e){this.sendHttpRequest(e).then((()=>{})).catch((()=>{}))}sendHttpRequest(e){return t(this,void 0,void 0,(function*(){try{const t=JSON.stringify(e),r=new AbortController,o=setTimeout((()=>r.abort()),this.REQUEST_TIMEOUT_MS);try{const e=yield fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.config.apiKey}`},body:t,keepalive:!0,signal:r.signal});return clearTimeout(o),e.ok}catch(e){return clearTimeout(o),!1}}catch(e){return!1}}))}}const X=Object.freeze({name:"@tonder.io/ionic-lite-sdk",version:"1.0.2"});var Q,W,J,G,Z,ee,te,re,oe,ie,ne,se,ae;class de{constructor({mode:e="stage",customization:t,apiKey:r,apiKeyTonder:o,returnUrl:i,tdsIframeId:n,callBack:s=(()=>{}),baseUrlTonder:a,tonderPayButtonId:d,sdkInfo:l}){Q.add(this),this.baseUrl="",this.cartTotal="0",this.secureToken="",this.customization={redirectOnComplete:!0},this.metadata={},this.order_reference=null,this.card={},this.currency="",this.cardOnFileInstance=null,W.set(this,void 0),J.set(this,void 0),this.apiKeyTonder=o||r||"",this.returnUrl=i,this.callBack=s,this.mode=e,this.customer={},this.baseUrl=a||b[this.mode]||b.stage,this.abortController=new AbortController,this.requestId=this.generateRequestId(),this.customization=Object.assign(Object.assign({},this.customization),t||{}),this.process3ds=new N({apiKey:r,baseUrl:this.baseUrl,redirectOnComplete:this.customization.redirectOnComplete,tdsIframeId:n,tonderPayButtonId:d,callBack:s}),this.tdsIframeId=n;const c=l||X;this.telemetry=new q({endpoint:j(this.mode),apiKey:this.apiKeyTonder,platform:c.name,platform_version:c.version,mode:this.mode||"stage"})}configureCheckout(e){"secureToken"in e&&r(this,Q,"m",ee).call(this,e.secureToken),r(this,Q,"m",G).call(this,e)}getCustomerId(){var e,t;return null===(t=null===(e=r(this,J,"f"))||void 0===e?void 0:e.id)||void 0===t?void 0:t.toString()}reportSdkError(e,t){var r,o,i,n;try{const s=this.getCustomerId(),a=e instanceof m&&void 0!==e.originalError?e.originalError:e,d=Object.assign(Object.assign({},(null==t?void 0:t.metadata)||{}),void 0===(null===(r=null==t?void 0:t.metadata)||void 0===r?void 0:r.error)?{error:a}:{}),l=Object.assign(Object.assign({tenant_id:null===(n=null===(i=null===(o=this.merchantData)||void 0===o?void 0:o.business)||void 0===i?void 0:i.pk)||void 0===n?void 0:n.toString(),user_id:s},t||{}),{metadata:d,request_id:this.requestId});l.user_id||delete l.user_id,l.feature=(null==t?void 0:t.feature)||"unknown",this.telemetry.captureException(e,l)}catch(e){}}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}verify3dsTransaction(){return t(this,void 0,void 0,(function*(){const e=yield this.process3ds.verifyTransactionStatus(),t=yield r(this,Q,"m",ne).call(this,e);return this.process3ds.setPayload(t),this._handle3dsRedirect(t)}))}payment(e){return new Promise(((o,i)=>t(this,void 0,void 0,(function*(){var t,s;let a;try{r(this,Q,"m",G).call(this,e),a=yield this._checkout(e),this.process3ds.setPayload(a);if(yield this._handle3dsRedirect(a)){try{const e=document.querySelector(`#${this.tonderPayButtonId}`);e&&(e.disabled=!1)}catch(e){}this.callBack&&this.callBack(a),o(a)}}catch(r){this.reportSdkError(r,{feature:"payment",process_id:(null==a?void 0:a.payment_id)||(null===(t=null==a?void 0:a.payment)||void 0===t?void 0:t.id)||(null===(s=null==a?void 0:a.payment)||void 0===s?void 0:s.pk),metadata:{step:"payment",request:e,response:a}}),i(C({errorCode:n.PAYMENT_PROCESS_ERROR},r))}}))))}getSecureToken(e){return t(this,void 0,void 0,(function*(){try{return yield function(e,r,o=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/secure-token/`,{method:"POST",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:o});if(t.ok)return yield t.json();throw yield C({response:t,errorCode:n.SECURE_TOKEN_ERROR})}))}(this.baseUrl,e)}catch(e){throw this.reportSdkError(e,{feature:"secure-token",metadata:{step:"getSecureToken"}}),C({errorCode:n.SECURE_TOKEN_ERROR},e)}}))}_initializeCheckout(){return t(this,void 0,void 0,(function*(){const e=yield this._fetchMerchantData();e&&e.mercado_pago&&e.mercado_pago.active&&function(){try{const e=document.createElement("script");e.src="https://www.mercadopago.com/v2/security.js",e.setAttribute("view",""),e.onload=()=>{},e.onerror=e=>{console.error("Error loading Mercado Pago script:",e)},document.head.appendChild(e)}catch(e){console.error("Error attempting to inject Mercado Pago script:",e)}}(),this._hasCardOnFileKeys()&&(yield this._initializeCardOnFile())}))}_checkout(e){return t(this,void 0,void 0,(function*(){throw new Error("The #checkout method should be implement in child classes.")}))}_setCartTotal(e){throw new Error("The #setCartTotal method should be implement in child classes.")}_getCustomer(e=null){return t(this,void 0,void 0,(function*(){return r(this,J,"f")||o(this,J,yield function(e,r,o,i=null){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/customer/`,s={email:o.email,first_name:null==o?void 0:o.firstName,last_name:null==o?void 0:o.lastName,phone:null==o?void 0:o.phone},a=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},signal:i,body:JSON.stringify(s)});if(a.ok)return yield a.json();throw yield C({response:a,errorCode:n.CUSTOMER_OPERATION_ERROR})}))}(this.baseUrl,this.apiKeyTonder,this.customer,e),"f"),r(this,J,"f")}))}_handleCheckout({card:e,payment_method:o,customer:i,isSandbox:s,enable_card_on_file:a,returnUrl:d}){return t(this,void 0,void 0,(function*(){const{openpay_keys:l,reference:u,business:h}=this.merchantData,E=Number(this.cartTotal);let _,m,R;try{let p;!p&&l.merchant_id&&l.public_key&&!o&&(p=yield M(l.merchant_id,l.public_key,s,this.abortController.signal));const{id:y,auth_token:v}=i;_={business:this.apiKeyTonder,client:v,billing_address_id:null,shipping_address_id:null,amount:E,status:"A",reference:u,is_oneclick:!0,items:this.cartItems,currency:this.currency,metadata:this.metadata};const A=yield function(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/orders/`,i=o,s=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(i)});if(s.ok)return yield s.json();throw yield C({response:s,errorCode:n.CREATE_ORDER_ERROR})}))}(this.baseUrl,this.apiKeyTonder,_),f=(new Date).toISOString();m={business_pk:h.pk,client_id:y,amount:E,date:f,order_id:A.id,customer_order_reference:this.order_reference?this.order_reference:u,items:this.cartItems,currency:this.currency,metadata:this.metadata};const O=yield function(e,r,o){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${o.business_pk}/payments/`,i=o,s=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${r}`},body:JSON.stringify(i)});if(s.ok)return yield s.json();throw yield C({response:s,errorCode:n.CREATE_PAYMENT_ERROR})}))}(this.baseUrl,this.apiKeyTonder,m);R=Object.assign(Object.assign(Object.assign(Object.assign({name:F(this.customer,"firstName",F(this.customer,"name","")),last_name:F(this.customer,"lastName",F(this.customer,"lastname","")),email_client:F(this.customer,"email",""),phone_number:F(this.customer,"phone",""),return_url:d||this.returnUrl,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:E,title_ship:"shipping",description:"transaction",device_session_id:p||null,token_id:"",order_id:A.id,business_id:h.pk,payment_id:O.pk,source:"sdk",items:this.cartItems,metadata:this.metadata,browser_info:c(),currency:this.currency},o?{payment_method:o}:{card:e}),{apm_config:r(this,W,"f")}),this.customer&&"identification"in this.customer?{identification:this.customer.identification}:{}),void 0!==a?{enable_card_on_file:a}:{});const T=yield D(this.baseUrl,this.apiKeyTonder,R);return T||!1}catch(e){throw this.reportSdkError(e,{feature:"payment",process_id:null==R?void 0:R.payment_id,metadata:{step:"_handleCheckout",orderItems:_,paymentItems:m,routerItems:R}}),e}}))}_fetchMerchantData(){return t(this,void 0,void 0,(function*(){try{return this.merchantData||(this.merchantData=yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)),this.merchantData}catch(e){return this.reportSdkError(e,{feature:"fetch-merchant-data",metadata:{step:"_fetchMerchantData"}}),this.merchantData}}))}_getCustomerCards(e,r){return t(this,void 0,void 0,(function*(){return yield function(e,r,o,i,s=null){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${i}/cards/`,a=yield fetch(t,{method:"GET",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r},signal:s});if(a.ok)return yield a.json();if(401===a.status)return{user_id:0,cards:[]};throw yield C({response:a,errorCode:n.FETCH_CARDS_ERROR})}))}(this.baseUrl,e,this.secureToken,r)}))}_saveCustomerCard(e,r,o,i=!1){return t(this,void 0,void 0,(function*(){return yield function(e,r,o,i,s,a=!1){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${i}/cards/`,d=yield fetch(t,{method:"POST",headers:Object.assign({Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r},a?{"X-App-Origin":"sdk/ionic"}:{}),body:JSON.stringify(s)});if(d.ok)return yield d.json();throw yield C({response:d,errorCode:n.SAVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,r,o,i)}))}_removeCustomerCard(e,r,o){return t(this,void 0,void 0,(function*(){return yield function(e,r,o,i="",a){return t(this,void 0,void 0,(function*(){const t=`${e}/api/v1/business/${a}/cards/${i}`,d=yield fetch(t,{method:"DELETE",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","User-token":r}});if(204===d.status)return s[n.CARD_REMOVED_SUCCESSFULLY];if(d.ok&&"json"in d)return yield d.json();throw yield C({response:d,errorCode:n.REMOVE_CARD_ERROR})}))}(this.baseUrl,e,this.secureToken,o,r)}))}_fetchCustomerPaymentMethods(){return t(this,void 0,void 0,(function*(){return yield function(e,r,o={status:"active",pagesize:"10000"},i=null){return t(this,void 0,void 0,(function*(){const t=new URLSearchParams(o).toString(),s=yield fetch(`${e}/api/v1/payment_methods?${t}`,{method:"GET",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:i});if(s.ok)return yield s.json();throw yield C({response:s,errorCode:n.FETCH_PAYMENT_METHODS_ERROR})}))}(this.baseUrl,this.apiKeyTonder)}))}_hasCardOnFileKeys(){var e,t;return!!(null===(t=null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys)||void 0===t?void 0:t.public_key)}_initializeCardOnFile(){var e;return t(this,void 0,void 0,(function*(){return this.cardOnFileInstance||(this.cardOnFileInstance=new z({merchantId:null===(e=this.merchantData)||void 0===e?void 0:e.cardonfile_keys.public_key,apiKey:this.apiKeyTonder,isTestEnvironment:"production"!==this.mode}),yield this.cardOnFileInstance.initialize()),this.cardOnFileInstance}))}_handle3dsRedirect(e){var r,o;return t(this,void 0,void 0,(function*(){if(e&&"next_action"in e?null===(o=null===(r=null==e?void 0:e.next_action)||void 0===r?void 0:r.iframe_resources)||void 0===o?void 0:o.iframe:null)this.process3ds.loadIframe().then((()=>{this.process3ds.verifyTransactionStatus()})).catch((t=>{console.log("Error loading iframe:",t),this.reportSdkError(t,{feature:"3ds-verification",metadata:{step:"_handle3dsRedirect",response:e}})}));else{if(!this.process3ds.getRedirectUrl())return e;this.process3ds.redirectToChallenge()}}))}}function le(e,r,o=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/v1/vault-token/`,{method:"GET",headers:{Authorization:`Token ${r}`},signal:o});if(t.ok){return(yield t.json()).token}throw yield C({response:t,errorCode:n.VAULT_TOKEN_ERROR})}))}W=new WeakMap,J=new WeakMap,Q=new WeakSet,G=function(e){var t,o;!e||e&&0===Object.keys(e).length||(r(this,Q,"m",Z).call(this,e.customer),this._setCartTotal((null===(t=e.cart)||void 0===t?void 0:t.total)||0),r(this,Q,"m",te).call(this,(null===(o=e.cart)||void 0===o?void 0:o.items)||[]),r(this,Q,"m",re).call(this,e),r(this,Q,"m",oe).call(this,e),r(this,Q,"m",ie).call(this,e),r(this,Q,"m",se).call(this,e))},Z=function(e){e&&(this.customer=e)},ee=function(e){if("string"!=typeof(t=e)||!/^[\x21-\x7E]+$/.test(t))throw C({errorCode:n.SECURE_TOKEN_INVALID,statusCode:400});var t;this.secureToken=e},te=function(e){this.cartItems=e},re=function(e){this.metadata=null==e?void 0:e.metadata,this.order_reference=null==e?void 0:e.order_reference},oe=function(e){this.currency=null==e?void 0:e.currency},ie=function(e){this.card=null==e?void 0:e.card},ne=function(e){var r,o,i,n,s;return t(this,void 0,void 0,(function*(){if("Hard"===(null===(r=null==e?void 0:e.decline)||void 0===r?void 0:r.error_type)||(null===(o=null==e?void 0:e.checkout)||void 0===o?void 0:o.is_route_finished)||(null==e?void 0:e.is_route_finished)||["Pending"].includes(null==e?void 0:e.transaction_status))return e;if(["Success","Authorized"].includes(null==e?void 0:e.transaction_status))return e;if(e){const t={checkout_id:(null===(i=e.checkout)||void 0===i?void 0:i.id)||(null==e?void 0:e.checkout_id)};try{return yield D(this.baseUrl,this.apiKeyTonder,t)}catch(t){this.reportSdkError(t,{feature:"payment",process_id:(null==e?void 0:e.payment_id)||(null===(n=null==e?void 0:e.payment)||void 0===n?void 0:n.id)||(null===(s=null==e?void 0:e.payment)||void 0===s?void 0:s.pk),metadata:{step:"#resumeCheckout",response:e}})}return e}}))},se=function(e){o(this,W,null==e?void 0:e.apm_config,"f")},function(e){e.CARD_NUMBER="card_number",e.CVV="cvv",e.EXPIRATION_MONTH="expiration_month",e.EXPIRATION_YEAR="expiration_year",e.CARDHOLDER_NAME="cardholder_name"}(ae||(ae={}));const ce={type:e.ValidationRuleType.LENGTH_MATCH_RULE,params:{max:70}},ue=RegExp("^(?!s*$).+"),he={type:e.ValidationRuleType.REGEX_MATCH_RULE,params:{regex:ue,error:"El campo es requerido"}},Ee="Titular de la tarjeta",_e="Número de tarjeta",me="CVC/CVV",Re="Mes",pe="Año",ye="Fecha de expiración",ve="Nombre como aparece en la tarjeta",Ce="1234 1234 1234 1234",Ae="3-4 dígitos",fe="MM",Oe="AA",Te={base:{border:"1px solid #e0e0e0",padding:"10px 7px",borderRadius:"5px",color:"#1d1d1d",marginTop:"2px",backgroundColor:"white",fontFamily:'"Inter", sans-serif',fontSize:"16px","&::placeholder":{color:"#ccc"}},complete:{color:"#4caf50"},invalid:{border:"1px solid #f44336"},empty:{},focus:{},global:{"@import":'url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;700&display=swap")'}},Se={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif'}},Ie={base:{fontSize:"12px",fontWeight:"500",fontFamily:'"Inter", sans-serif',color:"#f44336"}};function ge({baseUrl:r,apiKey:o,vault_id:i,vault_url:s,data:a}){return t(this,void 0,void 0,(function*(){const d=e.init({vaultID:i,vaultURL:s,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield le(r,o)})),options:{logLevel:e.LogLevel.ERROR,env:e.Env.DEV}}).container(e.ContainerType.COLLECT),l=yield function(r,o){return t(this,void 0,void 0,(function*(){const i=yield function(r,o){return t(this,void 0,void 0,(function*(){return yield Promise.all(Object.keys(r).map((r=>t(this,void 0,void 0,(function*(){return{element:yield o.create({table:"cards",column:r,type:e.ElementType.INPUT_FIELD}),key:r}})))))}))}(r,o);return i?i.map((e=>new Promise((t=>{var o;const i=document.createElement("div");i.hidden=!0,i.id=`id-${e.key}`,null===(o=document.querySelector("body"))||void 0===o||o.appendChild(i),setTimeout((()=>{e.element.mount(`#id-${e.key}`),setInterval((()=>{if(e.element.isMounted()){const o=r[e.key];return e.element.setValue(o),t(e.element.isMounted())}}),120)}),120)})))):[]}))}(a,d);if((yield Promise.all(l)).some((e=>!e)))throw C({errorCode:n.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}});try{const e=yield d.collect();if(e)return e.records[0].fields;throw C({errorCode:n.SAVE_CARD_PROCESS_ERROR,details:{step:"get_skyflow_tokens"}})}catch(e){throw C({errorCode:n.SAVE_CARD_PROCESS_ERROR},e)}}))}function Ne(t){const{element:r,fieldMessage:o="",errorStyles:i={},requiredMessage:n="Campo requerido",invalidMessage:s="Campo no válido",events:a}=t;"on"in r&&(r.on(e.EventName.CHANGE,(e=>{De({eventName:"onChange",data:e,events:a}),be({element:r,errorStyles:i,color:"transparent"})})),r.on(e.EventName.BLUR,(e=>{if(De({eventName:"onBlur",data:e,events:a}),!e.isValid){const t=e.isEmpty?n:""!=o?`El campo ${o} no es válido`:s;r.setError(t)}be({element:r,errorStyles:i})})),r.on(e.EventName.FOCUS,(e=>{De({eventName:"onFocus",data:e,events:a}),be({element:r,errorStyles:i,color:"transparent"}),r.resetError()})))}function be(e){const{element:t,errorStyles:r={},color:o=""}=e;Object.keys(r).length>0&&t.update({errorTextStyles:Object.assign(Object.assign({},r),{base:Object.assign(Object.assign({},r.base&&Object.assign({},r.base)),""!=o&&{color:o})})})}const De=e=>{const{eventName:t,data:r,events:o}=e;if(o&&t in o){const e=o[t];"function"==typeof e&&e({elementType:F(r,"elementType",""),isEmpty:F(r,"isEmpty",!1),isFocused:F(r,"isFocused",!1),isValid:F(r,"isValid",!1),value:F(r,"value","")})}};function Me(e){return t(this,void 0,void 0,(function*(){const{element:t,containerId:r,retries:o=2,delay:i=30}=e;for(let e=0;e<=o;e++){if(document.querySelector(r))return void t.mount(r);e<o&&(yield new Promise((e=>setTimeout(e,i))))}console.warn(`[mountCardFields] Container ${r} was not found after ${o+1} attempts`)}))}const ke=Object.freeze({SORIANA:"SORIANA",OXXO:"OXXO",OXXOPAY:"OXXOPAY",SPEI:"SPEI",CODI:"CODI",MERCADOPAGO:"MERCADOPAGO",PAYPAL:"PAYPAL",COMERCIALMEXICANA:"COMERCIALMEXICANA",BANCOMER:"BANCOMER",WALMART:"WALMART",BODEGA:"BODEGA",SAMSCLUB:"SAMSCLUB",SUPERAMA:"SUPERAMA",CALIMAX:"CALIMAX",EXTRA:"EXTRA",CIRCULOK:"CIRCULOK",SEVEN11:"7ELEVEN",TELECOMM:"TELECOMM",BANORTE:"BANORTE",BENAVIDES:"BENAVIDES",DELAHORRO:"DELAHORRO",ELASTURIANO:"ELASTURIANO",WALDOS:"WALDOS",ALSUPER:"ALSUPER",KIOSKO:"KIOSKO",STAMARIA:"STAMARIA",LAMASBARATA:"LAMASBARATA",FARMROMA:"FARMROMA",FARMUNION:"FARMUNION",FARMATODO:"FARMATODO",SFDEASIS:"SFDEASIS",FARM911:"FARM911",FARMECONOMICAS:"FARMECONOMICAS",FARMMEDICITY:"FARMMEDICITY",RIANXEIRA:"RIANXEIRA",WESTERNUNION:"WESTERNUNION",ZONAPAGO:"ZONAPAGO",CAJALOSANDES:"CAJALOSANDES",CAJAPAITA:"CAJAPAITA",CAJASANTA:"CAJASANTA",CAJASULLANA:"CAJASULLANA",CAJATRUJILLO:"CAJATRUJILLO",EDPYME:"EDPYME",KASNET:"KASNET",NORANDINO:"NORANDINO",QAPAQ:"QAPAQ",RAIZ:"RAIZ",PAYSER:"PAYSER",WUNION:"WUNION",BANCOCONTINENTAL:"BANCOCONTINENTAL",GMONEY:"GMONEY",GOPAY:"GOPAY",WU:"WU",PUNTOSHEY:"PUNTOSHEY",AMPM:"AMPM",JUMBOMARKET:"JUMBOMARKET",SMELPUEBLO:"SMELPUEBLO",BAM:"BAM",REFACIL:"REFACIL",ACYVALORES:"ACYVALORES"}),Pe={[ke.SORIANA]:{label:"Soriana",iconPath:"/payment_methods/soriana.png"},[ke.OXXO]:{label:"Oxxo",iconPath:"/payment_methods/oxxo.png"},[ke.CODI]:{label:"CoDi",iconPath:"/payment_methods/codi.png"},[ke.MERCADOPAGO]:{label:"Mercado Pago",iconPath:"/payment_methods/mercadopago.png"},[ke.OXXOPAY]:{label:"Oxxo Pay",iconPath:"/payment_methods/oxxopay.png"},[ke.SPEI]:{label:"SPEI",iconPath:"/payment_methods/spei.png"},[ke.PAYPAL]:{label:"Paypal",iconPath:"/payment_methods/paypal.png"},[ke.COMERCIALMEXICANA]:{label:"Comercial Mexicana",iconPath:"/payment_methods/comercial_exicana.png"},[ke.BANCOMER]:{label:"Bancomer",iconPath:"/payment_methods/bancomer.png"},[ke.WALMART]:{label:"Walmart",iconPath:"/payment_methods/walmart.png"},[ke.BODEGA]:{label:"Bodega Aurrera",iconPath:"/payment_methods/bodega_aurrera.png"},[ke.SAMSCLUB]:{label:"Sam´s Club",iconPath:"/payment_methods/sams_club.png"},[ke.SUPERAMA]:{label:"Superama",iconPath:"/payment_methods/superama.png"},[ke.CALIMAX]:{label:"Calimax",iconPath:"/payment_methods/calimax.png"},[ke.EXTRA]:{label:"Tiendas Extra",iconPath:"/payment_methods/tiendas_extra.png"},[ke.CIRCULOK]:{label:"Círculo K",iconPath:"/payment_methods/circulo_k.png"},[ke.SEVEN11]:{label:"7 Eleven",iconPath:"/payment_methods/7_eleven.png"},[ke.TELECOMM]:{label:"Telecomm",iconPath:"/payment_methods/telecomm.png"},[ke.BANORTE]:{label:"Banorte",iconPath:"/payment_methods/banorte.png"},[ke.BENAVIDES]:{label:"Farmacias Benavides",iconPath:"/payment_methods/farmacias_benavides.png"},[ke.DELAHORRO]:{label:"Farmacias del Ahorro",iconPath:"/payment_methods/farmacias_ahorro.png"},[ke.ELASTURIANO]:{label:"El Asturiano",iconPath:"/payment_methods/asturiano.png"},[ke.WALDOS]:{label:"Waldos",iconPath:"/payment_methods/waldos.png"},[ke.ALSUPER]:{label:"Alsuper",iconPath:"/payment_methods/al_super.png"},[ke.KIOSKO]:{label:"Kiosko",iconPath:"/payment_methods/kiosko.png"},[ke.STAMARIA]:{label:"Farmacias Santa María",iconPath:"/payment_methods/farmacias_santa_maria.png"},[ke.LAMASBARATA]:{label:"Farmacias la más barata",iconPath:"/payment_methods/farmacias_barata.png"},[ke.FARMROMA]:{label:"Farmacias Roma",iconPath:"/payment_methods/farmacias_roma.png"},[ke.FARMUNION]:{label:"Pago en Farmacias Unión",iconPath:"/payment_methods/farmacias_union.png"},[ke.FARMATODO]:{label:"Pago en Farmacias Farmatodo",iconPath:"/payment_methods/farmacias_farmatodo.png\t"},[ke.SFDEASIS]:{label:"Pago en Farmacias San Francisco de Asís",iconPath:"/payment_methods/farmacias_san_francisco.png"},[ke.FARM911]:{label:"Farmacias 911",iconPath:"/payment_methods/store.png"},[ke.FARMECONOMICAS]:{label:"Farmacias Economicas",iconPath:"/payment_methods/store.png"},[ke.FARMMEDICITY]:{label:"Farmacias Medicity",iconPath:"/payment_methods/store.png"},[ke.RIANXEIRA]:{label:"Rianxeira",iconPath:"/payment_methods/store.png"},[ke.WESTERNUNION]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[ke.ZONAPAGO]:{label:"Zona Pago",iconPath:"/payment_methods/store.png"},[ke.CAJALOSANDES]:{label:"Caja Los Andes",iconPath:"/payment_methods/store.png"},[ke.CAJAPAITA]:{label:"Caja Paita",iconPath:"/payment_methods/store.png"},[ke.CAJASANTA]:{label:"Caja Santa",iconPath:"/payment_methods/store.png"},[ke.CAJASULLANA]:{label:"Caja Sullana",iconPath:"/payment_methods/store.png"},[ke.CAJATRUJILLO]:{label:"Caja Trujillo",iconPath:"/payment_methods/store.png"},[ke.EDPYME]:{label:"Edpyme",iconPath:"/payment_methods/store.png"},[ke.KASNET]:{label:"KasNet",iconPath:"/payment_methods/store.png"},[ke.NORANDINO]:{label:"Norandino",iconPath:"/payment_methods/store.png"},[ke.QAPAQ]:{label:"Qapaq",iconPath:"/payment_methods/store.png"},[ke.RAIZ]:{label:"Raiz",iconPath:"/payment_methods/store.png"},[ke.PAYSER]:{label:"Paysera",iconPath:"/payment_methods/store.png"},[ke.WUNION]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[ke.BANCOCONTINENTAL]:{label:"Banco Continental",iconPath:"/payment_methods/store.png"},[ke.GMONEY]:{label:"Go money",iconPath:"/payment_methods/store.png"},[ke.GOPAY]:{label:"Go pay",iconPath:"/payment_methods/store.png"},[ke.WU]:{label:"Western Union",iconPath:"/payment_methods/store.png"},[ke.PUNTOSHEY]:{label:"Puntoshey",iconPath:"/payment_methods/store.png"},[ke.AMPM]:{label:"Ampm",iconPath:"/payment_methods/store.png"},[ke.JUMBOMARKET]:{label:"Jumbomarket",iconPath:"/payment_methods/store.png"},[ke.SMELPUEBLO]:{label:"Smelpueblo",iconPath:"/payment_methods/store.png"},[ke.BAM]:{label:"Bam",iconPath:"/payment_methods/store.png"},[ke.REFACIL]:{label:"Refacil",iconPath:"/payment_methods/store.png"},[ke.ACYVALORES]:{label:"Acyvalores",iconPath:"/payment_methods/store.png"}},Ue=(e,t="stage")=>{const r=e.toUpperCase().trim().replace(/\s+/g,"");const o=Pe[r]||{iconPath:"/payment_methods/store.png",label:""};return{label:o.label,icon:`${l(t)}${o.iconPath}`}};class Le extends de{constructor({apiKey:e,mode:t,returnUrl:r,callBack:o,apiKeyTonder:i,baseUrlTonder:n,customization:s,collectorIds:a,events:d}){super({mode:t,apiKey:e,returnUrl:r,callBack:o,apiKeyTonder:i,baseUrlTonder:n,customization:s,tdsIframeId:a&&"tdsIframe"in a?null==a?void 0:a.tdsIframe:"tdsIframe",sdkInfo:X}),this.activeAPMs=[],this.mountedElementsByContext=new Map,this.customerCardsCache=null,this.lastCollectedTokens=null,this.skyflowInstance=null,this.events=d||{}}injectCheckout(){return t(this,void 0,void 0,(function*(){yield this._initializeCheckout()}))}getCustomerCards(){return t(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:e}=yield this._getCustomer(),t=yield this._getCustomerCards(e,this.merchantData.business.pk);return this.customerCardsCache=t,Object.assign(Object.assign({},t),{cards:t.cards.map((e=>Object.assign(Object.assign({},e),{fields:Object.assign(Object.assign({},e.fields),{subscription_id:this._hasCardOnFileKeys()?e.fields.subscription_id:void 0}),icon:h(e.fields.card_scheme,this.mode)})))})}catch(e){throw this.reportSdkError(e,{feature:"get-cards",process_id:this.getCustomerId(),metadata:{step:"getCustomerCards"}}),C({errorCode:n.FETCH_CARDS_ERROR},e)}}))}saveCustomerCard(){return t(this,void 0,void 0,(function*(){let e=null;try{yield this._fetchMerchantData();const t=yield this._getCustomer(),{auth_token:r,first_name:o="",last_name:i="",email:s=""}=t,{business:a}=this.merchantData,d=this._hasCardOnFileKeys(),l=yield this.collectCreateCardTokens(),c=yield this._saveCustomerCard(r,null==a?void 0:a.pk,l,d);if(e=c.skyflow_id,d){const e=c.card_bin;if(!e)throw new Error("Card BIN not returned from save card");const t=yield this._initializeCardOnFile();let d;try{d=yield t.process({cardTokens:{name:l.cardholder_name,number:l.card_number,expiryMonth:l.expiration_month,expiryYear:l.expiration_year,cvv:l.cvv},cardBin:e,contactDetails:{firstName:o||"",lastName:i||"",email:s||""},customerId:r,currency:this.currency||"MXN"})}catch(e){throw C({errorCode:n.CARD_ON_FILE_DECLINED,lockErrorCode:!0},e)}const u={skyflow_id:l.skyflow_id,subscription_id:d.subscriptionId};yield this._saveCustomerCard(r,null==a?void 0:a.pk,u)}return c}catch(t){throw e&&(yield this.removeCustomerCard(e)),this.reportSdkError(t,{feature:"save-card",process_id:e||this.getCustomerId(),metadata:{step:"saveCustomerCard"}}),C({errorCode:n.SAVE_CARD_ERROR},t)}}))}removeCustomerCard(e){return t(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const{auth_token:t}=yield this._getCustomer(),{business:r}=this.merchantData;return yield this._removeCustomerCard(t,null==r?void 0:r.pk,e)}catch(t){throw this.reportSdkError(t,{feature:"remove-card",process_id:e,metadata:{step:"removeCustomerCard"}}),C({errorCode:n.REMOVE_CARD_ERROR},t)}}))}getCustomerPaymentMethods(){return t(this,void 0,void 0,(function*(){try{const e=yield this._fetchCustomerPaymentMethods();return(e&&"results"in e&&e.results.length>0?e.results:[]).filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},Ue(e.payment_method,this.mode)))).sort(((e,t)=>e.priority-t.priority))}catch(e){throw this.reportSdkError(e,{feature:"get-payment-methods",metadata:{step:"getCustomerPaymentMethods"}}),C({errorCode:n.FETCH_PAYMENT_METHODS_ERROR},e)}}))}mountCardFields(r){var o;return t(this,void 0,void 0,(function*(){const i=r.card_id?`update:${r.card_id}`:"create",n=null!==(o=r.unmount_context)&&void 0!==o?o:"all";"none"!==n&&("current"===n?this.unmountCardFields(i):this.unmountCardFields(n)),yield this.createSkyflowInstance();const s=yield function(r){var o,i,n,s,a,d,l,c,u,h,E,_,m;return t(this,void 0,void 0,(function*(){const{skyflowInstance:t,data:R,customization:p,events:y}=r,v=t.container(e.ContainerType.COLLECT),C=[],A={[ae.CVV]:e.ElementType.CVV,[ae.CARD_NUMBER]:e.ElementType.CARD_NUMBER,[ae.EXPIRATION_MONTH]:e.ElementType.EXPIRATION_MONTH,[ae.EXPIRATION_YEAR]:e.ElementType.EXPIRATION_YEAR,[ae.CARDHOLDER_NAME]:e.ElementType.CARDHOLDER_NAME},f={[ae.CVV]:[he],[ae.CARD_NUMBER]:[he],[ae.EXPIRATION_MONTH]:[he],[ae.EXPIRATION_YEAR]:[he],[ae.CARDHOLDER_NAME]:[ce,he]},O={[ae.CARDHOLDER_NAME]:"cardholderName",[ae.CARD_NUMBER]:"cardNumber",[ae.CVV]:"cvv",[ae.EXPIRATION_MONTH]:"expirationMonth",[ae.EXPIRATION_YEAR]:"expirationYear"},T=e=>{var t,r,o,i,n,s,a,d,l;const c=null===(t=null==p?void 0:p.styles)||void 0===t?void 0:t[O[e]],u=null===(r=null==p?void 0:p.styles)||void 0===r?void 0:r.cardForm,h=null!==(i=null!==(o=null==c?void 0:c.inputStyles)&&void 0!==o?o:null==u?void 0:u.inputStyles)&&void 0!==i?i:Te;return{inputStyles:e===ae.CARD_NUMBER&&!1!==(null===(n=null==p?void 0:p.styles)||void 0===n?void 0:n.enableCardIcon)?Object.assign(Object.assign({},h),{base:Object.assign({paddingLeft:"15px"},null==h?void 0:h.base)}):h,labelStyles:null!==(a=null!==(s=null==c?void 0:c.labelStyles)&&void 0!==s?s:null==u?void 0:u.labelStyles)&&void 0!==a?a:Se,errorStyles:null!==(l=null!==(d=null==c?void 0:c.errorStyles)&&void 0!==d?d:null==u?void 0:u.errorStyles)&&void 0!==l?l:Ie}},S={cardholder_name:(null===(o=null==p?void 0:p.labels)||void 0===o?void 0:o.name)||Ee,card_number:(null===(i=null==p?void 0:p.labels)||void 0===i?void 0:i.card_number)||_e,cvv:(null===(n=null==p?void 0:p.labels)||void 0===n?void 0:n.cvv)||me,expiration_date:(null===(s=null==p?void 0:p.labels)||void 0===s?void 0:s.expiry_date)||ye,expiration_month:(null===(a=null==p?void 0:p.labels)||void 0===a?void 0:a.expiration_month)||Re,expiration_year:(null===(d=null==p?void 0:p.labels)||void 0===d?void 0:d.expiration_year)||pe},I={cardholder_name:(null===(l=null==p?void 0:p.placeholders)||void 0===l?void 0:l.name)||ve,card_number:(null===(c=null==p?void 0:p.placeholders)||void 0===c?void 0:c.card_number)||Ce,cvv:(null===(u=null==p?void 0:p.placeholders)||void 0===u?void 0:u.cvv)||Ae,expiration_month:(null===(h=null==p?void 0:p.placeholders)||void 0===h?void 0:h.expiration_month)||fe,expiration_year:(null===(E=null==p?void 0:p.placeholders)||void 0===E?void 0:E.expiration_year)||Oe},g={[ae.CVV]:null==y?void 0:y.cvvEvents,[ae.CARD_NUMBER]:null==y?void 0:y.cardNumberEvents,[ae.EXPIRATION_MONTH]:null==y?void 0:y.monthEvents,[ae.EXPIRATION_YEAR]:null==y?void 0:y.yearEvents,[ae.CARDHOLDER_NAME]:null==y?void 0:y.cardHolderEvents};if("fields"in R&&Array.isArray(R.fields)){const e={enableCardIcon:null===(m=null===(_=null==p?void 0:p.styles)||void 0===_?void 0:_.enableCardIcon)||void 0===m||m};if(R.fields.length>0&&"string"==typeof R.fields[0])for(const t of R.fields){const r=v.create(Object.assign(Object.assign(Object.assign({table:"cards",column:t,type:A[t],validations:f[t]},T(t)),{label:S[t],placeholder:I[t]}),R.card_id?{skyflowID:R.card_id}:{}),t===ae.CARD_NUMBER?e:void 0);Ne({element:r,errorStyles:T(t).errorStyles,fieldMessage:[ae.CVV,ae.EXPIRATION_MONTH,ae.EXPIRATION_YEAR].includes(t)?"":S[t],events:g[t]});const o=`#collect_${String(t)}`+(R.card_id?`_${R.card_id}`:"");yield Me({element:r,containerId:o}),C.push({element:r,containerId:o})}else for(const t of R.fields){const r=t.field,o=v.create(Object.assign(Object.assign(Object.assign({table:"cards",column:r,type:A[r],validations:f[r]},T(r)),{label:S[r],placeholder:I[r]}),R.card_id?{skyflowID:R.card_id}:{}),r===ae.CARD_NUMBER?e:void 0);Ne({element:o,errorStyles:T(r).errorStyles,fieldMessage:[ae.CVV,ae.EXPIRATION_MONTH,ae.EXPIRATION_YEAR].includes(r)?"":S[r],events:g[r]});const i=t.container_id||`#collect_${String(r)}`+(R.card_id?`_${R.card_id}`:"");yield Me({element:o,containerId:i}),C.push({element:o,containerId:i})}}return{elements:C.map((e=>e.element)),container:v}}))}({skyflowInstance:this.skyflowInstance,data:r,customization:this.customization,events:this.events});this.mountedElementsByContext.set(i,{elements:s.elements||[],container:s})}))}getContainerByCardId(e){var t;const r=`update:${e}`,o=this.mountedElementsByContext.get(r);return(null===(t=null==o?void 0:o.container)||void 0===t?void 0:t.container)||null}collectCardTokens(e){var r,o,i;return t(this,void 0,void 0,(function*(){const t=this.getContainerByCardId(e);if(!t)return null;try{const e=yield t.collect();return(null===(o=null===(r=null==e?void 0:e.records)||void 0===r?void 0:r[0])||void 0===o?void 0:o.fields)||null}catch(t){const r=null===(i=null==t?void 0:t.error)||void 0===i?void 0:i.description;throw this.reportSdkError(t,{feature:"collect-card-tokens",process_id:e,metadata:{step:"collectCardTokens"}}),new a({code:n.MOUNT_COLLECT_ERROR,details:{message:r}})}}))}collectCreateCardTokens(){var e,r,o,i;return t(this,void 0,void 0,(function*(){const t=this.mountedElementsByContext.get("create"),s=null===(e=null==t?void 0:t.container)||void 0===e?void 0:e.container;if(!s)throw new a({code:n.MOUNT_COLLECT_ERROR,details:{message:"No card fields are mounted. Call mountCardFields() with the required fields before proceeding."}});try{const e=yield s.collect(),t=(null===(o=null===(r=null==e?void 0:e.records)||void 0===r?void 0:r[0])||void 0===o?void 0:o.fields)||{};return this.lastCollectedTokens=t,t}catch(e){const t=null===(i=null==e?void 0:e.error)||void 0===i?void 0:i.description;throw this.reportSdkError(e,{feature:"collect-create-card-tokens",metadata:{step:"collectCreateCardTokens"}}),new a({code:n.MOUNT_COLLECT_ERROR,details:{message:t}})}}))}revealCardFields(r){return t(this,void 0,void 0,(function*(){if(!this.lastCollectedTokens)throw C({errorCode:n.MOUNT_COLLECT_ERROR,details:{message:"No card tokens available. Call saveCustomerCard() or payment() with a new card before calling revealCardFields()."}});if(!this.skyflowInstance)throw C({errorCode:n.MOUNT_COLLECT_ERROR,details:{message:"Skyflow instance not initialized. Ensure mountCardFields() was called before saveCustomerCard() or payment()."}});yield function(r){var o,i,n,s,a,d;return t(this,void 0,void 0,(function*(){const{skyflowInstance:t,tokens:l,request:c}=r,u=t.container(e.ContainerType.REVEAL),h={[ae.CARD_NUMBER]:"MASKED",[ae.CARDHOLDER_NAME]:"PLAIN_TEXT",[ae.EXPIRATION_MONTH]:"PLAIN_TEXT",[ae.EXPIRATION_YEAR]:"PLAIN_TEXT"};for(const t of c.fields){const r="string"==typeof t,E=r?t:t.field;if(E===ae.CVV){console.warn("[revealCardFields] CVV cannot be revealed (PCI DSS req. 3.2.1). Skipping.");continue}const _=l[E];if(!_){console.warn(`[revealCardFields] No token found for field "${E}", skipping.`);continue}const m=r?{}:t,R=null!==(o=m.container_id)&&void 0!==o?o:`#reveal_${E}`,p=h[E],y=null!==(i=m.styles)&&void 0!==i?i:{},v=null!==(n=c.styles)&&void 0!==n?n:{},C=u.create(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({token:_,redaction:e.RedactionType[p]},void 0!==m.altText&&{altText:m.altText}),void 0!==m.label&&{label:m.label}),y.inputStyles||v.inputStyles?{inputStyles:null!==(s=y.inputStyles)&&void 0!==s?s:v.inputStyles}:{}),y.labelStyles||v.labelStyles?{labelStyles:null!==(a=y.labelStyles)&&void 0!==a?a:v.labelStyles}:{}),y.errorTextStyles||v.errorTextStyles?{errorTextStyles:null!==(d=y.errorTextStyles)&&void 0!==d?d:v.errorTextStyles}:{}));yield Me({element:C,containerId:R})}try{yield u.reveal()}catch(e){console.warn("[revealCardFields] reveal completed with errors:",e)}}))}({skyflowInstance:this.skyflowInstance,tokens:this.lastCollectedTokens,request:r})}))}unmountCardFields(e="all"){"all"===e?(this.mountedElementsByContext.forEach(((e,t)=>{this.unmountContext(t)})),this.mountedElementsByContext.clear()):(this.unmountContext(e),this.mountedElementsByContext.delete(e))}unmountContext(e){const t=this.mountedElementsByContext.get(e);if(!t)return;const{elements:r}=t;r&&r.length>0&&r.forEach((t=>{try{t&&"function"==typeof t.unmount&&t.unmount()}catch(t){console.warn(`Error unmounting Skyflow element from context '${e}':`,t),this.reportSdkError(t,{feature:"unmount-card-fields",metadata:{step:"unmountContext",context:e}})}}))}getBusiness(){return t(this,void 0,void 0,(function*(){try{return yield i(this.baseUrl,this.apiKeyTonder,this.abortController.signal)}catch(e){throw this.reportSdkError(e,{feature:"get-business",metadata:{step:"getBusiness"}}),C({errorCode:n.FETCH_BUSINESS_ERROR},e)}}))}createSkyflowInstance(){return t(this,void 0,void 0,(function*(){if(this.skyflowInstance)return this.skyflowInstance;yield this._fetchMerchantData();const{vault_id:r,vault_url:o}=this.merchantData;this.skyflowInstance=yield function({baseUrl:r,apiKey:o,vault_id:i,vault_url:n,mode:s}){return t(this,void 0,void 0,(function*(){const a="production"===s?e.Env.PROD:e.Env.DEV;return e.init({vaultID:i,vaultURL:n,getBearerToken:()=>t(this,void 0,void 0,(function*(){return yield le(r,o)})),options:{logLevel:e.LogLevel.ERROR,env:a}})}))}({vault_id:r,vault_url:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder,mode:this.mode})}))}getOpenpayDeviceSessionID(e,r,o){return t(this,void 0,void 0,(function*(){try{return yield M(e,r,o)}catch(e){throw this.reportSdkError(e,{feature:"get-openpay-device-session",metadata:{step:"getOpenpayDeviceSessionID"}}),C({errorCode:n.START_CHECKOUT_ERROR},e)}}))}getSkyflowTokens({vault_id:e,vault_url:r,data:o}){return t(this,void 0,void 0,(function*(){return yield ge({vault_id:e,vault_url:r,data:o,baseUrl:this.baseUrl,apiKey:this.apiKeyTonder})}))}_setCartTotal(e){this.cartTotal=e}_checkout({card:e,payment_method:r,isSandbox:o,returnUrl:i}){var s,a;return t(this,void 0,void 0,(function*(){yield this._fetchMerchantData();const d=yield this._getCustomer(this.abortController.signal),{business:l}=this.merchantData,{auth_token:c,first_name:u="",last_name:h="",email:E=""}=d,_=this._hasCardOnFileKeys();let m,R=null,p=null,y=null,v=!1;const A=()=>t(this,void 0,void 0,(function*(){var e,t;(null===(t=null===(e=this.customerCardsCache)||void 0===e?void 0:e.cards)||void 0===t?void 0:t.length)||(this.customerCardsCache=yield this._getCustomerCards(c,this.merchantData.business.pk))}));if(!r){if("string"==typeof e)if(p=e,m={skyflow_id:e},_){yield A();const t=null===(a=null===(s=this.customerCardsCache)||void 0===s?void 0:s.cards)||void 0===a?void 0:a.find((t=>t.fields.skyflow_id===e));if(!t)throw new Error("Card not found for card-on-file processing");const r=!!t.fields.subscription_id;r||(yield this.collectCardTokens(e)),r&&(R={subscriptionId:t.fields.subscription_id})}else yield this.collectCardTokens(e);else m=yield this.collectCreateCardTokens(),p=m.skyflow_id,_&&(y={name:m.cardholder_name,number:m.card_number,expiryMonth:m.expiration_month,expiryYear:m.expiration_year,cvv:m.cvv},v=!0);if(v){if(!p||!y)throw new Error("Missing card data for card-on-file processing");let e=null;try{const t=yield this._saveCustomerCard(c,null==l?void 0:l.pk,{skyflow_id:p},!0);e=t.skyflow_id;const r=t.card_bin;if(!r)throw new Error("Card BIN not returned from save card");const o=yield this._initializeCardOnFile();let i;try{i=yield o.process({cardTokens:y,cardBin:r,contactDetails:{firstName:u||"",lastName:h||"",email:E||""},customerId:c,currency:this.currency||"MXN"})}catch(e){throw C({errorCode:n.CARD_ON_FILE_DECLINED,lockErrorCode:!0},e)}R={subscriptionId:i.subscriptionId},yield this._saveCustomerCard(c,null==l?void 0:l.pk,{skyflow_id:p,subscription_id:R.subscriptionId})}catch(t){throw e&&(yield this.removeCustomerCard(e)),this.reportSdkError(t,{feature:"payment",process_id:e||this.getCustomerId(),metadata:{step:"card_on_file"}}),t}}}return yield this._handleCheckout({card:m,payment_method:r,customer:d,isSandbox:o,returnUrl:i,enable_card_on_file:!!(null==R?void 0:R.subscriptionId)&&_})}))}customerRegister(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/customer/`,r={email:e},o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},signal:this.abortController.signal,body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield C({response:o,errorCode:n.CUSTOMER_OPERATION_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"customer-register",metadata:{step:"customerRegister"}}),C({errorCode:n.CUSTOMER_OPERATION_ERROR},e)}}))}createOrder(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/orders/`,r=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield C({response:o,errorCode:n.CREATE_ORDER_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-order",metadata:{step:"createOrder"}}),C({errorCode:n.CREATE_ORDER_ERROR},e)}}))}createPayment(e){return t(this,void 0,void 0,(function*(){try{const t=`${this.baseUrl}/api/v1/business/${e.business_pk}/payments/`,r=e,o=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Token ${this.apiKeyTonder}`},body:JSON.stringify(r)});if(o.ok)return yield o.json();throw yield C({response:o,errorCode:n.CREATE_PAYMENT_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"create-payment",metadata:{step:"createPayment"}}),C({errorCode:n.CREATE_PAYMENT_ERROR},e)}}))}startCheckoutRouter(e){return t(this,void 0,void 0,(function*(){const t=yield D(this.baseUrl,this.apiKeyTonder,e);if(yield this.init3DSRedirect(t))return t}))}init3DSRedirect(e){return t(this,void 0,void 0,(function*(){return this.process3ds.setPayload(e),yield this._handle3dsRedirect(e)}))}startCheckoutRouterFull(e){return t(this,void 0,void 0,(function*(){try{const{order:t,total:r,customer:o,skyflowTokens:i,return_url:s,isSandbox:a,metadata:d,currency:l,payment_method:u}=e,h=yield this._fetchMerchantData(),E=yield this.customerRegister(o.email);if(!(E&&"auth_token"in E&&h&&"reference"in h))throw C({errorCode:n.START_CHECKOUT_ERROR,details:{message:"Merchant or customer reposne errors",merchantResult:h,customerResult:E}});{const e={business:this.apiKeyTonder,client:E.auth_token,billing_address_id:null,shipping_address_id:null,amount:r,reference:h.reference,is_oneclick:!0,items:t.items},_=yield this.createOrder(e),m=(new Date).toISOString();if(!("id"in _&&"id"in E&&"business"in h))throw C({errorCode:n.START_CHECKOUT_ERROR,details:{message:"Order response errors",orderResult:_}});{const e={business_pk:h.business.pk,amount:r,date:m,order_id:_.id,client_id:E.id},t=yield this.createPayment(e);let n;const{openpay_keys:R,business:p}=h;R.merchant_id&&R.public_key&&(n=yield M(R.merchant_id,R.public_key,a));const y=Object.assign(Object.assign({name:o.name,last_name:o.lastname,email_client:o.email,phone_number:o.phone,return_url:s,id_product:"no_id",quantity_product:1,id_ship:"0",instance_id_ship:"0",amount:r,title_ship:"shipping",description:"transaction",device_session_id:n||null,token_id:"",order_id:"id"in _&&_.id,business_id:p.pk,payment_id:"pk"in t&&t.pk,source:"sdk",metadata:d,browser_info:c(),currency:l},u?{payment_method:u}:{card:i}),"undefined"!=typeof MP_DEVICE_SESSION_ID?{mp_device_session_id:MP_DEVICE_SESSION_ID}:{}),v=yield D(this.baseUrl,this.apiKeyTonder,y);if(yield this.init3DSRedirect(v))return v}}}catch(e){throw this.reportSdkError(e,{feature:"start-checkout-router-full",metadata:{step:"startCheckoutRouterFull"}}),C({errorCode:n.START_CHECKOUT_ERROR},e)}}))}registerCustomerCard(e,r,o){return t(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const t=yield fetch(`${this.baseUrl}/api/v1/business/${u(this.merchantData)}/cards/`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"User-token":r,"Content-Type":"application/json"},body:JSON.stringify(Object.assign({},o))});if(t.ok)return yield t.json();throw yield C({response:t,errorCode:n.SAVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"register-customer-card",metadata:{step:"registerCustomerCard"}}),C({errorCode:n.SAVE_CARD_ERROR},e)}}))}deleteCustomerCard(e,r=""){return t(this,void 0,void 0,(function*(){try{yield this._fetchMerchantData();const t=yield fetch(`${this.baseUrl}/api/v1/business/${u(this.merchantData)}/cards/${r}`,{method:"DELETE",headers:{Authorization:`Token ${e}`,"Content-Type":"application/json"},signal:this.abortController.signal});if(t.ok)return!0;throw yield C({response:t,errorCode:n.REMOVE_CARD_ERROR})}catch(e){throw this.reportSdkError(e,{feature:"delete-customer-card",process_id:r,metadata:{step:"deleteCustomerCard"}}),C({errorCode:n.REMOVE_CARD_ERROR},e)}}))}getActiveAPMs(){return t(this,void 0,void 0,(function*(){try{const e=yield function(e,r,o="?status=active&page_size=10000&country=México",i=null){return t(this,void 0,void 0,(function*(){const t=yield fetch(`${e}/api/v1/payment_methods${o}`,{method:"GET",headers:{Authorization:`Token ${r}`,"Content-Type":"application/json"},signal:i});if(t.ok)return yield t.json();throw yield C({response:t,errorCode:n.FETCH_PAYMENT_METHODS_ERROR})}))}(this.baseUrl,this.apiKeyTonder),r=e&&e.results&&e.results.length>0?e.results:[];return this.activeAPMs=r.filter((e=>"cards"!==e.category.toLowerCase())).map((e=>Object.assign({id:e.pk,payment_method:e.payment_method,priority:e.priority,category:e.category},Ue(e.payment_method,this.mode)))).sort(((e,t)=>e.priority-t.priority)),this.activeAPMs}catch(e){return console.error("Error getting APMS",e),[]}}))}}export{m as AppError,de as BaseInlineCheckout,Le as LiteCheckout,q as SdkTelemetryClient,U as validateCVV,k as validateCardNumber,P as validateCardholderName,L as validateExpirationMonth,w as validateExpirationYear};
|
package/jest.config.ts
CHANGED
|
@@ -1,8 +1,18 @@
|
|
|
1
1
|
import type { JestConfigWithTsJest } from 'ts-jest'
|
|
2
|
+
import packageJson from './package.json'
|
|
2
3
|
|
|
3
4
|
const jestConfig: JestConfigWithTsJest = {
|
|
4
5
|
testEnvironment: "jsdom",
|
|
6
|
+
// A checkout page is https in every environment that matters, and the SDK resolves
|
|
7
|
+
// relative URLs against it. jsdom defaults to http://localhost, which would make
|
|
8
|
+
// relative URLs fail the https-only scheme check for a reason production never has.
|
|
9
|
+
testEnvironmentOptions: { url: "https://localhost/" },
|
|
5
10
|
preset: 'ts-jest',
|
|
11
|
+
// Rollup's replace plugin injects these at build time; tests get the same values.
|
|
12
|
+
globals: {
|
|
13
|
+
__SDK_NAME__: packageJson.name,
|
|
14
|
+
__SDK_VERSION__: packageJson.version,
|
|
15
|
+
},
|
|
6
16
|
transform: {
|
|
7
17
|
'^.+\\.tsx?$': [
|
|
8
18
|
'ts-jest',
|
|
@@ -12,4 +22,4 @@ const jestConfig: JestConfigWithTsJest = {
|
|
|
12
22
|
},
|
|
13
23
|
}
|
|
14
24
|
|
|
15
|
-
export default jestConfig
|
|
25
|
+
export default jestConfig
|
package/package.json
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import { sanitize3dsMarkup } from "../helpers/sanitize3dsMarkup"
|
|
2
|
+
import { isHttpsUrl } from "../helpers/safeUrl"
|
|
3
|
+
import { ErrorKeyEnum } from "../shared/enum/ErrorKeyEnum"
|
|
4
|
+
import { buildPublicAppError } from "../shared/utils/appError"
|
|
5
|
+
|
|
1
6
|
type ThreeDSHandlerContructor = {
|
|
2
7
|
payload?: any,
|
|
3
8
|
apiKey?: string,
|
|
@@ -112,7 +117,13 @@ export class ThreeDSHandler {
|
|
|
112
117
|
if (iframe) {
|
|
113
118
|
this.saveVerifyTransactionUrl()
|
|
114
119
|
const container = document.createElement('div')
|
|
115
|
-
|
|
120
|
+
// The 3DS Method step is device fingerprinting, not UI: the ACS form posts
|
|
121
|
+
// itself into its target frame and nothing here is ever meant to be seen. The
|
|
122
|
+
// hiding belongs to the SDK rather than to the remote markup that asks for it,
|
|
123
|
+
// so the sanitizer is free to drop the style attribute, and a fragment that
|
|
124
|
+
// positions itself over the card fields has nothing to render into.
|
|
125
|
+
container.style.display = 'none'
|
|
126
|
+
container.appendChild(sanitize3dsMarkup(iframe))
|
|
116
127
|
document.body.appendChild(container)
|
|
117
128
|
|
|
118
129
|
// Create and append the script tag manually
|
|
@@ -143,6 +154,23 @@ export class ThreeDSHandler {
|
|
|
143
154
|
redirectToChallenge() {
|
|
144
155
|
const url = this.getRedirectUrl()
|
|
145
156
|
if (url) {
|
|
157
|
+
// The challenge URL arrives in the remote payload and reaches two sinks below:
|
|
158
|
+
// window.location and an iframe src. A javascript: URL at either one executes in
|
|
159
|
+
// the merchant's own origin, next to the card fields.
|
|
160
|
+
//
|
|
161
|
+
// Rejection throws rather than skipping the navigation: the caller turns it into
|
|
162
|
+
// a rejected payment the merchant can surface and the shopper can retry, whereas
|
|
163
|
+
// doing nothing would strand the shopper mid-challenge with no signal that the
|
|
164
|
+
// flow had stopped. The error code is locked so it survives the caller's wrapping
|
|
165
|
+
// and stays distinguishable from an ordinary payment failure.
|
|
166
|
+
if (!isHttpsUrl(url)) {
|
|
167
|
+
throw buildPublicAppError({
|
|
168
|
+
errorCode: ErrorKeyEnum.THREEDS_REDIRECTION_ERROR,
|
|
169
|
+
statusCode: 400,
|
|
170
|
+
lockErrorCode: true,
|
|
171
|
+
})
|
|
172
|
+
}
|
|
173
|
+
|
|
146
174
|
this.saveVerifyTransactionUrl()
|
|
147
175
|
if(this.redirectOnComplete) {
|
|
148
176
|
window.location = url;
|
|
@@ -11,6 +11,7 @@ import { getOpenpayDeviceSessionID } from "../data/openPayApi";
|
|
|
11
11
|
import {
|
|
12
12
|
getBrowserInfo
|
|
13
13
|
} from "../helpers/utils";
|
|
14
|
+
import { validateSecureToken } from "../helpers/validations";
|
|
14
15
|
import { registerOrFetchCustomer } from "../data/customerApi";
|
|
15
16
|
import { get } from "../helpers/get";
|
|
16
17
|
import {
|
|
@@ -504,6 +505,13 @@ export class BaseInlineCheckout<T extends CustomizationOptions = CustomizationOp
|
|
|
504
505
|
}
|
|
505
506
|
|
|
506
507
|
#setSecureToken(token: string) {
|
|
508
|
+
if (!validateSecureToken(token)) {
|
|
509
|
+
throw buildPublicAppError({
|
|
510
|
+
errorCode: ErrorKeyEnum.SECURE_TOKEN_INVALID,
|
|
511
|
+
statusCode: 400,
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
|
|
507
515
|
this.secureToken = token;
|
|
508
516
|
}
|
|
509
517
|
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scheme check shared by every sink a URL from the 3DS payload can reach: the
|
|
3
|
+
* attributes of the ACS markup and the challenge redirect.
|
|
4
|
+
*
|
|
5
|
+
* Resolution goes through the platform's URL parser rather than a prefix match. The
|
|
6
|
+
* parser strips the leading whitespace and the embedded tabs and newlines a crafted
|
|
7
|
+
* string uses to hide its scheme, and lowercases the result, so "JavaScript:" and a
|
|
8
|
+
* scheme followed by a comment that merely contains the word http are both classified
|
|
9
|
+
* on what they actually are.
|
|
10
|
+
*
|
|
11
|
+
* https only. A production ACS is always https — the card schemes require it — so
|
|
12
|
+
* allowing http would only add a downgrade path for someone on the network to serve
|
|
13
|
+
* the challenge. If a local sandbox over http is ever needed, widen this deliberately.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const ALLOWED_SCHEMES = new Set(["https:"]);
|
|
17
|
+
|
|
18
|
+
export function isHttpsUrl(value: unknown): boolean {
|
|
19
|
+
if (typeof value !== "string") return false;
|
|
20
|
+
|
|
21
|
+
try {
|
|
22
|
+
return ALLOWED_SCHEMES.has(new URL(value, document.baseURI).protocol);
|
|
23
|
+
} catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The 3DS Method step cannot be rendered as text: the ACS sends back a hidden form
|
|
3
|
+
* and the iframe it targets, and the flow submits that form by id. So the markup has
|
|
4
|
+
* to reach the DOM as markup, and the only safe handling is to strip what the step
|
|
5
|
+
* never needs — script execution, event handlers, CSS, beacons and non-https URLs —
|
|
6
|
+
* before insertion.
|
|
7
|
+
*
|
|
8
|
+
* Parsing happens in a document with no browsing context, so nothing loads, navigates
|
|
9
|
+
* or executes while the markup is being inspected. That inertness does not survive the
|
|
10
|
+
* move: a script carried out of a parsed document into a live one has not been marked
|
|
11
|
+
* already-started, so insertion runs it. Removal is the protection, never inertness.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { isHttpsUrl } from "./safeUrl";
|
|
15
|
+
|
|
16
|
+
const HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Compared against localName, which is lowercase in every namespace. tagName is not:
|
|
20
|
+
* the parser only uppercases it for HTML elements, so an SVG script reports "script"
|
|
21
|
+
* and slips past an uppercase set.
|
|
22
|
+
*/
|
|
23
|
+
const FORBIDDEN_ELEMENTS = new Set([
|
|
24
|
+
"script",
|
|
25
|
+
"object",
|
|
26
|
+
"embed",
|
|
27
|
+
"applet",
|
|
28
|
+
"link",
|
|
29
|
+
"meta",
|
|
30
|
+
"base",
|
|
31
|
+
// A style block is not scoped to the fragment it arrived in. Its selectors reach the
|
|
32
|
+
// merchant's own card fields, and url() in a matched rule turns an attribute value
|
|
33
|
+
// into a request to wherever the ACS payload chose.
|
|
34
|
+
"style",
|
|
35
|
+
// A template's content is a separate fragment that querySelectorAll never descends
|
|
36
|
+
// into, so its markup would travel into the page unsanitized. The step has no use
|
|
37
|
+
// for one.
|
|
38
|
+
"template",
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Dropped outright, because no value of theirs is one this step has a use for and
|
|
43
|
+
* none of them is a plain URL the scheme check could judge.
|
|
44
|
+
*/
|
|
45
|
+
const FORBIDDEN_ATTRIBUTES = new Set([
|
|
46
|
+
"srcdoc",
|
|
47
|
+
// The caller hides its own container, so the step needs no CSS of its own. Left in,
|
|
48
|
+
// a style attribute still positions an element over the merchant's card fields.
|
|
49
|
+
"style",
|
|
50
|
+
// A space-separated list of URLs the browser POSTs to on click. https tells us
|
|
51
|
+
// nothing here: exfiltration to an attacker's origin is https too, so the scheme
|
|
52
|
+
// check would pass the attack and reject only the benign multi-URL form.
|
|
53
|
+
"ping",
|
|
54
|
+
// A candidate list ("a.png 1x, b.png 2x"), not a URL. The parser folds the whole
|
|
55
|
+
// string into one path and calls it https, so a scheme check reads as a guarantee
|
|
56
|
+
// while inspecting none of the candidates.
|
|
57
|
+
"srcset",
|
|
58
|
+
]);
|
|
59
|
+
|
|
60
|
+
// Single-URL attributes, each judged on its own resolved scheme.
|
|
61
|
+
const URL_ATTRIBUTES = new Set([
|
|
62
|
+
"src",
|
|
63
|
+
"href",
|
|
64
|
+
"action",
|
|
65
|
+
"formaction",
|
|
66
|
+
"data",
|
|
67
|
+
"poster",
|
|
68
|
+
"background",
|
|
69
|
+
]);
|
|
70
|
+
|
|
71
|
+
// An attribute may legitimately hold nothing, or point an iframe at the blank page;
|
|
72
|
+
// neither carries anywhere to navigate to. Everything else goes through the shared
|
|
73
|
+
// scheme check.
|
|
74
|
+
function isSafeAttributeUrl(value: string): boolean {
|
|
75
|
+
const candidate = value.trim();
|
|
76
|
+
if (candidate === "") return true;
|
|
77
|
+
if (candidate.toLowerCase() === "about:blank") return true;
|
|
78
|
+
|
|
79
|
+
return isHttpsUrl(candidate);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Matches on localName and removes by node, so a prefixed attribute is judged on what
|
|
84
|
+
* it does rather than on how it was spelled: in foreign content the parser keeps the
|
|
85
|
+
* prefix, and "xlink:href" as a qualified name matches neither the handler test nor the
|
|
86
|
+
* URL set. The element walk below already keeps foreign content out of the fragment —
|
|
87
|
+
* this does not lean on it, so relaxing that rule cannot silently reopen the hole.
|
|
88
|
+
*/
|
|
89
|
+
function sanitizeElement(element: Element): void {
|
|
90
|
+
for (const attribute of Array.from(element.attributes)) {
|
|
91
|
+
const name = attribute.localName.toLowerCase();
|
|
92
|
+
|
|
93
|
+
if (name.startsWith("on") || FORBIDDEN_ATTRIBUTES.has(name)) {
|
|
94
|
+
element.removeAttributeNode(attribute);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (URL_ATTRIBUTES.has(name) && !isSafeAttributeUrl(attribute.value)) {
|
|
99
|
+
element.removeAttributeNode(attribute);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Parses 3DS markup and returns a fragment owned by the current document, with every
|
|
106
|
+
* executable construct removed. Throws nothing: unparseable markup yields an empty
|
|
107
|
+
* fragment, which the caller treats as a missing redirection.
|
|
108
|
+
*/
|
|
109
|
+
export function sanitize3dsMarkup(markup: string): DocumentFragment {
|
|
110
|
+
const parsed = new DOMParser().parseFromString(markup, "text/html");
|
|
111
|
+
|
|
112
|
+
for (const element of Array.from(parsed.body.querySelectorAll("*"))) {
|
|
113
|
+
// Foreign content goes entirely. SVG and MathML are where the parser's exceptions
|
|
114
|
+
// live — case-preserving names, prefixed attributes, SMIL animating an href into a
|
|
115
|
+
// javascript: URL, integration points that switch parsing back to HTML mid-subtree
|
|
116
|
+
// — and each one is a separate way past a rule written for HTML. The step this
|
|
117
|
+
// sanitizer exists for is a hidden form and its hidden target iframe, so nothing it
|
|
118
|
+
// needs is out there to lose.
|
|
119
|
+
if (element.namespaceURI !== HTML_NAMESPACE || FORBIDDEN_ELEMENTS.has(element.localName)) {
|
|
120
|
+
element.remove();
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
sanitizeElement(element);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const fragment = document.createDocumentFragment();
|
|
128
|
+
for (const node of Array.from(parsed.body.childNodes)) {
|
|
129
|
+
fragment.appendChild(document.importNode(node, true));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return fragment;
|
|
133
|
+
}
|
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
// The secure token crosses into the SDK straight from an HTTP response body and is
|
|
2
|
+
// reused verbatim as an Authorization header value on every authenticated call. Only
|
|
3
|
+
// visible ASCII can travel in a header value, so anything else - whitespace, control
|
|
4
|
+
// characters, CR/LF, non-ASCII - is rejected here rather than deep inside fetch. The
|
|
5
|
+
// token format itself is deliberately not constrained, so it can change server-side.
|
|
6
|
+
export function validateSecureToken(secureToken: unknown): secureToken is string {
|
|
7
|
+
return typeof secureToken === "string" && /^[\x21-\x7E]+$/.test(secureToken);
|
|
8
|
+
}
|
|
9
|
+
|
|
1
10
|
export function validateCardNumber(cardNumber: string) {
|
|
2
11
|
const regex = /^\d{12,19}$/;
|
|
3
12
|
return regex.test(cardNumber) && luhnCheck(cardNumber);
|
|
@@ -72,9 +72,9 @@ export const MESSAGES_EN: Record<string, string> = {
|
|
|
72
72
|
[ErrorKeyEnum.CREATE_ERROR]: 'Error creating the SDK.',
|
|
73
73
|
[ErrorKeyEnum.FETCH_TRANSACTION_ERROR]: 'Error retrieving the transaction.',
|
|
74
74
|
[ErrorKeyEnum.THREEDS_REDIRECTION_ERROR]:
|
|
75
|
-
'
|
|
75
|
+
'An error occurred during the 3DS redirection.',
|
|
76
76
|
[ErrorKeyEnum.REMOVE_SDK_ERROR]:
|
|
77
|
-
'
|
|
77
|
+
'An error occurred while removing the SDK instance.',
|
|
78
78
|
};
|
|
79
79
|
|
|
80
80
|
export const MESSAGES_ES = {
|
|
@@ -135,7 +135,7 @@ export const MESSAGES_ES = {
|
|
|
135
135
|
[ErrorKeyEnum.CREATE_ERROR]: 'Error creando el SDK.',
|
|
136
136
|
[ErrorKeyEnum.FETCH_TRANSACTION_ERROR]: 'Error obteniendo la transacción',
|
|
137
137
|
[ErrorKeyEnum.THREEDS_REDIRECTION_ERROR]:
|
|
138
|
-
'
|
|
138
|
+
'Ocurrió un error durante la redirección de 3DS.',
|
|
139
139
|
[ErrorKeyEnum.REMOVE_SDK_ERROR]:
|
|
140
|
-
'
|
|
140
|
+
'Ocurrió un error removiendo la instancia del SDK.',
|
|
141
141
|
};
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { ThreeDSHandler } from "../src/classes/3dsHandler";
|
|
2
|
+
import { AppError } from "../src/shared/utils/appError";
|
|
3
|
+
import { ErrorKeyEnum } from "../src/shared/enum/ErrorKeyEnum";
|
|
4
|
+
|
|
5
|
+
const CHALLENGE_URL = "https://acs.example.com/challenge?id=42";
|
|
6
|
+
const IFRAME_ID = "tdsIframe";
|
|
7
|
+
|
|
8
|
+
const realLocation = Object.getOwnPropertyDescriptor(window, "location")!;
|
|
9
|
+
|
|
10
|
+
// jsdom's window.location has no setter, and a real assignment would navigate. Swapping
|
|
11
|
+
// in a plain data property records exactly what redirectToChallenge assigns to it.
|
|
12
|
+
function stubLocation(): { href: string } {
|
|
13
|
+
const stub = { href: "http://localhost/" };
|
|
14
|
+
Object.defineProperty(window, "location", {
|
|
15
|
+
configurable: true,
|
|
16
|
+
writable: true,
|
|
17
|
+
value: stub,
|
|
18
|
+
});
|
|
19
|
+
return stub;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function buildHandler(url: string, redirectOnComplete: boolean): ThreeDSHandler {
|
|
23
|
+
return new ThreeDSHandler({
|
|
24
|
+
payload: {
|
|
25
|
+
next_action: {
|
|
26
|
+
redirect_to_url: {
|
|
27
|
+
url,
|
|
28
|
+
verify_transaction_status_url: "/api/v1/verify/42",
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
apiKey: "api-key",
|
|
33
|
+
baseUrl: "https://stage.tonder.io",
|
|
34
|
+
redirectOnComplete,
|
|
35
|
+
tdsIframeId: IFRAME_ID,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function mountIframe(): HTMLIFrameElement {
|
|
40
|
+
const iframe = document.createElement("iframe");
|
|
41
|
+
iframe.id = IFRAME_ID;
|
|
42
|
+
document.body.appendChild(iframe);
|
|
43
|
+
return iframe;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
describe("ThreeDSHandler.redirectToChallenge", () => {
|
|
47
|
+
beforeEach(() => {
|
|
48
|
+
// Giving the iframe a src makes jsdom fire load, which drives the status poller.
|
|
49
|
+
// Without a stub that call reaches an undefined global fetch and tears the worker
|
|
50
|
+
// down before any assertion is reported.
|
|
51
|
+
(global as any).fetch = jest.fn().mockResolvedValue({
|
|
52
|
+
status: 200,
|
|
53
|
+
json: async () => ({ transaction_status: "Success" }),
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
afterEach(() => {
|
|
58
|
+
Object.defineProperty(window, "location", realLocation);
|
|
59
|
+
document.body.innerHTML = "";
|
|
60
|
+
localStorage.clear();
|
|
61
|
+
delete (global as any).fetch;
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
describe("window.location sink", () => {
|
|
65
|
+
it("navigates to a legitimate https challenge URL", () => {
|
|
66
|
+
const stub = stubLocation();
|
|
67
|
+
const handler = buildHandler(CHALLENGE_URL, true);
|
|
68
|
+
|
|
69
|
+
handler.redirectToChallenge();
|
|
70
|
+
|
|
71
|
+
expect(window.location as unknown as string).toBe(CHALLENGE_URL);
|
|
72
|
+
expect(window.location).not.toBe(stub);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it("never assigns a javascript: URL to window.location", () => {
|
|
76
|
+
const stub = stubLocation();
|
|
77
|
+
const handler = buildHandler("javascript:alert(document.cookie)", true);
|
|
78
|
+
|
|
79
|
+
expect(() => handler.redirectToChallenge()).toThrow(AppError);
|
|
80
|
+
|
|
81
|
+
expect(window.location).toBe(stub);
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
describe("iframe src sink", () => {
|
|
86
|
+
it("points the iframe at a legitimate https challenge URL and reveals it", () => {
|
|
87
|
+
const iframe = mountIframe();
|
|
88
|
+
const handler = buildHandler(CHALLENGE_URL, false);
|
|
89
|
+
|
|
90
|
+
handler.redirectToChallenge();
|
|
91
|
+
|
|
92
|
+
expect(iframe.getAttribute("src")).toBe(CHALLENGE_URL);
|
|
93
|
+
expect(iframe.getAttribute("style")).toBe("display: block");
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it("never assigns a javascript: URL to the iframe src", () => {
|
|
97
|
+
const iframe = mountIframe();
|
|
98
|
+
const handler = buildHandler("javascript:alert(document.cookie)", false);
|
|
99
|
+
|
|
100
|
+
expect(() => handler.redirectToChallenge()).toThrow(AppError);
|
|
101
|
+
|
|
102
|
+
expect(iframe.getAttribute("src")).toBeNull();
|
|
103
|
+
expect(iframe.getAttribute("style")).toBeNull();
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
describe("rejection", () => {
|
|
108
|
+
it("reports a 3DS redirection error the caller can surface", () => {
|
|
109
|
+
stubLocation();
|
|
110
|
+
const handler = buildHandler("javascript:alert(1)", true);
|
|
111
|
+
|
|
112
|
+
try {
|
|
113
|
+
handler.redirectToChallenge();
|
|
114
|
+
throw new Error("expected redirectToChallenge to throw");
|
|
115
|
+
} catch (error) {
|
|
116
|
+
expect(error).toBeInstanceOf(AppError);
|
|
117
|
+
expect((error as AppError).code).toBe(ErrorKeyEnum.THREEDS_REDIRECTION_ERROR);
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it("does not persist the verify transaction URL for a refused challenge", () => {
|
|
122
|
+
stubLocation();
|
|
123
|
+
const handler = buildHandler("javascript:alert(1)", true);
|
|
124
|
+
|
|
125
|
+
expect(() => handler.redirectToChallenge()).toThrow(AppError);
|
|
126
|
+
|
|
127
|
+
expect(handler.getVerifyTransactionUrl()).toBeNull();
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it.each([
|
|
131
|
+
["leading whitespace", " javascript:alert(1)"],
|
|
132
|
+
["mixed case", "JaVaScRiPt:alert(1)"],
|
|
133
|
+
["an embedded tab", "java\tscript:alert(1)"],
|
|
134
|
+
["an embedded newline", "java\nscript:alert(1)"],
|
|
135
|
+
["a comment that merely contains http", "javascript:/*http*/alert(1)"],
|
|
136
|
+
["a data: URL", "data:text/html,<script>alert(1)</script>"],
|
|
137
|
+
["a vbscript: URL", "vbscript:msgbox(1)"],
|
|
138
|
+
["a blob: URL", "blob:http://localhost/8f1c2b3a"],
|
|
139
|
+
["a file: URL", "file:///etc/passwd"],
|
|
140
|
+
])("refuses %s", (_label, url) => {
|
|
141
|
+
const stub = stubLocation();
|
|
142
|
+
const handler = buildHandler(url, true);
|
|
143
|
+
|
|
144
|
+
expect(() => handler.redirectToChallenge()).toThrow(AppError);
|
|
145
|
+
|
|
146
|
+
expect(window.location).toBe(stub);
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
});
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { ThreeDSHandler } from "../src/classes/3dsHandler";
|
|
2
|
+
import { sanitize3dsMarkup } from "../src/helpers/sanitize3dsMarkup";
|
|
3
|
+
|
|
4
|
+
// Shape of the markup the ACS returns for the 3DS Method step: a hidden form plus the
|
|
5
|
+
// iframe it targets. The flow depends on both surviving sanitization.
|
|
6
|
+
const THREE_DS_METHOD_MARKUP = `
|
|
7
|
+
<iframe id="tdsMmethodTgtFrame" name="tdsMmethodTgtFrame" style="display: none"></iframe>
|
|
8
|
+
<form id="tdsMmethodForm" name="tdsMmethodForm" target="tdsMmethodTgtFrame"
|
|
9
|
+
action="https://acs.example.com/3ds-method" method="POST">
|
|
10
|
+
<input type="hidden" name="threeDSMethodData" value="eyJ0aHJlZURTTWV0aG9kTm90aWZpY2F0aW9uVVJMIjoiIn0" />
|
|
11
|
+
</form>
|
|
12
|
+
`;
|
|
13
|
+
|
|
14
|
+
function buildHandler(iframe: string): ThreeDSHandler {
|
|
15
|
+
return new ThreeDSHandler({
|
|
16
|
+
payload: {
|
|
17
|
+
next_action: {
|
|
18
|
+
iframe_resources: {
|
|
19
|
+
iframe,
|
|
20
|
+
verify_transaction_status_url: "/api/v1/verify/1",
|
|
21
|
+
},
|
|
22
|
+
},
|
|
23
|
+
},
|
|
24
|
+
apiKey: "api-key",
|
|
25
|
+
baseUrl: "https://stage.tonder.io",
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
describe("sanitize3dsMarkup", () => {
|
|
30
|
+
it("keeps the form, its hidden input and the target iframe the 3DS Method step needs", () => {
|
|
31
|
+
const container = document.createElement("div");
|
|
32
|
+
container.appendChild(sanitize3dsMarkup(THREE_DS_METHOD_MARKUP));
|
|
33
|
+
|
|
34
|
+
const form = container.querySelector("form");
|
|
35
|
+
expect(form).not.toBeNull();
|
|
36
|
+
expect(form!.id).toBe("tdsMmethodForm");
|
|
37
|
+
expect(form!.getAttribute("action")).toBe("https://acs.example.com/3ds-method");
|
|
38
|
+
expect(form!.getAttribute("target")).toBe("tdsMmethodTgtFrame");
|
|
39
|
+
expect(container.querySelector("input[name='threeDSMethodData']")).not.toBeNull();
|
|
40
|
+
expect(container.querySelector("iframe#tdsMmethodTgtFrame")).not.toBeNull();
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it("removes inline event handlers", () => {
|
|
44
|
+
const container = document.createElement("div");
|
|
45
|
+
container.appendChild(
|
|
46
|
+
sanitize3dsMarkup(`<img src="https://acs.example.com/x.png" onerror="stealCard()" />`),
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
const img = container.querySelector("img")!;
|
|
50
|
+
expect(img.getAttribute("onerror")).toBeNull();
|
|
51
|
+
expect(img.getAttribute("src")).toBe("https://acs.example.com/x.png");
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it("removes script elements", () => {
|
|
55
|
+
const container = document.createElement("div");
|
|
56
|
+
container.appendChild(sanitize3dsMarkup(`<div></div><script>stealCard()</script>`));
|
|
57
|
+
|
|
58
|
+
expect(container.querySelector("script")).toBeNull();
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it("drops non-https URLs while keeping https and relative ones", () => {
|
|
62
|
+
const container = document.createElement("div");
|
|
63
|
+
container.appendChild(
|
|
64
|
+
sanitize3dsMarkup(
|
|
65
|
+
`<a id="js" href="javascript:stealCard()"></a>` +
|
|
66
|
+
`<iframe id="srcdoc" srcdoc="<script>stealCard()</script>"></iframe>` +
|
|
67
|
+
`<form id="rel" action="/api/v1/challenge"></form>`,
|
|
68
|
+
),
|
|
69
|
+
);
|
|
70
|
+
|
|
71
|
+
expect(container.querySelector("#js")!.getAttribute("href")).toBeNull();
|
|
72
|
+
expect(container.querySelector("#srcdoc")!.getAttribute("srcdoc")).toBeNull();
|
|
73
|
+
expect(container.querySelector("#rel")!.getAttribute("action")).toBe("/api/v1/challenge");
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it("removes script elements the parser leaves in the SVG namespace", () => {
|
|
77
|
+
const container = document.createElement("div");
|
|
78
|
+
container.appendChild(
|
|
79
|
+
sanitize3dsMarkup(`<div></div><svg><script>stealCard()</script></svg>`),
|
|
80
|
+
);
|
|
81
|
+
|
|
82
|
+
// tagName is "script" in lowercase here, so an uppercase set never matched it and
|
|
83
|
+
// the element travelled into the page intact.
|
|
84
|
+
expect(container.querySelector("script")).toBeNull();
|
|
85
|
+
expect(container.querySelector("svg")).toBeNull();
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("removes an SVG link whose javascript: URL hides behind a namespace prefix", () => {
|
|
89
|
+
const container = document.createElement("div");
|
|
90
|
+
container.appendChild(
|
|
91
|
+
sanitize3dsMarkup(
|
|
92
|
+
`<svg><a id="svg-link" xlink:href="javascript:stealCard()"><text>pay</text></a></svg>`,
|
|
93
|
+
),
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
// The qualified name is "xlink:href", which the URL set never matched, so the
|
|
97
|
+
// scheme check was never reached.
|
|
98
|
+
expect(container.querySelector("#svg-link")).toBeNull();
|
|
99
|
+
expect(container.innerHTML).not.toContain("javascript:");
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it("removes style elements, whose selectors are not scoped to the fragment", () => {
|
|
103
|
+
const container = document.createElement("div");
|
|
104
|
+
container.appendChild(
|
|
105
|
+
sanitize3dsMarkup(
|
|
106
|
+
`<div></div><style>input{background:url("https://attacker.example/x")}</style>`,
|
|
107
|
+
),
|
|
108
|
+
);
|
|
109
|
+
|
|
110
|
+
expect(container.querySelector("style")).toBeNull();
|
|
111
|
+
expect(container.innerHTML).not.toContain("attacker.example");
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it("removes the style attribute, which the caller no longer depends on", () => {
|
|
115
|
+
const container = document.createElement("div");
|
|
116
|
+
container.appendChild(sanitize3dsMarkup(THREE_DS_METHOD_MARKUP));
|
|
117
|
+
|
|
118
|
+
// The step's own markup carries style="display: none" here, but the SDK hides its
|
|
119
|
+
// container itself, so nothing is lost and an overlay over the card fields has no
|
|
120
|
+
// way in.
|
|
121
|
+
expect(container.querySelector("iframe")!.getAttribute("style")).toBeNull();
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it("removes an element-scoped style that would cover the card fields", () => {
|
|
125
|
+
const container = document.createElement("div");
|
|
126
|
+
container.appendChild(
|
|
127
|
+
sanitize3dsMarkup(
|
|
128
|
+
`<div id="overlay" style="position:fixed;top:0;left:0;width:100vw;height:100vh"></div>`,
|
|
129
|
+
),
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
expect(container.querySelector("#overlay")!.getAttribute("style")).toBeNull();
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it("removes ping, which POSTs to a remote origin on click", () => {
|
|
136
|
+
const container = document.createElement("div");
|
|
137
|
+
container.appendChild(
|
|
138
|
+
sanitize3dsMarkup(
|
|
139
|
+
`<a id="beacon" href="https://acs.example.com/x" ping="https://attacker.example/steal"></a>`,
|
|
140
|
+
),
|
|
141
|
+
);
|
|
142
|
+
|
|
143
|
+
// https says nothing about a beacon: the attacker's collector is https too. The
|
|
144
|
+
// attribute goes rather than being scheme-checked.
|
|
145
|
+
expect(container.querySelector("#beacon")!.getAttribute("ping")).toBeNull();
|
|
146
|
+
expect(container.querySelector("#beacon")!.getAttribute("href")).toBe(
|
|
147
|
+
"https://acs.example.com/x",
|
|
148
|
+
);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it("removes srcset, whose candidate list no scheme check can judge", () => {
|
|
152
|
+
const container = document.createElement("div");
|
|
153
|
+
container.appendChild(
|
|
154
|
+
sanitize3dsMarkup(
|
|
155
|
+
`<img id="candidates" srcset="https://acs.example.com/a.png 1x, http://attacker.example/b.png 2x" />`,
|
|
156
|
+
),
|
|
157
|
+
);
|
|
158
|
+
|
|
159
|
+
// Resolved whole, this string parses as one https path and would pass a scheme
|
|
160
|
+
// check while the http candidate inside it still loads.
|
|
161
|
+
expect(container.querySelector("#candidates")!.getAttribute("srcset")).toBeNull();
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it("scheme-checks background, which is a single URL", () => {
|
|
165
|
+
const container = document.createElement("div");
|
|
166
|
+
container.appendChild(
|
|
167
|
+
sanitize3dsMarkup(
|
|
168
|
+
`<table id="insecure" background="http://attacker.example/bg.png"></table>` +
|
|
169
|
+
`<table id="secure" background="https://acs.example.com/bg.png"></table>`,
|
|
170
|
+
),
|
|
171
|
+
);
|
|
172
|
+
|
|
173
|
+
expect(container.querySelector("#insecure")!.getAttribute("background")).toBeNull();
|
|
174
|
+
expect(container.querySelector("#secure")!.getAttribute("background")).toBe(
|
|
175
|
+
"https://acs.example.com/bg.png",
|
|
176
|
+
);
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
it("drops non-https URLs whatever case the attribute was written in", () => {
|
|
180
|
+
const container = document.createElement("div");
|
|
181
|
+
container.appendChild(sanitize3dsMarkup(`<a id="js" HREF="javascript:stealCard()"></a>`));
|
|
182
|
+
|
|
183
|
+
expect(container.querySelector("#js")!.getAttribute("href")).toBeNull();
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
describe("ThreeDSHandler.loadIframe", () => {
|
|
188
|
+
afterEach(() => {
|
|
189
|
+
document.body.innerHTML = "";
|
|
190
|
+
localStorage.clear();
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
it("renders the 3DS Method form and resolves once its target iframe loads", async () => {
|
|
194
|
+
const handler = buildHandler(THREE_DS_METHOD_MARKUP);
|
|
195
|
+
|
|
196
|
+
const loading = handler.loadIframe();
|
|
197
|
+
const target = document.getElementById("tdsMmethodTgtFrame");
|
|
198
|
+
|
|
199
|
+
expect(target).not.toBeNull();
|
|
200
|
+
expect(document.getElementById("tdsMmethodForm")).not.toBeNull();
|
|
201
|
+
|
|
202
|
+
target!.dispatchEvent(new Event("load"));
|
|
203
|
+
await expect(loading).resolves.toBe(true);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
it("does not carry attacker-controlled event handlers from the payload into the page", () => {
|
|
207
|
+
const handler = buildHandler(
|
|
208
|
+
`<img id="payload-img" src="https://acs.example.com/x.png" onerror="window.__tonderXss = true" />` +
|
|
209
|
+
THREE_DS_METHOD_MARKUP,
|
|
210
|
+
);
|
|
211
|
+
|
|
212
|
+
handler.loadIframe();
|
|
213
|
+
|
|
214
|
+
const injected = document.getElementById("payload-img")!;
|
|
215
|
+
expect(injected.getAttribute("onerror")).toBeNull();
|
|
216
|
+
// jsdom does not fetch images, so assert the handler itself was never registered.
|
|
217
|
+
expect((injected as HTMLElement & { onerror?: unknown }).onerror).toBeNull();
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
it("does not carry a namespaced script from the payload into the merchant document", () => {
|
|
221
|
+
const handler = buildHandler(
|
|
222
|
+
`<svg><script id="payload-svg-script">window.__tonderXss = true</script></svg>` +
|
|
223
|
+
THREE_DS_METHOD_MARKUP,
|
|
224
|
+
);
|
|
225
|
+
|
|
226
|
+
handler.loadIframe();
|
|
227
|
+
|
|
228
|
+
// The SDK inserts the fragment into the live document, where a script that was
|
|
229
|
+
// never marked already-started runs on insertion. Removal is the only protection.
|
|
230
|
+
expect(document.getElementById("payload-svg-script")).toBeNull();
|
|
231
|
+
expect(document.querySelector("svg")).toBeNull();
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
it("hides the container it inserts, so the step renders nothing either way", () => {
|
|
235
|
+
const handler = buildHandler(THREE_DS_METHOD_MARKUP);
|
|
236
|
+
|
|
237
|
+
handler.loadIframe();
|
|
238
|
+
|
|
239
|
+
const target = document.getElementById("tdsMmethodTgtFrame")!;
|
|
240
|
+
// The ACS markup asked for display: none and the sanitizer took the attribute away.
|
|
241
|
+
// The step stays invisible because the SDK hides its own container, not because the
|
|
242
|
+
// payload was polite.
|
|
243
|
+
expect(target.getAttribute("style")).toBeNull();
|
|
244
|
+
// display is not inherited, so the child still computes its own value; the container
|
|
245
|
+
// being none is what takes the whole subtree out of rendering.
|
|
246
|
+
expect(getComputedStyle(target.parentElement!).display).toBe("none");
|
|
247
|
+
});
|
|
248
|
+
});
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { LiteCheckout } from "../src/classes/liteCheckout";
|
|
2
|
+
import { AppError } from "../src/shared/utils/appError";
|
|
3
|
+
import { ErrorKeyEnum } from "../src/shared/enum/ErrorKeyEnum";
|
|
4
|
+
|
|
5
|
+
const VALID_TOKEN =
|
|
6
|
+
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MDAwMDAwMDB9.Kx-3vQ0m9R1s2T4u6W8y";
|
|
7
|
+
|
|
8
|
+
function buildCheckout(): LiteCheckout {
|
|
9
|
+
return new LiteCheckout({ mode: "stage", apiKey: "public-api-key" });
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function configure(checkout: LiteCheckout, secureToken: unknown) {
|
|
13
|
+
checkout.configureCheckout({
|
|
14
|
+
customer: { email: "buyer@example.com" },
|
|
15
|
+
secureToken,
|
|
16
|
+
} as any);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
describe("secure token trust boundary", () => {
|
|
20
|
+
it("accepts a well-formed token", () => {
|
|
21
|
+
const checkout = buildCheckout();
|
|
22
|
+
|
|
23
|
+
configure(checkout, VALID_TOKEN);
|
|
24
|
+
|
|
25
|
+
expect(checkout.secureToken).toBe(VALID_TOKEN);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it.each([
|
|
29
|
+
["a header-splitting value", "good-token\r\nX-Injected: 1"],
|
|
30
|
+
["an embedded newline", "good-token\ninjected"],
|
|
31
|
+
["surrounding whitespace", " good-token "],
|
|
32
|
+
["a null byte", "good-token\u0000"],
|
|
33
|
+
["a non-ASCII character", "good-tokén"],
|
|
34
|
+
["an empty string", ""],
|
|
35
|
+
["a missing value", undefined],
|
|
36
|
+
["a non-string value", { access: VALID_TOKEN }],
|
|
37
|
+
])("rejects %s", (_label, token) => {
|
|
38
|
+
const checkout = buildCheckout();
|
|
39
|
+
|
|
40
|
+
expect(() => configure(checkout, token)).toThrow(AppError);
|
|
41
|
+
try {
|
|
42
|
+
configure(checkout, token);
|
|
43
|
+
} catch (error) {
|
|
44
|
+
expect((error as AppError).code).toBe(ErrorKeyEnum.SECURE_TOKEN_INVALID);
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("leaves the previously accepted token in place when a bad one is rejected", () => {
|
|
49
|
+
const checkout = buildCheckout();
|
|
50
|
+
configure(checkout, VALID_TOKEN);
|
|
51
|
+
|
|
52
|
+
expect(() => configure(checkout, "poisoned\r\nX-Injected: 1")).toThrow(AppError);
|
|
53
|
+
|
|
54
|
+
expect(checkout.secureToken).toBe(VALID_TOKEN);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it("never lets a rejected token reach the Authorization header", async () => {
|
|
58
|
+
const checkout = buildCheckout();
|
|
59
|
+
configure(checkout, VALID_TOKEN);
|
|
60
|
+
|
|
61
|
+
try {
|
|
62
|
+
configure(checkout, "poisoned\r\nX-Injected: 1");
|
|
63
|
+
} catch {
|
|
64
|
+
// Rejected at the boundary; the request below must still carry the good token.
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const fetchMock = jest.fn().mockResolvedValue({
|
|
68
|
+
ok: true,
|
|
69
|
+
status: 200,
|
|
70
|
+
json: async () => ({ user_id: 1, cards: [] }),
|
|
71
|
+
});
|
|
72
|
+
(global as any).fetch = fetchMock;
|
|
73
|
+
|
|
74
|
+
await checkout._getCustomerCards("customer-token", 42);
|
|
75
|
+
|
|
76
|
+
const headers = fetchMock.mock.calls[0][1].headers;
|
|
77
|
+
expect(headers.Authorization).toBe(`Bearer ${VALID_TOKEN}`);
|
|
78
|
+
expect(headers.Authorization).not.toContain("\r");
|
|
79
|
+
expect(headers.Authorization).not.toContain("\n");
|
|
80
|
+
});
|
|
81
|
+
});
|