Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
fix(payment_link): sanitize embedded payment link data (#7736)
Kashif0f43aa43aa1d
diff --git a/crates/hyperswitch_domain_models/src/api.rs b/crates/hyperswitch_domain_models/src/api.rsindex 571371dc63..f6d9349762 100644--- a/crates/hyperswitch_domain_models/src/api.rs+++ b/crates/hyperswitch_domain_models/src/api.rs@@ -72,7 +72,7 @@ pub enum PaymentLinkAction {pub struct PaymentLinkFormData {pub js_script: String,pub css_script: String,- pub sdk_url: String,+ pub sdk_url: url::Url,pub html_meta_tags: String,}@@ -127,7 +127,7 @@ pub struct GenericExpiredLinkData {pub struct GenericLinkFormData {pub js_data: String,pub css_data: String,- pub sdk_url: String,+ pub sdk_url: url::Url,pub html_meta_tags: String,}diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex fb40451888..8e1fb35ddc 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -444,9 +444,19 @@ impl Default for GenericLinkEnvUiConfig {}}-#[derive(Debug, Deserialize, Clone, Default)]+#[derive(Debug, Deserialize, Clone)]pub struct PaymentLink {- pub sdk_url: String,+ pub sdk_url: url::Url,+}++impl Default for PaymentLink {+ fn default() -> Self {+ Self {+ #[allow(clippy::expect_used)]+ sdk_url: url::Url::parse("https://beta.hyperswitch.io/v0/HyperLoader.js")+ .expect("Failed to parse default SDK URL"),+ }+ }}#[derive(Debug, Deserialize, Clone, Default)]diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rsindex adcfe8046d..545966968b 100644--- a/crates/router/src/core/payment_link.rs+++ b/crates/router/src/core/payment_link.rs@@ -387,12 +387,11 @@ pub async fn initiate_secure_payment_link_flow(payment_form_label_type: payment_link_config.payment_form_label_type,show_card_terms: payment_link_config.show_card_terms,};- let js_script = format!(- "window.__PAYMENT_DETAILS = {}",- serde_json::to_string(&secure_payment_link_details)- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to serialize PaymentLinkData")?- );+ let payment_details_str = serde_json::to_string(&secure_payment_link_details)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to serialize PaymentLinkData")?;+ let url_encoded_str = urlencoding::encode(&payment_details_str);+ let js_script = format!("window.__PAYMENT_DETAILS = '{}';", url_encoded_str);let html_meta_tags = get_meta_tags_html(&link_details);let payment_link_data = services::PaymentLinkFormData {js_script,@@ -491,7 +490,8 @@ fn get_js_script(payment_details: &PaymentLinkData) -> RouterResult<String> {let payment_details_str = serde_json::to_string(payment_details).change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to serialize PaymentLinkData")?;- Ok(format!("window.__PAYMENT_DETAILS = {payment_details_str};"))+ let url_encoded_str = urlencoding::encode(&payment_details_str);+ Ok(format!("window.__PAYMENT_DETAILS = '{url_encoded_str}';"))}fn get_color_scheme_css(payment_link_config: &PaymentLinkConfig) -> String {diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.jsindex bdfdfa8a8b..1e96731402 100644--- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js+++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js@@ -1,9 +1,19 @@-// @ts-nocheck+// @ts-check/*** UTIL FUNCTIONS*/+function decodeUri(uri) {+ try {+ var uriStr = decodeURIComponent(uri);+ return JSON.parse(uriStr);+ } catch (e) {+ console.error("Error decoding and parsing string URI:", e);+ return uri;+ }+}+function adjustLightness(hexColor, factor) {// Convert hex to RGBvar r = parseInt(hexColor.slice(1, 3), 16);@@ -176,10 +186,13 @@ window.state = {var widgets = null;var unifiedCheckout = null;// @ts-ignore-var pub_key = window.__PAYMENT_DETAILS.pub_key;+var encodedPaymentDetails = window.__PAYMENT_DETAILS;+var paymentDetails = decodeUri(encodedPaymentDetails);+var pub_key = paymentDetails.pub_key;var hyper = null;-const translations = getTranslations(window.__PAYMENT_DETAILS.locale);+// @ts-ignore+const translations = getTranslations(paymentDetails.locale);var isFramed = false;try {@@ -215,10 +228,6 @@ function emitPaymentStatus(paymentDetails) {* - Initialize SDK**/function boot() {-- // @ts-ignore- var paymentDetails = window.__PAYMENT_DETAILS;-// Emit latest payment statusif (isFramed) {emitPaymentStatus(paymentDetails);@@ -435,7 +444,7 @@ function initializeEventListeners(paymentDetails) {if (paymentForm instanceof HTMLFormElement) {paymentForm.addEventListener("submit", function (event) {event.preventDefault();- handleSubmit(event);+ handleSubmit(event, paymentDetails);})}@@ -447,18 +456,20 @@ function initializeEventListeners(paymentDetails) {function handleFormReadyForSubmission() {window.addEventListener("message", function (event) {// Event listener for updating the button rules- if (isObject(event.data) && event.data["isFormReadyForSubmission"] !== null) {- let isFormReadyForSubmission = event.data["isFormReadyForSubmission"];- var submitButtonNode = document.getElementById("submit");- if (submitButtonNode instanceof HTMLButtonElement) {- if (isFormReadyForSubmission === false) {- submitButtonNode.disabled = true;- addClass("#submit", "not-ready");- addClass("#submit", "disabled");- } else if (isFormReadyForSubmission === true) {- submitButtonNode.disabled = false;- removeClass("#submit", "not-ready");- removeClass("#submit", "disabled");+ if (event.origin == "{{sdk_origin}}") {+ if (isObject(event.data) && event.data["isFormReadyForSubmission"] !== null) {+ let isFormReadyForSubmission = event.data["isFormReadyForSubmission"];+ var submitButtonNode = document.getElementById("submit");+ if (submitButtonNode instanceof HTMLButtonElement) {+ if (isFormReadyForSubmission === false) {+ submitButtonNode.disabled = true;+ addClass("#submit", "not-ready");+ addClass("#submit", "disabled");+ } else if (isFormReadyForSubmission === true) {+ submitButtonNode.disabled = false;+ removeClass("#submit", "not-ready");+ removeClass("#submit", "disabled");+ }}}}@@ -504,12 +515,10 @@ function mountUnifiedCheckout(id) {* - Toggle UI loaders appropriately* - Handle errors and redirect to status page* @param {Event} e+ * @param {PaymentDetails} paymentDetails*/// @ts-ignore-function handleSubmit(e) {- // @ts-ignore- var paymentDetails = window.__PAYMENT_DETAILS;-+function handleSubmit(e, paymentDetails) {// Update button loaderhide("#submit-button-text");show("#submit-spinner");@@ -553,7 +562,7 @@ function handleSubmit(e) {url.search = params.toString();window.top.location.href = url.toString();} else {- redirectToStatus();+ redirectToStatus(paymentDetails);}}).catch(function (error) {@@ -772,25 +781,33 @@ function appendMerchantDetails(paymentDetails, merchantDynamicDetails) {);var horizontalLine = document.createElement("hr");horizontalLine.className = "hyper-checkout-payment-horizontal-line";- horizontalLineContainer.append(horizontalLine);+ if (horizontalLineContainer instanceof HTMLDivElement) {+ horizontalLineContainer.append(horizontalLine);+ }// max number of items to show in the merchant detailslet maxItemsInDetails = 50;for (var item of merchantDetailsObject) {var merchantData = document.createElement("div");merchantData.className = "hyper-checkout-payment-merchant-dynamic-data";+ var keyNode = document.createElement("span");+ keyNode.textContent = item.key;+ var valueNode = document.createElement("span");+ valueNode.textContent = item.value;// make the key and value bold if specified in the ui_configuration- var key = item.ui_configuration- ? item.ui_configuration.is_key_bold- ? item.key.bold()- : item.key- : item.key;- var value = item.ui_configuration- ? item.ui_configuration.is_value_bold- ? item.value.bold()- : item.value- : item.value;- merchantData.innerHTML = key + " : " + value;+ if (isObject(item.ui_configuration)) {+ if (item.ui_configuration.is_key_bold) {+ keyNode.style.fontWeight = "bold";+ }+ if (item.ui_configuration.is_value_bold) {+ valueNode.style.fontWeight = "bold";+ }+ }+ var separatorNode = document.createElement("span");+ separatorNode.textContent = " : ";+ merchantData.appendChild(keyNode);+ merchantData.appendChild(separatorNode);+ merchantData.appendChild(valueNode);merchantDynamicDetails.append(merchantData);if (--maxItemsInDetails === 0) {diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.jsindex effd27cc64..33758131aa 100644--- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js+++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js@@ -9,7 +9,8 @@**/function initializeSDK() {// @ts-ignore- var paymentDetails = window.__PAYMENT_DETAILS;+ var encodedPaymentDetails = window.__PAYMENT_DETAILS;+ var paymentDetails = decodeUri(encodedPaymentDetails);var clientSecret = paymentDetails.client_secret;var sdkUiRules = paymentDetails.sdk_ui_rules;var labelType = paymentDetails.payment_form_label_type;@@ -99,8 +100,7 @@ function initializeSDK() {/*** Use - redirect to /payment_link/status*/-function redirectToStatus() {- var paymentDetails = window.__PAYMENT_DETAILS;+function redirectToStatus(paymentDetails) {var arr = window.location.pathname.split("/");// NOTE - This code preserves '/api' in url for integ and sbxdiff --git a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.jsindex 446428e6ff..3db5eb94de 100644--- a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js+++ b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js@@ -123,8 +123,7 @@ if (!isFramed) {/*** Use - redirect to /payment_link/status*/- function redirectToStatus() {- var paymentDetails = window.__PAYMENT_DETAILS;+ function redirectToStatus(paymentDetails) {var arr = window.location.pathname.split("/");// NOTE - This code preserves '/api' in url for integ and sbx envsdiff --git a/crates/router/src/core/payment_link/payment_link_status/status.js b/crates/router/src/core/payment_link/payment_link_status/status.jsindex 16949d546a..371fdf1d2d 100644--- a/crates/router/src/core/payment_link/payment_link_status/status.js+++ b/crates/router/src/core/payment_link/payment_link_status/status.js@@ -4,6 +4,16 @@* UTIL FUNCTIONS*/+function decodeUri(uri) {+ try {+ var uriStr = decodeURIComponent(uri);+ return JSON.parse(uriStr);+ } catch (e) {+ console.error("Error decoding and parsing string URI:", e);+ return uri;+ }+}+/*** Ref - https://github.com/onury/invert-color/blob/master/lib/cjs/invert.js*/@@ -86,7 +96,12 @@ window.state = {isMobileView: window.innerWidth <= 1400,};-const translations = getTranslations(window.__PAYMENT_DETAILS.locale);+// @ts-ignore+var encodedPaymentDetails = window.__PAYMENT_DETAILS;+var paymentDetails = decodeUri(encodedPaymentDetails);++// @ts-ignore+const translations = getTranslations(paymentDetails.locale);var isFramed = false;try {@@ -122,9 +137,6 @@ function emitPaymentStatus(paymentDetails) {* - Initialize SDK**/function boot() {- // @ts-ignore- var paymentDetails = window.__PAYMENT_DETAILS;-// Emit latest payment statusif (isFramed) {emitPaymentStatus(paymentDetails);@@ -272,7 +284,7 @@ function renderStatusDetails(paymentDetails) {var merchantLogoNode = document.createElement("img");merchantLogoNode.className = "hyper-checkout-status-merchant-logo";// @ts-ignore- merchantLogoNode.src = window.__PAYMENT_DETAILS.merchant_logo;+ merchantLogoNode.src = paymentDetails.merchant_logo;merchantLogoNode.alt = "";// Form content itemsdiff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex 4a2b3d7520..7e13dbbed1 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -400,7 +400,7 @@ pub async fn render_pm_collect_link(let generic_form_data = services::GenericLinkFormData {js_data: serialized_js_content,css_data: serialized_css_content,- sdk_url: default_config.sdk_url.to_string(),+ sdk_url: default_config.sdk_url.clone(),html_meta_tags: String::new(),};Ok(services::ApplicationResponse::GenericLinkForm(Box::new(diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rsindex 063529e21f..06edca897d 100644--- a/crates/router/src/core/payout_link.rs+++ b/crates/router/src/core/payout_link.rs@@ -260,7 +260,7 @@ pub async fn initiate_payout_link(let generic_form_data = services::GenericLinkFormData {js_data: serialized_js_content,css_data: serialized_css_content,- sdk_url: default_config.sdk_url.to_string(),+ sdk_url: default_config.sdk_url.clone(),html_meta_tags: String::new(),};Ok(services::ApplicationResponse::GenericLinkForm(Box::new(diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rsindex 76a2b9e50e..2ae0c68cce 100644--- a/crates/router/src/services/api.rs+++ b/crates/router/src/services/api.rs@@ -1877,6 +1877,30 @@ fn build_payment_link_template(let _ = tera.add_raw_template("payment_link_js", &js_template);context.insert("payment_details_js_script", &payment_link_data.js_script);+ let sdk_origin = payment_link_data+ .sdk_url+ .host_str()+ .ok_or_else(|| {+ logger::error!("Host missing for payment link SDK URL");+ report!(errors::ApiErrorResponse::InternalServerError)+ })+ .and_then(|host| {+ if host == "localhost" {+ let port = payment_link_data.sdk_url.port().ok_or_else(|| {+ logger::error!("Port missing for localhost in SDK URL");+ report!(errors::ApiErrorResponse::InternalServerError)+ })?;+ Ok(format!(+ "{}://{}:{}",+ payment_link_data.sdk_url.scheme(),+ host,+ port+ ))+ } else {+ Ok(format!("{}://{}", payment_link_data.sdk_url.scheme(), host))+ }+ })?;+ context.insert("sdk_origin", &sdk_origin);let rendered_js = match tera.render("payment_link_js", &context) {Ok(rendered_js) => rendered_js,@@ -1954,11 +1978,11 @@ pub fn build_secure_payment_link_html(.attach_printable("Error while rendering secure payment link's HTML template")}-fn get_hyper_loader_sdk(sdk_url: &str) -> String {+fn get_hyper_loader_sdk(sdk_url: &url::Url) -> String {format!("<script src=\"{sdk_url}\" onload=\"initializeSDK()\"></script>")}-fn get_preload_link_html_template(sdk_url: &str) -> String {+fn get_preload_link_html_template(sdk_url: &url::Url) -> String {format!(r#"<link rel="preload" href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800" as="style"><link rel="preload" href="{sdk_url}" as="script">"#,